diff --git a/All/.DS_Store b/All/.DS_Store index e8185ef..2262cb6 100644 Binary files a/All/.DS_Store and b/All/.DS_Store differ diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/diff.diff deleted file mode 100755 index e1fc96c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/directdot/PSystemDot.java b/src/net/sourceforge/plantuml/directdot/PSystemDot.java -index 6da4d97d..519f3928 100644 ---- a/src/net/sourceforge/plantuml/directdot/PSystemDot.java -+++ b/src/net/sourceforge/plantuml/directdot/PSystemDot.java -@@ -38,0 +39 @@ import net.sourceforge.plantuml.FileFormatOption; -+import net.sourceforge.plantuml.StringUtils; -@@ -60 +61 @@ public class PSystemDot extends AbstractPSystem { -- final Graphviz graphviz = GraphvizUtils.create(data, fileFormat.getFileFormat().name().toLowerCase()); -+ final Graphviz graphviz = GraphvizUtils.create(data, StringUtils.goLowerCase(fileFormat.getFileFormat().name())); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/new/PSystemDot.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/new/PSystemDot.java deleted file mode 100755 index 519f392..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/new/PSystemDot.java +++ /dev/null @@ -1,69 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - */ -package net.sourceforge.plantuml.directdot; - -import java.io.IOException; -import java.io.OutputStream; - -import net.sourceforge.plantuml.AbstractPSystem; -import net.sourceforge.plantuml.FileFormatOption; -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.api.ImageDataSimple; -import net.sourceforge.plantuml.core.DiagramDescription; -import net.sourceforge.plantuml.core.DiagramDescriptionImpl; -import net.sourceforge.plantuml.core.ImageData; -import net.sourceforge.plantuml.cucadiagram.dot.Graphviz; -import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils; -import net.sourceforge.plantuml.cucadiagram.dot.ProcessState; - -public class PSystemDot extends AbstractPSystem { - - private final String data; - - public PSystemDot(String data) { - this.data = data; - } - - public DiagramDescription getDescription() { - return new DiagramDescriptionImpl("(Dot)", getClass()); - } - - public ImageData exportDiagram(OutputStream os, int num, FileFormatOption fileFormat) throws IOException { - final Graphviz graphviz = GraphvizUtils.create(data, StringUtils.goLowerCase(fileFormat.getFileFormat().name())); - final ProcessState state = graphviz.createFile3(os); - if (state.differs(ProcessState.TERMINATED_OK())) { - throw new IllegalStateException("Timeout1 " + state); - } - - return new ImageDataSimple(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/old/PSystemDot.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/old/PSystemDot.java deleted file mode 100755 index 6da4d97..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/old/PSystemDot.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - */ -package net.sourceforge.plantuml.directdot; - -import java.io.IOException; -import java.io.OutputStream; - -import net.sourceforge.plantuml.AbstractPSystem; -import net.sourceforge.plantuml.FileFormatOption; -import net.sourceforge.plantuml.api.ImageDataSimple; -import net.sourceforge.plantuml.core.DiagramDescription; -import net.sourceforge.plantuml.core.DiagramDescriptionImpl; -import net.sourceforge.plantuml.core.ImageData; -import net.sourceforge.plantuml.cucadiagram.dot.Graphviz; -import net.sourceforge.plantuml.cucadiagram.dot.GraphvizUtils; -import net.sourceforge.plantuml.cucadiagram.dot.ProcessState; - -public class PSystemDot extends AbstractPSystem { - - private final String data; - - public PSystemDot(String data) { - this.data = data; - } - - public DiagramDescription getDescription() { - return new DiagramDescriptionImpl("(Dot)", getClass()); - } - - public ImageData exportDiagram(OutputStream os, int num, FileFormatOption fileFormat) throws IOException { - final Graphviz graphviz = GraphvizUtils.create(data, fileFormat.getFileFormat().name().toLowerCase()); - final ProcessState state = graphviz.createFile3(os); - if (state.differs(ProcessState.TERMINATED_OK())) { - throw new IllegalStateException("Timeout1 " + state); - } - - return new ImageDataSimple(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/pair.info deleted file mode 100755 index 20039b9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22187/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22187 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/directdot/PSystemDot.java -FixedFilePath:src/net/sourceforge/plantuml/directdot/PSystemDot.java -StartLineNum:60 -EndLineNum:60 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/comMsg.txt deleted file mode 100755 index f39245a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8025 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@570 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/diff.diff deleted file mode 100755 index 60890e2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/cute/CuteShapeFactory.java b/src/net/sourceforge/plantuml/cute/CuteShapeFactory.java -index ab68e29b..abee1c00 100644 ---- a/src/net/sourceforge/plantuml/cute/CuteShapeFactory.java -+++ b/src/net/sourceforge/plantuml/cute/CuteShapeFactory.java -@@ -37,0 +38,2 @@ import java.util.Map; -+import net.sourceforge.plantuml.StringUtils; -+ -@@ -53 +55 @@ public class CuteShapeFactory { -- data = data.toLowerCase().trim(); -+ data = StringUtils.trin(data.toLowerCase()); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/new/CuteShapeFactory.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/new/CuteShapeFactory.java deleted file mode 100755 index abee1c0..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/new/CuteShapeFactory.java +++ /dev/null @@ -1,82 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4041 $ - * - */ -package net.sourceforge.plantuml.cute; - -import java.util.Map; - -import net.sourceforge.plantuml.StringUtils; - -public class CuteShapeFactory { - - private final Map groups; - - public CuteShapeFactory(Map groups) { - this.groups = groups; - - } - - public Positionned createCuteShapePositionned(String data) { - final VarArgs varArgs = new VarArgs(data); - return new PositionnedImpl(createCuteShape(data), varArgs); - } - - private CuteShape createCuteShape(String data) { - data = StringUtils.trin(data.toLowerCase()); - final VarArgs varArgs = new VarArgs(data); - if (data.startsWith("circle ")) { - return new Circle(varArgs); - } - if (data.startsWith("cheese ")) { - return new Cheese(varArgs); - } - if (data.startsWith("stick ")) { - return new Stick(varArgs); - } - if (data.startsWith("rectangle ") || data.startsWith("rect ")) { - return new Rectangle(varArgs); - } - if (data.startsWith("triangle ")) { - return new Triangle(varArgs); - } - final String first = data.split(" ")[0]; - System.err.println("Looking for group " + first + " in " + groups.keySet()); - final Group group = groups.get(first); - if (group == null) { - throw new IllegalArgumentException("Cannot find group " + first + " in " + groups.keySet()); - } - System.err.println("Found group " + first + " in " + groups.keySet()); - return group; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/old/CuteShapeFactory.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/old/CuteShapeFactory.java deleted file mode 100755 index ab68e29..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/old/CuteShapeFactory.java +++ /dev/null @@ -1,80 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4041 $ - * - */ -package net.sourceforge.plantuml.cute; - -import java.util.Map; - -public class CuteShapeFactory { - - private final Map groups; - - public CuteShapeFactory(Map groups) { - this.groups = groups; - - } - - public Positionned createCuteShapePositionned(String data) { - final VarArgs varArgs = new VarArgs(data); - return new PositionnedImpl(createCuteShape(data), varArgs); - } - - private CuteShape createCuteShape(String data) { - data = data.toLowerCase().trim(); - final VarArgs varArgs = new VarArgs(data); - if (data.startsWith("circle ")) { - return new Circle(varArgs); - } - if (data.startsWith("cheese ")) { - return new Cheese(varArgs); - } - if (data.startsWith("stick ")) { - return new Stick(varArgs); - } - if (data.startsWith("rectangle ") || data.startsWith("rect ")) { - return new Rectangle(varArgs); - } - if (data.startsWith("triangle ")) { - return new Triangle(varArgs); - } - final String first = data.split(" ")[0]; - System.err.println("Looking for group " + first + " in " + groups.keySet()); - final Group group = groups.get(first); - if (group == null) { - throw new IllegalArgumentException("Cannot find group " + first + " in " + groups.keySet()); - } - System.err.println("Found group " + first + " in " + groups.keySet()); - return group; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/pair.info deleted file mode 100755 index 547383c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22196/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22196 -comSha:cf7a6c66b867dda475c76bd33d3d9937647f4fea -parentComSha:a1f043c88f08b5625dee3a455ce28ab00a96f912 -BuggyFilePath:src/net/sourceforge/plantuml/cute/CuteShapeFactory.java -FixedFilePath:src/net/sourceforge/plantuml/cute/CuteShapeFactory.java -StartLineNum:53 -EndLineNum:53 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/diff.diff deleted file mode 100755 index a51e06a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/activitydiagram3/command/CommandNote3.java b/src/net/sourceforge/plantuml/activitydiagram3/command/CommandNote3.java -index 62a680b1..9784e7f5 100644 ---- a/src/net/sourceforge/plantuml/activitydiagram3/command/CommandNote3.java -+++ b/src/net/sourceforge/plantuml/activitydiagram3/command/CommandNote3.java -@@ -35,0 +36 @@ package net.sourceforge.plantuml.activitydiagram3.command; -+import net.sourceforge.plantuml.StringUtils; -@@ -71 +72 @@ public class CommandNote3 extends SingleLineCommand2 { -- return NotePosition.valueOf(s.toUpperCase()); -+ return NotePosition.valueOf(StringUtils.goUpperCase(s)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/new/CommandNote3.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/new/CommandNote3.java deleted file mode 100755 index 9784e7f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/new/CommandNote3.java +++ /dev/null @@ -1,75 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4762 $ - * - */ -package net.sourceforge.plantuml.activitydiagram3.command; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.activitydiagram3.ActivityDiagram3; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.sequencediagram.NotePosition; - -public class CommandNote3 extends SingleLineCommand2 { - - public CommandNote3() { - super(getRegexConcat()); - } - - static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("note"), // - new RegexLeaf("POSITION", "[%s]*(left|right)?"), // - new RegexLeaf("[%s]*:[%s]*"), // - new RegexLeaf("NOTE", "(.*)"), // - new RegexLeaf("$")); - } - - @Override - protected CommandExecutionResult executeArg(ActivityDiagram3 diagram, RegexResult arg) { - final Display note = Display.getWithNewlines(arg.get("NOTE", 0)); - final NotePosition position = getPosition(arg.get("POSITION", 0)); - return diagram.addNote(note, position); - } - - private NotePosition getPosition(String s) { - if (s == null) { - return NotePosition.LEFT; - } - return NotePosition.valueOf(StringUtils.goUpperCase(s)); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/old/CommandNote3.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/old/CommandNote3.java deleted file mode 100755 index 62a680b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/old/CommandNote3.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4762 $ - * - */ -package net.sourceforge.plantuml.activitydiagram3.command; - -import net.sourceforge.plantuml.activitydiagram3.ActivityDiagram3; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.sequencediagram.NotePosition; - -public class CommandNote3 extends SingleLineCommand2 { - - public CommandNote3() { - super(getRegexConcat()); - } - - static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("note"), // - new RegexLeaf("POSITION", "[%s]*(left|right)?"), // - new RegexLeaf("[%s]*:[%s]*"), // - new RegexLeaf("NOTE", "(.*)"), // - new RegexLeaf("$")); - } - - @Override - protected CommandExecutionResult executeArg(ActivityDiagram3 diagram, RegexResult arg) { - final Display note = Display.getWithNewlines(arg.get("NOTE", 0)); - final NotePosition position = getPosition(arg.get("POSITION", 0)); - return diagram.addNote(note, position); - } - - private NotePosition getPosition(String s) { - if (s == null) { - return NotePosition.LEFT; - } - return NotePosition.valueOf(s.toUpperCase()); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/pair.info deleted file mode 100755 index c015f4a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22211/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22211 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/activitydiagram3/command/CommandNote3.java -FixedFilePath:src/net/sourceforge/plantuml/activitydiagram3/command/CommandNote3.java -StartLineNum:71 -EndLineNum:71 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/diff.diff deleted file mode 100755 index 897194f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/svek/Line.java b/src/net/sourceforge/plantuml/svek/Line.java -index 12a03d1a..7eda6fdb 100644 ---- a/src/net/sourceforge/plantuml/svek/Line.java -+++ b/src/net/sourceforge/plantuml/svek/Line.java -@@ -520 +520 @@ public class Line implements Moveable, Hideable { -- String s = "stroke=\"" + StringUtils.getAsHtml(color).toLowerCase() + "\""; -+ String s = "stroke=\"" + StringUtils.goLowerCase(StringUtils.getAsHtml(color)) + "\""; -@@ -525 +525 @@ public class Line implements Moveable, Hideable { -- s = ";stroke:" + StringUtils.getAsHtml(color).toLowerCase() + ";"; -+ s = ";stroke:" + StringUtils.goLowerCase(StringUtils.getAsHtml(color)) + ";"; -@@ -530 +530 @@ public class Line implements Moveable, Hideable { -- s = "fill=\"" + StringUtils.getAsHtml(color).toLowerCase() + "\""; -+ s = "fill=\"" + StringUtils.goLowerCase(StringUtils.getAsHtml(color)) + "\""; -@@ -535 +535 @@ public class Line implements Moveable, Hideable { -- Log.info("Cannot find color=" + color + " " + StringUtils.getAsHtml(color).toLowerCase()); -+ Log.info("Cannot find color=" + color + " " + StringUtils.goLowerCase(StringUtils.getAsHtml(color))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/new/Line.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/new/Line.java deleted file mode 100755 index 7eda6fd..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/new/Line.java +++ /dev/null @@ -1,818 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4236 $ - * - */ -package net.sourceforge.plantuml.svek; - -import java.awt.geom.Dimension2D; -import java.awt.geom.Point2D; -import java.util.Collection; -import java.util.List; - -import net.sourceforge.plantuml.Direction; -import net.sourceforge.plantuml.Hideable; -import net.sourceforge.plantuml.ISkinParam; -import net.sourceforge.plantuml.Log; -import net.sourceforge.plantuml.OptionFlags; -import net.sourceforge.plantuml.Pragma; -import net.sourceforge.plantuml.Url; -import net.sourceforge.plantuml.command.Position; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.cucadiagram.IEntity; -import net.sourceforge.plantuml.cucadiagram.IGroup; -import net.sourceforge.plantuml.cucadiagram.Link; -import net.sourceforge.plantuml.cucadiagram.LinkArrow; -import net.sourceforge.plantuml.cucadiagram.LinkDecor; -import net.sourceforge.plantuml.cucadiagram.LinkHat; -import net.sourceforge.plantuml.cucadiagram.LinkMiddleDecor; -import net.sourceforge.plantuml.cucadiagram.LinkType; -import net.sourceforge.plantuml.cucadiagram.dot.GraphvizVersion; -import net.sourceforge.plantuml.graphic.FontConfiguration; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; -import net.sourceforge.plantuml.graphic.HtmlColor; -import net.sourceforge.plantuml.graphic.StringBounder; -import net.sourceforge.plantuml.graphic.TextBlock; -import net.sourceforge.plantuml.graphic.TextBlockArrow; -import net.sourceforge.plantuml.graphic.TextBlockUtils; -import net.sourceforge.plantuml.graphic.UDrawable; -import net.sourceforge.plantuml.graphic.VerticalAlignment; -import net.sourceforge.plantuml.posimo.BezierUtils; -import net.sourceforge.plantuml.posimo.DotPath; -import net.sourceforge.plantuml.posimo.Moveable; -import net.sourceforge.plantuml.posimo.Positionable; -import net.sourceforge.plantuml.posimo.PositionableUtils; -import net.sourceforge.plantuml.svek.SvekUtils.PointListIterator; -import net.sourceforge.plantuml.svek.extremity.ExtremityFactory; -import net.sourceforge.plantuml.svek.image.EntityImageNoteLink; -import net.sourceforge.plantuml.ugraphic.UChangeBackColor; -import net.sourceforge.plantuml.ugraphic.UChangeColor; -import net.sourceforge.plantuml.ugraphic.UGraphic; -import net.sourceforge.plantuml.ugraphic.UPolygon; -import net.sourceforge.plantuml.ugraphic.UShape; -import net.sourceforge.plantuml.ugraphic.UStroke; -import net.sourceforge.plantuml.ugraphic.UTranslate; -import net.sourceforge.plantuml.StringUtils; - -public class Line implements Moveable, Hideable { - - private final String ltail; - private final String lhead; - private final Link link; - - private final String startUid; - private final String endUid; - - private final TextBlock startTailText; - private final TextBlock endHeadText; - private final TextBlock noteLabelText; - - private final int lineColor; - private final int noteLabelColor; - private final int startTailColor; - private final int endHeadColor; - - private final StringBounder stringBounder; - private final Bibliotekon bibliotekon; - - private DotPath dotPath; - - private Positionable startTailLabelXY; - private Positionable endHeadLabelXY; - private Positionable noteLabelXY; - - private UDrawable extremity2; - private UDrawable extremity1; - - private double dx; - private double dy; - - private boolean opale; - private Cluster projectionCluster; - private final GraphvizVersion graphvizVersion; - - private final Pragma pragma; - - // private GraphvizVersion getGraphvizVersion() { - // if (pragma.isDefine("graphviz")==false) { - // return GraphvizVersion.COMMON; - // } - // final String value = pragma.getValue("graphviz"); - // if ("2.34".equals(value)) { - // return GraphvizVersion.V2_34_0; - // } - // return GraphvizVersion.COMMON; - // } - - @Override - public String toString() { - return super.toString() + " color=" + lineColor; - } - - class DirectionalTextBlock implements TextBlock { - - private final TextBlock right; - private final TextBlock left; - private final TextBlock up; - private final TextBlock down; - - DirectionalTextBlock(TextBlock right, TextBlock left, TextBlock up, TextBlock down) { - this.right = right; - this.left = left; - this.up = up; - this.down = down; - } - - public void drawU(UGraphic ug) { - Direction dir = getDirection(); - if (getLinkArrow() == LinkArrow.BACKWARD) { - dir = dir.getInv(); - } - switch (dir) { - case RIGHT: - right.drawU(ug); - break; - case LEFT: - left.drawU(ug); - break; - case UP: - up.drawU(ug); - break; - case DOWN: - down.drawU(ug); - break; - default: - throw new UnsupportedOperationException(); - } - } - - public Dimension2D calculateDimension(StringBounder stringBounder) { - return right.calculateDimension(stringBounder); - } - - private Direction getDirection() { - if (isAutolink()) { - final double startAngle = dotPath.getStartAngle(); - return Direction.LEFT; - } - final Point2D start = dotPath.getStartPoint(); - final Point2D end = dotPath.getEndPoint(); - final double ang = Math.atan2(end.getX() - start.getX(), end.getY() - start.getY()); - if (ang > -Math.PI / 4 && ang < Math.PI / 4) { - return Direction.DOWN; - } - if (ang > Math.PI * 3 / 4 || ang < -Math.PI * 3 / 4) { - return Direction.UP; - } - return end.getX() > start.getX() ? Direction.RIGHT : Direction.LEFT; - } - - } - - // private boolean projectionStart() { - // return startUid.startsWith(Cluster.CENTER_ID); - // } - - public Line(String startUid, String endUid, Link link, ColorSequence colorSequence, String ltail, String lhead, - ISkinParam skinParam, StringBounder stringBounder, FontConfiguration labelFont, Bibliotekon bibliotekon, - GraphvizVersion graphvizVersion, Pragma pragma) { - if (startUid == null || endUid == null || link == null) { - throw new IllegalArgumentException(); - } - this.graphvizVersion = graphvizVersion; - this.pragma = pragma; - this.bibliotekon = bibliotekon; - this.stringBounder = stringBounder; - this.link = link; - this.startUid = startUid; - this.endUid = endUid; - this.ltail = ltail; - this.lhead = lhead; - - this.lineColor = colorSequence.getValue(); - this.noteLabelColor = colorSequence.getValue(); - this.startTailColor = colorSequence.getValue(); - this.endHeadColor = colorSequence.getValue(); - - final TextBlock labelOnly; - if (link.getLabel() == null) { - if (getLinkArrow() == LinkArrow.NONE) { - labelOnly = null; - } else { - final TextBlockArrow right = new TextBlockArrow(Direction.RIGHT, labelFont); - final TextBlockArrow left = new TextBlockArrow(Direction.LEFT, labelFont); - final TextBlockArrow up = new TextBlockArrow(Direction.UP, labelFont); - final TextBlockArrow down = new TextBlockArrow(Direction.DOWN, labelFont); - labelOnly = new DirectionalTextBlock(right, left, up, down); - } - } else { - final double marginLabel = startUid.equals(endUid) ? 6 : 1; - final TextBlock label = TextBlockUtils.withMargin( - TextBlockUtils.create(link.getLabel(), labelFont, HorizontalAlignment.CENTER, skinParam), - marginLabel, marginLabel); - if (getLinkArrow() == LinkArrow.NONE) { - labelOnly = label; - } else { - TextBlock right = new TextBlockArrow(Direction.RIGHT, labelFont); - right = TextBlockUtils.mergeLR(label, right, VerticalAlignment.CENTER); - TextBlock left = new TextBlockArrow(Direction.LEFT, labelFont); - left = TextBlockUtils.mergeLR(left, label, VerticalAlignment.CENTER); - TextBlock up = new TextBlockArrow(Direction.UP, labelFont); - up = TextBlockUtils.mergeTB(up, label, HorizontalAlignment.CENTER); - TextBlock down = new TextBlockArrow(Direction.DOWN, labelFont); - down = TextBlockUtils.mergeTB(label, down, HorizontalAlignment.CENTER); - labelOnly = new DirectionalTextBlock(right, left, up, down); - } - } - - final TextBlock noteOnly; - if (link.getNote() == null) { - noteOnly = null; - } else { - noteOnly = new EntityImageNoteLink(link.getNote(), link.getNoteColor(), skinParam); - } - - if (labelOnly != null && noteOnly != null) { - if (link.getNotePosition() == Position.LEFT) { - noteLabelText = TextBlockUtils.mergeLR(noteOnly, labelOnly, VerticalAlignment.CENTER); - } else if (link.getNotePosition() == Position.RIGHT) { - noteLabelText = TextBlockUtils.mergeLR(labelOnly, noteOnly, VerticalAlignment.CENTER); - } else if (link.getNotePosition() == Position.TOP) { - noteLabelText = TextBlockUtils.mergeTB(noteOnly, labelOnly, HorizontalAlignment.CENTER); - } else { - noteLabelText = TextBlockUtils.mergeTB(labelOnly, noteOnly, HorizontalAlignment.CENTER); - } - } else if (labelOnly != null) { - noteLabelText = labelOnly; - } else if (noteOnly != null) { - noteLabelText = noteOnly; - } else { - noteLabelText = null; - } - - if (link.getQualifier1() == null) { - startTailText = null; - } else { - startTailText = TextBlockUtils.create(Display.getWithNewlines(link.getQualifier1()), labelFont, - HorizontalAlignment.CENTER, skinParam); - } - - if (link.getQualifier2() == null) { - endHeadText = null; - } else { - endHeadText = TextBlockUtils.create(Display.getWithNewlines(link.getQualifier2()), labelFont, - HorizontalAlignment.CENTER, skinParam); - } - - } - - public boolean hasNoteLabelText() { - return noteLabelText != null; - } - - private LinkArrow getLinkArrow() { - return link.getLinkArrow(); - } - - public void appendLine(StringBuilder sb) { - // Log.println("inverted=" + isInverted()); - // if (isInverted()) { - // sb.append(endUid); - // sb.append("->"); - // sb.append(startUid); - // } else { - sb.append(startUid); - sb.append("->"); - sb.append(endUid); - // } - sb.append("["); - final LinkType linkType = link.getType(); - String decoration = linkType.getSpecificDecorationSvek(); - if (decoration.endsWith(",") == false) { - decoration += ","; - } - sb.append(decoration); - - int length = link.getLength(); - // if (graphvizVersion == GraphvizVersion.V2_34_0 && length == 1) { - // length = 2; - // } - if (pragma.horizontalLineBetweenDifferentPackageAllowed() || link.isInvis() || length != 1) { - sb.append("minlen=" + (length - 1)); - sb.append(","); - } - sb.append("color=\"" + StringUtils.getAsHtml(lineColor) + "\""); - if (noteLabelText != null) { - sb.append(","); - sb.append("label=<"); - appendTable(sb, noteLabelText.calculateDimension(stringBounder), noteLabelColor); - sb.append(">"); - // sb.append(",labelfloat=true"); - } - - if (startTailText != null) { - sb.append(","); - sb.append("taillabel=<"); - appendTable(sb, startTailText.calculateDimension(stringBounder), startTailColor); - sb.append(">"); - // sb.append(",labelangle=0"); - } - if (endHeadText != null) { - sb.append(","); - sb.append("headlabel=<"); - appendTable(sb, endHeadText.calculateDimension(stringBounder), endHeadColor); - sb.append(">"); - // sb.append(",labelangle=0"); - } - - if (ltail != null) { - sb.append(","); - sb.append("ltail="); - sb.append(ltail); - } - if (lhead != null) { - sb.append(","); - sb.append("lhead="); - sb.append(lhead); - } - if (link.isInvis()) { - sb.append(","); - sb.append("style=invis"); - } - - if (link.isConstraint() == false || link.hasTwoEntryPointsSameContainer()) { - sb.append("constraint=false,"); - } - - // if (link.getLabeldistance() != null) { - // sb.append("labeldistance=" + link.getLabeldistance() + ","); - // } - // if (link.getLabelangle() != null) { - // sb.append("labelangle=" + link.getLabelangle() + ","); - // } - // sb.append("labelangle=1,"); - - sb.append("];"); - SvekUtils.println(sb); - } - - public String rankSame() { - // if (graphvizVersion == GraphvizVersion.V2_34_0) { - // return null; - // } - if (pragma.horizontalLineBetweenDifferentPackageAllowed() == false && link.getLength() == 1) { - return "{rank=same; " + getStartUid() + "; " + getEndUid() + "}"; - } - return null; - } - - public static void appendTable(StringBuilder sb, Dimension2D dim, int col) { - final int w = (int) dim.getWidth(); - final int h = (int) dim.getHeight(); - appendTable(sb, w, h, col); - } - - public static void appendTable(StringBuilder sb, int w, int h, int col) { - sb.append(""); - sb.append(""); - sb.append(""); - sb.append(""); - sb.append(""); - sb.append("
"); - } - - public final String getStartUid() { - if (startUid.endsWith(":h")) { - return startUid.substring(0, startUid.length() - 2); - } - return startUid; - } - - public final String getEndUid() { - if (endUid.endsWith(":h")) { - return endUid.substring(0, endUid.length() - 2); - } - return endUid; - } - - public UDrawable getExtremity(LinkHat hat, LinkDecor decor, PointListIterator pointListIterator) { - final ExtremityFactory extremityFactory = decor.getExtremityFactory(); - - if (extremityFactory != null) { - final List points = pointListIterator.next(); - final Point2D p0 = points.get(0); - final Point2D p1 = points.get(1); - final Point2D p2 = points.get(2); - return extremityFactory.createUDrawable(p0, p1, p2); - } else if (decor != LinkDecor.NONE) { - final UShape sh = new UPolygon(pointListIterator.next()); - return new UDrawable() { - public void drawU(UGraphic ug) { - ug.draw(sh); - } - }; - } - return null; - - } - - public void solveLine(final String svg, final int fullHeight, MinFinder corner1) { - if (this.link.isInvis()) { - return; - } - - int idx = getIndexFromColor(svg, this.lineColor); - if (idx == -1) { - return; - // throw new IllegalStateException(); - } - idx = svg.indexOf("d=\"", idx); - if (idx == -1) { - throw new IllegalStateException(); - } - final int end = svg.indexOf("\"", idx + 3); - final String path = svg.substring(idx + 3, end); - dotPath = new DotPath(path, fullHeight); - - final PointListIterator pointListIterator = new PointListIterator(svg.substring(end), fullHeight); - - final LinkType linkType = link.getType(); - this.extremity2 = getExtremity(linkType.getHat2(), linkType.getDecor2(), pointListIterator); - this.extremity1 = getExtremity(linkType.getHat1(), linkType.getDecor1(), pointListIterator); - - if (this.noteLabelText != null) { - final Point2D pos = getXY(svg, this.noteLabelColor, fullHeight); - if (pos != null) { - corner1.manage(pos); - this.noteLabelXY = TextBlockUtils.asPositionable(noteLabelText, stringBounder, pos); - } - } - - if (this.startTailText != null) { - final Point2D pos = getXY(svg, this.startTailColor, fullHeight); - if (pos != null) { - corner1.manage(pos); - this.startTailLabelXY = TextBlockUtils.asPositionable(startTailText, stringBounder, pos); - } - } - - if (this.endHeadText != null) { - final Point2D pos = getXY(svg, this.endHeadColor, fullHeight); - if (pos != null) { - corner1.manage(pos); - this.endHeadLabelXY = TextBlockUtils.asPositionable(endHeadText, stringBounder, pos); - } - } - - if (isOpalisable() == false) { - setOpale(false); - } - } - - private boolean isOpalisable() { - return dotPath.getBeziers().size() <= 1; - } - - private Point2D.Double getXY(String svg, int color, int height) { - final int idx = getIndexFromColor(svg, color); - if (idx == -1) { - return null; - } - return SvekUtils.getMinXY(SvekUtils.extractPointsList(svg, idx, height)); - - } - - private int getIndexFromColor(String svg, int color) { - String s = "stroke=\"" + StringUtils.goLowerCase(StringUtils.getAsHtml(color)) + "\""; - int idx = svg.indexOf(s); - if (idx != -1) { - return idx; - } - s = ";stroke:" + StringUtils.goLowerCase(StringUtils.getAsHtml(color)) + ";"; - idx = svg.indexOf(s); - if (idx != -1) { - return idx; - } - s = "fill=\"" + StringUtils.goLowerCase(StringUtils.getAsHtml(color)) + "\""; - idx = svg.indexOf(s); - if (idx != -1) { - return idx; - } - Log.info("Cannot find color=" + color + " " + StringUtils.goLowerCase(StringUtils.getAsHtml(color))); - return -1; - - } - - public void drawU(UGraphic ug, double x, double y, HtmlColor color) { - if (opale) { - return; - } - - final Url url = link.getUrl(); - if (url != null) { - ug.startUrl(url); - } - - if (link.isAutoLinkOfAGroup()) { - final Cluster cl = bibliotekon.getCluster((IGroup) link.getEntity1()); - x += cl.getWidth(); - x -= dotPath.getStartPoint().getX() - cl.getMinX(); - } - - x += dx; - y += dy; - - if (link.isInvis()) { - return; - } - if (this.link.getSpecificColor() != null) { - color = this.link.getSpecificColor(); - } - - ug = ug.apply(new UChangeBackColor(null)).apply(new UChangeColor(color)); - final LinkType linkType = link.getType(); - ug = ug.apply(linkType.getStroke()); - double moveStartX = 0; - double moveStartY = 0; - double moveEndX = 0; - double moveEndY = 0; - if (projectionCluster != null && link.getEntity1() == projectionCluster.getGroup()) { - final DotPath copy = new DotPath(dotPath); - final Point2D start = copy.getStartPoint(); - final Point2D proj = projectionCluster.getClusterPosition().getProjectionOnFrontier(start); - moveStartX = proj.getX() - start.getX(); - moveStartY = proj.getY() - start.getY(); - copy.forceStartPoint(proj.getX(), proj.getY()); - ug.apply(new UTranslate(x, y)).draw(copy); - } else if (projectionCluster != null && link.getEntity2() == projectionCluster.getGroup()) { - final DotPath copy = new DotPath(dotPath); - final Point2D end = copy.getEndPoint(); - final Point2D proj = projectionCluster.getClusterPosition().getProjectionOnFrontier(end); - moveEndX = proj.getX() - end.getX(); - moveEndY = proj.getY() - end.getY(); - copy.forceEndPoint(proj.getX(), proj.getY()); - ug.apply(new UTranslate(x, y)).draw(copy); - } else { - if (dotPath == null) { - Log.info("DotPath is null for " + this); - return; - } - ug.apply(new UTranslate(x, y)).draw(dotPath); - } - - ug = ug.apply(new UStroke()).apply(new UChangeColor(color)); - - if (this.extremity1 != null) { - if (linkType.getDecor1().isFill()) { - ug = ug.apply(new UChangeBackColor(color)); - } else { - ug = ug.apply(new UChangeBackColor(null)); - } - this.extremity1.drawU(ug.apply(new UTranslate(x + moveEndX, y + moveEndY))); - } - if (this.extremity2 != null) { - if (linkType.getDecor2().isFill()) { - ug = ug.apply(new UChangeBackColor(color)); - } else { - ug = ug.apply(new UChangeBackColor(null)); - } - this.extremity2.drawU(ug.apply(new UTranslate(x + moveStartX, y + moveStartY))); - } - if (this.noteLabelText != null && this.noteLabelXY != null) { - this.noteLabelText.drawU(ug.apply(new UTranslate(x + this.noteLabelXY.getPosition().getX(), y - + this.noteLabelXY.getPosition().getY()))); - } - if (this.startTailText != null) { - this.startTailText.drawU(ug.apply(new UTranslate(x + this.startTailLabelXY.getPosition().getX(), y - + this.startTailLabelXY.getPosition().getY()))); - } - if (this.endHeadText != null) { - this.endHeadText.drawU(ug.apply(new UTranslate(x + this.endHeadLabelXY.getPosition().getX(), y - + this.endHeadLabelXY.getPosition().getY()))); - } - - if (linkType.getMiddleDecor() != LinkMiddleDecor.NONE) { - final PointAndAngle middle = dotPath.getMiddle(); - final double angleRad = middle.getAngle(); - final double angleDeg = -angleRad * 180.0 / Math.PI; - final UDrawable mi = linkType.getMiddleDecor().getMiddleFactory().createUDrawable(angleDeg - 45); - mi.drawU(ug.apply(new UTranslate(x + middle.getX(), y + middle.getY()))); - } - - if (url != null) { - ug.closeAction(); - } - } - - public boolean isInverted() { - return link.isInverted(); - } - - private double getDecorDzeta() { - final LinkType linkType = link.getType(); - final int size1 = linkType.getDecor1().getMargin(); - final int size2 = linkType.getDecor2().getMargin(); - return size1 + size2; - } - - public double getHorizontalDzeta(StringBounder stringBounder) { - if (startUid.equals(endUid)) { - return getDecorDzeta(); - } - final ArithmeticStrategy strategy; - if (isHorizontal()) { - strategy = new ArithmeticStrategySum(); - } else { - return 0; - } - if (noteLabelText != null) { - strategy.eat(noteLabelText.calculateDimension(stringBounder).getWidth()); - } - if (startTailText != null) { - strategy.eat(startTailText.calculateDimension(stringBounder).getWidth()); - } - if (endHeadText != null) { - strategy.eat(endHeadText.calculateDimension(stringBounder).getWidth()); - } - return strategy.getResult() + getDecorDzeta(); - } - - private boolean isHorizontal() { - return link.getLength() == 1; - } - - public double getVerticalDzeta(StringBounder stringBounder) { - if (startUid.equals(endUid)) { - return getDecorDzeta(); - } - if (isHorizontal()) { - return 0; - } - final ArithmeticStrategy strategy = new ArithmeticStrategySum(); - if (noteLabelText != null) { - strategy.eat(noteLabelText.calculateDimension(stringBounder).getHeight()); - } - if (startTailText != null) { - strategy.eat(startTailText.calculateDimension(stringBounder).getHeight()); - } - if (endHeadText != null) { - strategy.eat(endHeadText.calculateDimension(stringBounder).getHeight()); - } - return strategy.getResult() + getDecorDzeta(); - } - - public void manageCollision(Collection allShapes) { - - for (Shape sh : allShapes) { - final Positionable cl = PositionableUtils.addMargin(sh, 8, 8); - if (startTailText != null && startTailLabelXY != null && PositionableUtils.intersect(cl, startTailLabelXY)) { - startTailLabelXY = PositionableUtils.moveAwayFrom(cl, startTailLabelXY); - } - if (endHeadText != null && endHeadLabelXY != null && PositionableUtils.intersect(cl, endHeadLabelXY)) { - endHeadLabelXY = PositionableUtils.moveAwayFrom(cl, endHeadLabelXY); - } - } - - // final Positionable start = getStartTailPositionnable(); - // if (start != null) { - // for (Shape sh : allShapes) { - // if (cut(start, sh)) { - // avoid(startTailLabelXY, start, sh); - // } - // } - // } - // - // final Positionable end = getEndHeadPositionnable(); - // if (end != null) { - // for (Shape sh : allShapes) { - // if (cut(end, sh)) { - // avoid(endHeadLabelXY, end, sh); - // } - // } - // } - - } - - private void avoid(Point2D.Double move, Positionable pos, Shape sh) { - final Oscillator oscillator = new Oscillator(); - final Point2D.Double orig = new Point2D.Double(move.x, move.y); - while (cut(pos, sh)) { - final Point2D.Double m = oscillator.nextPosition(); - move.setLocation(orig.x + m.x, orig.y + m.y); - } - } - - private boolean cut(Positionable pos, Shape sh) { - return BezierUtils.intersect(pos, sh) || tooClose(pos); - } - - private boolean tooClose(Positionable pos) { - final double dist = dotPath.getMinDist(BezierUtils.getCenter(pos)); - final Dimension2D dim = pos.getSize(); - // Log.println("dist=" + dist); - return dist < (dim.getWidth() / 2 + 2) || dist < (dim.getHeight() / 2 + 2); - } - - public void moveSvek(double deltaX, double deltaY) { - this.dx += deltaX; - this.dy += deltaY; - } - - public final DotPath getDotPath() { - final DotPath result = new DotPath(dotPath); - result.moveSvek(dx, dy); - return result; - } - - public int getLength() { - return link.getLength(); - } - - public void setOpale(boolean opale) { - this.link.setOpale(opale); - this.opale = opale; - - } - - public boolean isOpale() { - return opale; - } - - public boolean isHorizontalSolitary() { - return link.isHorizontalSolitary(); - } - - public boolean isLinkFromOrTo(IEntity group) { - return link.getEntity1() == group || link.getEntity2() == group; - } - - public boolean hasEntryPoint() { - return link.hasEntryPoint(); - } - - public void setProjectionCluster(Cluster cluster) { - this.projectionCluster = cluster; - - } - - public boolean isHidden() { - return link.isHidden(); - } - - public boolean sameConnections(Line other) { - return link.sameConnections(other.link); - } - - private boolean isAutolink() { - return link.getEntity1() == link.getEntity2(); - } - - public Point2D getMyPoint(IEntity entity) { - if (link.getEntity1() == entity) { - return moveDelta(dotPath.getStartPoint()); - } - if (link.getEntity2() == entity) { - return moveDelta(dotPath.getEndPoint()); - } - throw new IllegalArgumentException(); - } - - private Point2D moveDelta(Point2D pt) { - return new Point2D.Double(pt.getX() + dx, pt.getY() + dy); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/old/Line.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/old/Line.java deleted file mode 100755 index 12a03d1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/old/Line.java +++ /dev/null @@ -1,818 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4236 $ - * - */ -package net.sourceforge.plantuml.svek; - -import java.awt.geom.Dimension2D; -import java.awt.geom.Point2D; -import java.util.Collection; -import java.util.List; - -import net.sourceforge.plantuml.Direction; -import net.sourceforge.plantuml.Hideable; -import net.sourceforge.plantuml.ISkinParam; -import net.sourceforge.plantuml.Log; -import net.sourceforge.plantuml.OptionFlags; -import net.sourceforge.plantuml.Pragma; -import net.sourceforge.plantuml.Url; -import net.sourceforge.plantuml.command.Position; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.cucadiagram.IEntity; -import net.sourceforge.plantuml.cucadiagram.IGroup; -import net.sourceforge.plantuml.cucadiagram.Link; -import net.sourceforge.plantuml.cucadiagram.LinkArrow; -import net.sourceforge.plantuml.cucadiagram.LinkDecor; -import net.sourceforge.plantuml.cucadiagram.LinkHat; -import net.sourceforge.plantuml.cucadiagram.LinkMiddleDecor; -import net.sourceforge.plantuml.cucadiagram.LinkType; -import net.sourceforge.plantuml.cucadiagram.dot.GraphvizVersion; -import net.sourceforge.plantuml.graphic.FontConfiguration; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; -import net.sourceforge.plantuml.graphic.HtmlColor; -import net.sourceforge.plantuml.graphic.StringBounder; -import net.sourceforge.plantuml.graphic.TextBlock; -import net.sourceforge.plantuml.graphic.TextBlockArrow; -import net.sourceforge.plantuml.graphic.TextBlockUtils; -import net.sourceforge.plantuml.graphic.UDrawable; -import net.sourceforge.plantuml.graphic.VerticalAlignment; -import net.sourceforge.plantuml.posimo.BezierUtils; -import net.sourceforge.plantuml.posimo.DotPath; -import net.sourceforge.plantuml.posimo.Moveable; -import net.sourceforge.plantuml.posimo.Positionable; -import net.sourceforge.plantuml.posimo.PositionableUtils; -import net.sourceforge.plantuml.svek.SvekUtils.PointListIterator; -import net.sourceforge.plantuml.svek.extremity.ExtremityFactory; -import net.sourceforge.plantuml.svek.image.EntityImageNoteLink; -import net.sourceforge.plantuml.ugraphic.UChangeBackColor; -import net.sourceforge.plantuml.ugraphic.UChangeColor; -import net.sourceforge.plantuml.ugraphic.UGraphic; -import net.sourceforge.plantuml.ugraphic.UPolygon; -import net.sourceforge.plantuml.ugraphic.UShape; -import net.sourceforge.plantuml.ugraphic.UStroke; -import net.sourceforge.plantuml.ugraphic.UTranslate; -import net.sourceforge.plantuml.StringUtils; - -public class Line implements Moveable, Hideable { - - private final String ltail; - private final String lhead; - private final Link link; - - private final String startUid; - private final String endUid; - - private final TextBlock startTailText; - private final TextBlock endHeadText; - private final TextBlock noteLabelText; - - private final int lineColor; - private final int noteLabelColor; - private final int startTailColor; - private final int endHeadColor; - - private final StringBounder stringBounder; - private final Bibliotekon bibliotekon; - - private DotPath dotPath; - - private Positionable startTailLabelXY; - private Positionable endHeadLabelXY; - private Positionable noteLabelXY; - - private UDrawable extremity2; - private UDrawable extremity1; - - private double dx; - private double dy; - - private boolean opale; - private Cluster projectionCluster; - private final GraphvizVersion graphvizVersion; - - private final Pragma pragma; - - // private GraphvizVersion getGraphvizVersion() { - // if (pragma.isDefine("graphviz")==false) { - // return GraphvizVersion.COMMON; - // } - // final String value = pragma.getValue("graphviz"); - // if ("2.34".equals(value)) { - // return GraphvizVersion.V2_34_0; - // } - // return GraphvizVersion.COMMON; - // } - - @Override - public String toString() { - return super.toString() + " color=" + lineColor; - } - - class DirectionalTextBlock implements TextBlock { - - private final TextBlock right; - private final TextBlock left; - private final TextBlock up; - private final TextBlock down; - - DirectionalTextBlock(TextBlock right, TextBlock left, TextBlock up, TextBlock down) { - this.right = right; - this.left = left; - this.up = up; - this.down = down; - } - - public void drawU(UGraphic ug) { - Direction dir = getDirection(); - if (getLinkArrow() == LinkArrow.BACKWARD) { - dir = dir.getInv(); - } - switch (dir) { - case RIGHT: - right.drawU(ug); - break; - case LEFT: - left.drawU(ug); - break; - case UP: - up.drawU(ug); - break; - case DOWN: - down.drawU(ug); - break; - default: - throw new UnsupportedOperationException(); - } - } - - public Dimension2D calculateDimension(StringBounder stringBounder) { - return right.calculateDimension(stringBounder); - } - - private Direction getDirection() { - if (isAutolink()) { - final double startAngle = dotPath.getStartAngle(); - return Direction.LEFT; - } - final Point2D start = dotPath.getStartPoint(); - final Point2D end = dotPath.getEndPoint(); - final double ang = Math.atan2(end.getX() - start.getX(), end.getY() - start.getY()); - if (ang > -Math.PI / 4 && ang < Math.PI / 4) { - return Direction.DOWN; - } - if (ang > Math.PI * 3 / 4 || ang < -Math.PI * 3 / 4) { - return Direction.UP; - } - return end.getX() > start.getX() ? Direction.RIGHT : Direction.LEFT; - } - - } - - // private boolean projectionStart() { - // return startUid.startsWith(Cluster.CENTER_ID); - // } - - public Line(String startUid, String endUid, Link link, ColorSequence colorSequence, String ltail, String lhead, - ISkinParam skinParam, StringBounder stringBounder, FontConfiguration labelFont, Bibliotekon bibliotekon, - GraphvizVersion graphvizVersion, Pragma pragma) { - if (startUid == null || endUid == null || link == null) { - throw new IllegalArgumentException(); - } - this.graphvizVersion = graphvizVersion; - this.pragma = pragma; - this.bibliotekon = bibliotekon; - this.stringBounder = stringBounder; - this.link = link; - this.startUid = startUid; - this.endUid = endUid; - this.ltail = ltail; - this.lhead = lhead; - - this.lineColor = colorSequence.getValue(); - this.noteLabelColor = colorSequence.getValue(); - this.startTailColor = colorSequence.getValue(); - this.endHeadColor = colorSequence.getValue(); - - final TextBlock labelOnly; - if (link.getLabel() == null) { - if (getLinkArrow() == LinkArrow.NONE) { - labelOnly = null; - } else { - final TextBlockArrow right = new TextBlockArrow(Direction.RIGHT, labelFont); - final TextBlockArrow left = new TextBlockArrow(Direction.LEFT, labelFont); - final TextBlockArrow up = new TextBlockArrow(Direction.UP, labelFont); - final TextBlockArrow down = new TextBlockArrow(Direction.DOWN, labelFont); - labelOnly = new DirectionalTextBlock(right, left, up, down); - } - } else { - final double marginLabel = startUid.equals(endUid) ? 6 : 1; - final TextBlock label = TextBlockUtils.withMargin( - TextBlockUtils.create(link.getLabel(), labelFont, HorizontalAlignment.CENTER, skinParam), - marginLabel, marginLabel); - if (getLinkArrow() == LinkArrow.NONE) { - labelOnly = label; - } else { - TextBlock right = new TextBlockArrow(Direction.RIGHT, labelFont); - right = TextBlockUtils.mergeLR(label, right, VerticalAlignment.CENTER); - TextBlock left = new TextBlockArrow(Direction.LEFT, labelFont); - left = TextBlockUtils.mergeLR(left, label, VerticalAlignment.CENTER); - TextBlock up = new TextBlockArrow(Direction.UP, labelFont); - up = TextBlockUtils.mergeTB(up, label, HorizontalAlignment.CENTER); - TextBlock down = new TextBlockArrow(Direction.DOWN, labelFont); - down = TextBlockUtils.mergeTB(label, down, HorizontalAlignment.CENTER); - labelOnly = new DirectionalTextBlock(right, left, up, down); - } - } - - final TextBlock noteOnly; - if (link.getNote() == null) { - noteOnly = null; - } else { - noteOnly = new EntityImageNoteLink(link.getNote(), link.getNoteColor(), skinParam); - } - - if (labelOnly != null && noteOnly != null) { - if (link.getNotePosition() == Position.LEFT) { - noteLabelText = TextBlockUtils.mergeLR(noteOnly, labelOnly, VerticalAlignment.CENTER); - } else if (link.getNotePosition() == Position.RIGHT) { - noteLabelText = TextBlockUtils.mergeLR(labelOnly, noteOnly, VerticalAlignment.CENTER); - } else if (link.getNotePosition() == Position.TOP) { - noteLabelText = TextBlockUtils.mergeTB(noteOnly, labelOnly, HorizontalAlignment.CENTER); - } else { - noteLabelText = TextBlockUtils.mergeTB(labelOnly, noteOnly, HorizontalAlignment.CENTER); - } - } else if (labelOnly != null) { - noteLabelText = labelOnly; - } else if (noteOnly != null) { - noteLabelText = noteOnly; - } else { - noteLabelText = null; - } - - if (link.getQualifier1() == null) { - startTailText = null; - } else { - startTailText = TextBlockUtils.create(Display.getWithNewlines(link.getQualifier1()), labelFont, - HorizontalAlignment.CENTER, skinParam); - } - - if (link.getQualifier2() == null) { - endHeadText = null; - } else { - endHeadText = TextBlockUtils.create(Display.getWithNewlines(link.getQualifier2()), labelFont, - HorizontalAlignment.CENTER, skinParam); - } - - } - - public boolean hasNoteLabelText() { - return noteLabelText != null; - } - - private LinkArrow getLinkArrow() { - return link.getLinkArrow(); - } - - public void appendLine(StringBuilder sb) { - // Log.println("inverted=" + isInverted()); - // if (isInverted()) { - // sb.append(endUid); - // sb.append("->"); - // sb.append(startUid); - // } else { - sb.append(startUid); - sb.append("->"); - sb.append(endUid); - // } - sb.append("["); - final LinkType linkType = link.getType(); - String decoration = linkType.getSpecificDecorationSvek(); - if (decoration.endsWith(",") == false) { - decoration += ","; - } - sb.append(decoration); - - int length = link.getLength(); - // if (graphvizVersion == GraphvizVersion.V2_34_0 && length == 1) { - // length = 2; - // } - if (pragma.horizontalLineBetweenDifferentPackageAllowed() || link.isInvis() || length != 1) { - sb.append("minlen=" + (length - 1)); - sb.append(","); - } - sb.append("color=\"" + StringUtils.getAsHtml(lineColor) + "\""); - if (noteLabelText != null) { - sb.append(","); - sb.append("label=<"); - appendTable(sb, noteLabelText.calculateDimension(stringBounder), noteLabelColor); - sb.append(">"); - // sb.append(",labelfloat=true"); - } - - if (startTailText != null) { - sb.append(","); - sb.append("taillabel=<"); - appendTable(sb, startTailText.calculateDimension(stringBounder), startTailColor); - sb.append(">"); - // sb.append(",labelangle=0"); - } - if (endHeadText != null) { - sb.append(","); - sb.append("headlabel=<"); - appendTable(sb, endHeadText.calculateDimension(stringBounder), endHeadColor); - sb.append(">"); - // sb.append(",labelangle=0"); - } - - if (ltail != null) { - sb.append(","); - sb.append("ltail="); - sb.append(ltail); - } - if (lhead != null) { - sb.append(","); - sb.append("lhead="); - sb.append(lhead); - } - if (link.isInvis()) { - sb.append(","); - sb.append("style=invis"); - } - - if (link.isConstraint() == false || link.hasTwoEntryPointsSameContainer()) { - sb.append("constraint=false,"); - } - - // if (link.getLabeldistance() != null) { - // sb.append("labeldistance=" + link.getLabeldistance() + ","); - // } - // if (link.getLabelangle() != null) { - // sb.append("labelangle=" + link.getLabelangle() + ","); - // } - // sb.append("labelangle=1,"); - - sb.append("];"); - SvekUtils.println(sb); - } - - public String rankSame() { - // if (graphvizVersion == GraphvizVersion.V2_34_0) { - // return null; - // } - if (pragma.horizontalLineBetweenDifferentPackageAllowed() == false && link.getLength() == 1) { - return "{rank=same; " + getStartUid() + "; " + getEndUid() + "}"; - } - return null; - } - - public static void appendTable(StringBuilder sb, Dimension2D dim, int col) { - final int w = (int) dim.getWidth(); - final int h = (int) dim.getHeight(); - appendTable(sb, w, h, col); - } - - public static void appendTable(StringBuilder sb, int w, int h, int col) { - sb.append(""); - sb.append(""); - sb.append(""); - sb.append(""); - sb.append(""); - sb.append("
"); - } - - public final String getStartUid() { - if (startUid.endsWith(":h")) { - return startUid.substring(0, startUid.length() - 2); - } - return startUid; - } - - public final String getEndUid() { - if (endUid.endsWith(":h")) { - return endUid.substring(0, endUid.length() - 2); - } - return endUid; - } - - public UDrawable getExtremity(LinkHat hat, LinkDecor decor, PointListIterator pointListIterator) { - final ExtremityFactory extremityFactory = decor.getExtremityFactory(); - - if (extremityFactory != null) { - final List points = pointListIterator.next(); - final Point2D p0 = points.get(0); - final Point2D p1 = points.get(1); - final Point2D p2 = points.get(2); - return extremityFactory.createUDrawable(p0, p1, p2); - } else if (decor != LinkDecor.NONE) { - final UShape sh = new UPolygon(pointListIterator.next()); - return new UDrawable() { - public void drawU(UGraphic ug) { - ug.draw(sh); - } - }; - } - return null; - - } - - public void solveLine(final String svg, final int fullHeight, MinFinder corner1) { - if (this.link.isInvis()) { - return; - } - - int idx = getIndexFromColor(svg, this.lineColor); - if (idx == -1) { - return; - // throw new IllegalStateException(); - } - idx = svg.indexOf("d=\"", idx); - if (idx == -1) { - throw new IllegalStateException(); - } - final int end = svg.indexOf("\"", idx + 3); - final String path = svg.substring(idx + 3, end); - dotPath = new DotPath(path, fullHeight); - - final PointListIterator pointListIterator = new PointListIterator(svg.substring(end), fullHeight); - - final LinkType linkType = link.getType(); - this.extremity2 = getExtremity(linkType.getHat2(), linkType.getDecor2(), pointListIterator); - this.extremity1 = getExtremity(linkType.getHat1(), linkType.getDecor1(), pointListIterator); - - if (this.noteLabelText != null) { - final Point2D pos = getXY(svg, this.noteLabelColor, fullHeight); - if (pos != null) { - corner1.manage(pos); - this.noteLabelXY = TextBlockUtils.asPositionable(noteLabelText, stringBounder, pos); - } - } - - if (this.startTailText != null) { - final Point2D pos = getXY(svg, this.startTailColor, fullHeight); - if (pos != null) { - corner1.manage(pos); - this.startTailLabelXY = TextBlockUtils.asPositionable(startTailText, stringBounder, pos); - } - } - - if (this.endHeadText != null) { - final Point2D pos = getXY(svg, this.endHeadColor, fullHeight); - if (pos != null) { - corner1.manage(pos); - this.endHeadLabelXY = TextBlockUtils.asPositionable(endHeadText, stringBounder, pos); - } - } - - if (isOpalisable() == false) { - setOpale(false); - } - } - - private boolean isOpalisable() { - return dotPath.getBeziers().size() <= 1; - } - - private Point2D.Double getXY(String svg, int color, int height) { - final int idx = getIndexFromColor(svg, color); - if (idx == -1) { - return null; - } - return SvekUtils.getMinXY(SvekUtils.extractPointsList(svg, idx, height)); - - } - - private int getIndexFromColor(String svg, int color) { - String s = "stroke=\"" + StringUtils.getAsHtml(color).toLowerCase() + "\""; - int idx = svg.indexOf(s); - if (idx != -1) { - return idx; - } - s = ";stroke:" + StringUtils.getAsHtml(color).toLowerCase() + ";"; - idx = svg.indexOf(s); - if (idx != -1) { - return idx; - } - s = "fill=\"" + StringUtils.getAsHtml(color).toLowerCase() + "\""; - idx = svg.indexOf(s); - if (idx != -1) { - return idx; - } - Log.info("Cannot find color=" + color + " " + StringUtils.getAsHtml(color).toLowerCase()); - return -1; - - } - - public void drawU(UGraphic ug, double x, double y, HtmlColor color) { - if (opale) { - return; - } - - final Url url = link.getUrl(); - if (url != null) { - ug.startUrl(url); - } - - if (link.isAutoLinkOfAGroup()) { - final Cluster cl = bibliotekon.getCluster((IGroup) link.getEntity1()); - x += cl.getWidth(); - x -= dotPath.getStartPoint().getX() - cl.getMinX(); - } - - x += dx; - y += dy; - - if (link.isInvis()) { - return; - } - if (this.link.getSpecificColor() != null) { - color = this.link.getSpecificColor(); - } - - ug = ug.apply(new UChangeBackColor(null)).apply(new UChangeColor(color)); - final LinkType linkType = link.getType(); - ug = ug.apply(linkType.getStroke()); - double moveStartX = 0; - double moveStartY = 0; - double moveEndX = 0; - double moveEndY = 0; - if (projectionCluster != null && link.getEntity1() == projectionCluster.getGroup()) { - final DotPath copy = new DotPath(dotPath); - final Point2D start = copy.getStartPoint(); - final Point2D proj = projectionCluster.getClusterPosition().getProjectionOnFrontier(start); - moveStartX = proj.getX() - start.getX(); - moveStartY = proj.getY() - start.getY(); - copy.forceStartPoint(proj.getX(), proj.getY()); - ug.apply(new UTranslate(x, y)).draw(copy); - } else if (projectionCluster != null && link.getEntity2() == projectionCluster.getGroup()) { - final DotPath copy = new DotPath(dotPath); - final Point2D end = copy.getEndPoint(); - final Point2D proj = projectionCluster.getClusterPosition().getProjectionOnFrontier(end); - moveEndX = proj.getX() - end.getX(); - moveEndY = proj.getY() - end.getY(); - copy.forceEndPoint(proj.getX(), proj.getY()); - ug.apply(new UTranslate(x, y)).draw(copy); - } else { - if (dotPath == null) { - Log.info("DotPath is null for " + this); - return; - } - ug.apply(new UTranslate(x, y)).draw(dotPath); - } - - ug = ug.apply(new UStroke()).apply(new UChangeColor(color)); - - if (this.extremity1 != null) { - if (linkType.getDecor1().isFill()) { - ug = ug.apply(new UChangeBackColor(color)); - } else { - ug = ug.apply(new UChangeBackColor(null)); - } - this.extremity1.drawU(ug.apply(new UTranslate(x + moveEndX, y + moveEndY))); - } - if (this.extremity2 != null) { - if (linkType.getDecor2().isFill()) { - ug = ug.apply(new UChangeBackColor(color)); - } else { - ug = ug.apply(new UChangeBackColor(null)); - } - this.extremity2.drawU(ug.apply(new UTranslate(x + moveStartX, y + moveStartY))); - } - if (this.noteLabelText != null && this.noteLabelXY != null) { - this.noteLabelText.drawU(ug.apply(new UTranslate(x + this.noteLabelXY.getPosition().getX(), y - + this.noteLabelXY.getPosition().getY()))); - } - if (this.startTailText != null) { - this.startTailText.drawU(ug.apply(new UTranslate(x + this.startTailLabelXY.getPosition().getX(), y - + this.startTailLabelXY.getPosition().getY()))); - } - if (this.endHeadText != null) { - this.endHeadText.drawU(ug.apply(new UTranslate(x + this.endHeadLabelXY.getPosition().getX(), y - + this.endHeadLabelXY.getPosition().getY()))); - } - - if (linkType.getMiddleDecor() != LinkMiddleDecor.NONE) { - final PointAndAngle middle = dotPath.getMiddle(); - final double angleRad = middle.getAngle(); - final double angleDeg = -angleRad * 180.0 / Math.PI; - final UDrawable mi = linkType.getMiddleDecor().getMiddleFactory().createUDrawable(angleDeg - 45); - mi.drawU(ug.apply(new UTranslate(x + middle.getX(), y + middle.getY()))); - } - - if (url != null) { - ug.closeAction(); - } - } - - public boolean isInverted() { - return link.isInverted(); - } - - private double getDecorDzeta() { - final LinkType linkType = link.getType(); - final int size1 = linkType.getDecor1().getMargin(); - final int size2 = linkType.getDecor2().getMargin(); - return size1 + size2; - } - - public double getHorizontalDzeta(StringBounder stringBounder) { - if (startUid.equals(endUid)) { - return getDecorDzeta(); - } - final ArithmeticStrategy strategy; - if (isHorizontal()) { - strategy = new ArithmeticStrategySum(); - } else { - return 0; - } - if (noteLabelText != null) { - strategy.eat(noteLabelText.calculateDimension(stringBounder).getWidth()); - } - if (startTailText != null) { - strategy.eat(startTailText.calculateDimension(stringBounder).getWidth()); - } - if (endHeadText != null) { - strategy.eat(endHeadText.calculateDimension(stringBounder).getWidth()); - } - return strategy.getResult() + getDecorDzeta(); - } - - private boolean isHorizontal() { - return link.getLength() == 1; - } - - public double getVerticalDzeta(StringBounder stringBounder) { - if (startUid.equals(endUid)) { - return getDecorDzeta(); - } - if (isHorizontal()) { - return 0; - } - final ArithmeticStrategy strategy = new ArithmeticStrategySum(); - if (noteLabelText != null) { - strategy.eat(noteLabelText.calculateDimension(stringBounder).getHeight()); - } - if (startTailText != null) { - strategy.eat(startTailText.calculateDimension(stringBounder).getHeight()); - } - if (endHeadText != null) { - strategy.eat(endHeadText.calculateDimension(stringBounder).getHeight()); - } - return strategy.getResult() + getDecorDzeta(); - } - - public void manageCollision(Collection allShapes) { - - for (Shape sh : allShapes) { - final Positionable cl = PositionableUtils.addMargin(sh, 8, 8); - if (startTailText != null && startTailLabelXY != null && PositionableUtils.intersect(cl, startTailLabelXY)) { - startTailLabelXY = PositionableUtils.moveAwayFrom(cl, startTailLabelXY); - } - if (endHeadText != null && endHeadLabelXY != null && PositionableUtils.intersect(cl, endHeadLabelXY)) { - endHeadLabelXY = PositionableUtils.moveAwayFrom(cl, endHeadLabelXY); - } - } - - // final Positionable start = getStartTailPositionnable(); - // if (start != null) { - // for (Shape sh : allShapes) { - // if (cut(start, sh)) { - // avoid(startTailLabelXY, start, sh); - // } - // } - // } - // - // final Positionable end = getEndHeadPositionnable(); - // if (end != null) { - // for (Shape sh : allShapes) { - // if (cut(end, sh)) { - // avoid(endHeadLabelXY, end, sh); - // } - // } - // } - - } - - private void avoid(Point2D.Double move, Positionable pos, Shape sh) { - final Oscillator oscillator = new Oscillator(); - final Point2D.Double orig = new Point2D.Double(move.x, move.y); - while (cut(pos, sh)) { - final Point2D.Double m = oscillator.nextPosition(); - move.setLocation(orig.x + m.x, orig.y + m.y); - } - } - - private boolean cut(Positionable pos, Shape sh) { - return BezierUtils.intersect(pos, sh) || tooClose(pos); - } - - private boolean tooClose(Positionable pos) { - final double dist = dotPath.getMinDist(BezierUtils.getCenter(pos)); - final Dimension2D dim = pos.getSize(); - // Log.println("dist=" + dist); - return dist < (dim.getWidth() / 2 + 2) || dist < (dim.getHeight() / 2 + 2); - } - - public void moveSvek(double deltaX, double deltaY) { - this.dx += deltaX; - this.dy += deltaY; - } - - public final DotPath getDotPath() { - final DotPath result = new DotPath(dotPath); - result.moveSvek(dx, dy); - return result; - } - - public int getLength() { - return link.getLength(); - } - - public void setOpale(boolean opale) { - this.link.setOpale(opale); - this.opale = opale; - - } - - public boolean isOpale() { - return opale; - } - - public boolean isHorizontalSolitary() { - return link.isHorizontalSolitary(); - } - - public boolean isLinkFromOrTo(IEntity group) { - return link.getEntity1() == group || link.getEntity2() == group; - } - - public boolean hasEntryPoint() { - return link.hasEntryPoint(); - } - - public void setProjectionCluster(Cluster cluster) { - this.projectionCluster = cluster; - - } - - public boolean isHidden() { - return link.isHidden(); - } - - public boolean sameConnections(Line other) { - return link.sameConnections(other.link); - } - - private boolean isAutolink() { - return link.getEntity1() == link.getEntity2(); - } - - public Point2D getMyPoint(IEntity entity) { - if (link.getEntity1() == entity) { - return moveDelta(dotPath.getStartPoint()); - } - if (link.getEntity2() == entity) { - return moveDelta(dotPath.getEndPoint()); - } - throw new IllegalArgumentException(); - } - - private Point2D moveDelta(Point2D pt) { - return new Point2D.Double(pt.getX() + dx, pt.getY() + dy); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/pair.info deleted file mode 100755 index 8fd4d97..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22235/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22235 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/svek/Line.java -FixedFilePath:src/net/sourceforge/plantuml/svek/Line.java -StartLineNum:520 -EndLineNum:520 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/comMsg.txt deleted file mode 100755 index 4a9e473..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 7933 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@211 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/diff.diff deleted file mode 100755 index fa019a2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/project2/command/CommandCloseWeekDay.java b/src/net/sourceforge/plantuml/project2/command/CommandCloseWeekDay.java -index 465a325f..993cdf35 100644 ---- a/src/net/sourceforge/plantuml/project2/command/CommandCloseWeekDay.java -+++ b/src/net/sourceforge/plantuml/project2/command/CommandCloseWeekDay.java -@@ -40 +39,0 @@ import net.sourceforge.plantuml.command.SingleLineCommand; --import net.sourceforge.plantuml.project.WeekDay; -@@ -51 +50 @@ public class CommandCloseWeekDay extends SingleLineCommand { -- final WeekDay weekDay = WeekDay.valueOf(arg.get(0).substring(0, 3).toUpperCase()); -+ // final WeekDay weekDay = WeekDay.valueOf(arg.get(0).substring(0, 3).toUpperCase()); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/new/CommandCloseWeekDay.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/new/CommandCloseWeekDay.java deleted file mode 100755 index 993cdf3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/new/CommandCloseWeekDay.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2012, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5884 $ - * - */ -package net.sourceforge.plantuml.project2.command; - -import java.util.List; - -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand; -import net.sourceforge.plantuml.project2.PSystemProject2; - -public class CommandCloseWeekDay extends SingleLineCommand { - - public CommandCloseWeekDay(PSystemProject2 diagram) { - super(diagram, "(?i)^\\s*close\\s+(\\w{3,}day)\\s*$"); - } - - @Override - protected CommandExecutionResult executeArg(List arg) { - // final WeekDay weekDay = WeekDay.valueOf(arg.get(0).substring(0, 3).toUpperCase()); -// getSystem().getProject().closeWeekDay(weekDay); - return CommandExecutionResult.ok(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/old/CommandCloseWeekDay.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/old/CommandCloseWeekDay.java deleted file mode 100755 index 465a325..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/old/CommandCloseWeekDay.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2012, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5884 $ - * - */ -package net.sourceforge.plantuml.project2.command; - -import java.util.List; - -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand; -import net.sourceforge.plantuml.project.WeekDay; -import net.sourceforge.plantuml.project2.PSystemProject2; - -public class CommandCloseWeekDay extends SingleLineCommand { - - public CommandCloseWeekDay(PSystemProject2 diagram) { - super(diagram, "(?i)^\\s*close\\s+(\\w{3,}day)\\s*$"); - } - - @Override - protected CommandExecutionResult executeArg(List arg) { - final WeekDay weekDay = WeekDay.valueOf(arg.get(0).substring(0, 3).toUpperCase()); -// getSystem().getProject().closeWeekDay(weekDay); - return CommandExecutionResult.ok(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/pair.info deleted file mode 100755 index aec923c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22242/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22242 -comSha:aebe4904d250a778adc1060cef17bce05f2b16cd -parentComSha:d0f0909d2e0b79b18361203c14f8766365a53056 -BuggyFilePath:src/net/sourceforge/plantuml/project2/command/CommandCloseWeekDay.java -FixedFilePath:src/net/sourceforge/plantuml/project2/command/CommandCloseWeekDay.java -StartLineNum:51 -EndLineNum:51 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/diff.diff deleted file mode 100755 index 582f3c3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/ftp/FtpLoop.java b/src/net/sourceforge/plantuml/ftp/FtpLoop.java -index 4c5fec7e..85cb9cca 100644 ---- a/src/net/sourceforge/plantuml/ftp/FtpLoop.java -+++ b/src/net/sourceforge/plantuml/ftp/FtpLoop.java -@@ -53,0 +54 @@ import net.sourceforge.plantuml.FileUtils; -+import net.sourceforge.plantuml.StringUtils; -@@ -104 +105 @@ class FtpLoop implements Runnable { -- final String upper = cmd.toUpperCase(); -+ final String upper = StringUtils.goUpperCase(cmd); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/new/FtpLoop.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/new/FtpLoop.java deleted file mode 100755 index 85cb9cc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/new/FtpLoop.java +++ /dev/null @@ -1,305 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3830 $ - * - */ -package net.sourceforge.plantuml.ftp; - -// server - -// FtpServer.java -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.UnknownHostException; -import java.util.Collection; -import java.util.StringTokenizer; - -import net.sourceforge.plantuml.FileFormat; -import net.sourceforge.plantuml.FileUtils; -import net.sourceforge.plantuml.StringUtils; - -class FtpLoop implements Runnable { - enum Mode { - ACTIF, PASSIF - }; - - final private Socket incoming; - final private FtpServer ftpServer; - final private BufferedReader br; - final private PrintWriter pw; - - private FtpConnexion connexion; - private String ipClient = null; - private int port = -1; - private Mode mode; - - public FtpLoop(Socket socket, FtpServer ftpServer) throws IOException { - this.incoming = socket; - this.ftpServer = ftpServer; - this.br = new BufferedReader(new InputStreamReader(incoming.getInputStream(), ftpServer.getCharset())); - this.pw = new PrintWriter(incoming.getOutputStream(), true); - } - - // http://www.ncftp.com/libncftp/doc/ftp_overview.html - // http://www.nsftools.com/tips/RawFTP.htm - // http://www.commentcamarche.net/contents/internet/ftp.php3 - // http://en.wikipedia.org/wiki/List_of_FTP_server_return_codes - // http://www.freefire.org/articles/ftpexample.php - // http://forum.hardware.fr/hfr/Programmation/VB-VBA-VBS/transfert-sujet_59989_1.htm - // http://www.excel-downloads.com/forum/104130-telechargement-ftp-via-vba.html - // http://www.pcreview.co.uk/forums/ftp-vba-macro-t949945.html - private void runInternal() throws IOException, InterruptedException { - localLog("Starting Loop"); - myOut("220 PlantUML"); - while (true) { - final String s = br.readLine(); - localLog("s=" + s); - if (s == null) { - pw.close(); - br.close(); - return; - } - final boolean finish = manage(s); - if (finish) { - return; - } - } - } - - private boolean manage(final String cmd) throws UnknownHostException, IOException, InterruptedException { - final String upper = StringUtils.goUpperCase(cmd); - if (upper.startsWith("USER")) { - myOut("331 Password required"); - final String user = cmd.substring("USER ".length()); - connexion = ftpServer.getFtpConnexion(user); - } else if (upper.startsWith("PASS")) { - myOut("230 Logged in."); - } else if (upper.startsWith("PWD")) { - // myOut("/"); - // myOut("200 OK /"); - myOut("257 \"/\" is current directory."); - } else if (upper.startsWith("CWD")) { - final String dir = cmd.substring("CWD ".length()); - myOut("250 \"" + dir + "\" is new working directory.."); - } else if (upper.startsWith("TYPE")) { - myOut("200 Command okay."); - // localLog("type=" + s); - } else if (upper.startsWith("PORT")) { - mode = Mode.ACTIF; - final StringTokenizer st = new StringTokenizer(cmd, " ,"); - st.nextToken(); - ipClient = st.nextToken() + "." + st.nextToken() + "." + st.nextToken() + "." + st.nextToken(); - port = Integer.parseInt(st.nextToken()) * 256 + Integer.parseInt(st.nextToken()); - // localLog("ipClient=" + ipClient); - // localLog("port=" + port); - - myOut("200 Command okay."); - } else if (upper.startsWith("LIST")) { - if (mode == Mode.ACTIF) { - listActif(); - } else { - listPassif(); - } - } else if (upper.startsWith("STOR")) { - if (mode == Mode.ACTIF) { - storActif(cmd); - } else { - storPassif(cmd); - } - } else if (upper.startsWith("PASV")) { - mode = Mode.PASSIF; - port = ftpServer.getFreePort(); - final int p1 = port / 256; - final int p2 = port % 256; - assert port == p1 * 256 + p2; - localLog("adr=" + incoming.getInetAddress().getHostAddress()); - final String ipServer = ftpServer.getIpServer(); - localLog("server=" + ipServer); - myOut("227 Entering Passive Mode (" + ipServer.replace('.', ',') + "," + p1 + "," + p2 + ")."); - ipClient = ipServer; - } else if (upper.startsWith("RETR")) { - if (mode == Mode.ACTIF) { - retrActif(cmd); - } else { - retrPassif(cmd); - } - } else if (upper.startsWith("DELE")) { - final String file = cmd.substring("DELE ".length()); - connexion.delete(file); - myOut("200 Command okay."); - } else if (upper.startsWith("QUIT")) { - myOut("221 Goodbye."); - return true; - } else if (upper.startsWith("SYST")) { - myOut("215 UNIX Type: L8."); - } else { - myOut("502 Command not implemented."); - } - return false; - } - - private void localLog(String s) { - } - - private void retr(final String fileName, Socket soc) throws UnknownHostException, IOException, InterruptedException { - final OutputStream os = soc.getOutputStream(); - byte[] data = null; - do { - data = connexion.getData(fileName); - if (data.length == 0) { - Thread.sleep(200L); - } - } while (data.length == 0); - - os.write(data); - os.flush(); - os.close(); - soc.close(); - myOut("226 Transfer complete."); - } - - private void retrPassif(final String s) throws UnknownHostException, IOException, InterruptedException { - String fileName = s.substring("STOR ".length()); - fileName = removeStartingsSlash(fileName); - myOut("150 Opening"); - final ServerSocket ss = new ServerSocket(port); - final Socket incoming = ss.accept(); - retr(fileName, incoming); - ss.close(); - } - - private void retrActif(final String s) throws UnknownHostException, IOException, InterruptedException { - String fileName = s.substring("STOR ".length()); - fileName = removeStartingsSlash(fileName); - myOut("150 Opening"); - final Socket soc = new Socket(ipClient, port); - retr(fileName, soc); - } - - private void storActif(final String s) throws IOException { - final String fileName = removeStartingsSlash(s.substring("STOR ".length())); - myOut("150 FILE: " + fileName); - final Socket soc = new Socket(ipClient, port); - stor(fileName, soc); - } - - private void storPassif(final String s) throws IOException { - final String fileName = removeStartingsSlash(s.substring("STOR ".length())); - myOut("150 FILE: " + fileName); - final ServerSocket ss = new ServerSocket(port); - final Socket incoming = ss.accept(); - stor(fileName, incoming); - ss.close(); - } - - private String removeStartingsSlash(String fileName) { - while (fileName.startsWith("/")) { - fileName = fileName.substring(1); - } - return fileName; - } - - private void stor(String fileName, Socket socket) throws UnknownHostException, IOException { - final InputStream is = socket.getInputStream(); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - FileUtils.copyToStream(is, baos); - myOut("226 Transfer complete."); - final String data = new String(baos.toByteArray(), ftpServer.getCharset()); - final FileFormat format = FileFormat.PNG; - final String pngFileName = format.changeName(fileName, 0); - connexion.removeOutgoing(pngFileName); - connexion.addIncoming(fileName, data); - - ftpServer.processImage(connexion, fileName); - } - - private void listActif() throws UnknownHostException, IOException { - myOut("150 Opening ASCII mode data"); - final Socket soc = new Socket(ipClient, port); - list(soc); - } - - private void listPassif() throws UnknownHostException, IOException { - myOut("150 Opening ASCII mode data"); - final ServerSocket ss = new ServerSocket(port); - final Socket incoming = ss.accept(); - list(incoming); - ss.close(); - } - - private void list(final Socket soc) throws IOException { - final PrintWriter listing = new PrintWriter(soc.getOutputStream(), true); - final Collection files = connexion.getFiles(); - if (files.size() > 0) { - int total = 0; - for (String n : files) { - total += (connexion.getSize(n) + 511) / 512; - } - listing.println("total " + total); - // localLog(total); - for (String n : files) { - final String ls = String.format("%10s %4d %-8s %-8s %8d %3s %2s %5s %s", "-rw-rw-r--", 1, "plantuml", - "plantuml", connexion.getSize(n), "Sep", 28, 2006, n); - listing.println(ls); - // localLog(ls); - } - } - listing.flush(); - listing.close(); - soc.close(); - myOut("226 Listing completed."); - } - - private void myOut(String s) { - if (s.indexOf('\t') != -1) { - throw new IllegalArgumentException(); - } - pw.println(s); - pw.flush(); - } - - public void run() { - try { - runInternal(); - } catch (Throwable t) { - t.printStackTrace(); - } - - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/old/FtpLoop.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/old/FtpLoop.java deleted file mode 100755 index 4c5fec7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/old/FtpLoop.java +++ /dev/null @@ -1,304 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3830 $ - * - */ -package net.sourceforge.plantuml.ftp; - -// server - -// FtpServer.java -import java.io.BufferedReader; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.net.ServerSocket; -import java.net.Socket; -import java.net.UnknownHostException; -import java.util.Collection; -import java.util.StringTokenizer; - -import net.sourceforge.plantuml.FileFormat; -import net.sourceforge.plantuml.FileUtils; - -class FtpLoop implements Runnable { - enum Mode { - ACTIF, PASSIF - }; - - final private Socket incoming; - final private FtpServer ftpServer; - final private BufferedReader br; - final private PrintWriter pw; - - private FtpConnexion connexion; - private String ipClient = null; - private int port = -1; - private Mode mode; - - public FtpLoop(Socket socket, FtpServer ftpServer) throws IOException { - this.incoming = socket; - this.ftpServer = ftpServer; - this.br = new BufferedReader(new InputStreamReader(incoming.getInputStream(), ftpServer.getCharset())); - this.pw = new PrintWriter(incoming.getOutputStream(), true); - } - - // http://www.ncftp.com/libncftp/doc/ftp_overview.html - // http://www.nsftools.com/tips/RawFTP.htm - // http://www.commentcamarche.net/contents/internet/ftp.php3 - // http://en.wikipedia.org/wiki/List_of_FTP_server_return_codes - // http://www.freefire.org/articles/ftpexample.php - // http://forum.hardware.fr/hfr/Programmation/VB-VBA-VBS/transfert-sujet_59989_1.htm - // http://www.excel-downloads.com/forum/104130-telechargement-ftp-via-vba.html - // http://www.pcreview.co.uk/forums/ftp-vba-macro-t949945.html - private void runInternal() throws IOException, InterruptedException { - localLog("Starting Loop"); - myOut("220 PlantUML"); - while (true) { - final String s = br.readLine(); - localLog("s=" + s); - if (s == null) { - pw.close(); - br.close(); - return; - } - final boolean finish = manage(s); - if (finish) { - return; - } - } - } - - private boolean manage(final String cmd) throws UnknownHostException, IOException, InterruptedException { - final String upper = cmd.toUpperCase(); - if (upper.startsWith("USER")) { - myOut("331 Password required"); - final String user = cmd.substring("USER ".length()); - connexion = ftpServer.getFtpConnexion(user); - } else if (upper.startsWith("PASS")) { - myOut("230 Logged in."); - } else if (upper.startsWith("PWD")) { - // myOut("/"); - // myOut("200 OK /"); - myOut("257 \"/\" is current directory."); - } else if (upper.startsWith("CWD")) { - final String dir = cmd.substring("CWD ".length()); - myOut("250 \"" + dir + "\" is new working directory.."); - } else if (upper.startsWith("TYPE")) { - myOut("200 Command okay."); - // localLog("type=" + s); - } else if (upper.startsWith("PORT")) { - mode = Mode.ACTIF; - final StringTokenizer st = new StringTokenizer(cmd, " ,"); - st.nextToken(); - ipClient = st.nextToken() + "." + st.nextToken() + "." + st.nextToken() + "." + st.nextToken(); - port = Integer.parseInt(st.nextToken()) * 256 + Integer.parseInt(st.nextToken()); - // localLog("ipClient=" + ipClient); - // localLog("port=" + port); - - myOut("200 Command okay."); - } else if (upper.startsWith("LIST")) { - if (mode == Mode.ACTIF) { - listActif(); - } else { - listPassif(); - } - } else if (upper.startsWith("STOR")) { - if (mode == Mode.ACTIF) { - storActif(cmd); - } else { - storPassif(cmd); - } - } else if (upper.startsWith("PASV")) { - mode = Mode.PASSIF; - port = ftpServer.getFreePort(); - final int p1 = port / 256; - final int p2 = port % 256; - assert port == p1 * 256 + p2; - localLog("adr=" + incoming.getInetAddress().getHostAddress()); - final String ipServer = ftpServer.getIpServer(); - localLog("server=" + ipServer); - myOut("227 Entering Passive Mode (" + ipServer.replace('.', ',') + "," + p1 + "," + p2 + ")."); - ipClient = ipServer; - } else if (upper.startsWith("RETR")) { - if (mode == Mode.ACTIF) { - retrActif(cmd); - } else { - retrPassif(cmd); - } - } else if (upper.startsWith("DELE")) { - final String file = cmd.substring("DELE ".length()); - connexion.delete(file); - myOut("200 Command okay."); - } else if (upper.startsWith("QUIT")) { - myOut("221 Goodbye."); - return true; - } else if (upper.startsWith("SYST")) { - myOut("215 UNIX Type: L8."); - } else { - myOut("502 Command not implemented."); - } - return false; - } - - private void localLog(String s) { - } - - private void retr(final String fileName, Socket soc) throws UnknownHostException, IOException, InterruptedException { - final OutputStream os = soc.getOutputStream(); - byte[] data = null; - do { - data = connexion.getData(fileName); - if (data.length == 0) { - Thread.sleep(200L); - } - } while (data.length == 0); - - os.write(data); - os.flush(); - os.close(); - soc.close(); - myOut("226 Transfer complete."); - } - - private void retrPassif(final String s) throws UnknownHostException, IOException, InterruptedException { - String fileName = s.substring("STOR ".length()); - fileName = removeStartingsSlash(fileName); - myOut("150 Opening"); - final ServerSocket ss = new ServerSocket(port); - final Socket incoming = ss.accept(); - retr(fileName, incoming); - ss.close(); - } - - private void retrActif(final String s) throws UnknownHostException, IOException, InterruptedException { - String fileName = s.substring("STOR ".length()); - fileName = removeStartingsSlash(fileName); - myOut("150 Opening"); - final Socket soc = new Socket(ipClient, port); - retr(fileName, soc); - } - - private void storActif(final String s) throws IOException { - final String fileName = removeStartingsSlash(s.substring("STOR ".length())); - myOut("150 FILE: " + fileName); - final Socket soc = new Socket(ipClient, port); - stor(fileName, soc); - } - - private void storPassif(final String s) throws IOException { - final String fileName = removeStartingsSlash(s.substring("STOR ".length())); - myOut("150 FILE: " + fileName); - final ServerSocket ss = new ServerSocket(port); - final Socket incoming = ss.accept(); - stor(fileName, incoming); - ss.close(); - } - - private String removeStartingsSlash(String fileName) { - while (fileName.startsWith("/")) { - fileName = fileName.substring(1); - } - return fileName; - } - - private void stor(String fileName, Socket socket) throws UnknownHostException, IOException { - final InputStream is = socket.getInputStream(); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - FileUtils.copyToStream(is, baos); - myOut("226 Transfer complete."); - final String data = new String(baos.toByteArray(), ftpServer.getCharset()); - final FileFormat format = FileFormat.PNG; - final String pngFileName = format.changeName(fileName, 0); - connexion.removeOutgoing(pngFileName); - connexion.addIncoming(fileName, data); - - ftpServer.processImage(connexion, fileName); - } - - private void listActif() throws UnknownHostException, IOException { - myOut("150 Opening ASCII mode data"); - final Socket soc = new Socket(ipClient, port); - list(soc); - } - - private void listPassif() throws UnknownHostException, IOException { - myOut("150 Opening ASCII mode data"); - final ServerSocket ss = new ServerSocket(port); - final Socket incoming = ss.accept(); - list(incoming); - ss.close(); - } - - private void list(final Socket soc) throws IOException { - final PrintWriter listing = new PrintWriter(soc.getOutputStream(), true); - final Collection files = connexion.getFiles(); - if (files.size() > 0) { - int total = 0; - for (String n : files) { - total += (connexion.getSize(n) + 511) / 512; - } - listing.println("total " + total); - // localLog(total); - for (String n : files) { - final String ls = String.format("%10s %4d %-8s %-8s %8d %3s %2s %5s %s", "-rw-rw-r--", 1, "plantuml", - "plantuml", connexion.getSize(n), "Sep", 28, 2006, n); - listing.println(ls); - // localLog(ls); - } - } - listing.flush(); - listing.close(); - soc.close(); - myOut("226 Listing completed."); - } - - private void myOut(String s) { - if (s.indexOf('\t') != -1) { - throw new IllegalArgumentException(); - } - pw.println(s); - pw.flush(); - } - - public void run() { - try { - runInternal(); - } catch (Throwable t) { - t.printStackTrace(); - } - - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/pair.info deleted file mode 100755 index 65c73b9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22258/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22258 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/ftp/FtpLoop.java -FixedFilePath:src/net/sourceforge/plantuml/ftp/FtpLoop.java -StartLineNum:104 -EndLineNum:104 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/diff.diff deleted file mode 100755 index 336b640..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/cucadiagram/Member.java b/src/net/sourceforge/plantuml/cucadiagram/Member.java -index f7e7e84d..f57a5541 100644 ---- a/src/net/sourceforge/plantuml/cucadiagram/Member.java -+++ b/src/net/sourceforge/plantuml/cucadiagram/Member.java -@@ -38,0 +39 @@ import java.util.regex.Pattern; -+import net.sourceforge.plantuml.StringUtils; -@@ -85 +86 @@ public class Member { -- final String lower = display.toLowerCase(); -+ final String lower = StringUtils.goLowerCase(display); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/new/Member.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/new/Member.java deleted file mode 100755 index f57a554..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/new/Member.java +++ /dev/null @@ -1,191 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4749 $ - * - */ -package net.sourceforge.plantuml.cucadiagram; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.Url; -import net.sourceforge.plantuml.UrlBuilder; -import net.sourceforge.plantuml.UrlBuilder.ModeUrl; -import net.sourceforge.plantuml.command.regex.MyPattern; -import net.sourceforge.plantuml.skin.VisibilityModifier; - -public class Member { - - private final String display; - private final boolean staticModifier; - private final boolean abstractModifier; - private final Url url; - private final boolean hasUrl; - - private final VisibilityModifier visibilityModifier; - - public Member(String display, boolean isMethod, boolean manageModifier) { - this.hasUrl = new UrlBuilder(null, ModeUrl.ANYWHERE).getUrl(display) != null; - final Pattern pstart = MyPattern.cmpile("^(" + UrlBuilder.getRegexp() + ")([^\\[\\]]+)$"); - final Matcher mstart = pstart.matcher(display); - - if (mstart.matches()) { - if (mstart.groupCount() != 5) { - throw new IllegalStateException(); - } - final UrlBuilder urlBuilder = new UrlBuilder(null, ModeUrl.AT_START); - url = urlBuilder.getUrl(mstart.group(1)); - url.setMember(true); - display = /* mstart.group(1).trim() + */mstart.group(mstart.groupCount()).trim(); - } else { - final Pattern pend = MyPattern.cmpile("^((?:[^\\[\\]]|\\[[^\\[\\]]*\\])+)(" + UrlBuilder.getRegexp() + ")$"); - final Matcher mend = pend.matcher(display); - - if (mend.matches()) { - if (mend.groupCount() != 5) { - throw new IllegalStateException(); - } - final UrlBuilder urlBuilder = new UrlBuilder(null, ModeUrl.AT_END); - url = urlBuilder.getUrl(mend.group(2)); - url.setMember(true); - display = mend.group(1).trim(); - } else { - url = null; - } - } - - final String lower = StringUtils.goLowerCase(display); - - if (manageModifier) { - this.staticModifier = lower.contains("{static}") || lower.contains("{classifier}"); - this.abstractModifier = lower.contains("{abstract}"); - String displayClean = display.replaceAll("(?i)\\{(static|classifier|abstract)\\}", "").trim(); - if (displayClean.length() == 0) { - displayClean = " "; - } - - if (VisibilityModifier.isVisibilityCharacter(displayClean.charAt(0))) { - visibilityModifier = VisibilityModifier.getVisibilityModifier(display.charAt(0), isMethod == false); - this.display = displayClean.substring(1).trim(); - } else { - this.display = displayClean; - visibilityModifier = null; - } - } else { - this.staticModifier = false; - this.visibilityModifier = null; - this.abstractModifier = false; - display = display.trim(); - this.display = display.length() == 0 ? " " : display.trim(); - } - } - - public String getDisplay(boolean withVisibilityChar) { - if (withVisibilityChar) { - return getDisplayWithVisibilityChar(); - } - return getDisplayWithoutVisibilityChar(); - } - - public String getDisplayWithoutVisibilityChar() { - // assert display.length() == 0 || VisibilityModifier.isVisibilityCharacter(display.charAt(0)) == false; - return display; - } - - public String getDisplayWithVisibilityChar() { - if (isPrivate()) { - return "-" + display; - } - if (isPublic()) { - return "+" + display; - } - if (isPackagePrivate()) { - return "~" + display; - } - if (isProtected()) { - return "#" + display; - } - return display; - } - - @Override - public boolean equals(Object obj) { - final Member other = (Member) obj; - return this.display.equals(other.display); - } - - @Override - public int hashCode() { - return display.hashCode(); - } - - public final boolean isStatic() { - return staticModifier; - } - - public final boolean isAbstract() { - return abstractModifier; - } - - private boolean isPrivate() { - return visibilityModifier == VisibilityModifier.PRIVATE_FIELD - || visibilityModifier == VisibilityModifier.PRIVATE_METHOD; - } - - private boolean isProtected() { - return visibilityModifier == VisibilityModifier.PROTECTED_FIELD - || visibilityModifier == VisibilityModifier.PROTECTED_METHOD; - } - - private boolean isPublic() { - return visibilityModifier == VisibilityModifier.PUBLIC_FIELD - || visibilityModifier == VisibilityModifier.PUBLIC_METHOD; - } - - private boolean isPackagePrivate() { - return visibilityModifier == VisibilityModifier.PACKAGE_PRIVATE_FIELD - || visibilityModifier == VisibilityModifier.PACKAGE_PRIVATE_METHOD; - } - - public final VisibilityModifier getVisibilityModifier() { - return visibilityModifier; - } - - public final Url getUrl() { - return url; - } - - public boolean hasUrl() { - return hasUrl; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/old/Member.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/old/Member.java deleted file mode 100755 index f7e7e84..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/old/Member.java +++ /dev/null @@ -1,190 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4749 $ - * - */ -package net.sourceforge.plantuml.cucadiagram; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sourceforge.plantuml.Url; -import net.sourceforge.plantuml.UrlBuilder; -import net.sourceforge.plantuml.UrlBuilder.ModeUrl; -import net.sourceforge.plantuml.command.regex.MyPattern; -import net.sourceforge.plantuml.skin.VisibilityModifier; - -public class Member { - - private final String display; - private final boolean staticModifier; - private final boolean abstractModifier; - private final Url url; - private final boolean hasUrl; - - private final VisibilityModifier visibilityModifier; - - public Member(String display, boolean isMethod, boolean manageModifier) { - this.hasUrl = new UrlBuilder(null, ModeUrl.ANYWHERE).getUrl(display) != null; - final Pattern pstart = MyPattern.cmpile("^(" + UrlBuilder.getRegexp() + ")([^\\[\\]]+)$"); - final Matcher mstart = pstart.matcher(display); - - if (mstart.matches()) { - if (mstart.groupCount() != 5) { - throw new IllegalStateException(); - } - final UrlBuilder urlBuilder = new UrlBuilder(null, ModeUrl.AT_START); - url = urlBuilder.getUrl(mstart.group(1)); - url.setMember(true); - display = /* mstart.group(1).trim() + */mstart.group(mstart.groupCount()).trim(); - } else { - final Pattern pend = MyPattern.cmpile("^((?:[^\\[\\]]|\\[[^\\[\\]]*\\])+)(" + UrlBuilder.getRegexp() + ")$"); - final Matcher mend = pend.matcher(display); - - if (mend.matches()) { - if (mend.groupCount() != 5) { - throw new IllegalStateException(); - } - final UrlBuilder urlBuilder = new UrlBuilder(null, ModeUrl.AT_END); - url = urlBuilder.getUrl(mend.group(2)); - url.setMember(true); - display = mend.group(1).trim(); - } else { - url = null; - } - } - - final String lower = display.toLowerCase(); - - if (manageModifier) { - this.staticModifier = lower.contains("{static}") || lower.contains("{classifier}"); - this.abstractModifier = lower.contains("{abstract}"); - String displayClean = display.replaceAll("(?i)\\{(static|classifier|abstract)\\}", "").trim(); - if (displayClean.length() == 0) { - displayClean = " "; - } - - if (VisibilityModifier.isVisibilityCharacter(displayClean.charAt(0))) { - visibilityModifier = VisibilityModifier.getVisibilityModifier(display.charAt(0), isMethod == false); - this.display = displayClean.substring(1).trim(); - } else { - this.display = displayClean; - visibilityModifier = null; - } - } else { - this.staticModifier = false; - this.visibilityModifier = null; - this.abstractModifier = false; - display = display.trim(); - this.display = display.length() == 0 ? " " : display.trim(); - } - } - - public String getDisplay(boolean withVisibilityChar) { - if (withVisibilityChar) { - return getDisplayWithVisibilityChar(); - } - return getDisplayWithoutVisibilityChar(); - } - - public String getDisplayWithoutVisibilityChar() { - // assert display.length() == 0 || VisibilityModifier.isVisibilityCharacter(display.charAt(0)) == false; - return display; - } - - public String getDisplayWithVisibilityChar() { - if (isPrivate()) { - return "-" + display; - } - if (isPublic()) { - return "+" + display; - } - if (isPackagePrivate()) { - return "~" + display; - } - if (isProtected()) { - return "#" + display; - } - return display; - } - - @Override - public boolean equals(Object obj) { - final Member other = (Member) obj; - return this.display.equals(other.display); - } - - @Override - public int hashCode() { - return display.hashCode(); - } - - public final boolean isStatic() { - return staticModifier; - } - - public final boolean isAbstract() { - return abstractModifier; - } - - private boolean isPrivate() { - return visibilityModifier == VisibilityModifier.PRIVATE_FIELD - || visibilityModifier == VisibilityModifier.PRIVATE_METHOD; - } - - private boolean isProtected() { - return visibilityModifier == VisibilityModifier.PROTECTED_FIELD - || visibilityModifier == VisibilityModifier.PROTECTED_METHOD; - } - - private boolean isPublic() { - return visibilityModifier == VisibilityModifier.PUBLIC_FIELD - || visibilityModifier == VisibilityModifier.PUBLIC_METHOD; - } - - private boolean isPackagePrivate() { - return visibilityModifier == VisibilityModifier.PACKAGE_PRIVATE_FIELD - || visibilityModifier == VisibilityModifier.PACKAGE_PRIVATE_METHOD; - } - - public final VisibilityModifier getVisibilityModifier() { - return visibilityModifier; - } - - public final Url getUrl() { - return url; - } - - public boolean hasUrl() { - return hasUrl; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/pair.info deleted file mode 100755 index ac3f4a9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22261/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22261 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/cucadiagram/Member.java -FixedFilePath:src/net/sourceforge/plantuml/cucadiagram/Member.java -StartLineNum:85 -EndLineNum:85 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/diff.diff deleted file mode 100755 index 1445554..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/Option.java b/src/net/sourceforge/plantuml/Option.java -index 33982587..3800a090 100644 ---- a/src/net/sourceforge/plantuml/Option.java -+++ b/src/net/sourceforge/plantuml/Option.java -@@ -31 +31 @@ -- * Revision $Revision: 14321 $ -+ * Revision $Revision: 14727 $ -@@ -243 +243 @@ public class Option { -- } else if (s.toLowerCase().startsWith("-ftp")) { -+ } else if (StringUtils.goLowerCase(s).startsWith("-ftp")) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/new/Option.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/new/Option.java deleted file mode 100755 index 3800a09..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/new/Option.java +++ /dev/null @@ -1,415 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14727 $ - * - */ -package net.sourceforge.plantuml; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sourceforge.plantuml.command.regex.MyPattern; -import net.sourceforge.plantuml.preproc.Defines; - -public class Option { - - private final List excludes = new ArrayList(); - private final List config = new ArrayList(); - private final Map defines = new LinkedHashMap(); - private String charset; - private boolean computeurl = false; - private boolean decodeurl = false; - private boolean pipe = false; - private boolean syntax = false; - private boolean checkOnly = false; - private boolean failfast = false; - private boolean failfast2 = false; - private boolean pattern = false; - private boolean duration = false; - private int nbThreads = 0; - private int ftpPort = -1; - - private File outputDir = null; - private File outputFile = null; - - private final List result = new ArrayList(); - - public Option() { - } - - private FileFormat fileFormat = FileFormat.PNG; - - public FileFormat getFileFormat() { - return fileFormat; - } - - public void setFileFormat(FileFormat fileFormat) { - this.fileFormat = fileFormat; - } - - public Option(String... arg) throws InterruptedException, IOException { - if (arg.length == 0) { - OptionFlags.getInstance().setGui(true); - } - for (int i = 0; i < arg.length; i++) { - String s = arg[i]; - if (s.equalsIgnoreCase("-tsvg") || s.equalsIgnoreCase("-svg")) { - setFileFormat(FileFormat.SVG); - } else if (s.equalsIgnoreCase("-thtml") || s.equalsIgnoreCase("-html")) { - setFileFormat(FileFormat.HTML); - } else if (s.equalsIgnoreCase("-txmi") || s.equalsIgnoreCase("-xmi")) { - setFileFormat(FileFormat.XMI_STANDARD); - } else if (s.equalsIgnoreCase("-txmi:argo") || s.equalsIgnoreCase("-xmi:argo")) { - setFileFormat(FileFormat.XMI_ARGO); - } else if (s.equalsIgnoreCase("-txmi:star") || s.equalsIgnoreCase("-xmi:star")) { - setFileFormat(FileFormat.XMI_STAR); - } else if (s.equalsIgnoreCase("-teps") || s.equalsIgnoreCase("-eps")) { - setFileFormat(FileFormat.EPS); - } else if (s.equalsIgnoreCase("-teps:text") || s.equalsIgnoreCase("-eps:text")) { - setFileFormat(FileFormat.EPS_TEXT); - } else if (s.equalsIgnoreCase("-ttxt") || s.equalsIgnoreCase("-txt")) { - setFileFormat(FileFormat.ATXT); - } else if (s.equalsIgnoreCase("-tutxt") || s.equalsIgnoreCase("-utxt")) { - setFileFormat(FileFormat.UTXT); - } else if (s.equalsIgnoreCase("-png") || s.equalsIgnoreCase("-tpng")) { - setFileFormat(FileFormat.PNG); - } else if (s.equalsIgnoreCase("-vdx") || s.equalsIgnoreCase("-tvdx")) { - setFileFormat(FileFormat.VDX); - } else if (s.equalsIgnoreCase("-latex") || s.equalsIgnoreCase("-tlatex")) { - setFileFormat(FileFormat.LATEX); - } else if (s.equalsIgnoreCase("-base64") || s.equalsIgnoreCase("-tbase64")) { - setFileFormat(FileFormat.BASE64); - } else if (s.equalsIgnoreCase("-pdf") || s.equalsIgnoreCase("-tpdf")) { - setFileFormat(FileFormat.PDF); - } else if (s.equalsIgnoreCase("-overwrite")) { - OptionFlags.getInstance().setOverwrite(true); - } else if (s.equalsIgnoreCase("-output") || s.equalsIgnoreCase("-o")) { - i++; - if (i == arg.length) { - continue; - } - outputDir = new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-ofile")) { - i++; - if (i == arg.length) { - continue; - } - outputFile = new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-graphvizdot") || s.equalsIgnoreCase("-graphviz_dot")) { - i++; - if (i == arg.length) { - continue; - } - OptionFlags.getInstance().setDotExecutable( - StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-charset")) { - i++; - if (i == arg.length) { - continue; - } - charset = StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i]); - } else if (s.startsWith("-o") && s.length() > 3) { - s = s.substring(2); - outputDir = new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(s)); - } else if (s.equalsIgnoreCase("-recurse") || s.equalsIgnoreCase("-r")) { - // recurse = true; - } else if (s.equalsIgnoreCase("-exclude") || s.equalsIgnoreCase("-x")) { - i++; - if (i == arg.length) { - continue; - } - excludes.add(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-nbthread") || s.equalsIgnoreCase("-nbthreads")) { - i++; - if (i == arg.length) { - continue; - } - final String nb = arg[i]; - if ("auto".equalsIgnoreCase(nb)) { - this.nbThreads = defaultNbThreads(); - } else if (nb.matches("\\d+")) { - this.nbThreads = Integer.parseInt(nb); - } - } else if (s.equalsIgnoreCase("-failfast")) { - this.failfast = true; - } else if (s.equalsIgnoreCase("-failfast2")) { - this.failfast2 = true; - } else if (s.equalsIgnoreCase("-checkonly")) { - this.checkOnly = true; - } else if (s.equalsIgnoreCase("-config")) { - i++; - if (i == arg.length) { - continue; - } - initConfig(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-computeurl") || s.equalsIgnoreCase("-encodeurl")) { - this.computeurl = true; - } else if (s.startsWith("-x")) { - s = s.substring(2); - excludes.add(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(s)); - } else if (s.equalsIgnoreCase("-verbose") || s.equalsIgnoreCase("-v")) { - OptionFlags.getInstance().setVerbose(true); - } else if (s.equalsIgnoreCase("-pipe") || s.equalsIgnoreCase("-p")) { - pipe = true; - } else if (s.equalsIgnoreCase("-pattern")) { - pattern = true; - } else if (s.equalsIgnoreCase("-syntax")) { - syntax = true; - OptionFlags.getInstance().setQuiet(true); - } else if (s.equalsIgnoreCase("-duration")) { - duration = true; - } else if (s.equalsIgnoreCase("-keepfiles") || s.equalsIgnoreCase("-keepfile")) { - OptionFlags.getInstance().setKeepTmpFiles(true); - } else if (s.equalsIgnoreCase("-metadata")) { - OptionFlags.getInstance().setMetadata(true); - } else if (s.equalsIgnoreCase("-logdata")) { - i++; - if (i == arg.length) { - continue; - } - OptionFlags.getInstance().setLogData( - new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i]))); - } else if (s.equalsIgnoreCase("-word")) { - OptionFlags.getInstance().setWord(true); - OptionFlags.getInstance().setQuiet(true); - } else if (s.equalsIgnoreCase("-quiet")) { - OptionFlags.getInstance().setQuiet(true); - } else if (s.equalsIgnoreCase("-decodeurl")) { - this.decodeurl = true; - } else if (s.equalsIgnoreCase("-version")) { - OptionPrint.printVersion(); - } else if (s.matches("(?i)^-li[sc][ea]n[sc]e\\s*$")) { - OptionPrint.printLicense(); - } else if (s.equalsIgnoreCase("-checkversion")) { - OptionPrint.checkVersion(); - } else if (s.startsWith("-D")) { - manageDefine(s.substring(2)); - } else if (s.startsWith("-S")) { - manageSkinParam(s.substring(2)); - } else if (s.equalsIgnoreCase("-testdot")) { - OptionPrint.printTestDot(); - } else if (s.equalsIgnoreCase("-about") || s.equalsIgnoreCase("-author") || s.equalsIgnoreCase("-authors")) { - OptionPrint.printAbout(); - } else if (s.equalsIgnoreCase("-help") || s.equalsIgnoreCase("-h") || s.equalsIgnoreCase("-?")) { - OptionPrint.printHelp(); - } else if (s.equalsIgnoreCase("-language")) { - OptionPrint.printLanguage(); - } else if (s.equalsIgnoreCase("-gui")) { - OptionFlags.getInstance().setGui(true); - } else if (s.equalsIgnoreCase("-encodesprite")) { - OptionFlags.getInstance().setEncodesprite(true); - } else if (s.equalsIgnoreCase("-nosuggestengine")) { - OptionFlags.getInstance().setUseSuggestEngine(false); - } else if (s.equalsIgnoreCase("-printfonts")) { - OptionFlags.getInstance().setPrintFonts(true); - } else if (StringUtils.goLowerCase(s).startsWith("-ftp")) { - final int x = s.indexOf(':'); - if (x == -1) { - this.ftpPort = 4242; - } else { - this.ftpPort = Integer.parseInt(s.substring(x + 1)); - } - } else if (s.startsWith("-c")) { - s = s.substring(2); - config.add(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(s)); - } else { - result.add(s); - } - } - } - - public int getFtpPort() { - return ftpPort; - } - - public void initConfig(String filename) throws IOException { - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(filename)); - String s = null; - while ((s = br.readLine()) != null) { - config.add(s); - } - } finally { - if (br != null) { - br.close(); - } - } - } - - private void manageDefine(String s) { - final Pattern p = MyPattern.cmpile("^(\\w+)(?:=(.*))?$"); - final Matcher m = p.matcher(s); - if (m.find()) { - define(m.group(1), m.group(2)); - } - } - - private void manageSkinParam(String s) { - final Pattern p = MyPattern.cmpile("^(\\w+)(?:=(.*))?$"); - final Matcher m = p.matcher(s); - if (m.find()) { - skinParam(m.group(1), m.group(2)); - } - } - - private void skinParam(String var, String value) { - if (var != null && value != null) { - config.add("skinparamlocked " + var + " " + value); - } - - } - - public final File getOutputDir() { - return outputDir; - } - - public final static String getPattern() { - return "(?i)^.*\\.(txt|tex|java|htm|html|c|h|cpp|apt|pu)$"; - } - - public void setOutputDir(File f) { - outputDir = f; - } - - public final List getExcludes() { - return Collections.unmodifiableList(excludes); - } - - public Defines getDefaultDefines() { - final Defines result = new Defines(); - for (Map.Entry ent : defines.entrySet()) { - result.define(ent.getKey(), Arrays.asList(ent.getValue())); - - } - return result; - } - - public void define(String name, String value) { - defines.put(name, value); - } - - public List getConfig() { - return Collections.unmodifiableList(config); - } - - public final List getResult() { - return Collections.unmodifiableList(result); - } - - public final String getCharset() { - return charset; - } - - public void setCharset(String s) { - this.charset = s; - - } - - public final boolean isComputeurl() { - return computeurl; - } - - public final boolean isDecodeurl() { - return decodeurl; - } - - public final boolean isPipe() { - return pipe; - } - - public final boolean isSyntax() { - return syntax; - } - - public final boolean isPattern() { - return pattern; - } - - public FileFormatOption getFileFormatOption() { - return new FileFormatOption(getFileFormat()); - } - - public final boolean isDuration() { - return duration; - } - - public final int getNbThreads() { - return nbThreads; - } - - public final void setNbThreads(int nb) { - this.nbThreads = nb; - } - - public static int defaultNbThreads() { - return Runtime.getRuntime().availableProcessors(); - } - - public final boolean isCheckOnly() { - return checkOnly; - } - - public final void setCheckOnly(boolean checkOnly) { - this.checkOnly = checkOnly; - } - - public final boolean isFailfastOrFailfast2() { - return failfast || failfast2; - } - - public final boolean isFailfast2() { - return failfast2; - } - - public final void setFailfast(boolean failfast) { - this.failfast = failfast; - } - - public final void setFailfast2(boolean failfast2) { - this.failfast2 = failfast2; - } - - public final File getOutputFile() { - return outputFile; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/old/Option.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/old/Option.java deleted file mode 100755 index 3398258..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/old/Option.java +++ /dev/null @@ -1,415 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14321 $ - * - */ -package net.sourceforge.plantuml; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sourceforge.plantuml.command.regex.MyPattern; -import net.sourceforge.plantuml.preproc.Defines; - -public class Option { - - private final List excludes = new ArrayList(); - private final List config = new ArrayList(); - private final Map defines = new LinkedHashMap(); - private String charset; - private boolean computeurl = false; - private boolean decodeurl = false; - private boolean pipe = false; - private boolean syntax = false; - private boolean checkOnly = false; - private boolean failfast = false; - private boolean failfast2 = false; - private boolean pattern = false; - private boolean duration = false; - private int nbThreads = 0; - private int ftpPort = -1; - - private File outputDir = null; - private File outputFile = null; - - private final List result = new ArrayList(); - - public Option() { - } - - private FileFormat fileFormat = FileFormat.PNG; - - public FileFormat getFileFormat() { - return fileFormat; - } - - public void setFileFormat(FileFormat fileFormat) { - this.fileFormat = fileFormat; - } - - public Option(String... arg) throws InterruptedException, IOException { - if (arg.length == 0) { - OptionFlags.getInstance().setGui(true); - } - for (int i = 0; i < arg.length; i++) { - String s = arg[i]; - if (s.equalsIgnoreCase("-tsvg") || s.equalsIgnoreCase("-svg")) { - setFileFormat(FileFormat.SVG); - } else if (s.equalsIgnoreCase("-thtml") || s.equalsIgnoreCase("-html")) { - setFileFormat(FileFormat.HTML); - } else if (s.equalsIgnoreCase("-txmi") || s.equalsIgnoreCase("-xmi")) { - setFileFormat(FileFormat.XMI_STANDARD); - } else if (s.equalsIgnoreCase("-txmi:argo") || s.equalsIgnoreCase("-xmi:argo")) { - setFileFormat(FileFormat.XMI_ARGO); - } else if (s.equalsIgnoreCase("-txmi:star") || s.equalsIgnoreCase("-xmi:star")) { - setFileFormat(FileFormat.XMI_STAR); - } else if (s.equalsIgnoreCase("-teps") || s.equalsIgnoreCase("-eps")) { - setFileFormat(FileFormat.EPS); - } else if (s.equalsIgnoreCase("-teps:text") || s.equalsIgnoreCase("-eps:text")) { - setFileFormat(FileFormat.EPS_TEXT); - } else if (s.equalsIgnoreCase("-ttxt") || s.equalsIgnoreCase("-txt")) { - setFileFormat(FileFormat.ATXT); - } else if (s.equalsIgnoreCase("-tutxt") || s.equalsIgnoreCase("-utxt")) { - setFileFormat(FileFormat.UTXT); - } else if (s.equalsIgnoreCase("-png") || s.equalsIgnoreCase("-tpng")) { - setFileFormat(FileFormat.PNG); - } else if (s.equalsIgnoreCase("-vdx") || s.equalsIgnoreCase("-tvdx")) { - setFileFormat(FileFormat.VDX); - } else if (s.equalsIgnoreCase("-latex") || s.equalsIgnoreCase("-tlatex")) { - setFileFormat(FileFormat.LATEX); - } else if (s.equalsIgnoreCase("-base64") || s.equalsIgnoreCase("-tbase64")) { - setFileFormat(FileFormat.BASE64); - } else if (s.equalsIgnoreCase("-pdf") || s.equalsIgnoreCase("-tpdf")) { - setFileFormat(FileFormat.PDF); - } else if (s.equalsIgnoreCase("-overwrite")) { - OptionFlags.getInstance().setOverwrite(true); - } else if (s.equalsIgnoreCase("-output") || s.equalsIgnoreCase("-o")) { - i++; - if (i == arg.length) { - continue; - } - outputDir = new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-ofile")) { - i++; - if (i == arg.length) { - continue; - } - outputFile = new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-graphvizdot") || s.equalsIgnoreCase("-graphviz_dot")) { - i++; - if (i == arg.length) { - continue; - } - OptionFlags.getInstance().setDotExecutable( - StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-charset")) { - i++; - if (i == arg.length) { - continue; - } - charset = StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i]); - } else if (s.startsWith("-o") && s.length() > 3) { - s = s.substring(2); - outputDir = new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(s)); - } else if (s.equalsIgnoreCase("-recurse") || s.equalsIgnoreCase("-r")) { - // recurse = true; - } else if (s.equalsIgnoreCase("-exclude") || s.equalsIgnoreCase("-x")) { - i++; - if (i == arg.length) { - continue; - } - excludes.add(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-nbthread") || s.equalsIgnoreCase("-nbthreads")) { - i++; - if (i == arg.length) { - continue; - } - final String nb = arg[i]; - if ("auto".equalsIgnoreCase(nb)) { - this.nbThreads = defaultNbThreads(); - } else if (nb.matches("\\d+")) { - this.nbThreads = Integer.parseInt(nb); - } - } else if (s.equalsIgnoreCase("-failfast")) { - this.failfast = true; - } else if (s.equalsIgnoreCase("-failfast2")) { - this.failfast2 = true; - } else if (s.equalsIgnoreCase("-checkonly")) { - this.checkOnly = true; - } else if (s.equalsIgnoreCase("-config")) { - i++; - if (i == arg.length) { - continue; - } - initConfig(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i])); - } else if (s.equalsIgnoreCase("-computeurl") || s.equalsIgnoreCase("-encodeurl")) { - this.computeurl = true; - } else if (s.startsWith("-x")) { - s = s.substring(2); - excludes.add(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(s)); - } else if (s.equalsIgnoreCase("-verbose") || s.equalsIgnoreCase("-v")) { - OptionFlags.getInstance().setVerbose(true); - } else if (s.equalsIgnoreCase("-pipe") || s.equalsIgnoreCase("-p")) { - pipe = true; - } else if (s.equalsIgnoreCase("-pattern")) { - pattern = true; - } else if (s.equalsIgnoreCase("-syntax")) { - syntax = true; - OptionFlags.getInstance().setQuiet(true); - } else if (s.equalsIgnoreCase("-duration")) { - duration = true; - } else if (s.equalsIgnoreCase("-keepfiles") || s.equalsIgnoreCase("-keepfile")) { - OptionFlags.getInstance().setKeepTmpFiles(true); - } else if (s.equalsIgnoreCase("-metadata")) { - OptionFlags.getInstance().setMetadata(true); - } else if (s.equalsIgnoreCase("-logdata")) { - i++; - if (i == arg.length) { - continue; - } - OptionFlags.getInstance().setLogData( - new File(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(arg[i]))); - } else if (s.equalsIgnoreCase("-word")) { - OptionFlags.getInstance().setWord(true); - OptionFlags.getInstance().setQuiet(true); - } else if (s.equalsIgnoreCase("-quiet")) { - OptionFlags.getInstance().setQuiet(true); - } else if (s.equalsIgnoreCase("-decodeurl")) { - this.decodeurl = true; - } else if (s.equalsIgnoreCase("-version")) { - OptionPrint.printVersion(); - } else if (s.matches("(?i)^-li[sc][ea]n[sc]e\\s*$")) { - OptionPrint.printLicense(); - } else if (s.equalsIgnoreCase("-checkversion")) { - OptionPrint.checkVersion(); - } else if (s.startsWith("-D")) { - manageDefine(s.substring(2)); - } else if (s.startsWith("-S")) { - manageSkinParam(s.substring(2)); - } else if (s.equalsIgnoreCase("-testdot")) { - OptionPrint.printTestDot(); - } else if (s.equalsIgnoreCase("-about") || s.equalsIgnoreCase("-author") || s.equalsIgnoreCase("-authors")) { - OptionPrint.printAbout(); - } else if (s.equalsIgnoreCase("-help") || s.equalsIgnoreCase("-h") || s.equalsIgnoreCase("-?")) { - OptionPrint.printHelp(); - } else if (s.equalsIgnoreCase("-language")) { - OptionPrint.printLanguage(); - } else if (s.equalsIgnoreCase("-gui")) { - OptionFlags.getInstance().setGui(true); - } else if (s.equalsIgnoreCase("-encodesprite")) { - OptionFlags.getInstance().setEncodesprite(true); - } else if (s.equalsIgnoreCase("-nosuggestengine")) { - OptionFlags.getInstance().setUseSuggestEngine(false); - } else if (s.equalsIgnoreCase("-printfonts")) { - OptionFlags.getInstance().setPrintFonts(true); - } else if (s.toLowerCase().startsWith("-ftp")) { - final int x = s.indexOf(':'); - if (x == -1) { - this.ftpPort = 4242; - } else { - this.ftpPort = Integer.parseInt(s.substring(x + 1)); - } - } else if (s.startsWith("-c")) { - s = s.substring(2); - config.add(StringUtils.eventuallyRemoveStartingAndEndingDoubleQuote(s)); - } else { - result.add(s); - } - } - } - - public int getFtpPort() { - return ftpPort; - } - - public void initConfig(String filename) throws IOException { - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(filename)); - String s = null; - while ((s = br.readLine()) != null) { - config.add(s); - } - } finally { - if (br != null) { - br.close(); - } - } - } - - private void manageDefine(String s) { - final Pattern p = MyPattern.cmpile("^(\\w+)(?:=(.*))?$"); - final Matcher m = p.matcher(s); - if (m.find()) { - define(m.group(1), m.group(2)); - } - } - - private void manageSkinParam(String s) { - final Pattern p = MyPattern.cmpile("^(\\w+)(?:=(.*))?$"); - final Matcher m = p.matcher(s); - if (m.find()) { - skinParam(m.group(1), m.group(2)); - } - } - - private void skinParam(String var, String value) { - if (var != null && value != null) { - config.add("skinparamlocked " + var + " " + value); - } - - } - - public final File getOutputDir() { - return outputDir; - } - - public final static String getPattern() { - return "(?i)^.*\\.(txt|tex|java|htm|html|c|h|cpp|apt|pu)$"; - } - - public void setOutputDir(File f) { - outputDir = f; - } - - public final List getExcludes() { - return Collections.unmodifiableList(excludes); - } - - public Defines getDefaultDefines() { - final Defines result = new Defines(); - for (Map.Entry ent : defines.entrySet()) { - result.define(ent.getKey(), Arrays.asList(ent.getValue())); - - } - return result; - } - - public void define(String name, String value) { - defines.put(name, value); - } - - public List getConfig() { - return Collections.unmodifiableList(config); - } - - public final List getResult() { - return Collections.unmodifiableList(result); - } - - public final String getCharset() { - return charset; - } - - public void setCharset(String s) { - this.charset = s; - - } - - public final boolean isComputeurl() { - return computeurl; - } - - public final boolean isDecodeurl() { - return decodeurl; - } - - public final boolean isPipe() { - return pipe; - } - - public final boolean isSyntax() { - return syntax; - } - - public final boolean isPattern() { - return pattern; - } - - public FileFormatOption getFileFormatOption() { - return new FileFormatOption(getFileFormat()); - } - - public final boolean isDuration() { - return duration; - } - - public final int getNbThreads() { - return nbThreads; - } - - public final void setNbThreads(int nb) { - this.nbThreads = nb; - } - - public static int defaultNbThreads() { - return Runtime.getRuntime().availableProcessors(); - } - - public final boolean isCheckOnly() { - return checkOnly; - } - - public final void setCheckOnly(boolean checkOnly) { - this.checkOnly = checkOnly; - } - - public final boolean isFailfastOrFailfast2() { - return failfast || failfast2; - } - - public final boolean isFailfast2() { - return failfast2; - } - - public final void setFailfast(boolean failfast) { - this.failfast = failfast; - } - - public final void setFailfast2(boolean failfast2) { - this.failfast2 = failfast2; - } - - public final File getOutputFile() { - return outputFile; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/pair.info deleted file mode 100755 index cdefa5b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22267/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22267 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/Option.java -FixedFilePath:src/net/sourceforge/plantuml/Option.java -StartLineNum:243 -EndLineNum:243 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22283/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22283/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22283/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22283/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22283/diff.diff deleted file mode 100755 index 85c6254..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22283/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/sequencediagram/command/CommandGrouping.java b/src/net/sourceforge/plantuml/sequencediagram/command/CommandGrouping.java -index 39c29e77..61769e2c 100644 ---- a/src/net/sourceforge/plantuml/sequencediagram/command/CommandGrouping.java -+++ b/src/net/sourceforge/plantuml/sequencediagram/command/CommandGrouping.java -@@ -31 +31 @@ -- * Revision $Revision: 14321 $ -+ * Revision $Revision: 14727 $ -@@ -66 +66 @@ public class CommandGrouping extends SingleLineCommand2 { -- String type = arg.get("TYPE", 0).toLowerCase(); -+ String type = StringUtils.goLowerCase(arg.get("TYPE", 0)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22283/new/CommandGrouping.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22283/new/CommandGrouping.java deleted file mode 100755 index 61769e2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22283/new/CommandGrouping.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14727 $ - * - */ -package net.sourceforge.plantuml.sequencediagram.command; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.graphic.HtmlColor; -import net.sourceforge.plantuml.sequencediagram.GroupingType; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagram; -import net.sourceforge.plantuml.StringUtils; - -public class CommandGrouping extends SingleLineCommand2 { - - public CommandGrouping() { - super(getRegexConcat()); - } - - static RegexConcat getRegexConcat() { - return new RegexConcat(// - new RegexLeaf("^"), // - new RegexLeaf("TYPE", "(opt|alt|loop|par|par2|break|critical|else|end|also|group)"), // - new RegexLeaf("COLORS", "((? { - - public CommandGrouping() { - super(getRegexConcat()); - } - - static RegexConcat getRegexConcat() { - return new RegexConcat(// - new RegexLeaf("^"), // - new RegexLeaf("TYPE", "(opt|alt|loop|par|par2|break|critical|else|end|also|group)"), // - new RegexLeaf("COLORS", "((? encode(BufferedImage img) { - if (this == GRAY_16) { - return encode16(img); - } - if (this == GRAY_8) { - return encode8(img); - } - if (this == GRAY_4) { - return encode4(img); - } - throw new UnsupportedOperationException(); - } - - private List encode16(BufferedImage img) { - final int width = img.getWidth(); - final int height = img.getHeight(); - // final int type = img.getType(); - - final List result = new ArrayList(); - - for (int y = 0; y < height; y++) { - final StringBuilder sb = new StringBuilder(); - for (int x = 0; x < width; x++) { - final int level = getGrayOn16(img, x, y); - final char code = "0123456789ABCDEF".charAt(level); - sb.append(code); - } - result.add(sb.toString()); - } - return Collections.unmodifiableList(result); - } - - private List encode8(BufferedImage img) { - final int width = img.getWidth(); - final int height = img.getHeight(); - // final int type = img.getType(); - - final List result = new ArrayList(); - final AsciiEncoder encoder = new AsciiEncoder(); - - for (int y = 0; y < height; y += 2) { - final StringBuilder sb = new StringBuilder(); - for (int x = 0; x < width; x++) { - final int level1 = getGrayOn16(img, x, y) / 2; - assert level1 >= 0 && level1 <= 7; - final int level2 = getGrayOn16(img, x, y + 1) / 2; - assert level2 >= 0 && level2 <= 7; - final int v = level1 * 8 + level2; - sb.append(encoder.encode6bit((byte) v)); - } - result.add(sb.toString()); - } - return Collections.unmodifiableList(result); - } - - private List encode4(BufferedImage img) { - final int width = img.getWidth(); - final int height = img.getHeight(); - // final int type = img.getType(); - - final List result = new ArrayList(); - final AsciiEncoder encoder = new AsciiEncoder(); - - for (int y = 0; y < height; y += 3) { - final StringBuilder sb = new StringBuilder(); - for (int x = 0; x < width; x++) { - final int level1 = getGrayOn16(img, x, y) / 4; - assert level1 >= 0 && level1 <= 3; - final int level2 = getGrayOn16(img, x, y + 1) / 4; - assert level2 >= 0 && level2 <= 3; - final int level3 = getGrayOn16(img, x, y + 2) / 4; - assert level3 >= 0 && level3 <= 3; - final int v = level1 * 16 + level2 * 4 + level3; - sb.append(encoder.encode6bit((byte) v)); - } - result.add(sb.toString()); - } - return Collections.unmodifiableList(result); - } - - private int getGrayOn16(BufferedImage img, int x, int y) { - if (x >= img.getWidth()) { - return 0; - } - if (y >= img.getHeight()) { - return 0; - } - final Color g = mono.getChangedColor(new Color(img.getRGB(x, y))); - final int grey = 255 - g.getRed(); - return grey / 16; - } - - public Sprite buildSprite(int width, int height, List strings) { - if (this == SpriteGrayLevel.GRAY_16) { - return buildSprite16(strings); - } - if (this == SpriteGrayLevel.GRAY_8) { - return buildSprite8(width, height, strings); - } - if (this == SpriteGrayLevel.GRAY_4) { - return buildSprite4(width, height, strings); - } - throw new UnsupportedOperationException(toString()); - } - - private Sprite buildSprite16(List strings) { - final SpriteMonochrome result = new SpriteMonochrome(strings.get(0).length(), strings.size(), 16); - for (int col = 0; col < result.getWidth(); col++) { - for (int line = 0; line < result.getHeight(); line++) { - if (col >= strings.get(line).length()) { - continue; - } - if (strings.get(line).charAt(col) != '0') { - final String s = "" + strings.get(line).charAt(col); - final int x = Integer.parseInt(StringUtils.goUpperCase(s), 16); - result.setPixel(col, line, x); - } - } - } - return result; - } - - private Sprite buildSprite8(int width, int height, List strings) { - final AsciiEncoder encoder = new AsciiEncoder(); - final SpriteMonochrome result = new SpriteMonochrome(width, height, 8); - for (int col = 0; col < result.getWidth(); col++) { - for (int line = 0; line < strings.size(); line++) { - if (col >= strings.get(line).length()) { - continue; - } - final int v = encoder.decode6bit(strings.get(line).charAt(col)); - final int w1 = v / 8; - final int w2 = v % 8; - result.setPixel(col, line * 2, w1); - result.setPixel(col, line * 2 + 1, w2); - - } - } - return result; - } - - private Sprite buildSprite4(int width, int height, List strings) { - final AsciiEncoder encoder = new AsciiEncoder(); - final SpriteMonochrome result = new SpriteMonochrome(width, height, 4); - for (int col = 0; col < result.getWidth(); col++) { - for (int line = 0; line < strings.size(); line++) { - if (col >= strings.get(line).length()) { - continue; - } - int v = encoder.decode6bit(strings.get(line).charAt(col)); - final int w1 = v / 16; - v = v % 16; - final int w2 = v / 4; - final int w3 = v % 4; - result.setPixel(col, line * 3, w1); - result.setPixel(col, line * 3 + 1, w2); - result.setPixel(col, line * 3 + 2, w3); - - } - } - return result; - } - - public List encodeZ(BufferedImage img) { - final int width = img.getWidth(); - final int height = img.getHeight(); - final byte raw[] = new byte[width * height]; - final BufferedImage grayImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - int cpt = 0; - final int coef = 16 / nbColor; - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - final int color = getGrayOn16(img, x, y) / coef; - raw[cpt++] = (byte) color; - grayImg.setRGB(x, y, color * coef); - } - } - final byte[] comp = new CompressionZlib().compress(raw); - return cut(new AsciiEncoder().encode(comp)); - } - - private List cut(String s) { - final List result = new ArrayList(); - for (int i = 0; i < s.length(); i += 120) { - final int j = Math.min(i + 120, s.length()); - result.add(s.substring(i, j)); - - } - return Collections.unmodifiableList(result); - } - - public Sprite buildSpriteZ(int width, int height, String compressed) throws IOException { - final byte comp[] = new AsciiEncoder().decode(compressed); - final byte img[] = new CompressionZlib().decompress(comp); - final SpriteMonochrome result = new SpriteMonochrome(width, height, nbColor); - int cpt = 0; - for (int line = 0; line < result.getHeight(); line++) { - for (int col = 0; col < result.getWidth(); col++) { - result.setPixel(col, line, img[cpt++]); - - } - } - return result; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22291/old/SpriteGrayLevel.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22291/old/SpriteGrayLevel.java deleted file mode 100755 index 8fc32f3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22291/old/SpriteGrayLevel.java +++ /dev/null @@ -1,279 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3837 $ - * - */ -package net.sourceforge.plantuml.ugraphic; - -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sourceforge.plantuml.code.AsciiEncoder; -import net.sourceforge.plantuml.code.CompressionZlib; - -public enum SpriteGrayLevel { - - GRAY_16(16), GRAY_8(8), GRAY_4(4); - - private final int nbColor; - private static final ColorChangerMonochrome mono = new ColorChangerMonochrome(); - - private SpriteGrayLevel(int nbColor) { - this.nbColor = nbColor; - } - - public static SpriteGrayLevel get(int n) { - if (n == 4) { - return SpriteGrayLevel.GRAY_4; - } - if (n == 8) { - return SpriteGrayLevel.GRAY_8; - } - if (n == 16) { - return SpriteGrayLevel.GRAY_16; - } - throw new UnsupportedOperationException(); - } - - public int getNbColor() { - return nbColor; - } - - public List encode(BufferedImage img) { - if (this == GRAY_16) { - return encode16(img); - } - if (this == GRAY_8) { - return encode8(img); - } - if (this == GRAY_4) { - return encode4(img); - } - throw new UnsupportedOperationException(); - } - - private List encode16(BufferedImage img) { - final int width = img.getWidth(); - final int height = img.getHeight(); - // final int type = img.getType(); - - final List result = new ArrayList(); - - for (int y = 0; y < height; y++) { - final StringBuilder sb = new StringBuilder(); - for (int x = 0; x < width; x++) { - final int level = getGrayOn16(img, x, y); - final char code = "0123456789ABCDEF".charAt(level); - sb.append(code); - } - result.add(sb.toString()); - } - return Collections.unmodifiableList(result); - } - - private List encode8(BufferedImage img) { - final int width = img.getWidth(); - final int height = img.getHeight(); - // final int type = img.getType(); - - final List result = new ArrayList(); - final AsciiEncoder encoder = new AsciiEncoder(); - - for (int y = 0; y < height; y += 2) { - final StringBuilder sb = new StringBuilder(); - for (int x = 0; x < width; x++) { - final int level1 = getGrayOn16(img, x, y) / 2; - assert level1 >= 0 && level1 <= 7; - final int level2 = getGrayOn16(img, x, y + 1) / 2; - assert level2 >= 0 && level2 <= 7; - final int v = level1 * 8 + level2; - sb.append(encoder.encode6bit((byte) v)); - } - result.add(sb.toString()); - } - return Collections.unmodifiableList(result); - } - - private List encode4(BufferedImage img) { - final int width = img.getWidth(); - final int height = img.getHeight(); - // final int type = img.getType(); - - final List result = new ArrayList(); - final AsciiEncoder encoder = new AsciiEncoder(); - - for (int y = 0; y < height; y += 3) { - final StringBuilder sb = new StringBuilder(); - for (int x = 0; x < width; x++) { - final int level1 = getGrayOn16(img, x, y) / 4; - assert level1 >= 0 && level1 <= 3; - final int level2 = getGrayOn16(img, x, y + 1) / 4; - assert level2 >= 0 && level2 <= 3; - final int level3 = getGrayOn16(img, x, y + 2) / 4; - assert level3 >= 0 && level3 <= 3; - final int v = level1 * 16 + level2 * 4 + level3; - sb.append(encoder.encode6bit((byte) v)); - } - result.add(sb.toString()); - } - return Collections.unmodifiableList(result); - } - - private int getGrayOn16(BufferedImage img, int x, int y) { - if (x >= img.getWidth()) { - return 0; - } - if (y >= img.getHeight()) { - return 0; - } - final Color g = mono.getChangedColor(new Color(img.getRGB(x, y))); - final int grey = 255 - g.getRed(); - return grey / 16; - } - - public Sprite buildSprite(int width, int height, List strings) { - if (this == SpriteGrayLevel.GRAY_16) { - return buildSprite16(strings); - } - if (this == SpriteGrayLevel.GRAY_8) { - return buildSprite8(width, height, strings); - } - if (this == SpriteGrayLevel.GRAY_4) { - return buildSprite4(width, height, strings); - } - throw new UnsupportedOperationException(toString()); - } - - private Sprite buildSprite16(List strings) { - final SpriteMonochrome result = new SpriteMonochrome(strings.get(0).length(), strings.size(), 16); - for (int col = 0; col < result.getWidth(); col++) { - for (int line = 0; line < result.getHeight(); line++) { - if (col >= strings.get(line).length()) { - continue; - } - if (strings.get(line).charAt(col) != '0') { - final String s = "" + strings.get(line).charAt(col); - final int x = Integer.parseInt(s.toUpperCase(), 16); - result.setPixel(col, line, x); - } - } - } - return result; - } - - private Sprite buildSprite8(int width, int height, List strings) { - final AsciiEncoder encoder = new AsciiEncoder(); - final SpriteMonochrome result = new SpriteMonochrome(width, height, 8); - for (int col = 0; col < result.getWidth(); col++) { - for (int line = 0; line < strings.size(); line++) { - if (col >= strings.get(line).length()) { - continue; - } - final int v = encoder.decode6bit(strings.get(line).charAt(col)); - final int w1 = v / 8; - final int w2 = v % 8; - result.setPixel(col, line * 2, w1); - result.setPixel(col, line * 2 + 1, w2); - - } - } - return result; - } - - private Sprite buildSprite4(int width, int height, List strings) { - final AsciiEncoder encoder = new AsciiEncoder(); - final SpriteMonochrome result = new SpriteMonochrome(width, height, 4); - for (int col = 0; col < result.getWidth(); col++) { - for (int line = 0; line < strings.size(); line++) { - if (col >= strings.get(line).length()) { - continue; - } - int v = encoder.decode6bit(strings.get(line).charAt(col)); - final int w1 = v / 16; - v = v % 16; - final int w2 = v / 4; - final int w3 = v % 4; - result.setPixel(col, line * 3, w1); - result.setPixel(col, line * 3 + 1, w2); - result.setPixel(col, line * 3 + 2, w3); - - } - } - return result; - } - - public List encodeZ(BufferedImage img) { - final int width = img.getWidth(); - final int height = img.getHeight(); - final byte raw[] = new byte[width * height]; - final BufferedImage grayImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - int cpt = 0; - final int coef = 16 / nbColor; - for (int y = 0; y < height; y++) { - for (int x = 0; x < width; x++) { - final int color = getGrayOn16(img, x, y) / coef; - raw[cpt++] = (byte) color; - grayImg.setRGB(x, y, color * coef); - } - } - final byte[] comp = new CompressionZlib().compress(raw); - return cut(new AsciiEncoder().encode(comp)); - } - - private List cut(String s) { - final List result = new ArrayList(); - for (int i = 0; i < s.length(); i += 120) { - final int j = Math.min(i + 120, s.length()); - result.add(s.substring(i, j)); - - } - return Collections.unmodifiableList(result); - } - - public Sprite buildSpriteZ(int width, int height, String compressed) throws IOException { - final byte comp[] = new AsciiEncoder().decode(compressed); - final byte img[] = new CompressionZlib().decompress(comp); - final SpriteMonochrome result = new SpriteMonochrome(width, height, nbColor); - int cpt = 0; - for (int line = 0; line < result.getHeight(); line++) { - for (int col = 0; col < result.getWidth(); col++) { - result.setPixel(col, line, img[cpt++]); - - } - } - return result; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22291/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22291/pair.info deleted file mode 100755 index 7d38c3f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22291/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22291 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/ugraphic/SpriteGrayLevel.java -FixedFilePath:src/net/sourceforge/plantuml/ugraphic/SpriteGrayLevel.java -StartLineNum:188 -EndLineNum:188 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/diff.diff deleted file mode 100755 index 5931165..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/command/CommandMultilinesHeader.java b/src/net/sourceforge/plantuml/command/CommandMultilinesHeader.java -index 1ab77a48..24177285 100644 ---- a/src/net/sourceforge/plantuml/command/CommandMultilinesHeader.java -+++ b/src/net/sourceforge/plantuml/command/CommandMultilinesHeader.java -@@ -31 +31 @@ -- * Revision $Revision: 14321 $ -+ * Revision $Revision: 14726 $ -@@ -64 +64 @@ public class CommandMultilinesHeader extends CommandMultilines { -- diagram.setHeaderAlignment(HorizontalAlignment.valueOf(align.toUpperCase())); -+ diagram.setHeaderAlignment(HorizontalAlignment.valueOf(StringUtils.goUpperCase(align))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/new/CommandMultilinesHeader.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/new/CommandMultilinesHeader.java deleted file mode 100755 index 2417728..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/new/CommandMultilinesHeader.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14726 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; -import java.util.regex.Matcher; - -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; -import net.sourceforge.plantuml.StringUtils; - -public class CommandMultilinesHeader extends CommandMultilines { - - public CommandMultilinesHeader() { - super("(?i)^(?:(left|right|center)?[%s]*)header$"); - } - - @Override - public String getPatternEnd() { - return "(?i)^end[%s]?header$"; - } - - - public CommandExecutionResult execute(final UmlDiagram diagram, List lines) { - StringUtils.trim(lines, false); - final Matcher m = getStartingPattern().matcher(lines.get(0).trim()); - if (m.find() == false) { - throw new IllegalStateException(); - } - final String align = m.group(1); - if (align != null) { - diagram.setHeaderAlignment(HorizontalAlignment.valueOf(StringUtils.goUpperCase(align))); - } - final Display strings = Display.create(lines.subList(1, lines.size() - 1)); - if (strings.size() > 0) { - diagram.setHeader(strings); - return CommandExecutionResult.ok(); - } - return CommandExecutionResult.error("Empty header"); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/old/CommandMultilinesHeader.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/old/CommandMultilinesHeader.java deleted file mode 100755 index 1ab77a4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/old/CommandMultilinesHeader.java +++ /dev/null @@ -1,74 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14321 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; -import java.util.regex.Matcher; - -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; -import net.sourceforge.plantuml.StringUtils; - -public class CommandMultilinesHeader extends CommandMultilines { - - public CommandMultilinesHeader() { - super("(?i)^(?:(left|right|center)?[%s]*)header$"); - } - - @Override - public String getPatternEnd() { - return "(?i)^end[%s]?header$"; - } - - - public CommandExecutionResult execute(final UmlDiagram diagram, List lines) { - StringUtils.trim(lines, false); - final Matcher m = getStartingPattern().matcher(lines.get(0).trim()); - if (m.find() == false) { - throw new IllegalStateException(); - } - final String align = m.group(1); - if (align != null) { - diagram.setHeaderAlignment(HorizontalAlignment.valueOf(align.toUpperCase())); - } - final Display strings = Display.create(lines.subList(1, lines.size() - 1)); - if (strings.size() > 0) { - diagram.setHeader(strings); - return CommandExecutionResult.ok(); - } - return CommandExecutionResult.error("Empty header"); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/pair.info deleted file mode 100755 index 783d80b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22300/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22300 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/command/CommandMultilinesHeader.java -FixedFilePath:src/net/sourceforge/plantuml/command/CommandMultilinesHeader.java -StartLineNum:64 -EndLineNum:64 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/diff.diff deleted file mode 100755 index 2b241c6..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/graphic/USymbol.java b/src/net/sourceforge/plantuml/graphic/USymbol.java -index a01e1232..d56b397b 100644 ---- a/src/net/sourceforge/plantuml/graphic/USymbol.java -+++ b/src/net/sourceforge/plantuml/graphic/USymbol.java -@@ -42,0 +43 @@ import net.sourceforge.plantuml.FontParam; -+import net.sourceforge.plantuml.StringUtils; -@@ -105 +106 @@ public abstract class USymbol { -- final USymbol result = all.get(s.toUpperCase()); -+ final USymbol result = all.get(StringUtils.goUpperCase(s)); -@@ -116 +117 @@ public abstract class USymbol { -- all.put(code.toUpperCase(), symbol); -+ all.put(StringUtils.goUpperCase(code), symbol); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/new/USymbol.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/new/USymbol.java deleted file mode 100755 index d56b397..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/new/USymbol.java +++ /dev/null @@ -1,172 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 8066 $ - * - */ -package net.sourceforge.plantuml.graphic; - -import java.awt.geom.Dimension2D; -import java.util.HashMap; -import java.util.Map; - -import net.sourceforge.plantuml.ColorParam; -import net.sourceforge.plantuml.Dimension2DDouble; -import net.sourceforge.plantuml.FontParam; -import net.sourceforge.plantuml.StringUtils; - -public abstract class USymbol { - - private static final Map all = new HashMap(); - - public final static USymbol STORAGE = record("STORAGE", new USymbolStorage()); - public final static USymbol DATABASE = record("DATABASE", new USymbolDatabase()); - public final static USymbol CLOUD = record("CLOUD", new USymbolCloud()); - public final static USymbol CARD = record("CARD", new USymbolCard(ColorParam.rectangleBackground, - ColorParam.rectangleBorder, FontParam.RECTANGLE, FontParam.RECTANGLE_STEREOTYPE)); - public final static USymbol FRAME = record("FRAME", new USymbolFrame()); - public final static USymbol NODE = record("NODE", new USymbolNode()); - public final static USymbol ARTIFACT = record("ARTIFACT", new USymbolArtifact()); - public final static USymbol PACKAGE = record("PACKAGE", new USymbolFolder(ColorParam.packageBackground, - ColorParam.packageBorder)); - public final static USymbol FOLDER = record("FOLDER", new USymbolFolder(ColorParam.folderBackground, - ColorParam.folderBorder)); - public final static USymbol RECTANGLE = record("RECTANGLE", new USymbolRect(ColorParam.rectangleBackground, - ColorParam.rectangleBorder, FontParam.RECTANGLE, FontParam.RECTANGLE_STEREOTYPE)); - public final static USymbol AGENT = record("AGENT", new USymbolRect(ColorParam.agentBackground, - ColorParam.agentBorder, FontParam.AGENT, FontParam.AGENT_STEREOTYPE)); - public final static USymbol ACTOR = record("ACTOR", new USymbolActor()); - public final static USymbol USECASE = null; - public final static USymbol COMPONENT1 = record("COMPONENT1", new USymbolComponent1()); - public final static USymbol COMPONENT2 = record("COMPONENT2", new USymbolComponent2()); - public final static USymbol BOUNDARY = record("BOUNDARY", new USymbolBoundary()); - public final static USymbol ENTITY_DOMAIN = record("ENTITY_DOMAIN", new USymbolEntityDomain(2)); - public final static USymbol CONTROL = record("CONTROL", new USymbolControl(2)); - public final static USymbol INTERFACE = record("INTERFACE", new USymbolInterface()); - - private final ColorParam colorParamBorder; - private final ColorParam colorParamBack; - private final FontParam fontParam; - private final FontParam fontParamStereotype; - - public USymbol(ColorParam colorParamBack, ColorParam colorParamBorder, FontParam fontParam, - FontParam fontParamStereotype) { - this.colorParamBack = colorParamBack; - this.colorParamBorder = colorParamBorder; - this.fontParam = fontParam; - this.fontParamStereotype = fontParamStereotype; - } - - public FontParam getFontParam() { - return fontParam; - - } - - public FontParam getFontParamStereotype() { - return fontParamStereotype; - - } - - public ColorParam getColorParamBack() { - return colorParamBack; - } - - public ColorParam getColorParamBorder() { - return colorParamBorder; - } - - public static USymbol getFromString(String s) { - final USymbol result = all.get(StringUtils.goUpperCase(s)); - if (result == null) { - if (s.equalsIgnoreCase("component")) { - return COMPONENT2; - } - throw new IllegalArgumentException("s=" + s); - } - return result; - } - - private static USymbol record(String code, USymbol symbol) { - all.put(StringUtils.goUpperCase(code), symbol); - return symbol; - } - - public abstract TextBlock asSmall(TextBlock label, TextBlock stereotype, SymbolContext symbolContext); - - public abstract TextBlock asBig(TextBlock label, TextBlock stereotype, double width, double height, - SymbolContext symbolContext); - - static class Margin { - private final double x1; - private final double x2; - private final double y1; - private final double y2; - - Margin(double x1, double x2, double y1, double y2) { - this.x1 = x1; - this.x2 = x2; - this.y1 = y1; - this.y2 = y2; - } - - double getWidth() { - return x1 + x2; - } - - double getHeight() { - return y1 + y2; - } - - public Dimension2D addDimension(Dimension2D dim) { - return new Dimension2DDouble(dim.getWidth() + x1 + x2, dim.getHeight() + y1 + y2); - } - - public double getX1() { - return x1; - } - - public double getY1() { - return y1; - } - } - - public boolean manageHorizontalLine() { - return false; - } - - public int suppHeightBecauseOfShape() { - return 0; - } - - public int suppWidthBecauseOfShape() { - return 0; - } - -} \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/old/USymbol.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/old/USymbol.java deleted file mode 100755 index a01e123..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/old/USymbol.java +++ /dev/null @@ -1,171 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 8066 $ - * - */ -package net.sourceforge.plantuml.graphic; - -import java.awt.geom.Dimension2D; -import java.util.HashMap; -import java.util.Map; - -import net.sourceforge.plantuml.ColorParam; -import net.sourceforge.plantuml.Dimension2DDouble; -import net.sourceforge.plantuml.FontParam; - -public abstract class USymbol { - - private static final Map all = new HashMap(); - - public final static USymbol STORAGE = record("STORAGE", new USymbolStorage()); - public final static USymbol DATABASE = record("DATABASE", new USymbolDatabase()); - public final static USymbol CLOUD = record("CLOUD", new USymbolCloud()); - public final static USymbol CARD = record("CARD", new USymbolCard(ColorParam.rectangleBackground, - ColorParam.rectangleBorder, FontParam.RECTANGLE, FontParam.RECTANGLE_STEREOTYPE)); - public final static USymbol FRAME = record("FRAME", new USymbolFrame()); - public final static USymbol NODE = record("NODE", new USymbolNode()); - public final static USymbol ARTIFACT = record("ARTIFACT", new USymbolArtifact()); - public final static USymbol PACKAGE = record("PACKAGE", new USymbolFolder(ColorParam.packageBackground, - ColorParam.packageBorder)); - public final static USymbol FOLDER = record("FOLDER", new USymbolFolder(ColorParam.folderBackground, - ColorParam.folderBorder)); - public final static USymbol RECTANGLE = record("RECTANGLE", new USymbolRect(ColorParam.rectangleBackground, - ColorParam.rectangleBorder, FontParam.RECTANGLE, FontParam.RECTANGLE_STEREOTYPE)); - public final static USymbol AGENT = record("AGENT", new USymbolRect(ColorParam.agentBackground, - ColorParam.agentBorder, FontParam.AGENT, FontParam.AGENT_STEREOTYPE)); - public final static USymbol ACTOR = record("ACTOR", new USymbolActor()); - public final static USymbol USECASE = null; - public final static USymbol COMPONENT1 = record("COMPONENT1", new USymbolComponent1()); - public final static USymbol COMPONENT2 = record("COMPONENT2", new USymbolComponent2()); - public final static USymbol BOUNDARY = record("BOUNDARY", new USymbolBoundary()); - public final static USymbol ENTITY_DOMAIN = record("ENTITY_DOMAIN", new USymbolEntityDomain(2)); - public final static USymbol CONTROL = record("CONTROL", new USymbolControl(2)); - public final static USymbol INTERFACE = record("INTERFACE", new USymbolInterface()); - - private final ColorParam colorParamBorder; - private final ColorParam colorParamBack; - private final FontParam fontParam; - private final FontParam fontParamStereotype; - - public USymbol(ColorParam colorParamBack, ColorParam colorParamBorder, FontParam fontParam, - FontParam fontParamStereotype) { - this.colorParamBack = colorParamBack; - this.colorParamBorder = colorParamBorder; - this.fontParam = fontParam; - this.fontParamStereotype = fontParamStereotype; - } - - public FontParam getFontParam() { - return fontParam; - - } - - public FontParam getFontParamStereotype() { - return fontParamStereotype; - - } - - public ColorParam getColorParamBack() { - return colorParamBack; - } - - public ColorParam getColorParamBorder() { - return colorParamBorder; - } - - public static USymbol getFromString(String s) { - final USymbol result = all.get(s.toUpperCase()); - if (result == null) { - if (s.equalsIgnoreCase("component")) { - return COMPONENT2; - } - throw new IllegalArgumentException("s=" + s); - } - return result; - } - - private static USymbol record(String code, USymbol symbol) { - all.put(code.toUpperCase(), symbol); - return symbol; - } - - public abstract TextBlock asSmall(TextBlock label, TextBlock stereotype, SymbolContext symbolContext); - - public abstract TextBlock asBig(TextBlock label, TextBlock stereotype, double width, double height, - SymbolContext symbolContext); - - static class Margin { - private final double x1; - private final double x2; - private final double y1; - private final double y2; - - Margin(double x1, double x2, double y1, double y2) { - this.x1 = x1; - this.x2 = x2; - this.y1 = y1; - this.y2 = y2; - } - - double getWidth() { - return x1 + x2; - } - - double getHeight() { - return y1 + y2; - } - - public Dimension2D addDimension(Dimension2D dim) { - return new Dimension2DDouble(dim.getWidth() + x1 + x2, dim.getHeight() + y1 + y2); - } - - public double getX1() { - return x1; - } - - public double getY1() { - return y1; - } - } - - public boolean manageHorizontalLine() { - return false; - } - - public int suppHeightBecauseOfShape() { - return 0; - } - - public int suppWidthBecauseOfShape() { - return 0; - } - -} \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/pair.info deleted file mode 100755 index 5f9cdc4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22307/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22307 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/graphic/USymbol.java -FixedFilePath:src/net/sourceforge/plantuml/graphic/USymbol.java -StartLineNum:116 -EndLineNum:116 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/diff.diff deleted file mode 100755 index 5053b5f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/sequencediagram/command/CommandArrow.java b/src/net/sourceforge/plantuml/sequencediagram/command/CommandArrow.java -index 7581a5d5..fc9a5d59 100644 ---- a/src/net/sourceforge/plantuml/sequencediagram/command/CommandArrow.java -+++ b/src/net/sourceforge/plantuml/sequencediagram/command/CommandArrow.java -@@ -37,0 +38 @@ import java.util.StringTokenizer; -+import net.sourceforge.plantuml.StringUtils; -@@ -137,2 +138,2 @@ public class CommandArrow extends SingleLineCommand2 { -- final String dressing1 = CommandLinkClass.notNull(arg.get("ARROW_DRESSING1", 0)).toLowerCase(); -- final String dressing2 = CommandLinkClass.notNull(arg.get("ARROW_DRESSING2", 0)).toLowerCase(); -+ final String dressing1 = StringUtils.goLowerCase(CommandLinkClass.notNull(arg.get("ARROW_DRESSING1", 0))); -+ final String dressing2 = StringUtils.goLowerCase(CommandLinkClass.notNull(arg.get("ARROW_DRESSING2", 0))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/new/CommandArrow.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/new/CommandArrow.java deleted file mode 100755 index fc9a5d5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/new/CommandArrow.java +++ /dev/null @@ -1,275 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5424 $ - * - */ -package net.sourceforge.plantuml.sequencediagram.command; - -import java.util.StringTokenizer; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.classdiagram.command.CommandLinkClass; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexOr; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HtmlColor; -import net.sourceforge.plantuml.graphic.HtmlColorSet; -import net.sourceforge.plantuml.sequencediagram.LifeEventType; -import net.sourceforge.plantuml.sequencediagram.Message; -import net.sourceforge.plantuml.sequencediagram.Participant; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagram; -import net.sourceforge.plantuml.skin.ArrowConfiguration; -import net.sourceforge.plantuml.skin.ArrowDecoration; -import net.sourceforge.plantuml.skin.ArrowHead; -import net.sourceforge.plantuml.skin.ArrowPart; - -public class CommandArrow extends SingleLineCommand2 { - - public CommandArrow() { - super(getRegexConcat()); - } - - public static String getColorOrStylePattern() { - return "(?:\\[((?:#\\w+|dotted|dashed|bold|hidden)(?:,#\\w+|,dotted|,dashed|,bold|,hidden)*)\\])?"; - } - - static RegexConcat getRegexConcat() { - return new RegexConcat( - new RegexLeaf("^"), // - new RegexOr("PART1", // - new RegexLeaf("PART1CODE", "([\\p{L}0-9_.@]+)"), // - new RegexLeaf("PART1LONG", "[%g]([^%g]+)[%g]"), // - new RegexLeaf("PART1LONGCODE", "[%g]([^%g]+)[%g][%s]*as[%s]+([\\p{L}0-9_.@]+)"), // - new RegexLeaf("PART1CODELONG", "([\\p{L}0-9_.@]+)[%s]+as[%s]*[%g]([^%g]+)[%g]")), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("ARROW_DRESSING1", "([%s][ox]|(?:[%s][ox])?<>?(?:[ox][%s])?|//?(?:[ox][%s])?|\\\\\\\\?(?:[ox][%s])?|[ox][%s])?"), // - new RegexLeaf("[%s]*"), // - new RegexOr("PART2", // - new RegexLeaf("PART2CODE", "([\\p{L}0-9_.@]+)"), // - new RegexLeaf("PART2LONG", "[%g]([^%g]+)[%g]"), // - new RegexLeaf("PART2LONGCODE", "[%g]([^%g]+)[%g][%s]*as[%s]+([\\p{L}0-9_.@]+)"), // - new RegexLeaf("PART2CODELONG", "([\\p{L}0-9_.@]+)[%s]+as[%s]*[%g]([^%g]+)[%g]")), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("ACTIVATION", "(?:([+*!-]+)?)"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("LIFECOLOR", "(?:(#\\w+)?)"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("MESSAGE", "(?::[%s]*(.*))?$")); - } - - private Participant getOrCreateParticipant(SequenceDiagram system, RegexResult arg2, String n) { - final String code; - final Display display; - if (arg2.get(n + "CODE", 0) != null) { - code = arg2.get(n + "CODE", 0); - display = Display.getWithNewlines(code); - } else if (arg2.get(n + "LONG", 0) != null) { - code = arg2.get(n + "LONG", 0); - display = Display.getWithNewlines(code); - } else if (arg2.get(n + "LONGCODE", 0) != null) { - display = Display.getWithNewlines(arg2.get(n + "LONGCODE", 0)); - code = arg2.get(n + "LONGCODE", 1); - } else if (arg2.get(n + "CODELONG", 0) != null) { - code = arg2.get(n + "CODELONG", 0); - display = Display.getWithNewlines(arg2.get(n + "CODELONG", 1)); - return system.getOrCreateParticipant(code, display); - } else { - throw new IllegalStateException(); - } - return system.getOrCreateParticipant(code, display); - } - - private boolean contains(String string, String... totest) { - for (String t : totest) { - if (string.contains(t)) { - return true; - } - } - return false; - } - - @Override - protected CommandExecutionResult executeArg(SequenceDiagram diagram, RegexResult arg) { - - Participant p1; - Participant p2; - - final String dressing1 = StringUtils.goLowerCase(CommandLinkClass.notNull(arg.get("ARROW_DRESSING1", 0))); - final String dressing2 = StringUtils.goLowerCase(CommandLinkClass.notNull(arg.get("ARROW_DRESSING2", 0))); - - final boolean circleAtStart; - final boolean circleAtEnd; - - final boolean hasDressing2 = contains(dressing2, ">", "\\", "/", "x"); - final boolean hasDressing1 = contains(dressing1, "x", "<", "\\", "/"); - if (hasDressing2) { - p1 = getOrCreateParticipant(diagram, arg, "PART1"); - p2 = getOrCreateParticipant(diagram, arg, "PART2"); - circleAtStart = dressing1.contains("o"); - circleAtEnd = dressing2.contains("o"); - } else if (hasDressing1) { - p2 = getOrCreateParticipant(diagram, arg, "PART1"); - p1 = getOrCreateParticipant(diagram, arg, "PART2"); - circleAtStart = dressing2.contains("o"); - circleAtEnd = dressing1.contains("o"); - } else { - return CommandExecutionResult.error("Illegal sequence arrow"); - - } - - final boolean sync = contains(dressing1, "<<", "\\\\", "//") || contains(dressing2, ">>", "\\\\", "//"); - - final boolean dotted = getLength(arg) > 1; - - final Display labels; - if (arg.get("MESSAGE", 0) == null) { - labels = Display.create(""); - } else { - labels = Display.getWithNewlines(arg.get("MESSAGE", 0)); - } - - ArrowConfiguration config = hasDressing1 && hasDressing2 ? ArrowConfiguration.withDirectionBoth() - : ArrowConfiguration.withDirectionNormal(); - if (dotted) { - config = config.withDotted(); - } - if (sync) { - config = config.withHead(ArrowHead.ASYNC); - } - if (dressing2.contains("\\") || dressing1.contains("/")) { - config = config.withPart(ArrowPart.TOP_PART); - } - if (dressing2.contains("/") || dressing1.contains("\\")) { - config = config.withPart(ArrowPart.BOTTOM_PART); - } - if (circleAtEnd) { - config = config.withDecoration2(ArrowDecoration.CIRCLE); - } - if (circleAtStart) { - config = config.withDecoration1(ArrowDecoration.CIRCLE); - } - if (dressing1.contains("x")) { - config = config.withHead2(ArrowHead.CROSSX); - - } - if (dressing2.contains("x")) { - config = config.withHead2(ArrowHead.CROSSX); - } - - config = applyStyle(arg.getLazzy("ARROW_STYLE", 0), config); - - final String activationSpec = arg.get("ACTIVATION", 0); - - if (activationSpec != null && activationSpec.charAt(0) == '*') { - diagram.activate(p2, LifeEventType.CREATE, null); - } - - final String error = diagram.addMessage(new Message(p1, p2, labels, config, diagram.getNextMessageNumber())); - if (error != null) { - return CommandExecutionResult.error(error); - } - - final HtmlColor activationColor = diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("LIFECOLOR", 0)); - - if (activationSpec != null) { - switch (activationSpec.charAt(0)) { - case '+': - diagram.activate(p2, LifeEventType.ACTIVATE, activationColor); - break; - case '-': - diagram.activate(p1, LifeEventType.DEACTIVATE, null); - break; - case '!': - diagram.activate(p2, LifeEventType.DESTROY, null); - break; - default: - break; - } - } else if (diagram.isAutoactivate() - && (config.getHead() == ArrowHead.NORMAL || config.getHead() == ArrowHead.ASYNC)) { - if (config.isDotted()) { - diagram.activate(p1, LifeEventType.DEACTIVATE, null); - } else { - diagram.activate(p2, LifeEventType.ACTIVATE, activationColor); - } - - } - return CommandExecutionResult.ok(); - } - - private int getLength(RegexResult arg2) { - String sa = arg2.getLazzy("ARROW_BODYA", 0); - if (sa == null) { - sa = ""; - } - String sb = arg2.getLazzy("ARROW_BODYB", 0); - if (sb == null) { - sb = ""; - } - return sa.length() + sb.length(); - } - - public static ArrowConfiguration applyStyle(String arrowStyle, ArrowConfiguration config) { - if (arrowStyle == null) { - return config; - } - final StringTokenizer st = new StringTokenizer(arrowStyle, ","); - while (st.hasMoreTokens()) { - final String s = st.nextToken(); - if (s.equalsIgnoreCase("dashed")) { - // link.goDashed(); - } else if (s.equalsIgnoreCase("bold")) { - // link.goBold(); - } else if (s.equalsIgnoreCase("dotted")) { - // link.goDotted(); - } else if (s.equalsIgnoreCase("hidden")) { - // link.goHidden(); - } else { - config = config.withColor(HtmlColorSet.getInstance().getColorIfValid(s)); - } - } - return config; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/old/CommandArrow.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/old/CommandArrow.java deleted file mode 100755 index 7581a5d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/old/CommandArrow.java +++ /dev/null @@ -1,274 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5424 $ - * - */ -package net.sourceforge.plantuml.sequencediagram.command; - -import java.util.StringTokenizer; - -import net.sourceforge.plantuml.classdiagram.command.CommandLinkClass; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexOr; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HtmlColor; -import net.sourceforge.plantuml.graphic.HtmlColorSet; -import net.sourceforge.plantuml.sequencediagram.LifeEventType; -import net.sourceforge.plantuml.sequencediagram.Message; -import net.sourceforge.plantuml.sequencediagram.Participant; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagram; -import net.sourceforge.plantuml.skin.ArrowConfiguration; -import net.sourceforge.plantuml.skin.ArrowDecoration; -import net.sourceforge.plantuml.skin.ArrowHead; -import net.sourceforge.plantuml.skin.ArrowPart; - -public class CommandArrow extends SingleLineCommand2 { - - public CommandArrow() { - super(getRegexConcat()); - } - - public static String getColorOrStylePattern() { - return "(?:\\[((?:#\\w+|dotted|dashed|bold|hidden)(?:,#\\w+|,dotted|,dashed|,bold|,hidden)*)\\])?"; - } - - static RegexConcat getRegexConcat() { - return new RegexConcat( - new RegexLeaf("^"), // - new RegexOr("PART1", // - new RegexLeaf("PART1CODE", "([\\p{L}0-9_.@]+)"), // - new RegexLeaf("PART1LONG", "[%g]([^%g]+)[%g]"), // - new RegexLeaf("PART1LONGCODE", "[%g]([^%g]+)[%g][%s]*as[%s]+([\\p{L}0-9_.@]+)"), // - new RegexLeaf("PART1CODELONG", "([\\p{L}0-9_.@]+)[%s]+as[%s]*[%g]([^%g]+)[%g]")), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("ARROW_DRESSING1", "([%s][ox]|(?:[%s][ox])?<>?(?:[ox][%s])?|//?(?:[ox][%s])?|\\\\\\\\?(?:[ox][%s])?|[ox][%s])?"), // - new RegexLeaf("[%s]*"), // - new RegexOr("PART2", // - new RegexLeaf("PART2CODE", "([\\p{L}0-9_.@]+)"), // - new RegexLeaf("PART2LONG", "[%g]([^%g]+)[%g]"), // - new RegexLeaf("PART2LONGCODE", "[%g]([^%g]+)[%g][%s]*as[%s]+([\\p{L}0-9_.@]+)"), // - new RegexLeaf("PART2CODELONG", "([\\p{L}0-9_.@]+)[%s]+as[%s]*[%g]([^%g]+)[%g]")), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("ACTIVATION", "(?:([+*!-]+)?)"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("LIFECOLOR", "(?:(#\\w+)?)"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("MESSAGE", "(?::[%s]*(.*))?$")); - } - - private Participant getOrCreateParticipant(SequenceDiagram system, RegexResult arg2, String n) { - final String code; - final Display display; - if (arg2.get(n + "CODE", 0) != null) { - code = arg2.get(n + "CODE", 0); - display = Display.getWithNewlines(code); - } else if (arg2.get(n + "LONG", 0) != null) { - code = arg2.get(n + "LONG", 0); - display = Display.getWithNewlines(code); - } else if (arg2.get(n + "LONGCODE", 0) != null) { - display = Display.getWithNewlines(arg2.get(n + "LONGCODE", 0)); - code = arg2.get(n + "LONGCODE", 1); - } else if (arg2.get(n + "CODELONG", 0) != null) { - code = arg2.get(n + "CODELONG", 0); - display = Display.getWithNewlines(arg2.get(n + "CODELONG", 1)); - return system.getOrCreateParticipant(code, display); - } else { - throw new IllegalStateException(); - } - return system.getOrCreateParticipant(code, display); - } - - private boolean contains(String string, String... totest) { - for (String t : totest) { - if (string.contains(t)) { - return true; - } - } - return false; - } - - @Override - protected CommandExecutionResult executeArg(SequenceDiagram diagram, RegexResult arg) { - - Participant p1; - Participant p2; - - final String dressing1 = CommandLinkClass.notNull(arg.get("ARROW_DRESSING1", 0)).toLowerCase(); - final String dressing2 = CommandLinkClass.notNull(arg.get("ARROW_DRESSING2", 0)).toLowerCase(); - - final boolean circleAtStart; - final boolean circleAtEnd; - - final boolean hasDressing2 = contains(dressing2, ">", "\\", "/", "x"); - final boolean hasDressing1 = contains(dressing1, "x", "<", "\\", "/"); - if (hasDressing2) { - p1 = getOrCreateParticipant(diagram, arg, "PART1"); - p2 = getOrCreateParticipant(diagram, arg, "PART2"); - circleAtStart = dressing1.contains("o"); - circleAtEnd = dressing2.contains("o"); - } else if (hasDressing1) { - p2 = getOrCreateParticipant(diagram, arg, "PART1"); - p1 = getOrCreateParticipant(diagram, arg, "PART2"); - circleAtStart = dressing2.contains("o"); - circleAtEnd = dressing1.contains("o"); - } else { - return CommandExecutionResult.error("Illegal sequence arrow"); - - } - - final boolean sync = contains(dressing1, "<<", "\\\\", "//") || contains(dressing2, ">>", "\\\\", "//"); - - final boolean dotted = getLength(arg) > 1; - - final Display labels; - if (arg.get("MESSAGE", 0) == null) { - labels = Display.create(""); - } else { - labels = Display.getWithNewlines(arg.get("MESSAGE", 0)); - } - - ArrowConfiguration config = hasDressing1 && hasDressing2 ? ArrowConfiguration.withDirectionBoth() - : ArrowConfiguration.withDirectionNormal(); - if (dotted) { - config = config.withDotted(); - } - if (sync) { - config = config.withHead(ArrowHead.ASYNC); - } - if (dressing2.contains("\\") || dressing1.contains("/")) { - config = config.withPart(ArrowPart.TOP_PART); - } - if (dressing2.contains("/") || dressing1.contains("\\")) { - config = config.withPart(ArrowPart.BOTTOM_PART); - } - if (circleAtEnd) { - config = config.withDecoration2(ArrowDecoration.CIRCLE); - } - if (circleAtStart) { - config = config.withDecoration1(ArrowDecoration.CIRCLE); - } - if (dressing1.contains("x")) { - config = config.withHead2(ArrowHead.CROSSX); - - } - if (dressing2.contains("x")) { - config = config.withHead2(ArrowHead.CROSSX); - } - - config = applyStyle(arg.getLazzy("ARROW_STYLE", 0), config); - - final String activationSpec = arg.get("ACTIVATION", 0); - - if (activationSpec != null && activationSpec.charAt(0) == '*') { - diagram.activate(p2, LifeEventType.CREATE, null); - } - - final String error = diagram.addMessage(new Message(p1, p2, labels, config, diagram.getNextMessageNumber())); - if (error != null) { - return CommandExecutionResult.error(error); - } - - final HtmlColor activationColor = diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("LIFECOLOR", 0)); - - if (activationSpec != null) { - switch (activationSpec.charAt(0)) { - case '+': - diagram.activate(p2, LifeEventType.ACTIVATE, activationColor); - break; - case '-': - diagram.activate(p1, LifeEventType.DEACTIVATE, null); - break; - case '!': - diagram.activate(p2, LifeEventType.DESTROY, null); - break; - default: - break; - } - } else if (diagram.isAutoactivate() - && (config.getHead() == ArrowHead.NORMAL || config.getHead() == ArrowHead.ASYNC)) { - if (config.isDotted()) { - diagram.activate(p1, LifeEventType.DEACTIVATE, null); - } else { - diagram.activate(p2, LifeEventType.ACTIVATE, activationColor); - } - - } - return CommandExecutionResult.ok(); - } - - private int getLength(RegexResult arg2) { - String sa = arg2.getLazzy("ARROW_BODYA", 0); - if (sa == null) { - sa = ""; - } - String sb = arg2.getLazzy("ARROW_BODYB", 0); - if (sb == null) { - sb = ""; - } - return sa.length() + sb.length(); - } - - public static ArrowConfiguration applyStyle(String arrowStyle, ArrowConfiguration config) { - if (arrowStyle == null) { - return config; - } - final StringTokenizer st = new StringTokenizer(arrowStyle, ","); - while (st.hasMoreTokens()) { - final String s = st.nextToken(); - if (s.equalsIgnoreCase("dashed")) { - // link.goDashed(); - } else if (s.equalsIgnoreCase("bold")) { - // link.goBold(); - } else if (s.equalsIgnoreCase("dotted")) { - // link.goDotted(); - } else if (s.equalsIgnoreCase("hidden")) { - // link.goHidden(); - } else { - config = config.withColor(HtmlColorSet.getInstance().getColorIfValid(s)); - } - } - return config; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/pair.info deleted file mode 100755 index f510526..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22309/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22309 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/sequencediagram/command/CommandArrow.java -FixedFilePath:src/net/sourceforge/plantuml/sequencediagram/command/CommandArrow.java -StartLineNum:137 -EndLineNum:137 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/diff.diff deleted file mode 100755 index 96c5298..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/project/Project.java b/src/net/sourceforge/plantuml/project/Project.java -index 77c6f3ca..28699e29 100644 ---- a/src/net/sourceforge/plantuml/project/Project.java -+++ b/src/net/sourceforge/plantuml/project/Project.java -@@ -41,0 +42,2 @@ import java.util.TreeMap; -+import net.sourceforge.plantuml.StringUtils; -+ -@@ -124 +126 @@ public class Project { -- return new Constant(ItemCaract.valueOf(desc.substring(idx + 1).toUpperCase()).getData(item)); -+ return new Constant(ItemCaract.valueOf(StringUtils.goUpperCase(desc.substring(idx + 1))).getData(item)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/new/Project.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/new/Project.java deleted file mode 100755 index 28699e2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/new/Project.java +++ /dev/null @@ -1,281 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 6104 $ - * - */ -package net.sourceforge.plantuml.project; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import net.sourceforge.plantuml.StringUtils; - -public class Project { - - private final Map variables = new TreeMap(); - - private final Map items = new TreeMap(); - - private final Map ressources = new TreeMap(); - - private final DayCloseOr dayClose = new DayCloseOr(); - - public Project() { - } - - public final Instant getStart() { - Instant result = null; - for (Item it : getValidItems()) { - if (result == null || result.compareTo(it.getBegin()) > 0) { - result = it.getBegin(); - } - } - return result; - } - - public final Instant getEnd() { - Instant result = null; - for (Item it : getValidItems()) { - if (result == null || result.compareTo(it.getCompleted()) < 0) { - result = it.getCompleted(); - } - } - return result; - } - - public FreeVariable createVariable(String name, NumericType type) { - if (variables.containsKey(name)) { - throw new IllegalArgumentException("Already exist: " + name); - } - final FreeVariable variable = new FreeVariable(name, type); - variables.put(name, variable); - return variable; - } - - public Expression getExpression(String desc) { - desc = desc.trim(); - final int plus = desc.indexOf('+'); - - if (plus != -1) { - final Expression exp1 = getExpression(desc.substring(0, plus)); - final Expression exp2 = getExpression(desc.substring(plus + 1)); - if (exp1.getNumericType() == NumericType.INSTANT - && (exp2.getNumericType() == NumericType.DURATION || exp2.getNumericType() == NumericType.NUMBER)) { - return new FormalAdditionInstantDuration(exp1, exp2, new BasicInstantArithmetic(dayClose)); - } - if (exp2.getNumericType() == NumericType.INSTANT - && (exp1.getNumericType() == NumericType.DURATION || exp1.getNumericType() == NumericType.NUMBER)) { - return new FormalAdditionInstantDuration(exp2, exp1, new BasicInstantArithmetic(dayClose)); - } - return new FormalAddition(exp1, exp2); - } - - if (desc.matches("^\\d+$")) { - return new Constant(new NumericNumber(Integer.parseInt(desc))); - } - if (desc.matches("^\\$\\w+$")) { - final String varName = desc.substring(1); - final FreeVariable v = variables.get(varName); - if (v != null) { - return v; - } - throw new IllegalArgumentException("No such variable: " + desc); - } - if (Day.isValidDesc(desc)) { - final Day d = new Day(desc); - return new Constant(new Instant(d)); - } - if (desc.matches("^[\\w/]+\\$(begin|completed|work|load|duration)$")) { - final int idx = desc.indexOf('$'); - final String varName = desc.substring(0, idx); - final Item item = items.get(varName); - if (item == null) { - throw new IllegalArgumentException("No such variable: " + desc); - } - return new Constant(ItemCaract.valueOf(StringUtils.goUpperCase(desc.substring(idx + 1))).getData(item)); - } - if (desc.startsWith("^")) { - final Item item = items.get(desc.substring(1)); - if (item == null) { - throw new IllegalArgumentException("No such variable: " + desc); - } - return new Constant(item.getBegin()); - } - throw new IllegalArgumentException("cannot parse"); - } - - public boolean affectation(String destination, Expression expression) { - if (destination.startsWith("^")) { - return affectationJalon(destination, expression); - } - if (destination.startsWith("~")) { - return affectationRessource(destination, expression); - } - final int idx = destination.indexOf('$'); - if (idx == -1) { - return affectationVariable(destination, expression); - } - final String itemName = destination.substring(0, idx); - final Item item = getItem(itemName); - if (item instanceof IncompleteItem == false) { - return false; - } - final IncompleteItem incompleteItem = (IncompleteItem) item; - final String suf = destination.substring(idx + 1); - if (suf.equalsIgnoreCase("begin")) { - incompleteItem.setData(ItemCaract.BEGIN, expression.getValue()); - } else if (suf.equalsIgnoreCase("completed")) { - incompleteItem.setData(ItemCaract.COMPLETED, expression.getValue()); - } else if (suf.equalsIgnoreCase("work")) { - incompleteItem.setData(ItemCaract.WORK, expression.getValue()); - } else if (suf.equalsIgnoreCase("duration")) { - if (expression.getNumericType() == NumericType.NUMBER) { - expression = new Constant(new Duration((NumericNumber) expression.getValue())); - } - incompleteItem.setData(ItemCaract.DURATION, expression.getValue()); - } else if (suf.equalsIgnoreCase("LOAD")) { - if (expression.getNumericType() == NumericType.NUMBER) { - expression = new Constant(new Load((NumericNumber) expression.getValue())); - } - incompleteItem.setData(ItemCaract.LOAD, expression.getValue()); - } else { - return false; - } - return true; - } - - private boolean affectationRessource(String res, Expression expression) { - res = res.substring(1); - final int idx = res.indexOf('$'); - final String suf = res.substring(idx + 1); - if (suf.equals("capacity")) { - final Ressource ressource = getRessource(res.substring(0, idx)); - ressource.setCapacity(((NumericNumber) expression.getValue()).getIntValue()); - return true; - } - return false; - } - - private Ressource getRessource(String code) { - Ressource result = ressources.get(code); - if (result == null) { - result = new Ressource(code); - ressources.put(code, result); - } - return result; - } - - private boolean affectationJalon(String jalon, Expression expression) { - final Jalon it = getItemJalon(jalon.substring(1)); - it.setInstant(expression.getValue()); - return true; - } - - private Jalon getItemJalon(String jalon) { - Jalon result = (Jalon) items.get(jalon); - if (result == null) { - result = new Jalon(jalon, null); - items.put(jalon, result); - - } - return result; - } - - private Item getItem(String code) { - Item result = items.get(code); - if (result == null) { - final int idx = code.indexOf('/'); - if (idx == -1) { - result = new IncompleteItem(code, null, new BasicInstantArithmetic(dayClose)); - } else { - final ParentItem parent = getItemParent(code.substring(0, idx)); - result = new IncompleteItem(code, parent, new BasicInstantArithmetic(dayClose)); - parent.addChild(result); - } - items.put(code, result); - } - return result; - } - - private ParentItem getItemParent(String code) { - Item result = items.get(code); - if (result == null) { - final int idx = code.indexOf('/'); - if (idx == -1) { - result = new ParentItem(code, null); - items.put(code, result); - } else { - throw new UnsupportedOperationException(); - } - } - return (ParentItem) result; - } - - private boolean affectationVariable(String destination, Expression expression) { - if (variables.containsKey(destination) == false) { - return false; - } - variables.get(destination).setValue(expression); - return true; - } - - public List getValidItems() { - final List result = new ArrayList(); - for (Item item : items.values()) { - if (item.isValid()) { - result.add(item); - } - } - Collections.sort(result, new ItemComparator()); - return Collections.unmodifiableList(result); - } - - public final DayClose getDayClose() { - return dayClose; - } - - public void closeWeekDay(WeekDay weekDay) { - dayClose.add(new DayCloseWeekDay(weekDay)); - } - - // public Item getItem(String code) { - // BasicItem result = items.get(code); - // if (result == null) { - // result = new BasicItem(code); - // items.put(code, result); - // } - // return result; - // } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/old/Project.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/old/Project.java deleted file mode 100755 index 77c6f3c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/old/Project.java +++ /dev/null @@ -1,279 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 6104 $ - * - */ -package net.sourceforge.plantuml.project; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -public class Project { - - private final Map variables = new TreeMap(); - - private final Map items = new TreeMap(); - - private final Map ressources = new TreeMap(); - - private final DayCloseOr dayClose = new DayCloseOr(); - - public Project() { - } - - public final Instant getStart() { - Instant result = null; - for (Item it : getValidItems()) { - if (result == null || result.compareTo(it.getBegin()) > 0) { - result = it.getBegin(); - } - } - return result; - } - - public final Instant getEnd() { - Instant result = null; - for (Item it : getValidItems()) { - if (result == null || result.compareTo(it.getCompleted()) < 0) { - result = it.getCompleted(); - } - } - return result; - } - - public FreeVariable createVariable(String name, NumericType type) { - if (variables.containsKey(name)) { - throw new IllegalArgumentException("Already exist: " + name); - } - final FreeVariable variable = new FreeVariable(name, type); - variables.put(name, variable); - return variable; - } - - public Expression getExpression(String desc) { - desc = desc.trim(); - final int plus = desc.indexOf('+'); - - if (plus != -1) { - final Expression exp1 = getExpression(desc.substring(0, plus)); - final Expression exp2 = getExpression(desc.substring(plus + 1)); - if (exp1.getNumericType() == NumericType.INSTANT - && (exp2.getNumericType() == NumericType.DURATION || exp2.getNumericType() == NumericType.NUMBER)) { - return new FormalAdditionInstantDuration(exp1, exp2, new BasicInstantArithmetic(dayClose)); - } - if (exp2.getNumericType() == NumericType.INSTANT - && (exp1.getNumericType() == NumericType.DURATION || exp1.getNumericType() == NumericType.NUMBER)) { - return new FormalAdditionInstantDuration(exp2, exp1, new BasicInstantArithmetic(dayClose)); - } - return new FormalAddition(exp1, exp2); - } - - if (desc.matches("^\\d+$")) { - return new Constant(new NumericNumber(Integer.parseInt(desc))); - } - if (desc.matches("^\\$\\w+$")) { - final String varName = desc.substring(1); - final FreeVariable v = variables.get(varName); - if (v != null) { - return v; - } - throw new IllegalArgumentException("No such variable: " + desc); - } - if (Day.isValidDesc(desc)) { - final Day d = new Day(desc); - return new Constant(new Instant(d)); - } - if (desc.matches("^[\\w/]+\\$(begin|completed|work|load|duration)$")) { - final int idx = desc.indexOf('$'); - final String varName = desc.substring(0, idx); - final Item item = items.get(varName); - if (item == null) { - throw new IllegalArgumentException("No such variable: " + desc); - } - return new Constant(ItemCaract.valueOf(desc.substring(idx + 1).toUpperCase()).getData(item)); - } - if (desc.startsWith("^")) { - final Item item = items.get(desc.substring(1)); - if (item == null) { - throw new IllegalArgumentException("No such variable: " + desc); - } - return new Constant(item.getBegin()); - } - throw new IllegalArgumentException("cannot parse"); - } - - public boolean affectation(String destination, Expression expression) { - if (destination.startsWith("^")) { - return affectationJalon(destination, expression); - } - if (destination.startsWith("~")) { - return affectationRessource(destination, expression); - } - final int idx = destination.indexOf('$'); - if (idx == -1) { - return affectationVariable(destination, expression); - } - final String itemName = destination.substring(0, idx); - final Item item = getItem(itemName); - if (item instanceof IncompleteItem == false) { - return false; - } - final IncompleteItem incompleteItem = (IncompleteItem) item; - final String suf = destination.substring(idx + 1); - if (suf.equalsIgnoreCase("begin")) { - incompleteItem.setData(ItemCaract.BEGIN, expression.getValue()); - } else if (suf.equalsIgnoreCase("completed")) { - incompleteItem.setData(ItemCaract.COMPLETED, expression.getValue()); - } else if (suf.equalsIgnoreCase("work")) { - incompleteItem.setData(ItemCaract.WORK, expression.getValue()); - } else if (suf.equalsIgnoreCase("duration")) { - if (expression.getNumericType() == NumericType.NUMBER) { - expression = new Constant(new Duration((NumericNumber) expression.getValue())); - } - incompleteItem.setData(ItemCaract.DURATION, expression.getValue()); - } else if (suf.equalsIgnoreCase("LOAD")) { - if (expression.getNumericType() == NumericType.NUMBER) { - expression = new Constant(new Load((NumericNumber) expression.getValue())); - } - incompleteItem.setData(ItemCaract.LOAD, expression.getValue()); - } else { - return false; - } - return true; - } - - private boolean affectationRessource(String res, Expression expression) { - res = res.substring(1); - final int idx = res.indexOf('$'); - final String suf = res.substring(idx + 1); - if (suf.equals("capacity")) { - final Ressource ressource = getRessource(res.substring(0, idx)); - ressource.setCapacity(((NumericNumber) expression.getValue()).getIntValue()); - return true; - } - return false; - } - - private Ressource getRessource(String code) { - Ressource result = ressources.get(code); - if (result == null) { - result = new Ressource(code); - ressources.put(code, result); - } - return result; - } - - private boolean affectationJalon(String jalon, Expression expression) { - final Jalon it = getItemJalon(jalon.substring(1)); - it.setInstant(expression.getValue()); - return true; - } - - private Jalon getItemJalon(String jalon) { - Jalon result = (Jalon) items.get(jalon); - if (result == null) { - result = new Jalon(jalon, null); - items.put(jalon, result); - - } - return result; - } - - private Item getItem(String code) { - Item result = items.get(code); - if (result == null) { - final int idx = code.indexOf('/'); - if (idx == -1) { - result = new IncompleteItem(code, null, new BasicInstantArithmetic(dayClose)); - } else { - final ParentItem parent = getItemParent(code.substring(0, idx)); - result = new IncompleteItem(code, parent, new BasicInstantArithmetic(dayClose)); - parent.addChild(result); - } - items.put(code, result); - } - return result; - } - - private ParentItem getItemParent(String code) { - Item result = items.get(code); - if (result == null) { - final int idx = code.indexOf('/'); - if (idx == -1) { - result = new ParentItem(code, null); - items.put(code, result); - } else { - throw new UnsupportedOperationException(); - } - } - return (ParentItem) result; - } - - private boolean affectationVariable(String destination, Expression expression) { - if (variables.containsKey(destination) == false) { - return false; - } - variables.get(destination).setValue(expression); - return true; - } - - public List getValidItems() { - final List result = new ArrayList(); - for (Item item : items.values()) { - if (item.isValid()) { - result.add(item); - } - } - Collections.sort(result, new ItemComparator()); - return Collections.unmodifiableList(result); - } - - public final DayClose getDayClose() { - return dayClose; - } - - public void closeWeekDay(WeekDay weekDay) { - dayClose.add(new DayCloseWeekDay(weekDay)); - } - - // public Item getItem(String code) { - // BasicItem result = items.get(code); - // if (result == null) { - // result = new BasicItem(code); - // items.put(code, result); - // } - // return result; - // } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/pair.info deleted file mode 100755 index 1c88e4d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22311/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22311 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/project/Project.java -FixedFilePath:src/net/sourceforge/plantuml/project/Project.java -StartLineNum:124 -EndLineNum:124 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/diff.diff deleted file mode 100755 index 3ad3b00..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/command/CommandRankDir.java b/src/net/sourceforge/plantuml/command/CommandRankDir.java -index f829d126..4fdcfe56 100644 ---- a/src/net/sourceforge/plantuml/command/CommandRankDir.java -+++ b/src/net/sourceforge/plantuml/command/CommandRankDir.java -@@ -36,0 +37 @@ import net.sourceforge.plantuml.SkinParam; -+import net.sourceforge.plantuml.StringUtils; -@@ -48 +49 @@ public class CommandRankDir extends SingleLineCommand { -- final String s = arg.get(0).toUpperCase().replace(' ', '_'); -+ final String s = StringUtils.goUpperCase(arg.get(0)).replace(' ', '_'); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/new/CommandRankDir.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/new/CommandRankDir.java deleted file mode 100755 index 4fdcfe5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/new/CommandRankDir.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; - -import net.sourceforge.plantuml.SkinParam; -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.cucadiagram.CucaDiagram; -import net.sourceforge.plantuml.cucadiagram.Rankdir; - -public class CommandRankDir extends SingleLineCommand { - - public CommandRankDir() { - super("(?i)^(left[%s]to[%s]right|top[%s]to[%s]bottom)[%s]+direction$"); - } - - @Override - protected CommandExecutionResult executeArg(CucaDiagram diagram, List arg) { - final String s = StringUtils.goUpperCase(arg.get(0)).replace(' ', '_'); - ((SkinParam) diagram.getSkinParam()).setRankdir(Rankdir.valueOf(s)); - // diagram.setRankdir(Rankdir.valueOf(s)); - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/old/CommandRankDir.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/old/CommandRankDir.java deleted file mode 100755 index f829d12..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/old/CommandRankDir.java +++ /dev/null @@ -1,54 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; - -import net.sourceforge.plantuml.SkinParam; -import net.sourceforge.plantuml.cucadiagram.CucaDiagram; -import net.sourceforge.plantuml.cucadiagram.Rankdir; - -public class CommandRankDir extends SingleLineCommand { - - public CommandRankDir() { - super("(?i)^(left[%s]to[%s]right|top[%s]to[%s]bottom)[%s]+direction$"); - } - - @Override - protected CommandExecutionResult executeArg(CucaDiagram diagram, List arg) { - final String s = arg.get(0).toUpperCase().replace(' ', '_'); - ((SkinParam) diagram.getSkinParam()).setRankdir(Rankdir.valueOf(s)); - // diagram.setRankdir(Rankdir.valueOf(s)); - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/pair.info deleted file mode 100755 index 21104f3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22314/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22314 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/command/CommandRankDir.java -FixedFilePath:src/net/sourceforge/plantuml/command/CommandRankDir.java -StartLineNum:48 -EndLineNum:48 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/diff.diff deleted file mode 100755 index 0b90743..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/graphic/Img.java b/src/net/sourceforge/plantuml/graphic/Img.java -index a6a8bf1b..0b653664 100644 ---- a/src/net/sourceforge/plantuml/graphic/Img.java -+++ b/src/net/sourceforge/plantuml/graphic/Img.java -@@ -31 +31 @@ -- * Revision $Revision: 14056 $ -+ * Revision $Revision: 14726 $ -@@ -49,0 +50 @@ import net.sourceforge.plantuml.FileSystem; -+import net.sourceforge.plantuml.StringUtils; -@@ -78 +79 @@ public class Img implements HtmlCommand { -- return ImgValign.valueOf(m.group(1).toUpperCase()); -+ return ImgValign.valueOf(StringUtils.goUpperCase(m.group(1))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/new/Img.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/new/Img.java deleted file mode 100755 index 0b65366..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/new/Img.java +++ /dev/null @@ -1,152 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14726 $ - * - */ -package net.sourceforge.plantuml.graphic; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.imageio.ImageIO; - -import net.sourceforge.plantuml.FileSystem; -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.command.regex.MyPattern; - -public class Img implements HtmlCommand { - - final static private Pattern srcPattern = MyPattern.cmpile("(?i)src[%s]*=[%s]*[\"%q]?([^%s\">]+)[\"%q]?"); - final static private Pattern vspacePattern = MyPattern.cmpile("(?i)vspace[%s]*=[%s]*[\"%q]?(\\d+)[\"%q]?"); - final static private Pattern valignPattern = MyPattern.cmpile("(?i)valign[%s]*=[%s]*[\"%q]?(top|bottom|middle)[\"%q]?"); - final static private Pattern noSrcColonPattern = MyPattern.cmpile("(?i)" + Splitter.imgPatternNoSrcColon); - - private final TextBlock tileImage; - - private Img(TextBlock image) { - this.tileImage = image; - } - - static int getVspace(String html) { - final Matcher m = vspacePattern.matcher(html); - if (m.find() == false) { - return 0; - } - return Integer.parseInt(m.group(1)); - } - - static ImgValign getValign(String html) { - final Matcher m = valignPattern.matcher(html); - if (m.find() == false) { - return ImgValign.TOP; - } - return ImgValign.valueOf(StringUtils.goUpperCase(m.group(1))); - } - - static HtmlCommand getInstance(String html, boolean withSrc) { - if (withSrc) { - final Matcher m = srcPattern.matcher(html); - final int vspace = getVspace(html); - final ImgValign valign = getValign(html); - return build(m, valign, vspace); - } - final Matcher m = noSrcColonPattern.matcher(html); - return build(m, ImgValign.TOP, 0); - } - - private static HtmlCommand build(final Matcher m, final ImgValign valign, final int vspace) { - if (m.find() == false) { - return new Text("(SYNTAX ERROR)"); - } - final String src = m.group(1); - try { - final File f = FileSystem.getInstance().getFile(src); - if (f.exists() == false) { - // Check if valid URL - if (src.startsWith("http:") || src.startsWith("https:")) { - final byte image[] = getFile(src); - final BufferedImage read = ImageIO.read(new ByteArrayInputStream(image)); - if (read == null) { - return new Text("(Cannot decode: " + src + ")"); - } - return new Img(new TileImage(read, valign, vspace)); - } - return new Text("(File not found: " + f + ")"); - } - if (f.getName().endsWith(".svg")) { - return new Img(new TileImageSvg(f)); - } - final BufferedImage read = ImageIO.read(f); - if (read == null) { - return new Text("(Cannot decode: " + f + ")"); - } - return new Img(new TileImage(ImageIO.read(f), valign, vspace)); - } catch (IOException e) { - return new Text("ERROR " + e.toString()); - } - } - - public TextBlock createMonoImage() { - return tileImage; - } - - // Added by Alain Corbiere - static byte[] getFile(String host) throws IOException { - final ByteArrayOutputStream image = new ByteArrayOutputStream(); - InputStream input = null; - try { - final URL url = new URL(host); - final URLConnection connection = url.openConnection(); - input = connection.getInputStream(); - final byte[] buffer = new byte[1024]; - int read; - while ((read = input.read(buffer)) > 0) { - image.write(buffer, 0, read); - } - image.close(); - return image.toByteArray(); - } finally { - if (input != null) { - input.close(); - } - } - } - // End - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/old/Img.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/old/Img.java deleted file mode 100755 index a6a8bf1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/old/Img.java +++ /dev/null @@ -1,151 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14056 $ - * - */ -package net.sourceforge.plantuml.graphic; - -import java.awt.image.BufferedImage; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLConnection; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.imageio.ImageIO; - -import net.sourceforge.plantuml.FileSystem; -import net.sourceforge.plantuml.command.regex.MyPattern; - -public class Img implements HtmlCommand { - - final static private Pattern srcPattern = MyPattern.cmpile("(?i)src[%s]*=[%s]*[\"%q]?([^%s\">]+)[\"%q]?"); - final static private Pattern vspacePattern = MyPattern.cmpile("(?i)vspace[%s]*=[%s]*[\"%q]?(\\d+)[\"%q]?"); - final static private Pattern valignPattern = MyPattern.cmpile("(?i)valign[%s]*=[%s]*[\"%q]?(top|bottom|middle)[\"%q]?"); - final static private Pattern noSrcColonPattern = MyPattern.cmpile("(?i)" + Splitter.imgPatternNoSrcColon); - - private final TextBlock tileImage; - - private Img(TextBlock image) { - this.tileImage = image; - } - - static int getVspace(String html) { - final Matcher m = vspacePattern.matcher(html); - if (m.find() == false) { - return 0; - } - return Integer.parseInt(m.group(1)); - } - - static ImgValign getValign(String html) { - final Matcher m = valignPattern.matcher(html); - if (m.find() == false) { - return ImgValign.TOP; - } - return ImgValign.valueOf(m.group(1).toUpperCase()); - } - - static HtmlCommand getInstance(String html, boolean withSrc) { - if (withSrc) { - final Matcher m = srcPattern.matcher(html); - final int vspace = getVspace(html); - final ImgValign valign = getValign(html); - return build(m, valign, vspace); - } - final Matcher m = noSrcColonPattern.matcher(html); - return build(m, ImgValign.TOP, 0); - } - - private static HtmlCommand build(final Matcher m, final ImgValign valign, final int vspace) { - if (m.find() == false) { - return new Text("(SYNTAX ERROR)"); - } - final String src = m.group(1); - try { - final File f = FileSystem.getInstance().getFile(src); - if (f.exists() == false) { - // Check if valid URL - if (src.startsWith("http:") || src.startsWith("https:")) { - final byte image[] = getFile(src); - final BufferedImage read = ImageIO.read(new ByteArrayInputStream(image)); - if (read == null) { - return new Text("(Cannot decode: " + src + ")"); - } - return new Img(new TileImage(read, valign, vspace)); - } - return new Text("(File not found: " + f + ")"); - } - if (f.getName().endsWith(".svg")) { - return new Img(new TileImageSvg(f)); - } - final BufferedImage read = ImageIO.read(f); - if (read == null) { - return new Text("(Cannot decode: " + f + ")"); - } - return new Img(new TileImage(ImageIO.read(f), valign, vspace)); - } catch (IOException e) { - return new Text("ERROR " + e.toString()); - } - } - - public TextBlock createMonoImage() { - return tileImage; - } - - // Added by Alain Corbiere - static byte[] getFile(String host) throws IOException { - final ByteArrayOutputStream image = new ByteArrayOutputStream(); - InputStream input = null; - try { - final URL url = new URL(host); - final URLConnection connection = url.openConnection(); - input = connection.getInputStream(); - final byte[] buffer = new byte[1024]; - int read; - while ((read = input.read(buffer)) > 0) { - image.write(buffer, 0, read); - } - image.close(); - return image.toByteArray(); - } finally { - if (input != null) { - input.close(); - } - } - } - // End - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/pair.info deleted file mode 100755 index ac41669..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22322/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22322 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/graphic/Img.java -FixedFilePath:src/net/sourceforge/plantuml/graphic/Img.java -StartLineNum:78 -EndLineNum:78 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/diff.diff deleted file mode 100755 index 34bfb13..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/cucadiagram/dot/OSLinux.java b/src/net/sourceforge/plantuml/cucadiagram/dot/OSLinux.java -index 47a71cf2..bf66d57c 100644 ---- a/src/net/sourceforge/plantuml/cucadiagram/dot/OSLinux.java -+++ b/src/net/sourceforge/plantuml/cucadiagram/dot/OSLinux.java -@@ -37,0 +38,2 @@ import java.io.File; -+import net.sourceforge.plantuml.StringUtils; -+ -@@ -58 +60 @@ class OSLinux extends OS { -- return strategy.name().toLowerCase(); -+ return StringUtils.goLowerCase(strategy.name()); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/new/OSLinux.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/new/OSLinux.java deleted file mode 100755 index bf66d57..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/new/OSLinux.java +++ /dev/null @@ -1,68 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 6104 $ - * - */ -package net.sourceforge.plantuml.cucadiagram.dot; - -import java.io.File; - -import net.sourceforge.plantuml.StringUtils; - -class OSLinux extends OS { - - @Override - File getExecutable(GraphvizLayoutStrategy strategy) { - final File result = strategy.getSystemForcedExecutable(); - if (result != null) { - return result; - } - final String fileName = getFileName(strategy); - final File usrLocalBin = new File("/usr/local/bin/" + fileName); - - if (usrLocalBin.exists()) { - return usrLocalBin; - } - final File usrBin = new File("/usr/bin/" + fileName); - return usrBin; - } - - @Override - String getFileName(GraphvizLayoutStrategy strategy) { - return StringUtils.goLowerCase(strategy.name()); - } - - @Override - public String getCommand(GraphvizLayoutStrategy strategy) { - return getExecutable(strategy).getAbsolutePath(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/old/OSLinux.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/old/OSLinux.java deleted file mode 100755 index 47a71cf..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/old/OSLinux.java +++ /dev/null @@ -1,66 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 6104 $ - * - */ -package net.sourceforge.plantuml.cucadiagram.dot; - -import java.io.File; - -class OSLinux extends OS { - - @Override - File getExecutable(GraphvizLayoutStrategy strategy) { - final File result = strategy.getSystemForcedExecutable(); - if (result != null) { - return result; - } - final String fileName = getFileName(strategy); - final File usrLocalBin = new File("/usr/local/bin/" + fileName); - - if (usrLocalBin.exists()) { - return usrLocalBin; - } - final File usrBin = new File("/usr/bin/" + fileName); - return usrBin; - } - - @Override - String getFileName(GraphvizLayoutStrategy strategy) { - return strategy.name().toLowerCase(); - } - - @Override - public String getCommand(GraphvizLayoutStrategy strategy) { - return getExecutable(strategy).getAbsolutePath(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/pair.info deleted file mode 100755 index 8c9bf89..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22328/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22328 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/cucadiagram/dot/OSLinux.java -FixedFilePath:src/net/sourceforge/plantuml/cucadiagram/dot/OSLinux.java -StartLineNum:58 -EndLineNum:58 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/diff.diff deleted file mode 100755 index 50fde98..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/command/CommandFooter.java b/src/net/sourceforge/plantuml/command/CommandFooter.java -index f6568746..fe11bf12 100644 ---- a/src/net/sourceforge/plantuml/command/CommandFooter.java -+++ b/src/net/sourceforge/plantuml/command/CommandFooter.java -@@ -31 +31 @@ -- * Revision $Revision: 12235 $ -+ * Revision $Revision: 14726 $ -@@ -37,0 +38 @@ import java.util.List; -+import net.sourceforge.plantuml.StringUtils; -@@ -52 +53 @@ public class CommandFooter extends SingleLineCommand { -- diagram.setFooterAlignment(HorizontalAlignment.valueOf(align.toUpperCase())); -+ diagram.setFooterAlignment(HorizontalAlignment.valueOf(StringUtils.goUpperCase(align))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/new/CommandFooter.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/new/CommandFooter.java deleted file mode 100755 index fe11bf1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/new/CommandFooter.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14726 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; - -public class CommandFooter extends SingleLineCommand { - - public CommandFooter() { - super("(?i)^(?:(left|right|center)?[%s]*)footer(?:[%s]*:[%s]*|[%s]+)(.*[\\p{L}0-9_.].*)$"); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram diagram, List arg) { - final String align = arg.get(0); - if (align != null) { - diagram.setFooterAlignment(HorizontalAlignment.valueOf(StringUtils.goUpperCase(align))); - } - diagram.setFooter(Display.getWithNewlines(arg.get(1))); - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/old/CommandFooter.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/old/CommandFooter.java deleted file mode 100755 index f656874..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/old/CommandFooter.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 12235 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; - -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; - -public class CommandFooter extends SingleLineCommand { - - public CommandFooter() { - super("(?i)^(?:(left|right|center)?[%s]*)footer(?:[%s]*:[%s]*|[%s]+)(.*[\\p{L}0-9_.].*)$"); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram diagram, List arg) { - final String align = arg.get(0); - if (align != null) { - diagram.setFooterAlignment(HorizontalAlignment.valueOf(align.toUpperCase())); - } - diagram.setFooter(Display.getWithNewlines(arg.get(1))); - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/pair.info deleted file mode 100755 index e74391e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22341/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22341 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/command/CommandFooter.java -FixedFilePath:src/net/sourceforge/plantuml/command/CommandFooter.java -StartLineNum:52 -EndLineNum:52 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/diff.diff deleted file mode 100755 index 7cd3fd8..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow.java b/src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow.java -index 66c0828c..224eab27 100644 ---- a/src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow.java -+++ b/src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow.java -@@ -38,0 +39 @@ import java.util.Set; -+import net.sourceforge.plantuml.StringUtils; -@@ -167 +168 @@ public class CommandHideShow extends SingleLineCommand2 { -- final String sub = s.substring(0, 3).toLowerCase(); -+ final String sub = StringUtils.goLowerCase(s.substring(0, 3)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/new/CommandHideShow.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/new/CommandHideShow.java deleted file mode 100755 index 224eab2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/new/CommandHideShow.java +++ /dev/null @@ -1,187 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5019 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.util.EnumSet; -import java.util.Set; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.classdiagram.ClassDiagram; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Code; -import net.sourceforge.plantuml.cucadiagram.EntityGender; -import net.sourceforge.plantuml.cucadiagram.EntityGenderUtils; -import net.sourceforge.plantuml.cucadiagram.EntityPortion; -import net.sourceforge.plantuml.cucadiagram.EntityUtils; -import net.sourceforge.plantuml.cucadiagram.IEntity; -import net.sourceforge.plantuml.cucadiagram.LeafType; -import net.sourceforge.plantuml.descdiagram.DescriptionDiagram; - -public class CommandHideShow extends SingleLineCommand2 { - - private static final EnumSet PORTION_METHOD = EnumSet. of(EntityPortion.METHOD); - private static final EnumSet PORTION_MEMBER = EnumSet. of(EntityPortion.FIELD, - EntityPortion.METHOD); - private static final EnumSet PORTION_FIELD = EnumSet. of(EntityPortion.FIELD); - - public CommandHideShow() { - super(getRegexConcat()); - } - - static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("COMMAND", "(hide|show)"), // - new RegexLeaf("[%s]+"), // - new RegexLeaf("GENDER", - "(?:(class|interface|enum|annotation|abstract|[\\p{L}0-9_.]+|[%g][^%g]+[%g]|\\<\\<.*\\>\\>)[%s]+)*?"), // - new RegexLeaf("EMPTY", "(?:(empty)[%s]+)?"), // - new RegexLeaf("PORTION", "(members?|attributes?|fields?|methods?|circle\\w*|stereotypes?)"), // - new RegexLeaf("$")); - } - - private final EntityGender emptyByGender(Set portion) { - if (portion == PORTION_METHOD) { - return EntityGenderUtils.emptyMethods(); - } - if (portion == PORTION_FIELD) { - return EntityGenderUtils.emptyFields(); - } - if (portion == PORTION_MEMBER) { - return EntityGenderUtils.emptyMembers(); - } - return EntityGenderUtils.all(); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram classDiagram, RegexResult arg) { - if (classDiagram instanceof ClassDiagram) { - return executeClassDiagram((ClassDiagram) classDiagram, arg); - } - if (classDiagram instanceof DescriptionDiagram) { - return executeDescriptionDiagram((DescriptionDiagram) classDiagram, arg); - } - // Just ignored - return CommandExecutionResult.ok(); - } - - private CommandExecutionResult executeDescriptionDiagram(DescriptionDiagram diagram, RegexResult arg) { - final Set portion = getEntityPortion(arg.get("PORTION", 0)); - final EntityGender gender; - final String arg1 = arg.get("GENDER", 0); - if (arg1 == null) { - gender = EntityGenderUtils.all(); - } else if (arg1.equalsIgnoreCase("class")) { - gender = EntityGenderUtils.byEntityType(LeafType.CLASS); - } else if (arg1.equalsIgnoreCase("interface")) { - gender = EntityGenderUtils.byEntityType(LeafType.INTERFACE); - } else if (arg1.equalsIgnoreCase("enum")) { - gender = EntityGenderUtils.byEntityType(LeafType.ENUM); - } else if (arg1.equalsIgnoreCase("abstract")) { - gender = EntityGenderUtils.byEntityType(LeafType.ABSTRACT_CLASS); - } else if (arg1.equalsIgnoreCase("annotation")) { - gender = EntityGenderUtils.byEntityType(LeafType.ANNOTATION); - } else if (arg1.startsWith("<<")) { - gender = EntityGenderUtils.byStereotype(arg1); - } else { - final IEntity entity = diagram.getOrCreateLeaf(Code.of(arg1), null, null); - gender = EntityGenderUtils.byEntityAlone(entity); - } - - diagram.hideOrShow(gender, portion, arg.get("COMMAND", 0).equalsIgnoreCase("show")); - return CommandExecutionResult.ok(); - } - - private CommandExecutionResult executeClassDiagram(ClassDiagram classDiagram, RegexResult arg) { - - final Set portion = getEntityPortion(arg.get("PORTION", 0)); - - EntityGender gender = null; - final String arg1 = arg.get("GENDER", 0); - if (arg1 == null) { - gender = EntityGenderUtils.all(); - } else if (arg1.equalsIgnoreCase("class")) { - gender = EntityGenderUtils.byEntityType(LeafType.CLASS); - } else if (arg1.equalsIgnoreCase("interface")) { - gender = EntityGenderUtils.byEntityType(LeafType.INTERFACE); - } else if (arg1.equalsIgnoreCase("enum")) { - gender = EntityGenderUtils.byEntityType(LeafType.ENUM); - } else if (arg1.equalsIgnoreCase("abstract")) { - gender = EntityGenderUtils.byEntityType(LeafType.ABSTRACT_CLASS); - } else if (arg1.equalsIgnoreCase("annotation")) { - gender = EntityGenderUtils.byEntityType(LeafType.ANNOTATION); - } else if (arg1.startsWith("<<")) { - gender = EntityGenderUtils.byStereotype(arg1); - } else { - final IEntity entity = classDiagram.getOrCreateLeaf(Code.of(arg1), null, null); - gender = EntityGenderUtils.byEntityAlone(entity); - } - if (gender != null) { - final boolean empty = arg.get("EMPTY", 0) != null; - if (empty == true) { - gender = EntityGenderUtils.and(gender, emptyByGender(portion)); - } - if (EntityUtils.groupRoot(classDiagram.getCurrentGroup()) == false) { - gender = EntityGenderUtils.and(gender, EntityGenderUtils.byPackage(classDiagram.getCurrentGroup())); - } - classDiagram.hideOrShow(gender, portion, arg.get("COMMAND", 0).equalsIgnoreCase("show")); - } - return CommandExecutionResult.ok(); - } - - private Set getEntityPortion(String s) { - final String sub = StringUtils.goLowerCase(s.substring(0, 3)); - if (sub.equals("met")) { - return PORTION_METHOD; - } - if (sub.equals("mem")) { - return PORTION_MEMBER; - } - if (sub.equals("att") || sub.equals("fie")) { - return PORTION_FIELD; - } - if (sub.equals("cir")) { - return EnumSet. of(EntityPortion.CIRCLED_CHARACTER); - } - if (sub.equals("ste")) { - return EnumSet. of(EntityPortion.STEREOTYPE); - } - throw new IllegalArgumentException(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/old/CommandHideShow.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/old/CommandHideShow.java deleted file mode 100755 index 66c0828..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/old/CommandHideShow.java +++ /dev/null @@ -1,186 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5019 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.util.EnumSet; -import java.util.Set; - -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.classdiagram.ClassDiagram; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Code; -import net.sourceforge.plantuml.cucadiagram.EntityGender; -import net.sourceforge.plantuml.cucadiagram.EntityGenderUtils; -import net.sourceforge.plantuml.cucadiagram.EntityPortion; -import net.sourceforge.plantuml.cucadiagram.EntityUtils; -import net.sourceforge.plantuml.cucadiagram.IEntity; -import net.sourceforge.plantuml.cucadiagram.LeafType; -import net.sourceforge.plantuml.descdiagram.DescriptionDiagram; - -public class CommandHideShow extends SingleLineCommand2 { - - private static final EnumSet PORTION_METHOD = EnumSet. of(EntityPortion.METHOD); - private static final EnumSet PORTION_MEMBER = EnumSet. of(EntityPortion.FIELD, - EntityPortion.METHOD); - private static final EnumSet PORTION_FIELD = EnumSet. of(EntityPortion.FIELD); - - public CommandHideShow() { - super(getRegexConcat()); - } - - static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("COMMAND", "(hide|show)"), // - new RegexLeaf("[%s]+"), // - new RegexLeaf("GENDER", - "(?:(class|interface|enum|annotation|abstract|[\\p{L}0-9_.]+|[%g][^%g]+[%g]|\\<\\<.*\\>\\>)[%s]+)*?"), // - new RegexLeaf("EMPTY", "(?:(empty)[%s]+)?"), // - new RegexLeaf("PORTION", "(members?|attributes?|fields?|methods?|circle\\w*|stereotypes?)"), // - new RegexLeaf("$")); - } - - private final EntityGender emptyByGender(Set portion) { - if (portion == PORTION_METHOD) { - return EntityGenderUtils.emptyMethods(); - } - if (portion == PORTION_FIELD) { - return EntityGenderUtils.emptyFields(); - } - if (portion == PORTION_MEMBER) { - return EntityGenderUtils.emptyMembers(); - } - return EntityGenderUtils.all(); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram classDiagram, RegexResult arg) { - if (classDiagram instanceof ClassDiagram) { - return executeClassDiagram((ClassDiagram) classDiagram, arg); - } - if (classDiagram instanceof DescriptionDiagram) { - return executeDescriptionDiagram((DescriptionDiagram) classDiagram, arg); - } - // Just ignored - return CommandExecutionResult.ok(); - } - - private CommandExecutionResult executeDescriptionDiagram(DescriptionDiagram diagram, RegexResult arg) { - final Set portion = getEntityPortion(arg.get("PORTION", 0)); - final EntityGender gender; - final String arg1 = arg.get("GENDER", 0); - if (arg1 == null) { - gender = EntityGenderUtils.all(); - } else if (arg1.equalsIgnoreCase("class")) { - gender = EntityGenderUtils.byEntityType(LeafType.CLASS); - } else if (arg1.equalsIgnoreCase("interface")) { - gender = EntityGenderUtils.byEntityType(LeafType.INTERFACE); - } else if (arg1.equalsIgnoreCase("enum")) { - gender = EntityGenderUtils.byEntityType(LeafType.ENUM); - } else if (arg1.equalsIgnoreCase("abstract")) { - gender = EntityGenderUtils.byEntityType(LeafType.ABSTRACT_CLASS); - } else if (arg1.equalsIgnoreCase("annotation")) { - gender = EntityGenderUtils.byEntityType(LeafType.ANNOTATION); - } else if (arg1.startsWith("<<")) { - gender = EntityGenderUtils.byStereotype(arg1); - } else { - final IEntity entity = diagram.getOrCreateLeaf(Code.of(arg1), null, null); - gender = EntityGenderUtils.byEntityAlone(entity); - } - - diagram.hideOrShow(gender, portion, arg.get("COMMAND", 0).equalsIgnoreCase("show")); - return CommandExecutionResult.ok(); - } - - private CommandExecutionResult executeClassDiagram(ClassDiagram classDiagram, RegexResult arg) { - - final Set portion = getEntityPortion(arg.get("PORTION", 0)); - - EntityGender gender = null; - final String arg1 = arg.get("GENDER", 0); - if (arg1 == null) { - gender = EntityGenderUtils.all(); - } else if (arg1.equalsIgnoreCase("class")) { - gender = EntityGenderUtils.byEntityType(LeafType.CLASS); - } else if (arg1.equalsIgnoreCase("interface")) { - gender = EntityGenderUtils.byEntityType(LeafType.INTERFACE); - } else if (arg1.equalsIgnoreCase("enum")) { - gender = EntityGenderUtils.byEntityType(LeafType.ENUM); - } else if (arg1.equalsIgnoreCase("abstract")) { - gender = EntityGenderUtils.byEntityType(LeafType.ABSTRACT_CLASS); - } else if (arg1.equalsIgnoreCase("annotation")) { - gender = EntityGenderUtils.byEntityType(LeafType.ANNOTATION); - } else if (arg1.startsWith("<<")) { - gender = EntityGenderUtils.byStereotype(arg1); - } else { - final IEntity entity = classDiagram.getOrCreateLeaf(Code.of(arg1), null, null); - gender = EntityGenderUtils.byEntityAlone(entity); - } - if (gender != null) { - final boolean empty = arg.get("EMPTY", 0) != null; - if (empty == true) { - gender = EntityGenderUtils.and(gender, emptyByGender(portion)); - } - if (EntityUtils.groupRoot(classDiagram.getCurrentGroup()) == false) { - gender = EntityGenderUtils.and(gender, EntityGenderUtils.byPackage(classDiagram.getCurrentGroup())); - } - classDiagram.hideOrShow(gender, portion, arg.get("COMMAND", 0).equalsIgnoreCase("show")); - } - return CommandExecutionResult.ok(); - } - - private Set getEntityPortion(String s) { - final String sub = s.substring(0, 3).toLowerCase(); - if (sub.equals("met")) { - return PORTION_METHOD; - } - if (sub.equals("mem")) { - return PORTION_MEMBER; - } - if (sub.equals("att") || sub.equals("fie")) { - return PORTION_FIELD; - } - if (sub.equals("cir")) { - return EnumSet. of(EntityPortion.CIRCLED_CHARACTER); - } - if (sub.equals("ste")) { - return EnumSet. of(EntityPortion.STEREOTYPE); - } - throw new IllegalArgumentException(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/pair.info deleted file mode 100755 index aab61ad..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22342/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22342 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow.java -FixedFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow.java -StartLineNum:167 -EndLineNum:167 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/diff.diff deleted file mode 100755 index 3c32f88..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/cucadiagram/dot/OSWindows.java b/src/net/sourceforge/plantuml/cucadiagram/dot/OSWindows.java -index ea2fd395..fcd76ee2 100644 ---- a/src/net/sourceforge/plantuml/cucadiagram/dot/OSWindows.java -+++ b/src/net/sourceforge/plantuml/cucadiagram/dot/OSWindows.java -@@ -41,0 +42,2 @@ import java.util.List; -+import net.sourceforge.plantuml.StringUtils; -+ -@@ -86 +88 @@ class OSWindows extends OS { -- return strategy.name().toLowerCase() + ".exe"; -+ return StringUtils.goLowerCase(strategy.name()) + ".exe"; \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/new/OSWindows.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/new/OSWindows.java deleted file mode 100755 index fcd76ee..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/new/OSWindows.java +++ /dev/null @@ -1,96 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 6104 $ - * - */ -package net.sourceforge.plantuml.cucadiagram.dot; - -import java.io.File; -import java.io.FileFilter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sourceforge.plantuml.StringUtils; - -class OSWindows extends OS { - - @Override - File getExecutable(GraphvizLayoutStrategy strategy) { - File result = strategy.getSystemForcedExecutable(); - if (result != null) { - return result; - } - result = searchInDir(new File("c:/Program Files"), strategy); - if (result != null) { - return result; - } - result = searchInDir(new File("c:/Program Files (x86)"), strategy); - return result; - } - - private File searchInDir(final File programFile, GraphvizLayoutStrategy strategy) { - if (programFile.exists() == false || programFile.isDirectory() == false) { - return null; - } - final List dots = new ArrayList(); - for (File f : programFile.listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.isDirectory() && pathname.getName().startsWith("Graphviz"); - } - })) { - final File result = new File(new File(f, "bin"), getFileName(strategy)); - if (result.exists() && result.canRead()) { - dots.add(result.getAbsoluteFile()); - } - } - return higherVersion(dots); - } - - static File higherVersion(List dots) { - if (dots.size() == 0) { - return null; - } - Collections.sort(dots, Collections.reverseOrder()); - return dots.get(0); - } - - @Override - String getFileName(GraphvizLayoutStrategy strategy) { - return StringUtils.goLowerCase(strategy.name()) + ".exe"; - } - - @Override - public String getCommand(GraphvizLayoutStrategy strategy) { - return "\"" + getExecutable(strategy).getAbsolutePath() + "\""; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/old/OSWindows.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/old/OSWindows.java deleted file mode 100755 index ea2fd39..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/old/OSWindows.java +++ /dev/null @@ -1,94 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 6104 $ - * - */ -package net.sourceforge.plantuml.cucadiagram.dot; - -import java.io.File; -import java.io.FileFilter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -class OSWindows extends OS { - - @Override - File getExecutable(GraphvizLayoutStrategy strategy) { - File result = strategy.getSystemForcedExecutable(); - if (result != null) { - return result; - } - result = searchInDir(new File("c:/Program Files"), strategy); - if (result != null) { - return result; - } - result = searchInDir(new File("c:/Program Files (x86)"), strategy); - return result; - } - - private File searchInDir(final File programFile, GraphvizLayoutStrategy strategy) { - if (programFile.exists() == false || programFile.isDirectory() == false) { - return null; - } - final List dots = new ArrayList(); - for (File f : programFile.listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.isDirectory() && pathname.getName().startsWith("Graphviz"); - } - })) { - final File result = new File(new File(f, "bin"), getFileName(strategy)); - if (result.exists() && result.canRead()) { - dots.add(result.getAbsoluteFile()); - } - } - return higherVersion(dots); - } - - static File higherVersion(List dots) { - if (dots.size() == 0) { - return null; - } - Collections.sort(dots, Collections.reverseOrder()); - return dots.get(0); - } - - @Override - String getFileName(GraphvizLayoutStrategy strategy) { - return strategy.name().toLowerCase() + ".exe"; - } - - @Override - public String getCommand(GraphvizLayoutStrategy strategy) { - return "\"" + getExecutable(strategy).getAbsolutePath() + "\""; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/pair.info deleted file mode 100755 index c7a1b61..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22355/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22355 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/cucadiagram/dot/OSWindows.java -FixedFilePath:src/net/sourceforge/plantuml/cucadiagram/dot/OSWindows.java -StartLineNum:86 -EndLineNum:86 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/diff.diff deleted file mode 100755 index 9291569..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/FileFormat.java b/src/net/sourceforge/plantuml/FileFormat.java -index 2b3ae183..646b688d 100644 ---- a/src/net/sourceforge/plantuml/FileFormat.java -+++ b/src/net/sourceforge/plantuml/FileFormat.java -@@ -65 +65 @@ public enum FileFormat { -- return "." + name().toLowerCase(); -+ return "." + StringUtils.goLowerCase(name()); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/new/FileFormat.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/new/FileFormat.java deleted file mode 100755 index 646b688..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/new/FileFormat.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 9786 $ - * - */ -package net.sourceforge.plantuml; - -import java.io.File; - -/** - * Format for output files generated by PlantUML. - * - * @author Arnaud Roques - * - */ -public enum FileFormat { - PNG, SVG, EPS, EPS_TEXT, ATXT, UTXT, XMI_STANDARD, XMI_STAR, XMI_ARGO, PDF, MJPEG, ANIMATED_GIF, HTML, HTML5, VDX, LATEX, BASE64; - - /** - * Returns the file format to be used for that format. - * - * @return a string starting by a point. - */ - public String getFileSuffix() { - if (name().startsWith("XMI")) { - return ".xmi"; - } - if (this == MJPEG) { - return ".avi"; - } - if (this == ANIMATED_GIF) { - return ".gif"; - } - if (this == EPS_TEXT) { - return EPS.getFileSuffix(); - } - return "." + StringUtils.goLowerCase(name()); - } - - /** - * Check if this file format is Encapsulated PostScript. - * - * @return true for EPS. - */ - public boolean isEps() { - if (this == EPS) { - return true; - } - if (this == EPS_TEXT) { - return true; - } - return false; - } - - public String changeName(String fileName, int cpt) { - if (cpt == 0) { - return changeName(fileName, getFileSuffix()); - } - return changeName(fileName, "_" + String.format("%03d", cpt) + getFileSuffix()); - } - - private String changeName(String fileName, String replacement) { - String result = fileName.replaceAll("\\.\\w+$", replacement); - if (result.equals(fileName)) { - result = fileName + replacement; - } - return result; - } - - public File computeFilename(File pngFile, int i) { - if (i == 0) { - return pngFile; - } - final File dir = pngFile.getParentFile(); - return new File(dir, computeFilename(pngFile.getName(), i)); - // String name = pngFile.getName(); - // name = name.replaceAll("\\" + getFileSuffix() + "$", "_" + String.format("%03d", i) + getFileSuffix()); - // return new File(dir, name); - - } - - public String computeFilename(String name, int i) { - if (i == 0) { - return name; - } - return name.replaceAll("\\" + getFileSuffix() + "$", "_" + String.format("%03d", i) + getFileSuffix()); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/old/FileFormat.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/old/FileFormat.java deleted file mode 100755 index 2b3ae18..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/old/FileFormat.java +++ /dev/null @@ -1,117 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 9786 $ - * - */ -package net.sourceforge.plantuml; - -import java.io.File; - -/** - * Format for output files generated by PlantUML. - * - * @author Arnaud Roques - * - */ -public enum FileFormat { - PNG, SVG, EPS, EPS_TEXT, ATXT, UTXT, XMI_STANDARD, XMI_STAR, XMI_ARGO, PDF, MJPEG, ANIMATED_GIF, HTML, HTML5, VDX, LATEX, BASE64; - - /** - * Returns the file format to be used for that format. - * - * @return a string starting by a point. - */ - public String getFileSuffix() { - if (name().startsWith("XMI")) { - return ".xmi"; - } - if (this == MJPEG) { - return ".avi"; - } - if (this == ANIMATED_GIF) { - return ".gif"; - } - if (this == EPS_TEXT) { - return EPS.getFileSuffix(); - } - return "." + name().toLowerCase(); - } - - /** - * Check if this file format is Encapsulated PostScript. - * - * @return true for EPS. - */ - public boolean isEps() { - if (this == EPS) { - return true; - } - if (this == EPS_TEXT) { - return true; - } - return false; - } - - public String changeName(String fileName, int cpt) { - if (cpt == 0) { - return changeName(fileName, getFileSuffix()); - } - return changeName(fileName, "_" + String.format("%03d", cpt) + getFileSuffix()); - } - - private String changeName(String fileName, String replacement) { - String result = fileName.replaceAll("\\.\\w+$", replacement); - if (result.equals(fileName)) { - result = fileName + replacement; - } - return result; - } - - public File computeFilename(File pngFile, int i) { - if (i == 0) { - return pngFile; - } - final File dir = pngFile.getParentFile(); - return new File(dir, computeFilename(pngFile.getName(), i)); - // String name = pngFile.getName(); - // name = name.replaceAll("\\" + getFileSuffix() + "$", "_" + String.format("%03d", i) + getFileSuffix()); - // return new File(dir, name); - - } - - public String computeFilename(String name, int i) { - if (i == 0) { - return name; - } - return name.replaceAll("\\" + getFileSuffix() + "$", "_" + String.format("%03d", i) + getFileSuffix()); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/pair.info deleted file mode 100755 index d99ff6d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22357/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22357 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/FileFormat.java -FixedFilePath:src/net/sourceforge/plantuml/FileFormat.java -StartLineNum:65 -EndLineNum:65 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/diff.diff deleted file mode 100755 index e4aa829..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/sudoku/SudokuDLX.java b/src/net/sourceforge/plantuml/sudoku/SudokuDLX.java -index b171155e..f47f4d54 100644 ---- a/src/net/sourceforge/plantuml/sudoku/SudokuDLX.java -+++ b/src/net/sourceforge/plantuml/sudoku/SudokuDLX.java -@@ -31 +31 @@ -- * Revision $Revision: 12235 $ -+ * Revision $Revision: 14726 $ -@@ -38,0 +39 @@ import net.sourceforge.plantuml.Log; -+import net.sourceforge.plantuml.StringUtils; -@@ -79 +80 @@ public class SudokuDLX implements ISudoku { -- Log.println("Seed=" + Long.toString(seed, 36).toUpperCase()); -+ Log.println("Seed=" + StringUtils.goUpperCase(Long.toString(seed, 36))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/new/SudokuDLX.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/new/SudokuDLX.java deleted file mode 100755 index f47f4d5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/new/SudokuDLX.java +++ /dev/null @@ -1,90 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14726 $ - * - */ -package net.sourceforge.plantuml.sudoku; - -import java.util.Random; - -import net.sourceforge.plantuml.Log; -import net.sourceforge.plantuml.StringUtils; - -public class SudokuDLX implements ISudoku { - - private final String tab[]; - private final long seed; - private final long rate; - - public SudokuDLX(Long seed) { - if (seed == null) { - this.seed = Math.abs(new Random().nextLong()); - } else { - this.seed = Math.abs(seed.longValue()); - } - final DLXEngine engine = new DLXEngine(new Random(this.seed)); - final String s = engine.generate(10000, 100000); - rate = engine.rate(s.replace("\n", "").trim()); - tab = s.split("\\s"); - } - - public long getRatting() { - return rate; - } - - public long getSeed() { - return seed; - } - - public int getGiven(int x, int y) { - final char c = tab[x].charAt(y); - if (c == '.') { - return 0; - } - return c - '0'; - } - - public void print() { - for (String s : tab) { - Log.println(s); - } - Log.println("Rate=" + rate); - Log.println("Seed=" + StringUtils.goUpperCase(Long.toString(seed, 36))); - } - - public static void main(String[] args) { - for (int i = 0; i < 1; i++) { - final SudokuDLX sudoku = new SudokuDLX(null); - sudoku.print(); - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/old/SudokuDLX.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/old/SudokuDLX.java deleted file mode 100755 index b171155..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/old/SudokuDLX.java +++ /dev/null @@ -1,89 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 12235 $ - * - */ -package net.sourceforge.plantuml.sudoku; - -import java.util.Random; - -import net.sourceforge.plantuml.Log; - -public class SudokuDLX implements ISudoku { - - private final String tab[]; - private final long seed; - private final long rate; - - public SudokuDLX(Long seed) { - if (seed == null) { - this.seed = Math.abs(new Random().nextLong()); - } else { - this.seed = Math.abs(seed.longValue()); - } - final DLXEngine engine = new DLXEngine(new Random(this.seed)); - final String s = engine.generate(10000, 100000); - rate = engine.rate(s.replace("\n", "").trim()); - tab = s.split("\\s"); - } - - public long getRatting() { - return rate; - } - - public long getSeed() { - return seed; - } - - public int getGiven(int x, int y) { - final char c = tab[x].charAt(y); - if (c == '.') { - return 0; - } - return c - '0'; - } - - public void print() { - for (String s : tab) { - Log.println(s); - } - Log.println("Rate=" + rate); - Log.println("Seed=" + Long.toString(seed, 36).toUpperCase()); - } - - public static void main(String[] args) { - for (int i = 0; i < 1; i++) { - final SudokuDLX sudoku = new SudokuDLX(null); - sudoku.print(); - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/pair.info deleted file mode 100755 index c62209c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22422/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22422 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/sudoku/SudokuDLX.java -FixedFilePath:src/net/sourceforge/plantuml/sudoku/SudokuDLX.java -StartLineNum:79 -EndLineNum:79 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/diff.diff deleted file mode 100755 index 1e89aa6..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/oregon/OregonBasicGame.java b/src/net/sourceforge/plantuml/oregon/OregonBasicGame.java -index abf45bed..0692d369 100644 ---- a/src/net/sourceforge/plantuml/oregon/OregonBasicGame.java -+++ b/src/net/sourceforge/plantuml/oregon/OregonBasicGame.java -@@ -37,0 +38,2 @@ import java.util.Random; -+import net.sourceforge.plantuml.StringUtils; -+ -@@ -871 +873 @@ public class OregonBasicGame implements BasicGame { -- return valueOf(s.toUpperCase()); -+ return valueOf(StringUtils.goUpperCase(s)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/new/OregonBasicGame.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/new/OregonBasicGame.java deleted file mode 100755 index 0692d36..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/new/OregonBasicGame.java +++ /dev/null @@ -1,938 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4639 $ - * - */ -package net.sourceforge.plantuml.oregon; - -import java.util.Random; - -import net.sourceforge.plantuml.StringUtils; - -public class OregonBasicGame implements BasicGame { - - private Screen screen; - private SmartKeyboard skb; - private Random rnd; - - private int ks; - private int kh; - private int kp; - private int kb; - private int km; - private int kq; - - private double ma; - - private final String da[] = new String[] { "March 29", "April 12", "April 26", "May 10", "May 24", "June 7", - "June 21", "July 5", "July 19", "August 2", "August 16", "August 31", "September 13", "September 27", - "October 11", "October 25", "November 8", "November 22", "December 6", "December 20" }; - - private final int ep[] = new int[] { 6, 11, 13, 15, 17, 22, 32, 35, 37, 42, 44, 54, 64, 69, 95 }; - - public Screen getScreen() { - return screen; - } - - private void print(String s) { - screen.print(s); - } - - private void printb(String s) { - screen.print("** " + s + " **"); - } - - private void print() { - screen.print(); - } - - public void run(Keyboard keyboard) throws NoInputException { - if (screen != null) { - throw new IllegalStateException(); - } - screen = new Screen(); - skb = new SmartKeyboard(keyboard); - init(); - } - - private double rnd() { - if (this.rnd == null) { - this.rnd = new Random(skb.getHistory().hashCode()); - } - return rnd.nextDouble(); - } - - private void init() throws NoInputException { - printInitialScenario490(); - initialPurchasesOfPlayer690(); - initialShootingRanking920(); - screen.clear(); - print("** Your trip is about to begin... **"); - print(); - for (int j = 0; j < 20; j++) { - if (m > 2039) { - madeIt3190(j); - break; - } - print("Monday, " + da[j] + ", 1847. You are " + whereAreWe()); - print(); - if (f < 6) { - print("** You're low on food. Better buy some or go hunting soon. **"); - print(); - } - if (ks == 1 || kh == 1) { - t = t - 10; - if (t < 0) { - needDoctorBadly3010(j); - } - print("Doctor charged $10 for his services"); - print("to treat your " + (ks == 1 ? "illness." : "injuries.")); - } - // MP flag to be done? - - m = (int) (m + .5); - print("Total mileage to date is: " + ((int) m) + ""); - m += 200 + (a - 110) / 2.5 + 10 * rnd(); - print(); - // Calculate how far we travel in 2 weeks - print("Here's what you now have (no. of bullets, $ worth of other items) :"); - printInventory3350(); - question1000(j); - eating1310(j); - screen.clear(); - riders1390(j); - // print(); - events1800(j); - // print(); - montains2640(j); - if (skb.hasMore()) { - screen.clear(); - } - } - } - - private void events1800(int j) throws NoInputException { - final int rn = (int) (100.0 * rnd()); - for (int i = 0; i < ep.length; i++) { - if (rn <= ep[i]) { - execEvent(i, j); - return; - } - } - execEvent(ep.length, j); - } - - private void execEvent(int i, int j) throws NoInputException { - switch (i) { - case 0: - printb("Your wagon breaks down. It costs you time and supplies to fix it."); - m = m - 15 - 5 * rnd(); - r = r - 4; - break; - case 1: - printb("An ox gores your leg. That slows you down for the rest of the trip."); - m = m - 25; - a = a - 10; - break; - case 2: - printb("Bad luck... your daughter breaks her arm. You must stop and"); - printb("make a splint and sling with some of your medical supplies."); - m = m - 5 - 4 * rnd(); - r = r - 1 - 2 * rnd(); - break; - case 3: - printb("An ox wanders off and you have to spend time looking for it."); - m = m - 17; - break; - case 4: - printb("Your son gets lost and you spend half a day searching for him."); - m = m - 10; - break; - case 5: - printb("Nothing but contaminated and stagnant water near the trail."); - printb("You lose time looking for a clean spring or creek."); - m = m - 2 - 10 * rnd(); - break; - - case 6: - if (m > 950) { - int c1 = 0; - if (c < 11 + 2 * rnd()) { - c1 = 1; - } - printb("Cold weather... Brrrrrrr! ... You " + (c1 == 1 ? "dont't " : "") - + "have enough clothing to keep warm."); - if (c1 == 1) { - dealWithIllness2880(j); - } - } else { - printb("Heavy rains. Traveling is slow in the mud and you break your spare"); - printb("ox yoke using it to pry your wagon out of the mud. Worse yet, some"); - printb("of your ammo is damaged by the water."); - m = m - 5 - 10 * rnd(); - r = r - 7; - b = b - 400; - f = f - 5; - } - break; - - case 7: - printb("Bandits attacking!"); - final int br1 = shoot3870(); - b = b - 20 * br1; - if (b > 0) { - if (br1 <= 1) { - print("That was the quickest draw outside of Dodge City."); - print("You got at least one and drove 'em off."); - return; - } - } else { - t = t / 3; - print("You try to drive them off but you run out of bullets."); - print("They grab as much cash as they can find."); - - } - print("You get shot in the leg -"); - kh = 1; - print("and they grab one of your oxen."); - a = a - 10; - r = r - 2; - print("Better have a doc look at your leg... and soon!"); - break; - - case 8: - printb("You have a fire in your wagon. Food and supplies are damaged."); - m = m - 15; - f = f - 20; - b = b - 400; - r = r - 2 * 6 * rnd(); - break; - - case 9: - printb("You lose your way in heavy fog. Time lost regaining the trail."); - m = m - 10 - 5 * rnd(); - break; - - case 10: - printb("You come upon a rattlesnake and before you are able to get your gun"); - printb("out, it bites you."); - b = b - 10; - r = r - 2; - if (r < 0) { - printb("You have no medical supplies left, and you die of poison."); - die3060(j); - - } - print("Fortunately, you acted quickly, sucked out the poison, and"); - print("treated the wound. It is painful, but you'll survive."); - break; - - case 11: - print("Your wagon gets swamped fording a river; you lose food and clothes."); - m = m - 20 - 20 * rnd(); - f = f - 15; - c = c - 10; - break; - - case 12: - printb("You're sound asleep and you hear a noise... get up to investigate."); - printb("It's wild animals! They attack you!"); - final int br2 = shoot3870(); - if (b <= 39) { - print("You're almost out of ammo; can't reach more."); - print("The wolves come at you biting and clawing."); - kh = 1; - die3030(j); - } - if (br2 <= 2) { - print("Nice shooting, pardner... They didn't get much."); - } else { - print("Kind of slow on the draw. The wolves got at your food and clothes."); - b = b - 20 * br2; - c = c - 2 * br2; - f = f - 4 * br2; - } - break; - - case 13: - printb("You're caught in a fierce hailstorm; ammo and supplies are damaged."); - m = m - 5 - 10 * rnd(); - b = b - 150; - r = r - 2 - 2 * rnd(); - break; - - case 14: - if (e == 1) { - dealWithIllness2880(j); - } else if (e == 2 && rnd() > .25) { - dealWithIllness2880(j); - } else if (e == 3 && rnd() > .5) { - dealWithIllness2880(j); - } - break; - - case 15: - printb("Helpful Indians show you where to find more food."); - f = f + 7; - break; - - default: - printb("EVENT " + i); - } - print(); - - } - - private void madeIt3190(int j) throws NoInputException { - final double ml = (2040 - ma) / (m - ma); - f = f + (1 - ml) * (8 + 5 * e); - print("You finally arrived at Oregon City after 2040 long miles."); - print("You're exhausted and haggard, but you made it! A real pioneer!"); - final int d = (int) (14 * (j + ml)); - final int dm = (int) (d / 30.5); - final int dd = (int) (d - 30.5 * dm); - print("You've been on the trail for " + dm + " months and " + dd + " days."); - print("You have few supplies remaining :"); - printInventory3350(); - print(); - print("President James A. Polk sends you his heartiest"); - - print("congratulations and wishes you a prosperous life in your new home."); - throw new NoInputException(); - } - - private boolean riders1390(int j) throws NoInputException { - final double value = (Math.pow(m / 100 - 4, 2) + 72) / (Math.pow(m / 100 - 4, 2) + 12) - 1; - final double random = 10.0 * rnd(); - if (random > value) { - return false; - } - int gh = 0; - if (rnd() > .2) { - gh = 1; - } - print(); - print("Riders ahead! They " + (gh == 1 ? "don't " : "") + "look hostile."); - int gt; - do { - print("You can (1) run, (2) attack, (3) ignore them, or (4) circle wagons."); - gt = skb.inputInt(screen); - } while (gt < 0 || gt > 4); - if (rnd() < .2) { - gh = 1 - gh; - } - if (gh == 1) { - if (gt == 1) { - m = m + 15; - a = a - 5; - } else if (gt == 2) { - m = m - 5; - b = b - 100; - } else if (gt == 4) { - m = m - 20; - } - print("Riders were friendly, but check for possible losses."); - return true; - } - if (gt == 1) { - m = m + 20; - r = r - 7; - b = b - 150; - a = a - 20; - } else if (gt == 2) { - final int br = shoot3870(); - b = b - br * 40 - 80; - riderShoot(br); - } else if (gt == 3) { - if (rnd() > .8) { - print("They did not attack. Whew!"); - return true; - } - b = b - 150; - r = r - 7; - } else { - assert gt == 4; - final int br = shoot3870(); - b = b - br * 30 - 80; - m = m - 25; - riderShoot(br); - } - print("Riders were hostile. Better check for losses!"); - if (b >= 0) { - return true; - } - print(); - print("Oh, my gosh!"); - print("They're coming back and you're out of ammo! Your dreams turn to"); - print("dust as you and your family are massacred on the prairie."); - print3110(j); - return true; - - } - - private void riderShoot(final int br) { - if (br <= 1) { - print("Nice shooting - you drove them off."); - } else if (br <= 4) { - print("Kind of slow with your Colt .45."); - } else { - print("Pretty slow on the draw, partner. You got a nasty flesh wound."); - kh = 1; - print("You'll have to see the doc soon as you can."); - } - } - - private void montains2640(int j) throws NoInputException { - if (m <= 975) { - return; - } - final double mm = m / 100.0 - 15; - if (10 * rnd() > 9 - (mm * mm + 72) / (mm * mm + 12)) { - southPass2750(j); - return; - } - print("You're in rugged mountain country."); - if (rnd() <= .1) { - print("You get lost and lose valuable time trying to find the trail."); - m = m - 60; - southPass2750(j); - return; - } - if (rnd() > .11) { - print("The going is really slow; oxen are very tired."); - m = m - 45 - 50 * rnd(); - } else { - print("Trail cave in damages your wagon. You lose time and supplies."); - m = m - 20 - 30 * rnd(); - b = b - 200; - r = r - 3; - } - southPass2750(j); - - } - - private void southPass2750(int j) throws NoInputException { - if (kp == 0) { - kp = 1; - if (rnd() < .8) { - blizzard2840(j); - return; - } - print("You made it safely through the South Pass....no snow!"); - } - if (m < 1700) { - return; - } - if (km == 0) { - km = 1; - if (rnd() < .7) { - blizzard2840(j); - } - } - - } - - private void blizzard2840(int j) throws NoInputException { - print("Blizzard in the mountain pass. Going is slow; supplies are lost."); - kb = 1; - m = m - 30 - 40 * rnd(); - f = f - 12; - b = b - 200; - r = r - 5; - if (c < 18 + 2 * rnd()) { - dealWithIllness2880(j); - } - } - - private void dealWithIllness2880(int j) throws NoInputException { - if (100 * rnd() < 10 + 35 * (e - 1)) { - print("Mild illness. Your own medicine will cure it."); - m -= 5; - r -= 1; - } else if (100 * rnd() < 100.0 - 40.0 / Math.pow(4.0, e - 1)) { - print("The whole family is sick. Your medicine will probably work okay."); - m -= 5; - r -= 2.5; - } else { - print("Serious illness in the family. You'll have to stop and see a doctor"); - print("soon. For now, your medicine will work."); - r -= 5; - ks = 1; - } - if (r <= 0) { - print("...if only you had enough."); - outOfMedicalSupplies3020(j); - } - - } - - private void eating1310(int j) throws NoInputException { - if (f < 5) { - die3000(j); - return; - } - do { - print("Do you want to eat (1) poorly, (2) moderately or (3) well ?"); - e = skb.inputInt(screen); - if (e < 1 || e > 3) { - print("Enter 1, 2, or 3, please."); - break; - } - final int ee = (int) (4 + 2.5 * e); - if (e == 1 && ee > f) { - f = 0; - return; - } - if (ee > f) { - print("You don't have enough to eat that well."); - break; - } - f -= ee; - return; - } while (true); - - } - - private void needDoctorBadly3010(int j) throws NoInputException { - print("You need a doctor badly but can't afford one."); - die3030(j); - } - - private void outOfMedicalSupplies3020(int j) throws NoInputException { - print("You have run out of all medical supplies."); - print(); - die3030(j); - } - - private void die3000(int j) throws NoInputException { - screen.clear(); - print("You run out of food and starve to death."); - print(); - print3110(j); - } - - private void die3030(int j) throws NoInputException { - print("The wilderness is unforgiving and you die of " + (kh == 1 ? "your injuries" : "pneumonia")); - die3060(j); - } - - private void die3060(int j) throws NoInputException { - print("Your family tries to push on, but finds the going too rough"); - print(" without you."); - print3110(j); - } - - private void print3110(int j) throws NoInputException { - print("Some travelers find the bodies of you and your"); - print("family the following spring. They give you a decent"); - print("burial and notify your next of kin."); - print(); - print("At the time of your unfortunate demise, you had been on the trail"); - final int d = 14 * j; - final int dm = (int) (d / 30.5); - final int dd = (int) (d - 30.5 * dm); - print("for " + dm + " months and " + dd + " days and had covered " + (int) ((m + 70)) + " miles."); - print(); - print("You had a few supplies left :"); - printInventory3350(); - throw new NoInputException(); - } - - private void question1000(int j) throws NoInputException { - int x; - if (j % 2 == 1) { - do { - print("Want to (1) stop at the next fort, (2) hunt, or (3) push on ?"); - x = skb.inputInt(screen); - if (x == 3) { - return; - } - if (x == 1) { - stopAtFort1100(j); - return; - } - if (x == 2) { - hunt1200(j); - if (kq == 0) { - return; - } - } - } while (true); - } else { - do { - print("Would you like to (1) hunt or (2) continue on ?"); - x = skb.inputInt(screen); - if (x == 2) { - return; - } - } while (x < 1 || x > 2); - if (x == 1) { - hunt1200(j); - } - } - - } - - private void hunt1200(int j) throws NoInputException { - kq = 0; - if (b <= 39) { - print("Tough luck. You don't have enough ammo to hunt."); - kq = 1; - return; - } - m = m - 45; - final int br = shoot3870(); - if (br <= 1) { - print("Right between the eyes... you got a big one!"); - print("Full bellies tonight!"); - b = b - 10 - 4 * rnd(); - f = f + 26 + 3 * rnd(); - return; - } - if (100.0 * rnd() < 13 * br) { - print("You missed completely... and your dinner got away."); - return; - } - print("Nice shot... right on target... good eatin' tonight!"); - f = f + 24 - 2 * br; - b = b - 10 - 3 * br; - return; - } - - private void stopAtFort1100(int j) throws NoInputException { - if (t <= 0) { - print("You sing with the folks there and get a good"); - print("night's sleep, but you have no money to buy anything."); - return; - } - - while (true) { - print("What would you like to spend on each of the following"); - print("Food?"); - final double p1 = skb.inputInt(screen); - print("Ammunition?"); - final double p2 = skb.inputInt(screen); - print("Clothing?"); - final double p3 = skb.inputInt(screen); - print("Medicine and supplies?"); - final double p4 = skb.inputInt(screen); - final double p = p1 + p2 + p3 + p4; - print("The storekeeper tallies up your bill. It comes to $" + ((int) p)); - if (t >= p) { - t = t - p; - f = f + .67 * p1; - b = b + 33 * p2; - c = c + .67 * p3; - r = r + .67 * p4; - return; - } - print("Uh, oh. That's more than you have. Better start over."); - } - } - - private void printInventory3350() { - // print("+------+------+------+---------+--------------------+"); - print(); - print("| Cash | Food | Ammo | Clothes | Medicine/parts/... |"); - print("+------+------+------+---------+--------------------+"); - if (t < 0) { - t = 0; - } - if (f < 0) { - f = 0; - } - if (b < 0) { - b = 0; - } - if (c < 0) { - c = 0; - } - if (r < 0) { - r = 0; - } - print(String.format("|%5d |%5d |%5d | %5d | %5d |", (int) t, (int) f, (int) b, (int) c, (int) r)); - print("+------+------+------+---------+--------------------+"); - print(); - } - - private String whereAreWe() { - if (m < 5) { - return "on the high prairie."; - } - if (m < 200) { - return "near Independence Crossing on the Big Blue River."; - } - if (m < 350) { - return "following the Platte River."; - } - if (m < 450) { - return "near Fort Kearney."; - } - if (m < 600) { - return "following the North Platte River."; - } - if (m < 750) { - return "within sight of Chimney Rock."; - } - if (m < 850) { - return "near Fort Laramie."; - } - if (m < 1000) { - return "close upon Independence Rock."; - } - if (m < 1050) { - return "in the Big Horn Mountains."; - } - if (m < 1150) { - return "following the Green River."; - } - if (m < 1250) { - return "not too far from Fort Hall."; - } - if (m < 1400) { - return "following the Snake River."; - } - if (m < 1550) { - return "not far from Fort Boise."; - } - if (m < 1850) { - return "in the Blue Mountains."; - } - return "following the Columbia River"; - - } - - private void printInitialScenario490() { - print(" Your journey over the Oregon Trail takes place in 1847."); - print(); - print("Starting in Independence, Missouri, you plan to take your family of"); - print("five over 2040 tough miles to Oregon City."); - print(); - print(" Having saved $420 for the trip, you bought a wagon for $70 and"); - print("now have to purchase the following items :"); - print(); - print(" * Oxen (spending more will buy you a larger and better team which"); - print(" will be faster so you'll be on the trail for less time)"); - print(" * Food (you'll need ample food to keep up your strength and health)"); - print(" * Ammunition ($1 buys a belt of 50 bullets. You'll need ammo for"); - print(" hunting and for fighting off attacks by bandits and animals)"); - print(" * Clothing (you'll need warm clothes, especially when you hit the"); - print(" snow and freezing weather in the mountains)"); - print(" * Other supplies (includes medicine, first-aid supplies, tools, and"); - print(" wagon parts for unexpected emergencies)"); - print(); - print(" You can spend all your money at the start or save some to spend"); - print("at forts along the way. However, items cost more at the forts. You"); - print("can also hunt for food if you run low."); - print(); - - } - - private void initialPurchasesOfPlayer690() throws NoInputException { - if (skb.hasMore()) { - screen.clear(); - } - do { - print("How much do you want to pay for a team of oxen ?"); - a = skb.inputInt(screen); - if (a < 100) { - print("No one in town has a team that cheap"); - continue; - } - break; - } while (true); - if (a >= 151) { - print("You choose an honest dealer who tells you that $" + a + " is too much for"); - print("a team of oxen. He charges you $150 and gives you $" + (a - 150) + " change."); - a = 150; - } - do { - print(); - print("How much do you want to spend on food ?"); - f = skb.inputInt(screen); - if (f <= 13) { - print("That won't even get you to the Kansas River"); - print(" - better spend a bit more."); - continue; - } - if (a + f > 300) { - print("You wont't have any for ammo and clothes."); - continue; - } - break; - } while (true); - do { - print(); - print("How much do you want to spend on ammunition ?"); - b = skb.inputInt(screen); - if (b < 2) { - print("Better take a bit just for protection."); - continue; - } - if (a + f + b > 320) { - print("That won't leave any money for clothes."); - continue; - } - break; - } while (true); - do { - print(); - print("How much do you want to spend on clothes ?"); - c = skb.inputInt(screen); - if (c <= 24) { - print("Your family is going to be mighty cold in."); - print("the montains."); - print("Better spend a bit more."); - continue; - } - if (a + f + b + c > 345) { - print("That leaves nothing for medecine."); - continue; - } - break; - } while (true); - do { - print(); - screen.print("How much for medecine, bandage, repair parts, etc. ?"); - r = skb.inputInt(screen); - if (r <= 5) { - print("That's not at all wise."); - continue; - } - if (a + f + b + c + r > 350) { - print("You don't have that much money."); - continue; - } - break; - } while (true); - t = 350 - a - f - b - c - r; - print(); - print("You now have $" + ((int) t) + " left."); - b = 50 * b; - } - - private void initialShootingRanking920() throws NoInputException { - print(); - print("Please rank your shooting (typing) ability as follows :"); - print(" (1) Ace marksman (2) Good shot (3) Fair to middlin'"); - print(" (4) Need more practice (5) Shaky knees"); - do { - print(); - print("How do you rank yourself ?"); - dr = skb.inputInt(screen); - if (dr >= 1 && dr <= 6) { - return; - } - print("Please enter 1, 2, 3, 4 or 5."); - } while (true); - } - - private int e; - private int a; - private double b; - private double f; - private double c; - private double r; - private double t; - private int dr; - private double m; - - enum ShootingWord { - POW, BANG, BLAM, WHOP, WHAM, ZING, ZACK, ZANG, WOOSH, BAM, ZAP, BOOM, WOW, CLANG, BOING, ZOW, PANG, ZOSH, KAZ, KOOG, ZOOP, PONG, PING, BAZ, ZONG, PAM, POOM, DOING; - - public static ShootingWord safeValueOf(String s) { - try { - return valueOf(StringUtils.goUpperCase(s)); - } catch (IllegalArgumentException e) { - return null; - } - } - - public int decode(ShootingWord key) { - return (ordinal() + key.ordinal()) % NB_WORDS; - } - - public ShootingWord encode(int v) { - v = v - this.ordinal(); - if (v < 0) { - v += NB_WORDS; - } - return ShootingWord.values()[v]; - } - } - - private static int NB_WORDS = ShootingWord.values().length; - - private int getTime() { - return (int) ((System.currentTimeMillis() / 1000L) % NB_WORDS); - } - - private int shoot3870() throws NoInputException { - final int time1 = getTime(); - final ShootingWord word1Printed = ShootingWord.values()[time1]; - if (skb.hasMore() == false) { - print("Type: " + word1Printed); - } - final String typed1 = skb.input(screen); - ShootingWord wordType1 = ShootingWord.safeValueOf(typed1); - final int delta; - if (wordType1 == null) { - delta = NB_WORDS - 1; - wordType1 = ShootingWord.values()[NB_WORDS - 1]; - } else { - delta = protect(getTime() - wordType1.ordinal()); - } - // print("delta="+delta); - final ShootingWord word2 = wordType1.encode(delta); - if (skb.hasMore() == false) { - print("Type: " + word2); - } - final String typed2 = skb.input(screen); - final ShootingWord wordType2 = ShootingWord.safeValueOf(typed2); - final int duration = wordType2 == null ? NB_WORDS : wordType1.decode(wordType2) - dr; - // print("duration=" + duration); - if (duration < 0) { - return 0; - } - return duration; - } - - private int protect(int v) { - while (v >= NB_WORDS) { - v -= NB_WORDS; - } - while (v < 0) { - v += NB_WORDS; - } - return v; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/old/OregonBasicGame.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/old/OregonBasicGame.java deleted file mode 100755 index abf45be..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/old/OregonBasicGame.java +++ /dev/null @@ -1,936 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4639 $ - * - */ -package net.sourceforge.plantuml.oregon; - -import java.util.Random; - -public class OregonBasicGame implements BasicGame { - - private Screen screen; - private SmartKeyboard skb; - private Random rnd; - - private int ks; - private int kh; - private int kp; - private int kb; - private int km; - private int kq; - - private double ma; - - private final String da[] = new String[] { "March 29", "April 12", "April 26", "May 10", "May 24", "June 7", - "June 21", "July 5", "July 19", "August 2", "August 16", "August 31", "September 13", "September 27", - "October 11", "October 25", "November 8", "November 22", "December 6", "December 20" }; - - private final int ep[] = new int[] { 6, 11, 13, 15, 17, 22, 32, 35, 37, 42, 44, 54, 64, 69, 95 }; - - public Screen getScreen() { - return screen; - } - - private void print(String s) { - screen.print(s); - } - - private void printb(String s) { - screen.print("** " + s + " **"); - } - - private void print() { - screen.print(); - } - - public void run(Keyboard keyboard) throws NoInputException { - if (screen != null) { - throw new IllegalStateException(); - } - screen = new Screen(); - skb = new SmartKeyboard(keyboard); - init(); - } - - private double rnd() { - if (this.rnd == null) { - this.rnd = new Random(skb.getHistory().hashCode()); - } - return rnd.nextDouble(); - } - - private void init() throws NoInputException { - printInitialScenario490(); - initialPurchasesOfPlayer690(); - initialShootingRanking920(); - screen.clear(); - print("** Your trip is about to begin... **"); - print(); - for (int j = 0; j < 20; j++) { - if (m > 2039) { - madeIt3190(j); - break; - } - print("Monday, " + da[j] + ", 1847. You are " + whereAreWe()); - print(); - if (f < 6) { - print("** You're low on food. Better buy some or go hunting soon. **"); - print(); - } - if (ks == 1 || kh == 1) { - t = t - 10; - if (t < 0) { - needDoctorBadly3010(j); - } - print("Doctor charged $10 for his services"); - print("to treat your " + (ks == 1 ? "illness." : "injuries.")); - } - // MP flag to be done? - - m = (int) (m + .5); - print("Total mileage to date is: " + ((int) m) + ""); - m += 200 + (a - 110) / 2.5 + 10 * rnd(); - print(); - // Calculate how far we travel in 2 weeks - print("Here's what you now have (no. of bullets, $ worth of other items) :"); - printInventory3350(); - question1000(j); - eating1310(j); - screen.clear(); - riders1390(j); - // print(); - events1800(j); - // print(); - montains2640(j); - if (skb.hasMore()) { - screen.clear(); - } - } - } - - private void events1800(int j) throws NoInputException { - final int rn = (int) (100.0 * rnd()); - for (int i = 0; i < ep.length; i++) { - if (rn <= ep[i]) { - execEvent(i, j); - return; - } - } - execEvent(ep.length, j); - } - - private void execEvent(int i, int j) throws NoInputException { - switch (i) { - case 0: - printb("Your wagon breaks down. It costs you time and supplies to fix it."); - m = m - 15 - 5 * rnd(); - r = r - 4; - break; - case 1: - printb("An ox gores your leg. That slows you down for the rest of the trip."); - m = m - 25; - a = a - 10; - break; - case 2: - printb("Bad luck... your daughter breaks her arm. You must stop and"); - printb("make a splint and sling with some of your medical supplies."); - m = m - 5 - 4 * rnd(); - r = r - 1 - 2 * rnd(); - break; - case 3: - printb("An ox wanders off and you have to spend time looking for it."); - m = m - 17; - break; - case 4: - printb("Your son gets lost and you spend half a day searching for him."); - m = m - 10; - break; - case 5: - printb("Nothing but contaminated and stagnant water near the trail."); - printb("You lose time looking for a clean spring or creek."); - m = m - 2 - 10 * rnd(); - break; - - case 6: - if (m > 950) { - int c1 = 0; - if (c < 11 + 2 * rnd()) { - c1 = 1; - } - printb("Cold weather... Brrrrrrr! ... You " + (c1 == 1 ? "dont't " : "") - + "have enough clothing to keep warm."); - if (c1 == 1) { - dealWithIllness2880(j); - } - } else { - printb("Heavy rains. Traveling is slow in the mud and you break your spare"); - printb("ox yoke using it to pry your wagon out of the mud. Worse yet, some"); - printb("of your ammo is damaged by the water."); - m = m - 5 - 10 * rnd(); - r = r - 7; - b = b - 400; - f = f - 5; - } - break; - - case 7: - printb("Bandits attacking!"); - final int br1 = shoot3870(); - b = b - 20 * br1; - if (b > 0) { - if (br1 <= 1) { - print("That was the quickest draw outside of Dodge City."); - print("You got at least one and drove 'em off."); - return; - } - } else { - t = t / 3; - print("You try to drive them off but you run out of bullets."); - print("They grab as much cash as they can find."); - - } - print("You get shot in the leg -"); - kh = 1; - print("and they grab one of your oxen."); - a = a - 10; - r = r - 2; - print("Better have a doc look at your leg... and soon!"); - break; - - case 8: - printb("You have a fire in your wagon. Food and supplies are damaged."); - m = m - 15; - f = f - 20; - b = b - 400; - r = r - 2 * 6 * rnd(); - break; - - case 9: - printb("You lose your way in heavy fog. Time lost regaining the trail."); - m = m - 10 - 5 * rnd(); - break; - - case 10: - printb("You come upon a rattlesnake and before you are able to get your gun"); - printb("out, it bites you."); - b = b - 10; - r = r - 2; - if (r < 0) { - printb("You have no medical supplies left, and you die of poison."); - die3060(j); - - } - print("Fortunately, you acted quickly, sucked out the poison, and"); - print("treated the wound. It is painful, but you'll survive."); - break; - - case 11: - print("Your wagon gets swamped fording a river; you lose food and clothes."); - m = m - 20 - 20 * rnd(); - f = f - 15; - c = c - 10; - break; - - case 12: - printb("You're sound asleep and you hear a noise... get up to investigate."); - printb("It's wild animals! They attack you!"); - final int br2 = shoot3870(); - if (b <= 39) { - print("You're almost out of ammo; can't reach more."); - print("The wolves come at you biting and clawing."); - kh = 1; - die3030(j); - } - if (br2 <= 2) { - print("Nice shooting, pardner... They didn't get much."); - } else { - print("Kind of slow on the draw. The wolves got at your food and clothes."); - b = b - 20 * br2; - c = c - 2 * br2; - f = f - 4 * br2; - } - break; - - case 13: - printb("You're caught in a fierce hailstorm; ammo and supplies are damaged."); - m = m - 5 - 10 * rnd(); - b = b - 150; - r = r - 2 - 2 * rnd(); - break; - - case 14: - if (e == 1) { - dealWithIllness2880(j); - } else if (e == 2 && rnd() > .25) { - dealWithIllness2880(j); - } else if (e == 3 && rnd() > .5) { - dealWithIllness2880(j); - } - break; - - case 15: - printb("Helpful Indians show you where to find more food."); - f = f + 7; - break; - - default: - printb("EVENT " + i); - } - print(); - - } - - private void madeIt3190(int j) throws NoInputException { - final double ml = (2040 - ma) / (m - ma); - f = f + (1 - ml) * (8 + 5 * e); - print("You finally arrived at Oregon City after 2040 long miles."); - print("You're exhausted and haggard, but you made it! A real pioneer!"); - final int d = (int) (14 * (j + ml)); - final int dm = (int) (d / 30.5); - final int dd = (int) (d - 30.5 * dm); - print("You've been on the trail for " + dm + " months and " + dd + " days."); - print("You have few supplies remaining :"); - printInventory3350(); - print(); - print("President James A. Polk sends you his heartiest"); - - print("congratulations and wishes you a prosperous life in your new home."); - throw new NoInputException(); - } - - private boolean riders1390(int j) throws NoInputException { - final double value = (Math.pow(m / 100 - 4, 2) + 72) / (Math.pow(m / 100 - 4, 2) + 12) - 1; - final double random = 10.0 * rnd(); - if (random > value) { - return false; - } - int gh = 0; - if (rnd() > .2) { - gh = 1; - } - print(); - print("Riders ahead! They " + (gh == 1 ? "don't " : "") + "look hostile."); - int gt; - do { - print("You can (1) run, (2) attack, (3) ignore them, or (4) circle wagons."); - gt = skb.inputInt(screen); - } while (gt < 0 || gt > 4); - if (rnd() < .2) { - gh = 1 - gh; - } - if (gh == 1) { - if (gt == 1) { - m = m + 15; - a = a - 5; - } else if (gt == 2) { - m = m - 5; - b = b - 100; - } else if (gt == 4) { - m = m - 20; - } - print("Riders were friendly, but check for possible losses."); - return true; - } - if (gt == 1) { - m = m + 20; - r = r - 7; - b = b - 150; - a = a - 20; - } else if (gt == 2) { - final int br = shoot3870(); - b = b - br * 40 - 80; - riderShoot(br); - } else if (gt == 3) { - if (rnd() > .8) { - print("They did not attack. Whew!"); - return true; - } - b = b - 150; - r = r - 7; - } else { - assert gt == 4; - final int br = shoot3870(); - b = b - br * 30 - 80; - m = m - 25; - riderShoot(br); - } - print("Riders were hostile. Better check for losses!"); - if (b >= 0) { - return true; - } - print(); - print("Oh, my gosh!"); - print("They're coming back and you're out of ammo! Your dreams turn to"); - print("dust as you and your family are massacred on the prairie."); - print3110(j); - return true; - - } - - private void riderShoot(final int br) { - if (br <= 1) { - print("Nice shooting - you drove them off."); - } else if (br <= 4) { - print("Kind of slow with your Colt .45."); - } else { - print("Pretty slow on the draw, partner. You got a nasty flesh wound."); - kh = 1; - print("You'll have to see the doc soon as you can."); - } - } - - private void montains2640(int j) throws NoInputException { - if (m <= 975) { - return; - } - final double mm = m / 100.0 - 15; - if (10 * rnd() > 9 - (mm * mm + 72) / (mm * mm + 12)) { - southPass2750(j); - return; - } - print("You're in rugged mountain country."); - if (rnd() <= .1) { - print("You get lost and lose valuable time trying to find the trail."); - m = m - 60; - southPass2750(j); - return; - } - if (rnd() > .11) { - print("The going is really slow; oxen are very tired."); - m = m - 45 - 50 * rnd(); - } else { - print("Trail cave in damages your wagon. You lose time and supplies."); - m = m - 20 - 30 * rnd(); - b = b - 200; - r = r - 3; - } - southPass2750(j); - - } - - private void southPass2750(int j) throws NoInputException { - if (kp == 0) { - kp = 1; - if (rnd() < .8) { - blizzard2840(j); - return; - } - print("You made it safely through the South Pass....no snow!"); - } - if (m < 1700) { - return; - } - if (km == 0) { - km = 1; - if (rnd() < .7) { - blizzard2840(j); - } - } - - } - - private void blizzard2840(int j) throws NoInputException { - print("Blizzard in the mountain pass. Going is slow; supplies are lost."); - kb = 1; - m = m - 30 - 40 * rnd(); - f = f - 12; - b = b - 200; - r = r - 5; - if (c < 18 + 2 * rnd()) { - dealWithIllness2880(j); - } - } - - private void dealWithIllness2880(int j) throws NoInputException { - if (100 * rnd() < 10 + 35 * (e - 1)) { - print("Mild illness. Your own medicine will cure it."); - m -= 5; - r -= 1; - } else if (100 * rnd() < 100.0 - 40.0 / Math.pow(4.0, e - 1)) { - print("The whole family is sick. Your medicine will probably work okay."); - m -= 5; - r -= 2.5; - } else { - print("Serious illness in the family. You'll have to stop and see a doctor"); - print("soon. For now, your medicine will work."); - r -= 5; - ks = 1; - } - if (r <= 0) { - print("...if only you had enough."); - outOfMedicalSupplies3020(j); - } - - } - - private void eating1310(int j) throws NoInputException { - if (f < 5) { - die3000(j); - return; - } - do { - print("Do you want to eat (1) poorly, (2) moderately or (3) well ?"); - e = skb.inputInt(screen); - if (e < 1 || e > 3) { - print("Enter 1, 2, or 3, please."); - break; - } - final int ee = (int) (4 + 2.5 * e); - if (e == 1 && ee > f) { - f = 0; - return; - } - if (ee > f) { - print("You don't have enough to eat that well."); - break; - } - f -= ee; - return; - } while (true); - - } - - private void needDoctorBadly3010(int j) throws NoInputException { - print("You need a doctor badly but can't afford one."); - die3030(j); - } - - private void outOfMedicalSupplies3020(int j) throws NoInputException { - print("You have run out of all medical supplies."); - print(); - die3030(j); - } - - private void die3000(int j) throws NoInputException { - screen.clear(); - print("You run out of food and starve to death."); - print(); - print3110(j); - } - - private void die3030(int j) throws NoInputException { - print("The wilderness is unforgiving and you die of " + (kh == 1 ? "your injuries" : "pneumonia")); - die3060(j); - } - - private void die3060(int j) throws NoInputException { - print("Your family tries to push on, but finds the going too rough"); - print(" without you."); - print3110(j); - } - - private void print3110(int j) throws NoInputException { - print("Some travelers find the bodies of you and your"); - print("family the following spring. They give you a decent"); - print("burial and notify your next of kin."); - print(); - print("At the time of your unfortunate demise, you had been on the trail"); - final int d = 14 * j; - final int dm = (int) (d / 30.5); - final int dd = (int) (d - 30.5 * dm); - print("for " + dm + " months and " + dd + " days and had covered " + (int) ((m + 70)) + " miles."); - print(); - print("You had a few supplies left :"); - printInventory3350(); - throw new NoInputException(); - } - - private void question1000(int j) throws NoInputException { - int x; - if (j % 2 == 1) { - do { - print("Want to (1) stop at the next fort, (2) hunt, or (3) push on ?"); - x = skb.inputInt(screen); - if (x == 3) { - return; - } - if (x == 1) { - stopAtFort1100(j); - return; - } - if (x == 2) { - hunt1200(j); - if (kq == 0) { - return; - } - } - } while (true); - } else { - do { - print("Would you like to (1) hunt or (2) continue on ?"); - x = skb.inputInt(screen); - if (x == 2) { - return; - } - } while (x < 1 || x > 2); - if (x == 1) { - hunt1200(j); - } - } - - } - - private void hunt1200(int j) throws NoInputException { - kq = 0; - if (b <= 39) { - print("Tough luck. You don't have enough ammo to hunt."); - kq = 1; - return; - } - m = m - 45; - final int br = shoot3870(); - if (br <= 1) { - print("Right between the eyes... you got a big one!"); - print("Full bellies tonight!"); - b = b - 10 - 4 * rnd(); - f = f + 26 + 3 * rnd(); - return; - } - if (100.0 * rnd() < 13 * br) { - print("You missed completely... and your dinner got away."); - return; - } - print("Nice shot... right on target... good eatin' tonight!"); - f = f + 24 - 2 * br; - b = b - 10 - 3 * br; - return; - } - - private void stopAtFort1100(int j) throws NoInputException { - if (t <= 0) { - print("You sing with the folks there and get a good"); - print("night's sleep, but you have no money to buy anything."); - return; - } - - while (true) { - print("What would you like to spend on each of the following"); - print("Food?"); - final double p1 = skb.inputInt(screen); - print("Ammunition?"); - final double p2 = skb.inputInt(screen); - print("Clothing?"); - final double p3 = skb.inputInt(screen); - print("Medicine and supplies?"); - final double p4 = skb.inputInt(screen); - final double p = p1 + p2 + p3 + p4; - print("The storekeeper tallies up your bill. It comes to $" + ((int) p)); - if (t >= p) { - t = t - p; - f = f + .67 * p1; - b = b + 33 * p2; - c = c + .67 * p3; - r = r + .67 * p4; - return; - } - print("Uh, oh. That's more than you have. Better start over."); - } - } - - private void printInventory3350() { - // print("+------+------+------+---------+--------------------+"); - print(); - print("| Cash | Food | Ammo | Clothes | Medicine/parts/... |"); - print("+------+------+------+---------+--------------------+"); - if (t < 0) { - t = 0; - } - if (f < 0) { - f = 0; - } - if (b < 0) { - b = 0; - } - if (c < 0) { - c = 0; - } - if (r < 0) { - r = 0; - } - print(String.format("|%5d |%5d |%5d | %5d | %5d |", (int) t, (int) f, (int) b, (int) c, (int) r)); - print("+------+------+------+---------+--------------------+"); - print(); - } - - private String whereAreWe() { - if (m < 5) { - return "on the high prairie."; - } - if (m < 200) { - return "near Independence Crossing on the Big Blue River."; - } - if (m < 350) { - return "following the Platte River."; - } - if (m < 450) { - return "near Fort Kearney."; - } - if (m < 600) { - return "following the North Platte River."; - } - if (m < 750) { - return "within sight of Chimney Rock."; - } - if (m < 850) { - return "near Fort Laramie."; - } - if (m < 1000) { - return "close upon Independence Rock."; - } - if (m < 1050) { - return "in the Big Horn Mountains."; - } - if (m < 1150) { - return "following the Green River."; - } - if (m < 1250) { - return "not too far from Fort Hall."; - } - if (m < 1400) { - return "following the Snake River."; - } - if (m < 1550) { - return "not far from Fort Boise."; - } - if (m < 1850) { - return "in the Blue Mountains."; - } - return "following the Columbia River"; - - } - - private void printInitialScenario490() { - print(" Your journey over the Oregon Trail takes place in 1847."); - print(); - print("Starting in Independence, Missouri, you plan to take your family of"); - print("five over 2040 tough miles to Oregon City."); - print(); - print(" Having saved $420 for the trip, you bought a wagon for $70 and"); - print("now have to purchase the following items :"); - print(); - print(" * Oxen (spending more will buy you a larger and better team which"); - print(" will be faster so you'll be on the trail for less time)"); - print(" * Food (you'll need ample food to keep up your strength and health)"); - print(" * Ammunition ($1 buys a belt of 50 bullets. You'll need ammo for"); - print(" hunting and for fighting off attacks by bandits and animals)"); - print(" * Clothing (you'll need warm clothes, especially when you hit the"); - print(" snow and freezing weather in the mountains)"); - print(" * Other supplies (includes medicine, first-aid supplies, tools, and"); - print(" wagon parts for unexpected emergencies)"); - print(); - print(" You can spend all your money at the start or save some to spend"); - print("at forts along the way. However, items cost more at the forts. You"); - print("can also hunt for food if you run low."); - print(); - - } - - private void initialPurchasesOfPlayer690() throws NoInputException { - if (skb.hasMore()) { - screen.clear(); - } - do { - print("How much do you want to pay for a team of oxen ?"); - a = skb.inputInt(screen); - if (a < 100) { - print("No one in town has a team that cheap"); - continue; - } - break; - } while (true); - if (a >= 151) { - print("You choose an honest dealer who tells you that $" + a + " is too much for"); - print("a team of oxen. He charges you $150 and gives you $" + (a - 150) + " change."); - a = 150; - } - do { - print(); - print("How much do you want to spend on food ?"); - f = skb.inputInt(screen); - if (f <= 13) { - print("That won't even get you to the Kansas River"); - print(" - better spend a bit more."); - continue; - } - if (a + f > 300) { - print("You wont't have any for ammo and clothes."); - continue; - } - break; - } while (true); - do { - print(); - print("How much do you want to spend on ammunition ?"); - b = skb.inputInt(screen); - if (b < 2) { - print("Better take a bit just for protection."); - continue; - } - if (a + f + b > 320) { - print("That won't leave any money for clothes."); - continue; - } - break; - } while (true); - do { - print(); - print("How much do you want to spend on clothes ?"); - c = skb.inputInt(screen); - if (c <= 24) { - print("Your family is going to be mighty cold in."); - print("the montains."); - print("Better spend a bit more."); - continue; - } - if (a + f + b + c > 345) { - print("That leaves nothing for medecine."); - continue; - } - break; - } while (true); - do { - print(); - screen.print("How much for medecine, bandage, repair parts, etc. ?"); - r = skb.inputInt(screen); - if (r <= 5) { - print("That's not at all wise."); - continue; - } - if (a + f + b + c + r > 350) { - print("You don't have that much money."); - continue; - } - break; - } while (true); - t = 350 - a - f - b - c - r; - print(); - print("You now have $" + ((int) t) + " left."); - b = 50 * b; - } - - private void initialShootingRanking920() throws NoInputException { - print(); - print("Please rank your shooting (typing) ability as follows :"); - print(" (1) Ace marksman (2) Good shot (3) Fair to middlin'"); - print(" (4) Need more practice (5) Shaky knees"); - do { - print(); - print("How do you rank yourself ?"); - dr = skb.inputInt(screen); - if (dr >= 1 && dr <= 6) { - return; - } - print("Please enter 1, 2, 3, 4 or 5."); - } while (true); - } - - private int e; - private int a; - private double b; - private double f; - private double c; - private double r; - private double t; - private int dr; - private double m; - - enum ShootingWord { - POW, BANG, BLAM, WHOP, WHAM, ZING, ZACK, ZANG, WOOSH, BAM, ZAP, BOOM, WOW, CLANG, BOING, ZOW, PANG, ZOSH, KAZ, KOOG, ZOOP, PONG, PING, BAZ, ZONG, PAM, POOM, DOING; - - public static ShootingWord safeValueOf(String s) { - try { - return valueOf(s.toUpperCase()); - } catch (IllegalArgumentException e) { - return null; - } - } - - public int decode(ShootingWord key) { - return (ordinal() + key.ordinal()) % NB_WORDS; - } - - public ShootingWord encode(int v) { - v = v - this.ordinal(); - if (v < 0) { - v += NB_WORDS; - } - return ShootingWord.values()[v]; - } - } - - private static int NB_WORDS = ShootingWord.values().length; - - private int getTime() { - return (int) ((System.currentTimeMillis() / 1000L) % NB_WORDS); - } - - private int shoot3870() throws NoInputException { - final int time1 = getTime(); - final ShootingWord word1Printed = ShootingWord.values()[time1]; - if (skb.hasMore() == false) { - print("Type: " + word1Printed); - } - final String typed1 = skb.input(screen); - ShootingWord wordType1 = ShootingWord.safeValueOf(typed1); - final int delta; - if (wordType1 == null) { - delta = NB_WORDS - 1; - wordType1 = ShootingWord.values()[NB_WORDS - 1]; - } else { - delta = protect(getTime() - wordType1.ordinal()); - } - // print("delta="+delta); - final ShootingWord word2 = wordType1.encode(delta); - if (skb.hasMore() == false) { - print("Type: " + word2); - } - final String typed2 = skb.input(screen); - final ShootingWord wordType2 = ShootingWord.safeValueOf(typed2); - final int duration = wordType2 == null ? NB_WORDS : wordType1.decode(wordType2) - dr; - // print("duration=" + duration); - if (duration < 0) { - return 0; - } - return duration; - } - - private int protect(int v) { - while (v >= NB_WORDS) { - v -= NB_WORDS; - } - while (v < 0) { - v += NB_WORDS; - } - return v; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/pair.info deleted file mode 100755 index 3068c1d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22426/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22426 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/oregon/OregonBasicGame.java -FixedFilePath:src/net/sourceforge/plantuml/oregon/OregonBasicGame.java -StartLineNum:871 -EndLineNum:871 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/diff.diff deleted file mode 100755 index 82145ec..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/cucadiagram/dot/GraphvizWindows.java b/src/net/sourceforge/plantuml/cucadiagram/dot/GraphvizWindows.java -index e8b3d285..0753edeb 100644 ---- a/src/net/sourceforge/plantuml/cucadiagram/dot/GraphvizWindows.java -+++ b/src/net/sourceforge/plantuml/cucadiagram/dot/GraphvizWindows.java -@@ -31 +31 @@ -- * Revision $Revision: 14616 $ -+ * Revision $Revision: 14727 $ -@@ -41,0 +42,2 @@ import java.util.List; -+import net.sourceforge.plantuml.StringUtils; -+ -@@ -68 +70 @@ class GraphvizWindows extends AbstractGraphviz { -- return pathname.isDirectory() && pathname.getName().toLowerCase().startsWith("graphviz"); -+ return pathname.isDirectory() && StringUtils.goLowerCase(pathname.getName()).startsWith("graphviz"); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/new/GraphvizWindows.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/new/GraphvizWindows.java deleted file mode 100755 index 0753ede..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/new/GraphvizWindows.java +++ /dev/null @@ -1,93 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14727 $ - * - */ -package net.sourceforge.plantuml.cucadiagram.dot; - -import java.io.File; -import java.io.FileFilter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import net.sourceforge.plantuml.StringUtils; - -class GraphvizWindows extends AbstractGraphviz { - - @Override - protected File specificDotExe() { - final File result = searchInDir(new File("c:/Program Files")); - if (result != null) { - return result; - } - final File result86 = searchInDir(new File("c:/Program Files (x86)")); - if (result86 != null) { - return result86; - } - final File resultEclipse = searchInDir(new File("c:/eclipse/graphviz")); - if (resultEclipse != null) { - return resultEclipse; - } - return null; - } - - private static File searchInDir(final File programFile) { - if (programFile.exists() == false || programFile.isDirectory() == false) { - return null; - } - final List dots = new ArrayList(); - for (File f : programFile.listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.isDirectory() && StringUtils.goLowerCase(pathname.getName()).startsWith("graphviz"); - } - })) { - final File result = new File(new File(f, "bin"), "dot.exe"); - if (result.exists() && result.canRead()) { - dots.add(result.getAbsoluteFile()); - } - } - return higherVersion(dots); - } - - static File higherVersion(List dots) { - if (dots.size() == 0) { - return null; - } - Collections.sort(dots, Collections.reverseOrder()); - return dots.get(0); - } - - GraphvizWindows(String dotString, String... type) { - super(dotString, type); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/old/GraphvizWindows.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/old/GraphvizWindows.java deleted file mode 100755 index e8b3d28..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/old/GraphvizWindows.java +++ /dev/null @@ -1,91 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14616 $ - * - */ -package net.sourceforge.plantuml.cucadiagram.dot; - -import java.io.File; -import java.io.FileFilter; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -class GraphvizWindows extends AbstractGraphviz { - - @Override - protected File specificDotExe() { - final File result = searchInDir(new File("c:/Program Files")); - if (result != null) { - return result; - } - final File result86 = searchInDir(new File("c:/Program Files (x86)")); - if (result86 != null) { - return result86; - } - final File resultEclipse = searchInDir(new File("c:/eclipse/graphviz")); - if (resultEclipse != null) { - return resultEclipse; - } - return null; - } - - private static File searchInDir(final File programFile) { - if (programFile.exists() == false || programFile.isDirectory() == false) { - return null; - } - final List dots = new ArrayList(); - for (File f : programFile.listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.isDirectory() && pathname.getName().toLowerCase().startsWith("graphviz"); - } - })) { - final File result = new File(new File(f, "bin"), "dot.exe"); - if (result.exists() && result.canRead()) { - dots.add(result.getAbsoluteFile()); - } - } - return higherVersion(dots); - } - - static File higherVersion(List dots) { - if (dots.size() == 0) { - return null; - } - Collections.sort(dots, Collections.reverseOrder()); - return dots.get(0); - } - - GraphvizWindows(String dotString, String... type) { - super(dotString, type); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/pair.info deleted file mode 100755 index 734cb24..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22444/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22444 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/cucadiagram/dot/GraphvizWindows.java -FixedFilePath:src/net/sourceforge/plantuml/cucadiagram/dot/GraphvizWindows.java -StartLineNum:68 -EndLineNum:68 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/diff.diff deleted file mode 100755 index ce10e11..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/classdiagram/command/CommandImport.java b/src/net/sourceforge/plantuml/classdiagram/command/CommandImport.java -index 6f01acc5..2a830bb0 100644 ---- a/src/net/sourceforge/plantuml/classdiagram/command/CommandImport.java -+++ b/src/net/sourceforge/plantuml/classdiagram/command/CommandImport.java -@@ -31 +31 @@ -- * Revision $Revision: 14056 $ -+ * Revision $Revision: 14727 $ -@@ -40,0 +41 @@ import net.sourceforge.plantuml.FileSystem; -+import net.sourceforge.plantuml.StringUtils; -@@ -82 +83 @@ public class CommandImport extends SingleLineCommand { -- if (f.getName().toLowerCase().endsWith(".java")) { -+ if (StringUtils.goLowerCase(f.getName()).endsWith(".java")) { -@@ -85 +86 @@ public class CommandImport extends SingleLineCommand { -- // if (f.getName().toLowerCase().endsWith(".sql")) { -+ // if (f.getName().goLowerCase().endsWith(".sql")) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/new/CommandImport.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/new/CommandImport.java deleted file mode 100755 index 2a830bb..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/new/CommandImport.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14727 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -import net.sourceforge.plantuml.FileSystem; -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.classdiagram.ClassDiagram; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand; -import net.sourceforge.plantuml.cucadiagram.Code; -import net.sourceforge.plantuml.cucadiagram.IEntity; -import net.sourceforge.plantuml.cucadiagram.Link; -import net.sourceforge.plantuml.cucadiagram.LinkDecor; -import net.sourceforge.plantuml.cucadiagram.LinkType; - -public class CommandImport extends SingleLineCommand { - - public CommandImport() { - super("(?i)^import[%s]+[%g]?([^%g]+)[%g]?$"); - } - - @Override - protected CommandExecutionResult executeArg(ClassDiagram classDiagram, List arg) { - final String arg0 = arg.get(0); - try { - final File f = FileSystem.getInstance().getFile(arg0); - - if (f.isFile()) { - includeSimpleFile(classDiagram, f); - } else if (f.isDirectory()) { - includeDirectory(classDiagram, f); - } - } catch (IOException e) { - e.printStackTrace(); - return CommandExecutionResult.error("IO error " + e); - } - return CommandExecutionResult.ok(); - } - - private void includeDirectory(ClassDiagram classDiagram, File dir) throws IOException { - for (File f : dir.listFiles()) { - includeSimpleFile(classDiagram, f); - } - - } - - private void includeSimpleFile(ClassDiagram classDiagram, File f) throws IOException { - if (StringUtils.goLowerCase(f.getName()).endsWith(".java")) { - includeFileJava(classDiagram, f); - } - // if (f.getName().goLowerCase().endsWith(".sql")) { - // includeFileSql(f); - // } - } - - private void includeFileJava(ClassDiagram classDiagram, final File f) throws IOException { - final JavaFile javaFile = new JavaFile(f); - for (JavaClass cl : javaFile.getJavaClasses()) { - final Code name = Code.of(cl.getName()); - final IEntity ent1 = classDiagram.getOrCreateLeaf(name, cl.getType(), null); - - for (String p : cl.getParents()) { - final IEntity ent2 = classDiagram.getOrCreateLeaf(Code.of(p), cl.getParentType(), null); - final Link link = new Link(ent2, ent1, new LinkType(LinkDecor.NONE, LinkDecor.EXTENDS), null, 2); - classDiagram.addLink(link); - } - } - } - - // private void includeFileSql(final File f) throws IOException { - // new SqlImporter(getSystem(), f).process(); - // } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/old/CommandImport.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/old/CommandImport.java deleted file mode 100755 index 6f01acc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/old/CommandImport.java +++ /dev/null @@ -1,108 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14056 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -import net.sourceforge.plantuml.FileSystem; -import net.sourceforge.plantuml.classdiagram.ClassDiagram; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand; -import net.sourceforge.plantuml.cucadiagram.Code; -import net.sourceforge.plantuml.cucadiagram.IEntity; -import net.sourceforge.plantuml.cucadiagram.Link; -import net.sourceforge.plantuml.cucadiagram.LinkDecor; -import net.sourceforge.plantuml.cucadiagram.LinkType; - -public class CommandImport extends SingleLineCommand { - - public CommandImport() { - super("(?i)^import[%s]+[%g]?([^%g]+)[%g]?$"); - } - - @Override - protected CommandExecutionResult executeArg(ClassDiagram classDiagram, List arg) { - final String arg0 = arg.get(0); - try { - final File f = FileSystem.getInstance().getFile(arg0); - - if (f.isFile()) { - includeSimpleFile(classDiagram, f); - } else if (f.isDirectory()) { - includeDirectory(classDiagram, f); - } - } catch (IOException e) { - e.printStackTrace(); - return CommandExecutionResult.error("IO error " + e); - } - return CommandExecutionResult.ok(); - } - - private void includeDirectory(ClassDiagram classDiagram, File dir) throws IOException { - for (File f : dir.listFiles()) { - includeSimpleFile(classDiagram, f); - } - - } - - private void includeSimpleFile(ClassDiagram classDiagram, File f) throws IOException { - if (f.getName().toLowerCase().endsWith(".java")) { - includeFileJava(classDiagram, f); - } - // if (f.getName().toLowerCase().endsWith(".sql")) { - // includeFileSql(f); - // } - } - - private void includeFileJava(ClassDiagram classDiagram, final File f) throws IOException { - final JavaFile javaFile = new JavaFile(f); - for (JavaClass cl : javaFile.getJavaClasses()) { - final Code name = Code.of(cl.getName()); - final IEntity ent1 = classDiagram.getOrCreateLeaf(name, cl.getType(), null); - - for (String p : cl.getParents()) { - final IEntity ent2 = classDiagram.getOrCreateLeaf(Code.of(p), cl.getParentType(), null); - final Link link = new Link(ent2, ent1, new LinkType(LinkDecor.NONE, LinkDecor.EXTENDS), null, 2); - classDiagram.addLink(link); - } - } - } - - // private void includeFileSql(final File f) throws IOException { - // new SqlImporter(getSystem(), f).process(); - // } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/pair.info deleted file mode 100755 index 186b9a0..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22448/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22448 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandImport.java -FixedFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandImport.java -StartLineNum:82 -EndLineNum:82 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/diff.diff deleted file mode 100755 index 29624c6..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/mjpeg/MJPEGGenerator.java b/src/net/sourceforge/plantuml/mjpeg/MJPEGGenerator.java -index 8cd9ca99..30651321 100644 ---- a/src/net/sourceforge/plantuml/mjpeg/MJPEGGenerator.java -+++ b/src/net/sourceforge/plantuml/mjpeg/MJPEGGenerator.java -@@ -28,0 +29,2 @@ import javax.swing.ImageIcon; -+import net.sourceforge.plantuml.StringUtils; -+ -@@ -555 +557 @@ public class MJPEGGenerator -- if(name.toLowerCase().endsWith("jpg")) -+ if(StringUtils.goLowerCase(name).endsWith("jpg")) \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/new/MJPEGGenerator.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/new/MJPEGGenerator.java deleted file mode 100755 index 3065132..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/new/MJPEGGenerator.java +++ /dev/null @@ -1,575 +0,0 @@ -/* - * MJPEGGenerator.java - * - * Created on April 17, 2006, 11:48 PM - * - * To change this template, choose Tools | Options and locate the template under - * the Source Creation and Management node. Right-click the template and choose - * Open. You can then make changes to the template in the Source Editor. - */ - -package net.sourceforge.plantuml.mjpeg; - -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.channels.FileChannel; -import java.util.ArrayList; -import java.util.Arrays; - -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; - -import net.sourceforge.plantuml.StringUtils; - -/** - * - * @author monceaux - */ -public class MJPEGGenerator -{ - /* - * Info needed for MJPEG AVI - * - * - size of file minus "RIFF & 4 byte file size" - * - */ - - int width = 0; - int height = 0; - double framerate = 0; - int numFrames = 0; - File aviFile = null; - FileOutputStream aviOutput = null; - FileChannel aviChannel = null; - - long riffOffset = 0; - long aviMovieOffset = 0; - - AVIIndexList indexlist = null; - - /** Creates a new instance of MJPEGGenerator */ - public MJPEGGenerator(File aviFile, int width, int height, double framerate, int numFrames) throws IOException - { - this.aviFile = aviFile; - this.width = width; - this.height = height; - this.framerate = framerate; - this.numFrames = numFrames; - aviOutput = new FileOutputStream(aviFile); - aviChannel = aviOutput.getChannel(); - - RIFFHeader rh = new RIFFHeader(); - aviOutput.write(rh.toBytes()); - aviOutput.write(new AVIMainHeader().toBytes()); - aviOutput.write(new AVIStreamList().toBytes()); - aviOutput.write(new AVIStreamHeader().toBytes()); - aviOutput.write(new AVIStreamFormat().toBytes()); - aviOutput.write(new AVIJunk().toBytes()); - aviMovieOffset = aviChannel.position(); - aviOutput.write(new AVIMovieList().toBytes()); - indexlist = new AVIIndexList(); - } - - public void addImage(Image image) throws IOException - { - byte[] fcc = new byte[]{'0','0','d','b'}; - byte[] imagedata = writeImageToBytes(image); - int useLength = imagedata.length; - long position = aviChannel.position(); - int extra = (useLength+(int)position) % 4; - if(extra > 0) - useLength = useLength + extra; - - indexlist.addAVIIndex((int)position,useLength); - - aviOutput.write(fcc); - aviOutput.write(intBytes(swapInt(useLength))); - aviOutput.write(imagedata); - if(extra > 0) - { - for(int i = 0; i < extra; i++) - aviOutput.write(0); - } - imagedata = null; - } - - public void finishAVI() throws IOException - { - byte[] indexlistBytes = indexlist.toBytes(); - aviOutput.write(indexlistBytes); - aviOutput.close(); - long size = aviFile.length(); - RandomAccessFile raf = new RandomAccessFile(aviFile, "rw"); - raf.seek(4); - raf.write(intBytes(swapInt((int)size - 8))); - raf.seek(aviMovieOffset+4); - raf.write(intBytes(swapInt((int)(size - 8 - aviMovieOffset - indexlistBytes.length)))); - raf.close(); - } - -// public void writeAVI(File file) throws Exception -// { -// OutputStream os = new FileOutputStream(file); -// -// // RIFFHeader -// // AVIMainHeader -// // AVIStreamList -// // AVIStreamHeader -// // AVIStreamFormat -// // write 00db and image bytes... -// } - - public static int swapInt(int v) - { - return (v >>> 24) | (v << 24) | - ((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00); - } - - public static short swapShort(short v) - { - return (short)((v >>> 8) | (v << 8)); - } - - public static byte[] intBytes(int i) - { - byte[] b = new byte[4]; - b[0] = (byte)(i >>> 24); - b[1] = (byte)((i >>> 16) & 0x000000FF); - b[2] = (byte)((i >>> 8) & 0x000000FF); - b[3] = (byte)(i & 0x000000FF); - - return b; - } - - public static byte[] shortBytes(short i) - { - byte[] b = new byte[2]; - b[0] = (byte)(i >>> 8); - b[1] = (byte)(i & 0x000000FF); - - return b; - } - - private class RIFFHeader - { - public byte[] fcc = new byte[]{'R','I','F','F'}; - public int fileSize = 0; - public byte[] fcc2 = new byte[]{'A','V','I',' '}; - public byte[] fcc3 = new byte[]{'L','I','S','T'}; - public int listSize = 200; - public byte[] fcc4 = new byte[]{'h','d','r','l'}; - - public RIFFHeader() - { - - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(fileSize))); - baos.write(fcc2); - baos.write(fcc3); - baos.write(intBytes(swapInt(listSize))); - baos.write(fcc4); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIMainHeader - { - /* - * - FOURCC fcc; - DWORD cb; - DWORD dwMicroSecPerFrame; - DWORD dwMaxBytesPerSec; - DWORD dwPaddingGranularity; - DWORD dwFlags; - DWORD dwTotalFrames; - DWORD dwInitialFrames; - DWORD dwStreams; - DWORD dwSuggestedBufferSize; - DWORD dwWidth; - DWORD dwHeight; - DWORD dwReserved[4]; - */ - - public byte[] fcc = new byte[]{'a','v','i','h'}; - public int cb = 56; - public int dwMicroSecPerFrame = 0; // (1 / frames per sec) * 1,000,000 - public int dwMaxBytesPerSec = 10000000; - public int dwPaddingGranularity = 0; - public int dwFlags = 65552; - public int dwTotalFrames = 0; // replace with correct value - public int dwInitialFrames = 0; - public int dwStreams = 1; - public int dwSuggestedBufferSize = 0; - public int dwWidth = 0; // replace with correct value - public int dwHeight = 0; // replace with correct value - public int[] dwReserved = new int[4]; - - public AVIMainHeader() - { - dwMicroSecPerFrame = (int)((1.0/framerate)*1000000.0); - dwWidth = width; - dwHeight = height; - dwTotalFrames = numFrames; - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(cb))); - baos.write(intBytes(swapInt(dwMicroSecPerFrame))); - baos.write(intBytes(swapInt(dwMaxBytesPerSec))); - baos.write(intBytes(swapInt(dwPaddingGranularity))); - baos.write(intBytes(swapInt(dwFlags))); - baos.write(intBytes(swapInt(dwTotalFrames))); - baos.write(intBytes(swapInt(dwInitialFrames))); - baos.write(intBytes(swapInt(dwStreams))); - baos.write(intBytes(swapInt(dwSuggestedBufferSize))); - baos.write(intBytes(swapInt(dwWidth))); - baos.write(intBytes(swapInt(dwHeight))); - baos.write(intBytes(swapInt(dwReserved[0]))); - baos.write(intBytes(swapInt(dwReserved[1]))); - baos.write(intBytes(swapInt(dwReserved[2]))); - baos.write(intBytes(swapInt(dwReserved[3]))); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIStreamList - { - public byte[] fcc = new byte[]{'L','I','S','T'}; - public int size = 124; - public byte[] fcc2 = new byte[]{'s','t','r','l'}; - - public AVIStreamList() - { - - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(size))); - baos.write(fcc2); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIStreamHeader - { - /* - FOURCC fcc; - DWORD cb; - FOURCC fccType; - FOURCC fccHandler; - DWORD dwFlags; - WORD wPriority; - WORD wLanguage; - DWORD dwInitialFrames; - DWORD dwScale; - DWORD dwRate; - DWORD dwStart; - DWORD dwLength; - DWORD dwSuggestedBufferSize; - DWORD dwQuality; - DWORD dwSampleSize; - struct { - short int left; - short int top; - short int right; - short int bottom; - } rcFrame; - */ - - public byte[] fcc = new byte[]{'s','t','r','h'}; - public int cb = 64; - public byte[] fccType = new byte[]{'v','i','d','s'}; - public byte[] fccHandler = new byte[]{'M','J','P','G'}; - public int dwFlags = 0; - public short wPriority = 0; - public short wLanguage = 0; - public int dwInitialFrames = 0; - public int dwScale = 0; // microseconds per frame - public int dwRate = 1000000; // dwRate / dwScale = frame rate - public int dwStart = 0; - public int dwLength = 0; // num frames - public int dwSuggestedBufferSize = 0; - public int dwQuality = -1; - public int dwSampleSize = 0; - public int left = 0; - public int top = 0; - public int right = 0; - public int bottom = 0; - - public AVIStreamHeader() - { - dwScale = (int)((1.0/framerate)*1000000.0); - dwLength = numFrames; - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(cb))); - baos.write(fccType); - baos.write(fccHandler); - baos.write(intBytes(swapInt(dwFlags))); - baos.write(shortBytes(swapShort(wPriority))); - baos.write(shortBytes(swapShort(wLanguage))); - baos.write(intBytes(swapInt(dwInitialFrames))); - baos.write(intBytes(swapInt(dwScale))); - baos.write(intBytes(swapInt(dwRate))); - baos.write(intBytes(swapInt(dwStart))); - baos.write(intBytes(swapInt(dwLength))); - baos.write(intBytes(swapInt(dwSuggestedBufferSize))); - baos.write(intBytes(swapInt(dwQuality))); - baos.write(intBytes(swapInt(dwSampleSize))); - baos.write(intBytes(swapInt(left))); - baos.write(intBytes(swapInt(top))); - baos.write(intBytes(swapInt(right))); - baos.write(intBytes(swapInt(bottom))); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIStreamFormat - { - /* - FOURCC fcc; - DWORD cb; - DWORD biSize; - LONG biWidth; - LONG biHeight; - WORD biPlanes; - WORD biBitCount; - DWORD biCompression; - DWORD biSizeImage; - LONG biXPelsPerMeter; - LONG biYPelsPerMeter; - DWORD biClrUsed; - DWORD biClrImportant; - */ - - public byte[] fcc = new byte[]{'s','t','r','f'}; - public int cb = 40; - public int biSize = 40; // same as cb - public int biWidth = 0; - public int biHeight = 0; - public short biPlanes = 1; - public short biBitCount = 24; - public byte[] biCompression = new byte[]{'M','J','P','G'}; - public int biSizeImage = 0; // width x height in pixels - public int biXPelsPerMeter = 0; - public int biYPelsPerMeter = 0; - public int biClrUsed = 0; - public int biClrImportant = 0; - - - public AVIStreamFormat() - { - biWidth = width; - biHeight = height; - biSizeImage = width * height; - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(cb))); - baos.write(intBytes(swapInt(biSize))); - baos.write(intBytes(swapInt(biWidth))); - baos.write(intBytes(swapInt(biHeight))); - baos.write(shortBytes(swapShort(biPlanes))); - baos.write(shortBytes(swapShort(biBitCount))); - baos.write(biCompression); - baos.write(intBytes(swapInt(biSizeImage))); - baos.write(intBytes(swapInt(biXPelsPerMeter))); - baos.write(intBytes(swapInt(biYPelsPerMeter))); - baos.write(intBytes(swapInt(biClrUsed))); - baos.write(intBytes(swapInt(biClrImportant))); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIMovieList - { - public byte[] fcc = new byte[]{'L','I','S','T'}; - public int listSize = 0; - public byte[] fcc2 = new byte[]{'m','o','v','i'}; - // 00db size jpg image data ... - - public AVIMovieList() - { - - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(listSize))); - baos.write(fcc2); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIIndexList - { - public byte[] fcc = new byte[]{'i','d','x','1'}; - public int cb = 0; - public ArrayList ind = new ArrayList(); - - public AVIIndexList() - { - - } - - public void addAVIIndex(AVIIndex ai) - { - ind.add(ai); - } - - public void addAVIIndex(int dwOffset, int dwSize) - { - ind.add(new AVIIndex(dwOffset, dwSize)); - } - - public byte[] toBytes() throws IOException - { - cb = 16 * ind.size(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(cb))); - for(int i = 0; i < ind.size(); i++) - { - AVIIndex in = (AVIIndex)ind.get(i); - baos.write(in.toBytes()); - } - - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIIndex - { - public byte[] fcc = new byte[]{'0','0','d','b'}; - public int dwFlags = 16; - public int dwOffset = 0; - public int dwSize = 0; - - public AVIIndex(int dwOffset, int dwSize) - { - this.dwOffset = dwOffset; - this.dwSize = dwSize; - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(dwFlags))); - baos.write(intBytes(swapInt(dwOffset))); - baos.write(intBytes(swapInt(dwSize))); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIJunk - { - public byte[] fcc = new byte[]{'J','U','N','K'}; - public int size = 1808; - public byte[] data = new byte[size]; - - public AVIJunk() - { - Arrays.fill(data,(byte)0); - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(size))); - baos.write(data); - baos.close(); - - return baos.toByteArray(); - } - } - - private byte[] writeImageToBytes(Image image) throws IOException - { - BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Graphics2D g = bi.createGraphics(); - g.drawImage(image,0,0,width,height,null); - ImageIO.write(bi,"jpg",baos); - baos.close(); - bi = null; - g = null; - - return baos.toByteArray(); - } - - public static void main(String[] args) throws Exception - { - double framerate = 12.0; - double transitionDuration = 1; // seconds - double slideDuration = 3; // seconds - - File photoDir = new File(args[0]); - File[] files = photoDir.listFiles(new FilenameFilter(){ - public boolean accept(File dir, String name) - { - if(StringUtils.goLowerCase(name).endsWith("jpg")) - return true; - return false; - } - }); - - - int numFrames = (int)(files.length * framerate * (slideDuration + transitionDuration) + (transitionDuration * framerate)); - MJPEGGenerator m = new MJPEGGenerator(new File(args[1]), 640, 480, framerate, numFrames); - for(int i = 0; i < files.length; i++) - { - System.out.println("processing file "+i); - ImageIcon ii = new ImageIcon(files[i].getCanonicalPath()); - m.addImage(ii.getImage()); - } - m.finishAVI(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/old/MJPEGGenerator.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/old/MJPEGGenerator.java deleted file mode 100755 index 8cd9ca9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/old/MJPEGGenerator.java +++ /dev/null @@ -1,573 +0,0 @@ -/* - * MJPEGGenerator.java - * - * Created on April 17, 2006, 11:48 PM - * - * To change this template, choose Tools | Options and locate the template under - * the Source Creation and Management node. Right-click the template and choose - * Open. You can then make changes to the template in the Source Editor. - */ - -package net.sourceforge.plantuml.mjpeg; - -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.nio.channels.FileChannel; -import java.util.ArrayList; -import java.util.Arrays; - -import javax.imageio.ImageIO; -import javax.swing.ImageIcon; - -/** - * - * @author monceaux - */ -public class MJPEGGenerator -{ - /* - * Info needed for MJPEG AVI - * - * - size of file minus "RIFF & 4 byte file size" - * - */ - - int width = 0; - int height = 0; - double framerate = 0; - int numFrames = 0; - File aviFile = null; - FileOutputStream aviOutput = null; - FileChannel aviChannel = null; - - long riffOffset = 0; - long aviMovieOffset = 0; - - AVIIndexList indexlist = null; - - /** Creates a new instance of MJPEGGenerator */ - public MJPEGGenerator(File aviFile, int width, int height, double framerate, int numFrames) throws IOException - { - this.aviFile = aviFile; - this.width = width; - this.height = height; - this.framerate = framerate; - this.numFrames = numFrames; - aviOutput = new FileOutputStream(aviFile); - aviChannel = aviOutput.getChannel(); - - RIFFHeader rh = new RIFFHeader(); - aviOutput.write(rh.toBytes()); - aviOutput.write(new AVIMainHeader().toBytes()); - aviOutput.write(new AVIStreamList().toBytes()); - aviOutput.write(new AVIStreamHeader().toBytes()); - aviOutput.write(new AVIStreamFormat().toBytes()); - aviOutput.write(new AVIJunk().toBytes()); - aviMovieOffset = aviChannel.position(); - aviOutput.write(new AVIMovieList().toBytes()); - indexlist = new AVIIndexList(); - } - - public void addImage(Image image) throws IOException - { - byte[] fcc = new byte[]{'0','0','d','b'}; - byte[] imagedata = writeImageToBytes(image); - int useLength = imagedata.length; - long position = aviChannel.position(); - int extra = (useLength+(int)position) % 4; - if(extra > 0) - useLength = useLength + extra; - - indexlist.addAVIIndex((int)position,useLength); - - aviOutput.write(fcc); - aviOutput.write(intBytes(swapInt(useLength))); - aviOutput.write(imagedata); - if(extra > 0) - { - for(int i = 0; i < extra; i++) - aviOutput.write(0); - } - imagedata = null; - } - - public void finishAVI() throws IOException - { - byte[] indexlistBytes = indexlist.toBytes(); - aviOutput.write(indexlistBytes); - aviOutput.close(); - long size = aviFile.length(); - RandomAccessFile raf = new RandomAccessFile(aviFile, "rw"); - raf.seek(4); - raf.write(intBytes(swapInt((int)size - 8))); - raf.seek(aviMovieOffset+4); - raf.write(intBytes(swapInt((int)(size - 8 - aviMovieOffset - indexlistBytes.length)))); - raf.close(); - } - -// public void writeAVI(File file) throws Exception -// { -// OutputStream os = new FileOutputStream(file); -// -// // RIFFHeader -// // AVIMainHeader -// // AVIStreamList -// // AVIStreamHeader -// // AVIStreamFormat -// // write 00db and image bytes... -// } - - public static int swapInt(int v) - { - return (v >>> 24) | (v << 24) | - ((v << 8) & 0x00FF0000) | ((v >> 8) & 0x0000FF00); - } - - public static short swapShort(short v) - { - return (short)((v >>> 8) | (v << 8)); - } - - public static byte[] intBytes(int i) - { - byte[] b = new byte[4]; - b[0] = (byte)(i >>> 24); - b[1] = (byte)((i >>> 16) & 0x000000FF); - b[2] = (byte)((i >>> 8) & 0x000000FF); - b[3] = (byte)(i & 0x000000FF); - - return b; - } - - public static byte[] shortBytes(short i) - { - byte[] b = new byte[2]; - b[0] = (byte)(i >>> 8); - b[1] = (byte)(i & 0x000000FF); - - return b; - } - - private class RIFFHeader - { - public byte[] fcc = new byte[]{'R','I','F','F'}; - public int fileSize = 0; - public byte[] fcc2 = new byte[]{'A','V','I',' '}; - public byte[] fcc3 = new byte[]{'L','I','S','T'}; - public int listSize = 200; - public byte[] fcc4 = new byte[]{'h','d','r','l'}; - - public RIFFHeader() - { - - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(fileSize))); - baos.write(fcc2); - baos.write(fcc3); - baos.write(intBytes(swapInt(listSize))); - baos.write(fcc4); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIMainHeader - { - /* - * - FOURCC fcc; - DWORD cb; - DWORD dwMicroSecPerFrame; - DWORD dwMaxBytesPerSec; - DWORD dwPaddingGranularity; - DWORD dwFlags; - DWORD dwTotalFrames; - DWORD dwInitialFrames; - DWORD dwStreams; - DWORD dwSuggestedBufferSize; - DWORD dwWidth; - DWORD dwHeight; - DWORD dwReserved[4]; - */ - - public byte[] fcc = new byte[]{'a','v','i','h'}; - public int cb = 56; - public int dwMicroSecPerFrame = 0; // (1 / frames per sec) * 1,000,000 - public int dwMaxBytesPerSec = 10000000; - public int dwPaddingGranularity = 0; - public int dwFlags = 65552; - public int dwTotalFrames = 0; // replace with correct value - public int dwInitialFrames = 0; - public int dwStreams = 1; - public int dwSuggestedBufferSize = 0; - public int dwWidth = 0; // replace with correct value - public int dwHeight = 0; // replace with correct value - public int[] dwReserved = new int[4]; - - public AVIMainHeader() - { - dwMicroSecPerFrame = (int)((1.0/framerate)*1000000.0); - dwWidth = width; - dwHeight = height; - dwTotalFrames = numFrames; - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(cb))); - baos.write(intBytes(swapInt(dwMicroSecPerFrame))); - baos.write(intBytes(swapInt(dwMaxBytesPerSec))); - baos.write(intBytes(swapInt(dwPaddingGranularity))); - baos.write(intBytes(swapInt(dwFlags))); - baos.write(intBytes(swapInt(dwTotalFrames))); - baos.write(intBytes(swapInt(dwInitialFrames))); - baos.write(intBytes(swapInt(dwStreams))); - baos.write(intBytes(swapInt(dwSuggestedBufferSize))); - baos.write(intBytes(swapInt(dwWidth))); - baos.write(intBytes(swapInt(dwHeight))); - baos.write(intBytes(swapInt(dwReserved[0]))); - baos.write(intBytes(swapInt(dwReserved[1]))); - baos.write(intBytes(swapInt(dwReserved[2]))); - baos.write(intBytes(swapInt(dwReserved[3]))); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIStreamList - { - public byte[] fcc = new byte[]{'L','I','S','T'}; - public int size = 124; - public byte[] fcc2 = new byte[]{'s','t','r','l'}; - - public AVIStreamList() - { - - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(size))); - baos.write(fcc2); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIStreamHeader - { - /* - FOURCC fcc; - DWORD cb; - FOURCC fccType; - FOURCC fccHandler; - DWORD dwFlags; - WORD wPriority; - WORD wLanguage; - DWORD dwInitialFrames; - DWORD dwScale; - DWORD dwRate; - DWORD dwStart; - DWORD dwLength; - DWORD dwSuggestedBufferSize; - DWORD dwQuality; - DWORD dwSampleSize; - struct { - short int left; - short int top; - short int right; - short int bottom; - } rcFrame; - */ - - public byte[] fcc = new byte[]{'s','t','r','h'}; - public int cb = 64; - public byte[] fccType = new byte[]{'v','i','d','s'}; - public byte[] fccHandler = new byte[]{'M','J','P','G'}; - public int dwFlags = 0; - public short wPriority = 0; - public short wLanguage = 0; - public int dwInitialFrames = 0; - public int dwScale = 0; // microseconds per frame - public int dwRate = 1000000; // dwRate / dwScale = frame rate - public int dwStart = 0; - public int dwLength = 0; // num frames - public int dwSuggestedBufferSize = 0; - public int dwQuality = -1; - public int dwSampleSize = 0; - public int left = 0; - public int top = 0; - public int right = 0; - public int bottom = 0; - - public AVIStreamHeader() - { - dwScale = (int)((1.0/framerate)*1000000.0); - dwLength = numFrames; - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(cb))); - baos.write(fccType); - baos.write(fccHandler); - baos.write(intBytes(swapInt(dwFlags))); - baos.write(shortBytes(swapShort(wPriority))); - baos.write(shortBytes(swapShort(wLanguage))); - baos.write(intBytes(swapInt(dwInitialFrames))); - baos.write(intBytes(swapInt(dwScale))); - baos.write(intBytes(swapInt(dwRate))); - baos.write(intBytes(swapInt(dwStart))); - baos.write(intBytes(swapInt(dwLength))); - baos.write(intBytes(swapInt(dwSuggestedBufferSize))); - baos.write(intBytes(swapInt(dwQuality))); - baos.write(intBytes(swapInt(dwSampleSize))); - baos.write(intBytes(swapInt(left))); - baos.write(intBytes(swapInt(top))); - baos.write(intBytes(swapInt(right))); - baos.write(intBytes(swapInt(bottom))); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIStreamFormat - { - /* - FOURCC fcc; - DWORD cb; - DWORD biSize; - LONG biWidth; - LONG biHeight; - WORD biPlanes; - WORD biBitCount; - DWORD biCompression; - DWORD biSizeImage; - LONG biXPelsPerMeter; - LONG biYPelsPerMeter; - DWORD biClrUsed; - DWORD biClrImportant; - */ - - public byte[] fcc = new byte[]{'s','t','r','f'}; - public int cb = 40; - public int biSize = 40; // same as cb - public int biWidth = 0; - public int biHeight = 0; - public short biPlanes = 1; - public short biBitCount = 24; - public byte[] biCompression = new byte[]{'M','J','P','G'}; - public int biSizeImage = 0; // width x height in pixels - public int biXPelsPerMeter = 0; - public int biYPelsPerMeter = 0; - public int biClrUsed = 0; - public int biClrImportant = 0; - - - public AVIStreamFormat() - { - biWidth = width; - biHeight = height; - biSizeImage = width * height; - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(cb))); - baos.write(intBytes(swapInt(biSize))); - baos.write(intBytes(swapInt(biWidth))); - baos.write(intBytes(swapInt(biHeight))); - baos.write(shortBytes(swapShort(biPlanes))); - baos.write(shortBytes(swapShort(biBitCount))); - baos.write(biCompression); - baos.write(intBytes(swapInt(biSizeImage))); - baos.write(intBytes(swapInt(biXPelsPerMeter))); - baos.write(intBytes(swapInt(biYPelsPerMeter))); - baos.write(intBytes(swapInt(biClrUsed))); - baos.write(intBytes(swapInt(biClrImportant))); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIMovieList - { - public byte[] fcc = new byte[]{'L','I','S','T'}; - public int listSize = 0; - public byte[] fcc2 = new byte[]{'m','o','v','i'}; - // 00db size jpg image data ... - - public AVIMovieList() - { - - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(listSize))); - baos.write(fcc2); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIIndexList - { - public byte[] fcc = new byte[]{'i','d','x','1'}; - public int cb = 0; - public ArrayList ind = new ArrayList(); - - public AVIIndexList() - { - - } - - public void addAVIIndex(AVIIndex ai) - { - ind.add(ai); - } - - public void addAVIIndex(int dwOffset, int dwSize) - { - ind.add(new AVIIndex(dwOffset, dwSize)); - } - - public byte[] toBytes() throws IOException - { - cb = 16 * ind.size(); - - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(cb))); - for(int i = 0; i < ind.size(); i++) - { - AVIIndex in = (AVIIndex)ind.get(i); - baos.write(in.toBytes()); - } - - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIIndex - { - public byte[] fcc = new byte[]{'0','0','d','b'}; - public int dwFlags = 16; - public int dwOffset = 0; - public int dwSize = 0; - - public AVIIndex(int dwOffset, int dwSize) - { - this.dwOffset = dwOffset; - this.dwSize = dwSize; - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(dwFlags))); - baos.write(intBytes(swapInt(dwOffset))); - baos.write(intBytes(swapInt(dwSize))); - baos.close(); - - return baos.toByteArray(); - } - } - - private class AVIJunk - { - public byte[] fcc = new byte[]{'J','U','N','K'}; - public int size = 1808; - public byte[] data = new byte[size]; - - public AVIJunk() - { - Arrays.fill(data,(byte)0); - } - - public byte[] toBytes() throws IOException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write(fcc); - baos.write(intBytes(swapInt(size))); - baos.write(data); - baos.close(); - - return baos.toByteArray(); - } - } - - private byte[] writeImageToBytes(Image image) throws IOException - { - BufferedImage bi = new BufferedImage(width, height,BufferedImage.TYPE_INT_RGB); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - Graphics2D g = bi.createGraphics(); - g.drawImage(image,0,0,width,height,null); - ImageIO.write(bi,"jpg",baos); - baos.close(); - bi = null; - g = null; - - return baos.toByteArray(); - } - - public static void main(String[] args) throws Exception - { - double framerate = 12.0; - double transitionDuration = 1; // seconds - double slideDuration = 3; // seconds - - File photoDir = new File(args[0]); - File[] files = photoDir.listFiles(new FilenameFilter(){ - public boolean accept(File dir, String name) - { - if(name.toLowerCase().endsWith("jpg")) - return true; - return false; - } - }); - - - int numFrames = (int)(files.length * framerate * (slideDuration + transitionDuration) + (transitionDuration * framerate)); - MJPEGGenerator m = new MJPEGGenerator(new File(args[1]), 640, 480, framerate, numFrames); - for(int i = 0; i < files.length; i++) - { - System.out.println("processing file "+i); - ImageIcon ii = new ImageIcon(files[i].getCanonicalPath()); - m.addImage(ii.getImage()); - } - m.finishAVI(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/pair.info deleted file mode 100755 index e75773e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22476/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22476 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/mjpeg/MJPEGGenerator.java -FixedFilePath:src/net/sourceforge/plantuml/mjpeg/MJPEGGenerator.java -StartLineNum:555 -EndLineNum:555 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/diff.diff deleted file mode 100755 index 8170b54..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/Run.java b/src/net/sourceforge/plantuml/Run.java -index 3eabd4e9..8ee280ba 100644 ---- a/src/net/sourceforge/plantuml/Run.java -+++ b/src/net/sourceforge/plantuml/Run.java -@@ -31 +31 @@ -- * Revision $Revision: 12866 $ -+ * Revision $Revision: 14727 $ -@@ -165 +165 @@ public class Run { -- compressed = result.get(0).toLowerCase().endsWith("z"); -+ compressed = StringUtils.goLowerCase(result.get(0)).endsWith("z"); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/new/Run.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/new/Run.java deleted file mode 100755 index 8ee280b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/new/Run.java +++ /dev/null @@ -1,410 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14727 $ - * - */ -package net.sourceforge.plantuml; - -import java.awt.Font; -import java.awt.GraphicsEnvironment; -import java.awt.image.BufferedImage; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.imageio.ImageIO; -import javax.swing.UIManager; - -import net.sourceforge.plantuml.activitydiagram.ActivityDiagramFactory; -import net.sourceforge.plantuml.classdiagram.ClassDiagramFactory; -import net.sourceforge.plantuml.code.Transcoder; -import net.sourceforge.plantuml.code.TranscoderUtil; -import net.sourceforge.plantuml.command.UmlDiagramFactory; -import net.sourceforge.plantuml.core.Diagram; -import net.sourceforge.plantuml.descdiagram.DescriptionDiagramFactory; -import net.sourceforge.plantuml.ftp.FtpServer; -import net.sourceforge.plantuml.objectdiagram.ObjectDiagramFactory; -import net.sourceforge.plantuml.png.MetadataTag; -import net.sourceforge.plantuml.preproc.Defines; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagramFactory; -import net.sourceforge.plantuml.statediagram.StateDiagramFactory; -import net.sourceforge.plantuml.swing.MainWindow2; -import net.sourceforge.plantuml.ugraphic.SpriteGrayLevel; -import net.sourceforge.plantuml.ugraphic.SpriteUtils; -import net.sourceforge.plantuml.version.Version; - -public class Run { - - public static void main(String[] argsArray) throws IOException, InterruptedException { - final long start = System.currentTimeMillis(); - final Option option = new Option(argsArray); - if (OptionFlags.getInstance().isEncodesprite()) { - encodeSprite(option.getResult()); - return; - } - if (OptionFlags.getInstance().isVerbose()) { - Log.info("PlantUML Version " + Version.versionString()); - Log.info("GraphicsEnvironment.isHeadless() " + GraphicsEnvironment.isHeadless()); - } - if (GraphicsEnvironment.isHeadless()) { - Log.info("Forcing -Djava.awt.headless=true"); - System.setProperty("java.awt.headless", "true"); - Log.info("java.awt.headless set as true"); - - } - if (OptionFlags.getInstance().isPrintFonts()) { - printFonts(); - return; - } - - if (option.getFtpPort() != -1) { - goFtp(option); - return; - } - - boolean error = false; - boolean forceQuit = false; - if (option.isPattern()) { - managePattern(); - } else if (OptionFlags.getInstance().isGui()) { - try { - UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); - } catch (Exception e) { - } - final List list = option.getResult(); - File dir = null; - if (list.size() == 1) { - final File f = new File(list.get(0)); - if (f.exists() && f.isDirectory()) { - dir = f; - } - } - new MainWindow2(option, dir); - } else if (option.isPipe() || option.isSyntax()) { - managePipe(option); - forceQuit = true; - } else if (option.isFailfast2()) { - final long start2 = System.currentTimeMillis(); - option.setCheckOnly(true); - error = manageAllFiles(option); - option.setCheckOnly(false); - if (option.isDuration()) { - final double duration = (System.currentTimeMillis() - start2) / 1000.0; - Log.error("Check Duration = " + duration + " seconds"); - } - if (error == false) { - error = manageAllFiles(option); - } - forceQuit = true; - } else { - error = manageAllFiles(option); - forceQuit = true; - } - - if (option.isDuration()) { - final double duration = (System.currentTimeMillis() - start) / 1000.0; - Log.error("Duration = " + duration + " seconds"); - } - - if (error) { - Log.error("Some diagram description contains errors"); - System.exit(1); - } - - if (forceQuit && OptionFlags.getInstance().isSystemExit()) { - System.exit(0); - } - } - - private static void encodeSprite(List result) throws IOException { - SpriteGrayLevel level = SpriteGrayLevel.GRAY_16; - boolean compressed = false; - final File f; - if (result.size() > 1 && result.get(0).matches("(4|8|16)z?")) { - if (result.get(0).startsWith("8")) { - level = SpriteGrayLevel.GRAY_8; - } - if (result.get(0).startsWith("4")) { - level = SpriteGrayLevel.GRAY_4; - } - compressed = StringUtils.goLowerCase(result.get(0)).endsWith("z"); - f = new File(result.get(1)); - } else { - f = new File(result.get(0)); - } - final BufferedImage im = ImageIO.read(f); - final String name = getSpriteName(f); - final String s = compressed ? SpriteUtils.encodeCompressed(im, name, level) : SpriteUtils.encode(im, name, - level); - System.out.println(s); - } - - private static String getSpriteName(File f) { - final String s = getSpriteNameInternal(f); - if (s.length() == 0) { - return "test"; - } - return s; - } - - private static String getSpriteNameInternal(File f) { - final StringBuilder sb = new StringBuilder(); - for (char c : f.getName().toCharArray()) { - if (("" + c).matches("[\\p{L}0-9_]")) { - sb.append(c); - } else { - return sb.toString(); - } - } - return sb.toString(); - } - - private static void goFtp(Option option) throws IOException { - final int ftpPort = option.getFtpPort(); - System.err.println("ftpPort=" + ftpPort); - final FtpServer ftpServer = new FtpServer(ftpPort); - ftpServer.go(); - } - - static void printFonts() { - final Font fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); - for (Font f : fonts) { - System.out.println("f=" + f + "/" + f.getPSName() + "/" + f.getName() + "/" + f.getFontName() + "/" - + f.getFamily()); - } - final String name[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); - for (String n : name) { - System.out.println("n=" + n); - } - - } - - private static void managePattern() { - printPattern(new SequenceDiagramFactory()); - printPattern(new ClassDiagramFactory()); - printPattern(new ActivityDiagramFactory()); - printPattern(new DescriptionDiagramFactory()); - // printPattern(new ComponentDiagramFactory()); - printPattern(new StateDiagramFactory()); - printPattern(new ObjectDiagramFactory()); - } - - private static void printPattern(UmlDiagramFactory factory) { - System.out.println(); - System.out.println(factory.getClass().getSimpleName().replaceAll("Factory", "")); - final List descriptions = factory.getDescription(); - for (String s : descriptions) { - System.out.println(s); - } - } - - private static void managePipe(Option option) throws IOException { - final String charset = option.getCharset(); - final BufferedReader br; - if (charset == null) { - br = new BufferedReader(new InputStreamReader(System.in)); - } else { - br = new BufferedReader(new InputStreamReader(System.in, charset)); - } - managePipe(option, br, System.out); - } - - static void managePipe(Option option, final BufferedReader br, final PrintStream ps) throws IOException { - final StringBuilder sb = new StringBuilder(); - String s = null; - while ((s = br.readLine()) != null) { - sb.append(s); - sb.append("\n"); - } - String source = sb.toString(); - if (source.contains("@startuml") == false) { - source = "@startuml\n" + source + "\n@enduml"; - } - final SourceStringReader sourceStringReader = new SourceStringReader(new Defines(), source, option.getConfig()); - - if (option.isSyntax()) { - final Diagram system = sourceStringReader.getBlocks().get(0).getDiagram(); - if (system instanceof UmlDiagram) { - ps.println(((UmlDiagram) system).getUmlDiagramType().name()); - ps.println(system.getDescription()); - } else if (system instanceof PSystemError) { - ps.println("ERROR"); - final PSystemError sys = (PSystemError) system; - ps.println(sys.getHigherErrorPosition()); - for (ErrorUml er : sys.getErrorsUml()) { - ps.println(er.getError()); - } - } else { - ps.println("OTHER"); - ps.println(system.getDescription()); - } - } else if (option.isPipe()) { - sourceStringReader.generateImage(ps, 0, option.getFileFormatOption()); - } - } - - private static boolean manageAllFiles(Option option) throws IOException, InterruptedException { - - File lockFile = null; - try { - if (OptionFlags.getInstance().isWord()) { - final File dir = new File(option.getResult().get(0)); - final File javaIsRunningFile = new File(dir, "javaisrunning.tmp"); - javaIsRunningFile.delete(); - lockFile = new File(dir, "javaumllock.tmp"); - } - return processArgs(option); - } finally { - if (lockFile != null) { - lockFile.delete(); - } - } - - } - - private static boolean processArgs(Option option) throws IOException, InterruptedException { - if (option.isDecodeurl() == false && option.getNbThreads() > 0 && option.isCheckOnly() == false - && OptionFlags.getInstance().isMetadata() == false) { - return multithread(option); - } - boolean errorGlobal = false; - for (String s : option.getResult()) { - if (option.isDecodeurl()) { - final Transcoder transcoder = TranscoderUtil.getDefaultTranscoder(); - System.out.println("@startuml"); - System.out.println(transcoder.decode(s)); - System.out.println("@enduml"); - } else { - final FileGroup group = new FileGroup(s, option.getExcludes(), option); - for (File f : group.getFiles()) { - try { - final boolean error = manageFileInternal(f, option); - if (error) { - errorGlobal = true; - } - if (error && option.isFailfastOrFailfast2()) { - return true; - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - return errorGlobal; - } - - private static boolean multithread(final Option option) throws InterruptedException { - Log.info("Using several threads: " + option.getNbThreads()); - final ExecutorService executor = Executors.newFixedThreadPool(option.getNbThreads()); - final AtomicBoolean errors = new AtomicBoolean(false); - for (String s : option.getResult()) { - final FileGroup group = new FileGroup(s, option.getExcludes(), option); - for (final File f : group.getFiles()) { - executor.submit(new Runnable() { - public void run() { - if (errors.get() && option.isFailfastOrFailfast2()) { - return; - } - try { - final boolean error = manageFileInternal(f, option); - if (error) { - errors.set(true); - } - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }); - } - } - executor.shutdown(); - executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); - return errors.get(); - } - - private static boolean manageFileInternal(File f, Option option) throws IOException, InterruptedException { - if (OptionFlags.getInstance().isMetadata()) { - System.out.println("------------------------"); - System.out.println(f); - // new Metadata().readAndDisplayMetadata(f); - System.out.println(); - System.out.println(new MetadataTag(f, "plantuml").getData()); - System.out.println("------------------------"); - return false; - } - final ISourceFileReader sourceFileReader; - if (option.getOutputFile() == null) { - sourceFileReader = new SourceFileReader(option.getDefaultDefines(), f, option.getOutputDir(), - option.getConfig(), option.getCharset(), option.getFileFormatOption()); - } else { - sourceFileReader = new SourceFileReader2(option.getDefaultDefines(), f, option.getOutputFile(), - option.getConfig(), option.getCharset(), option.getFileFormatOption()); - } - if (option.isComputeurl()) { - final List urls = sourceFileReader.getEncodedUrl(); - for (String s : urls) { - System.out.println(s); - } - return false; - } - if (option.isCheckOnly()) { - final boolean hasError = sourceFileReader.hasError(); - final List result = sourceFileReader.getGeneratedImages(); - hasErrors(f, result); - return hasError; - } - final List result = sourceFileReader.getGeneratedImages(); - return hasErrors(f, result); - } - - private static boolean hasErrors(File f, final List list) throws IOException { - boolean result = false; - for (GeneratedImage i : list) { - final int lineError = i.lineErrorRaw(); - if (lineError != -1) { - Log.error("Error line " + lineError + " in file: " + f.getCanonicalPath()); - result = true; - } - } - return result; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/old/Run.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/old/Run.java deleted file mode 100755 index 3eabd4e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/old/Run.java +++ /dev/null @@ -1,410 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 12866 $ - * - */ -package net.sourceforge.plantuml; - -import java.awt.Font; -import java.awt.GraphicsEnvironment; -import java.awt.image.BufferedImage; -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintStream; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import javax.imageio.ImageIO; -import javax.swing.UIManager; - -import net.sourceforge.plantuml.activitydiagram.ActivityDiagramFactory; -import net.sourceforge.plantuml.classdiagram.ClassDiagramFactory; -import net.sourceforge.plantuml.code.Transcoder; -import net.sourceforge.plantuml.code.TranscoderUtil; -import net.sourceforge.plantuml.command.UmlDiagramFactory; -import net.sourceforge.plantuml.core.Diagram; -import net.sourceforge.plantuml.descdiagram.DescriptionDiagramFactory; -import net.sourceforge.plantuml.ftp.FtpServer; -import net.sourceforge.plantuml.objectdiagram.ObjectDiagramFactory; -import net.sourceforge.plantuml.png.MetadataTag; -import net.sourceforge.plantuml.preproc.Defines; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagramFactory; -import net.sourceforge.plantuml.statediagram.StateDiagramFactory; -import net.sourceforge.plantuml.swing.MainWindow2; -import net.sourceforge.plantuml.ugraphic.SpriteGrayLevel; -import net.sourceforge.plantuml.ugraphic.SpriteUtils; -import net.sourceforge.plantuml.version.Version; - -public class Run { - - public static void main(String[] argsArray) throws IOException, InterruptedException { - final long start = System.currentTimeMillis(); - final Option option = new Option(argsArray); - if (OptionFlags.getInstance().isEncodesprite()) { - encodeSprite(option.getResult()); - return; - } - if (OptionFlags.getInstance().isVerbose()) { - Log.info("PlantUML Version " + Version.versionString()); - Log.info("GraphicsEnvironment.isHeadless() " + GraphicsEnvironment.isHeadless()); - } - if (GraphicsEnvironment.isHeadless()) { - Log.info("Forcing -Djava.awt.headless=true"); - System.setProperty("java.awt.headless", "true"); - Log.info("java.awt.headless set as true"); - - } - if (OptionFlags.getInstance().isPrintFonts()) { - printFonts(); - return; - } - - if (option.getFtpPort() != -1) { - goFtp(option); - return; - } - - boolean error = false; - boolean forceQuit = false; - if (option.isPattern()) { - managePattern(); - } else if (OptionFlags.getInstance().isGui()) { - try { - UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); - } catch (Exception e) { - } - final List list = option.getResult(); - File dir = null; - if (list.size() == 1) { - final File f = new File(list.get(0)); - if (f.exists() && f.isDirectory()) { - dir = f; - } - } - new MainWindow2(option, dir); - } else if (option.isPipe() || option.isSyntax()) { - managePipe(option); - forceQuit = true; - } else if (option.isFailfast2()) { - final long start2 = System.currentTimeMillis(); - option.setCheckOnly(true); - error = manageAllFiles(option); - option.setCheckOnly(false); - if (option.isDuration()) { - final double duration = (System.currentTimeMillis() - start2) / 1000.0; - Log.error("Check Duration = " + duration + " seconds"); - } - if (error == false) { - error = manageAllFiles(option); - } - forceQuit = true; - } else { - error = manageAllFiles(option); - forceQuit = true; - } - - if (option.isDuration()) { - final double duration = (System.currentTimeMillis() - start) / 1000.0; - Log.error("Duration = " + duration + " seconds"); - } - - if (error) { - Log.error("Some diagram description contains errors"); - System.exit(1); - } - - if (forceQuit && OptionFlags.getInstance().isSystemExit()) { - System.exit(0); - } - } - - private static void encodeSprite(List result) throws IOException { - SpriteGrayLevel level = SpriteGrayLevel.GRAY_16; - boolean compressed = false; - final File f; - if (result.size() > 1 && result.get(0).matches("(4|8|16)z?")) { - if (result.get(0).startsWith("8")) { - level = SpriteGrayLevel.GRAY_8; - } - if (result.get(0).startsWith("4")) { - level = SpriteGrayLevel.GRAY_4; - } - compressed = result.get(0).toLowerCase().endsWith("z"); - f = new File(result.get(1)); - } else { - f = new File(result.get(0)); - } - final BufferedImage im = ImageIO.read(f); - final String name = getSpriteName(f); - final String s = compressed ? SpriteUtils.encodeCompressed(im, name, level) : SpriteUtils.encode(im, name, - level); - System.out.println(s); - } - - private static String getSpriteName(File f) { - final String s = getSpriteNameInternal(f); - if (s.length() == 0) { - return "test"; - } - return s; - } - - private static String getSpriteNameInternal(File f) { - final StringBuilder sb = new StringBuilder(); - for (char c : f.getName().toCharArray()) { - if (("" + c).matches("[\\p{L}0-9_]")) { - sb.append(c); - } else { - return sb.toString(); - } - } - return sb.toString(); - } - - private static void goFtp(Option option) throws IOException { - final int ftpPort = option.getFtpPort(); - System.err.println("ftpPort=" + ftpPort); - final FtpServer ftpServer = new FtpServer(ftpPort); - ftpServer.go(); - } - - static void printFonts() { - final Font fonts[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAllFonts(); - for (Font f : fonts) { - System.out.println("f=" + f + "/" + f.getPSName() + "/" + f.getName() + "/" + f.getFontName() + "/" - + f.getFamily()); - } - final String name[] = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(); - for (String n : name) { - System.out.println("n=" + n); - } - - } - - private static void managePattern() { - printPattern(new SequenceDiagramFactory()); - printPattern(new ClassDiagramFactory()); - printPattern(new ActivityDiagramFactory()); - printPattern(new DescriptionDiagramFactory()); - // printPattern(new ComponentDiagramFactory()); - printPattern(new StateDiagramFactory()); - printPattern(new ObjectDiagramFactory()); - } - - private static void printPattern(UmlDiagramFactory factory) { - System.out.println(); - System.out.println(factory.getClass().getSimpleName().replaceAll("Factory", "")); - final List descriptions = factory.getDescription(); - for (String s : descriptions) { - System.out.println(s); - } - } - - private static void managePipe(Option option) throws IOException { - final String charset = option.getCharset(); - final BufferedReader br; - if (charset == null) { - br = new BufferedReader(new InputStreamReader(System.in)); - } else { - br = new BufferedReader(new InputStreamReader(System.in, charset)); - } - managePipe(option, br, System.out); - } - - static void managePipe(Option option, final BufferedReader br, final PrintStream ps) throws IOException { - final StringBuilder sb = new StringBuilder(); - String s = null; - while ((s = br.readLine()) != null) { - sb.append(s); - sb.append("\n"); - } - String source = sb.toString(); - if (source.contains("@startuml") == false) { - source = "@startuml\n" + source + "\n@enduml"; - } - final SourceStringReader sourceStringReader = new SourceStringReader(new Defines(), source, option.getConfig()); - - if (option.isSyntax()) { - final Diagram system = sourceStringReader.getBlocks().get(0).getDiagram(); - if (system instanceof UmlDiagram) { - ps.println(((UmlDiagram) system).getUmlDiagramType().name()); - ps.println(system.getDescription()); - } else if (system instanceof PSystemError) { - ps.println("ERROR"); - final PSystemError sys = (PSystemError) system; - ps.println(sys.getHigherErrorPosition()); - for (ErrorUml er : sys.getErrorsUml()) { - ps.println(er.getError()); - } - } else { - ps.println("OTHER"); - ps.println(system.getDescription()); - } - } else if (option.isPipe()) { - sourceStringReader.generateImage(ps, 0, option.getFileFormatOption()); - } - } - - private static boolean manageAllFiles(Option option) throws IOException, InterruptedException { - - File lockFile = null; - try { - if (OptionFlags.getInstance().isWord()) { - final File dir = new File(option.getResult().get(0)); - final File javaIsRunningFile = new File(dir, "javaisrunning.tmp"); - javaIsRunningFile.delete(); - lockFile = new File(dir, "javaumllock.tmp"); - } - return processArgs(option); - } finally { - if (lockFile != null) { - lockFile.delete(); - } - } - - } - - private static boolean processArgs(Option option) throws IOException, InterruptedException { - if (option.isDecodeurl() == false && option.getNbThreads() > 0 && option.isCheckOnly() == false - && OptionFlags.getInstance().isMetadata() == false) { - return multithread(option); - } - boolean errorGlobal = false; - for (String s : option.getResult()) { - if (option.isDecodeurl()) { - final Transcoder transcoder = TranscoderUtil.getDefaultTranscoder(); - System.out.println("@startuml"); - System.out.println(transcoder.decode(s)); - System.out.println("@enduml"); - } else { - final FileGroup group = new FileGroup(s, option.getExcludes(), option); - for (File f : group.getFiles()) { - try { - final boolean error = manageFileInternal(f, option); - if (error) { - errorGlobal = true; - } - if (error && option.isFailfastOrFailfast2()) { - return true; - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - return errorGlobal; - } - - private static boolean multithread(final Option option) throws InterruptedException { - Log.info("Using several threads: " + option.getNbThreads()); - final ExecutorService executor = Executors.newFixedThreadPool(option.getNbThreads()); - final AtomicBoolean errors = new AtomicBoolean(false); - for (String s : option.getResult()) { - final FileGroup group = new FileGroup(s, option.getExcludes(), option); - for (final File f : group.getFiles()) { - executor.submit(new Runnable() { - public void run() { - if (errors.get() && option.isFailfastOrFailfast2()) { - return; - } - try { - final boolean error = manageFileInternal(f, option); - if (error) { - errors.set(true); - } - } catch (IOException e) { - e.printStackTrace(); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - }); - } - } - executor.shutdown(); - executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); - return errors.get(); - } - - private static boolean manageFileInternal(File f, Option option) throws IOException, InterruptedException { - if (OptionFlags.getInstance().isMetadata()) { - System.out.println("------------------------"); - System.out.println(f); - // new Metadata().readAndDisplayMetadata(f); - System.out.println(); - System.out.println(new MetadataTag(f, "plantuml").getData()); - System.out.println("------------------------"); - return false; - } - final ISourceFileReader sourceFileReader; - if (option.getOutputFile() == null) { - sourceFileReader = new SourceFileReader(option.getDefaultDefines(), f, option.getOutputDir(), - option.getConfig(), option.getCharset(), option.getFileFormatOption()); - } else { - sourceFileReader = new SourceFileReader2(option.getDefaultDefines(), f, option.getOutputFile(), - option.getConfig(), option.getCharset(), option.getFileFormatOption()); - } - if (option.isComputeurl()) { - final List urls = sourceFileReader.getEncodedUrl(); - for (String s : urls) { - System.out.println(s); - } - return false; - } - if (option.isCheckOnly()) { - final boolean hasError = sourceFileReader.hasError(); - final List result = sourceFileReader.getGeneratedImages(); - hasErrors(f, result); - return hasError; - } - final List result = sourceFileReader.getGeneratedImages(); - return hasErrors(f, result); - } - - private static boolean hasErrors(File f, final List list) throws IOException { - boolean result = false; - for (GeneratedImage i : list) { - final int lineError = i.lineErrorRaw(); - if (lineError != -1) { - Log.error("Error line " + lineError + " in file: " + f.getCanonicalPath()); - result = true; - } - } - return result; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/pair.info deleted file mode 100755 index 25f27ab..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22488/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22488 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/Run.java -FixedFilePath:src/net/sourceforge/plantuml/Run.java -StartLineNum:165 -EndLineNum:165 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/diff.diff deleted file mode 100755 index 79ad4a6..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClass.java b/src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClass.java -index de830f24..7cfdd43a 100644 ---- a/src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClass.java -+++ b/src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClass.java -@@ -35,0 +36,2 @@ package net.sourceforge.plantuml.classdiagram.command; -+import java.util.Locale; -+ -@@ -36,0 +39 @@ import net.sourceforge.plantuml.FontParam; -+import net.sourceforge.plantuml.StringUtils; -@@ -97 +100 @@ public class CommandCreateClass extends SingleLineCommand2 { -- final LeafType type = LeafType.getLeafType(arg.get("TYPE", 0).toUpperCase()); -+ final LeafType type = LeafType.getLeafType(StringUtils.goUpperCase(arg.get("TYPE", 0))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/new/CommandCreateClass.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/new/CommandCreateClass.java deleted file mode 100755 index 7cfdd43..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/new/CommandCreateClass.java +++ /dev/null @@ -1,162 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5075 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.util.Locale; - -import net.sourceforge.plantuml.FontParam; -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.Url; -import net.sourceforge.plantuml.UrlBuilder; -import net.sourceforge.plantuml.UrlBuilder.ModeUrl; -import net.sourceforge.plantuml.classdiagram.ClassDiagram; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexOr; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Code; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.cucadiagram.ILeaf; -import net.sourceforge.plantuml.cucadiagram.LeafType; -import net.sourceforge.plantuml.cucadiagram.Stereotype; -import net.sourceforge.plantuml.graphic.HtmlColorUtils; - -public class CommandCreateClass extends SingleLineCommand2 { - - public static final String CODE = "[^%s{}%g<>]+"; - - enum Mode { - EXTENDS, IMPLEMENTS - }; - - public CommandCreateClass() { - super(getRegexConcat()); - } - - private static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("TYPE", // - "(interface|enum|annotation|abstract[%s]+class|abstract|class)[%s]+"), // - new RegexOr(// - new RegexConcat(// - new RegexLeaf("DISPLAY1", "[%g]([^%g]+)[%g]"), // - new RegexLeaf("[%s]+as[%s]+"), // - new RegexLeaf("CODE1", "(" + CODE + ")")), // - new RegexConcat(// - new RegexLeaf("CODE2", "(" + CODE + ")"), // - new RegexLeaf("[%s]+as[%s]+"), // // - new RegexLeaf("DISPLAY2", "[%g]([^%g]+)[%g]")), // - new RegexLeaf("CODE3", "(" + CODE + ")"), // - new RegexLeaf("CODE4", "[%g]([^%g]+)[%g]")), // - new RegexLeaf("GENERIC", "(?:[%s]*\\<(" + GenericRegexProducer.PATTERN + ")\\>)?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("STEREO", "(\\<{2}.*\\>{2})?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("URL", "(" + UrlBuilder.getRegexp() + ")?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("COLOR", "(" + HtmlColorUtils.COLOR_REGEXP + ")?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("LINECOLOR", "(?:##(?:\\[(dotted|dashed|bold)\\])?(\\w+)?)?"), // - new RegexLeaf("EXTENDS", "([%s]+(extends)[%s]+(" + CommandCreateClassMultilines.CODES + "))?"), // - new RegexLeaf("IMPLEMENTS", "([%s]+(implements)[%s]+(" + CommandCreateClassMultilines.CODES + "))?"), // - new RegexLeaf("$")); - } - - @Override - protected CommandExecutionResult executeArg(ClassDiagram diagram, RegexResult arg) { - final LeafType type = LeafType.getLeafType(StringUtils.goUpperCase(arg.get("TYPE", 0))); - final Code code = Code.of(arg.getLazzy("CODE", 0)).eventuallyRemoveStartingAndEndingDoubleQuote("\"([:"); - final String display = arg.getLazzy("DISPLAY", 0); - - final String stereotype = arg.get("STEREO", 0); - final String generic = arg.get("GENERIC", 0); - final ILeaf entity; - if (diagram.leafExist(code)) { - entity = diagram.getOrCreateLeaf(code, type, null); - entity.muteToType(type, null); - } else { - entity = diagram.createLeaf(code, Display.getWithNewlines(display), type, null); - } - if (stereotype != null) { - entity.setStereotype(new Stereotype(stereotype, diagram.getSkinParam().getCircledCharacterRadius(), diagram - .getSkinParam().getFont(FontParam.CIRCLED_CHARACTER, null, false), diagram.getSkinParam() - .getIHtmlColorSet())); - } - if (generic != null) { - entity.setGeneric(generic); - } - - final String urlString = arg.get("URL", 0); - if (urlString != null) { - final UrlBuilder urlBuilder = new UrlBuilder(diagram.getSkinParam().getValue("topurl"), ModeUrl.STRICT); - final Url url = urlBuilder.getUrl(urlString); - entity.addUrl(url); - } - - entity.setSpecificBackcolor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("COLOR", 0))); - entity.setSpecificLineColor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("LINECOLOR", 1))); - CommandCreateClassMultilines.applyStroke(entity, arg.get("LINECOLOR", 0)); - - // manageExtends(diagram, arg, entity); - CommandCreateClassMultilines.manageExtends("EXTENDS", diagram, arg, entity); - CommandCreateClassMultilines.manageExtends("IMPLEMENTS", diagram, arg, entity); - - return CommandExecutionResult.ok(); - } - - // public static void manageExtends(ClassDiagram system, RegexResult arg, final IEntity entity) { - // if (arg.get("EXTENDS", 1) != null) { - // final Mode mode = arg.get("EXTENDS", 1).equalsIgnoreCase("extends") ? Mode.EXTENDS : Mode.IMPLEMENTS; - // final Code other = Code.of(arg.get("EXTENDS", 2)); - // LeafType type2 = LeafType.CLASS; - // if (mode == Mode.IMPLEMENTS) { - // type2 = LeafType.INTERFACE; - // } - // if (mode == Mode.EXTENDS && entity.getEntityType() == LeafType.INTERFACE) { - // type2 = LeafType.INTERFACE; - // } - // final IEntity cl2 = system.getOrCreateLeaf(other, type2, null); - // LinkType typeLink = new LinkType(LinkDecor.NONE, LinkDecor.EXTENDS); - // if (type2 == LeafType.INTERFACE && entity.getEntityType() != LeafType.INTERFACE) { - // typeLink = typeLink.getDashed(); - // } - // final Link link = new Link(cl2, entity, typeLink, null, 2, null, null, system.getLabeldistance(), - // system.getLabelangle()); - // system.addLink(link); - // } - // } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/old/CommandCreateClass.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/old/CommandCreateClass.java deleted file mode 100755 index de830f2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/old/CommandCreateClass.java +++ /dev/null @@ -1,159 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5075 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import net.sourceforge.plantuml.FontParam; -import net.sourceforge.plantuml.Url; -import net.sourceforge.plantuml.UrlBuilder; -import net.sourceforge.plantuml.UrlBuilder.ModeUrl; -import net.sourceforge.plantuml.classdiagram.ClassDiagram; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexOr; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Code; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.cucadiagram.ILeaf; -import net.sourceforge.plantuml.cucadiagram.LeafType; -import net.sourceforge.plantuml.cucadiagram.Stereotype; -import net.sourceforge.plantuml.graphic.HtmlColorUtils; - -public class CommandCreateClass extends SingleLineCommand2 { - - public static final String CODE = "[^%s{}%g<>]+"; - - enum Mode { - EXTENDS, IMPLEMENTS - }; - - public CommandCreateClass() { - super(getRegexConcat()); - } - - private static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("TYPE", // - "(interface|enum|annotation|abstract[%s]+class|abstract|class)[%s]+"), // - new RegexOr(// - new RegexConcat(// - new RegexLeaf("DISPLAY1", "[%g]([^%g]+)[%g]"), // - new RegexLeaf("[%s]+as[%s]+"), // - new RegexLeaf("CODE1", "(" + CODE + ")")), // - new RegexConcat(// - new RegexLeaf("CODE2", "(" + CODE + ")"), // - new RegexLeaf("[%s]+as[%s]+"), // // - new RegexLeaf("DISPLAY2", "[%g]([^%g]+)[%g]")), // - new RegexLeaf("CODE3", "(" + CODE + ")"), // - new RegexLeaf("CODE4", "[%g]([^%g]+)[%g]")), // - new RegexLeaf("GENERIC", "(?:[%s]*\\<(" + GenericRegexProducer.PATTERN + ")\\>)?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("STEREO", "(\\<{2}.*\\>{2})?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("URL", "(" + UrlBuilder.getRegexp() + ")?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("COLOR", "(" + HtmlColorUtils.COLOR_REGEXP + ")?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("LINECOLOR", "(?:##(?:\\[(dotted|dashed|bold)\\])?(\\w+)?)?"), // - new RegexLeaf("EXTENDS", "([%s]+(extends)[%s]+(" + CommandCreateClassMultilines.CODES + "))?"), // - new RegexLeaf("IMPLEMENTS", "([%s]+(implements)[%s]+(" + CommandCreateClassMultilines.CODES + "))?"), // - new RegexLeaf("$")); - } - - @Override - protected CommandExecutionResult executeArg(ClassDiagram diagram, RegexResult arg) { - final LeafType type = LeafType.getLeafType(arg.get("TYPE", 0).toUpperCase()); - final Code code = Code.of(arg.getLazzy("CODE", 0)).eventuallyRemoveStartingAndEndingDoubleQuote("\"([:"); - final String display = arg.getLazzy("DISPLAY", 0); - - final String stereotype = arg.get("STEREO", 0); - final String generic = arg.get("GENERIC", 0); - final ILeaf entity; - if (diagram.leafExist(code)) { - entity = diagram.getOrCreateLeaf(code, type, null); - entity.muteToType(type, null); - } else { - entity = diagram.createLeaf(code, Display.getWithNewlines(display), type, null); - } - if (stereotype != null) { - entity.setStereotype(new Stereotype(stereotype, diagram.getSkinParam().getCircledCharacterRadius(), diagram - .getSkinParam().getFont(FontParam.CIRCLED_CHARACTER, null, false), diagram.getSkinParam() - .getIHtmlColorSet())); - } - if (generic != null) { - entity.setGeneric(generic); - } - - final String urlString = arg.get("URL", 0); - if (urlString != null) { - final UrlBuilder urlBuilder = new UrlBuilder(diagram.getSkinParam().getValue("topurl"), ModeUrl.STRICT); - final Url url = urlBuilder.getUrl(urlString); - entity.addUrl(url); - } - - entity.setSpecificBackcolor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("COLOR", 0))); - entity.setSpecificLineColor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("LINECOLOR", 1))); - CommandCreateClassMultilines.applyStroke(entity, arg.get("LINECOLOR", 0)); - - // manageExtends(diagram, arg, entity); - CommandCreateClassMultilines.manageExtends("EXTENDS", diagram, arg, entity); - CommandCreateClassMultilines.manageExtends("IMPLEMENTS", diagram, arg, entity); - - return CommandExecutionResult.ok(); - } - - // public static void manageExtends(ClassDiagram system, RegexResult arg, final IEntity entity) { - // if (arg.get("EXTENDS", 1) != null) { - // final Mode mode = arg.get("EXTENDS", 1).equalsIgnoreCase("extends") ? Mode.EXTENDS : Mode.IMPLEMENTS; - // final Code other = Code.of(arg.get("EXTENDS", 2)); - // LeafType type2 = LeafType.CLASS; - // if (mode == Mode.IMPLEMENTS) { - // type2 = LeafType.INTERFACE; - // } - // if (mode == Mode.EXTENDS && entity.getEntityType() == LeafType.INTERFACE) { - // type2 = LeafType.INTERFACE; - // } - // final IEntity cl2 = system.getOrCreateLeaf(other, type2, null); - // LinkType typeLink = new LinkType(LinkDecor.NONE, LinkDecor.EXTENDS); - // if (type2 == LeafType.INTERFACE && entity.getEntityType() != LeafType.INTERFACE) { - // typeLink = typeLink.getDashed(); - // } - // final Link link = new Link(cl2, entity, typeLink, null, 2, null, null, system.getLabeldistance(), - // system.getLabelangle()); - // system.addLink(link); - // } - // } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/pair.info deleted file mode 100755 index 0c3a79c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22502/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22502 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClass.java -FixedFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClass.java -StartLineNum:97 -EndLineNum:97 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/diff.diff deleted file mode 100755 index abac156..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/command/CommandPragma.java b/src/net/sourceforge/plantuml/command/CommandPragma.java -index 13ba21cd..9f32b13b 100644 ---- a/src/net/sourceforge/plantuml/command/CommandPragma.java -+++ b/src/net/sourceforge/plantuml/command/CommandPragma.java -@@ -37,0 +38 @@ import java.util.List; -+import net.sourceforge.plantuml.StringUtils; -@@ -48 +49 @@ public class CommandPragma extends SingleLineCommand { -- system.getPragma().define(arg.get(0).toLowerCase(), arg.get(1)); -+ system.getPragma().define(StringUtils.goLowerCase(arg.get(0)), arg.get(1)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/new/CommandPragma.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/new/CommandPragma.java deleted file mode 100755 index 9f32b13..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/new/CommandPragma.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3828 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.UmlDiagram; - -public class CommandPragma extends SingleLineCommand { - - public CommandPragma() { - super("(?i)^!pragma[%s]+([A-Za-z_][A-Za-z_0-9]*)(?:[%s]+(.*))?$"); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram system, List arg) { - system.getPragma().define(StringUtils.goLowerCase(arg.get(0)), arg.get(1)); - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/old/CommandPragma.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/old/CommandPragma.java deleted file mode 100755 index 13ba21c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/old/CommandPragma.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3828 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; - -import net.sourceforge.plantuml.UmlDiagram; - -public class CommandPragma extends SingleLineCommand { - - public CommandPragma() { - super("(?i)^!pragma[%s]+([A-Za-z_][A-Za-z_0-9]*)(?:[%s]+(.*))?$"); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram system, List arg) { - system.getPragma().define(arg.get(0).toLowerCase(), arg.get(1)); - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/pair.info deleted file mode 100755 index fdcb43d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22509/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22509 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/command/CommandPragma.java -FixedFilePath:src/net/sourceforge/plantuml/command/CommandPragma.java -StartLineNum:48 -EndLineNum:48 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/diff.diff deleted file mode 100755 index 64939c1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/UmlDiagram.java b/src/net/sourceforge/plantuml/UmlDiagram.java -index becd57f1..d19f402d 100644 ---- a/src/net/sourceforge/plantuml/UmlDiagram.java -+++ b/src/net/sourceforge/plantuml/UmlDiagram.java -@@ -31 +31 @@ -- * Revision $Revision: 14086 $ -+ * Revision $Revision: 14727 $ -@@ -136 +136 @@ public abstract class UmlDiagram extends AbstractPSystem implements Diagram { -- skinParam.setParam(key.toLowerCase(), value); -+ skinParam.setParam(StringUtils.goLowerCase(key), value); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/new/UmlDiagram.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/new/UmlDiagram.java deleted file mode 100755 index d19f402..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/new/UmlDiagram.java +++ /dev/null @@ -1,422 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14727 $ - * - */ -package net.sourceforge.plantuml; - -import java.awt.Font; -import java.awt.geom.AffineTransform; -import java.awt.geom.Dimension2D; -import java.awt.image.BufferedImage; -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; - -import javax.imageio.ImageIO; -import javax.script.ScriptException; - -import net.sourceforge.plantuml.anim.Animation; -import net.sourceforge.plantuml.anim.AnimationDecoder; -import net.sourceforge.plantuml.api.ImageDataSimple; -import net.sourceforge.plantuml.core.Diagram; -import net.sourceforge.plantuml.core.ImageData; -import net.sourceforge.plantuml.core.UmlSource; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.cucadiagram.UnparsableGraphvizException; -import net.sourceforge.plantuml.flashcode.FlashCodeFactory; -import net.sourceforge.plantuml.flashcode.FlashCodeUtils; -import net.sourceforge.plantuml.fun.IconLoader; -import net.sourceforge.plantuml.graphic.GraphicPosition; -import net.sourceforge.plantuml.graphic.GraphicStrings; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; -import net.sourceforge.plantuml.graphic.HtmlColorUtils; -import net.sourceforge.plantuml.graphic.QuoteUtils; -import net.sourceforge.plantuml.graphic.UDrawable; -import net.sourceforge.plantuml.mjpeg.MJPEGGenerator; -import net.sourceforge.plantuml.pdf.PdfConverter; -import net.sourceforge.plantuml.svek.EmptySvgException; -import net.sourceforge.plantuml.svek.GraphvizCrash; -import net.sourceforge.plantuml.ugraphic.ColorMapperIdentity; -import net.sourceforge.plantuml.ugraphic.ImageBuilder; -import net.sourceforge.plantuml.ugraphic.Sprite; -import net.sourceforge.plantuml.ugraphic.UAntiAliasing; -import net.sourceforge.plantuml.ugraphic.UFont; -import net.sourceforge.plantuml.ugraphic.UGraphic; -import net.sourceforge.plantuml.ugraphic.UImage; -import net.sourceforge.plantuml.ugraphic.UTranslate; -import net.sourceforge.plantuml.version.Version; - -public abstract class UmlDiagram extends AbstractPSystem implements Diagram { - - private boolean rotation; - private boolean hideUnlinkedData; - - private int minwidth = Integer.MAX_VALUE; - - private Display title; - private Display header; - private Display footer; - private Display legend = null; - private HorizontalAlignment legendAlignment = HorizontalAlignment.CENTER; - - private HorizontalAlignment headerAlignment = HorizontalAlignment.RIGHT; - private HorizontalAlignment footerAlignment = HorizontalAlignment.CENTER; - private final Pragma pragma = new Pragma(); - private Scale scale; - private Animation animation; - - private final SkinParam skinParam = new SkinParam(getUmlDiagramType()); - - final public void setTitle(Display strings) { - this.title = strings; - } - - final public Display getTitle() { - return title; - } - - final public int getMinwidth() { - return minwidth; - } - - final public void setMinwidth(int minwidth) { - this.minwidth = minwidth; - } - - final public boolean isRotation() { - return rotation; - } - - final public void setRotation(boolean rotation) { - this.rotation = rotation; - } - - public final ISkinParam getSkinParam() { - return skinParam; - } - - public void setParam(String key, String value) { - skinParam.setParam(StringUtils.goLowerCase(key), value); - } - - public final Display getHeader() { - return header; - } - - public final void setHeader(Display header) { - this.header = header; - } - - public final Display getFooter() { - return footer; - } - - public final void setFooter(Display footer) { - this.footer = footer; - } - - public final HorizontalAlignment getHeaderAlignment() { - return headerAlignment; - } - - public final void setHeaderAlignment(HorizontalAlignment headerAlignment) { - this.headerAlignment = headerAlignment; - } - - public final HorizontalAlignment getFooterAlignment() { - return footerAlignment; - } - - public final void setFooterAlignment(HorizontalAlignment footerAlignment) { - this.footerAlignment = footerAlignment; - } - - abstract public UmlDiagramType getUmlDiagramType(); - - public Pragma getPragma() { - return pragma; - } - - final public void setScale(Scale scale) { - this.scale = scale; - } - - final public Scale getScale() { - return scale; - } - - final public void setAnimation(List animationData) { - try { - final AnimationDecoder animationDecoder = new AnimationDecoder(animationData); - this.animation = Animation.create(animationDecoder.decode()); - } catch (ScriptException e) { - e.printStackTrace(); - } - - } - - final public Animation getAnimation() { - return animation; - } - - public final double getDpiFactor(FileFormatOption fileFormatOption) { - if (getSkinParam().getDpi() == 96) { - return 1.0; - } - return getSkinParam().getDpi() / 96.0; - } - - public final int getDpi(FileFormatOption fileFormatOption) { - return getSkinParam().getDpi(); - } - - public final boolean isHideUnlinkedData() { - return hideUnlinkedData; - } - - public final void setHideUnlinkedData(boolean hideUnlinkedData) { - this.hideUnlinkedData = hideUnlinkedData; - } - - final public ImageData exportDiagram(OutputStream os, int index, FileFormatOption fileFormatOption) - throws IOException { - - if (fileFormatOption.getFileFormat() == FileFormat.PDF) { - return exportDiagramInternalPdf(os, index); - } - - try { - final ImageData imageData = exportDiagramInternal(os, index, fileFormatOption); - this.lastInfo = new Dimension2DDouble(imageData.getWidth(), imageData.getHeight()); - return imageData; - } catch (UnparsableGraphvizException e) { - e.printStackTrace(); - exportDiagramError(os, e.getCause(), fileFormatOption, e.getGraphvizVersion(), e.getDebugData()); - } catch (Exception e) { - e.printStackTrace(); - exportDiagramError(os, e, fileFormatOption, null, null); - } - return new ImageDataSimple(); - - } - - private void exportDiagramError(OutputStream os, Throwable exception, FileFormatOption fileFormat, - String graphvizVersion, String svg) throws IOException { - final UFont font = new UFont("SansSerif", Font.PLAIN, 12); - final List strings = getFailureText(exception, graphvizVersion); - - final String flash = getFlashData(); - for (StackTraceElement ste : exception.getStackTrace()) { - strings.add(" " + ste.toString()); - } - if (exception.getCause() != null) { - final Throwable cause = exception.getCause(); - strings.add(" "); - strings.add("Caused by " + cause.toString()); - for (StackTraceElement ste : cause.getStackTrace()) { - strings.add(" " + ste.toString()); - } - - } - - final ImageBuilder imageBuilder = new ImageBuilder(new ColorMapperIdentity(), 1.0, HtmlColorUtils.WHITE, - getMetadata(), null, 0, 0, null); - - final FlashCodeUtils utils = FlashCodeFactory.getFlashCodeUtils(); - final BufferedImage im = utils.exportFlashcode(flash); - if (im != null) { - GraphvizCrash.addDecodeHint(strings); - } - - final GraphicStrings graphicStrings = new GraphicStrings(strings, font, HtmlColorUtils.BLACK, - HtmlColorUtils.WHITE, UAntiAliasing.ANTI_ALIASING_ON, IconLoader.getRandom(), - GraphicPosition.BACKGROUND_CORNER_TOP_RIGHT); - - if (im == null) { - imageBuilder.addUDrawable(graphicStrings); - } else { - imageBuilder.addUDrawable(new UDrawable() { - public void drawU(UGraphic ug) { - graphicStrings.drawU(ug); - final double height = graphicStrings.calculateDimension(ug.getStringBounder()).getHeight(); - ug = ug.apply(new UTranslate(0, height)); - ug.draw(new UImage(im)); - } - }); - } - imageBuilder.writeImageTOBEMOVED(fileFormat.getFileFormat(), os); - } - - private String getFlashData() { - // for (Map.Entry ent : System.getProperties().entrySet()) { - // System.err.println("p1=" + ent.getKey() + " " + ent.getValue()); - // } - final StringBuilder result = new StringBuilder(); - final UmlSource source = getSource(); - result.append(source.getPlainString()); - return result.toString(); - } - - private List getFailureText(Throwable exception, String graphvizVersion) { - final List strings = new ArrayList(); - strings.add("An error has occured : " + exception); - final String quote = QuoteUtils.getSomeQuote(); - strings.add("" + quote); - strings.add(" "); - strings.add("PlantUML (" + Version.versionString() + ") cannot parse result from dot/GraphViz."); - if (exception instanceof EmptySvgException) { - strings.add("Because dot/GraphViz returns an empty string."); - } - if (graphvizVersion != null) { - strings.add(" "); - strings.add("GraphViz version used : " + graphvizVersion); - } - strings.add(" "); - GraphvizCrash.addProperties(strings); - strings.add(" "); - strings.add("This may be caused by :"); - strings.add(" - a bug in PlantUML"); - strings.add(" - a problem in GraphViz"); - strings.add(" "); - strings.add("You should send this diagram and this image to plantuml@gmail.com to solve this issue."); - strings.add("You can try to turn arround this issue by simplifing your diagram."); - strings.add(" "); - strings.add(exception.toString()); - return strings; - } - - private void exportDiagramInternalMjpeg(OutputStream os) throws IOException { - final File f = new File("c:/test.avi"); - final int nb = 150; - final double framerate = 30; - final MJPEGGenerator m = new MJPEGGenerator(f, 640, 480, framerate, nb); - - for (int i = 0; i < nb; i++) { - final AffineTransform at = new AffineTransform(); - final double coef = (nb - 1 - i) * 1.0 / nb; - at.setToShear(coef, coef); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - // exportDiagramTOxxBEREMOVED(baos, null, 0, new FileFormatOption(FileFormat.PNG, at)); - baos.close(); - final BufferedImage im = ImageIO.read(new ByteArrayInputStream(baos.toByteArray())); - m.addImage(im); - } - m.finishAVI(); - - } - - private Dimension2D lastInfo; - - private ImageData exportDiagramInternalPdf(OutputStream os, int index) throws IOException { - final File svg = FileUtils.createTempFile("pdf", ".svf"); - final File pdfFile = FileUtils.createTempFile("pdf", ".pdf"); - final OutputStream fos = new BufferedOutputStream(new FileOutputStream(svg)); - final ImageData result = exportDiagram(fos, index, new FileFormatOption(FileFormat.SVG)); - fos.close(); - PdfConverter.convert(svg, pdfFile); - FileUtils.copyToStream(pdfFile, os); - return result; - } - - protected abstract ImageData exportDiagramInternal(OutputStream os, int index, FileFormatOption fileFormatOption) - throws IOException; - - final protected void exportCmap(File suggestedFile, final ImageData cmapdata) throws FileNotFoundException { - final String name = changeName(suggestedFile.getAbsolutePath()); - final File cmapFile = new File(name); - PrintWriter pw = null; - try { - if (PSystemUtils.canFileBeWritten(cmapFile) == false) { - return; - } - pw = new PrintWriter(cmapFile); - pw.print(cmapdata.getCMapData(cmapFile.getName().substring(0, cmapFile.getName().length() - 6))); - pw.close(); - } finally { - if (pw != null) { - pw.close(); - } - } - } - - static String changeName(String name) { - return name.replaceAll("(?i)\\.\\w{3}$", ".cmapx"); - } - - @Override - public String getWarningOrError() { - if (lastInfo == null) { - return null; - } - final double actualWidth = lastInfo.getWidth(); - if (actualWidth == 0) { - return null; - } - final String value = getSkinParam().getValue("widthwarning"); - if (value == null) { - return null; - } - if (value.matches("\\d+") == false) { - return null; - } - final int widthwarning = Integer.parseInt(value); - if (actualWidth > widthwarning) { - return "The image is " + ((int) actualWidth) + " pixel width. (Warning limit is " + widthwarning + ")"; - } - return null; - } - - public void addSprite(String name, Sprite sprite) { - skinParam.addSprite(name, sprite); - } - - public final Display getLegend() { - return legend; - } - - public final HorizontalAlignment getLegendAlignment() { - return legendAlignment; - } - - public final void setLegend(Display legend, HorizontalAlignment horizontalAlignment) { - this.legend = legend; - this.legendAlignment = horizontalAlignment; - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/old/UmlDiagram.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/old/UmlDiagram.java deleted file mode 100755 index becd57f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/old/UmlDiagram.java +++ /dev/null @@ -1,422 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14086 $ - * - */ -package net.sourceforge.plantuml; - -import java.awt.Font; -import java.awt.geom.AffineTransform; -import java.awt.geom.Dimension2D; -import java.awt.image.BufferedImage; -import java.io.BufferedOutputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.List; - -import javax.imageio.ImageIO; -import javax.script.ScriptException; - -import net.sourceforge.plantuml.anim.Animation; -import net.sourceforge.plantuml.anim.AnimationDecoder; -import net.sourceforge.plantuml.api.ImageDataSimple; -import net.sourceforge.plantuml.core.Diagram; -import net.sourceforge.plantuml.core.ImageData; -import net.sourceforge.plantuml.core.UmlSource; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.cucadiagram.UnparsableGraphvizException; -import net.sourceforge.plantuml.flashcode.FlashCodeFactory; -import net.sourceforge.plantuml.flashcode.FlashCodeUtils; -import net.sourceforge.plantuml.fun.IconLoader; -import net.sourceforge.plantuml.graphic.GraphicPosition; -import net.sourceforge.plantuml.graphic.GraphicStrings; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; -import net.sourceforge.plantuml.graphic.HtmlColorUtils; -import net.sourceforge.plantuml.graphic.QuoteUtils; -import net.sourceforge.plantuml.graphic.UDrawable; -import net.sourceforge.plantuml.mjpeg.MJPEGGenerator; -import net.sourceforge.plantuml.pdf.PdfConverter; -import net.sourceforge.plantuml.svek.EmptySvgException; -import net.sourceforge.plantuml.svek.GraphvizCrash; -import net.sourceforge.plantuml.ugraphic.ColorMapperIdentity; -import net.sourceforge.plantuml.ugraphic.ImageBuilder; -import net.sourceforge.plantuml.ugraphic.Sprite; -import net.sourceforge.plantuml.ugraphic.UAntiAliasing; -import net.sourceforge.plantuml.ugraphic.UFont; -import net.sourceforge.plantuml.ugraphic.UGraphic; -import net.sourceforge.plantuml.ugraphic.UImage; -import net.sourceforge.plantuml.ugraphic.UTranslate; -import net.sourceforge.plantuml.version.Version; - -public abstract class UmlDiagram extends AbstractPSystem implements Diagram { - - private boolean rotation; - private boolean hideUnlinkedData; - - private int minwidth = Integer.MAX_VALUE; - - private Display title; - private Display header; - private Display footer; - private Display legend = null; - private HorizontalAlignment legendAlignment = HorizontalAlignment.CENTER; - - private HorizontalAlignment headerAlignment = HorizontalAlignment.RIGHT; - private HorizontalAlignment footerAlignment = HorizontalAlignment.CENTER; - private final Pragma pragma = new Pragma(); - private Scale scale; - private Animation animation; - - private final SkinParam skinParam = new SkinParam(getUmlDiagramType()); - - final public void setTitle(Display strings) { - this.title = strings; - } - - final public Display getTitle() { - return title; - } - - final public int getMinwidth() { - return minwidth; - } - - final public void setMinwidth(int minwidth) { - this.minwidth = minwidth; - } - - final public boolean isRotation() { - return rotation; - } - - final public void setRotation(boolean rotation) { - this.rotation = rotation; - } - - public final ISkinParam getSkinParam() { - return skinParam; - } - - public void setParam(String key, String value) { - skinParam.setParam(key.toLowerCase(), value); - } - - public final Display getHeader() { - return header; - } - - public final void setHeader(Display header) { - this.header = header; - } - - public final Display getFooter() { - return footer; - } - - public final void setFooter(Display footer) { - this.footer = footer; - } - - public final HorizontalAlignment getHeaderAlignment() { - return headerAlignment; - } - - public final void setHeaderAlignment(HorizontalAlignment headerAlignment) { - this.headerAlignment = headerAlignment; - } - - public final HorizontalAlignment getFooterAlignment() { - return footerAlignment; - } - - public final void setFooterAlignment(HorizontalAlignment footerAlignment) { - this.footerAlignment = footerAlignment; - } - - abstract public UmlDiagramType getUmlDiagramType(); - - public Pragma getPragma() { - return pragma; - } - - final public void setScale(Scale scale) { - this.scale = scale; - } - - final public Scale getScale() { - return scale; - } - - final public void setAnimation(List animationData) { - try { - final AnimationDecoder animationDecoder = new AnimationDecoder(animationData); - this.animation = Animation.create(animationDecoder.decode()); - } catch (ScriptException e) { - e.printStackTrace(); - } - - } - - final public Animation getAnimation() { - return animation; - } - - public final double getDpiFactor(FileFormatOption fileFormatOption) { - if (getSkinParam().getDpi() == 96) { - return 1.0; - } - return getSkinParam().getDpi() / 96.0; - } - - public final int getDpi(FileFormatOption fileFormatOption) { - return getSkinParam().getDpi(); - } - - public final boolean isHideUnlinkedData() { - return hideUnlinkedData; - } - - public final void setHideUnlinkedData(boolean hideUnlinkedData) { - this.hideUnlinkedData = hideUnlinkedData; - } - - final public ImageData exportDiagram(OutputStream os, int index, FileFormatOption fileFormatOption) - throws IOException { - - if (fileFormatOption.getFileFormat() == FileFormat.PDF) { - return exportDiagramInternalPdf(os, index); - } - - try { - final ImageData imageData = exportDiagramInternal(os, index, fileFormatOption); - this.lastInfo = new Dimension2DDouble(imageData.getWidth(), imageData.getHeight()); - return imageData; - } catch (UnparsableGraphvizException e) { - e.printStackTrace(); - exportDiagramError(os, e.getCause(), fileFormatOption, e.getGraphvizVersion(), e.getDebugData()); - } catch (Exception e) { - e.printStackTrace(); - exportDiagramError(os, e, fileFormatOption, null, null); - } - return new ImageDataSimple(); - - } - - private void exportDiagramError(OutputStream os, Throwable exception, FileFormatOption fileFormat, - String graphvizVersion, String svg) throws IOException { - final UFont font = new UFont("SansSerif", Font.PLAIN, 12); - final List strings = getFailureText(exception, graphvizVersion); - - final String flash = getFlashData(); - for (StackTraceElement ste : exception.getStackTrace()) { - strings.add(" " + ste.toString()); - } - if (exception.getCause() != null) { - final Throwable cause = exception.getCause(); - strings.add(" "); - strings.add("Caused by " + cause.toString()); - for (StackTraceElement ste : cause.getStackTrace()) { - strings.add(" " + ste.toString()); - } - - } - - final ImageBuilder imageBuilder = new ImageBuilder(new ColorMapperIdentity(), 1.0, HtmlColorUtils.WHITE, - getMetadata(), null, 0, 0, null); - - final FlashCodeUtils utils = FlashCodeFactory.getFlashCodeUtils(); - final BufferedImage im = utils.exportFlashcode(flash); - if (im != null) { - GraphvizCrash.addDecodeHint(strings); - } - - final GraphicStrings graphicStrings = new GraphicStrings(strings, font, HtmlColorUtils.BLACK, - HtmlColorUtils.WHITE, UAntiAliasing.ANTI_ALIASING_ON, IconLoader.getRandom(), - GraphicPosition.BACKGROUND_CORNER_TOP_RIGHT); - - if (im == null) { - imageBuilder.addUDrawable(graphicStrings); - } else { - imageBuilder.addUDrawable(new UDrawable() { - public void drawU(UGraphic ug) { - graphicStrings.drawU(ug); - final double height = graphicStrings.calculateDimension(ug.getStringBounder()).getHeight(); - ug = ug.apply(new UTranslate(0, height)); - ug.draw(new UImage(im)); - } - }); - } - imageBuilder.writeImageTOBEMOVED(fileFormat.getFileFormat(), os); - } - - private String getFlashData() { - // for (Map.Entry ent : System.getProperties().entrySet()) { - // System.err.println("p1=" + ent.getKey() + " " + ent.getValue()); - // } - final StringBuilder result = new StringBuilder(); - final UmlSource source = getSource(); - result.append(source.getPlainString()); - return result.toString(); - } - - private List getFailureText(Throwable exception, String graphvizVersion) { - final List strings = new ArrayList(); - strings.add("An error has occured : " + exception); - final String quote = QuoteUtils.getSomeQuote(); - strings.add("" + quote); - strings.add(" "); - strings.add("PlantUML (" + Version.versionString() + ") cannot parse result from dot/GraphViz."); - if (exception instanceof EmptySvgException) { - strings.add("Because dot/GraphViz returns an empty string."); - } - if (graphvizVersion != null) { - strings.add(" "); - strings.add("GraphViz version used : " + graphvizVersion); - } - strings.add(" "); - GraphvizCrash.addProperties(strings); - strings.add(" "); - strings.add("This may be caused by :"); - strings.add(" - a bug in PlantUML"); - strings.add(" - a problem in GraphViz"); - strings.add(" "); - strings.add("You should send this diagram and this image to plantuml@gmail.com to solve this issue."); - strings.add("You can try to turn arround this issue by simplifing your diagram."); - strings.add(" "); - strings.add(exception.toString()); - return strings; - } - - private void exportDiagramInternalMjpeg(OutputStream os) throws IOException { - final File f = new File("c:/test.avi"); - final int nb = 150; - final double framerate = 30; - final MJPEGGenerator m = new MJPEGGenerator(f, 640, 480, framerate, nb); - - for (int i = 0; i < nb; i++) { - final AffineTransform at = new AffineTransform(); - final double coef = (nb - 1 - i) * 1.0 / nb; - at.setToShear(coef, coef); - final ByteArrayOutputStream baos = new ByteArrayOutputStream(); - // exportDiagramTOxxBEREMOVED(baos, null, 0, new FileFormatOption(FileFormat.PNG, at)); - baos.close(); - final BufferedImage im = ImageIO.read(new ByteArrayInputStream(baos.toByteArray())); - m.addImage(im); - } - m.finishAVI(); - - } - - private Dimension2D lastInfo; - - private ImageData exportDiagramInternalPdf(OutputStream os, int index) throws IOException { - final File svg = FileUtils.createTempFile("pdf", ".svf"); - final File pdfFile = FileUtils.createTempFile("pdf", ".pdf"); - final OutputStream fos = new BufferedOutputStream(new FileOutputStream(svg)); - final ImageData result = exportDiagram(fos, index, new FileFormatOption(FileFormat.SVG)); - fos.close(); - PdfConverter.convert(svg, pdfFile); - FileUtils.copyToStream(pdfFile, os); - return result; - } - - protected abstract ImageData exportDiagramInternal(OutputStream os, int index, FileFormatOption fileFormatOption) - throws IOException; - - final protected void exportCmap(File suggestedFile, final ImageData cmapdata) throws FileNotFoundException { - final String name = changeName(suggestedFile.getAbsolutePath()); - final File cmapFile = new File(name); - PrintWriter pw = null; - try { - if (PSystemUtils.canFileBeWritten(cmapFile) == false) { - return; - } - pw = new PrintWriter(cmapFile); - pw.print(cmapdata.getCMapData(cmapFile.getName().substring(0, cmapFile.getName().length() - 6))); - pw.close(); - } finally { - if (pw != null) { - pw.close(); - } - } - } - - static String changeName(String name) { - return name.replaceAll("(?i)\\.\\w{3}$", ".cmapx"); - } - - @Override - public String getWarningOrError() { - if (lastInfo == null) { - return null; - } - final double actualWidth = lastInfo.getWidth(); - if (actualWidth == 0) { - return null; - } - final String value = getSkinParam().getValue("widthwarning"); - if (value == null) { - return null; - } - if (value.matches("\\d+") == false) { - return null; - } - final int widthwarning = Integer.parseInt(value); - if (actualWidth > widthwarning) { - return "The image is " + ((int) actualWidth) + " pixel width. (Warning limit is " + widthwarning + ")"; - } - return null; - } - - public void addSprite(String name, Sprite sprite) { - skinParam.addSprite(name, sprite); - } - - public final Display getLegend() { - return legend; - } - - public final HorizontalAlignment getLegendAlignment() { - return legendAlignment; - } - - public final void setLegend(Display legend, HorizontalAlignment horizontalAlignment) { - this.legend = legend; - this.legendAlignment = horizontalAlignment; - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/pair.info deleted file mode 100755 index 55789d8..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22514/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22514 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/UmlDiagram.java -FixedFilePath:src/net/sourceforge/plantuml/UmlDiagram.java -StartLineNum:136 -EndLineNum:136 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/diff.diff deleted file mode 100755 index 416f721..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow3.java b/src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow3.java -index a3643b15..54234235 100644 ---- a/src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow3.java -+++ b/src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow3.java -@@ -39,0 +40 @@ import java.util.StringTokenizer; -+import net.sourceforge.plantuml.StringUtils; -@@ -87 +88 @@ public class CommandHideShow3 extends SingleLineCommand2 { -- final StringTokenizer st = new StringTokenizer(arg.get("VISIBILITY", 0).toLowerCase(), " ,"); -+ final StringTokenizer st = new StringTokenizer(StringUtils.goLowerCase(arg.get("VISIBILITY", 0)), " ,"); -@@ -125 +126 @@ public class CommandHideShow3 extends SingleLineCommand2 { -- final String sub = s.substring(0, 3).toLowerCase(); -+ final String sub = StringUtils.goLowerCase(s.substring(0, 3)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/new/CommandHideShow3.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/new/CommandHideShow3.java deleted file mode 100755 index 5423423..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/new/CommandHideShow3.java +++ /dev/null @@ -1,139 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5019 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.util.EnumSet; -import java.util.Set; -import java.util.StringTokenizer; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.classdiagram.ClassDiagram; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.EntityPortion; -import net.sourceforge.plantuml.skin.VisibilityModifier; - -public class CommandHideShow3 extends SingleLineCommand2 { - - private static final EnumSet PORTION_METHOD = EnumSet. of(EntityPortion.METHOD); - private static final EnumSet PORTION_MEMBER = EnumSet. of(EntityPortion.FIELD, - EntityPortion.METHOD); - private static final EnumSet PORTION_FIELD = EnumSet. of(EntityPortion.FIELD); - - public CommandHideShow3() { - super(getRegexConcat()); - } - - static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("COMMAND", "(hide|show)"), // - new RegexLeaf("[%s]+"), // - new RegexLeaf("VISIBILITY", - "((?:public|private|protected|package)?(?:[,%s]+(?:public|private|protected|package))*)"), // - new RegexLeaf("[%s]+"), // - new RegexLeaf("PORTION", "(members?|attributes?|fields?|methods?)"), // - new RegexLeaf("$")); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram classDiagram, RegexResult arg) { - if (classDiagram instanceof ClassDiagram) { - return executeArgClass((ClassDiagram) classDiagram, arg); - } - // Just ignored - return CommandExecutionResult.ok(); - } - - - private CommandExecutionResult executeArgClass(ClassDiagram classDiagram, RegexResult arg) { - - final Set portion = getEntityPortion(arg.get("PORTION", 0)); - - final Set visibilities = EnumSet. noneOf(VisibilityModifier.class); - final StringTokenizer st = new StringTokenizer(StringUtils.goLowerCase(arg.get("VISIBILITY", 0)), " ,"); - while (st.hasMoreTokens()) { - addVisibilities(st.nextToken(), portion, visibilities); - } - - classDiagram.hideOrShow(visibilities, arg.get("COMMAND", 0).equalsIgnoreCase("show")); - - return CommandExecutionResult.ok(); - } - - private void addVisibilities(String token, Set portion, Set result) { - if (token.equals("public") && portion.contains(EntityPortion.FIELD)) { - result.add(VisibilityModifier.PUBLIC_FIELD); - } - if (token.equals("public") && portion.contains(EntityPortion.METHOD)) { - result.add(VisibilityModifier.PUBLIC_METHOD); - } - if (token.equals("private") && portion.contains(EntityPortion.FIELD)) { - result.add(VisibilityModifier.PRIVATE_FIELD); - } - if (token.equals("private") && portion.contains(EntityPortion.METHOD)) { - result.add(VisibilityModifier.PRIVATE_METHOD); - } - if (token.equals("protected") && portion.contains(EntityPortion.FIELD)) { - result.add(VisibilityModifier.PROTECTED_FIELD); - } - if (token.equals("protected") && portion.contains(EntityPortion.METHOD)) { - result.add(VisibilityModifier.PROTECTED_METHOD); - } - if (token.equals("package") && portion.contains(EntityPortion.FIELD)) { - result.add(VisibilityModifier.PACKAGE_PRIVATE_FIELD); - } - if (token.equals("package") && portion.contains(EntityPortion.METHOD)) { - result.add(VisibilityModifier.PACKAGE_PRIVATE_METHOD); - } - } - - private Set getEntityPortion(String s) { - final String sub = StringUtils.goLowerCase(s.substring(0, 3)); - if (sub.equals("met")) { - return PORTION_METHOD; - } - if (sub.equals("mem")) { - return PORTION_MEMBER; - } - if (sub.equals("att") || sub.equals("fie")) { - return PORTION_FIELD; - } - throw new IllegalArgumentException(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/old/CommandHideShow3.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/old/CommandHideShow3.java deleted file mode 100755 index a3643b1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/old/CommandHideShow3.java +++ /dev/null @@ -1,138 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5019 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.util.EnumSet; -import java.util.Set; -import java.util.StringTokenizer; - -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.classdiagram.ClassDiagram; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.EntityPortion; -import net.sourceforge.plantuml.skin.VisibilityModifier; - -public class CommandHideShow3 extends SingleLineCommand2 { - - private static final EnumSet PORTION_METHOD = EnumSet. of(EntityPortion.METHOD); - private static final EnumSet PORTION_MEMBER = EnumSet. of(EntityPortion.FIELD, - EntityPortion.METHOD); - private static final EnumSet PORTION_FIELD = EnumSet. of(EntityPortion.FIELD); - - public CommandHideShow3() { - super(getRegexConcat()); - } - - static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("COMMAND", "(hide|show)"), // - new RegexLeaf("[%s]+"), // - new RegexLeaf("VISIBILITY", - "((?:public|private|protected|package)?(?:[,%s]+(?:public|private|protected|package))*)"), // - new RegexLeaf("[%s]+"), // - new RegexLeaf("PORTION", "(members?|attributes?|fields?|methods?)"), // - new RegexLeaf("$")); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram classDiagram, RegexResult arg) { - if (classDiagram instanceof ClassDiagram) { - return executeArgClass((ClassDiagram) classDiagram, arg); - } - // Just ignored - return CommandExecutionResult.ok(); - } - - - private CommandExecutionResult executeArgClass(ClassDiagram classDiagram, RegexResult arg) { - - final Set portion = getEntityPortion(arg.get("PORTION", 0)); - - final Set visibilities = EnumSet. noneOf(VisibilityModifier.class); - final StringTokenizer st = new StringTokenizer(arg.get("VISIBILITY", 0).toLowerCase(), " ,"); - while (st.hasMoreTokens()) { - addVisibilities(st.nextToken(), portion, visibilities); - } - - classDiagram.hideOrShow(visibilities, arg.get("COMMAND", 0).equalsIgnoreCase("show")); - - return CommandExecutionResult.ok(); - } - - private void addVisibilities(String token, Set portion, Set result) { - if (token.equals("public") && portion.contains(EntityPortion.FIELD)) { - result.add(VisibilityModifier.PUBLIC_FIELD); - } - if (token.equals("public") && portion.contains(EntityPortion.METHOD)) { - result.add(VisibilityModifier.PUBLIC_METHOD); - } - if (token.equals("private") && portion.contains(EntityPortion.FIELD)) { - result.add(VisibilityModifier.PRIVATE_FIELD); - } - if (token.equals("private") && portion.contains(EntityPortion.METHOD)) { - result.add(VisibilityModifier.PRIVATE_METHOD); - } - if (token.equals("protected") && portion.contains(EntityPortion.FIELD)) { - result.add(VisibilityModifier.PROTECTED_FIELD); - } - if (token.equals("protected") && portion.contains(EntityPortion.METHOD)) { - result.add(VisibilityModifier.PROTECTED_METHOD); - } - if (token.equals("package") && portion.contains(EntityPortion.FIELD)) { - result.add(VisibilityModifier.PACKAGE_PRIVATE_FIELD); - } - if (token.equals("package") && portion.contains(EntityPortion.METHOD)) { - result.add(VisibilityModifier.PACKAGE_PRIVATE_METHOD); - } - } - - private Set getEntityPortion(String s) { - final String sub = s.substring(0, 3).toLowerCase(); - if (sub.equals("met")) { - return PORTION_METHOD; - } - if (sub.equals("mem")) { - return PORTION_MEMBER; - } - if (sub.equals("att") || sub.equals("fie")) { - return PORTION_FIELD; - } - throw new IllegalArgumentException(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/pair.info deleted file mode 100755 index 5990357..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22516/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22516 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow3.java -FixedFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandHideShow3.java -StartLineNum:125 -EndLineNum:125 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/diff.diff deleted file mode 100755 index b9720a5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/skin/SkinUtils.java b/src/net/sourceforge/plantuml/skin/SkinUtils.java -index 5a4fca7c..14541735 100644 ---- a/src/net/sourceforge/plantuml/skin/SkinUtils.java -+++ b/src/net/sourceforge/plantuml/skin/SkinUtils.java -@@ -31 +31 @@ -- * Revision $Revision: 12235 $ -+ * Revision $Revision: 14727 $ -@@ -39,0 +40 @@ import net.sourceforge.plantuml.Log; -+import net.sourceforge.plantuml.StringUtils; -@@ -53 +54 @@ public class SkinUtils { -- final String packageName = className.toLowerCase(); -+ final String packageName = StringUtils.goLowerCase(className); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/new/SkinUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/new/SkinUtils.java deleted file mode 100755 index 1454173..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/new/SkinUtils.java +++ /dev/null @@ -1,78 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14727 $ - * - */ -package net.sourceforge.plantuml.skin; - -import java.util.ArrayList; -import java.util.List; - -import net.sourceforge.plantuml.Log; -import net.sourceforge.plantuml.StringUtils; - -public class SkinUtils { - - static public Skin loadSkin(String className) { - final List errors = new ArrayList(); - Skin result = tryLoading(className, errors); - if (result != null) { - return result; - } - result = tryLoading("net.sourceforge.plantuml.skin." + className, errors); - if (result != null) { - return result; - } - final String packageName = StringUtils.goLowerCase(className); - result = tryLoading(packageName + "." + className, errors); - if (result != null) { - return result; - } - result = tryLoading("net.sourceforge.plantuml.skin." + packageName + "." + className, errors); - if (result != null) { - return result; - } - for (String e : errors) { - Log.println("err="+e); - } - return null; - } - - private static Skin tryLoading(String className, List errors) { - try { - final Class cl = (Class) Class.forName(className); - return cl.newInstance(); - } catch (Exception e) { - errors.add("Cannot load " + className); - return null; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/old/SkinUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/old/SkinUtils.java deleted file mode 100755 index 5a4fca7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/old/SkinUtils.java +++ /dev/null @@ -1,77 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 12235 $ - * - */ -package net.sourceforge.plantuml.skin; - -import java.util.ArrayList; -import java.util.List; - -import net.sourceforge.plantuml.Log; - -public class SkinUtils { - - static public Skin loadSkin(String className) { - final List errors = new ArrayList(); - Skin result = tryLoading(className, errors); - if (result != null) { - return result; - } - result = tryLoading("net.sourceforge.plantuml.skin." + className, errors); - if (result != null) { - return result; - } - final String packageName = className.toLowerCase(); - result = tryLoading(packageName + "." + className, errors); - if (result != null) { - return result; - } - result = tryLoading("net.sourceforge.plantuml.skin." + packageName + "." + className, errors); - if (result != null) { - return result; - } - for (String e : errors) { - Log.println("err="+e); - } - return null; - } - - private static Skin tryLoading(String className, List errors) { - try { - final Class cl = (Class) Class.forName(className); - return cl.newInstance(); - } catch (Exception e) { - errors.add("Cannot load " + className); - return null; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/pair.info deleted file mode 100755 index f2b2ea7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22517/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22517 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/skin/SkinUtils.java -FixedFilePath:src/net/sourceforge/plantuml/skin/SkinUtils.java -StartLineNum:53 -EndLineNum:53 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/diff.diff deleted file mode 100755 index 517bf8e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/asciiart/ComponentTextGroupingHeader.java b/src/net/sourceforge/plantuml/asciiart/ComponentTextGroupingHeader.java -index fd01e9a2..3e2addc4 100644 ---- a/src/net/sourceforge/plantuml/asciiart/ComponentTextGroupingHeader.java -+++ b/src/net/sourceforge/plantuml/asciiart/ComponentTextGroupingHeader.java -@@ -73 +73 @@ public class ComponentTextGroupingHeader extends AbstractComponentText { -- charArea.drawStringLR(text.toUpperCase() + " /", 2, 1); -+ charArea.drawStringLR(StringUtils.goUpperCase(text) + " /", 2, 1); -@@ -86 +86 @@ public class ComponentTextGroupingHeader extends AbstractComponentText { -- charArea.drawStringLR(text.toUpperCase() + " /", 2, 1); -+ charArea.drawStringLR(StringUtils.goUpperCase(text) + " /", 2, 1); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/new/ComponentTextGroupingHeader.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/new/ComponentTextGroupingHeader.java deleted file mode 100755 index 3e2addc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/new/ComponentTextGroupingHeader.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4169 $ - * - */ -package net.sourceforge.plantuml.asciiart; - -import java.awt.geom.Dimension2D; - -import net.sourceforge.plantuml.FileFormat; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.StringBounder; -import net.sourceforge.plantuml.skin.Area; -import net.sourceforge.plantuml.skin.Component; -import net.sourceforge.plantuml.skin.ComponentType; -import net.sourceforge.plantuml.skin.Context2D; -import net.sourceforge.plantuml.ugraphic.UGraphic; -import net.sourceforge.plantuml.ugraphic.txt.UGraphicTxt; -import net.sourceforge.plantuml.StringUtils; - -public class ComponentTextGroupingHeader extends AbstractComponentText { - - private final ComponentType type; - private final Display stringsToDisplay; - private final FileFormat fileFormat; - - public ComponentTextGroupingHeader(ComponentType type, Display stringsToDisplay, - FileFormat fileFormat) { - this.type = type; - this.stringsToDisplay = stringsToDisplay; - this.fileFormat = fileFormat; - } - - public void drawU(UGraphic ug, Area area, Context2D context) { - final Dimension2D dimensionToUse = area.getDimensionToUse(); - final UmlCharArea charArea = ((UGraphicTxt) ug).getCharArea(); - final int width = (int) dimensionToUse.getWidth(); - final int height = (int) dimensionToUse.getHeight(); - - // charArea.fillRect('G', 0, 0, width, height); - final String text = stringsToDisplay.get(0).toString(); - - if (fileFormat == FileFormat.UTXT) { - charArea.drawHLine('\u2550', 0, 1, width - 1, '\u2502', '\u256a'); - charArea.drawStringLR(StringUtils.goUpperCase(text) + " /", 2, 1); - charArea.drawHLine('\u2500', 2, 1, text.length() + 4); - charArea.drawVLine('\u2551', 0, 1, height - 1); - charArea.drawVLine('\u2551', width - 1, 1, height - 1); - charArea.drawChar('\u255f', 0, 2); - charArea.drawStringTB("\u2564\u2502\u2518", text.length() + 4, 0); - charArea.drawChar('\u2554', 0, 0); - charArea.drawChar('\u2557', width - 1, 0); - charArea.drawHLine('\u2550', height - 1, 1, width - 1, '\u2502', '\u256a'); - charArea.drawChar('\u255a', 0, height - 1); - charArea.drawChar('\u255d', width - 1, height - 1); - } else { - charArea.drawHLine('_', 0, 0, width - 1); - charArea.drawStringLR(StringUtils.goUpperCase(text) + " /", 2, 1); - charArea.drawHLine('_', 2, 1, text.length() + 3); - charArea.drawChar('/', text.length() + 3, 2); - charArea.drawVLine('!', 0, 1, height); - charArea.drawVLine('!', width - 1, 1, height); - charArea.drawHLine('~', height - 1, 1, width - 1); - } - - if (stringsToDisplay.size() > 1) { - final String comment = stringsToDisplay.get(1).toString(); - charArea.drawStringLR(comment, text.length() + 7, 1); - - } - } - - public double getPreferredHeight(StringBounder stringBounder) { - return StringUtils.getHeight(stringsToDisplay) + 1; - } - - public double getPreferredWidth(StringBounder stringBounder) { - return StringUtils.getWidth(stringsToDisplay) + 2; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/old/ComponentTextGroupingHeader.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/old/ComponentTextGroupingHeader.java deleted file mode 100755 index fd01e9a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/old/ComponentTextGroupingHeader.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4169 $ - * - */ -package net.sourceforge.plantuml.asciiart; - -import java.awt.geom.Dimension2D; - -import net.sourceforge.plantuml.FileFormat; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.StringBounder; -import net.sourceforge.plantuml.skin.Area; -import net.sourceforge.plantuml.skin.Component; -import net.sourceforge.plantuml.skin.ComponentType; -import net.sourceforge.plantuml.skin.Context2D; -import net.sourceforge.plantuml.ugraphic.UGraphic; -import net.sourceforge.plantuml.ugraphic.txt.UGraphicTxt; -import net.sourceforge.plantuml.StringUtils; - -public class ComponentTextGroupingHeader extends AbstractComponentText { - - private final ComponentType type; - private final Display stringsToDisplay; - private final FileFormat fileFormat; - - public ComponentTextGroupingHeader(ComponentType type, Display stringsToDisplay, - FileFormat fileFormat) { - this.type = type; - this.stringsToDisplay = stringsToDisplay; - this.fileFormat = fileFormat; - } - - public void drawU(UGraphic ug, Area area, Context2D context) { - final Dimension2D dimensionToUse = area.getDimensionToUse(); - final UmlCharArea charArea = ((UGraphicTxt) ug).getCharArea(); - final int width = (int) dimensionToUse.getWidth(); - final int height = (int) dimensionToUse.getHeight(); - - // charArea.fillRect('G', 0, 0, width, height); - final String text = stringsToDisplay.get(0).toString(); - - if (fileFormat == FileFormat.UTXT) { - charArea.drawHLine('\u2550', 0, 1, width - 1, '\u2502', '\u256a'); - charArea.drawStringLR(text.toUpperCase() + " /", 2, 1); - charArea.drawHLine('\u2500', 2, 1, text.length() + 4); - charArea.drawVLine('\u2551', 0, 1, height - 1); - charArea.drawVLine('\u2551', width - 1, 1, height - 1); - charArea.drawChar('\u255f', 0, 2); - charArea.drawStringTB("\u2564\u2502\u2518", text.length() + 4, 0); - charArea.drawChar('\u2554', 0, 0); - charArea.drawChar('\u2557', width - 1, 0); - charArea.drawHLine('\u2550', height - 1, 1, width - 1, '\u2502', '\u256a'); - charArea.drawChar('\u255a', 0, height - 1); - charArea.drawChar('\u255d', width - 1, height - 1); - } else { - charArea.drawHLine('_', 0, 0, width - 1); - charArea.drawStringLR(text.toUpperCase() + " /", 2, 1); - charArea.drawHLine('_', 2, 1, text.length() + 3); - charArea.drawChar('/', text.length() + 3, 2); - charArea.drawVLine('!', 0, 1, height); - charArea.drawVLine('!', width - 1, 1, height); - charArea.drawHLine('~', height - 1, 1, width - 1); - } - - if (stringsToDisplay.size() > 1) { - final String comment = stringsToDisplay.get(1).toString(); - charArea.drawStringLR(comment, text.length() + 7, 1); - - } - } - - public double getPreferredHeight(StringBounder stringBounder) { - return StringUtils.getHeight(stringsToDisplay) + 1; - } - - public double getPreferredWidth(StringBounder stringBounder) { - return StringUtils.getWidth(stringsToDisplay) + 2; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/pair.info deleted file mode 100755 index 1e9df15..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22536/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22536 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/asciiart/ComponentTextGroupingHeader.java -FixedFilePath:src/net/sourceforge/plantuml/asciiart/ComponentTextGroupingHeader.java -StartLineNum:73 -EndLineNum:73 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/diff.diff deleted file mode 100755 index 6346a50..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/openiconic/PSystemOpenIconicFactory.java b/src/net/sourceforge/plantuml/openiconic/PSystemOpenIconicFactory.java -index a6033487..4454079c 100644 ---- a/src/net/sourceforge/plantuml/openiconic/PSystemOpenIconicFactory.java -+++ b/src/net/sourceforge/plantuml/openiconic/PSystemOpenIconicFactory.java -@@ -36,0 +37 @@ import net.sourceforge.plantuml.AbstractPSystem; -+import net.sourceforge.plantuml.StringUtils; -@@ -43 +44 @@ public class PSystemOpenIconicFactory extends PSystemSingleLineFactory { -- final String lineLower = line.toLowerCase(); -+ final String lineLower = StringUtils.goLowerCase(line); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/new/PSystemOpenIconicFactory.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/new/PSystemOpenIconicFactory.java deleted file mode 100755 index 4454079..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/new/PSystemOpenIconicFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3830 $ - * - */ -package net.sourceforge.plantuml.openiconic; - -import net.sourceforge.plantuml.AbstractPSystem; -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.command.PSystemSingleLineFactory; - -public class PSystemOpenIconicFactory extends PSystemSingleLineFactory { - - @Override - protected AbstractPSystem executeLine(String line) { - final String lineLower = StringUtils.goLowerCase(line); - if (lineLower.startsWith("openiconic ")) { - final int idx = line.indexOf(' '); - return new PSystemOpenIconic(lineLower.substring(idx + 1), 1.0); - } - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/old/PSystemOpenIconicFactory.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/old/PSystemOpenIconicFactory.java deleted file mode 100755 index a603348..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/old/PSystemOpenIconicFactory.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3830 $ - * - */ -package net.sourceforge.plantuml.openiconic; - -import net.sourceforge.plantuml.AbstractPSystem; -import net.sourceforge.plantuml.command.PSystemSingleLineFactory; - -public class PSystemOpenIconicFactory extends PSystemSingleLineFactory { - - @Override - protected AbstractPSystem executeLine(String line) { - final String lineLower = line.toLowerCase(); - if (lineLower.startsWith("openiconic ")) { - final int idx = line.indexOf(' '); - return new PSystemOpenIconic(lineLower.substring(idx + 1), 1.0); - } - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/pair.info deleted file mode 100755 index 5ff3d1e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22570/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22570 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/openiconic/PSystemOpenIconicFactory.java -FixedFilePath:src/net/sourceforge/plantuml/openiconic/PSystemOpenIconicFactory.java -StartLineNum:43 -EndLineNum:43 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/diff.diff deleted file mode 100755 index 7a5fc9f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/sequencediagram/command/CommandActivate.java b/src/net/sourceforge/plantuml/sequencediagram/command/CommandActivate.java -index e826989f..69e08b6d 100644 ---- a/src/net/sourceforge/plantuml/sequencediagram/command/CommandActivate.java -+++ b/src/net/sourceforge/plantuml/sequencediagram/command/CommandActivate.java -@@ -31 +31 @@ -- * Revision $Revision: 14321 $ -+ * Revision $Revision: 14726 $ -@@ -53 +53 @@ public class CommandActivate extends SingleLineCommand { -- final LifeEventType type = LifeEventType.valueOf(arg.get(0).toUpperCase()); -+ final LifeEventType type = LifeEventType.valueOf(StringUtils.goUpperCase(arg.get(0))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/new/CommandActivate.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/new/CommandActivate.java deleted file mode 100755 index 69e08b6..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/new/CommandActivate.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14726 $ - * - */ -package net.sourceforge.plantuml.sequencediagram.command; - -import java.util.List; - -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand; -import net.sourceforge.plantuml.sequencediagram.LifeEventType; -import net.sourceforge.plantuml.sequencediagram.Participant; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagram; -import net.sourceforge.plantuml.StringUtils; - -public class CommandActivate extends SingleLineCommand { - - public CommandActivate() { - super("(?i)^(activate|deactivate|destroy|create)[%s]+([\\p{L}0-9_.@]+|[%g][^%g]+[%g])[%s]*(#\\w+)?$"); - } - - @Override - protected CommandExecutionResult executeArg(SequenceDiagram diagram, List arg) { - final LifeEventType type = LifeEventType.valueOf(StringUtils.goUpperCase(arg.get(0))); - final Participant p = diagram.getOrCreateParticipant(StringUtils - .eventuallyRemoveStartingAndEndingDoubleQuote(arg.get(1))); - final String error = diagram.activate(p, type, - diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get(2))); - if (error == null) { - return CommandExecutionResult.ok(); - } - return CommandExecutionResult.error(error); - - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/old/CommandActivate.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/old/CommandActivate.java deleted file mode 100755 index e826989..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/old/CommandActivate.java +++ /dev/null @@ -1,65 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14321 $ - * - */ -package net.sourceforge.plantuml.sequencediagram.command; - -import java.util.List; - -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand; -import net.sourceforge.plantuml.sequencediagram.LifeEventType; -import net.sourceforge.plantuml.sequencediagram.Participant; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagram; -import net.sourceforge.plantuml.StringUtils; - -public class CommandActivate extends SingleLineCommand { - - public CommandActivate() { - super("(?i)^(activate|deactivate|destroy|create)[%s]+([\\p{L}0-9_.@]+|[%g][^%g]+[%g])[%s]*(#\\w+)?$"); - } - - @Override - protected CommandExecutionResult executeArg(SequenceDiagram diagram, List arg) { - final LifeEventType type = LifeEventType.valueOf(arg.get(0).toUpperCase()); - final Participant p = diagram.getOrCreateParticipant(StringUtils - .eventuallyRemoveStartingAndEndingDoubleQuote(arg.get(1))); - final String error = diagram.activate(p, type, - diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get(2))); - if (error == null) { - return CommandExecutionResult.ok(); - } - return CommandExecutionResult.error(error); - - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/pair.info deleted file mode 100755 index ee70148..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22597/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22597 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/sequencediagram/command/CommandActivate.java -FixedFilePath:src/net/sourceforge/plantuml/sequencediagram/command/CommandActivate.java -StartLineNum:53 -EndLineNum:53 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/diff.diff deleted file mode 100755 index 6d91161..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/sequencediagram/command/CommandParticipant.java b/src/net/sourceforge/plantuml/sequencediagram/command/CommandParticipant.java -index 2accd351..db907a74 100644 ---- a/src/net/sourceforge/plantuml/sequencediagram/command/CommandParticipant.java -+++ b/src/net/sourceforge/plantuml/sequencediagram/command/CommandParticipant.java -@@ -37,0 +38 @@ import net.sourceforge.plantuml.ISkinParam; -+import net.sourceforge.plantuml.StringUtils; -@@ -85 +86 @@ public abstract class CommandParticipant extends SingleLineCommand2 { - - public CommandParticipant(RegexConcat pattern) { - super(pattern); - } - - static IRegex getRegexType() { - return new RegexOr(new RegexLeaf("TYPE", "(participant|actor|create|boundary|control|entity|database)"), // - new RegexLeaf("CREATE", "create[%s](participant|actor|boundary|control|entity|database)")); - } - - @Override - final protected CommandExecutionResult executeArg(SequenceDiagram diagram, RegexResult arg) { - final String code = arg.get("CODE", 0); - if (diagram.participants().containsKey(code)) { - diagram.putParticipantInLast(code); - return CommandExecutionResult.ok(); - } - - Display strings = null; - if (arg.get("FULL", 0) != null) { - strings = Display.getWithNewlines(arg.get("FULL", 0)); - } - - final String typeString1 = arg.get("TYPE", 0); - final String typeCreate1 = arg.get("CREATE", 0); - final ParticipantType type; - final boolean create; - if (typeCreate1 != null) { - type = ParticipantType.valueOf(StringUtils.goUpperCase(typeCreate1)); - create = true; - } else if (typeString1.equalsIgnoreCase("CREATE")) { - type = ParticipantType.PARTICIPANT; - create = true; - } else { - type = ParticipantType.valueOf(StringUtils.goUpperCase(typeString1)); - create = false; - } - final Participant participant = diagram.createNewParticipant(type, code, strings); - - final String stereotype = arg.get("STEREO", 0); - - if (stereotype != null) { - final ISkinParam skinParam = diagram.getSkinParam(); - final boolean stereotypePositionTop = skinParam.stereotypePositionTop(); - final UFont font = skinParam.getFont(FontParam.CIRCLED_CHARACTER, null, false); - participant.setStereotype(new Stereotype(stereotype, skinParam.getCircledCharacterRadius(), font, diagram - .getSkinParam().getIHtmlColorSet()), stereotypePositionTop); - } - participant - .setSpecificBackcolor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("COLOR", 0))); - - final String urlString = arg.get("URL", 0); - if (urlString != null) { - final UrlBuilder urlBuilder = new UrlBuilder(diagram.getSkinParam().getValue("topurl"), ModeUrl.STRICT); - final Url url = urlBuilder.getUrl(urlString); - participant.setUrl(url); - } - - if (create) { - final String error = diagram.activate(participant, LifeEventType.CREATE, null); - if (error != null) { - return CommandExecutionResult.error(error); - } - - } - - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/old/CommandParticipant.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/old/CommandParticipant.java deleted file mode 100755 index 2accd35..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/old/CommandParticipant.java +++ /dev/null @@ -1,126 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 6109 $ - * - */ -package net.sourceforge.plantuml.sequencediagram.command; - -import net.sourceforge.plantuml.FontParam; -import net.sourceforge.plantuml.ISkinParam; -import net.sourceforge.plantuml.Url; -import net.sourceforge.plantuml.UrlBuilder; -import net.sourceforge.plantuml.UrlBuilder.ModeUrl; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand2; -import net.sourceforge.plantuml.command.regex.IRegex; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexOr; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.cucadiagram.Stereotype; -import net.sourceforge.plantuml.sequencediagram.LifeEventType; -import net.sourceforge.plantuml.sequencediagram.Participant; -import net.sourceforge.plantuml.sequencediagram.ParticipantType; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagram; -import net.sourceforge.plantuml.ugraphic.UFont; - -public abstract class CommandParticipant extends SingleLineCommand2 { - - public CommandParticipant(RegexConcat pattern) { - super(pattern); - } - - static IRegex getRegexType() { - return new RegexOr(new RegexLeaf("TYPE", "(participant|actor|create|boundary|control|entity|database)"), // - new RegexLeaf("CREATE", "create[%s](participant|actor|boundary|control|entity|database)")); - } - - @Override - final protected CommandExecutionResult executeArg(SequenceDiagram diagram, RegexResult arg) { - final String code = arg.get("CODE", 0); - if (diagram.participants().containsKey(code)) { - diagram.putParticipantInLast(code); - return CommandExecutionResult.ok(); - } - - Display strings = null; - if (arg.get("FULL", 0) != null) { - strings = Display.getWithNewlines(arg.get("FULL", 0)); - } - - final String typeString1 = arg.get("TYPE", 0); - final String typeCreate1 = arg.get("CREATE", 0); - final ParticipantType type; - final boolean create; - if (typeCreate1 != null) { - type = ParticipantType.valueOf(typeCreate1.toUpperCase()); - create = true; - } else if (typeString1.equalsIgnoreCase("CREATE")) { - type = ParticipantType.PARTICIPANT; - create = true; - } else { - type = ParticipantType.valueOf(typeString1.toUpperCase()); - create = false; - } - final Participant participant = diagram.createNewParticipant(type, code, strings); - - final String stereotype = arg.get("STEREO", 0); - - if (stereotype != null) { - final ISkinParam skinParam = diagram.getSkinParam(); - final boolean stereotypePositionTop = skinParam.stereotypePositionTop(); - final UFont font = skinParam.getFont(FontParam.CIRCLED_CHARACTER, null, false); - participant.setStereotype(new Stereotype(stereotype, skinParam.getCircledCharacterRadius(), font, diagram - .getSkinParam().getIHtmlColorSet()), stereotypePositionTop); - } - participant - .setSpecificBackcolor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("COLOR", 0))); - - final String urlString = arg.get("URL", 0); - if (urlString != null) { - final UrlBuilder urlBuilder = new UrlBuilder(diagram.getSkinParam().getValue("topurl"), ModeUrl.STRICT); - final Url url = urlBuilder.getUrl(urlString); - participant.setUrl(url); - } - - if (create) { - final String error = diagram.activate(participant, LifeEventType.CREATE, null); - if (error != null) { - return CommandExecutionResult.error(error); - } - - } - - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/pair.info deleted file mode 100755 index b4ae499..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22600/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22600 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/sequencediagram/command/CommandParticipant.java -FixedFilePath:src/net/sourceforge/plantuml/sequencediagram/command/CommandParticipant.java -StartLineNum:85 -EndLineNum:85 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/diff.diff deleted file mode 100755 index a23fa33..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/command/CommandHeader.java b/src/net/sourceforge/plantuml/command/CommandHeader.java -index 3061f31a..d0ddbc0b 100644 ---- a/src/net/sourceforge/plantuml/command/CommandHeader.java -+++ b/src/net/sourceforge/plantuml/command/CommandHeader.java -@@ -31 +31 @@ -- * Revision $Revision: 12235 $ -+ * Revision $Revision: 14726 $ -@@ -37,0 +38 @@ import java.util.List; -+import net.sourceforge.plantuml.StringUtils; -@@ -52 +53 @@ public class CommandHeader extends SingleLineCommand { -- diagram.setHeaderAlignment(HorizontalAlignment.valueOf(align.toUpperCase())); -+ diagram.setHeaderAlignment(HorizontalAlignment.valueOf(StringUtils.goUpperCase(align))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/new/CommandHeader.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/new/CommandHeader.java deleted file mode 100755 index d0ddbc0..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/new/CommandHeader.java +++ /dev/null @@ -1,59 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14726 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; - -public class CommandHeader extends SingleLineCommand { - - public CommandHeader() { - super("(?i)^(?:(left|right|center)?[%s]*)header(?:[%s]*:[%s]*|[%s]+)(.*[\\p{L}0-9_.].*)$"); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram diagram, List arg) { - final String align = arg.get(0); - if (align != null) { - diagram.setHeaderAlignment(HorizontalAlignment.valueOf(StringUtils.goUpperCase(align))); - } - diagram.setHeader(Display.getWithNewlines(arg.get(1))); - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/old/CommandHeader.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/old/CommandHeader.java deleted file mode 100755 index 3061f31..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/old/CommandHeader.java +++ /dev/null @@ -1,58 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 12235 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; - -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; - -public class CommandHeader extends SingleLineCommand { - - public CommandHeader() { - super("(?i)^(?:(left|right|center)?[%s]*)header(?:[%s]*:[%s]*|[%s]+)(.*[\\p{L}0-9_.].*)$"); - } - - @Override - protected CommandExecutionResult executeArg(UmlDiagram diagram, List arg) { - final String align = arg.get(0); - if (align != null) { - diagram.setHeaderAlignment(HorizontalAlignment.valueOf(align.toUpperCase())); - } - diagram.setHeader(Display.getWithNewlines(arg.get(1))); - return CommandExecutionResult.ok(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/pair.info deleted file mode 100755 index 191f43f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22618/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22618 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/command/CommandHeader.java -FixedFilePath:src/net/sourceforge/plantuml/command/CommandHeader.java -StartLineNum:52 -EndLineNum:52 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/diff.diff deleted file mode 100755 index cc7e92e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/classdiagram/command/JavaFile.java b/src/net/sourceforge/plantuml/classdiagram/command/JavaFile.java -index d17daafa..9953239b 100644 ---- a/src/net/sourceforge/plantuml/classdiagram/command/JavaFile.java -+++ b/src/net/sourceforge/plantuml/classdiagram/command/JavaFile.java -@@ -31 +31 @@ -- * Revision $Revision: 12235 $ -+ * Revision $Revision: 14726 $ -@@ -45,0 +46 @@ import java.util.regex.Pattern; -+import net.sourceforge.plantuml.StringUtils; -@@ -83 +84 @@ class JavaFile { -- final LeafType type = LeafType.valueOf(matchClassDefinition.group(1).toUpperCase()); -+ final LeafType type = LeafType.valueOf(StringUtils.goUpperCase(matchClassDefinition.group(1))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/new/JavaFile.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/new/JavaFile.java deleted file mode 100755 index 9953239..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/new/JavaFile.java +++ /dev/null @@ -1,110 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14726 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.command.regex.MyPattern; -import net.sourceforge.plantuml.cucadiagram.LeafType; - -class JavaFile { - - private static final Pattern classDefinition = MyPattern - .cmpile("^(?:public[%s]+|abstract[%s]+|final[%s]+)*(class|interface|enum|annotation)[%s]+(\\w+)(?:.*\\b(extends|implements)[%s]+([\\w%s,]+))?"); - - private static final Pattern packageDefinition = MyPattern.cmpile("^package[%s]+([\\w+.]+)[%s]*;"); - - private final List all = new ArrayList(); - - public JavaFile(File f) throws IOException { - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(f)); - initFromReader(br); - } finally { - if (br != null) { - br.close(); - } - } - } - - private void initFromReader(BufferedReader br) throws IOException { - String javaPackage = null; - String s; - while ((s = br.readLine()) != null) { - s = s.trim(); - final Matcher matchPackage = packageDefinition.matcher(s); - if (matchPackage.find()) { - javaPackage = matchPackage.group(1); - } else { - final Matcher matchClassDefinition = classDefinition.matcher(s); - if (matchClassDefinition.find()) { - final String n = matchClassDefinition.group(2); - final String p = matchClassDefinition.group(4); - final LeafType type = LeafType.valueOf(StringUtils.goUpperCase(matchClassDefinition.group(1))); - final LeafType parentType = getParentType(type, matchClassDefinition.group(3)); - all.add(new JavaClass(javaPackage, n, p, type, parentType)); - } - } - } - } - - static LeafType getParentType(LeafType type, String extendsOrImplements) { - if (extendsOrImplements == null) { - return null; - } - if (type == LeafType.CLASS) { - if (extendsOrImplements.equals("extends")) { - return LeafType.CLASS; - } - return LeafType.INTERFACE; - } - return LeafType.INTERFACE; - } - - public List getJavaClasses() { - return Collections.unmodifiableList(all); - - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/old/JavaFile.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/old/JavaFile.java deleted file mode 100755 index d17daaf..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/old/JavaFile.java +++ /dev/null @@ -1,109 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 12235 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.sourceforge.plantuml.command.regex.MyPattern; -import net.sourceforge.plantuml.cucadiagram.LeafType; - -class JavaFile { - - private static final Pattern classDefinition = MyPattern - .cmpile("^(?:public[%s]+|abstract[%s]+|final[%s]+)*(class|interface|enum|annotation)[%s]+(\\w+)(?:.*\\b(extends|implements)[%s]+([\\w%s,]+))?"); - - private static final Pattern packageDefinition = MyPattern.cmpile("^package[%s]+([\\w+.]+)[%s]*;"); - - private final List all = new ArrayList(); - - public JavaFile(File f) throws IOException { - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(f)); - initFromReader(br); - } finally { - if (br != null) { - br.close(); - } - } - } - - private void initFromReader(BufferedReader br) throws IOException { - String javaPackage = null; - String s; - while ((s = br.readLine()) != null) { - s = s.trim(); - final Matcher matchPackage = packageDefinition.matcher(s); - if (matchPackage.find()) { - javaPackage = matchPackage.group(1); - } else { - final Matcher matchClassDefinition = classDefinition.matcher(s); - if (matchClassDefinition.find()) { - final String n = matchClassDefinition.group(2); - final String p = matchClassDefinition.group(4); - final LeafType type = LeafType.valueOf(matchClassDefinition.group(1).toUpperCase()); - final LeafType parentType = getParentType(type, matchClassDefinition.group(3)); - all.add(new JavaClass(javaPackage, n, p, type, parentType)); - } - } - } - } - - static LeafType getParentType(LeafType type, String extendsOrImplements) { - if (extendsOrImplements == null) { - return null; - } - if (type == LeafType.CLASS) { - if (extendsOrImplements.equals("extends")) { - return LeafType.CLASS; - } - return LeafType.INTERFACE; - } - return LeafType.INTERFACE; - } - - public List getJavaClasses() { - return Collections.unmodifiableList(all); - - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/pair.info deleted file mode 100755 index a79a033..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22620/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22620 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/classdiagram/command/JavaFile.java -FixedFilePath:src/net/sourceforge/plantuml/classdiagram/command/JavaFile.java -StartLineNum:83 -EndLineNum:83 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/diff.diff deleted file mode 100755 index 562b6e6..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/font/PSystemListFontsFactory.java b/src/net/sourceforge/plantuml/font/PSystemListFontsFactory.java -index 21b220e2..c6aa3360 100644 ---- a/src/net/sourceforge/plantuml/font/PSystemListFontsFactory.java -+++ b/src/net/sourceforge/plantuml/font/PSystemListFontsFactory.java -@@ -36,0 +37 @@ import net.sourceforge.plantuml.AbstractPSystem; -+import net.sourceforge.plantuml.StringUtils; -@@ -43 +44 @@ public class PSystemListFontsFactory extends PSystemSingleLineFactory { -- final String lineLower = line.toLowerCase(); -+ final String lineLower = StringUtils.goLowerCase(line); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/new/PSystemListFontsFactory.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/new/PSystemListFontsFactory.java deleted file mode 100755 index c6aa336..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/new/PSystemListFontsFactory.java +++ /dev/null @@ -1,53 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3830 $ - * - */ -package net.sourceforge.plantuml.font; - -import net.sourceforge.plantuml.AbstractPSystem; -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.command.PSystemSingleLineFactory; - -public class PSystemListFontsFactory extends PSystemSingleLineFactory { - - @Override - protected AbstractPSystem executeLine(String line) { - final String lineLower = StringUtils.goLowerCase(line); - if (lineLower.equals("listfont") || lineLower.equals("listfonts") || lineLower.startsWith("listfont ") - || lineLower.startsWith("listfonts ")) { - final int idx = line.indexOf(' '); - return new PSystemListFonts(idx == -1 ? "This is a test" : line.substring(idx).trim()); - } - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/old/PSystemListFontsFactory.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/old/PSystemListFontsFactory.java deleted file mode 100755 index 21b220e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/old/PSystemListFontsFactory.java +++ /dev/null @@ -1,52 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3830 $ - * - */ -package net.sourceforge.plantuml.font; - -import net.sourceforge.plantuml.AbstractPSystem; -import net.sourceforge.plantuml.command.PSystemSingleLineFactory; - -public class PSystemListFontsFactory extends PSystemSingleLineFactory { - - @Override - protected AbstractPSystem executeLine(String line) { - final String lineLower = line.toLowerCase(); - if (lineLower.equals("listfont") || lineLower.equals("listfonts") || lineLower.startsWith("listfont ") - || lineLower.startsWith("listfonts ")) { - final int idx = line.indexOf(' '); - return new PSystemListFonts(idx == -1 ? "This is a test" : line.substring(idx).trim()); - } - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/pair.info deleted file mode 100755 index c0b5033..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22621/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22621 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/font/PSystemListFontsFactory.java -FixedFilePath:src/net/sourceforge/plantuml/font/PSystemListFontsFactory.java -StartLineNum:43 -EndLineNum:43 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/diff.diff deleted file mode 100755 index b052461..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/openiconic/PSystemListOpenIconicFactory.java b/src/net/sourceforge/plantuml/openiconic/PSystemListOpenIconicFactory.java -index 121f887a..14f22088 100644 ---- a/src/net/sourceforge/plantuml/openiconic/PSystemListOpenIconicFactory.java -+++ b/src/net/sourceforge/plantuml/openiconic/PSystemListOpenIconicFactory.java -@@ -36,0 +37 @@ import net.sourceforge.plantuml.AbstractPSystem; -+import net.sourceforge.plantuml.StringUtils; -@@ -43 +44 @@ public class PSystemListOpenIconicFactory extends PSystemSingleLineFactory { -- final String lineLower = line.toLowerCase(); -+ final String lineLower = StringUtils.goLowerCase(line); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/new/PSystemListOpenIconicFactory.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/new/PSystemListOpenIconicFactory.java deleted file mode 100755 index 14f2208..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/new/PSystemListOpenIconicFactory.java +++ /dev/null @@ -1,51 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3830 $ - * - */ -package net.sourceforge.plantuml.openiconic; - -import net.sourceforge.plantuml.AbstractPSystem; -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.command.PSystemSingleLineFactory; - -public class PSystemListOpenIconicFactory extends PSystemSingleLineFactory { - - @Override - protected AbstractPSystem executeLine(String line) { - final String lineLower = StringUtils.goLowerCase(line); - if (lineLower.startsWith("listopeniconic")) { - return new PSystemListOpenIconic(); - } - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/old/PSystemListOpenIconicFactory.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/old/PSystemListOpenIconicFactory.java deleted file mode 100755 index 121f887..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/old/PSystemListOpenIconicFactory.java +++ /dev/null @@ -1,50 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 3830 $ - * - */ -package net.sourceforge.plantuml.openiconic; - -import net.sourceforge.plantuml.AbstractPSystem; -import net.sourceforge.plantuml.command.PSystemSingleLineFactory; - -public class PSystemListOpenIconicFactory extends PSystemSingleLineFactory { - - @Override - protected AbstractPSystem executeLine(String line) { - final String lineLower = line.toLowerCase(); - if (lineLower.startsWith("listopeniconic")) { - return new PSystemListOpenIconic(); - } - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/pair.info deleted file mode 100755 index cfd2763..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22622/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22622 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/openiconic/PSystemListOpenIconicFactory.java -FixedFilePath:src/net/sourceforge/plantuml/openiconic/PSystemListOpenIconicFactory.java -StartLineNum:43 -EndLineNum:43 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/diff.diff deleted file mode 100755 index 1ea5aa7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/command/CommandMultilinesFooter.java b/src/net/sourceforge/plantuml/command/CommandMultilinesFooter.java -index eca94312..910c9559 100644 ---- a/src/net/sourceforge/plantuml/command/CommandMultilinesFooter.java -+++ b/src/net/sourceforge/plantuml/command/CommandMultilinesFooter.java -@@ -31 +31 @@ -- * Revision $Revision: 14321 $ -+ * Revision $Revision: 14726 $ -@@ -63 +63 @@ public class CommandMultilinesFooter extends CommandMultilines { -- diagram.setFooterAlignment(HorizontalAlignment.valueOf(align.toUpperCase())); -+ diagram.setFooterAlignment(HorizontalAlignment.valueOf(StringUtils.goUpperCase(align))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/new/CommandMultilinesFooter.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/new/CommandMultilinesFooter.java deleted file mode 100755 index 910c955..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/new/CommandMultilinesFooter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14726 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; -import java.util.regex.Matcher; - -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; -import net.sourceforge.plantuml.StringUtils; - -public class CommandMultilinesFooter extends CommandMultilines { - - public CommandMultilinesFooter() { - super("(?i)^(?:(left|right|center)?[%s]*)footer$"); - } - - @Override - public String getPatternEnd() { - return "(?i)^end[%s]?footer$"; - } - - public CommandExecutionResult execute(final UmlDiagram diagram, List lines) { - StringUtils.trim(lines, false); - final Matcher m = getStartingPattern().matcher(lines.get(0).trim()); - if (m.find() == false) { - throw new IllegalStateException(); - } - final String align = m.group(1); - if (align != null) { - diagram.setFooterAlignment(HorizontalAlignment.valueOf(StringUtils.goUpperCase(align))); - } - final Display strings = Display.create(lines.subList(1, lines.size() - 1)); - if (strings.size() > 0) { - diagram.setFooter(strings); - return CommandExecutionResult.ok(); - } - return CommandExecutionResult.error("Empty footer"); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/old/CommandMultilinesFooter.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/old/CommandMultilinesFooter.java deleted file mode 100755 index eca9431..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/old/CommandMultilinesFooter.java +++ /dev/null @@ -1,73 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 14321 $ - * - */ -package net.sourceforge.plantuml.command; - -import java.util.List; -import java.util.regex.Matcher; - -import net.sourceforge.plantuml.UmlDiagram; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.graphic.HorizontalAlignment; -import net.sourceforge.plantuml.StringUtils; - -public class CommandMultilinesFooter extends CommandMultilines { - - public CommandMultilinesFooter() { - super("(?i)^(?:(left|right|center)?[%s]*)footer$"); - } - - @Override - public String getPatternEnd() { - return "(?i)^end[%s]?footer$"; - } - - public CommandExecutionResult execute(final UmlDiagram diagram, List lines) { - StringUtils.trim(lines, false); - final Matcher m = getStartingPattern().matcher(lines.get(0).trim()); - if (m.find() == false) { - throw new IllegalStateException(); - } - final String align = m.group(1); - if (align != null) { - diagram.setFooterAlignment(HorizontalAlignment.valueOf(align.toUpperCase())); - } - final Display strings = Display.create(lines.subList(1, lines.size() - 1)); - if (strings.size() > 0) { - diagram.setFooter(strings); - return CommandExecutionResult.ok(); - } - return CommandExecutionResult.error("Empty footer"); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/pair.info deleted file mode 100755 index 7a75158..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22624/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22624 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/command/CommandMultilinesFooter.java -FixedFilePath:src/net/sourceforge/plantuml/command/CommandMultilinesFooter.java -StartLineNum:63 -EndLineNum:63 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/diff.diff deleted file mode 100755 index 487f2c2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/project/command/CommandCloseWeekDay.java b/src/net/sourceforge/plantuml/project/command/CommandCloseWeekDay.java -index 50504643..de6d53dc 100644 ---- a/src/net/sourceforge/plantuml/project/command/CommandCloseWeekDay.java -+++ b/src/net/sourceforge/plantuml/project/command/CommandCloseWeekDay.java -@@ -37,0 +38 @@ import java.util.List; -+import net.sourceforge.plantuml.StringUtils; -@@ -51 +52 @@ public class CommandCloseWeekDay extends SingleLineCommand { -- final WeekDay weekDay = WeekDay.valueOf(arg.get(0).substring(0, 3).toUpperCase()); -+ final WeekDay weekDay = WeekDay.valueOf(StringUtils.goUpperCase(arg.get(0).substring(0, 3))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/new/CommandCloseWeekDay.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/new/CommandCloseWeekDay.java deleted file mode 100755 index de6d53d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/new/CommandCloseWeekDay.java +++ /dev/null @@ -1,56 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5884 $ - * - */ -package net.sourceforge.plantuml.project.command; - -import java.util.List; - -import net.sourceforge.plantuml.StringUtils; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand; -import net.sourceforge.plantuml.project.PSystemProject; -import net.sourceforge.plantuml.project.WeekDay; - -public class CommandCloseWeekDay extends SingleLineCommand { - - public CommandCloseWeekDay() { - super("(?i)^\\s*close\\s+(\\w{3,}day)\\s*$"); - } - - @Override - protected CommandExecutionResult executeArg(PSystemProject diagram, List arg) { - final WeekDay weekDay = WeekDay.valueOf(StringUtils.goUpperCase(arg.get(0).substring(0, 3))); - diagram.getProject().closeWeekDay(weekDay); - return CommandExecutionResult.ok(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/old/CommandCloseWeekDay.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/old/CommandCloseWeekDay.java deleted file mode 100755 index 5050464..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/old/CommandCloseWeekDay.java +++ /dev/null @@ -1,55 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 5884 $ - * - */ -package net.sourceforge.plantuml.project.command; - -import java.util.List; - -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.SingleLineCommand; -import net.sourceforge.plantuml.project.PSystemProject; -import net.sourceforge.plantuml.project.WeekDay; - -public class CommandCloseWeekDay extends SingleLineCommand { - - public CommandCloseWeekDay() { - super("(?i)^\\s*close\\s+(\\w{3,}day)\\s*$"); - } - - @Override - protected CommandExecutionResult executeArg(PSystemProject diagram, List arg) { - final WeekDay weekDay = WeekDay.valueOf(arg.get(0).substring(0, 3).toUpperCase()); - diagram.getProject().closeWeekDay(weekDay); - return CommandExecutionResult.ok(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/pair.info deleted file mode 100755 index 64ca918..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22636/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22636 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/project/command/CommandCloseWeekDay.java -FixedFilePath:src/net/sourceforge/plantuml/project/command/CommandCloseWeekDay.java -StartLineNum:51 -EndLineNum:51 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/comMsg.txt deleted file mode 100755 index 497d445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 8016 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@534 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/diff.diff deleted file mode 100755 index 013ca2b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClassMultilines.java b/src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClassMultilines.java -index 81bf3e4d..cd394825 100644 ---- a/src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClassMultilines.java -+++ b/src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClassMultilines.java -@@ -173 +173 @@ public class CommandCreateClassMultilines extends CommandMultilines2 { - - private static final String CODE = "(?:\\.|::)?[\\p{L}0-9_]+(?:(?:\\.|::)[\\p{L}0-9_]+)*"; - public static final String CODES = CODE + "(?:\\s*,\\s*" + CODE + ")*"; - - enum Mode { - EXTENDS, IMPLEMENTS - }; - - public CommandCreateClassMultilines() { - super(getRegexConcat(), MultilinesStrategy.REMOVE_STARTING_QUOTE); - } - - @Override - public String getPatternEnd() { - return "(?i)^[%s]*\\}[%s]*$"; - } - - private static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("TYPE", "(interface|enum|abstract[%s]+class|abstract|class)[%s]+"), // - new RegexOr(// - new RegexConcat(// - new RegexLeaf("DISPLAY1", "[%g]([^%g]+)[%g]"), // - new RegexLeaf("[%s]+as[%s]+"), // - new RegexLeaf("CODE1", "(" + CommandCreateClass.CODE + ")")), // - new RegexConcat(// - new RegexLeaf("CODE2", "(" + CommandCreateClass.CODE + ")"), // - new RegexLeaf("[%s]+as[%s]+"), // // - new RegexLeaf("DISPLAY2", "[%g]([^%g]+)[%g]")), // - new RegexLeaf("CODE3", "(" + CommandCreateClass.CODE + ")"), // - new RegexLeaf("CODE4", "[%g]([^%g]+)[%g]")), // - new RegexLeaf("GENERIC", "(?:[%s]*\\<(" + GenericRegexProducer.PATTERN + ")\\>)?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("STEREO", "(\\<\\<.+\\>\\>)?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("URL", "(" + UrlBuilder.getRegexp() + ")?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("COLOR", "(" + HtmlColorUtils.COLOR_REGEXP + ")?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("LINECOLOR", "(?:##(?:\\[(dotted|dashed|bold)\\])?(\\w+)?)?"), // - new RegexLeaf("EXTENDS", "([%s]+(extends)[%s]+(" + CODES + "))?"), // - new RegexLeaf("IMPLEMENTS", "([%s]+(implements)[%s]+(" + CODES + "))?"), // - new RegexLeaf("[%s]*\\{[%s]*$")); - } - - public CommandExecutionResult executeNow(ClassDiagram diagram, List lines) { - StringUtils.trim(lines, false); - final RegexResult line0 = getStartingPattern().matcher(lines.get(0).trim()); - final IEntity entity = executeArg0(diagram, line0); - if (entity == null) { - return CommandExecutionResult.error("No such entity"); - } - lines = lines.subList(1, lines.size() - 1); - final Url url; - if (lines.size() > 0) { - final UrlBuilder urlBuilder = new UrlBuilder(diagram.getSkinParam().getValue("topurl"), ModeUrl.STRICT); - url = urlBuilder.getUrl(lines.get(0).toString()); - } else { - url = null; - } - if (url != null) { - lines = lines.subList(1, lines.size()); - } - for (String s : lines) { - if (s.length() > 0 && VisibilityModifier.isVisibilityCharacter(s.charAt(0))) { - diagram.setVisibilityModifierPresent(true); - } - entity.addFieldOrMethod(s); - } - if (url != null) { - entity.addUrl(url); - } - - manageExtends("EXTENDS", diagram, line0, entity); - manageExtends("IMPLEMENTS", diagram, line0, entity); - - return CommandExecutionResult.ok(); - } - - public static void manageExtends(String keyword, ClassDiagram system, RegexResult arg, final IEntity entity) { - if (arg.get(keyword, 1) != null) { - final Mode mode = arg.get(keyword, 1).equalsIgnoreCase("extends") ? Mode.EXTENDS : Mode.IMPLEMENTS; - LeafType type2 = LeafType.CLASS; - if (mode == Mode.IMPLEMENTS) { - type2 = LeafType.INTERFACE; - } - if (mode == Mode.EXTENDS && entity.getEntityType() == LeafType.INTERFACE) { - type2 = LeafType.INTERFACE; - } - final String codes = arg.get(keyword, 2); - for (String s : codes.split(",")) { - final Code other = Code.of(s.trim()); - final IEntity cl2 = system.getOrCreateLeaf(other, type2, null); - LinkType typeLink = new LinkType(LinkDecor.NONE, LinkDecor.EXTENDS); - if (type2 == LeafType.INTERFACE && entity.getEntityType() != LeafType.INTERFACE) { - typeLink = typeLink.getDashed(); - } - final Link link = new Link(cl2, entity, typeLink, null, 2, null, null, system.getLabeldistance(), - system.getLabelangle()); - system.addLink(link); - } - } - } - - private IEntity executeArg0(ClassDiagram diagram, RegexResult arg) { - - final LeafType type = LeafType.getLeafType(StringUtils.goUpperCase(arg.get("TYPE", 0))); - - final Code code = Code.of(arg.getLazzy("CODE", 0)).eventuallyRemoveStartingAndEndingDoubleQuote("\"([:"); - final String display = arg.getLazzy("DISPLAY", 0); - - final String stereotype = arg.get("STEREO", 0); - final String generic = arg.get("GENERIC", 0); - - final ILeaf result; - if (diagram.leafExist(code)) { - result = diagram.getOrCreateLeaf(code, null, null); - result.muteToType(type, null); - } else { - result = diagram.createLeaf(code, Display.getWithNewlines(display), type, null); - } - if (stereotype != null) { - result.setStereotype(new Stereotype(stereotype, diagram.getSkinParam().getCircledCharacterRadius(), diagram - .getSkinParam().getFont(FontParam.CIRCLED_CHARACTER, null, false), diagram.getSkinParam() - .getIHtmlColorSet())); - } - - final String urlString = arg.get("URL", 0); - if (urlString != null) { - final UrlBuilder urlBuilder = new UrlBuilder(diagram.getSkinParam().getValue("topurl"), ModeUrl.STRICT); - final Url url = urlBuilder.getUrl(urlString); - result.addUrl(url); - } - - result.setSpecificBackcolor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("COLOR", 0))); - result.setSpecificLineColor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("LINECOLOR", 1))); - applyStroke(result, arg.get("LINECOLOR", 0)); - - if (generic != null) { - result.setGeneric(generic); - } - return result; - } - - public static UStroke getStroke(LinkStyle style) { - if (style == LinkStyle.DASHED) { - return new UStroke(6, 6, 1); - } - if (style == LinkStyle.DOTTED) { - return new UStroke(1, 3, 1); - } - if (style == LinkStyle.BOLD) { - return new UStroke(2.5); - } - return new UStroke(); - } - - public static void applyStroke(IEntity entity, String s) { - if (s == null) { - return; - } - final LinkStyle style = LinkStyle.valueOf(StringUtils.goUpperCase(s)); - entity.setSpecificLineStroke(getStroke(style)); - - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/old/CommandCreateClassMultilines.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/old/CommandCreateClassMultilines.java deleted file mode 100755 index 81bf3e4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/old/CommandCreateClassMultilines.java +++ /dev/null @@ -1,233 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2014, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4161 $ - * - */ -package net.sourceforge.plantuml.classdiagram.command; - -import java.util.List; - -import net.sourceforge.plantuml.FontParam; -import net.sourceforge.plantuml.Url; -import net.sourceforge.plantuml.UrlBuilder; -import net.sourceforge.plantuml.UrlBuilder.ModeUrl; -import net.sourceforge.plantuml.classdiagram.ClassDiagram; -import net.sourceforge.plantuml.command.CommandExecutionResult; -import net.sourceforge.plantuml.command.CommandMultilines2; -import net.sourceforge.plantuml.command.MultilinesStrategy; -import net.sourceforge.plantuml.command.regex.RegexConcat; -import net.sourceforge.plantuml.command.regex.RegexLeaf; -import net.sourceforge.plantuml.command.regex.RegexOr; -import net.sourceforge.plantuml.command.regex.RegexResult; -import net.sourceforge.plantuml.cucadiagram.Code; -import net.sourceforge.plantuml.cucadiagram.Display; -import net.sourceforge.plantuml.cucadiagram.IEntity; -import net.sourceforge.plantuml.cucadiagram.ILeaf; -import net.sourceforge.plantuml.cucadiagram.LeafType; -import net.sourceforge.plantuml.cucadiagram.Link; -import net.sourceforge.plantuml.cucadiagram.LinkDecor; -import net.sourceforge.plantuml.cucadiagram.LinkStyle; -import net.sourceforge.plantuml.cucadiagram.LinkType; -import net.sourceforge.plantuml.cucadiagram.Stereotype; -import net.sourceforge.plantuml.graphic.HtmlColorSet; -import net.sourceforge.plantuml.graphic.HtmlColorUtils; -import net.sourceforge.plantuml.skin.VisibilityModifier; -import net.sourceforge.plantuml.ugraphic.UStroke; -import net.sourceforge.plantuml.StringUtils; - -public class CommandCreateClassMultilines extends CommandMultilines2 { - - private static final String CODE = "(?:\\.|::)?[\\p{L}0-9_]+(?:(?:\\.|::)[\\p{L}0-9_]+)*"; - public static final String CODES = CODE + "(?:\\s*,\\s*" + CODE + ")*"; - - enum Mode { - EXTENDS, IMPLEMENTS - }; - - public CommandCreateClassMultilines() { - super(getRegexConcat(), MultilinesStrategy.REMOVE_STARTING_QUOTE); - } - - @Override - public String getPatternEnd() { - return "(?i)^[%s]*\\}[%s]*$"; - } - - private static RegexConcat getRegexConcat() { - return new RegexConcat(new RegexLeaf("^"), // - new RegexLeaf("TYPE", "(interface|enum|abstract[%s]+class|abstract|class)[%s]+"), // - new RegexOr(// - new RegexConcat(// - new RegexLeaf("DISPLAY1", "[%g]([^%g]+)[%g]"), // - new RegexLeaf("[%s]+as[%s]+"), // - new RegexLeaf("CODE1", "(" + CommandCreateClass.CODE + ")")), // - new RegexConcat(// - new RegexLeaf("CODE2", "(" + CommandCreateClass.CODE + ")"), // - new RegexLeaf("[%s]+as[%s]+"), // // - new RegexLeaf("DISPLAY2", "[%g]([^%g]+)[%g]")), // - new RegexLeaf("CODE3", "(" + CommandCreateClass.CODE + ")"), // - new RegexLeaf("CODE4", "[%g]([^%g]+)[%g]")), // - new RegexLeaf("GENERIC", "(?:[%s]*\\<(" + GenericRegexProducer.PATTERN + ")\\>)?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("STEREO", "(\\<\\<.+\\>\\>)?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("URL", "(" + UrlBuilder.getRegexp() + ")?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("COLOR", "(" + HtmlColorUtils.COLOR_REGEXP + ")?"), // - new RegexLeaf("[%s]*"), // - new RegexLeaf("LINECOLOR", "(?:##(?:\\[(dotted|dashed|bold)\\])?(\\w+)?)?"), // - new RegexLeaf("EXTENDS", "([%s]+(extends)[%s]+(" + CODES + "))?"), // - new RegexLeaf("IMPLEMENTS", "([%s]+(implements)[%s]+(" + CODES + "))?"), // - new RegexLeaf("[%s]*\\{[%s]*$")); - } - - public CommandExecutionResult executeNow(ClassDiagram diagram, List lines) { - StringUtils.trim(lines, false); - final RegexResult line0 = getStartingPattern().matcher(lines.get(0).trim()); - final IEntity entity = executeArg0(diagram, line0); - if (entity == null) { - return CommandExecutionResult.error("No such entity"); - } - lines = lines.subList(1, lines.size() - 1); - final Url url; - if (lines.size() > 0) { - final UrlBuilder urlBuilder = new UrlBuilder(diagram.getSkinParam().getValue("topurl"), ModeUrl.STRICT); - url = urlBuilder.getUrl(lines.get(0).toString()); - } else { - url = null; - } - if (url != null) { - lines = lines.subList(1, lines.size()); - } - for (String s : lines) { - if (s.length() > 0 && VisibilityModifier.isVisibilityCharacter(s.charAt(0))) { - diagram.setVisibilityModifierPresent(true); - } - entity.addFieldOrMethod(s); - } - if (url != null) { - entity.addUrl(url); - } - - manageExtends("EXTENDS", diagram, line0, entity); - manageExtends("IMPLEMENTS", diagram, line0, entity); - - return CommandExecutionResult.ok(); - } - - public static void manageExtends(String keyword, ClassDiagram system, RegexResult arg, final IEntity entity) { - if (arg.get(keyword, 1) != null) { - final Mode mode = arg.get(keyword, 1).equalsIgnoreCase("extends") ? Mode.EXTENDS : Mode.IMPLEMENTS; - LeafType type2 = LeafType.CLASS; - if (mode == Mode.IMPLEMENTS) { - type2 = LeafType.INTERFACE; - } - if (mode == Mode.EXTENDS && entity.getEntityType() == LeafType.INTERFACE) { - type2 = LeafType.INTERFACE; - } - final String codes = arg.get(keyword, 2); - for (String s : codes.split(",")) { - final Code other = Code.of(s.trim()); - final IEntity cl2 = system.getOrCreateLeaf(other, type2, null); - LinkType typeLink = new LinkType(LinkDecor.NONE, LinkDecor.EXTENDS); - if (type2 == LeafType.INTERFACE && entity.getEntityType() != LeafType.INTERFACE) { - typeLink = typeLink.getDashed(); - } - final Link link = new Link(cl2, entity, typeLink, null, 2, null, null, system.getLabeldistance(), - system.getLabelangle()); - system.addLink(link); - } - } - } - - private IEntity executeArg0(ClassDiagram diagram, RegexResult arg) { - - final LeafType type = LeafType.getLeafType(arg.get("TYPE", 0).toUpperCase()); - - final Code code = Code.of(arg.getLazzy("CODE", 0)).eventuallyRemoveStartingAndEndingDoubleQuote("\"([:"); - final String display = arg.getLazzy("DISPLAY", 0); - - final String stereotype = arg.get("STEREO", 0); - final String generic = arg.get("GENERIC", 0); - - final ILeaf result; - if (diagram.leafExist(code)) { - result = diagram.getOrCreateLeaf(code, null, null); - result.muteToType(type, null); - } else { - result = diagram.createLeaf(code, Display.getWithNewlines(display), type, null); - } - if (stereotype != null) { - result.setStereotype(new Stereotype(stereotype, diagram.getSkinParam().getCircledCharacterRadius(), diagram - .getSkinParam().getFont(FontParam.CIRCLED_CHARACTER, null, false), diagram.getSkinParam() - .getIHtmlColorSet())); - } - - final String urlString = arg.get("URL", 0); - if (urlString != null) { - final UrlBuilder urlBuilder = new UrlBuilder(diagram.getSkinParam().getValue("topurl"), ModeUrl.STRICT); - final Url url = urlBuilder.getUrl(urlString); - result.addUrl(url); - } - - result.setSpecificBackcolor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("COLOR", 0))); - result.setSpecificLineColor(diagram.getSkinParam().getIHtmlColorSet().getColorIfValid(arg.get("LINECOLOR", 1))); - applyStroke(result, arg.get("LINECOLOR", 0)); - - if (generic != null) { - result.setGeneric(generic); - } - return result; - } - - public static UStroke getStroke(LinkStyle style) { - if (style == LinkStyle.DASHED) { - return new UStroke(6, 6, 1); - } - if (style == LinkStyle.DOTTED) { - return new UStroke(1, 3, 1); - } - if (style == LinkStyle.BOLD) { - return new UStroke(2.5); - } - return new UStroke(); - } - - public static void applyStroke(IEntity entity, String s) { - if (s == null) { - return; - } - final LinkStyle style = LinkStyle.valueOf(s.toUpperCase()); - entity.setSpecificLineStroke(getStroke(style)); - - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/pair.info deleted file mode 100755 index a673148..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#22640/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22640 -comSha:b5f659f3a14253faefc977142cf29ed8fe14b2e6 -parentComSha:fd60132b3e3abd6b7029cff222421150b42a0dba -BuggyFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClassMultilines.java -FixedFilePath:src/net/sourceforge/plantuml/classdiagram/command/CommandCreateClassMultilines.java -StartLineNum:173 -EndLineNum:173 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/comMsg.txt deleted file mode 100755 index 1dbd6ab..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -added WordCounter \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/diff.diff deleted file mode 100755 index 2495bdb..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/teetime/stage/string/ToLowerCase.java b/src/main/java/teetime/stage/string/ToLowerCase.java -index 9a6efdd0..f15c1751 100644 ---- a/src/main/java/teetime/stage/string/ToLowerCase.java -+++ b/src/main/java/teetime/stage/string/ToLowerCase.java -@@ -17,0 +18,2 @@ package teetime.stage.string; -+import java.util.Locale; -+ -@@ -34,2 +36 @@ public final class ToLowerCase extends AbstractConsumerStage { -- this.outputPort.send(element.toLowerCase()); -- -+ this.outputPort.send(element.toLowerCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/new/ToLowerCase.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/new/ToLowerCase.java deleted file mode 100755 index f15c175..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/new/ToLowerCase.java +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://christianwulf.github.io/teetime) - * - * 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 teetime.stage.string; - -import java.util.Locale; - -import teetime.framework.AbstractConsumerStage; -import teetime.framework.OutputPort; - -/** - * Receives a string and passes it on to the next stage only with lower case letters. - * - * @since 1.1 - * - * @author Nelson Tavares de Sousa - */ -public final class ToLowerCase extends AbstractConsumerStage { - - private final OutputPort outputPort = this.createOutputPort(); - - @Override - protected void execute(final String element) { - this.outputPort.send(element.toLowerCase(Locale.ENGLISH)); - } - - public OutputPort getOutputPort() { - return this.outputPort; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/old/ToLowerCase.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/old/ToLowerCase.java deleted file mode 100755 index 9a6efdd..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/old/ToLowerCase.java +++ /dev/null @@ -1,42 +0,0 @@ -/** - * Copyright (C) 2015 Christian Wulf, Nelson Tavares de Sousa (http://christianwulf.github.io/teetime) - * - * 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 teetime.stage.string; - -import teetime.framework.AbstractConsumerStage; -import teetime.framework.OutputPort; - -/** - * Receives a string and passes it on to the next stage only with lower case letters. - * - * @since 1.1 - * - * @author Nelson Tavares de Sousa - */ -public final class ToLowerCase extends AbstractConsumerStage { - - private final OutputPort outputPort = this.createOutputPort(); - - @Override - protected void execute(final String element) { - this.outputPort.send(element.toLowerCase()); - - } - - public OutputPort getOutputPort() { - return this.outputPort; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/pair.info deleted file mode 100755 index 2d83f1a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#28021/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:28021 -comSha:1cecd76a398cdfa95045ae778ca4c8258e95b9d4 -parentComSha:a37b7d6efdabe41521bd1a7d08b753b512110bcf -BuggyFilePath:src/main/java/teetime/stage/string/ToLowerCase.java -FixedFilePath:src/main/java/teetime/stage/string/ToLowerCase.java -StartLineNum:34 -EndLineNum:34 -repoName:eXistence#TeeTime \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/comMsg.txt deleted file mode 100755 index 0baa73e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Bugfix \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/diff.diff deleted file mode 100755 index c0f87b5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java b/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java -index 71fd355..4273def 100644 ---- a/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java -+++ b/API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java -@@ -118 +118 @@ public class Classes { -- continue_ = kitTakeMoney(Bukkit.getPlayer(player), internalname.toLowerCase()); -+ continue_ = kitTakeMoney(Bukkit.getPlayer(player), internalname); -@@ -233 +233,2 @@ public class Classes { -- int money = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount"); -+ ClassesConfig config = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig(); -+ int money = config.getConfig().getInt("config.kits." + kit + ".money_amount"); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/new/Classes.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/new/Classes.java deleted file mode 100755 index 4273def..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/new/Classes.java +++ /dev/null @@ -1,266 +0,0 @@ -package com.comze_instancelabs.minigamesapi; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; - -import net.milkbowl.vault.economy.EconomyResponse; - -import org.apache.commons.lang.ArrayUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.java.JavaPlugin; - -import com.comze_instancelabs.minigamesapi.config.ClassesConfig; -import com.comze_instancelabs.minigamesapi.util.AClass; -import com.comze_instancelabs.minigamesapi.util.IconMenu; -import com.comze_instancelabs.minigamesapi.util.Util; -import com.shampaggon.crackshot.CSUtility; - -public class Classes { - - JavaPlugin plugin; - public HashMap lasticonm = new HashMap(); - - public Classes(JavaPlugin plugin) { - this.plugin = plugin; - } - - public void openGUI(final String p) { - final Classes cl = this; - IconMenu iconm; - int mincount = MinigamesAPI.getAPI().pinstances.get(plugin).getAClasses().keySet().size(); - if (lasticonm.containsKey(p)) { - iconm = lasticonm.get(p); - } else { - iconm = new IconMenu(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().classes_item, (9 * plugin.getConfig().getInt("config.classes_gui_rows") > mincount - 1) ? 9 * plugin.getConfig().getInt("config.classes_gui_rows") : Math.round(mincount / 9) * 9 + 9, new IconMenu.OptionClickEventHandler() { - @Override - public void onOptionClick(IconMenu.OptionClickEvent event) { - if (event.getPlayer().getName().equalsIgnoreCase(p)) { - String d = event.getName(); - Player p = event.getPlayer(); - if (MinigamesAPI.getAPI().pinstances.get(plugin).getAClasses().containsKey(d)) { - cl.setClass(MinigamesAPI.getAPI().pinstances.get(plugin).getClassesHandler().getInternalNameByName(d), p.getName()); - } - } - event.setWillClose(true); - } - }, plugin); - } - - int c = 0; - for (String ac : MinigamesAPI.getAPI().pinstances.get(plugin).getAClasses().keySet()) { - AClass ac_ = MinigamesAPI.getAPI().pinstances.get(plugin).getAClasses().get(ac); - if (ac_.isEnabled()) { - iconm.setOption(c, ac_.getIcon(), ac_.getName(), MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getString("config.kits." + ac_.getInternalName() + ".lore").split(";")); - c++; - } - } - - iconm.open(Bukkit.getPlayerExact(p)); - lasticonm.put(p, iconm); - } - - public void getClass(String player) { - AClass c = MinigamesAPI.getAPI().pinstances.get(plugin).getPClasses().get(player); - Player p = Bukkit.getServer().getPlayer(player); - p.getInventory().clear(); - p.getInventory().setHelmet(null); - p.getInventory().setChestplate(null); - p.getInventory().setLeggings(null); - p.getInventory().setBoots(null); - p.updateInventory(); - ArrayList items = new ArrayList(Arrays.asList(c.getItems())); - ArrayList temp = new ArrayList(Arrays.asList(c.getItems())); - ArrayList tempguns = new ArrayList(); - - // crackshot support - for (ItemStack item : temp) { - if (item != null) { - if (item.getItemMeta().hasDisplayName()) { - if (item.getItemMeta().getDisplayName().startsWith("crackshot:")) { - items.remove(item); - tempguns.add(item.getItemMeta().getDisplayName().split(":")[1]); - } - } - } - } - - p.getInventory().setContents((ItemStack[]) items.toArray(new ItemStack[items.size()])); - p.updateInventory(); - - if (MinigamesAPI.getAPI().crackshot) { - for (String t : tempguns) { - CSUtility cs = new CSUtility(); - cs.giveWeapon(p, t, 1); - } - } - } - - /** - * Sets the current class of a player - * - * @param classname - * the INTERNAL classname - * @param player - */ - public void setClass(String internalname, String player) { - if (!kitPlayerHasPermission(internalname, Bukkit.getPlayer(player))) { - Bukkit.getPlayer(player).sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().no_perm); - return; - } - boolean continue_ = true; - if (kitRequiresMoney(internalname)) { - continue_ = kitTakeMoney(Bukkit.getPlayer(player), internalname); - } - if (continue_) { - MinigamesAPI.getAPI().pinstances.get(plugin).setPClass(player, this.getClassByInternalname(internalname)); - Bukkit.getPlayer(player).sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().set_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(internalname).getName()))); - } - } - - public String getInternalNameByName(String name) { - PluginInstance pli = MinigamesAPI.getAPI().pinstances.get(plugin); - for (AClass ac : pli.getAClasses().values()) { - if (ac.getName().equalsIgnoreCase(name)) { - return ac.getInternalName(); - } - } - return "default"; - } - - public AClass getClassByInternalname(String internalname) { - PluginInstance pli = MinigamesAPI.getAPI().pinstances.get(plugin); - for (AClass ac : pli.getAClasses().values()) { - if (ac.getInternalName().equalsIgnoreCase(internalname)) { - return ac; - } - } - return null; - } - - public boolean hasClass(String player) { - return MinigamesAPI.getAPI().pinstances.get(plugin).getPClasses().containsKey(player); - } - - public void loadClasses() { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - FileConfiguration config = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig(); - if (config.isSet("config.kits")) { - for (String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) { - AClass n; - if (config.isSet("config.kits." + aclass + ".icon")) { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0)); - } else { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items"))); - } - // MinigamesAPI.getAPI().pinstances.get(plugin).addAClass(aclass, n); - MinigamesAPI.getAPI().pinstances.get(plugin).addAClass(config.getString("config.kits." + aclass + ".name"), n); - if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) { - plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!"); - } - } - } - } - }, 20L); - } - - /** - * Please use new Classes().loadClasses(); - * - * @param plugin - */ - @Deprecated - public static void loadClasses(final JavaPlugin plugin) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - FileConfiguration config = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig(); - if (config.isSet("config.kits")) { - for (String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) { - AClass n; - if (config.isSet("config.kits." + aclass + ".icon")) { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0)); - } else { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items"))); - } - // MinigamesAPI.getAPI().pinstances.get(plugin).addAClass(aclass, n); - MinigamesAPI.getAPI().pinstances.get(plugin).addAClass(config.getString("config.kits." + aclass + ".name"), n); - if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) { - plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!"); - } - } - } - } - }, 20L); - } - - public boolean kitRequiresMoney(String kit) { - return MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_money"); - } - - public boolean kitTakeMoney(Player p, String kit) { - if (!MinigamesAPI.getAPI().economy) { - plugin.getLogger().warning("Economy is turned OFF. Turn it ON in the config."); - return false; - } - if (MinigamesAPI.economy) { - if (plugin.getConfig().getBoolean("config.buy_classes_forever")) { - ClassesConfig cl = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig(); - if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit)) { - cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true); - cl.saveConfig(); - int money = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount"); - if (MinigamesAPI.getAPI().econ.getBalance(p.getName()) >= money) { - EconomyResponse r = MinigamesAPI.getAPI().econ.withdrawPlayer(p.getName(), money); - if (!r.transactionSuccess()) { - p.sendMessage(String.format("An error occured: %s", r.errorMessage)); - return false; - } - p.sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().successfully_bought_kit.replaceAll("", kit).replaceAll("", Integer.toString(money))); - } else { - p.sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().not_enough_money); - return false; - } - } else { - return true; - } - } else { - ClassesConfig config = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig(); - int money = config.getConfig().getInt("config.kits." + kit + ".money_amount"); - if (MinigamesAPI.getAPI().econ.getBalance(p.getName()) >= money) { - EconomyResponse r = MinigamesAPI.getAPI().econ.withdrawPlayer(p.getName(), money); - if (!r.transactionSuccess()) { - p.sendMessage(String.format("An error occured: %s", r.errorMessage)); - return false; - } - p.sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().successfully_bought_kit.replaceAll("", kit).replaceAll("", Integer.toString(money))); - } else { - p.sendMessage("§4You don't have enough money!"); - return false; - } - } - return true; - } else { - return false; - } - - } - - public boolean kitPlayerHasPermission(String kit, Player p) { - if (!MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_permission")) { - return true; - } else { - if (p.hasPermission(MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getString("config.kits." + kit + ".permission_node"))) { - return true; - } else { - return false; - } - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/old/Classes.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/old/Classes.java deleted file mode 100755 index 71fd355..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/old/Classes.java +++ /dev/null @@ -1,265 +0,0 @@ -package com.comze_instancelabs.minigamesapi; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; - -import net.milkbowl.vault.economy.EconomyResponse; - -import org.apache.commons.lang.ArrayUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.java.JavaPlugin; - -import com.comze_instancelabs.minigamesapi.config.ClassesConfig; -import com.comze_instancelabs.minigamesapi.util.AClass; -import com.comze_instancelabs.minigamesapi.util.IconMenu; -import com.comze_instancelabs.minigamesapi.util.Util; -import com.shampaggon.crackshot.CSUtility; - -public class Classes { - - JavaPlugin plugin; - public HashMap lasticonm = new HashMap(); - - public Classes(JavaPlugin plugin) { - this.plugin = plugin; - } - - public void openGUI(final String p) { - final Classes cl = this; - IconMenu iconm; - int mincount = MinigamesAPI.getAPI().pinstances.get(plugin).getAClasses().keySet().size(); - if (lasticonm.containsKey(p)) { - iconm = lasticonm.get(p); - } else { - iconm = new IconMenu(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().classes_item, (9 * plugin.getConfig().getInt("config.classes_gui_rows") > mincount - 1) ? 9 * plugin.getConfig().getInt("config.classes_gui_rows") : Math.round(mincount / 9) * 9 + 9, new IconMenu.OptionClickEventHandler() { - @Override - public void onOptionClick(IconMenu.OptionClickEvent event) { - if (event.getPlayer().getName().equalsIgnoreCase(p)) { - String d = event.getName(); - Player p = event.getPlayer(); - if (MinigamesAPI.getAPI().pinstances.get(plugin).getAClasses().containsKey(d)) { - cl.setClass(MinigamesAPI.getAPI().pinstances.get(plugin).getClassesHandler().getInternalNameByName(d), p.getName()); - } - } - event.setWillClose(true); - } - }, plugin); - } - - int c = 0; - for (String ac : MinigamesAPI.getAPI().pinstances.get(plugin).getAClasses().keySet()) { - AClass ac_ = MinigamesAPI.getAPI().pinstances.get(plugin).getAClasses().get(ac); - if (ac_.isEnabled()) { - iconm.setOption(c, ac_.getIcon(), ac_.getName(), MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getString("config.kits." + ac_.getInternalName() + ".lore").split(";")); - c++; - } - } - - iconm.open(Bukkit.getPlayerExact(p)); - lasticonm.put(p, iconm); - } - - public void getClass(String player) { - AClass c = MinigamesAPI.getAPI().pinstances.get(plugin).getPClasses().get(player); - Player p = Bukkit.getServer().getPlayer(player); - p.getInventory().clear(); - p.getInventory().setHelmet(null); - p.getInventory().setChestplate(null); - p.getInventory().setLeggings(null); - p.getInventory().setBoots(null); - p.updateInventory(); - ArrayList items = new ArrayList(Arrays.asList(c.getItems())); - ArrayList temp = new ArrayList(Arrays.asList(c.getItems())); - ArrayList tempguns = new ArrayList(); - - // crackshot support - for (ItemStack item : temp) { - if (item != null) { - if (item.getItemMeta().hasDisplayName()) { - if (item.getItemMeta().getDisplayName().startsWith("crackshot:")) { - items.remove(item); - tempguns.add(item.getItemMeta().getDisplayName().split(":")[1]); - } - } - } - } - - p.getInventory().setContents((ItemStack[]) items.toArray(new ItemStack[items.size()])); - p.updateInventory(); - - if (MinigamesAPI.getAPI().crackshot) { - for (String t : tempguns) { - CSUtility cs = new CSUtility(); - cs.giveWeapon(p, t, 1); - } - } - } - - /** - * Sets the current class of a player - * - * @param classname - * the INTERNAL classname - * @param player - */ - public void setClass(String internalname, String player) { - if (!kitPlayerHasPermission(internalname, Bukkit.getPlayer(player))) { - Bukkit.getPlayer(player).sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().no_perm); - return; - } - boolean continue_ = true; - if (kitRequiresMoney(internalname)) { - continue_ = kitTakeMoney(Bukkit.getPlayer(player), internalname.toLowerCase()); - } - if (continue_) { - MinigamesAPI.getAPI().pinstances.get(plugin).setPClass(player, this.getClassByInternalname(internalname)); - Bukkit.getPlayer(player).sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().set_kit.replaceAll("", ChatColor.translateAlternateColorCodes('&', getClassByInternalname(internalname).getName()))); - } - } - - public String getInternalNameByName(String name) { - PluginInstance pli = MinigamesAPI.getAPI().pinstances.get(plugin); - for (AClass ac : pli.getAClasses().values()) { - if (ac.getName().equalsIgnoreCase(name)) { - return ac.getInternalName(); - } - } - return "default"; - } - - public AClass getClassByInternalname(String internalname) { - PluginInstance pli = MinigamesAPI.getAPI().pinstances.get(plugin); - for (AClass ac : pli.getAClasses().values()) { - if (ac.getInternalName().equalsIgnoreCase(internalname)) { - return ac; - } - } - return null; - } - - public boolean hasClass(String player) { - return MinigamesAPI.getAPI().pinstances.get(plugin).getPClasses().containsKey(player); - } - - public void loadClasses() { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - FileConfiguration config = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig(); - if (config.isSet("config.kits")) { - for (String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) { - AClass n; - if (config.isSet("config.kits." + aclass + ".icon")) { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0)); - } else { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items"))); - } - // MinigamesAPI.getAPI().pinstances.get(plugin).addAClass(aclass, n); - MinigamesAPI.getAPI().pinstances.get(plugin).addAClass(config.getString("config.kits." + aclass + ".name"), n); - if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) { - plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!"); - } - } - } - } - }, 20L); - } - - /** - * Please use new Classes().loadClasses(); - * - * @param plugin - */ - @Deprecated - public static void loadClasses(final JavaPlugin plugin) { - Bukkit.getScheduler().runTaskLater(plugin, new Runnable() { - public void run() { - FileConfiguration config = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig(); - if (config.isSet("config.kits")) { - for (String aclass : config.getConfigurationSection("config.kits.").getKeys(false)) { - AClass n; - if (config.isSet("config.kits." + aclass + ".icon")) { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items")), Util.parseItems(config.getString("config.kits." + aclass + ".icon")).get(0)); - } else { - n = new AClass(plugin, config.getString("config.kits." + aclass + ".name"), aclass, config.isSet("config.kits." + aclass + ".enabled") ? config.getBoolean("config.kits." + aclass + ".enabled") : true, Util.parseItems(config.getString("config.kits." + aclass + ".items"))); - } - // MinigamesAPI.getAPI().pinstances.get(plugin).addAClass(aclass, n); - MinigamesAPI.getAPI().pinstances.get(plugin).addAClass(config.getString("config.kits." + aclass + ".name"), n); - if (!config.isSet("config.kits." + aclass + ".items") || !config.isSet("config.kits." + aclass + ".lore")) { - plugin.getLogger().warning("One of the classes found in the config file is invalid: " + aclass + ". Missing itemid or lore!"); - } - } - } - } - }, 20L); - } - - public boolean kitRequiresMoney(String kit) { - return MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_money"); - } - - public boolean kitTakeMoney(Player p, String kit) { - if (!MinigamesAPI.getAPI().economy) { - plugin.getLogger().warning("Economy is turned OFF. Turn it ON in the config."); - return false; - } - if (MinigamesAPI.economy) { - if (plugin.getConfig().getBoolean("config.buy_classes_forever")) { - ClassesConfig cl = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig(); - if (!cl.getConfig().isSet("players.bought_kits." + p.getName() + "." + kit)) { - cl.getConfig().set("players.bought_kits." + p.getName() + "." + kit, true); - cl.saveConfig(); - int money = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount"); - if (MinigamesAPI.getAPI().econ.getBalance(p.getName()) >= money) { - EconomyResponse r = MinigamesAPI.getAPI().econ.withdrawPlayer(p.getName(), money); - if (!r.transactionSuccess()) { - p.sendMessage(String.format("An error occured: %s", r.errorMessage)); - return false; - } - p.sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().successfully_bought_kit.replaceAll("", kit).replaceAll("", Integer.toString(money))); - } else { - p.sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().not_enough_money); - return false; - } - } else { - return true; - } - } else { - int money = MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getInt("config.kits." + kit + ".money_amount"); - if (MinigamesAPI.getAPI().econ.getBalance(p.getName()) >= money) { - EconomyResponse r = MinigamesAPI.getAPI().econ.withdrawPlayer(p.getName(), money); - if (!r.transactionSuccess()) { - p.sendMessage(String.format("An error occured: %s", r.errorMessage)); - return false; - } - p.sendMessage(MinigamesAPI.getAPI().pinstances.get(plugin).getMessagesConfig().successfully_bought_kit.replaceAll("", kit).replaceAll("", Integer.toString(money))); - } else { - p.sendMessage("§4You don't have enough money!"); - return false; - } - } - return true; - } else { - return false; - } - - } - - public boolean kitPlayerHasPermission(String kit, Player p) { - if (!MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getBoolean("config.kits." + kit + ".requires_permission")) { - return true; - } else { - if (p.hasPermission(MinigamesAPI.getAPI().pinstances.get(plugin).getClassesConfig().getConfig().getString("config.kits." + kit + ".permission_node"))) { - return true; - } else { - return false; - } - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/pair.info deleted file mode 100755 index 5dd001e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#44412/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:44412 -comSha:d7a0b1fe3d440e6493020d8fccf121d7e813c9f6 -parentComSha:18dbd83ee30e00ae17cc61b687663488d6665360 -BuggyFilePath:API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java -FixedFilePath:API/src/main/java/com/comze_instancelabs/minigamesapi/Classes.java -StartLineNum:118 -EndLineNum:118 -repoName:instance01#MinigamesAPI \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/comMsg.txt deleted file mode 100755 index da1470a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -[maven-release-plugin] copy for tag 4.0-alpha4 - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0-alpha4@653242 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/diff.diff deleted file mode 100755 index b3a0b6a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java b/module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -index bb1040d6c..d0040b060 100644 ---- a/module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -+++ b/module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -@@ -32,0 +33,2 @@ package org.apache.http.impl.cookie; -+import java.util.Locale; -+ -@@ -53 +55 @@ public class RFC2109DomainHandler implements CookieAttributeHandler { -- if (value.trim().equals("")) { -+ if (value.trim().length() == 0) { -@@ -93 +95 @@ public class RFC2109DomainHandler implements CookieAttributeHandler { -- host = host.toLowerCase(); -+ host = host.toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/new/RFC2109DomainHandler.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/new/RFC2109DomainHandler.java deleted file mode 100755 index d0040b0..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/new/RFC2109DomainHandler.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.Locale; - -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; - -public class RFC2109DomainHandler implements CookieAttributeHandler { - - public RFC2109DomainHandler() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (value == null) { - throw new MalformedCookieException("Missing value for domain attribute"); - } - if (value.trim().length() == 0) { - throw new MalformedCookieException("Blank value for domain attribute"); - } - cookie.setDomain(value); - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - throw new MalformedCookieException("Cookie domain may not be null"); - } - if (!domain.equals(host)) { - int dotIndex = domain.indexOf('.'); - if (dotIndex == -1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" does not match the host \"" - + host + "\""); - } - // domain must start with dot - if (!domain.startsWith(".")) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must start with a dot"); - } - // domain must have at least one embedded dot - dotIndex = domain.indexOf('.', 1); - if (dotIndex < 0 || dotIndex == domain.length() - 1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must contain an embedded dot"); - } - host = host.toLowerCase(Locale.ENGLISH); - if (!host.endsWith(domain)) { - throw new MalformedCookieException( - "Illegal domain attribute \"" + domain - + "\". Domain of origin: \"" + host + "\""); - } - // host minus domain may not contain any dots - String hostWithoutDomain = host.substring(0, host.length() - domain.length()); - if (hostWithoutDomain.indexOf('.') != -1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: host minus domain may not contain any dots"); - } - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain)); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/old/RFC2109DomainHandler.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/old/RFC2109DomainHandler.java deleted file mode 100755 index bb1040d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/old/RFC2109DomainHandler.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; - -public class RFC2109DomainHandler implements CookieAttributeHandler { - - public RFC2109DomainHandler() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (value == null) { - throw new MalformedCookieException("Missing value for domain attribute"); - } - if (value.trim().equals("")) { - throw new MalformedCookieException("Blank value for domain attribute"); - } - cookie.setDomain(value); - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - throw new MalformedCookieException("Cookie domain may not be null"); - } - if (!domain.equals(host)) { - int dotIndex = domain.indexOf('.'); - if (dotIndex == -1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" does not match the host \"" - + host + "\""); - } - // domain must start with dot - if (!domain.startsWith(".")) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must start with a dot"); - } - // domain must have at least one embedded dot - dotIndex = domain.indexOf('.', 1); - if (dotIndex < 0 || dotIndex == domain.length() - 1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must contain an embedded dot"); - } - host = host.toLowerCase(); - if (!host.endsWith(domain)) { - throw new MalformedCookieException( - "Illegal domain attribute \"" + domain - + "\". Domain of origin: \"" + host + "\""); - } - // host minus domain may not contain any dots - String hostWithoutDomain = host.substring(0, host.length() - domain.length()); - if (hostWithoutDomain.indexOf('.') != -1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: host minus domain may not contain any dots"); - } - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain)); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/pair.info deleted file mode 100755 index 49520ca..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47253/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47253 -comSha:b7b8c7731d36aaa2291f03480716a30b82837f21 -parentComSha:7fd801fcfd89666d2404899a5a9388a3bbb1b18b -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -StartLineNum:93 -EndLineNum:93 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/diff.diff deleted file mode 100755 index a3a7ce7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/auth/AuthScope.java b/module-client/src/main/java/org/apache/http/auth/AuthScope.java -index c8cf43052..344d6ff1c 100644 ---- a/module-client/src/main/java/org/apache/http/auth/AuthScope.java -+++ b/module-client/src/main/java/org/apache/http/auth/AuthScope.java -@@ -32,0 +33,2 @@ package org.apache.http.auth; -+import java.util.Locale; -+ -@@ -107 +109 @@ public class AuthScope { -- this.host = (host == null) ? ANY_HOST: host.toLowerCase(); -+ this.host = (host == null) ? ANY_HOST: host.toLowerCase(Locale.ENGLISH); -@@ -110 +112 @@ public class AuthScope { -- this.scheme = (scheme == null) ? ANY_SCHEME: scheme.toUpperCase(); -+ this.scheme = (scheme == null) ? ANY_SCHEME: scheme.toUpperCase(Locale.ENGLISH); -@@ -257 +259 @@ public class AuthScope { -- buffer.append(this.scheme.toUpperCase()); -+ buffer.append(this.scheme.toUpperCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/new/AuthScope.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/new/AuthScope.java deleted file mode 100755 index 344d6ff..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/new/AuthScope.java +++ /dev/null @@ -1,292 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.auth; - -import java.util.Locale; - -import org.apache.http.util.LangUtils; - -/** - * The class represents an authentication scope consisting of a host name, - * a port number, a realm name and an authentication scheme name which - * {@link Credentials Credentials} apply to. - * - * @author Oleg Kalnichevski - * @author Adrian Sutton - * - * @since 4.0 - */ -public class AuthScope { - - /** - * The null value represents any host. In the future versions of - * HttpClient the use of this parameter will be discontinued. - */ - public static final String ANY_HOST = null; - - /** - * The -1 value represents any port. - */ - public static final int ANY_PORT = -1; - - /** - * The null value represents any realm. - */ - public static final String ANY_REALM = null; - - /** - * The null value represents any authentication scheme. - */ - public static final String ANY_SCHEME = null; - - /** - * Default scope matching any host, port, realm and authentication scheme. - * In the future versions of HttpClient the use of this parameter will be - * discontinued. - */ - public static final AuthScope ANY = new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, ANY_SCHEME); - - /** The authentication scheme the credentials apply to. */ - private final String scheme; - - /** The realm the credentials apply to. */ - private final String realm; - - /** The host the credentials apply to. */ - private final String host; - - /** The port the credentials apply to. */ - private final int port; - - /** Creates a new credentials scope for the given - * host, port, realm, and - * authentication scheme. - * - * @param host the host the credentials apply to. May be set - * to null if credenticals are applicable to - * any host. - * @param port the port the credentials apply to. May be set - * to negative value if credenticals are applicable to - * any port. - * @param realm the realm the credentials apply to. May be set - * to null if credenticals are applicable to - * any realm. - * @param scheme the authentication scheme the credentials apply to. - * May be set to null if credenticals are applicable to - * any authentication scheme. - */ - public AuthScope(final String host, int port, - final String realm, final String scheme) - { - this.host = (host == null) ? ANY_HOST: host.toLowerCase(Locale.ENGLISH); - this.port = (port < 0) ? ANY_PORT: port; - this.realm = (realm == null) ? ANY_REALM: realm; - this.scheme = (scheme == null) ? ANY_SCHEME: scheme.toUpperCase(Locale.ENGLISH); - } - - /** Creates a new credentials scope for the given - * host, port, realm, and any - * authentication scheme. - * - * @param host the host the credentials apply to. May be set - * to null if credenticals are applicable to - * any host. - * @param port the port the credentials apply to. May be set - * to negative value if credenticals are applicable to - * any port. - * @param realm the realm the credentials apply to. May be set - * to null if credenticals are applicable to - * any realm. - */ - public AuthScope(final String host, int port, final String realm) { - this(host, port, realm, ANY_SCHEME); - } - - /** Creates a new credentials scope for the given - * host, port, any realm name, and any - * authentication scheme. - * - * @param host the host the credentials apply to. May be set - * to null if credenticals are applicable to - * any host. - * @param port the port the credentials apply to. May be set - * to negative value if credenticals are applicable to - * any port. - */ - public AuthScope(final String host, int port) { - this(host, port, ANY_REALM, ANY_SCHEME); - } - - /** - * Creates a copy of the given credentials scope. - */ - public AuthScope(final AuthScope authscope) { - super(); - if (authscope == null) { - throw new IllegalArgumentException("Scope may not be null"); - } - this.host = authscope.getHost(); - this.port = authscope.getPort(); - this.realm = authscope.getRealm(); - this.scheme = authscope.getScheme(); - } - - /** - * @return the host - */ - public String getHost() { - return this.host; - } - - /** - * @return the port - */ - public int getPort() { - return this.port; - } - - /** - * @return the realm name - */ - public String getRealm() { - return this.realm; - } - - /** - * @return the scheme type - */ - public String getScheme() { - return this.scheme; - } - - /** - * Tests if the authentication scopes match. - * - * @return the match factor. Negative value signifies no match. - * Non-negative signifies a match. The greater the returned value - * the closer the match. - */ - public int match(final AuthScope that) { - int factor = 0; - if (LangUtils.equals(this.scheme, that.scheme)) { - factor += 1; - } else { - if (this.scheme != ANY_SCHEME && that.scheme != ANY_SCHEME) { - return -1; - } - } - if (LangUtils.equals(this.realm, that.realm)) { - factor += 2; - } else { - if (this.realm != ANY_REALM && that.realm != ANY_REALM) { - return -1; - } - } - if (this.port == that.port) { - factor += 4; - } else { - if (this.port != ANY_PORT && that.port != ANY_PORT) { - return -1; - } - } - if (LangUtils.equals(this.host, that.host)) { - factor += 8; - } else { - if (this.host != ANY_HOST && that.host != ANY_HOST) { - return -1; - } - } - return factor; - } - - /** - * @see java.lang.Object#equals(Object) - */ - @Override - public boolean equals(Object o) { - if (o == null) { - return false; - } - if (o == this) { - return true; - } - if (!(o instanceof AuthScope)) { - return super.equals(o); - } - AuthScope that = (AuthScope) o; - return - LangUtils.equals(this.host, that.host) - && this.port == that.port - && LangUtils.equals(this.realm, that.realm) - && LangUtils.equals(this.scheme, that.scheme); - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuffer buffer = new StringBuffer(); - if (this.scheme != null) { - buffer.append(this.scheme.toUpperCase(Locale.ENGLISH)); - buffer.append(' '); - } - if (this.realm != null) { - buffer.append('\''); - buffer.append(this.realm); - buffer.append('\''); - } else { - buffer.append(""); - } - if (this.host != null) { - buffer.append('@'); - buffer.append(this.host); - if (this.port >= 0) { - buffer.append(':'); - buffer.append(this.port); - } - } - return buffer.toString(); - } - - /** - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.host); - hash = LangUtils.hashCode(hash, this.port); - hash = LangUtils.hashCode(hash, this.realm); - hash = LangUtils.hashCode(hash, this.scheme); - return hash; - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/old/AuthScope.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/old/AuthScope.java deleted file mode 100755 index c8cf430..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/old/AuthScope.java +++ /dev/null @@ -1,290 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.auth; - -import org.apache.http.util.LangUtils; - -/** - * The class represents an authentication scope consisting of a host name, - * a port number, a realm name and an authentication scheme name which - * {@link Credentials Credentials} apply to. - * - * @author Oleg Kalnichevski - * @author Adrian Sutton - * - * @since 4.0 - */ -public class AuthScope { - - /** - * The null value represents any host. In the future versions of - * HttpClient the use of this parameter will be discontinued. - */ - public static final String ANY_HOST = null; - - /** - * The -1 value represents any port. - */ - public static final int ANY_PORT = -1; - - /** - * The null value represents any realm. - */ - public static final String ANY_REALM = null; - - /** - * The null value represents any authentication scheme. - */ - public static final String ANY_SCHEME = null; - - /** - * Default scope matching any host, port, realm and authentication scheme. - * In the future versions of HttpClient the use of this parameter will be - * discontinued. - */ - public static final AuthScope ANY = new AuthScope(ANY_HOST, ANY_PORT, ANY_REALM, ANY_SCHEME); - - /** The authentication scheme the credentials apply to. */ - private final String scheme; - - /** The realm the credentials apply to. */ - private final String realm; - - /** The host the credentials apply to. */ - private final String host; - - /** The port the credentials apply to. */ - private final int port; - - /** Creates a new credentials scope for the given - * host, port, realm, and - * authentication scheme. - * - * @param host the host the credentials apply to. May be set - * to null if credenticals are applicable to - * any host. - * @param port the port the credentials apply to. May be set - * to negative value if credenticals are applicable to - * any port. - * @param realm the realm the credentials apply to. May be set - * to null if credenticals are applicable to - * any realm. - * @param scheme the authentication scheme the credentials apply to. - * May be set to null if credenticals are applicable to - * any authentication scheme. - */ - public AuthScope(final String host, int port, - final String realm, final String scheme) - { - this.host = (host == null) ? ANY_HOST: host.toLowerCase(); - this.port = (port < 0) ? ANY_PORT: port; - this.realm = (realm == null) ? ANY_REALM: realm; - this.scheme = (scheme == null) ? ANY_SCHEME: scheme.toUpperCase(); - } - - /** Creates a new credentials scope for the given - * host, port, realm, and any - * authentication scheme. - * - * @param host the host the credentials apply to. May be set - * to null if credenticals are applicable to - * any host. - * @param port the port the credentials apply to. May be set - * to negative value if credenticals are applicable to - * any port. - * @param realm the realm the credentials apply to. May be set - * to null if credenticals are applicable to - * any realm. - */ - public AuthScope(final String host, int port, final String realm) { - this(host, port, realm, ANY_SCHEME); - } - - /** Creates a new credentials scope for the given - * host, port, any realm name, and any - * authentication scheme. - * - * @param host the host the credentials apply to. May be set - * to null if credenticals are applicable to - * any host. - * @param port the port the credentials apply to. May be set - * to negative value if credenticals are applicable to - * any port. - */ - public AuthScope(final String host, int port) { - this(host, port, ANY_REALM, ANY_SCHEME); - } - - /** - * Creates a copy of the given credentials scope. - */ - public AuthScope(final AuthScope authscope) { - super(); - if (authscope == null) { - throw new IllegalArgumentException("Scope may not be null"); - } - this.host = authscope.getHost(); - this.port = authscope.getPort(); - this.realm = authscope.getRealm(); - this.scheme = authscope.getScheme(); - } - - /** - * @return the host - */ - public String getHost() { - return this.host; - } - - /** - * @return the port - */ - public int getPort() { - return this.port; - } - - /** - * @return the realm name - */ - public String getRealm() { - return this.realm; - } - - /** - * @return the scheme type - */ - public String getScheme() { - return this.scheme; - } - - /** - * Tests if the authentication scopes match. - * - * @return the match factor. Negative value signifies no match. - * Non-negative signifies a match. The greater the returned value - * the closer the match. - */ - public int match(final AuthScope that) { - int factor = 0; - if (LangUtils.equals(this.scheme, that.scheme)) { - factor += 1; - } else { - if (this.scheme != ANY_SCHEME && that.scheme != ANY_SCHEME) { - return -1; - } - } - if (LangUtils.equals(this.realm, that.realm)) { - factor += 2; - } else { - if (this.realm != ANY_REALM && that.realm != ANY_REALM) { - return -1; - } - } - if (this.port == that.port) { - factor += 4; - } else { - if (this.port != ANY_PORT && that.port != ANY_PORT) { - return -1; - } - } - if (LangUtils.equals(this.host, that.host)) { - factor += 8; - } else { - if (this.host != ANY_HOST && that.host != ANY_HOST) { - return -1; - } - } - return factor; - } - - /** - * @see java.lang.Object#equals(Object) - */ - @Override - public boolean equals(Object o) { - if (o == null) { - return false; - } - if (o == this) { - return true; - } - if (!(o instanceof AuthScope)) { - return super.equals(o); - } - AuthScope that = (AuthScope) o; - return - LangUtils.equals(this.host, that.host) - && this.port == that.port - && LangUtils.equals(this.realm, that.realm) - && LangUtils.equals(this.scheme, that.scheme); - } - - /** - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuffer buffer = new StringBuffer(); - if (this.scheme != null) { - buffer.append(this.scheme.toUpperCase()); - buffer.append(' '); - } - if (this.realm != null) { - buffer.append('\''); - buffer.append(this.realm); - buffer.append('\''); - } else { - buffer.append(""); - } - if (this.host != null) { - buffer.append('@'); - buffer.append(this.host); - if (this.port >= 0) { - buffer.append(':'); - buffer.append(this.port); - } - } - return buffer.toString(); - } - - /** - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.host); - hash = LangUtils.hashCode(hash, this.port); - hash = LangUtils.hashCode(hash, this.realm); - hash = LangUtils.hashCode(hash, this.scheme); - return hash; - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/pair.info deleted file mode 100755 index 216eac8..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47258/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47258 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/auth/AuthScope.java -FixedFilePath:module-client/src/main/java/org/apache/http/auth/AuthScope.java -StartLineNum:107 -EndLineNum:107 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/comMsg.txt deleted file mode 100755 index da1470a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -[maven-release-plugin] copy for tag 4.0-alpha4 - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0-alpha4@653242 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/diff.diff deleted file mode 100755 index e671fa3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java b/module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -index 86e30e46f..96793bbe6 100644 ---- a/module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -+++ b/module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -@@ -35,0 +36 @@ import java.util.List; -+import java.util.Locale; -@@ -112 +113 @@ public class BrowserCompatSpec extends CookieSpecBase { -- int i1 = headervalue.toLowerCase().indexOf("expires="); -+ int i1 = headervalue.toLowerCase(Locale.ENGLISH).indexOf("expires="); -@@ -115 +116 @@ public class BrowserCompatSpec extends CookieSpecBase { -- int i2 = headervalue.indexOf(";", i1); -+ int i2 = headervalue.indexOf(';', i1); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/new/BrowserCompatSpec.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/new/BrowserCompatSpec.java deleted file mode 100755 index 96793bb..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/new/BrowserCompatSpec.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BufferedHeader; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.CharArrayBuffer; - -/** - * Cookie specification that strives to closely mimic (mis)behavior of - * common web browser applications such as Microsoft Internet Explorer - * and Mozilla FireFox. - * - * @author Oleg Kalnichevski - * - * @since 4.0 - */ -public class BrowserCompatSpec extends CookieSpecBase { - - /** Valid date patterns used per default */ - private static final String[] DATE_PATTERNS = new String[] { - DateUtils.PATTERN_RFC1123, - DateUtils.PATTERN_RFC1036, - DateUtils.PATTERN_ASCTIME, - "EEE, dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MMM-yyyy HH-mm-ss z", - "EEE, dd MMM yy HH:mm:ss z", - "EEE dd-MMM-yyyy HH:mm:ss z", - "EEE dd MMM yyyy HH:mm:ss z", - "EEE dd-MMM-yyyy HH-mm-ss z", - "EEE dd-MMM-yy HH:mm:ss z", - "EEE dd MMM yy HH:mm:ss z", - "EEE,dd-MMM-yy HH:mm:ss z", - "EEE,dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MM-yyyy HH:mm:ss z", - }; - - private final String[] datepatterns; - - /** Default constructor */ - public BrowserCompatSpec(final String[] datepatterns) { - super(); - if (datepatterns != null) { - this.datepatterns = datepatterns.clone(); - } else { - this.datepatterns = DATE_PATTERNS; - } - registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler()); - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new BasicDomainHandler()); - registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler()); - registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler()); - registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler()); - registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler( - this.datepatterns)); - } - - /** Default constructor */ - public BrowserCompatSpec() { - this(null); - } - - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String headervalue = header.getValue(); - boolean isNetscapeCookie = false; - int i1 = headervalue.toLowerCase(Locale.ENGLISH).indexOf("expires="); - if (i1 != -1) { - i1 += "expires=".length(); - int i2 = headervalue.indexOf(';', i1); - if (i2 == -1) { - i2 = headervalue.length(); - } - try { - DateUtils.parseDate(headervalue.substring(i1, i2), this.datepatterns); - isNetscapeCookie = true; - } catch (DateParseException e) { - // Does not look like a valid expiry date - } - } - HeaderElement[] elems = null; - if (isNetscapeCookie) { - NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT; - CharArrayBuffer buffer; - ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor( - ((FormattedHeader) header).getValuePos(), - buffer.length()); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - elems = new HeaderElement[] { parser.parseHeader(buffer, cursor) }; - } else { - elems = header.getElements(); - } - return parse(elems, origin); - } - - public List
formatCookies(final List cookies) { - if (cookies == null) { - throw new IllegalArgumentException("List of cookies may not be null"); - } - if (cookies.isEmpty()) { - throw new IllegalArgumentException("List of cookies may not be empty"); - } - CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - for (int i = 0; i < cookies.size(); i++) { - Cookie cookie = cookies.get(i); - if (i > 0) { - buffer.append("; "); - } - buffer.append(cookie.getName()); - buffer.append("="); - String s = cookie.getValue(); - if (s != null) { - buffer.append(s); - } - } - List
headers = new ArrayList
(1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - public int getVersion() { - return 0; - } - - public Header getVersionHeader() { - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/old/BrowserCompatSpec.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/old/BrowserCompatSpec.java deleted file mode 100755 index 86e30e4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/old/BrowserCompatSpec.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BufferedHeader; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.CharArrayBuffer; - -/** - * Cookie specification that strives to closely mimic (mis)behavior of - * common web browser applications such as Microsoft Internet Explorer - * and Mozilla FireFox. - * - * @author Oleg Kalnichevski - * - * @since 4.0 - */ -public class BrowserCompatSpec extends CookieSpecBase { - - /** Valid date patterns used per default */ - private static final String[] DATE_PATTERNS = new String[] { - DateUtils.PATTERN_RFC1123, - DateUtils.PATTERN_RFC1036, - DateUtils.PATTERN_ASCTIME, - "EEE, dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MMM-yyyy HH-mm-ss z", - "EEE, dd MMM yy HH:mm:ss z", - "EEE dd-MMM-yyyy HH:mm:ss z", - "EEE dd MMM yyyy HH:mm:ss z", - "EEE dd-MMM-yyyy HH-mm-ss z", - "EEE dd-MMM-yy HH:mm:ss z", - "EEE dd MMM yy HH:mm:ss z", - "EEE,dd-MMM-yy HH:mm:ss z", - "EEE,dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MM-yyyy HH:mm:ss z", - }; - - private final String[] datepatterns; - - /** Default constructor */ - public BrowserCompatSpec(final String[] datepatterns) { - super(); - if (datepatterns != null) { - this.datepatterns = datepatterns.clone(); - } else { - this.datepatterns = DATE_PATTERNS; - } - registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler()); - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new BasicDomainHandler()); - registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler()); - registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler()); - registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler()); - registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler( - this.datepatterns)); - } - - /** Default constructor */ - public BrowserCompatSpec() { - this(null); - } - - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String headervalue = header.getValue(); - boolean isNetscapeCookie = false; - int i1 = headervalue.toLowerCase().indexOf("expires="); - if (i1 != -1) { - i1 += "expires=".length(); - int i2 = headervalue.indexOf(";", i1); - if (i2 == -1) { - i2 = headervalue.length(); - } - try { - DateUtils.parseDate(headervalue.substring(i1, i2), this.datepatterns); - isNetscapeCookie = true; - } catch (DateParseException e) { - // Does not look like a valid expiry date - } - } - HeaderElement[] elems = null; - if (isNetscapeCookie) { - NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT; - CharArrayBuffer buffer; - ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor( - ((FormattedHeader) header).getValuePos(), - buffer.length()); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - elems = new HeaderElement[] { parser.parseHeader(buffer, cursor) }; - } else { - elems = header.getElements(); - } - return parse(elems, origin); - } - - public List
formatCookies(final List cookies) { - if (cookies == null) { - throw new IllegalArgumentException("List of cookies may not be null"); - } - if (cookies.isEmpty()) { - throw new IllegalArgumentException("List of cookies may not be empty"); - } - CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - for (int i = 0; i < cookies.size(); i++) { - Cookie cookie = cookies.get(i); - if (i > 0) { - buffer.append("; "); - } - buffer.append(cookie.getName()); - buffer.append("="); - String s = cookie.getValue(); - if (s != null) { - buffer.append(s); - } - } - List
headers = new ArrayList
(1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - public int getVersion() { - return 0; - } - - public Header getVersionHeader() { - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/pair.info deleted file mode 100755 index f7a9b0e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47272/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47272 -comSha:b7b8c7731d36aaa2291f03480716a30b82837f21 -parentComSha:7fd801fcfd89666d2404899a5a9388a3bbb1b18b -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -StartLineNum:112 -EndLineNum:112 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/diff.diff deleted file mode 100755 index 2feb7d1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java b/module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -index bb1040d6c..0bf6ec20d 100644 ---- a/module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -+++ b/module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -@@ -32,0 +33,2 @@ package org.apache.http.impl.cookie; -+import java.util.Locale; -+ -@@ -93 +95 @@ public class RFC2109DomainHandler implements CookieAttributeHandler { -- host = host.toLowerCase(); -+ host = host.toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/new/RFC2109DomainHandler.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/new/RFC2109DomainHandler.java deleted file mode 100755 index 0bf6ec2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/new/RFC2109DomainHandler.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.Locale; - -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; - -public class RFC2109DomainHandler implements CookieAttributeHandler { - - public RFC2109DomainHandler() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (value == null) { - throw new MalformedCookieException("Missing value for domain attribute"); - } - if (value.trim().equals("")) { - throw new MalformedCookieException("Blank value for domain attribute"); - } - cookie.setDomain(value); - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - throw new MalformedCookieException("Cookie domain may not be null"); - } - if (!domain.equals(host)) { - int dotIndex = domain.indexOf('.'); - if (dotIndex == -1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" does not match the host \"" - + host + "\""); - } - // domain must start with dot - if (!domain.startsWith(".")) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must start with a dot"); - } - // domain must have at least one embedded dot - dotIndex = domain.indexOf('.', 1); - if (dotIndex < 0 || dotIndex == domain.length() - 1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must contain an embedded dot"); - } - host = host.toLowerCase(Locale.ENGLISH); - if (!host.endsWith(domain)) { - throw new MalformedCookieException( - "Illegal domain attribute \"" + domain - + "\". Domain of origin: \"" + host + "\""); - } - // host minus domain may not contain any dots - String hostWithoutDomain = host.substring(0, host.length() - domain.length()); - if (hostWithoutDomain.indexOf('.') != -1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: host minus domain may not contain any dots"); - } - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain)); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/old/RFC2109DomainHandler.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/old/RFC2109DomainHandler.java deleted file mode 100755 index bb1040d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/old/RFC2109DomainHandler.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SetCookie; - -public class RFC2109DomainHandler implements CookieAttributeHandler { - - public RFC2109DomainHandler() { - super(); - } - - public void parse(final SetCookie cookie, final String value) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (value == null) { - throw new MalformedCookieException("Missing value for domain attribute"); - } - if (value.trim().equals("")) { - throw new MalformedCookieException("Blank value for domain attribute"); - } - cookie.setDomain(value); - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - throw new MalformedCookieException("Cookie domain may not be null"); - } - if (!domain.equals(host)) { - int dotIndex = domain.indexOf('.'); - if (dotIndex == -1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" does not match the host \"" - + host + "\""); - } - // domain must start with dot - if (!domain.startsWith(".")) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must start with a dot"); - } - // domain must have at least one embedded dot - dotIndex = domain.indexOf('.', 1); - if (dotIndex < 0 || dotIndex == domain.length() - 1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: domain must contain an embedded dot"); - } - host = host.toLowerCase(); - if (!host.endsWith(domain)) { - throw new MalformedCookieException( - "Illegal domain attribute \"" + domain - + "\". Domain of origin: \"" + host + "\""); - } - // host minus domain may not contain any dots - String hostWithoutDomain = host.substring(0, host.length() - domain.length()); - if (hostWithoutDomain.indexOf('.') != -1) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates RFC 2109: host minus domain may not contain any dots"); - } - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.equals(domain) || (domain.startsWith(".") && host.endsWith(domain)); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/pair.info deleted file mode 100755 index 4066fd8..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47277/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47277 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/cookie/RFC2109DomainHandler.java -StartLineNum:93 -EndLineNum:93 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/diff.diff deleted file mode 100755 index 107862c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/cookie/RFC2965Spec.java b/module-client/src/main/java/org/apache/http/impl/cookie/RFC2965Spec.java -index afbb5cc6e..d36d8806f 100644 ---- a/module-client/src/main/java/org/apache/http/impl/cookie/RFC2965Spec.java -+++ b/module-client/src/main/java/org/apache/http/impl/cookie/RFC2965Spec.java -@@ -35,0 +36 @@ import java.util.List; -+import java.util.Locale; -@@ -135 +136 @@ public class RFC2965Spec extends RFC2109Spec { -- attribmap.put(param.getName().toLowerCase(), param); -+ attribmap.put(param.getName().toLowerCase(Locale.ENGLISH), param); -@@ -139 +140 @@ public class RFC2965Spec extends RFC2109Spec { -- String s = attrib.getName().toLowerCase(); -+ String s = attrib.getName().toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/new/RFC2965Spec.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/new/RFC2965Spec.java deleted file mode 100755 index d36d880..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/new/RFC2965Spec.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.NameValuePair; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BufferedHeader; -import org.apache.http.util.CharArrayBuffer; - -/** - *

RFC 2965 specific cookie management functions.

- * - * @author jain.samit@gmail.com (Samit Jain) - * @author Oleg Kalnichevski - * - * @since 3.1 - */ -public class RFC2965Spec extends RFC2109Spec { - - /** - * Default constructor - * - */ - public RFC2965Spec() { - this(null, false); - } - - public RFC2965Spec(final String[] datepatterns, boolean oneHeader) { - super(datepatterns, oneHeader); - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new RFC2965DomainAttributeHandler()); - registerAttribHandler(ClientCookie.PORT_ATTR, new RFC2965PortAttributeHandler()); - registerAttribHandler(ClientCookie.COMMENTURL_ATTR, new RFC2965CommentUrlAttributeHandler()); - registerAttribHandler(ClientCookie.DISCARD_ATTR, new RFC2965DiscardAttributeHandler()); - registerAttribHandler(ClientCookie.VERSION_ATTR, new RFC2965VersionAttributeHandler()); - } - - private BasicClientCookie createCookie( - final String name, final String value, final CookieOrigin origin) { - BasicClientCookie cookie = new BasicClientCookie(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - return cookie; - } - - private BasicClientCookie createCookie2( - final String name, final String value, final CookieOrigin origin) { - BasicClientCookie2 cookie = new BasicClientCookie2(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - cookie.setPorts(new int [] { origin.getPort() }); - return cookie; - } - - @Override - public List parse( - final Header header, - CookieOrigin origin) throws MalformedCookieException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - - origin = adjustEffectiveHost(origin); - - HeaderElement[] elems = header.getElements(); - - List cookies = new ArrayList(elems.length); - for (int i = 0; i < elems.length; i++) { - HeaderElement headerelement = elems[i]; - - String name = headerelement.getName(); - String value = headerelement.getValue(); - if (name == null || name.equals("")) { - throw new MalformedCookieException("Cookie name may not be empty"); - } - - BasicClientCookie cookie; - if (header.getName().equals(SM.SET_COOKIE2)) { - cookie = createCookie2(name, value, origin); - } else { - cookie = createCookie(name, value, origin); - } - - // cycle through the parameters - NameValuePair[] attribs = headerelement.getParameters(); - - // Eliminate duplicate attributes. The first occurrence takes precedence - // See RFC2965: 3.2 Origin Server Role - Map attribmap = - new HashMap(attribs.length); - for (int j = attribs.length - 1; j >= 0; j--) { - NameValuePair param = attribs[j]; - attribmap.put(param.getName().toLowerCase(Locale.ENGLISH), param); - } - for (Map.Entry entry: attribmap.entrySet()) { - NameValuePair attrib = entry.getValue(); - String s = attrib.getName().toLowerCase(Locale.ENGLISH); - - cookie.setAttribute(s, attrib.getValue()); - - CookieAttributeHandler handler = findAttribHandler(s); - if (handler != null) { - handler.parse(cookie, attrib.getValue()); - } - } - cookies.add(cookie); - } - return cookies; - } - - @Override - public void validate(final Cookie cookie, CookieOrigin origin) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - origin = adjustEffectiveHost(origin); - super.validate(cookie, origin); - } - - @Override - public boolean match(final Cookie cookie, CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - origin = adjustEffectiveHost(origin); - return super.match(cookie, origin); - } - - /** - * Adds valid Port attribute value, e.g. "8000,8001,8002" - */ - @Override - protected void formatCookieAsVer(final CharArrayBuffer buffer, - final Cookie cookie, int version) { - super.formatCookieAsVer(buffer, cookie, version); - // format port attribute - if (cookie instanceof ClientCookie) { - // Test if the port attribute as set by the origin server is not blank - String s = ((ClientCookie) cookie).getAttribute(ClientCookie.PORT_ATTR); - if (s != null) { - buffer.append("; $Port"); - buffer.append("=\""); - if (s.trim().length() > 0) { - int[] ports = cookie.getPorts(); - if (ports != null) { - for (int i = 0, len = ports.length; i < len; i++) { - if (i > 0) { - buffer.append(","); - } - buffer.append(Integer.toString(ports[i])); - } - } - } - buffer.append("\""); - } - } - } - - /** - * Set 'effective host name' as defined in RFC 2965. - *

- * If a host name contains no dots, the effective host name is - * that name with the string .local appended to it. Otherwise - * the effective host name is the same as the host name. Note - * that all effective host names contain at least one dot. - * - * @param host host name where cookie is received from or being sent to. - * @return - */ - private static CookieOrigin adjustEffectiveHost(final CookieOrigin origin) { - String host = origin.getHost(); - - // Test if the host name appears to be a fully qualified DNS name, - // IPv4 address or IPv6 address - boolean isLocalHost = true; - for (int i = 0; i < host.length(); i++) { - char ch = host.charAt(i); - if (ch == '.' || ch == ':') { - isLocalHost = false; - break; - } - } - if (isLocalHost) { - host += ".local"; - return new CookieOrigin( - host, - origin.getPort(), - origin.getPath(), - origin.isSecure()); - } else { - return origin; - } - } - - @Override - public int getVersion() { - return 1; - } - - @Override - public Header getVersionHeader() { - CharArrayBuffer buffer = new CharArrayBuffer(40); - buffer.append(SM.COOKIE2); - buffer.append(": "); - buffer.append("$Version="); - buffer.append(Integer.toString(getVersion())); - return new BufferedHeader(buffer); - } - -} - diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/old/RFC2965Spec.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/old/RFC2965Spec.java deleted file mode 100755 index afbb5cc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/old/RFC2965Spec.java +++ /dev/null @@ -1,260 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.NameValuePair; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BufferedHeader; -import org.apache.http.util.CharArrayBuffer; - -/** - *

RFC 2965 specific cookie management functions.

- * - * @author jain.samit@gmail.com (Samit Jain) - * @author Oleg Kalnichevski - * - * @since 3.1 - */ -public class RFC2965Spec extends RFC2109Spec { - - /** - * Default constructor - * - */ - public RFC2965Spec() { - this(null, false); - } - - public RFC2965Spec(final String[] datepatterns, boolean oneHeader) { - super(datepatterns, oneHeader); - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new RFC2965DomainAttributeHandler()); - registerAttribHandler(ClientCookie.PORT_ATTR, new RFC2965PortAttributeHandler()); - registerAttribHandler(ClientCookie.COMMENTURL_ATTR, new RFC2965CommentUrlAttributeHandler()); - registerAttribHandler(ClientCookie.DISCARD_ATTR, new RFC2965DiscardAttributeHandler()); - registerAttribHandler(ClientCookie.VERSION_ATTR, new RFC2965VersionAttributeHandler()); - } - - private BasicClientCookie createCookie( - final String name, final String value, final CookieOrigin origin) { - BasicClientCookie cookie = new BasicClientCookie(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - return cookie; - } - - private BasicClientCookie createCookie2( - final String name, final String value, final CookieOrigin origin) { - BasicClientCookie2 cookie = new BasicClientCookie2(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - cookie.setPorts(new int [] { origin.getPort() }); - return cookie; - } - - @Override - public List parse( - final Header header, - CookieOrigin origin) throws MalformedCookieException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - - origin = adjustEffectiveHost(origin); - - HeaderElement[] elems = header.getElements(); - - List cookies = new ArrayList(elems.length); - for (int i = 0; i < elems.length; i++) { - HeaderElement headerelement = elems[i]; - - String name = headerelement.getName(); - String value = headerelement.getValue(); - if (name == null || name.equals("")) { - throw new MalformedCookieException("Cookie name may not be empty"); - } - - BasicClientCookie cookie; - if (header.getName().equals(SM.SET_COOKIE2)) { - cookie = createCookie2(name, value, origin); - } else { - cookie = createCookie(name, value, origin); - } - - // cycle through the parameters - NameValuePair[] attribs = headerelement.getParameters(); - - // Eliminate duplicate attributes. The first occurrence takes precedence - // See RFC2965: 3.2 Origin Server Role - Map attribmap = - new HashMap(attribs.length); - for (int j = attribs.length - 1; j >= 0; j--) { - NameValuePair param = attribs[j]; - attribmap.put(param.getName().toLowerCase(), param); - } - for (Map.Entry entry: attribmap.entrySet()) { - NameValuePair attrib = entry.getValue(); - String s = attrib.getName().toLowerCase(); - - cookie.setAttribute(s, attrib.getValue()); - - CookieAttributeHandler handler = findAttribHandler(s); - if (handler != null) { - handler.parse(cookie, attrib.getValue()); - } - } - cookies.add(cookie); - } - return cookies; - } - - @Override - public void validate(final Cookie cookie, CookieOrigin origin) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - origin = adjustEffectiveHost(origin); - super.validate(cookie, origin); - } - - @Override - public boolean match(final Cookie cookie, CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - origin = adjustEffectiveHost(origin); - return super.match(cookie, origin); - } - - /** - * Adds valid Port attribute value, e.g. "8000,8001,8002" - */ - @Override - protected void formatCookieAsVer(final CharArrayBuffer buffer, - final Cookie cookie, int version) { - super.formatCookieAsVer(buffer, cookie, version); - // format port attribute - if (cookie instanceof ClientCookie) { - // Test if the port attribute as set by the origin server is not blank - String s = ((ClientCookie) cookie).getAttribute(ClientCookie.PORT_ATTR); - if (s != null) { - buffer.append("; $Port"); - buffer.append("=\""); - if (s.trim().length() > 0) { - int[] ports = cookie.getPorts(); - if (ports != null) { - for (int i = 0, len = ports.length; i < len; i++) { - if (i > 0) { - buffer.append(","); - } - buffer.append(Integer.toString(ports[i])); - } - } - } - buffer.append("\""); - } - } - } - - /** - * Set 'effective host name' as defined in RFC 2965. - *

- * If a host name contains no dots, the effective host name is - * that name with the string .local appended to it. Otherwise - * the effective host name is the same as the host name. Note - * that all effective host names contain at least one dot. - * - * @param host host name where cookie is received from or being sent to. - * @return - */ - private static CookieOrigin adjustEffectiveHost(final CookieOrigin origin) { - String host = origin.getHost(); - - // Test if the host name appears to be a fully qualified DNS name, - // IPv4 address or IPv6 address - boolean isLocalHost = true; - for (int i = 0; i < host.length(); i++) { - char ch = host.charAt(i); - if (ch == '.' || ch == ':') { - isLocalHost = false; - break; - } - } - if (isLocalHost) { - host += ".local"; - return new CookieOrigin( - host, - origin.getPort(), - origin.getPath(), - origin.isSecure()); - } else { - return origin; - } - } - - @Override - public int getVersion() { - return 1; - } - - @Override - public Header getVersionHeader() { - CharArrayBuffer buffer = new CharArrayBuffer(40); - buffer.append(SM.COOKIE2); - buffer.append(": "); - buffer.append("$Version="); - buffer.append(Integer.toString(getVersion())); - return new BufferedHeader(buffer); - } - -} - diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/pair.info deleted file mode 100755 index b2bbfbf..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47279/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47279 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/cookie/RFC2965Spec.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/cookie/RFC2965Spec.java -StartLineNum:135 -EndLineNum:135 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/diff.diff deleted file mode 100755 index 6c3b526..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/cookie/CookieOrigin.java b/module-client/src/main/java/org/apache/http/cookie/CookieOrigin.java -index 4ac5f36c7..68db99cea 100644 ---- a/module-client/src/main/java/org/apache/http/cookie/CookieOrigin.java -+++ b/module-client/src/main/java/org/apache/http/cookie/CookieOrigin.java -@@ -32,0 +33,2 @@ package org.apache.http.cookie; -+import java.util.Locale; -+ -@@ -65 +67 @@ public final class CookieOrigin { -- this.host = host.toLowerCase(); -+ this.host = host.toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/new/CookieOrigin.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/new/CookieOrigin.java deleted file mode 100755 index 68db99c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/new/CookieOrigin.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.cookie; - -import java.util.Locale; - -/** - * CookieOrigin class incapsulates details of an origin server that - * are relevant when parsing, validating or matching HTTP cookies. - * - * @author Oleg Kalnichevski - * - * @since 4.0 - */ -public final class CookieOrigin { - - private final String host; - private final int port; - private final String path; - private final boolean secure; - - public CookieOrigin(final String host, int port, final String path, boolean secure) { - super(); - if (host == null) { - throw new IllegalArgumentException( - "Host of origin may not be null"); - } - if (host.trim().equals("")) { - throw new IllegalArgumentException( - "Host of origin may not be blank"); - } - if (port < 0) { - throw new IllegalArgumentException("Invalid port: " + port); - } - if (path == null) { - throw new IllegalArgumentException( - "Path of origin may not be null."); - } - this.host = host.toLowerCase(Locale.ENGLISH); - this.port = port; - if (!path.trim().equals("")) { - this.path = path; - } else { - this.path = "/"; - } - this.secure = secure; - } - - public String getHost() { - return this.host; - } - - public String getPath() { - return this.path; - } - - public int getPort() { - return this.port; - } - - public boolean isSecure() { - return this.secure; - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append("["); - if (this.secure) { - buffer.append("(secure)"); - } - buffer.append(this.host); - buffer.append(":"); - buffer.append(Integer.toString(this.port)); - buffer.append(this.path); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/old/CookieOrigin.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/old/CookieOrigin.java deleted file mode 100755 index 4ac5f36..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/old/CookieOrigin.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.cookie; - -/** - * CookieOrigin class incapsulates details of an origin server that - * are relevant when parsing, validating or matching HTTP cookies. - * - * @author Oleg Kalnichevski - * - * @since 4.0 - */ -public final class CookieOrigin { - - private final String host; - private final int port; - private final String path; - private final boolean secure; - - public CookieOrigin(final String host, int port, final String path, boolean secure) { - super(); - if (host == null) { - throw new IllegalArgumentException( - "Host of origin may not be null"); - } - if (host.trim().equals("")) { - throw new IllegalArgumentException( - "Host of origin may not be blank"); - } - if (port < 0) { - throw new IllegalArgumentException("Invalid port: " + port); - } - if (path == null) { - throw new IllegalArgumentException( - "Path of origin may not be null."); - } - this.host = host.toLowerCase(); - this.port = port; - if (!path.trim().equals("")) { - this.path = path; - } else { - this.path = "/"; - } - this.secure = secure; - } - - public String getHost() { - return this.host; - } - - public String getPath() { - return this.path; - } - - public int getPort() { - return this.port; - } - - public boolean isSecure() { - return this.secure; - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append("["); - if (this.secure) { - buffer.append("(secure)"); - } - buffer.append(this.host); - buffer.append(":"); - buffer.append(Integer.toString(this.port)); - buffer.append(this.path); - buffer.append("]"); - return buffer.toString(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/pair.info deleted file mode 100755 index 1ebf2ab..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47282/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47282 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/cookie/CookieOrigin.java -FixedFilePath:module-client/src/main/java/org/apache/http/cookie/CookieOrigin.java -StartLineNum:65 -EndLineNum:65 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/diff.diff deleted file mode 100755 index 8598f21..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java b/module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -index 013f5c2f8..0f3a8779b 100644 ---- a/module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -+++ b/module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -@@ -33,0 +34 @@ import java.util.HashMap; -+import java.util.Locale; -@@ -162 +163 @@ public abstract class RFC2617Scheme implements AuthScheme { -- return this.params.get(name.toLowerCase()); -+ return this.params.get(name.toLowerCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/new/RFC2617Scheme.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/new/RFC2617Scheme.java deleted file mode 100755 index 0f3a877..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/new/RFC2617Scheme.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * $HeadeURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.auth; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.FormattedHeader; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.message.BasicHeaderValueParser; -import org.apache.http.message.HeaderValueParser; -import org.apache.http.message.ParserCursor; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.CharArrayBuffer; - -/** - *

- * Abstract authentication scheme class that lays foundation for all - * RFC 2617 compliant authetication schemes and provides capabilities common - * to all authentication schemes defined in RFC 2617. - *

- * - * @author Oleg Kalnichevski -*/ -public abstract class RFC2617Scheme implements AuthScheme { - - /** - * Authentication parameter map. - */ - private Map params = null; - - /** - * Flag whether authenticating against a proxy. - */ - private boolean proxy; - - /** - * Default constructor for RFC2617 compliant authetication schemes. - */ - public RFC2617Scheme() { - super(); - } - - /** - * Processes the given challenge token. Some authentication schemes - * may involve multiple challenge-response exchanges. Such schemes must be able - * to maintain the state information when dealing with sequential challenges - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - public void processChallenge(final Header header) throws MalformedChallengeException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - String authheader = header.getName(); - if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) { - this.proxy = false; - } else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) { - this.proxy = true; - } else { - throw new MalformedChallengeException("Unexpected header name: " + authheader); - } - - CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int endIndex = pos; - String s = buffer.substring(beginIndex, endIndex); - if (!s.equalsIgnoreCase(getSchemeName())) { - throw new MalformedChallengeException("Invalid scheme identifier: " + s); - } - HeaderValueParser parser = BasicHeaderValueParser.DEFAULT; - ParserCursor cursor = new ParserCursor(pos, buffer.length()); - HeaderElement[] elements = parser.parseElements(buffer, cursor); - if (elements.length == 0) { - throw new MalformedChallengeException("Authentication challenge is empty"); - } - - this.params = new HashMap(elements.length); - for (int i = 0; i < elements.length; i++) { - HeaderElement element = elements[i]; - this.params.put(element.getName(), element.getValue()); - } - } - - /** - * Returns authentication parameters map. Keys in the map are lower-cased. - * - * @return the map of authentication parameters - */ - protected Map getParameters() { - return this.params; - } - - /** - * Returns authentication parameter with the given name, if available. - * - * @param name The name of the parameter to be returned - * - * @return the parameter with the given name - */ - public String getParameter(final String name) { - if (name == null) { - throw new IllegalArgumentException("Parameter name may not be null"); - } - if (this.params == null) { - return null; - } - return this.params.get(name.toLowerCase(Locale.ENGLISH)); - } - - /** - * Returns authentication realm. The realm may not be null. - * - * @return the authentication realm - */ - public String getRealm() { - return getParameter("realm"); - } - - /** - * Returns true if authenticating against a proxy, false - * otherwise. - * - * @return true if authenticating against a proxy, false - * otherwise - */ - public boolean isProxy() { - return this.proxy; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/old/RFC2617Scheme.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/old/RFC2617Scheme.java deleted file mode 100755 index 013f5c2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/old/RFC2617Scheme.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * $HeadeURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.auth; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.FormattedHeader; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.message.BasicHeaderValueParser; -import org.apache.http.message.HeaderValueParser; -import org.apache.http.message.ParserCursor; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.CharArrayBuffer; - -/** - *

- * Abstract authentication scheme class that lays foundation for all - * RFC 2617 compliant authetication schemes and provides capabilities common - * to all authentication schemes defined in RFC 2617. - *

- * - * @author Oleg Kalnichevski -*/ -public abstract class RFC2617Scheme implements AuthScheme { - - /** - * Authentication parameter map. - */ - private Map params = null; - - /** - * Flag whether authenticating against a proxy. - */ - private boolean proxy; - - /** - * Default constructor for RFC2617 compliant authetication schemes. - */ - public RFC2617Scheme() { - super(); - } - - /** - * Processes the given challenge token. Some authentication schemes - * may involve multiple challenge-response exchanges. Such schemes must be able - * to maintain the state information when dealing with sequential challenges - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - public void processChallenge(final Header header) throws MalformedChallengeException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - String authheader = header.getName(); - if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) { - this.proxy = false; - } else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) { - this.proxy = true; - } else { - throw new MalformedChallengeException("Unexpected header name: " + authheader); - } - - CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int endIndex = pos; - String s = buffer.substring(beginIndex, endIndex); - if (!s.equalsIgnoreCase(getSchemeName())) { - throw new MalformedChallengeException("Invalid scheme identifier: " + s); - } - HeaderValueParser parser = BasicHeaderValueParser.DEFAULT; - ParserCursor cursor = new ParserCursor(pos, buffer.length()); - HeaderElement[] elements = parser.parseElements(buffer, cursor); - if (elements.length == 0) { - throw new MalformedChallengeException("Authentication challenge is empty"); - } - - this.params = new HashMap(elements.length); - for (int i = 0; i < elements.length; i++) { - HeaderElement element = elements[i]; - this.params.put(element.getName(), element.getValue()); - } - } - - /** - * Returns authentication parameters map. Keys in the map are lower-cased. - * - * @return the map of authentication parameters - */ - protected Map getParameters() { - return this.params; - } - - /** - * Returns authentication parameter with the given name, if available. - * - * @param name The name of the parameter to be returned - * - * @return the parameter with the given name - */ - public String getParameter(final String name) { - if (name == null) { - throw new IllegalArgumentException("Parameter name may not be null"); - } - if (this.params == null) { - return null; - } - return this.params.get(name.toLowerCase()); - } - - /** - * Returns authentication realm. The realm may not be null. - * - * @return the authentication realm - */ - public String getRealm() { - return getParameter("realm"); - } - - /** - * Returns true if authenticating against a proxy, false - * otherwise. - * - * @return true if authenticating against a proxy, false - * otherwise - */ - public boolean isProxy() { - return this.proxy; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/pair.info deleted file mode 100755 index 621da56..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47285/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47285 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -StartLineNum:162 -EndLineNum:162 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/comMsg.txt deleted file mode 100755 index da1470a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -[maven-release-plugin] copy for tag 4.0-alpha4 - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0-alpha4@653242 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/diff.diff deleted file mode 100755 index 5cea448..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/cookie/CookieSpecRegistry.java b/module-client/src/main/java/org/apache/http/cookie/CookieSpecRegistry.java -index bc5688223..4cdafe7e5 100644 ---- a/module-client/src/main/java/org/apache/http/cookie/CookieSpecRegistry.java -+++ b/module-client/src/main/java/org/apache/http/cookie/CookieSpecRegistry.java -@@ -36,0 +37 @@ import java.util.List; -+import java.util.Locale; -@@ -78 +79 @@ public final class CookieSpecRegistry { -- registeredSpecs.put(name.toLowerCase(), factory); -+ registeredSpecs.put(name.toLowerCase(Locale.ENGLISH), factory); -@@ -90 +91 @@ public final class CookieSpecRegistry { -- registeredSpecs.remove(id.toLowerCase()); -+ registeredSpecs.remove(id.toLowerCase(Locale.ENGLISH)); -@@ -110 +111 @@ public final class CookieSpecRegistry { -- CookieSpecFactory factory = registeredSpecs.get(name.toLowerCase()); -+ CookieSpecFactory factory = registeredSpecs.get(name.toLowerCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/new/CookieSpecRegistry.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/new/CookieSpecRegistry.java deleted file mode 100755 index 4cdafe7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/new/CookieSpecRegistry.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.cookie; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.params.HttpParams; - -/** - * Cookie specification registry that can be used to obtain the corresponding - * cookie specification implementation for a given type of type or version of - * cookie. - * - * @author Oleg Kalnichevski - * @author Mike Bowler - * - * @since 4.0 - */ -public final class CookieSpecRegistry { - - private final Map registeredSpecs; - - public CookieSpecRegistry() { - super(); - this.registeredSpecs = new LinkedHashMap(); - } - - /** - * Registers a {@link CookieSpecFactory} with the given identifier. - * If a specification with the given name already exists it will be overridden. - * This nameis the same one used to retrieve the {@link CookieSpecFactory} - * from {@link #getCookieSpec(String)}. - * - * @param name the identifier for this specification - * @param factory the {@link CookieSpecFactory} class to register - * - * @see #getCookieSpec(String) - */ - public synchronized void register(final String name, final CookieSpecFactory factory) { - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - if (factory == null) { - throw new IllegalArgumentException("Cookie spec factory may not be null"); - } - registeredSpecs.put(name.toLowerCase(Locale.ENGLISH), factory); - } - - /** - * Unregisters the {@link CookieSpecFactory} with the given ID. - * - * @param id the identifier of the {@link CookieSpec cookie specification} to unregister - */ - public synchronized void unregister(final String id) { - if (id == null) { - throw new IllegalArgumentException("Id may not be null"); - } - registeredSpecs.remove(id.toLowerCase(Locale.ENGLISH)); - } - - /** - * Gets the {@link CookieSpec cookie specification} with the given ID. - * - * @param name the {@link CookieSpec cookie specification} identifier - * @param params the {@link HttpParams HTTP parameters} for the cookie - * specification. - * - * @return {@link CookieSpec cookie specification} - * - * @throws IllegalStateException if a policy with the given name cannot be found - */ - public synchronized CookieSpec getCookieSpec(final String name, final HttpParams params) - throws IllegalStateException { - - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - CookieSpecFactory factory = registeredSpecs.get(name.toLowerCase(Locale.ENGLISH)); - if (factory != null) { - return factory.newInstance(params); - } else { - throw new IllegalStateException("Unsupported cookie spec: " + name); - } - } - - /** - * Gets the {@link CookieSpec cookie specification} with the given name. - * - * @param name the {@link CookieSpec cookie specification} identifier - * - * @return {@link CookieSpec cookie specification} - * - * @throws IllegalStateException if a policy with the given name cannot be found - */ - public synchronized CookieSpec getCookieSpec(final String name) - throws IllegalStateException { - return getCookieSpec(name, null); - } - - /** - * Obtains a list containing names of all registered {@link CookieSpec cookie - * specs} in their default order. - * - * Note that the DEFAULT policy (if present) is likely to be the same - * as one of the other policies, but does not have to be. - * - * @return list of registered cookie spec names - */ - public synchronized List getSpecNames(){ - return new ArrayList(registeredSpecs.keySet()); - } - - /** - * Populates the internal collection of registered {@link CookieSpec cookie - * specs} with the content of the map passed as a parameter. - * - * @param map cookie specs - */ - public synchronized void setItems(final Map map) { - if (map == null) { - return; - } - registeredSpecs.clear(); - registeredSpecs.putAll(map); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/old/CookieSpecRegistry.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/old/CookieSpecRegistry.java deleted file mode 100755 index bc56882..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/old/CookieSpecRegistry.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.cookie; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.http.params.HttpParams; - -/** - * Cookie specification registry that can be used to obtain the corresponding - * cookie specification implementation for a given type of type or version of - * cookie. - * - * @author Oleg Kalnichevski - * @author Mike Bowler - * - * @since 4.0 - */ -public final class CookieSpecRegistry { - - private final Map registeredSpecs; - - public CookieSpecRegistry() { - super(); - this.registeredSpecs = new LinkedHashMap(); - } - - /** - * Registers a {@link CookieSpecFactory} with the given identifier. - * If a specification with the given name already exists it will be overridden. - * This nameis the same one used to retrieve the {@link CookieSpecFactory} - * from {@link #getCookieSpec(String)}. - * - * @param name the identifier for this specification - * @param factory the {@link CookieSpecFactory} class to register - * - * @see #getCookieSpec(String) - */ - public synchronized void register(final String name, final CookieSpecFactory factory) { - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - if (factory == null) { - throw new IllegalArgumentException("Cookie spec factory may not be null"); - } - registeredSpecs.put(name.toLowerCase(), factory); - } - - /** - * Unregisters the {@link CookieSpecFactory} with the given ID. - * - * @param id the identifier of the {@link CookieSpec cookie specification} to unregister - */ - public synchronized void unregister(final String id) { - if (id == null) { - throw new IllegalArgumentException("Id may not be null"); - } - registeredSpecs.remove(id.toLowerCase()); - } - - /** - * Gets the {@link CookieSpec cookie specification} with the given ID. - * - * @param name the {@link CookieSpec cookie specification} identifier - * @param params the {@link HttpParams HTTP parameters} for the cookie - * specification. - * - * @return {@link CookieSpec cookie specification} - * - * @throws IllegalStateException if a policy with the given name cannot be found - */ - public synchronized CookieSpec getCookieSpec(final String name, final HttpParams params) - throws IllegalStateException { - - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - CookieSpecFactory factory = registeredSpecs.get(name.toLowerCase()); - if (factory != null) { - return factory.newInstance(params); - } else { - throw new IllegalStateException("Unsupported cookie spec: " + name); - } - } - - /** - * Gets the {@link CookieSpec cookie specification} with the given name. - * - * @param name the {@link CookieSpec cookie specification} identifier - * - * @return {@link CookieSpec cookie specification} - * - * @throws IllegalStateException if a policy with the given name cannot be found - */ - public synchronized CookieSpec getCookieSpec(final String name) - throws IllegalStateException { - return getCookieSpec(name, null); - } - - /** - * Obtains a list containing names of all registered {@link CookieSpec cookie - * specs} in their default order. - * - * Note that the DEFAULT policy (if present) is likely to be the same - * as one of the other policies, but does not have to be. - * - * @return list of registered cookie spec names - */ - public synchronized List getSpecNames(){ - return new ArrayList(registeredSpecs.keySet()); - } - - /** - * Populates the internal collection of registered {@link CookieSpec cookie - * specs} with the content of the map passed as a parameter. - * - * @param map cookie specs - */ - public synchronized void setItems(final Map map) { - if (map == null) { - return; - } - registeredSpecs.clear(); - registeredSpecs.putAll(map); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/pair.info deleted file mode 100755 index 37978c3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47288/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47288 -comSha:b7b8c7731d36aaa2291f03480716a30b82837f21 -parentComSha:7fd801fcfd89666d2404899a5a9388a3bbb1b18b -BuggyFilePath:module-client/src/main/java/org/apache/http/cookie/CookieSpecRegistry.java -FixedFilePath:module-client/src/main/java/org/apache/http/cookie/CookieSpecRegistry.java -StartLineNum:78 -EndLineNum:78 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/comMsg.txt deleted file mode 100755 index da1470a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -[maven-release-plugin] copy for tag 4.0-alpha4 - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0-alpha4@653242 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/diff.diff deleted file mode 100755 index 6206f48..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java b/module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -index 013f5c2f8..fac825ecf 100644 ---- a/module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -+++ b/module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -@@ -33,0 +34 @@ import java.util.HashMap; -+import java.util.Locale; -@@ -62 +63 @@ public abstract class RFC2617Scheme implements AuthScheme { -- private Map params = null; -+ private Map params; -@@ -133,2 +134 @@ public abstract class RFC2617Scheme implements AuthScheme { -- for (int i = 0; i < elements.length; i++) { -- HeaderElement element = elements[i]; -+ for (HeaderElement element : elements) { -@@ -162 +162 @@ public abstract class RFC2617Scheme implements AuthScheme { -- return this.params.get(name.toLowerCase()); -+ return this.params.get(name.toLowerCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/new/RFC2617Scheme.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/new/RFC2617Scheme.java deleted file mode 100755 index fac825e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/new/RFC2617Scheme.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * $HeadeURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.auth; - -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.FormattedHeader; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.message.BasicHeaderValueParser; -import org.apache.http.message.HeaderValueParser; -import org.apache.http.message.ParserCursor; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.CharArrayBuffer; - -/** - *

- * Abstract authentication scheme class that lays foundation for all - * RFC 2617 compliant authetication schemes and provides capabilities common - * to all authentication schemes defined in RFC 2617. - *

- * - * @author Oleg Kalnichevski -*/ -public abstract class RFC2617Scheme implements AuthScheme { - - /** - * Authentication parameter map. - */ - private Map params; - - /** - * Flag whether authenticating against a proxy. - */ - private boolean proxy; - - /** - * Default constructor for RFC2617 compliant authetication schemes. - */ - public RFC2617Scheme() { - super(); - } - - /** - * Processes the given challenge token. Some authentication schemes - * may involve multiple challenge-response exchanges. Such schemes must be able - * to maintain the state information when dealing with sequential challenges - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - public void processChallenge(final Header header) throws MalformedChallengeException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - String authheader = header.getName(); - if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) { - this.proxy = false; - } else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) { - this.proxy = true; - } else { - throw new MalformedChallengeException("Unexpected header name: " + authheader); - } - - CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int endIndex = pos; - String s = buffer.substring(beginIndex, endIndex); - if (!s.equalsIgnoreCase(getSchemeName())) { - throw new MalformedChallengeException("Invalid scheme identifier: " + s); - } - HeaderValueParser parser = BasicHeaderValueParser.DEFAULT; - ParserCursor cursor = new ParserCursor(pos, buffer.length()); - HeaderElement[] elements = parser.parseElements(buffer, cursor); - if (elements.length == 0) { - throw new MalformedChallengeException("Authentication challenge is empty"); - } - - this.params = new HashMap(elements.length); - for (HeaderElement element : elements) { - this.params.put(element.getName(), element.getValue()); - } - } - - /** - * Returns authentication parameters map. Keys in the map are lower-cased. - * - * @return the map of authentication parameters - */ - protected Map getParameters() { - return this.params; - } - - /** - * Returns authentication parameter with the given name, if available. - * - * @param name The name of the parameter to be returned - * - * @return the parameter with the given name - */ - public String getParameter(final String name) { - if (name == null) { - throw new IllegalArgumentException("Parameter name may not be null"); - } - if (this.params == null) { - return null; - } - return this.params.get(name.toLowerCase(Locale.ENGLISH)); - } - - /** - * Returns authentication realm. The realm may not be null. - * - * @return the authentication realm - */ - public String getRealm() { - return getParameter("realm"); - } - - /** - * Returns true if authenticating against a proxy, false - * otherwise. - * - * @return true if authenticating against a proxy, false - * otherwise - */ - public boolean isProxy() { - return this.proxy; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/old/RFC2617Scheme.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/old/RFC2617Scheme.java deleted file mode 100755 index 013f5c2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/old/RFC2617Scheme.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * $HeadeURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.auth; - -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.FormattedHeader; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AUTH; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.message.BasicHeaderValueParser; -import org.apache.http.message.HeaderValueParser; -import org.apache.http.message.ParserCursor; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.CharArrayBuffer; - -/** - *

- * Abstract authentication scheme class that lays foundation for all - * RFC 2617 compliant authetication schemes and provides capabilities common - * to all authentication schemes defined in RFC 2617. - *

- * - * @author Oleg Kalnichevski -*/ -public abstract class RFC2617Scheme implements AuthScheme { - - /** - * Authentication parameter map. - */ - private Map params = null; - - /** - * Flag whether authenticating against a proxy. - */ - private boolean proxy; - - /** - * Default constructor for RFC2617 compliant authetication schemes. - */ - public RFC2617Scheme() { - super(); - } - - /** - * Processes the given challenge token. Some authentication schemes - * may involve multiple challenge-response exchanges. Such schemes must be able - * to maintain the state information when dealing with sequential challenges - * - * @param header the challenge header - * - * @throws MalformedChallengeException is thrown if the authentication challenge - * is malformed - */ - public void processChallenge(final Header header) throws MalformedChallengeException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - String authheader = header.getName(); - if (authheader.equalsIgnoreCase(AUTH.WWW_AUTH)) { - this.proxy = false; - } else if (authheader.equalsIgnoreCase(AUTH.PROXY_AUTH)) { - this.proxy = true; - } else { - throw new MalformedChallengeException("Unexpected header name: " + authheader); - } - - CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int endIndex = pos; - String s = buffer.substring(beginIndex, endIndex); - if (!s.equalsIgnoreCase(getSchemeName())) { - throw new MalformedChallengeException("Invalid scheme identifier: " + s); - } - HeaderValueParser parser = BasicHeaderValueParser.DEFAULT; - ParserCursor cursor = new ParserCursor(pos, buffer.length()); - HeaderElement[] elements = parser.parseElements(buffer, cursor); - if (elements.length == 0) { - throw new MalformedChallengeException("Authentication challenge is empty"); - } - - this.params = new HashMap(elements.length); - for (int i = 0; i < elements.length; i++) { - HeaderElement element = elements[i]; - this.params.put(element.getName(), element.getValue()); - } - } - - /** - * Returns authentication parameters map. Keys in the map are lower-cased. - * - * @return the map of authentication parameters - */ - protected Map getParameters() { - return this.params; - } - - /** - * Returns authentication parameter with the given name, if available. - * - * @param name The name of the parameter to be returned - * - * @return the parameter with the given name - */ - public String getParameter(final String name) { - if (name == null) { - throw new IllegalArgumentException("Parameter name may not be null"); - } - if (this.params == null) { - return null; - } - return this.params.get(name.toLowerCase()); - } - - /** - * Returns authentication realm. The realm may not be null. - * - * @return the authentication realm - */ - public String getRealm() { - return getParameter("realm"); - } - - /** - * Returns true if authenticating against a proxy, false - * otherwise. - * - * @return true if authenticating against a proxy, false - * otherwise - */ - public boolean isProxy() { - return this.proxy; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/pair.info deleted file mode 100755 index b7239b2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47290/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47290 -comSha:b7b8c7731d36aaa2291f03480716a30b82837f21 -parentComSha:7fd801fcfd89666d2404899a5a9388a3bbb1b18b -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/auth/RFC2617Scheme.java -StartLineNum:162 -EndLineNum:162 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/comMsg.txt deleted file mode 100755 index da1470a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -[maven-release-plugin] copy for tag 4.0-alpha4 - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0-alpha4@653242 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/diff.diff deleted file mode 100755 index 4443925..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/auth/AuthSchemeRegistry.java b/module-client/src/main/java/org/apache/http/auth/AuthSchemeRegistry.java -index 198fd9e14..59ff7ae21 100644 ---- a/module-client/src/main/java/org/apache/http/auth/AuthSchemeRegistry.java -+++ b/module-client/src/main/java/org/apache/http/auth/AuthSchemeRegistry.java -@@ -35,0 +36 @@ import java.util.List; -+import java.util.Locale; -@@ -83 +84 @@ public final class AuthSchemeRegistry { -- registeredSchemes.put(name.toLowerCase(), factory); -+ registeredSchemes.put(name.toLowerCase(Locale.ENGLISH), factory); -@@ -96 +97 @@ public final class AuthSchemeRegistry { -- registeredSchemes.remove(name.toLowerCase()); -+ registeredSchemes.remove(name.toLowerCase(Locale.ENGLISH)); -@@ -116 +117 @@ public final class AuthSchemeRegistry { -- AuthSchemeFactory factory = registeredSchemes.get(name.toLowerCase()); -+ AuthSchemeFactory factory = registeredSchemes.get(name.toLowerCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/new/AuthSchemeRegistry.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/new/AuthSchemeRegistry.java deleted file mode 100755 index 59ff7ae..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/new/AuthSchemeRegistry.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.auth; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.params.HttpParams; - -/** - * Authentication scheme registry that can be used to obtain the corresponding - * authentication scheme implementation for a given type of authorization challenge. - * - * @author Oleg Kalnichevski - * - * - * @version $Revision$ - * @since 4.0 - */ -public final class AuthSchemeRegistry { - - private final Map registeredSchemes; - - public AuthSchemeRegistry() { - super(); - this.registeredSchemes = new LinkedHashMap(); - } - - /** - * Registers a {@link AuthSchemeFactory} with the given identifier. If a factory with the - * given name already exists it will be overridden. This name is the same one used to - * retrieve the {@link AuthScheme authentication scheme} from {@link #getAuthScheme}. - * - *

- * Please note that custom authentication preferences, if used, need to be updated accordingly - * for the new {@link AuthScheme authentication scheme} to take effect. - *

- * - * @param name the identifier for this scheme - * @param factory the {@link AuthSchemeFactory} class to register - * - * @see #getAuthScheme - */ - public synchronized void register( - final String name, - final AuthSchemeFactory factory) { - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - if (factory == null) { - throw new IllegalArgumentException("Authentication scheme factory may not be null"); - } - registeredSchemes.put(name.toLowerCase(Locale.ENGLISH), factory); - } - - /** - * Unregisters the class implementing an {@link AuthScheme authentication scheme} with - * the given name. - * - * @param name the identifier of the class to unregister - */ - public synchronized void unregister(final String name) { - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - registeredSchemes.remove(name.toLowerCase(Locale.ENGLISH)); - } - - /** - * Gets the {@link AuthScheme authentication scheme} with the given name. - * - * @param name the {@link AuthScheme authentication scheme} identifier - * @param params the {@link HttpParams HTTP parameters} for the authentication - * scheme. - * - * @return {@link AuthScheme authentication scheme} - * - * @throws IllegalStateException if a scheme with the given name cannot be found - */ - public synchronized AuthScheme getAuthScheme(final String name, final HttpParams params) - throws IllegalStateException { - - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - AuthSchemeFactory factory = registeredSchemes.get(name.toLowerCase(Locale.ENGLISH)); - if (factory != null) { - return factory.newInstance(params); - } else { - throw new IllegalStateException("Unsupported authentication scheme: " + name); - } - } - - /** - * Obtains a list containing names of all registered {@link AuthScheme authentication - * schemes} in their default order. - * - * @return list of registered scheme names - */ - public synchronized List getSchemeNames() { - return new ArrayList(registeredSchemes.keySet()); - } - - /** - * Populates the internal collection of registered {@link AuthScheme authentication schemes} - * with the content of the map passed as a parameter. - * - * @param map authentication schemes - */ - public synchronized void setItems(final Map map) { - if (map == null) { - return; - } - registeredSchemes.clear(); - registeredSchemes.putAll(map); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/old/AuthSchemeRegistry.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/old/AuthSchemeRegistry.java deleted file mode 100755 index 198fd9e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/old/AuthSchemeRegistry.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.auth; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.http.params.HttpParams; - -/** - * Authentication scheme registry that can be used to obtain the corresponding - * authentication scheme implementation for a given type of authorization challenge. - * - * @author Oleg Kalnichevski - * - * - * @version $Revision$ - * @since 4.0 - */ -public final class AuthSchemeRegistry { - - private final Map registeredSchemes; - - public AuthSchemeRegistry() { - super(); - this.registeredSchemes = new LinkedHashMap(); - } - - /** - * Registers a {@link AuthSchemeFactory} with the given identifier. If a factory with the - * given name already exists it will be overridden. This name is the same one used to - * retrieve the {@link AuthScheme authentication scheme} from {@link #getAuthScheme}. - * - *

- * Please note that custom authentication preferences, if used, need to be updated accordingly - * for the new {@link AuthScheme authentication scheme} to take effect. - *

- * - * @param name the identifier for this scheme - * @param factory the {@link AuthSchemeFactory} class to register - * - * @see #getAuthScheme - */ - public synchronized void register( - final String name, - final AuthSchemeFactory factory) { - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - if (factory == null) { - throw new IllegalArgumentException("Authentication scheme factory may not be null"); - } - registeredSchemes.put(name.toLowerCase(), factory); - } - - /** - * Unregisters the class implementing an {@link AuthScheme authentication scheme} with - * the given name. - * - * @param name the identifier of the class to unregister - */ - public synchronized void unregister(final String name) { - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - registeredSchemes.remove(name.toLowerCase()); - } - - /** - * Gets the {@link AuthScheme authentication scheme} with the given name. - * - * @param name the {@link AuthScheme authentication scheme} identifier - * @param params the {@link HttpParams HTTP parameters} for the authentication - * scheme. - * - * @return {@link AuthScheme authentication scheme} - * - * @throws IllegalStateException if a scheme with the given name cannot be found - */ - public synchronized AuthScheme getAuthScheme(final String name, final HttpParams params) - throws IllegalStateException { - - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - AuthSchemeFactory factory = registeredSchemes.get(name.toLowerCase()); - if (factory != null) { - return factory.newInstance(params); - } else { - throw new IllegalStateException("Unsupported authentication scheme: " + name); - } - } - - /** - * Obtains a list containing names of all registered {@link AuthScheme authentication - * schemes} in their default order. - * - * @return list of registered scheme names - */ - public synchronized List getSchemeNames() { - return new ArrayList(registeredSchemes.keySet()); - } - - /** - * Populates the internal collection of registered {@link AuthScheme authentication schemes} - * with the content of the map passed as a parameter. - * - * @param map authentication schemes - */ - public synchronized void setItems(final Map map) { - if (map == null) { - return; - } - registeredSchemes.clear(); - registeredSchemes.putAll(map); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/pair.info deleted file mode 100755 index 1bb53c4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47298/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47298 -comSha:b7b8c7731d36aaa2291f03480716a30b82837f21 -parentComSha:7fd801fcfd89666d2404899a5a9388a3bbb1b18b -BuggyFilePath:module-client/src/main/java/org/apache/http/auth/AuthSchemeRegistry.java -FixedFilePath:module-client/src/main/java/org/apache/http/auth/AuthSchemeRegistry.java -StartLineNum:96 -EndLineNum:96 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/comMsg.txt deleted file mode 100755 index da1470a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -[maven-release-plugin] copy for tag 4.0-alpha4 - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0-alpha4@653242 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/diff.diff deleted file mode 100755 index 5606c98..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java b/module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -index 6980a91de..376cc064e 100644 ---- a/module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -+++ b/module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -@@ -35,0 +36 @@ import java.util.HashMap; -+import java.util.Locale; -@@ -200 +201 @@ public class BasicClientCookie implements SetCookie, ClientCookie { -- cookieDomain = domain.toLowerCase(); -+ cookieDomain = domain.toLowerCase(Locale.ENGLISH); -@@ -365 +366 @@ public class BasicClientCookie implements SetCookie, ClientCookie { -- private int cookieVersion = 0; -+ private int cookieVersion; \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/new/BasicClientCookie.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/new/BasicClientCookie.java deleted file mode 100755 index 376cc06..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/new/BasicClientCookie.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.SetCookie; - -/** - * HTTP "magic-cookie" represents a piece of state information - * that the HTTP agent and the target server can exchange to maintain - * a session. - * - * @author B.C. Holmes - * @author Park, Sung-Gu - * @author Doug Sale - * @author Rod Waldhoff - * @author dIon Gillard - * @author Sean C. Sullivan - * @author John Evans - * @author Marc A. Saegesser - * @author Oleg Kalnichevski - * @author Mike Bowler - * - * @version $Revision$ - */ -public class BasicClientCookie implements SetCookie, ClientCookie { - - /** - * Default Constructor taking a name and a value. The value may be null. - * - * @param name The name. - * @param value The value. - */ - public BasicClientCookie(final String name, final String value) { - super(); - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - this.name = name; - this.attribs = new HashMap(); - this.value = value; - } - - /** - * Returns the name. - * - * @return String name The name - */ - public String getName() { - return this.name; - } - - /** - * Returns the value. - * - * @return String value The current value. - */ - public String getValue() { - return this.value; - } - - /** - * Sets the value - * - * @param value - */ - public void setValue(final String value) { - this.value = value; - } - - /** - * Returns the comment describing the purpose of this cookie, or - * null if no such comment has been defined. - * - * @return comment - * - * @see #setComment(String) - */ - public String getComment() { - return cookieComment; - } - - /** - * If a user agent (web browser) presents this cookie to a user, the - * cookie's purpose will be described using this comment. - * - * @param comment - * - * @see #getComment() - */ - public void setComment(String comment) { - cookieComment = comment; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public String getCommentURL() { - return null; - } - - - /** - * Returns the expiration {@link Date} of the cookie, or null - * if none exists. - *

Note: the object returned by this method is - * considered immutable. Changing it (e.g. using setTime()) could result - * in undefined behaviour. Do so at your peril.

- * @return Expiration {@link Date}, or null. - * - * @see #setExpiryDate(java.util.Date) - * - */ - public Date getExpiryDate() { - return cookieExpiryDate; - } - - /** - * Sets expiration date. - *

Note: the object returned by this method is considered - * immutable. Changing it (e.g. using setTime()) could result in undefined - * behaviour. Do so at your peril.

- * - * @param expiryDate the {@link Date} after which this cookie is no longer valid. - * - * @see #getExpiryDate - * - */ - public void setExpiryDate (Date expiryDate) { - cookieExpiryDate = expiryDate; - } - - - /** - * Returns false if the cookie should be discarded at the end - * of the "session"; true otherwise. - * - * @return false if the cookie should be discarded at the end - * of the "session"; true otherwise - */ - public boolean isPersistent() { - return (null != cookieExpiryDate); - } - - - /** - * Returns domain attribute of the cookie. - * - * @return the value of the domain attribute - * - * @see #setDomain(java.lang.String) - */ - public String getDomain() { - return cookieDomain; - } - - /** - * Sets the domain attribute. - * - * @param domain The value of the domain attribute - * - * @see #getDomain - */ - public void setDomain(String domain) { - if (domain != null) { - cookieDomain = domain.toLowerCase(Locale.ENGLISH); - } else { - cookieDomain = null; - } - } - - - /** - * Returns the path attribute of the cookie - * - * @return The value of the path attribute. - * - * @see #setPath(java.lang.String) - */ - public String getPath() { - return cookiePath; - } - - /** - * Sets the path attribute. - * - * @param path The value of the path attribute - * - * @see #getPath - * - */ - public void setPath(String path) { - cookiePath = path; - } - - /** - * @return true if this cookie should only be sent over secure connections. - * @see #setSecure(boolean) - */ - public boolean isSecure() { - return isSecure; - } - - /** - * Sets the secure attribute of the cookie. - *

- * When true the cookie should only be sent - * using a secure protocol (https). This should only be set when - * the cookie's originating server used a secure protocol to set the - * cookie's value. - * - * @param secure The value of the secure attribute - * - * @see #isSecure() - */ - public void setSecure (boolean secure) { - isSecure = secure; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public int[] getPorts() { - return null; - } - - - /** - * Returns the version of the cookie specification to which this - * cookie conforms. - * - * @return the version of the cookie. - * - * @see #setVersion(int) - * - */ - public int getVersion() { - return cookieVersion; - } - - /** - * Sets the version of the cookie specification to which this - * cookie conforms. - * - * @param version the version of the cookie. - * - * @see #getVersion - */ - public void setVersion(int version) { - cookieVersion = version; - } - - /** - * Returns true if this cookie has expired. - * @param date Current time - * - * @return true if the cookie has expired. - */ - public boolean isExpired(final Date date) { - if (date == null) { - throw new IllegalArgumentException("Date may not be null"); - } - return (cookieExpiryDate != null - && cookieExpiryDate.getTime() <= date.getTime()); - } - - public void setAttribute(final String name, final String value) { - this.attribs.put(name, value); - } - - public String getAttribute(final String name) { - return this.attribs.get(name); - } - - public boolean containsAttribute(final String name) { - return this.attribs.get(name) != null; - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append("[version: "); - buffer.append(Integer.toString(this.cookieVersion)); - buffer.append("]"); - buffer.append("[name: "); - buffer.append(this.name); - buffer.append("]"); - buffer.append("[value: "); - buffer.append(this.value); - buffer.append("]"); - buffer.append("[domain: "); - buffer.append(this.cookieDomain); - buffer.append("]"); - buffer.append("[path: "); - buffer.append(this.cookiePath); - buffer.append("]"); - buffer.append("[expiry: "); - buffer.append(this.cookieExpiryDate); - buffer.append("]"); - return buffer.toString(); - } - - // ----------------------------------------------------- Instance Variables - - /** Cookie name */ - private final String name; - - /** Cookie attributes as specified by the origin server */ - private final Map attribs; - - /** Cookie value */ - private String value; - - /** Comment attribute. */ - private String cookieComment; - - /** Domain attribute. */ - private String cookieDomain; - - /** Expiration {@link Date}. */ - private Date cookieExpiryDate; - - /** Path attribute. */ - private String cookiePath; - - /** My secure flag. */ - private boolean isSecure; - - /** The version of the cookie specification I was created from. */ - private int cookieVersion; - -} - diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/old/BasicClientCookie.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/old/BasicClientCookie.java deleted file mode 100755 index 6980a91..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/old/BasicClientCookie.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.SetCookie; - -/** - * HTTP "magic-cookie" represents a piece of state information - * that the HTTP agent and the target server can exchange to maintain - * a session. - * - * @author B.C. Holmes - * @author Park, Sung-Gu - * @author Doug Sale - * @author Rod Waldhoff - * @author dIon Gillard - * @author Sean C. Sullivan - * @author John Evans - * @author Marc A. Saegesser - * @author Oleg Kalnichevski - * @author Mike Bowler - * - * @version $Revision$ - */ -public class BasicClientCookie implements SetCookie, ClientCookie { - - /** - * Default Constructor taking a name and a value. The value may be null. - * - * @param name The name. - * @param value The value. - */ - public BasicClientCookie(final String name, final String value) { - super(); - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - this.name = name; - this.attribs = new HashMap(); - this.value = value; - } - - /** - * Returns the name. - * - * @return String name The name - */ - public String getName() { - return this.name; - } - - /** - * Returns the value. - * - * @return String value The current value. - */ - public String getValue() { - return this.value; - } - - /** - * Sets the value - * - * @param value - */ - public void setValue(final String value) { - this.value = value; - } - - /** - * Returns the comment describing the purpose of this cookie, or - * null if no such comment has been defined. - * - * @return comment - * - * @see #setComment(String) - */ - public String getComment() { - return cookieComment; - } - - /** - * If a user agent (web browser) presents this cookie to a user, the - * cookie's purpose will be described using this comment. - * - * @param comment - * - * @see #getComment() - */ - public void setComment(String comment) { - cookieComment = comment; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public String getCommentURL() { - return null; - } - - - /** - * Returns the expiration {@link Date} of the cookie, or null - * if none exists. - *

Note: the object returned by this method is - * considered immutable. Changing it (e.g. using setTime()) could result - * in undefined behaviour. Do so at your peril.

- * @return Expiration {@link Date}, or null. - * - * @see #setExpiryDate(java.util.Date) - * - */ - public Date getExpiryDate() { - return cookieExpiryDate; - } - - /** - * Sets expiration date. - *

Note: the object returned by this method is considered - * immutable. Changing it (e.g. using setTime()) could result in undefined - * behaviour. Do so at your peril.

- * - * @param expiryDate the {@link Date} after which this cookie is no longer valid. - * - * @see #getExpiryDate - * - */ - public void setExpiryDate (Date expiryDate) { - cookieExpiryDate = expiryDate; - } - - - /** - * Returns false if the cookie should be discarded at the end - * of the "session"; true otherwise. - * - * @return false if the cookie should be discarded at the end - * of the "session"; true otherwise - */ - public boolean isPersistent() { - return (null != cookieExpiryDate); - } - - - /** - * Returns domain attribute of the cookie. - * - * @return the value of the domain attribute - * - * @see #setDomain(java.lang.String) - */ - public String getDomain() { - return cookieDomain; - } - - /** - * Sets the domain attribute. - * - * @param domain The value of the domain attribute - * - * @see #getDomain - */ - public void setDomain(String domain) { - if (domain != null) { - cookieDomain = domain.toLowerCase(); - } else { - cookieDomain = null; - } - } - - - /** - * Returns the path attribute of the cookie - * - * @return The value of the path attribute. - * - * @see #setPath(java.lang.String) - */ - public String getPath() { - return cookiePath; - } - - /** - * Sets the path attribute. - * - * @param path The value of the path attribute - * - * @see #getPath - * - */ - public void setPath(String path) { - cookiePath = path; - } - - /** - * @return true if this cookie should only be sent over secure connections. - * @see #setSecure(boolean) - */ - public boolean isSecure() { - return isSecure; - } - - /** - * Sets the secure attribute of the cookie. - *

- * When true the cookie should only be sent - * using a secure protocol (https). This should only be set when - * the cookie's originating server used a secure protocol to set the - * cookie's value. - * - * @param secure The value of the secure attribute - * - * @see #isSecure() - */ - public void setSecure (boolean secure) { - isSecure = secure; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public int[] getPorts() { - return null; - } - - - /** - * Returns the version of the cookie specification to which this - * cookie conforms. - * - * @return the version of the cookie. - * - * @see #setVersion(int) - * - */ - public int getVersion() { - return cookieVersion; - } - - /** - * Sets the version of the cookie specification to which this - * cookie conforms. - * - * @param version the version of the cookie. - * - * @see #getVersion - */ - public void setVersion(int version) { - cookieVersion = version; - } - - /** - * Returns true if this cookie has expired. - * @param date Current time - * - * @return true if the cookie has expired. - */ - public boolean isExpired(final Date date) { - if (date == null) { - throw new IllegalArgumentException("Date may not be null"); - } - return (cookieExpiryDate != null - && cookieExpiryDate.getTime() <= date.getTime()); - } - - public void setAttribute(final String name, final String value) { - this.attribs.put(name, value); - } - - public String getAttribute(final String name) { - return this.attribs.get(name); - } - - public boolean containsAttribute(final String name) { - return this.attribs.get(name) != null; - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append("[version: "); - buffer.append(Integer.toString(this.cookieVersion)); - buffer.append("]"); - buffer.append("[name: "); - buffer.append(this.name); - buffer.append("]"); - buffer.append("[value: "); - buffer.append(this.value); - buffer.append("]"); - buffer.append("[domain: "); - buffer.append(this.cookieDomain); - buffer.append("]"); - buffer.append("[path: "); - buffer.append(this.cookiePath); - buffer.append("]"); - buffer.append("[expiry: "); - buffer.append(this.cookieExpiryDate); - buffer.append("]"); - return buffer.toString(); - } - - // ----------------------------------------------------- Instance Variables - - /** Cookie name */ - private final String name; - - /** Cookie attributes as specified by the origin server */ - private final Map attribs; - - /** Cookie value */ - private String value; - - /** Comment attribute. */ - private String cookieComment; - - /** Domain attribute. */ - private String cookieDomain; - - /** Expiration {@link Date}. */ - private Date cookieExpiryDate; - - /** Path attribute. */ - private String cookiePath; - - /** My secure flag. */ - private boolean isSecure; - - /** The version of the cookie specification I was created from. */ - private int cookieVersion = 0; - -} - diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/pair.info deleted file mode 100755 index 110c5e9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47300/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47300 -comSha:b7b8c7731d36aaa2291f03480716a30b82837f21 -parentComSha:7fd801fcfd89666d2404899a5a9388a3bbb1b18b -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -StartLineNum:200 -EndLineNum:200 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/diff.diff deleted file mode 100755 index 9822c4e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/cookie/CookieSpecBase.java b/module-client/src/main/java/org/apache/http/impl/cookie/CookieSpecBase.java -index 91f64665c..35e53a0c8 100644 ---- a/module-client/src/main/java/org/apache/http/impl/cookie/CookieSpecBase.java -+++ b/module-client/src/main/java/org/apache/http/impl/cookie/CookieSpecBase.java -@@ -35,0 +36 @@ import java.util.List; -+import java.util.Locale; -@@ -90 +91 @@ public abstract class CookieSpecBase extends AbstractCookieSpec { -- String s = attrib.getName().toLowerCase(); -+ String s = attrib.getName().toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/new/CookieSpecBase.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/new/CookieSpecBase.java deleted file mode 100755 index 35e53a0..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/new/CookieSpecBase.java +++ /dev/null @@ -1,133 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.http.HeaderElement; -import org.apache.http.NameValuePair; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; - -/** - * Cookie management functions shared by all specification. - * - * @author Oleg Kalnichevski - * - * @since 4.0 - */ -public abstract class CookieSpecBase extends AbstractCookieSpec { - - protected static String getDefaultPath(final CookieOrigin origin) { - String defaultPath = origin.getPath(); - int lastSlashIndex = defaultPath.lastIndexOf('/'); - if (lastSlashIndex >= 0) { - if (lastSlashIndex == 0) { - //Do not remove the very first slash - lastSlashIndex = 1; - } - defaultPath = defaultPath.substring(0, lastSlashIndex); - } - return defaultPath; - } - - protected static String getDefaultDomain(final CookieOrigin origin) { - return origin.getHost(); - } - - protected List parse(final HeaderElement[] elems, final CookieOrigin origin) - throws MalformedCookieException { - List cookies = new ArrayList(elems.length); - for (int i = 0; i < elems.length; i++) { - HeaderElement headerelement = elems[i]; - - String name = headerelement.getName(); - String value = headerelement.getValue(); - if (name == null || name.equals("")) { - throw new MalformedCookieException("Cookie name may not be empty"); - } - - BasicClientCookie cookie = new BasicClientCookie(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - - // cycle through the parameters - NameValuePair[] attribs = headerelement.getParameters(); - for (int j = attribs.length - 1; j >= 0; j--) { - NameValuePair attrib = attribs[j]; - String s = attrib.getName().toLowerCase(Locale.ENGLISH); - - cookie.setAttribute(s, attrib.getValue()); - - CookieAttributeHandler handler = findAttribHandler(s); - if (handler != null) { - handler.parse(cookie, attrib.getValue()); - } - } - cookies.add(cookie); - } - return cookies; - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - for (CookieAttributeHandler handler: getAttribHandlers()) { - handler.validate(cookie, origin); - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - for (CookieAttributeHandler handler: getAttribHandlers()) { - if (!handler.match(cookie, origin)) { - return false; - } - } - return true; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/old/CookieSpecBase.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/old/CookieSpecBase.java deleted file mode 100755 index 91f6466..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/old/CookieSpecBase.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.HeaderElement; -import org.apache.http.NameValuePair; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieAttributeHandler; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; - -/** - * Cookie management functions shared by all specification. - * - * @author Oleg Kalnichevski - * - * @since 4.0 - */ -public abstract class CookieSpecBase extends AbstractCookieSpec { - - protected static String getDefaultPath(final CookieOrigin origin) { - String defaultPath = origin.getPath(); - int lastSlashIndex = defaultPath.lastIndexOf('/'); - if (lastSlashIndex >= 0) { - if (lastSlashIndex == 0) { - //Do not remove the very first slash - lastSlashIndex = 1; - } - defaultPath = defaultPath.substring(0, lastSlashIndex); - } - return defaultPath; - } - - protected static String getDefaultDomain(final CookieOrigin origin) { - return origin.getHost(); - } - - protected List parse(final HeaderElement[] elems, final CookieOrigin origin) - throws MalformedCookieException { - List cookies = new ArrayList(elems.length); - for (int i = 0; i < elems.length; i++) { - HeaderElement headerelement = elems[i]; - - String name = headerelement.getName(); - String value = headerelement.getValue(); - if (name == null || name.equals("")) { - throw new MalformedCookieException("Cookie name may not be empty"); - } - - BasicClientCookie cookie = new BasicClientCookie(name, value); - cookie.setPath(getDefaultPath(origin)); - cookie.setDomain(getDefaultDomain(origin)); - - // cycle through the parameters - NameValuePair[] attribs = headerelement.getParameters(); - for (int j = attribs.length - 1; j >= 0; j--) { - NameValuePair attrib = attribs[j]; - String s = attrib.getName().toLowerCase(); - - cookie.setAttribute(s, attrib.getValue()); - - CookieAttributeHandler handler = findAttribHandler(s); - if (handler != null) { - handler.parse(cookie, attrib.getValue()); - } - } - cookies.add(cookie); - } - return cookies; - } - - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - for (CookieAttributeHandler handler: getAttribHandlers()) { - handler.validate(cookie, origin); - } - } - - public boolean match(final Cookie cookie, final CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - for (CookieAttributeHandler handler: getAttribHandlers()) { - if (!handler.match(cookie, origin)) { - return false; - } - } - return true; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/pair.info deleted file mode 100755 index f1ccf2c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47302/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47302 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/cookie/CookieSpecBase.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/cookie/CookieSpecBase.java -StartLineNum:90 -EndLineNum:90 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/comMsg.txt deleted file mode 100755 index da1470a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -[maven-release-plugin] copy for tag 4.0-alpha4 - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0-alpha4@653242 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/diff.diff deleted file mode 100755 index 370b8ed..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/conn/scheme/Scheme.java b/module-client/src/main/java/org/apache/http/conn/scheme/Scheme.java -index ee854b768..f352fa4f6 100644 ---- a/module-client/src/main/java/org/apache/http/conn/scheme/Scheme.java -+++ b/module-client/src/main/java/org/apache/http/conn/scheme/Scheme.java -@@ -32,0 +33,2 @@ package org.apache.http.conn.scheme; -+import java.util.Locale; -+ -@@ -102 +104 @@ public final class Scheme { -- this.name = name.toLowerCase(); -+ this.name = name.toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/new/Scheme.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/new/Scheme.java deleted file mode 100755 index f352fa4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/new/Scheme.java +++ /dev/null @@ -1,223 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn.scheme; - -import java.util.Locale; - -import org.apache.http.util.LangUtils; - -/** - * Encapsulates specifics of a protocol scheme such as "http" or "https". - * Schemes are identified by lowercase names. - * Supported schemes are typically collected in a - * {@link SchemeRegistry SchemeRegistry}. - * - *

- * For example, to configure support for "https://" URLs, - * you could write code like the following: - *

- *
- * Scheme https = new Scheme("https", new MySecureSocketFactory(), 443);
- * SchemeRegistry.DEFAULT.register(https);
- * 
- * - * @author Roland Weber - * @author Michael Becke - * @author Jeff Dever - * @author Mike Bowler - */ -public final class Scheme { - - /** The name of this scheme, in lowercase. (e.g. http, https) */ - private final String name; - - /** The socket factory for this scheme */ - private final SocketFactory socketFactory; - - /** The default port for this scheme */ - private final int defaultPort; - - /** Indicates whether this scheme allows for layered connections */ - private final boolean layered; - - - /** A string representation, for {@link #toString toString}. */ - private String stringRep; - - - /** - * Creates a new scheme. - * Whether the created scheme allows for layered connections - * depends on the class of factory. - * - * @param name the scheme name, for example "http". - * The name will be converted to lowercase. - * @param factory the factory for creating sockets for communication - * with this scheme - * @param port the default port for this scheme - */ - public Scheme(final String name, - final SocketFactory factory, - final int port) { - - if (name == null) { - throw new IllegalArgumentException - ("Scheme name may not be null"); - } - if (factory == null) { - throw new IllegalArgumentException - ("Socket factory may not be null"); - } - if ((port <= 0) || (port > 0xffff)) { - throw new IllegalArgumentException - ("Port is invalid: " + port); - } - - this.name = name.toLowerCase(Locale.ENGLISH); - this.socketFactory = factory; - this.defaultPort = port; - this.layered = (factory instanceof LayeredSocketFactory); - } - - - /** - * Obtains the default port. - * - * @return the default port for this scheme - */ - public final int getDefaultPort() { - return defaultPort; - } - - - /** - * Obtains the socket factory. - * If this scheme is {@link #isLayered layered}, the factory implements - * {@link LayeredSocketFactory LayeredSocketFactory}. - * - * @return the socket factory for this scheme - */ - public final SocketFactory getSocketFactory() { - return socketFactory; - } - - - /** - * Obtains the scheme name. - * - * @return the name of this scheme, in lowercase - */ - public final String getName() { - return name; - } - - - /** - * Indicates whether this scheme allows for layered connections. - * - * @return true if layered connections are possible, - * false otherwise - */ - public final boolean isLayered() { - return layered; - } - - - /** - * Resolves the correct port for this scheme. - * Returns the given port if it is valid, the default port otherwise. - * - * @param port the port to be resolved, - * a negative number to obtain the default port - * - * @return the given port or the defaultPort - */ - public final int resolvePort(int port) { - return ((port <= 0) || (port > 0xffff)) ? defaultPort : port; - } - - - /** - * Return a string representation of this object. - * - * @return a human-readable string description of this scheme - */ - @Override - public final String toString() { - if (stringRep == null) { - StringBuilder buffer = new StringBuilder(); - buffer.append(this.name); - buffer.append(':'); - buffer.append(Integer.toString(this.defaultPort)); - stringRep = buffer.toString(); - } - return stringRep; - } - - - /** - * Compares this scheme to an object. - * - * @param obj the object to compare with - * - * @return true iff the argument is equal to this scheme - */ - @Override - public final boolean equals(Object obj) { - if (obj == null) return false; - if (this == obj) return true; - if (!(obj instanceof Scheme)) return false; - - Scheme s = (Scheme) obj; - return (name.equals(s.name) && - defaultPort == s.defaultPort && - layered == s.layered && - socketFactory.equals(s.socketFactory) - ); - } // equals - - - /** - * Obtains a hash code for this scheme. - * - * @return the hash code - */ - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.defaultPort); - hash = LangUtils.hashCode(hash, this.name); - hash = LangUtils.hashCode(hash, this.layered); - hash = LangUtils.hashCode(hash, this.socketFactory); - return hash; - } - -} // class Scheme diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/old/Scheme.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/old/Scheme.java deleted file mode 100755 index ee854b7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/old/Scheme.java +++ /dev/null @@ -1,221 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.conn.scheme; - -import org.apache.http.util.LangUtils; - -/** - * Encapsulates specifics of a protocol scheme such as "http" or "https". - * Schemes are identified by lowercase names. - * Supported schemes are typically collected in a - * {@link SchemeRegistry SchemeRegistry}. - * - *

- * For example, to configure support for "https://" URLs, - * you could write code like the following: - *

- *
- * Scheme https = new Scheme("https", new MySecureSocketFactory(), 443);
- * SchemeRegistry.DEFAULT.register(https);
- * 
- * - * @author Roland Weber - * @author Michael Becke - * @author Jeff Dever - * @author Mike Bowler - */ -public final class Scheme { - - /** The name of this scheme, in lowercase. (e.g. http, https) */ - private final String name; - - /** The socket factory for this scheme */ - private final SocketFactory socketFactory; - - /** The default port for this scheme */ - private final int defaultPort; - - /** Indicates whether this scheme allows for layered connections */ - private final boolean layered; - - - /** A string representation, for {@link #toString toString}. */ - private String stringRep; - - - /** - * Creates a new scheme. - * Whether the created scheme allows for layered connections - * depends on the class of factory. - * - * @param name the scheme name, for example "http". - * The name will be converted to lowercase. - * @param factory the factory for creating sockets for communication - * with this scheme - * @param port the default port for this scheme - */ - public Scheme(final String name, - final SocketFactory factory, - final int port) { - - if (name == null) { - throw new IllegalArgumentException - ("Scheme name may not be null"); - } - if (factory == null) { - throw new IllegalArgumentException - ("Socket factory may not be null"); - } - if ((port <= 0) || (port > 0xffff)) { - throw new IllegalArgumentException - ("Port is invalid: " + port); - } - - this.name = name.toLowerCase(); - this.socketFactory = factory; - this.defaultPort = port; - this.layered = (factory instanceof LayeredSocketFactory); - } - - - /** - * Obtains the default port. - * - * @return the default port for this scheme - */ - public final int getDefaultPort() { - return defaultPort; - } - - - /** - * Obtains the socket factory. - * If this scheme is {@link #isLayered layered}, the factory implements - * {@link LayeredSocketFactory LayeredSocketFactory}. - * - * @return the socket factory for this scheme - */ - public final SocketFactory getSocketFactory() { - return socketFactory; - } - - - /** - * Obtains the scheme name. - * - * @return the name of this scheme, in lowercase - */ - public final String getName() { - return name; - } - - - /** - * Indicates whether this scheme allows for layered connections. - * - * @return true if layered connections are possible, - * false otherwise - */ - public final boolean isLayered() { - return layered; - } - - - /** - * Resolves the correct port for this scheme. - * Returns the given port if it is valid, the default port otherwise. - * - * @param port the port to be resolved, - * a negative number to obtain the default port - * - * @return the given port or the defaultPort - */ - public final int resolvePort(int port) { - return ((port <= 0) || (port > 0xffff)) ? defaultPort : port; - } - - - /** - * Return a string representation of this object. - * - * @return a human-readable string description of this scheme - */ - @Override - public final String toString() { - if (stringRep == null) { - StringBuilder buffer = new StringBuilder(); - buffer.append(this.name); - buffer.append(':'); - buffer.append(Integer.toString(this.defaultPort)); - stringRep = buffer.toString(); - } - return stringRep; - } - - - /** - * Compares this scheme to an object. - * - * @param obj the object to compare with - * - * @return true iff the argument is equal to this scheme - */ - @Override - public final boolean equals(Object obj) { - if (obj == null) return false; - if (this == obj) return true; - if (!(obj instanceof Scheme)) return false; - - Scheme s = (Scheme) obj; - return (name.equals(s.name) && - defaultPort == s.defaultPort && - layered == s.layered && - socketFactory.equals(s.socketFactory) - ); - } // equals - - - /** - * Obtains a hash code for this scheme. - * - * @return the hash code - */ - @Override - public int hashCode() { - int hash = LangUtils.HASH_SEED; - hash = LangUtils.hashCode(hash, this.defaultPort); - hash = LangUtils.hashCode(hash, this.name); - hash = LangUtils.hashCode(hash, this.layered); - hash = LangUtils.hashCode(hash, this.socketFactory); - return hash; - } - -} // class Scheme diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/pair.info deleted file mode 100755 index 3f35b28..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47307/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47307 -comSha:b7b8c7731d36aaa2291f03480716a30b82837f21 -parentComSha:7fd801fcfd89666d2404899a5a9388a3bbb1b18b -BuggyFilePath:module-client/src/main/java/org/apache/http/conn/scheme/Scheme.java -FixedFilePath:module-client/src/main/java/org/apache/http/conn/scheme/Scheme.java -StartLineNum:102 -EndLineNum:102 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/diff.diff deleted file mode 100755 index cd5f6f8..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java b/module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -index 7e731307c..ced6db164 100644 ---- a/module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -+++ b/module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -@@ -37,0 +38 @@ import java.net.URISyntaxException; -+import java.util.Locale; -@@ -945 +946 @@ public class DefaultClientRequestDirector -- Header challenge = challenges.get(id.toLowerCase()); -+ Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/new/DefaultClientRequestDirector.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/new/DefaultClientRequestDirector.java deleted file mode 100755 index ced6db1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/new/DefaultClientRequestDirector.java +++ /dev/null @@ -1,1002 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolException; -import org.apache.http.ProtocolVersion; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.client.AuthState; -import org.apache.http.client.AuthenticationHandler; -import org.apache.http.client.ClientRequestDirector; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.RedirectException; -import org.apache.http.client.RedirectHandler; -import org.apache.http.client.methods.AbortableHttpRequest; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.HttpClientParams; -import org.apache.http.client.protocol.ClientContext; -import org.apache.http.client.utils.URIUtils; -import org.apache.http.conn.BasicManagedEntity; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.ClientConnectionRequest; -import org.apache.http.conn.ManagedClientConnection; -import org.apache.http.conn.routing.BasicRouteDirector; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.HttpRouteDirector; -import org.apache.http.conn.routing.HttpRoutePlanner; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.message.BasicHttpRequest; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.ExecutionContext; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.protocol.HttpProcessor; -import org.apache.http.protocol.HttpRequestExecutor; - -/** - * Default implementation of a client-side request director. - *
- * This class replaces the HttpMethodDirector in HttpClient 3. - * - * @author Roland Weber - * @author Oleg Kalnichevski - * - * - * @version $Revision$ - * - * @since 4.0 - */ -public class DefaultClientRequestDirector - implements ClientRequestDirector { - - private static final Log LOG = LogFactory.getLog(DefaultClientRequestDirector.class); - - /** The connection manager. */ - protected final ClientConnectionManager connManager; - - /** The route planner. */ - protected final HttpRoutePlanner routePlanner; - - /** The connection re-use strategy. */ - protected final ConnectionReuseStrategy reuseStrategy; - - /** The request executor. */ - protected final HttpRequestExecutor requestExec; - - /** The HTTP protocol processor. */ - protected final HttpProcessor httpProcessor; - - /** The request retry handler. */ - protected final HttpRequestRetryHandler retryHandler; - - /** The redirect handler. */ - protected final RedirectHandler redirectHandler; - - /** The target authentication handler. */ - private final AuthenticationHandler targetAuthHandler; - - /** The proxy authentication handler. */ - private final AuthenticationHandler proxyAuthHandler; - - /** The HTTP parameters. */ - protected final HttpParams params; - - /** The currently allocated connection. */ - protected ManagedClientConnection managedConn; - - private int redirectCount; - - private int maxRedirects; - - private final AuthState targetAuthState; - - private final AuthState proxyAuthState; - - public DefaultClientRequestDirector( - final ClientConnectionManager conman, - final ConnectionReuseStrategy reustrat, - final HttpRoutePlanner rouplan, - final HttpProcessor httpProcessor, - final HttpRequestRetryHandler retryHandler, - final RedirectHandler redirectHandler, - final AuthenticationHandler targetAuthHandler, - final AuthenticationHandler proxyAuthHandler, - final HttpParams params) { - - if (conman == null) { - throw new IllegalArgumentException - ("Client connection manager may not be null."); - } - if (reustrat == null) { - throw new IllegalArgumentException - ("Connection reuse strategy may not be null."); - } - if (rouplan == null) { - throw new IllegalArgumentException - ("Route planner may not be null."); - } - if (httpProcessor == null) { - throw new IllegalArgumentException - ("HTTP protocol processor may not be null."); - } - if (retryHandler == null) { - throw new IllegalArgumentException - ("HTTP request retry handler may not be null."); - } - if (redirectHandler == null) { - throw new IllegalArgumentException - ("Redirect handler may not be null."); - } - if (targetAuthHandler == null) { - throw new IllegalArgumentException - ("Target authentication handler may not be null."); - } - if (proxyAuthHandler == null) { - throw new IllegalArgumentException - ("Proxy authentication handler may not be null."); - } - if (params == null) { - throw new IllegalArgumentException - ("HTTP parameters may not be null"); - } - this.connManager = conman; - this.reuseStrategy = reustrat; - this.routePlanner = rouplan; - this.httpProcessor = httpProcessor; - this.retryHandler = retryHandler; - this.redirectHandler = redirectHandler; - this.targetAuthHandler = targetAuthHandler; - this.proxyAuthHandler = proxyAuthHandler; - this.params = params; - this.requestExec = new HttpRequestExecutor(); - - this.managedConn = null; - - this.redirectCount = 0; - this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100); - this.targetAuthState = new AuthState(); - this.proxyAuthState = new AuthState(); - } // constructor - - - private RequestWrapper wrapRequest( - final HttpRequest request) throws ProtocolException { - if (request instanceof HttpEntityEnclosingRequest) { - return new EntityEnclosingRequestWrapper( - (HttpEntityEnclosingRequest) request); - } else { - return new RequestWrapper( - request); - } - } - - - private void rewriteRequestURI( - final RequestWrapper request, - final HttpRoute route) throws ProtocolException { - try { - - URI uri = request.getURI(); - if (route.getProxyHost() != null && !route.isTunnelled()) { - // Make sure the request URI is absolute - if (!uri.isAbsolute()) { - HttpHost target = route.getTargetHost(); - uri = URIUtils.rewriteURI(uri, target); - request.setURI(uri); - } - } else { - // Make sure the request URI is relative - if (uri.isAbsolute()) { - uri = URIUtils.rewriteURI(uri, null); - request.setURI(uri); - } - } - - } catch (URISyntaxException ex) { - throw new ProtocolException("Invalid URI: " + - request.getRequestLine().getUri(), ex); - } - } - - - // non-javadoc, see interface ClientRequestDirector - public HttpResponse execute(HttpHost target, HttpRequest request, - HttpContext context) - throws HttpException, IOException { - - HttpRequest orig = request; - RequestWrapper origWrapper = wrapRequest(orig); - origWrapper.setParams(params); - HttpRoute origRoute = determineRoute(target, origWrapper, context); - - RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); - - long timeout = HttpClientParams.getConnectionManagerTimeout(params); - - int execCount = 0; - - HttpResponse response = null; - boolean done = false; - try { - while (!done) { - // In this loop, the RoutedRequest may be replaced by a - // followup request and route. The request and route passed - // in the method arguments will be replaced. The original - // request is still available in 'orig'. - - RequestWrapper wrapper = roureq.getRequest(); - HttpRoute route = roureq.getRoute(); - - // Allocate connection if needed - if (managedConn == null) { - ClientConnectionRequest connRequest = connManager.requestConnection( - route, null); - if (orig instanceof AbortableHttpRequest) { - ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); - } - - try { - managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); - } catch(InterruptedException interrupted) { - InterruptedIOException iox = new InterruptedIOException(); - iox.initCause(interrupted); - throw iox; - } - } - - if (orig instanceof AbortableHttpRequest) { - ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); - } - - // Reopen connection if needed - if (!managedConn.isOpen()) { - managedConn.open(route, context, params); - } - - try { - establishRoute(route, context); - } catch (TunnelRefusedException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage()); - } - response = ex.getResponse(); - break; - } - - if (HttpConnectionParams.isStaleCheckingEnabled(params)) { - // validate connection - LOG.debug("Stale connection check"); - if (managedConn.isStale()) { - LOG.debug("Stale connection detected"); - managedConn.close(); - continue; - } - } - - // Re-write request URI if needed - rewriteRequestURI(wrapper, route); - - // Use virtual host if set - target = (HttpHost) wrapper.getParams().getParameter( - ClientPNames.VIRTUAL_HOST); - - if (target == null) { - target = route.getTargetHost(); - } - - HttpHost proxy = route.getProxyHost(); - - // Populate the execution context - context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, - target); - context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, - proxy); - context.setAttribute(ExecutionContext.HTTP_CONNECTION, - managedConn); - context.setAttribute(ClientContext.TARGET_AUTH_STATE, - targetAuthState); - context.setAttribute(ClientContext.PROXY_AUTH_STATE, - proxyAuthState); - requestExec.preProcess(wrapper, httpProcessor, context); - - context.setAttribute(ExecutionContext.HTTP_REQUEST, - wrapper); - - execCount++; - try { - if (LOG.isDebugEnabled()) { - LOG.debug("Attempt " + execCount + " to execute request"); - } - response = requestExec.execute(wrapper, managedConn, context); - - } catch (IOException ex) { - LOG.debug("Closing the connection."); - managedConn.close(); - if (retryHandler.retryRequest(ex, execCount, context)) { - if (LOG.isInfoEnabled()) { - LOG.info("I/O exception ("+ ex.getClass().getName() + - ") caught when processing request: " - + ex.getMessage()); - } - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage(), ex); - } - LOG.info("Retrying request"); - continue; - } - throw ex; - } - - response.setParams(params); - requestExec.postProcess(response, httpProcessor, context); - - RoutedRequest followup = handleResponse(roureq, response, context); - if (followup == null) { - done = true; - } else { - boolean reuse = reuseStrategy.keepAlive(response, context); - if (reuse) { - LOG.debug("Connection kept alive"); - // Make sure the response body is fully consumed, if present - HttpEntity entity = response.getEntity(); - if (entity != null) { - entity.consumeContent(); - } - // entity consumed above is not an auto-release entity, - // need to mark the connection re-usable explicitly - managedConn.markReusable(); - } else { - managedConn.close(); - } - // check if we can use the same connection for the followup - if (!followup.getRoute().equals(roureq.getRoute())) { - // the followup has a different route, release conn - connManager.releaseConnection(managedConn); - managedConn = null; - } - roureq = followup; - } - } // while not done - - // The connection is in or can be brought to a re-usable state. - boolean reuse = reuseStrategy.keepAlive(response, context); - - // check for entity, release connection if possible - if ((response == null) || (response.getEntity() == null) || - !response.getEntity().isStreaming()) { - // connection not needed and (assumed to be) in re-usable state - if (reuse) - managedConn.markReusable(); - connManager.releaseConnection(managedConn); - managedConn = null; - } else { - // install an auto-release entity - HttpEntity entity = response.getEntity(); - entity = new BasicManagedEntity(entity, managedConn, reuse); - response.setEntity(entity); - } - - return response; - - } catch (HttpException ex) { - abortConnection(); - throw ex; - } catch (IOException ex) { - abortConnection(); - throw ex; - } catch (RuntimeException ex) { - abortConnection(); - throw ex; - } - } // execute - - - /** - * Determines the route for a request. - * Called by {@link #execute} - * to determine the route for either the original or a followup request. - * - * @param target the target host for the request. - * Implementations may accept null - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param context the context to use for the execution, - * never null - * - * @return the route the request should take - * - * @throws HttpException in case of a problem - */ - protected HttpRoute determineRoute(HttpHost target, - HttpRequest request, - HttpContext context) - throws HttpException { - - if (target == null) { - target = (HttpHost) request.getParams().getParameter( - ClientPNames.DEFAULT_HOST); - } - if (target == null) { - throw new IllegalStateException - ("Target host must not be null, or set in parameters."); - } - - return this.routePlanner.determineRoute(target, request, context); - } - - - /** - * Establishes the target route. - * - * @param route the route to establish - * @param context the context for the request execution - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected void establishRoute(HttpRoute route, HttpContext context) - throws HttpException, IOException { - - //@@@ how to handle CONNECT requests for tunnelling? - //@@@ refuse to send external CONNECT via director? special handling? - - //@@@ should the request parameters already be used below? - //@@@ probably yes, but they're not linked yet - //@@@ will linking above cause problems with linking in reqExec? - //@@@ probably not, because the parent is replaced - //@@@ just make sure we don't link parameters to themselves - - HttpRouteDirector rowdy = new BasicRouteDirector(); - int step; - do { - HttpRoute fact = managedConn.getRoute(); - step = rowdy.nextStep(route, fact); - - switch (step) { - - case HttpRouteDirector.CONNECT_TARGET: - case HttpRouteDirector.CONNECT_PROXY: - managedConn.open(route, context, this.params); - break; - - case HttpRouteDirector.TUNNEL_TARGET: { - boolean secure = createTunnelToTarget(route, context); - LOG.debug("Tunnel to target created."); - managedConn.tunnelTarget(secure, this.params); - } break; - - case HttpRouteDirector.TUNNEL_PROXY: { - // The most simple example for this case is a proxy chain - // of two proxies, where P1 must be tunnelled to P2. - // route: Source -> P1 -> P2 -> Target (3 hops) - // fact: Source -> P1 -> Target (2 hops) - final int hop = fact.getHopCount()-1; // the hop to establish - boolean secure = createTunnelToProxy(route, hop, context); - LOG.debug("Tunnel to proxy created."); - managedConn.tunnelProxy(route.getHopTarget(hop), - secure, this.params); - } break; - - - case HttpRouteDirector.LAYER_PROTOCOL: - managedConn.layerProtocol(context, this.params); - break; - - case HttpRouteDirector.UNREACHABLE: - throw new IllegalStateException - ("Unable to establish route." + - "\nplanned = " + route + - "\ncurrent = " + fact); - - case HttpRouteDirector.COMPLETE: - // do nothing - break; - - default: - throw new IllegalStateException - ("Unknown step indicator "+step+" from RouteDirector."); - } // switch - - } while (step > HttpRouteDirector.COMPLETE); - - } // establishConnection - - - /** - * Creates a tunnel to the target server. - * The connection must be established to the (last) proxy. - * A CONNECT request for tunnelling through the proxy will - * be created and sent, the response received and checked. - * This method does not update the connection with - * information about the tunnel, that is left to the caller. - * - * @param route the route to establish - * @param context the context for request execution - * - * @return true if the tunnelled route is secure, - * false otherwise. - * The implementation here always returns false, - * but derived classes may override. - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected boolean createTunnelToTarget(HttpRoute route, - HttpContext context) - throws HttpException, IOException { - - HttpHost proxy = route.getProxyHost(); - HttpHost target = route.getTargetHost(); - HttpResponse response = null; - - boolean done = false; - while (!done) { - - done = true; - - if (!this.managedConn.isOpen()) { - this.managedConn.open(route, context, this.params); - } - - HttpRequest connect = createConnectRequest(route, context); - - String agent = HttpProtocolParams.getUserAgent(params); - if (agent != null) { - connect.addHeader(HTTP.USER_AGENT, agent); - } - connect.addHeader(HTTP.TARGET_HOST, target.toHostString()); - - AuthScheme authScheme = this.proxyAuthState.getAuthScheme(); - AuthScope authScope = this.proxyAuthState.getAuthScope(); - Credentials creds = this.proxyAuthState.getCredentials(); - if (creds != null) { - if (authScope != null || !authScheme.isConnectionBased()) { - try { - connect.addHeader(authScheme.authenticate(creds, connect)); - } catch (AuthenticationException ex) { - if (LOG.isErrorEnabled()) { - LOG.error("Proxy authentication error: " + ex.getMessage()); - } - } - } - } - - response = requestExec.execute(connect, this.managedConn, context); - - int status = response.getStatusLine().getStatusCode(); - if (status < 200) { - throw new HttpException("Unexpected response to CONNECT request: " + - response.getStatusLine()); - } - - CredentialsProvider credsProvider = (CredentialsProvider) - context.getAttribute(ClientContext.CREDS_PROVIDER); - - if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { - if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { - - LOG.debug("Proxy requested authentication"); - Map challenges = this.proxyAuthHandler.getChallenges( - response, context); - try { - processChallenges( - challenges, this.proxyAuthState, this.proxyAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - break; - } - } - updateAuthState(this.proxyAuthState, proxy, credsProvider); - - if (this.proxyAuthState.getCredentials() != null) { - done = false; - - // Retry request - if (this.reuseStrategy.keepAlive(response, context)) { - LOG.debug("Connection kept alive"); - // Consume response content - HttpEntity entity = response.getEntity(); - if (entity != null) { - entity.consumeContent(); - } - } else { - this.managedConn.close(); - } - - } - - } else { - // Reset proxy auth scope - this.proxyAuthState.setAuthScope(null); - } - } - } - - int status = response.getStatusLine().getStatusCode(); - - if (status > 299) { - - // Buffer response content - HttpEntity entity = response.getEntity(); - if (entity != null) { - response.setEntity(new BufferedHttpEntity(entity)); - } - - this.managedConn.close(); - throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); - } - - this.managedConn.markReusable(); - - // How to decide on security of the tunnelled connection? - // The socket factory knows only about the segment to the proxy. - // Even if that is secure, the hop to the target may be insecure. - // Leave it to derived classes, consider insecure by default here. - return false; - - } // createTunnelToTarget - - - - /** - * Creates a tunnel to an intermediate proxy. - * This method is not implemented in this class. - * It just throws an exception here. - * - * @param route the route to establish - * @param hop the hop in the route to establish now. - * route.getHopTarget(hop) - * will return the proxy to tunnel to. - * @param context the context for request execution - * - * @return true if the partially tunnelled connection - * is secure, false otherwise. - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected boolean createTunnelToProxy(HttpRoute route, int hop, - HttpContext context) - throws HttpException, IOException { - - // Have a look at createTunnelToTarget and replicate the parts - // you need in a custom derived class. If your proxies don't require - // authentication, it is not too hard. But for the stock version of - // HttpClient, we cannot make such simplifying assumptions and would - // have to include proxy authentication code. The HttpComponents team - // is currently not in a position to support rarely used code of this - // complexity. Feel free to submit patches that refactor the code in - // createTunnelToTarget to facilitate re-use for proxy tunnelling. - - throw new UnsupportedOperationException - ("Proxy chains are not supported."); - } - - - - /** - * Creates the CONNECT request for tunnelling. - * Called by {@link #createTunnelToTarget createTunnelToTarget}. - * - * @param route the route to establish - * @param context the context for request execution - * - * @return the CONNECT request for tunnelling - */ - protected HttpRequest createConnectRequest(HttpRoute route, - HttpContext context) { - // see RFC 2817, section 5.2 and - // INTERNET-DRAFT: Tunneling TCP based protocols through - // Web proxy servers - - HttpHost target = route.getTargetHost(); - - String host = target.getHostName(); - int port = target.getPort(); - if (port < 0) { - Scheme scheme = connManager.getSchemeRegistry(). - getScheme(target.getSchemeName()); - port = scheme.getDefaultPort(); - } - - StringBuilder buffer = new StringBuilder(host.length() + 6); - buffer.append(host); - buffer.append(":"); - buffer.append(Integer.toString(port)); - - String authority = buffer.toString(); - ProtocolVersion ver = HttpProtocolParams.getVersion(params); - HttpRequest req = new BasicHttpRequest - ("CONNECT", authority, ver); - - return req; - } - - - /** - * Analyzes a response to check need for a followup. - * - * @param roureq the request and route. - * @param response the response to analayze - * @param context the context used for the current request execution - * - * @return the followup request and route if there is a followup, or - * null if the response should be returned as is - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected RoutedRequest handleResponse(RoutedRequest roureq, - HttpResponse response, - HttpContext context) - throws HttpException, IOException { - - HttpRoute route = roureq.getRoute(); - HttpHost proxy = route.getProxyHost(); - RequestWrapper request = roureq.getRequest(); - - HttpParams params = request.getParams(); - if (HttpClientParams.isRedirecting(params) && - this.redirectHandler.isRedirectRequested(response, context)) { - - if (redirectCount >= maxRedirects) { - throw new RedirectException("Maximum redirects (" - + maxRedirects + ") exceeded"); - } - redirectCount++; - - URI uri = this.redirectHandler.getLocationURI(response, context); - - HttpHost newTarget = new HttpHost( - uri.getHost(), - uri.getPort(), - uri.getScheme()); - - HttpGet redirect = new HttpGet(uri); - - HttpRequest orig = request.getOriginal(); - redirect.setHeaders(orig.getAllHeaders()); - - RequestWrapper wrapper = new RequestWrapper(redirect); - wrapper.setParams(params); - - HttpRoute newRoute = determineRoute(newTarget, wrapper, context); - RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute); - - if (LOG.isDebugEnabled()) { - LOG.debug("Redirecting to '" + uri + "' via " + newRoute); - } - - return newRequest; - } - - CredentialsProvider credsProvider = (CredentialsProvider) - context.getAttribute(ClientContext.CREDS_PROVIDER); - - if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { - - if (this.targetAuthHandler.isAuthenticationRequested(response, context)) { - - HttpHost target = (HttpHost) - context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); - if (target == null) { - target = route.getTargetHost(); - } - - LOG.debug("Target requested authentication"); - Map challenges = this.targetAuthHandler.getChallenges( - response, context); - try { - processChallenges(challenges, - this.targetAuthState, this.targetAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - return null; - } - } - updateAuthState(this.targetAuthState, target, credsProvider); - - if (this.targetAuthState.getCredentials() != null) { - // Re-try the same request via the same route - return roureq; - } else { - return null; - } - } else { - // Reset target auth scope - this.targetAuthState.setAuthScope(null); - } - - if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { - - LOG.debug("Proxy requested authentication"); - Map challenges = this.proxyAuthHandler.getChallenges( - response, context); - try { - processChallenges(challenges, - this.proxyAuthState, this.proxyAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - return null; - } - } - updateAuthState(this.proxyAuthState, proxy, credsProvider); - - if (this.proxyAuthState.getCredentials() != null) { - // Re-try the same request via the same route - return roureq; - } else { - return null; - } - } else { - // Reset proxy auth scope - this.proxyAuthState.setAuthScope(null); - } - } - return null; - } // handleResponse - - - /** - * Shuts down the connection. - * This method is called from a catch block in - * {@link #execute execute} during exception handling. - * - * @throws IOException in case of an IO problem - */ - private void abortConnection() throws IOException { - ManagedClientConnection mcc = managedConn; - if (mcc != null) { - // we got here as the result of an exception - // no response will be returned, release the connection - managedConn = null; - try { - mcc.abortConnection(); - } catch (IOException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage(), ex); - } - } - // ensure the connection manager properly releases this connection - connManager.releaseConnection(mcc); - } - } // abortConnection - - - private void processChallenges( - final Map challenges, - final AuthState authState, - final AuthenticationHandler authHandler, - final HttpResponse response, - final HttpContext context) - throws MalformedChallengeException, AuthenticationException { - - AuthScheme authScheme = authState.getAuthScheme(); - if (authScheme == null) { - // Authentication not attempted before - authScheme = authHandler.selectScheme(challenges, response, context); - authState.setAuthScheme(authScheme); - } - String id = authScheme.getSchemeName(); - - Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH)); - if (challenge == null) { - throw new AuthenticationException(id + - " authorization challenge expected, but not found"); - } - authScheme.processChallenge(challenge); - LOG.debug("Authorization challenge processed"); - } - - - private void updateAuthState( - final AuthState authState, - final HttpHost host, - final CredentialsProvider credsProvider) { - - if (!authState.isValid()) { - return; - } - - String hostname = host.getHostName(); - int port = host.getPort(); - if (port < 0) { - Scheme scheme = connManager.getSchemeRegistry().getScheme(host); - port = scheme.getDefaultPort(); - } - - AuthScheme authScheme = authState.getAuthScheme(); - AuthScope authScope = new AuthScope( - hostname, - port, - authScheme.getRealm(), - authScheme.getSchemeName()); - - if (LOG.isDebugEnabled()) { - LOG.debug("Authentication scope: " + authScope); - } - Credentials creds = authState.getCredentials(); - if (creds == null) { - creds = credsProvider.getCredentials(authScope); - if (LOG.isDebugEnabled()) { - if (creds != null) { - LOG.debug("Found credentials"); - } else { - LOG.debug("Credentials not found"); - } - } - } else { - if (authScheme.isComplete()) { - LOG.debug("Authentication failed"); - creds = null; - } - } - authState.setAuthScope(authScope); - authState.setCredentials(creds); - } - -} // class DefaultClientRequestDirector diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/old/DefaultClientRequestDirector.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/old/DefaultClientRequestDirector.java deleted file mode 100755 index 7e73130..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/old/DefaultClientRequestDirector.java +++ /dev/null @@ -1,1001 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolException; -import org.apache.http.ProtocolVersion; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.client.AuthState; -import org.apache.http.client.AuthenticationHandler; -import org.apache.http.client.ClientRequestDirector; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.RedirectException; -import org.apache.http.client.RedirectHandler; -import org.apache.http.client.methods.AbortableHttpRequest; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.HttpClientParams; -import org.apache.http.client.protocol.ClientContext; -import org.apache.http.client.utils.URIUtils; -import org.apache.http.conn.BasicManagedEntity; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.ClientConnectionRequest; -import org.apache.http.conn.ManagedClientConnection; -import org.apache.http.conn.routing.BasicRouteDirector; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.HttpRouteDirector; -import org.apache.http.conn.routing.HttpRoutePlanner; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.message.BasicHttpRequest; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.ExecutionContext; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.protocol.HttpProcessor; -import org.apache.http.protocol.HttpRequestExecutor; - -/** - * Default implementation of a client-side request director. - *
- * This class replaces the HttpMethodDirector in HttpClient 3. - * - * @author Roland Weber - * @author Oleg Kalnichevski - * - * - * @version $Revision$ - * - * @since 4.0 - */ -public class DefaultClientRequestDirector - implements ClientRequestDirector { - - private static final Log LOG = LogFactory.getLog(DefaultClientRequestDirector.class); - - /** The connection manager. */ - protected final ClientConnectionManager connManager; - - /** The route planner. */ - protected final HttpRoutePlanner routePlanner; - - /** The connection re-use strategy. */ - protected final ConnectionReuseStrategy reuseStrategy; - - /** The request executor. */ - protected final HttpRequestExecutor requestExec; - - /** The HTTP protocol processor. */ - protected final HttpProcessor httpProcessor; - - /** The request retry handler. */ - protected final HttpRequestRetryHandler retryHandler; - - /** The redirect handler. */ - protected final RedirectHandler redirectHandler; - - /** The target authentication handler. */ - private final AuthenticationHandler targetAuthHandler; - - /** The proxy authentication handler. */ - private final AuthenticationHandler proxyAuthHandler; - - /** The HTTP parameters. */ - protected final HttpParams params; - - /** The currently allocated connection. */ - protected ManagedClientConnection managedConn; - - private int redirectCount; - - private int maxRedirects; - - private final AuthState targetAuthState; - - private final AuthState proxyAuthState; - - public DefaultClientRequestDirector( - final ClientConnectionManager conman, - final ConnectionReuseStrategy reustrat, - final HttpRoutePlanner rouplan, - final HttpProcessor httpProcessor, - final HttpRequestRetryHandler retryHandler, - final RedirectHandler redirectHandler, - final AuthenticationHandler targetAuthHandler, - final AuthenticationHandler proxyAuthHandler, - final HttpParams params) { - - if (conman == null) { - throw new IllegalArgumentException - ("Client connection manager may not be null."); - } - if (reustrat == null) { - throw new IllegalArgumentException - ("Connection reuse strategy may not be null."); - } - if (rouplan == null) { - throw new IllegalArgumentException - ("Route planner may not be null."); - } - if (httpProcessor == null) { - throw new IllegalArgumentException - ("HTTP protocol processor may not be null."); - } - if (retryHandler == null) { - throw new IllegalArgumentException - ("HTTP request retry handler may not be null."); - } - if (redirectHandler == null) { - throw new IllegalArgumentException - ("Redirect handler may not be null."); - } - if (targetAuthHandler == null) { - throw new IllegalArgumentException - ("Target authentication handler may not be null."); - } - if (proxyAuthHandler == null) { - throw new IllegalArgumentException - ("Proxy authentication handler may not be null."); - } - if (params == null) { - throw new IllegalArgumentException - ("HTTP parameters may not be null"); - } - this.connManager = conman; - this.reuseStrategy = reustrat; - this.routePlanner = rouplan; - this.httpProcessor = httpProcessor; - this.retryHandler = retryHandler; - this.redirectHandler = redirectHandler; - this.targetAuthHandler = targetAuthHandler; - this.proxyAuthHandler = proxyAuthHandler; - this.params = params; - this.requestExec = new HttpRequestExecutor(); - - this.managedConn = null; - - this.redirectCount = 0; - this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100); - this.targetAuthState = new AuthState(); - this.proxyAuthState = new AuthState(); - } // constructor - - - private RequestWrapper wrapRequest( - final HttpRequest request) throws ProtocolException { - if (request instanceof HttpEntityEnclosingRequest) { - return new EntityEnclosingRequestWrapper( - (HttpEntityEnclosingRequest) request); - } else { - return new RequestWrapper( - request); - } - } - - - private void rewriteRequestURI( - final RequestWrapper request, - final HttpRoute route) throws ProtocolException { - try { - - URI uri = request.getURI(); - if (route.getProxyHost() != null && !route.isTunnelled()) { - // Make sure the request URI is absolute - if (!uri.isAbsolute()) { - HttpHost target = route.getTargetHost(); - uri = URIUtils.rewriteURI(uri, target); - request.setURI(uri); - } - } else { - // Make sure the request URI is relative - if (uri.isAbsolute()) { - uri = URIUtils.rewriteURI(uri, null); - request.setURI(uri); - } - } - - } catch (URISyntaxException ex) { - throw new ProtocolException("Invalid URI: " + - request.getRequestLine().getUri(), ex); - } - } - - - // non-javadoc, see interface ClientRequestDirector - public HttpResponse execute(HttpHost target, HttpRequest request, - HttpContext context) - throws HttpException, IOException { - - HttpRequest orig = request; - RequestWrapper origWrapper = wrapRequest(orig); - origWrapper.setParams(params); - HttpRoute origRoute = determineRoute(target, origWrapper, context); - - RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); - - long timeout = HttpClientParams.getConnectionManagerTimeout(params); - - int execCount = 0; - - HttpResponse response = null; - boolean done = false; - try { - while (!done) { - // In this loop, the RoutedRequest may be replaced by a - // followup request and route. The request and route passed - // in the method arguments will be replaced. The original - // request is still available in 'orig'. - - RequestWrapper wrapper = roureq.getRequest(); - HttpRoute route = roureq.getRoute(); - - // Allocate connection if needed - if (managedConn == null) { - ClientConnectionRequest connRequest = connManager.requestConnection( - route, null); - if (orig instanceof AbortableHttpRequest) { - ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); - } - - try { - managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); - } catch(InterruptedException interrupted) { - InterruptedIOException iox = new InterruptedIOException(); - iox.initCause(interrupted); - throw iox; - } - } - - if (orig instanceof AbortableHttpRequest) { - ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); - } - - // Reopen connection if needed - if (!managedConn.isOpen()) { - managedConn.open(route, context, params); - } - - try { - establishRoute(route, context); - } catch (TunnelRefusedException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage()); - } - response = ex.getResponse(); - break; - } - - if (HttpConnectionParams.isStaleCheckingEnabled(params)) { - // validate connection - LOG.debug("Stale connection check"); - if (managedConn.isStale()) { - LOG.debug("Stale connection detected"); - managedConn.close(); - continue; - } - } - - // Re-write request URI if needed - rewriteRequestURI(wrapper, route); - - // Use virtual host if set - target = (HttpHost) wrapper.getParams().getParameter( - ClientPNames.VIRTUAL_HOST); - - if (target == null) { - target = route.getTargetHost(); - } - - HttpHost proxy = route.getProxyHost(); - - // Populate the execution context - context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, - target); - context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, - proxy); - context.setAttribute(ExecutionContext.HTTP_CONNECTION, - managedConn); - context.setAttribute(ClientContext.TARGET_AUTH_STATE, - targetAuthState); - context.setAttribute(ClientContext.PROXY_AUTH_STATE, - proxyAuthState); - requestExec.preProcess(wrapper, httpProcessor, context); - - context.setAttribute(ExecutionContext.HTTP_REQUEST, - wrapper); - - execCount++; - try { - if (LOG.isDebugEnabled()) { - LOG.debug("Attempt " + execCount + " to execute request"); - } - response = requestExec.execute(wrapper, managedConn, context); - - } catch (IOException ex) { - LOG.debug("Closing the connection."); - managedConn.close(); - if (retryHandler.retryRequest(ex, execCount, context)) { - if (LOG.isInfoEnabled()) { - LOG.info("I/O exception ("+ ex.getClass().getName() + - ") caught when processing request: " - + ex.getMessage()); - } - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage(), ex); - } - LOG.info("Retrying request"); - continue; - } - throw ex; - } - - response.setParams(params); - requestExec.postProcess(response, httpProcessor, context); - - RoutedRequest followup = handleResponse(roureq, response, context); - if (followup == null) { - done = true; - } else { - boolean reuse = reuseStrategy.keepAlive(response, context); - if (reuse) { - LOG.debug("Connection kept alive"); - // Make sure the response body is fully consumed, if present - HttpEntity entity = response.getEntity(); - if (entity != null) { - entity.consumeContent(); - } - // entity consumed above is not an auto-release entity, - // need to mark the connection re-usable explicitly - managedConn.markReusable(); - } else { - managedConn.close(); - } - // check if we can use the same connection for the followup - if (!followup.getRoute().equals(roureq.getRoute())) { - // the followup has a different route, release conn - connManager.releaseConnection(managedConn); - managedConn = null; - } - roureq = followup; - } - } // while not done - - // The connection is in or can be brought to a re-usable state. - boolean reuse = reuseStrategy.keepAlive(response, context); - - // check for entity, release connection if possible - if ((response == null) || (response.getEntity() == null) || - !response.getEntity().isStreaming()) { - // connection not needed and (assumed to be) in re-usable state - if (reuse) - managedConn.markReusable(); - connManager.releaseConnection(managedConn); - managedConn = null; - } else { - // install an auto-release entity - HttpEntity entity = response.getEntity(); - entity = new BasicManagedEntity(entity, managedConn, reuse); - response.setEntity(entity); - } - - return response; - - } catch (HttpException ex) { - abortConnection(); - throw ex; - } catch (IOException ex) { - abortConnection(); - throw ex; - } catch (RuntimeException ex) { - abortConnection(); - throw ex; - } - } // execute - - - /** - * Determines the route for a request. - * Called by {@link #execute} - * to determine the route for either the original or a followup request. - * - * @param target the target host for the request. - * Implementations may accept null - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param context the context to use for the execution, - * never null - * - * @return the route the request should take - * - * @throws HttpException in case of a problem - */ - protected HttpRoute determineRoute(HttpHost target, - HttpRequest request, - HttpContext context) - throws HttpException { - - if (target == null) { - target = (HttpHost) request.getParams().getParameter( - ClientPNames.DEFAULT_HOST); - } - if (target == null) { - throw new IllegalStateException - ("Target host must not be null, or set in parameters."); - } - - return this.routePlanner.determineRoute(target, request, context); - } - - - /** - * Establishes the target route. - * - * @param route the route to establish - * @param context the context for the request execution - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected void establishRoute(HttpRoute route, HttpContext context) - throws HttpException, IOException { - - //@@@ how to handle CONNECT requests for tunnelling? - //@@@ refuse to send external CONNECT via director? special handling? - - //@@@ should the request parameters already be used below? - //@@@ probably yes, but they're not linked yet - //@@@ will linking above cause problems with linking in reqExec? - //@@@ probably not, because the parent is replaced - //@@@ just make sure we don't link parameters to themselves - - HttpRouteDirector rowdy = new BasicRouteDirector(); - int step; - do { - HttpRoute fact = managedConn.getRoute(); - step = rowdy.nextStep(route, fact); - - switch (step) { - - case HttpRouteDirector.CONNECT_TARGET: - case HttpRouteDirector.CONNECT_PROXY: - managedConn.open(route, context, this.params); - break; - - case HttpRouteDirector.TUNNEL_TARGET: { - boolean secure = createTunnelToTarget(route, context); - LOG.debug("Tunnel to target created."); - managedConn.tunnelTarget(secure, this.params); - } break; - - case HttpRouteDirector.TUNNEL_PROXY: { - // The most simple example for this case is a proxy chain - // of two proxies, where P1 must be tunnelled to P2. - // route: Source -> P1 -> P2 -> Target (3 hops) - // fact: Source -> P1 -> Target (2 hops) - final int hop = fact.getHopCount()-1; // the hop to establish - boolean secure = createTunnelToProxy(route, hop, context); - LOG.debug("Tunnel to proxy created."); - managedConn.tunnelProxy(route.getHopTarget(hop), - secure, this.params); - } break; - - - case HttpRouteDirector.LAYER_PROTOCOL: - managedConn.layerProtocol(context, this.params); - break; - - case HttpRouteDirector.UNREACHABLE: - throw new IllegalStateException - ("Unable to establish route." + - "\nplanned = " + route + - "\ncurrent = " + fact); - - case HttpRouteDirector.COMPLETE: - // do nothing - break; - - default: - throw new IllegalStateException - ("Unknown step indicator "+step+" from RouteDirector."); - } // switch - - } while (step > HttpRouteDirector.COMPLETE); - - } // establishConnection - - - /** - * Creates a tunnel to the target server. - * The connection must be established to the (last) proxy. - * A CONNECT request for tunnelling through the proxy will - * be created and sent, the response received and checked. - * This method does not update the connection with - * information about the tunnel, that is left to the caller. - * - * @param route the route to establish - * @param context the context for request execution - * - * @return true if the tunnelled route is secure, - * false otherwise. - * The implementation here always returns false, - * but derived classes may override. - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected boolean createTunnelToTarget(HttpRoute route, - HttpContext context) - throws HttpException, IOException { - - HttpHost proxy = route.getProxyHost(); - HttpHost target = route.getTargetHost(); - HttpResponse response = null; - - boolean done = false; - while (!done) { - - done = true; - - if (!this.managedConn.isOpen()) { - this.managedConn.open(route, context, this.params); - } - - HttpRequest connect = createConnectRequest(route, context); - - String agent = HttpProtocolParams.getUserAgent(params); - if (agent != null) { - connect.addHeader(HTTP.USER_AGENT, agent); - } - connect.addHeader(HTTP.TARGET_HOST, target.toHostString()); - - AuthScheme authScheme = this.proxyAuthState.getAuthScheme(); - AuthScope authScope = this.proxyAuthState.getAuthScope(); - Credentials creds = this.proxyAuthState.getCredentials(); - if (creds != null) { - if (authScope != null || !authScheme.isConnectionBased()) { - try { - connect.addHeader(authScheme.authenticate(creds, connect)); - } catch (AuthenticationException ex) { - if (LOG.isErrorEnabled()) { - LOG.error("Proxy authentication error: " + ex.getMessage()); - } - } - } - } - - response = requestExec.execute(connect, this.managedConn, context); - - int status = response.getStatusLine().getStatusCode(); - if (status < 200) { - throw new HttpException("Unexpected response to CONNECT request: " + - response.getStatusLine()); - } - - CredentialsProvider credsProvider = (CredentialsProvider) - context.getAttribute(ClientContext.CREDS_PROVIDER); - - if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { - if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { - - LOG.debug("Proxy requested authentication"); - Map challenges = this.proxyAuthHandler.getChallenges( - response, context); - try { - processChallenges( - challenges, this.proxyAuthState, this.proxyAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - break; - } - } - updateAuthState(this.proxyAuthState, proxy, credsProvider); - - if (this.proxyAuthState.getCredentials() != null) { - done = false; - - // Retry request - if (this.reuseStrategy.keepAlive(response, context)) { - LOG.debug("Connection kept alive"); - // Consume response content - HttpEntity entity = response.getEntity(); - if (entity != null) { - entity.consumeContent(); - } - } else { - this.managedConn.close(); - } - - } - - } else { - // Reset proxy auth scope - this.proxyAuthState.setAuthScope(null); - } - } - } - - int status = response.getStatusLine().getStatusCode(); - - if (status > 299) { - - // Buffer response content - HttpEntity entity = response.getEntity(); - if (entity != null) { - response.setEntity(new BufferedHttpEntity(entity)); - } - - this.managedConn.close(); - throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); - } - - this.managedConn.markReusable(); - - // How to decide on security of the tunnelled connection? - // The socket factory knows only about the segment to the proxy. - // Even if that is secure, the hop to the target may be insecure. - // Leave it to derived classes, consider insecure by default here. - return false; - - } // createTunnelToTarget - - - - /** - * Creates a tunnel to an intermediate proxy. - * This method is not implemented in this class. - * It just throws an exception here. - * - * @param route the route to establish - * @param hop the hop in the route to establish now. - * route.getHopTarget(hop) - * will return the proxy to tunnel to. - * @param context the context for request execution - * - * @return true if the partially tunnelled connection - * is secure, false otherwise. - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected boolean createTunnelToProxy(HttpRoute route, int hop, - HttpContext context) - throws HttpException, IOException { - - // Have a look at createTunnelToTarget and replicate the parts - // you need in a custom derived class. If your proxies don't require - // authentication, it is not too hard. But for the stock version of - // HttpClient, we cannot make such simplifying assumptions and would - // have to include proxy authentication code. The HttpComponents team - // is currently not in a position to support rarely used code of this - // complexity. Feel free to submit patches that refactor the code in - // createTunnelToTarget to facilitate re-use for proxy tunnelling. - - throw new UnsupportedOperationException - ("Proxy chains are not supported."); - } - - - - /** - * Creates the CONNECT request for tunnelling. - * Called by {@link #createTunnelToTarget createTunnelToTarget}. - * - * @param route the route to establish - * @param context the context for request execution - * - * @return the CONNECT request for tunnelling - */ - protected HttpRequest createConnectRequest(HttpRoute route, - HttpContext context) { - // see RFC 2817, section 5.2 and - // INTERNET-DRAFT: Tunneling TCP based protocols through - // Web proxy servers - - HttpHost target = route.getTargetHost(); - - String host = target.getHostName(); - int port = target.getPort(); - if (port < 0) { - Scheme scheme = connManager.getSchemeRegistry(). - getScheme(target.getSchemeName()); - port = scheme.getDefaultPort(); - } - - StringBuilder buffer = new StringBuilder(host.length() + 6); - buffer.append(host); - buffer.append(":"); - buffer.append(Integer.toString(port)); - - String authority = buffer.toString(); - ProtocolVersion ver = HttpProtocolParams.getVersion(params); - HttpRequest req = new BasicHttpRequest - ("CONNECT", authority, ver); - - return req; - } - - - /** - * Analyzes a response to check need for a followup. - * - * @param roureq the request and route. - * @param response the response to analayze - * @param context the context used for the current request execution - * - * @return the followup request and route if there is a followup, or - * null if the response should be returned as is - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected RoutedRequest handleResponse(RoutedRequest roureq, - HttpResponse response, - HttpContext context) - throws HttpException, IOException { - - HttpRoute route = roureq.getRoute(); - HttpHost proxy = route.getProxyHost(); - RequestWrapper request = roureq.getRequest(); - - HttpParams params = request.getParams(); - if (HttpClientParams.isRedirecting(params) && - this.redirectHandler.isRedirectRequested(response, context)) { - - if (redirectCount >= maxRedirects) { - throw new RedirectException("Maximum redirects (" - + maxRedirects + ") exceeded"); - } - redirectCount++; - - URI uri = this.redirectHandler.getLocationURI(response, context); - - HttpHost newTarget = new HttpHost( - uri.getHost(), - uri.getPort(), - uri.getScheme()); - - HttpGet redirect = new HttpGet(uri); - - HttpRequest orig = request.getOriginal(); - redirect.setHeaders(orig.getAllHeaders()); - - RequestWrapper wrapper = new RequestWrapper(redirect); - wrapper.setParams(params); - - HttpRoute newRoute = determineRoute(newTarget, wrapper, context); - RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute); - - if (LOG.isDebugEnabled()) { - LOG.debug("Redirecting to '" + uri + "' via " + newRoute); - } - - return newRequest; - } - - CredentialsProvider credsProvider = (CredentialsProvider) - context.getAttribute(ClientContext.CREDS_PROVIDER); - - if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { - - if (this.targetAuthHandler.isAuthenticationRequested(response, context)) { - - HttpHost target = (HttpHost) - context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); - if (target == null) { - target = route.getTargetHost(); - } - - LOG.debug("Target requested authentication"); - Map challenges = this.targetAuthHandler.getChallenges( - response, context); - try { - processChallenges(challenges, - this.targetAuthState, this.targetAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - return null; - } - } - updateAuthState(this.targetAuthState, target, credsProvider); - - if (this.targetAuthState.getCredentials() != null) { - // Re-try the same request via the same route - return roureq; - } else { - return null; - } - } else { - // Reset target auth scope - this.targetAuthState.setAuthScope(null); - } - - if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { - - LOG.debug("Proxy requested authentication"); - Map challenges = this.proxyAuthHandler.getChallenges( - response, context); - try { - processChallenges(challenges, - this.proxyAuthState, this.proxyAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - return null; - } - } - updateAuthState(this.proxyAuthState, proxy, credsProvider); - - if (this.proxyAuthState.getCredentials() != null) { - // Re-try the same request via the same route - return roureq; - } else { - return null; - } - } else { - // Reset proxy auth scope - this.proxyAuthState.setAuthScope(null); - } - } - return null; - } // handleResponse - - - /** - * Shuts down the connection. - * This method is called from a catch block in - * {@link #execute execute} during exception handling. - * - * @throws IOException in case of an IO problem - */ - private void abortConnection() throws IOException { - ManagedClientConnection mcc = managedConn; - if (mcc != null) { - // we got here as the result of an exception - // no response will be returned, release the connection - managedConn = null; - try { - mcc.abortConnection(); - } catch (IOException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage(), ex); - } - } - // ensure the connection manager properly releases this connection - connManager.releaseConnection(mcc); - } - } // abortConnection - - - private void processChallenges( - final Map challenges, - final AuthState authState, - final AuthenticationHandler authHandler, - final HttpResponse response, - final HttpContext context) - throws MalformedChallengeException, AuthenticationException { - - AuthScheme authScheme = authState.getAuthScheme(); - if (authScheme == null) { - // Authentication not attempted before - authScheme = authHandler.selectScheme(challenges, response, context); - authState.setAuthScheme(authScheme); - } - String id = authScheme.getSchemeName(); - - Header challenge = challenges.get(id.toLowerCase()); - if (challenge == null) { - throw new AuthenticationException(id + - " authorization challenge expected, but not found"); - } - authScheme.processChallenge(challenge); - LOG.debug("Authorization challenge processed"); - } - - - private void updateAuthState( - final AuthState authState, - final HttpHost host, - final CredentialsProvider credsProvider) { - - if (!authState.isValid()) { - return; - } - - String hostname = host.getHostName(); - int port = host.getPort(); - if (port < 0) { - Scheme scheme = connManager.getSchemeRegistry().getScheme(host); - port = scheme.getDefaultPort(); - } - - AuthScheme authScheme = authState.getAuthScheme(); - AuthScope authScope = new AuthScope( - hostname, - port, - authScheme.getRealm(), - authScheme.getSchemeName()); - - if (LOG.isDebugEnabled()) { - LOG.debug("Authentication scope: " + authScope); - } - Credentials creds = authState.getCredentials(); - if (creds == null) { - creds = credsProvider.getCredentials(authScope); - if (LOG.isDebugEnabled()) { - if (creds != null) { - LOG.debug("Found credentials"); - } else { - LOG.debug("Credentials not found"); - } - } - } else { - if (authScheme.isComplete()) { - LOG.debug("Authentication failed"); - creds = null; - } - } - authState.setAuthScope(authScope); - authState.setCredentials(creds); - } - -} // class DefaultClientRequestDirector diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/pair.info deleted file mode 100755 index f498607..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47308/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47308 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -StartLineNum:945 -EndLineNum:945 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/diff.diff deleted file mode 100755 index 3d2ece9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java b/module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -index 86e30e46f..d4b472a47 100644 ---- a/module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -+++ b/module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -@@ -35,0 +36 @@ import java.util.List; -+import java.util.Locale; -@@ -112 +113 @@ public class BrowserCompatSpec extends CookieSpecBase { -- int i1 = headervalue.toLowerCase().indexOf("expires="); -+ int i1 = headervalue.toLowerCase(Locale.ENGLISH).indexOf("expires="); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/new/BrowserCompatSpec.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/new/BrowserCompatSpec.java deleted file mode 100755 index d4b472a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/new/BrowserCompatSpec.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BufferedHeader; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.CharArrayBuffer; - -/** - * Cookie specification that strives to closely mimic (mis)behavior of - * common web browser applications such as Microsoft Internet Explorer - * and Mozilla FireFox. - * - * @author Oleg Kalnichevski - * - * @since 4.0 - */ -public class BrowserCompatSpec extends CookieSpecBase { - - /** Valid date patterns used per default */ - private static final String[] DATE_PATTERNS = new String[] { - DateUtils.PATTERN_RFC1123, - DateUtils.PATTERN_RFC1036, - DateUtils.PATTERN_ASCTIME, - "EEE, dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MMM-yyyy HH-mm-ss z", - "EEE, dd MMM yy HH:mm:ss z", - "EEE dd-MMM-yyyy HH:mm:ss z", - "EEE dd MMM yyyy HH:mm:ss z", - "EEE dd-MMM-yyyy HH-mm-ss z", - "EEE dd-MMM-yy HH:mm:ss z", - "EEE dd MMM yy HH:mm:ss z", - "EEE,dd-MMM-yy HH:mm:ss z", - "EEE,dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MM-yyyy HH:mm:ss z", - }; - - private final String[] datepatterns; - - /** Default constructor */ - public BrowserCompatSpec(final String[] datepatterns) { - super(); - if (datepatterns != null) { - this.datepatterns = datepatterns.clone(); - } else { - this.datepatterns = DATE_PATTERNS; - } - registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler()); - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new BasicDomainHandler()); - registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler()); - registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler()); - registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler()); - registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler( - this.datepatterns)); - } - - /** Default constructor */ - public BrowserCompatSpec() { - this(null); - } - - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String headervalue = header.getValue(); - boolean isNetscapeCookie = false; - int i1 = headervalue.toLowerCase(Locale.ENGLISH).indexOf("expires="); - if (i1 != -1) { - i1 += "expires=".length(); - int i2 = headervalue.indexOf(";", i1); - if (i2 == -1) { - i2 = headervalue.length(); - } - try { - DateUtils.parseDate(headervalue.substring(i1, i2), this.datepatterns); - isNetscapeCookie = true; - } catch (DateParseException e) { - // Does not look like a valid expiry date - } - } - HeaderElement[] elems = null; - if (isNetscapeCookie) { - NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT; - CharArrayBuffer buffer; - ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor( - ((FormattedHeader) header).getValuePos(), - buffer.length()); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - elems = new HeaderElement[] { parser.parseHeader(buffer, cursor) }; - } else { - elems = header.getElements(); - } - return parse(elems, origin); - } - - public List
formatCookies(final List cookies) { - if (cookies == null) { - throw new IllegalArgumentException("List of cookies may not be null"); - } - if (cookies.isEmpty()) { - throw new IllegalArgumentException("List of cookies may not be empty"); - } - CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - for (int i = 0; i < cookies.size(); i++) { - Cookie cookie = cookies.get(i); - if (i > 0) { - buffer.append("; "); - } - buffer.append(cookie.getName()); - buffer.append("="); - String s = cookie.getValue(); - if (s != null) { - buffer.append(s); - } - } - List
headers = new ArrayList
(1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - public int getVersion() { - return 0; - } - - public Header getVersionHeader() { - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/old/BrowserCompatSpec.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/old/BrowserCompatSpec.java deleted file mode 100755 index 86e30e4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/old/BrowserCompatSpec.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.ArrayList; -import java.util.List; - -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HeaderElement; -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; -import org.apache.http.cookie.SM; -import org.apache.http.message.BufferedHeader; -import org.apache.http.message.ParserCursor; -import org.apache.http.util.CharArrayBuffer; - -/** - * Cookie specification that strives to closely mimic (mis)behavior of - * common web browser applications such as Microsoft Internet Explorer - * and Mozilla FireFox. - * - * @author Oleg Kalnichevski - * - * @since 4.0 - */ -public class BrowserCompatSpec extends CookieSpecBase { - - /** Valid date patterns used per default */ - private static final String[] DATE_PATTERNS = new String[] { - DateUtils.PATTERN_RFC1123, - DateUtils.PATTERN_RFC1036, - DateUtils.PATTERN_ASCTIME, - "EEE, dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MMM-yyyy HH-mm-ss z", - "EEE, dd MMM yy HH:mm:ss z", - "EEE dd-MMM-yyyy HH:mm:ss z", - "EEE dd MMM yyyy HH:mm:ss z", - "EEE dd-MMM-yyyy HH-mm-ss z", - "EEE dd-MMM-yy HH:mm:ss z", - "EEE dd MMM yy HH:mm:ss z", - "EEE,dd-MMM-yy HH:mm:ss z", - "EEE,dd-MMM-yyyy HH:mm:ss z", - "EEE, dd-MM-yyyy HH:mm:ss z", - }; - - private final String[] datepatterns; - - /** Default constructor */ - public BrowserCompatSpec(final String[] datepatterns) { - super(); - if (datepatterns != null) { - this.datepatterns = datepatterns.clone(); - } else { - this.datepatterns = DATE_PATTERNS; - } - registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler()); - registerAttribHandler(ClientCookie.DOMAIN_ATTR, new BasicDomainHandler()); - registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler()); - registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler()); - registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler()); - registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler( - this.datepatterns)); - } - - /** Default constructor */ - public BrowserCompatSpec() { - this(null); - } - - public List parse(final Header header, final CookieOrigin origin) - throws MalformedCookieException { - if (header == null) { - throw new IllegalArgumentException("Header may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String headervalue = header.getValue(); - boolean isNetscapeCookie = false; - int i1 = headervalue.toLowerCase().indexOf("expires="); - if (i1 != -1) { - i1 += "expires=".length(); - int i2 = headervalue.indexOf(";", i1); - if (i2 == -1) { - i2 = headervalue.length(); - } - try { - DateUtils.parseDate(headervalue.substring(i1, i2), this.datepatterns); - isNetscapeCookie = true; - } catch (DateParseException e) { - // Does not look like a valid expiry date - } - } - HeaderElement[] elems = null; - if (isNetscapeCookie) { - NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT; - CharArrayBuffer buffer; - ParserCursor cursor; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - cursor = new ParserCursor( - ((FormattedHeader) header).getValuePos(), - buffer.length()); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedCookieException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - cursor = new ParserCursor(0, buffer.length()); - } - elems = new HeaderElement[] { parser.parseHeader(buffer, cursor) }; - } else { - elems = header.getElements(); - } - return parse(elems, origin); - } - - public List
formatCookies(final List cookies) { - if (cookies == null) { - throw new IllegalArgumentException("List of cookies may not be null"); - } - if (cookies.isEmpty()) { - throw new IllegalArgumentException("List of cookies may not be empty"); - } - CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size()); - buffer.append(SM.COOKIE); - buffer.append(": "); - for (int i = 0; i < cookies.size(); i++) { - Cookie cookie = cookies.get(i); - if (i > 0) { - buffer.append("; "); - } - buffer.append(cookie.getName()); - buffer.append("="); - String s = cookie.getValue(); - if (s != null) { - buffer.append(s); - } - } - List
headers = new ArrayList
(1); - headers.add(new BufferedHeader(buffer)); - return headers; - } - - public int getVersion() { - return 0; - } - - public Header getVersionHeader() { - return null; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/pair.info deleted file mode 100755 index 44a3687..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47322/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47322 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/cookie/BrowserCompatSpec.java -StartLineNum:112 -EndLineNum:112 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/diff.diff deleted file mode 100755 index 29a9ed5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java b/module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -index 6980a91de..8088d2b61 100644 ---- a/module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -+++ b/module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -@@ -35,0 +36 @@ import java.util.HashMap; -+import java.util.Locale; -@@ -200 +201 @@ public class BasicClientCookie implements SetCookie, ClientCookie { -- cookieDomain = domain.toLowerCase(); -+ cookieDomain = domain.toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/new/BasicClientCookie.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/new/BasicClientCookie.java deleted file mode 100755 index 8088d2b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/new/BasicClientCookie.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Date; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.SetCookie; - -/** - * HTTP "magic-cookie" represents a piece of state information - * that the HTTP agent and the target server can exchange to maintain - * a session. - * - * @author B.C. Holmes - * @author Park, Sung-Gu - * @author Doug Sale - * @author Rod Waldhoff - * @author dIon Gillard - * @author Sean C. Sullivan - * @author John Evans - * @author Marc A. Saegesser - * @author Oleg Kalnichevski - * @author Mike Bowler - * - * @version $Revision$ - */ -public class BasicClientCookie implements SetCookie, ClientCookie { - - /** - * Default Constructor taking a name and a value. The value may be null. - * - * @param name The name. - * @param value The value. - */ - public BasicClientCookie(final String name, final String value) { - super(); - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - this.name = name; - this.attribs = new HashMap(); - this.value = value; - } - - /** - * Returns the name. - * - * @return String name The name - */ - public String getName() { - return this.name; - } - - /** - * Returns the value. - * - * @return String value The current value. - */ - public String getValue() { - return this.value; - } - - /** - * Sets the value - * - * @param value - */ - public void setValue(final String value) { - this.value = value; - } - - /** - * Returns the comment describing the purpose of this cookie, or - * null if no such comment has been defined. - * - * @return comment - * - * @see #setComment(String) - */ - public String getComment() { - return cookieComment; - } - - /** - * If a user agent (web browser) presents this cookie to a user, the - * cookie's purpose will be described using this comment. - * - * @param comment - * - * @see #getComment() - */ - public void setComment(String comment) { - cookieComment = comment; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public String getCommentURL() { - return null; - } - - - /** - * Returns the expiration {@link Date} of the cookie, or null - * if none exists. - *

Note: the object returned by this method is - * considered immutable. Changing it (e.g. using setTime()) could result - * in undefined behaviour. Do so at your peril.

- * @return Expiration {@link Date}, or null. - * - * @see #setExpiryDate(java.util.Date) - * - */ - public Date getExpiryDate() { - return cookieExpiryDate; - } - - /** - * Sets expiration date. - *

Note: the object returned by this method is considered - * immutable. Changing it (e.g. using setTime()) could result in undefined - * behaviour. Do so at your peril.

- * - * @param expiryDate the {@link Date} after which this cookie is no longer valid. - * - * @see #getExpiryDate - * - */ - public void setExpiryDate (Date expiryDate) { - cookieExpiryDate = expiryDate; - } - - - /** - * Returns false if the cookie should be discarded at the end - * of the "session"; true otherwise. - * - * @return false if the cookie should be discarded at the end - * of the "session"; true otherwise - */ - public boolean isPersistent() { - return (null != cookieExpiryDate); - } - - - /** - * Returns domain attribute of the cookie. - * - * @return the value of the domain attribute - * - * @see #setDomain(java.lang.String) - */ - public String getDomain() { - return cookieDomain; - } - - /** - * Sets the domain attribute. - * - * @param domain The value of the domain attribute - * - * @see #getDomain - */ - public void setDomain(String domain) { - if (domain != null) { - cookieDomain = domain.toLowerCase(Locale.ENGLISH); - } else { - cookieDomain = null; - } - } - - - /** - * Returns the path attribute of the cookie - * - * @return The value of the path attribute. - * - * @see #setPath(java.lang.String) - */ - public String getPath() { - return cookiePath; - } - - /** - * Sets the path attribute. - * - * @param path The value of the path attribute - * - * @see #getPath - * - */ - public void setPath(String path) { - cookiePath = path; - } - - /** - * @return true if this cookie should only be sent over secure connections. - * @see #setSecure(boolean) - */ - public boolean isSecure() { - return isSecure; - } - - /** - * Sets the secure attribute of the cookie. - *

- * When true the cookie should only be sent - * using a secure protocol (https). This should only be set when - * the cookie's originating server used a secure protocol to set the - * cookie's value. - * - * @param secure The value of the secure attribute - * - * @see #isSecure() - */ - public void setSecure (boolean secure) { - isSecure = secure; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public int[] getPorts() { - return null; - } - - - /** - * Returns the version of the cookie specification to which this - * cookie conforms. - * - * @return the version of the cookie. - * - * @see #setVersion(int) - * - */ - public int getVersion() { - return cookieVersion; - } - - /** - * Sets the version of the cookie specification to which this - * cookie conforms. - * - * @param version the version of the cookie. - * - * @see #getVersion - */ - public void setVersion(int version) { - cookieVersion = version; - } - - /** - * Returns true if this cookie has expired. - * @param date Current time - * - * @return true if the cookie has expired. - */ - public boolean isExpired(final Date date) { - if (date == null) { - throw new IllegalArgumentException("Date may not be null"); - } - return (cookieExpiryDate != null - && cookieExpiryDate.getTime() <= date.getTime()); - } - - public void setAttribute(final String name, final String value) { - this.attribs.put(name, value); - } - - public String getAttribute(final String name) { - return this.attribs.get(name); - } - - public boolean containsAttribute(final String name) { - return this.attribs.get(name) != null; - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append("[version: "); - buffer.append(Integer.toString(this.cookieVersion)); - buffer.append("]"); - buffer.append("[name: "); - buffer.append(this.name); - buffer.append("]"); - buffer.append("[value: "); - buffer.append(this.value); - buffer.append("]"); - buffer.append("[domain: "); - buffer.append(this.cookieDomain); - buffer.append("]"); - buffer.append("[path: "); - buffer.append(this.cookiePath); - buffer.append("]"); - buffer.append("[expiry: "); - buffer.append(this.cookieExpiryDate); - buffer.append("]"); - return buffer.toString(); - } - - // ----------------------------------------------------- Instance Variables - - /** Cookie name */ - private final String name; - - /** Cookie attributes as specified by the origin server */ - private final Map attribs; - - /** Cookie value */ - private String value; - - /** Comment attribute. */ - private String cookieComment; - - /** Domain attribute. */ - private String cookieDomain; - - /** Expiration {@link Date}. */ - private Date cookieExpiryDate; - - /** Path attribute. */ - private String cookiePath; - - /** My secure flag. */ - private boolean isSecure; - - /** The version of the cookie specification I was created from. */ - private int cookieVersion = 0; - -} - diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/old/BasicClientCookie.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/old/BasicClientCookie.java deleted file mode 100755 index 6980a91..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/old/BasicClientCookie.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.cookie; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.apache.http.cookie.ClientCookie; -import org.apache.http.cookie.SetCookie; - -/** - * HTTP "magic-cookie" represents a piece of state information - * that the HTTP agent and the target server can exchange to maintain - * a session. - * - * @author B.C. Holmes - * @author Park, Sung-Gu - * @author Doug Sale - * @author Rod Waldhoff - * @author dIon Gillard - * @author Sean C. Sullivan - * @author John Evans - * @author Marc A. Saegesser - * @author Oleg Kalnichevski - * @author Mike Bowler - * - * @version $Revision$ - */ -public class BasicClientCookie implements SetCookie, ClientCookie { - - /** - * Default Constructor taking a name and a value. The value may be null. - * - * @param name The name. - * @param value The value. - */ - public BasicClientCookie(final String name, final String value) { - super(); - if (name == null) { - throw new IllegalArgumentException("Name may not be null"); - } - this.name = name; - this.attribs = new HashMap(); - this.value = value; - } - - /** - * Returns the name. - * - * @return String name The name - */ - public String getName() { - return this.name; - } - - /** - * Returns the value. - * - * @return String value The current value. - */ - public String getValue() { - return this.value; - } - - /** - * Sets the value - * - * @param value - */ - public void setValue(final String value) { - this.value = value; - } - - /** - * Returns the comment describing the purpose of this cookie, or - * null if no such comment has been defined. - * - * @return comment - * - * @see #setComment(String) - */ - public String getComment() { - return cookieComment; - } - - /** - * If a user agent (web browser) presents this cookie to a user, the - * cookie's purpose will be described using this comment. - * - * @param comment - * - * @see #getComment() - */ - public void setComment(String comment) { - cookieComment = comment; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public String getCommentURL() { - return null; - } - - - /** - * Returns the expiration {@link Date} of the cookie, or null - * if none exists. - *

Note: the object returned by this method is - * considered immutable. Changing it (e.g. using setTime()) could result - * in undefined behaviour. Do so at your peril.

- * @return Expiration {@link Date}, or null. - * - * @see #setExpiryDate(java.util.Date) - * - */ - public Date getExpiryDate() { - return cookieExpiryDate; - } - - /** - * Sets expiration date. - *

Note: the object returned by this method is considered - * immutable. Changing it (e.g. using setTime()) could result in undefined - * behaviour. Do so at your peril.

- * - * @param expiryDate the {@link Date} after which this cookie is no longer valid. - * - * @see #getExpiryDate - * - */ - public void setExpiryDate (Date expiryDate) { - cookieExpiryDate = expiryDate; - } - - - /** - * Returns false if the cookie should be discarded at the end - * of the "session"; true otherwise. - * - * @return false if the cookie should be discarded at the end - * of the "session"; true otherwise - */ - public boolean isPersistent() { - return (null != cookieExpiryDate); - } - - - /** - * Returns domain attribute of the cookie. - * - * @return the value of the domain attribute - * - * @see #setDomain(java.lang.String) - */ - public String getDomain() { - return cookieDomain; - } - - /** - * Sets the domain attribute. - * - * @param domain The value of the domain attribute - * - * @see #getDomain - */ - public void setDomain(String domain) { - if (domain != null) { - cookieDomain = domain.toLowerCase(); - } else { - cookieDomain = null; - } - } - - - /** - * Returns the path attribute of the cookie - * - * @return The value of the path attribute. - * - * @see #setPath(java.lang.String) - */ - public String getPath() { - return cookiePath; - } - - /** - * Sets the path attribute. - * - * @param path The value of the path attribute - * - * @see #getPath - * - */ - public void setPath(String path) { - cookiePath = path; - } - - /** - * @return true if this cookie should only be sent over secure connections. - * @see #setSecure(boolean) - */ - public boolean isSecure() { - return isSecure; - } - - /** - * Sets the secure attribute of the cookie. - *

- * When true the cookie should only be sent - * using a secure protocol (https). This should only be set when - * the cookie's originating server used a secure protocol to set the - * cookie's value. - * - * @param secure The value of the secure attribute - * - * @see #isSecure() - */ - public void setSecure (boolean secure) { - isSecure = secure; - } - - - /** - * Returns null. Cookies prior to RFC2965 do not set this attribute - */ - public int[] getPorts() { - return null; - } - - - /** - * Returns the version of the cookie specification to which this - * cookie conforms. - * - * @return the version of the cookie. - * - * @see #setVersion(int) - * - */ - public int getVersion() { - return cookieVersion; - } - - /** - * Sets the version of the cookie specification to which this - * cookie conforms. - * - * @param version the version of the cookie. - * - * @see #getVersion - */ - public void setVersion(int version) { - cookieVersion = version; - } - - /** - * Returns true if this cookie has expired. - * @param date Current time - * - * @return true if the cookie has expired. - */ - public boolean isExpired(final Date date) { - if (date == null) { - throw new IllegalArgumentException("Date may not be null"); - } - return (cookieExpiryDate != null - && cookieExpiryDate.getTime() <= date.getTime()); - } - - public void setAttribute(final String name, final String value) { - this.attribs.put(name, value); - } - - public String getAttribute(final String name) { - return this.attribs.get(name); - } - - public boolean containsAttribute(final String name) { - return this.attribs.get(name) != null; - } - - @Override - public String toString() { - StringBuilder buffer = new StringBuilder(); - buffer.append("[version: "); - buffer.append(Integer.toString(this.cookieVersion)); - buffer.append("]"); - buffer.append("[name: "); - buffer.append(this.name); - buffer.append("]"); - buffer.append("[value: "); - buffer.append(this.value); - buffer.append("]"); - buffer.append("[domain: "); - buffer.append(this.cookieDomain); - buffer.append("]"); - buffer.append("[path: "); - buffer.append(this.cookiePath); - buffer.append("]"); - buffer.append("[expiry: "); - buffer.append(this.cookieExpiryDate); - buffer.append("]"); - return buffer.toString(); - } - - // ----------------------------------------------------- Instance Variables - - /** Cookie name */ - private final String name; - - /** Cookie attributes as specified by the origin server */ - private final Map attribs; - - /** Cookie value */ - private String value; - - /** Comment attribute. */ - private String cookieComment; - - /** Domain attribute. */ - private String cookieDomain; - - /** Expiration {@link Date}. */ - private Date cookieExpiryDate; - - /** Path attribute. */ - private String cookiePath; - - /** My secure flag. */ - private boolean isSecure; - - /** The version of the cookie specification I was created from. */ - private int cookieVersion = 0; - -} - diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/pair.info deleted file mode 100755 index 0fffde5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47329/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47329 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/cookie/BasicClientCookie.java -StartLineNum:200 -EndLineNum:200 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/comMsg.txt deleted file mode 100755 index da1470a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -[maven-release-plugin] copy for tag 4.0-alpha4 - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/tags/4.0-alpha4@653242 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/diff.diff deleted file mode 100755 index 7e14777..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java b/module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -index 7e731307c..b70f22e06 100644 ---- a/module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -+++ b/module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -@@ -37,0 +38 @@ import java.net.URISyntaxException; -+import java.util.Locale; -@@ -763 +764 @@ public class DefaultClientRequestDirector -- buffer.append(":"); -+ buffer.append(':'); -@@ -945 +946 @@ public class DefaultClientRequestDirector -- Header challenge = challenges.get(id.toLowerCase()); -+ Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/new/DefaultClientRequestDirector.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/new/DefaultClientRequestDirector.java deleted file mode 100755 index b70f22e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/new/DefaultClientRequestDirector.java +++ /dev/null @@ -1,1002 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolException; -import org.apache.http.ProtocolVersion; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.client.AuthState; -import org.apache.http.client.AuthenticationHandler; -import org.apache.http.client.ClientRequestDirector; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.RedirectException; -import org.apache.http.client.RedirectHandler; -import org.apache.http.client.methods.AbortableHttpRequest; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.HttpClientParams; -import org.apache.http.client.protocol.ClientContext; -import org.apache.http.client.utils.URIUtils; -import org.apache.http.conn.BasicManagedEntity; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.ClientConnectionRequest; -import org.apache.http.conn.ManagedClientConnection; -import org.apache.http.conn.routing.BasicRouteDirector; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.HttpRouteDirector; -import org.apache.http.conn.routing.HttpRoutePlanner; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.message.BasicHttpRequest; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.ExecutionContext; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.protocol.HttpProcessor; -import org.apache.http.protocol.HttpRequestExecutor; - -/** - * Default implementation of a client-side request director. - *
- * This class replaces the HttpMethodDirector in HttpClient 3. - * - * @author Roland Weber - * @author Oleg Kalnichevski - * - * - * @version $Revision$ - * - * @since 4.0 - */ -public class DefaultClientRequestDirector - implements ClientRequestDirector { - - private static final Log LOG = LogFactory.getLog(DefaultClientRequestDirector.class); - - /** The connection manager. */ - protected final ClientConnectionManager connManager; - - /** The route planner. */ - protected final HttpRoutePlanner routePlanner; - - /** The connection re-use strategy. */ - protected final ConnectionReuseStrategy reuseStrategy; - - /** The request executor. */ - protected final HttpRequestExecutor requestExec; - - /** The HTTP protocol processor. */ - protected final HttpProcessor httpProcessor; - - /** The request retry handler. */ - protected final HttpRequestRetryHandler retryHandler; - - /** The redirect handler. */ - protected final RedirectHandler redirectHandler; - - /** The target authentication handler. */ - private final AuthenticationHandler targetAuthHandler; - - /** The proxy authentication handler. */ - private final AuthenticationHandler proxyAuthHandler; - - /** The HTTP parameters. */ - protected final HttpParams params; - - /** The currently allocated connection. */ - protected ManagedClientConnection managedConn; - - private int redirectCount; - - private int maxRedirects; - - private final AuthState targetAuthState; - - private final AuthState proxyAuthState; - - public DefaultClientRequestDirector( - final ClientConnectionManager conman, - final ConnectionReuseStrategy reustrat, - final HttpRoutePlanner rouplan, - final HttpProcessor httpProcessor, - final HttpRequestRetryHandler retryHandler, - final RedirectHandler redirectHandler, - final AuthenticationHandler targetAuthHandler, - final AuthenticationHandler proxyAuthHandler, - final HttpParams params) { - - if (conman == null) { - throw new IllegalArgumentException - ("Client connection manager may not be null."); - } - if (reustrat == null) { - throw new IllegalArgumentException - ("Connection reuse strategy may not be null."); - } - if (rouplan == null) { - throw new IllegalArgumentException - ("Route planner may not be null."); - } - if (httpProcessor == null) { - throw new IllegalArgumentException - ("HTTP protocol processor may not be null."); - } - if (retryHandler == null) { - throw new IllegalArgumentException - ("HTTP request retry handler may not be null."); - } - if (redirectHandler == null) { - throw new IllegalArgumentException - ("Redirect handler may not be null."); - } - if (targetAuthHandler == null) { - throw new IllegalArgumentException - ("Target authentication handler may not be null."); - } - if (proxyAuthHandler == null) { - throw new IllegalArgumentException - ("Proxy authentication handler may not be null."); - } - if (params == null) { - throw new IllegalArgumentException - ("HTTP parameters may not be null"); - } - this.connManager = conman; - this.reuseStrategy = reustrat; - this.routePlanner = rouplan; - this.httpProcessor = httpProcessor; - this.retryHandler = retryHandler; - this.redirectHandler = redirectHandler; - this.targetAuthHandler = targetAuthHandler; - this.proxyAuthHandler = proxyAuthHandler; - this.params = params; - this.requestExec = new HttpRequestExecutor(); - - this.managedConn = null; - - this.redirectCount = 0; - this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100); - this.targetAuthState = new AuthState(); - this.proxyAuthState = new AuthState(); - } // constructor - - - private RequestWrapper wrapRequest( - final HttpRequest request) throws ProtocolException { - if (request instanceof HttpEntityEnclosingRequest) { - return new EntityEnclosingRequestWrapper( - (HttpEntityEnclosingRequest) request); - } else { - return new RequestWrapper( - request); - } - } - - - private void rewriteRequestURI( - final RequestWrapper request, - final HttpRoute route) throws ProtocolException { - try { - - URI uri = request.getURI(); - if (route.getProxyHost() != null && !route.isTunnelled()) { - // Make sure the request URI is absolute - if (!uri.isAbsolute()) { - HttpHost target = route.getTargetHost(); - uri = URIUtils.rewriteURI(uri, target); - request.setURI(uri); - } - } else { - // Make sure the request URI is relative - if (uri.isAbsolute()) { - uri = URIUtils.rewriteURI(uri, null); - request.setURI(uri); - } - } - - } catch (URISyntaxException ex) { - throw new ProtocolException("Invalid URI: " + - request.getRequestLine().getUri(), ex); - } - } - - - // non-javadoc, see interface ClientRequestDirector - public HttpResponse execute(HttpHost target, HttpRequest request, - HttpContext context) - throws HttpException, IOException { - - HttpRequest orig = request; - RequestWrapper origWrapper = wrapRequest(orig); - origWrapper.setParams(params); - HttpRoute origRoute = determineRoute(target, origWrapper, context); - - RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); - - long timeout = HttpClientParams.getConnectionManagerTimeout(params); - - int execCount = 0; - - HttpResponse response = null; - boolean done = false; - try { - while (!done) { - // In this loop, the RoutedRequest may be replaced by a - // followup request and route. The request and route passed - // in the method arguments will be replaced. The original - // request is still available in 'orig'. - - RequestWrapper wrapper = roureq.getRequest(); - HttpRoute route = roureq.getRoute(); - - // Allocate connection if needed - if (managedConn == null) { - ClientConnectionRequest connRequest = connManager.requestConnection( - route, null); - if (orig instanceof AbortableHttpRequest) { - ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); - } - - try { - managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); - } catch(InterruptedException interrupted) { - InterruptedIOException iox = new InterruptedIOException(); - iox.initCause(interrupted); - throw iox; - } - } - - if (orig instanceof AbortableHttpRequest) { - ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); - } - - // Reopen connection if needed - if (!managedConn.isOpen()) { - managedConn.open(route, context, params); - } - - try { - establishRoute(route, context); - } catch (TunnelRefusedException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage()); - } - response = ex.getResponse(); - break; - } - - if (HttpConnectionParams.isStaleCheckingEnabled(params)) { - // validate connection - LOG.debug("Stale connection check"); - if (managedConn.isStale()) { - LOG.debug("Stale connection detected"); - managedConn.close(); - continue; - } - } - - // Re-write request URI if needed - rewriteRequestURI(wrapper, route); - - // Use virtual host if set - target = (HttpHost) wrapper.getParams().getParameter( - ClientPNames.VIRTUAL_HOST); - - if (target == null) { - target = route.getTargetHost(); - } - - HttpHost proxy = route.getProxyHost(); - - // Populate the execution context - context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, - target); - context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, - proxy); - context.setAttribute(ExecutionContext.HTTP_CONNECTION, - managedConn); - context.setAttribute(ClientContext.TARGET_AUTH_STATE, - targetAuthState); - context.setAttribute(ClientContext.PROXY_AUTH_STATE, - proxyAuthState); - requestExec.preProcess(wrapper, httpProcessor, context); - - context.setAttribute(ExecutionContext.HTTP_REQUEST, - wrapper); - - execCount++; - try { - if (LOG.isDebugEnabled()) { - LOG.debug("Attempt " + execCount + " to execute request"); - } - response = requestExec.execute(wrapper, managedConn, context); - - } catch (IOException ex) { - LOG.debug("Closing the connection."); - managedConn.close(); - if (retryHandler.retryRequest(ex, execCount, context)) { - if (LOG.isInfoEnabled()) { - LOG.info("I/O exception ("+ ex.getClass().getName() + - ") caught when processing request: " - + ex.getMessage()); - } - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage(), ex); - } - LOG.info("Retrying request"); - continue; - } - throw ex; - } - - response.setParams(params); - requestExec.postProcess(response, httpProcessor, context); - - RoutedRequest followup = handleResponse(roureq, response, context); - if (followup == null) { - done = true; - } else { - boolean reuse = reuseStrategy.keepAlive(response, context); - if (reuse) { - LOG.debug("Connection kept alive"); - // Make sure the response body is fully consumed, if present - HttpEntity entity = response.getEntity(); - if (entity != null) { - entity.consumeContent(); - } - // entity consumed above is not an auto-release entity, - // need to mark the connection re-usable explicitly - managedConn.markReusable(); - } else { - managedConn.close(); - } - // check if we can use the same connection for the followup - if (!followup.getRoute().equals(roureq.getRoute())) { - // the followup has a different route, release conn - connManager.releaseConnection(managedConn); - managedConn = null; - } - roureq = followup; - } - } // while not done - - // The connection is in or can be brought to a re-usable state. - boolean reuse = reuseStrategy.keepAlive(response, context); - - // check for entity, release connection if possible - if ((response == null) || (response.getEntity() == null) || - !response.getEntity().isStreaming()) { - // connection not needed and (assumed to be) in re-usable state - if (reuse) - managedConn.markReusable(); - connManager.releaseConnection(managedConn); - managedConn = null; - } else { - // install an auto-release entity - HttpEntity entity = response.getEntity(); - entity = new BasicManagedEntity(entity, managedConn, reuse); - response.setEntity(entity); - } - - return response; - - } catch (HttpException ex) { - abortConnection(); - throw ex; - } catch (IOException ex) { - abortConnection(); - throw ex; - } catch (RuntimeException ex) { - abortConnection(); - throw ex; - } - } // execute - - - /** - * Determines the route for a request. - * Called by {@link #execute} - * to determine the route for either the original or a followup request. - * - * @param target the target host for the request. - * Implementations may accept null - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param context the context to use for the execution, - * never null - * - * @return the route the request should take - * - * @throws HttpException in case of a problem - */ - protected HttpRoute determineRoute(HttpHost target, - HttpRequest request, - HttpContext context) - throws HttpException { - - if (target == null) { - target = (HttpHost) request.getParams().getParameter( - ClientPNames.DEFAULT_HOST); - } - if (target == null) { - throw new IllegalStateException - ("Target host must not be null, or set in parameters."); - } - - return this.routePlanner.determineRoute(target, request, context); - } - - - /** - * Establishes the target route. - * - * @param route the route to establish - * @param context the context for the request execution - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected void establishRoute(HttpRoute route, HttpContext context) - throws HttpException, IOException { - - //@@@ how to handle CONNECT requests for tunnelling? - //@@@ refuse to send external CONNECT via director? special handling? - - //@@@ should the request parameters already be used below? - //@@@ probably yes, but they're not linked yet - //@@@ will linking above cause problems with linking in reqExec? - //@@@ probably not, because the parent is replaced - //@@@ just make sure we don't link parameters to themselves - - HttpRouteDirector rowdy = new BasicRouteDirector(); - int step; - do { - HttpRoute fact = managedConn.getRoute(); - step = rowdy.nextStep(route, fact); - - switch (step) { - - case HttpRouteDirector.CONNECT_TARGET: - case HttpRouteDirector.CONNECT_PROXY: - managedConn.open(route, context, this.params); - break; - - case HttpRouteDirector.TUNNEL_TARGET: { - boolean secure = createTunnelToTarget(route, context); - LOG.debug("Tunnel to target created."); - managedConn.tunnelTarget(secure, this.params); - } break; - - case HttpRouteDirector.TUNNEL_PROXY: { - // The most simple example for this case is a proxy chain - // of two proxies, where P1 must be tunnelled to P2. - // route: Source -> P1 -> P2 -> Target (3 hops) - // fact: Source -> P1 -> Target (2 hops) - final int hop = fact.getHopCount()-1; // the hop to establish - boolean secure = createTunnelToProxy(route, hop, context); - LOG.debug("Tunnel to proxy created."); - managedConn.tunnelProxy(route.getHopTarget(hop), - secure, this.params); - } break; - - - case HttpRouteDirector.LAYER_PROTOCOL: - managedConn.layerProtocol(context, this.params); - break; - - case HttpRouteDirector.UNREACHABLE: - throw new IllegalStateException - ("Unable to establish route." + - "\nplanned = " + route + - "\ncurrent = " + fact); - - case HttpRouteDirector.COMPLETE: - // do nothing - break; - - default: - throw new IllegalStateException - ("Unknown step indicator "+step+" from RouteDirector."); - } // switch - - } while (step > HttpRouteDirector.COMPLETE); - - } // establishConnection - - - /** - * Creates a tunnel to the target server. - * The connection must be established to the (last) proxy. - * A CONNECT request for tunnelling through the proxy will - * be created and sent, the response received and checked. - * This method does not update the connection with - * information about the tunnel, that is left to the caller. - * - * @param route the route to establish - * @param context the context for request execution - * - * @return true if the tunnelled route is secure, - * false otherwise. - * The implementation here always returns false, - * but derived classes may override. - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected boolean createTunnelToTarget(HttpRoute route, - HttpContext context) - throws HttpException, IOException { - - HttpHost proxy = route.getProxyHost(); - HttpHost target = route.getTargetHost(); - HttpResponse response = null; - - boolean done = false; - while (!done) { - - done = true; - - if (!this.managedConn.isOpen()) { - this.managedConn.open(route, context, this.params); - } - - HttpRequest connect = createConnectRequest(route, context); - - String agent = HttpProtocolParams.getUserAgent(params); - if (agent != null) { - connect.addHeader(HTTP.USER_AGENT, agent); - } - connect.addHeader(HTTP.TARGET_HOST, target.toHostString()); - - AuthScheme authScheme = this.proxyAuthState.getAuthScheme(); - AuthScope authScope = this.proxyAuthState.getAuthScope(); - Credentials creds = this.proxyAuthState.getCredentials(); - if (creds != null) { - if (authScope != null || !authScheme.isConnectionBased()) { - try { - connect.addHeader(authScheme.authenticate(creds, connect)); - } catch (AuthenticationException ex) { - if (LOG.isErrorEnabled()) { - LOG.error("Proxy authentication error: " + ex.getMessage()); - } - } - } - } - - response = requestExec.execute(connect, this.managedConn, context); - - int status = response.getStatusLine().getStatusCode(); - if (status < 200) { - throw new HttpException("Unexpected response to CONNECT request: " + - response.getStatusLine()); - } - - CredentialsProvider credsProvider = (CredentialsProvider) - context.getAttribute(ClientContext.CREDS_PROVIDER); - - if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { - if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { - - LOG.debug("Proxy requested authentication"); - Map challenges = this.proxyAuthHandler.getChallenges( - response, context); - try { - processChallenges( - challenges, this.proxyAuthState, this.proxyAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - break; - } - } - updateAuthState(this.proxyAuthState, proxy, credsProvider); - - if (this.proxyAuthState.getCredentials() != null) { - done = false; - - // Retry request - if (this.reuseStrategy.keepAlive(response, context)) { - LOG.debug("Connection kept alive"); - // Consume response content - HttpEntity entity = response.getEntity(); - if (entity != null) { - entity.consumeContent(); - } - } else { - this.managedConn.close(); - } - - } - - } else { - // Reset proxy auth scope - this.proxyAuthState.setAuthScope(null); - } - } - } - - int status = response.getStatusLine().getStatusCode(); - - if (status > 299) { - - // Buffer response content - HttpEntity entity = response.getEntity(); - if (entity != null) { - response.setEntity(new BufferedHttpEntity(entity)); - } - - this.managedConn.close(); - throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); - } - - this.managedConn.markReusable(); - - // How to decide on security of the tunnelled connection? - // The socket factory knows only about the segment to the proxy. - // Even if that is secure, the hop to the target may be insecure. - // Leave it to derived classes, consider insecure by default here. - return false; - - } // createTunnelToTarget - - - - /** - * Creates a tunnel to an intermediate proxy. - * This method is not implemented in this class. - * It just throws an exception here. - * - * @param route the route to establish - * @param hop the hop in the route to establish now. - * route.getHopTarget(hop) - * will return the proxy to tunnel to. - * @param context the context for request execution - * - * @return true if the partially tunnelled connection - * is secure, false otherwise. - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected boolean createTunnelToProxy(HttpRoute route, int hop, - HttpContext context) - throws HttpException, IOException { - - // Have a look at createTunnelToTarget and replicate the parts - // you need in a custom derived class. If your proxies don't require - // authentication, it is not too hard. But for the stock version of - // HttpClient, we cannot make such simplifying assumptions and would - // have to include proxy authentication code. The HttpComponents team - // is currently not in a position to support rarely used code of this - // complexity. Feel free to submit patches that refactor the code in - // createTunnelToTarget to facilitate re-use for proxy tunnelling. - - throw new UnsupportedOperationException - ("Proxy chains are not supported."); - } - - - - /** - * Creates the CONNECT request for tunnelling. - * Called by {@link #createTunnelToTarget createTunnelToTarget}. - * - * @param route the route to establish - * @param context the context for request execution - * - * @return the CONNECT request for tunnelling - */ - protected HttpRequest createConnectRequest(HttpRoute route, - HttpContext context) { - // see RFC 2817, section 5.2 and - // INTERNET-DRAFT: Tunneling TCP based protocols through - // Web proxy servers - - HttpHost target = route.getTargetHost(); - - String host = target.getHostName(); - int port = target.getPort(); - if (port < 0) { - Scheme scheme = connManager.getSchemeRegistry(). - getScheme(target.getSchemeName()); - port = scheme.getDefaultPort(); - } - - StringBuilder buffer = new StringBuilder(host.length() + 6); - buffer.append(host); - buffer.append(':'); - buffer.append(Integer.toString(port)); - - String authority = buffer.toString(); - ProtocolVersion ver = HttpProtocolParams.getVersion(params); - HttpRequest req = new BasicHttpRequest - ("CONNECT", authority, ver); - - return req; - } - - - /** - * Analyzes a response to check need for a followup. - * - * @param roureq the request and route. - * @param response the response to analayze - * @param context the context used for the current request execution - * - * @return the followup request and route if there is a followup, or - * null if the response should be returned as is - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected RoutedRequest handleResponse(RoutedRequest roureq, - HttpResponse response, - HttpContext context) - throws HttpException, IOException { - - HttpRoute route = roureq.getRoute(); - HttpHost proxy = route.getProxyHost(); - RequestWrapper request = roureq.getRequest(); - - HttpParams params = request.getParams(); - if (HttpClientParams.isRedirecting(params) && - this.redirectHandler.isRedirectRequested(response, context)) { - - if (redirectCount >= maxRedirects) { - throw new RedirectException("Maximum redirects (" - + maxRedirects + ") exceeded"); - } - redirectCount++; - - URI uri = this.redirectHandler.getLocationURI(response, context); - - HttpHost newTarget = new HttpHost( - uri.getHost(), - uri.getPort(), - uri.getScheme()); - - HttpGet redirect = new HttpGet(uri); - - HttpRequest orig = request.getOriginal(); - redirect.setHeaders(orig.getAllHeaders()); - - RequestWrapper wrapper = new RequestWrapper(redirect); - wrapper.setParams(params); - - HttpRoute newRoute = determineRoute(newTarget, wrapper, context); - RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute); - - if (LOG.isDebugEnabled()) { - LOG.debug("Redirecting to '" + uri + "' via " + newRoute); - } - - return newRequest; - } - - CredentialsProvider credsProvider = (CredentialsProvider) - context.getAttribute(ClientContext.CREDS_PROVIDER); - - if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { - - if (this.targetAuthHandler.isAuthenticationRequested(response, context)) { - - HttpHost target = (HttpHost) - context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); - if (target == null) { - target = route.getTargetHost(); - } - - LOG.debug("Target requested authentication"); - Map challenges = this.targetAuthHandler.getChallenges( - response, context); - try { - processChallenges(challenges, - this.targetAuthState, this.targetAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - return null; - } - } - updateAuthState(this.targetAuthState, target, credsProvider); - - if (this.targetAuthState.getCredentials() != null) { - // Re-try the same request via the same route - return roureq; - } else { - return null; - } - } else { - // Reset target auth scope - this.targetAuthState.setAuthScope(null); - } - - if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { - - LOG.debug("Proxy requested authentication"); - Map challenges = this.proxyAuthHandler.getChallenges( - response, context); - try { - processChallenges(challenges, - this.proxyAuthState, this.proxyAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - return null; - } - } - updateAuthState(this.proxyAuthState, proxy, credsProvider); - - if (this.proxyAuthState.getCredentials() != null) { - // Re-try the same request via the same route - return roureq; - } else { - return null; - } - } else { - // Reset proxy auth scope - this.proxyAuthState.setAuthScope(null); - } - } - return null; - } // handleResponse - - - /** - * Shuts down the connection. - * This method is called from a catch block in - * {@link #execute execute} during exception handling. - * - * @throws IOException in case of an IO problem - */ - private void abortConnection() throws IOException { - ManagedClientConnection mcc = managedConn; - if (mcc != null) { - // we got here as the result of an exception - // no response will be returned, release the connection - managedConn = null; - try { - mcc.abortConnection(); - } catch (IOException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage(), ex); - } - } - // ensure the connection manager properly releases this connection - connManager.releaseConnection(mcc); - } - } // abortConnection - - - private void processChallenges( - final Map challenges, - final AuthState authState, - final AuthenticationHandler authHandler, - final HttpResponse response, - final HttpContext context) - throws MalformedChallengeException, AuthenticationException { - - AuthScheme authScheme = authState.getAuthScheme(); - if (authScheme == null) { - // Authentication not attempted before - authScheme = authHandler.selectScheme(challenges, response, context); - authState.setAuthScheme(authScheme); - } - String id = authScheme.getSchemeName(); - - Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH)); - if (challenge == null) { - throw new AuthenticationException(id + - " authorization challenge expected, but not found"); - } - authScheme.processChallenge(challenge); - LOG.debug("Authorization challenge processed"); - } - - - private void updateAuthState( - final AuthState authState, - final HttpHost host, - final CredentialsProvider credsProvider) { - - if (!authState.isValid()) { - return; - } - - String hostname = host.getHostName(); - int port = host.getPort(); - if (port < 0) { - Scheme scheme = connManager.getSchemeRegistry().getScheme(host); - port = scheme.getDefaultPort(); - } - - AuthScheme authScheme = authState.getAuthScheme(); - AuthScope authScope = new AuthScope( - hostname, - port, - authScheme.getRealm(), - authScheme.getSchemeName()); - - if (LOG.isDebugEnabled()) { - LOG.debug("Authentication scope: " + authScope); - } - Credentials creds = authState.getCredentials(); - if (creds == null) { - creds = credsProvider.getCredentials(authScope); - if (LOG.isDebugEnabled()) { - if (creds != null) { - LOG.debug("Found credentials"); - } else { - LOG.debug("Credentials not found"); - } - } - } else { - if (authScheme.isComplete()) { - LOG.debug("Authentication failed"); - creds = null; - } - } - authState.setAuthScope(authScope); - authState.setCredentials(creds); - } - -} // class DefaultClientRequestDirector diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/old/DefaultClientRequestDirector.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/old/DefaultClientRequestDirector.java deleted file mode 100755 index 7e73130..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/old/DefaultClientRequestDirector.java +++ /dev/null @@ -1,1001 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.io.IOException; -import java.io.InterruptedIOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.ConnectionReuseStrategy; -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpEntityEnclosingRequest; -import org.apache.http.HttpException; -import org.apache.http.HttpHost; -import org.apache.http.HttpRequest; -import org.apache.http.HttpResponse; -import org.apache.http.ProtocolException; -import org.apache.http.ProtocolVersion; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.client.AuthState; -import org.apache.http.client.AuthenticationHandler; -import org.apache.http.client.ClientRequestDirector; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.HttpRequestRetryHandler; -import org.apache.http.client.RedirectException; -import org.apache.http.client.RedirectHandler; -import org.apache.http.client.methods.AbortableHttpRequest; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.HttpClientParams; -import org.apache.http.client.protocol.ClientContext; -import org.apache.http.client.utils.URIUtils; -import org.apache.http.conn.BasicManagedEntity; -import org.apache.http.conn.ClientConnectionManager; -import org.apache.http.conn.ClientConnectionRequest; -import org.apache.http.conn.ManagedClientConnection; -import org.apache.http.conn.routing.BasicRouteDirector; -import org.apache.http.conn.routing.HttpRoute; -import org.apache.http.conn.routing.HttpRouteDirector; -import org.apache.http.conn.routing.HttpRoutePlanner; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.entity.BufferedHttpEntity; -import org.apache.http.message.BasicHttpRequest; -import org.apache.http.params.HttpConnectionParams; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.ExecutionContext; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.protocol.HttpProcessor; -import org.apache.http.protocol.HttpRequestExecutor; - -/** - * Default implementation of a client-side request director. - *
- * This class replaces the HttpMethodDirector in HttpClient 3. - * - * @author Roland Weber - * @author Oleg Kalnichevski - * - * - * @version $Revision$ - * - * @since 4.0 - */ -public class DefaultClientRequestDirector - implements ClientRequestDirector { - - private static final Log LOG = LogFactory.getLog(DefaultClientRequestDirector.class); - - /** The connection manager. */ - protected final ClientConnectionManager connManager; - - /** The route planner. */ - protected final HttpRoutePlanner routePlanner; - - /** The connection re-use strategy. */ - protected final ConnectionReuseStrategy reuseStrategy; - - /** The request executor. */ - protected final HttpRequestExecutor requestExec; - - /** The HTTP protocol processor. */ - protected final HttpProcessor httpProcessor; - - /** The request retry handler. */ - protected final HttpRequestRetryHandler retryHandler; - - /** The redirect handler. */ - protected final RedirectHandler redirectHandler; - - /** The target authentication handler. */ - private final AuthenticationHandler targetAuthHandler; - - /** The proxy authentication handler. */ - private final AuthenticationHandler proxyAuthHandler; - - /** The HTTP parameters. */ - protected final HttpParams params; - - /** The currently allocated connection. */ - protected ManagedClientConnection managedConn; - - private int redirectCount; - - private int maxRedirects; - - private final AuthState targetAuthState; - - private final AuthState proxyAuthState; - - public DefaultClientRequestDirector( - final ClientConnectionManager conman, - final ConnectionReuseStrategy reustrat, - final HttpRoutePlanner rouplan, - final HttpProcessor httpProcessor, - final HttpRequestRetryHandler retryHandler, - final RedirectHandler redirectHandler, - final AuthenticationHandler targetAuthHandler, - final AuthenticationHandler proxyAuthHandler, - final HttpParams params) { - - if (conman == null) { - throw new IllegalArgumentException - ("Client connection manager may not be null."); - } - if (reustrat == null) { - throw new IllegalArgumentException - ("Connection reuse strategy may not be null."); - } - if (rouplan == null) { - throw new IllegalArgumentException - ("Route planner may not be null."); - } - if (httpProcessor == null) { - throw new IllegalArgumentException - ("HTTP protocol processor may not be null."); - } - if (retryHandler == null) { - throw new IllegalArgumentException - ("HTTP request retry handler may not be null."); - } - if (redirectHandler == null) { - throw new IllegalArgumentException - ("Redirect handler may not be null."); - } - if (targetAuthHandler == null) { - throw new IllegalArgumentException - ("Target authentication handler may not be null."); - } - if (proxyAuthHandler == null) { - throw new IllegalArgumentException - ("Proxy authentication handler may not be null."); - } - if (params == null) { - throw new IllegalArgumentException - ("HTTP parameters may not be null"); - } - this.connManager = conman; - this.reuseStrategy = reustrat; - this.routePlanner = rouplan; - this.httpProcessor = httpProcessor; - this.retryHandler = retryHandler; - this.redirectHandler = redirectHandler; - this.targetAuthHandler = targetAuthHandler; - this.proxyAuthHandler = proxyAuthHandler; - this.params = params; - this.requestExec = new HttpRequestExecutor(); - - this.managedConn = null; - - this.redirectCount = 0; - this.maxRedirects = this.params.getIntParameter(ClientPNames.MAX_REDIRECTS, 100); - this.targetAuthState = new AuthState(); - this.proxyAuthState = new AuthState(); - } // constructor - - - private RequestWrapper wrapRequest( - final HttpRequest request) throws ProtocolException { - if (request instanceof HttpEntityEnclosingRequest) { - return new EntityEnclosingRequestWrapper( - (HttpEntityEnclosingRequest) request); - } else { - return new RequestWrapper( - request); - } - } - - - private void rewriteRequestURI( - final RequestWrapper request, - final HttpRoute route) throws ProtocolException { - try { - - URI uri = request.getURI(); - if (route.getProxyHost() != null && !route.isTunnelled()) { - // Make sure the request URI is absolute - if (!uri.isAbsolute()) { - HttpHost target = route.getTargetHost(); - uri = URIUtils.rewriteURI(uri, target); - request.setURI(uri); - } - } else { - // Make sure the request URI is relative - if (uri.isAbsolute()) { - uri = URIUtils.rewriteURI(uri, null); - request.setURI(uri); - } - } - - } catch (URISyntaxException ex) { - throw new ProtocolException("Invalid URI: " + - request.getRequestLine().getUri(), ex); - } - } - - - // non-javadoc, see interface ClientRequestDirector - public HttpResponse execute(HttpHost target, HttpRequest request, - HttpContext context) - throws HttpException, IOException { - - HttpRequest orig = request; - RequestWrapper origWrapper = wrapRequest(orig); - origWrapper.setParams(params); - HttpRoute origRoute = determineRoute(target, origWrapper, context); - - RoutedRequest roureq = new RoutedRequest(origWrapper, origRoute); - - long timeout = HttpClientParams.getConnectionManagerTimeout(params); - - int execCount = 0; - - HttpResponse response = null; - boolean done = false; - try { - while (!done) { - // In this loop, the RoutedRequest may be replaced by a - // followup request and route. The request and route passed - // in the method arguments will be replaced. The original - // request is still available in 'orig'. - - RequestWrapper wrapper = roureq.getRequest(); - HttpRoute route = roureq.getRoute(); - - // Allocate connection if needed - if (managedConn == null) { - ClientConnectionRequest connRequest = connManager.requestConnection( - route, null); - if (orig instanceof AbortableHttpRequest) { - ((AbortableHttpRequest) orig).setConnectionRequest(connRequest); - } - - try { - managedConn = connRequest.getConnection(timeout, TimeUnit.MILLISECONDS); - } catch(InterruptedException interrupted) { - InterruptedIOException iox = new InterruptedIOException(); - iox.initCause(interrupted); - throw iox; - } - } - - if (orig instanceof AbortableHttpRequest) { - ((AbortableHttpRequest) orig).setReleaseTrigger(managedConn); - } - - // Reopen connection if needed - if (!managedConn.isOpen()) { - managedConn.open(route, context, params); - } - - try { - establishRoute(route, context); - } catch (TunnelRefusedException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage()); - } - response = ex.getResponse(); - break; - } - - if (HttpConnectionParams.isStaleCheckingEnabled(params)) { - // validate connection - LOG.debug("Stale connection check"); - if (managedConn.isStale()) { - LOG.debug("Stale connection detected"); - managedConn.close(); - continue; - } - } - - // Re-write request URI if needed - rewriteRequestURI(wrapper, route); - - // Use virtual host if set - target = (HttpHost) wrapper.getParams().getParameter( - ClientPNames.VIRTUAL_HOST); - - if (target == null) { - target = route.getTargetHost(); - } - - HttpHost proxy = route.getProxyHost(); - - // Populate the execution context - context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, - target); - context.setAttribute(ExecutionContext.HTTP_PROXY_HOST, - proxy); - context.setAttribute(ExecutionContext.HTTP_CONNECTION, - managedConn); - context.setAttribute(ClientContext.TARGET_AUTH_STATE, - targetAuthState); - context.setAttribute(ClientContext.PROXY_AUTH_STATE, - proxyAuthState); - requestExec.preProcess(wrapper, httpProcessor, context); - - context.setAttribute(ExecutionContext.HTTP_REQUEST, - wrapper); - - execCount++; - try { - if (LOG.isDebugEnabled()) { - LOG.debug("Attempt " + execCount + " to execute request"); - } - response = requestExec.execute(wrapper, managedConn, context); - - } catch (IOException ex) { - LOG.debug("Closing the connection."); - managedConn.close(); - if (retryHandler.retryRequest(ex, execCount, context)) { - if (LOG.isInfoEnabled()) { - LOG.info("I/O exception ("+ ex.getClass().getName() + - ") caught when processing request: " - + ex.getMessage()); - } - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage(), ex); - } - LOG.info("Retrying request"); - continue; - } - throw ex; - } - - response.setParams(params); - requestExec.postProcess(response, httpProcessor, context); - - RoutedRequest followup = handleResponse(roureq, response, context); - if (followup == null) { - done = true; - } else { - boolean reuse = reuseStrategy.keepAlive(response, context); - if (reuse) { - LOG.debug("Connection kept alive"); - // Make sure the response body is fully consumed, if present - HttpEntity entity = response.getEntity(); - if (entity != null) { - entity.consumeContent(); - } - // entity consumed above is not an auto-release entity, - // need to mark the connection re-usable explicitly - managedConn.markReusable(); - } else { - managedConn.close(); - } - // check if we can use the same connection for the followup - if (!followup.getRoute().equals(roureq.getRoute())) { - // the followup has a different route, release conn - connManager.releaseConnection(managedConn); - managedConn = null; - } - roureq = followup; - } - } // while not done - - // The connection is in or can be brought to a re-usable state. - boolean reuse = reuseStrategy.keepAlive(response, context); - - // check for entity, release connection if possible - if ((response == null) || (response.getEntity() == null) || - !response.getEntity().isStreaming()) { - // connection not needed and (assumed to be) in re-usable state - if (reuse) - managedConn.markReusable(); - connManager.releaseConnection(managedConn); - managedConn = null; - } else { - // install an auto-release entity - HttpEntity entity = response.getEntity(); - entity = new BasicManagedEntity(entity, managedConn, reuse); - response.setEntity(entity); - } - - return response; - - } catch (HttpException ex) { - abortConnection(); - throw ex; - } catch (IOException ex) { - abortConnection(); - throw ex; - } catch (RuntimeException ex) { - abortConnection(); - throw ex; - } - } // execute - - - /** - * Determines the route for a request. - * Called by {@link #execute} - * to determine the route for either the original or a followup request. - * - * @param target the target host for the request. - * Implementations may accept null - * if they can still determine a route, for example - * to a default target or by inspecting the request. - * @param request the request to execute - * @param context the context to use for the execution, - * never null - * - * @return the route the request should take - * - * @throws HttpException in case of a problem - */ - protected HttpRoute determineRoute(HttpHost target, - HttpRequest request, - HttpContext context) - throws HttpException { - - if (target == null) { - target = (HttpHost) request.getParams().getParameter( - ClientPNames.DEFAULT_HOST); - } - if (target == null) { - throw new IllegalStateException - ("Target host must not be null, or set in parameters."); - } - - return this.routePlanner.determineRoute(target, request, context); - } - - - /** - * Establishes the target route. - * - * @param route the route to establish - * @param context the context for the request execution - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected void establishRoute(HttpRoute route, HttpContext context) - throws HttpException, IOException { - - //@@@ how to handle CONNECT requests for tunnelling? - //@@@ refuse to send external CONNECT via director? special handling? - - //@@@ should the request parameters already be used below? - //@@@ probably yes, but they're not linked yet - //@@@ will linking above cause problems with linking in reqExec? - //@@@ probably not, because the parent is replaced - //@@@ just make sure we don't link parameters to themselves - - HttpRouteDirector rowdy = new BasicRouteDirector(); - int step; - do { - HttpRoute fact = managedConn.getRoute(); - step = rowdy.nextStep(route, fact); - - switch (step) { - - case HttpRouteDirector.CONNECT_TARGET: - case HttpRouteDirector.CONNECT_PROXY: - managedConn.open(route, context, this.params); - break; - - case HttpRouteDirector.TUNNEL_TARGET: { - boolean secure = createTunnelToTarget(route, context); - LOG.debug("Tunnel to target created."); - managedConn.tunnelTarget(secure, this.params); - } break; - - case HttpRouteDirector.TUNNEL_PROXY: { - // The most simple example for this case is a proxy chain - // of two proxies, where P1 must be tunnelled to P2. - // route: Source -> P1 -> P2 -> Target (3 hops) - // fact: Source -> P1 -> Target (2 hops) - final int hop = fact.getHopCount()-1; // the hop to establish - boolean secure = createTunnelToProxy(route, hop, context); - LOG.debug("Tunnel to proxy created."); - managedConn.tunnelProxy(route.getHopTarget(hop), - secure, this.params); - } break; - - - case HttpRouteDirector.LAYER_PROTOCOL: - managedConn.layerProtocol(context, this.params); - break; - - case HttpRouteDirector.UNREACHABLE: - throw new IllegalStateException - ("Unable to establish route." + - "\nplanned = " + route + - "\ncurrent = " + fact); - - case HttpRouteDirector.COMPLETE: - // do nothing - break; - - default: - throw new IllegalStateException - ("Unknown step indicator "+step+" from RouteDirector."); - } // switch - - } while (step > HttpRouteDirector.COMPLETE); - - } // establishConnection - - - /** - * Creates a tunnel to the target server. - * The connection must be established to the (last) proxy. - * A CONNECT request for tunnelling through the proxy will - * be created and sent, the response received and checked. - * This method does not update the connection with - * information about the tunnel, that is left to the caller. - * - * @param route the route to establish - * @param context the context for request execution - * - * @return true if the tunnelled route is secure, - * false otherwise. - * The implementation here always returns false, - * but derived classes may override. - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected boolean createTunnelToTarget(HttpRoute route, - HttpContext context) - throws HttpException, IOException { - - HttpHost proxy = route.getProxyHost(); - HttpHost target = route.getTargetHost(); - HttpResponse response = null; - - boolean done = false; - while (!done) { - - done = true; - - if (!this.managedConn.isOpen()) { - this.managedConn.open(route, context, this.params); - } - - HttpRequest connect = createConnectRequest(route, context); - - String agent = HttpProtocolParams.getUserAgent(params); - if (agent != null) { - connect.addHeader(HTTP.USER_AGENT, agent); - } - connect.addHeader(HTTP.TARGET_HOST, target.toHostString()); - - AuthScheme authScheme = this.proxyAuthState.getAuthScheme(); - AuthScope authScope = this.proxyAuthState.getAuthScope(); - Credentials creds = this.proxyAuthState.getCredentials(); - if (creds != null) { - if (authScope != null || !authScheme.isConnectionBased()) { - try { - connect.addHeader(authScheme.authenticate(creds, connect)); - } catch (AuthenticationException ex) { - if (LOG.isErrorEnabled()) { - LOG.error("Proxy authentication error: " + ex.getMessage()); - } - } - } - } - - response = requestExec.execute(connect, this.managedConn, context); - - int status = response.getStatusLine().getStatusCode(); - if (status < 200) { - throw new HttpException("Unexpected response to CONNECT request: " + - response.getStatusLine()); - } - - CredentialsProvider credsProvider = (CredentialsProvider) - context.getAttribute(ClientContext.CREDS_PROVIDER); - - if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { - if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { - - LOG.debug("Proxy requested authentication"); - Map challenges = this.proxyAuthHandler.getChallenges( - response, context); - try { - processChallenges( - challenges, this.proxyAuthState, this.proxyAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - break; - } - } - updateAuthState(this.proxyAuthState, proxy, credsProvider); - - if (this.proxyAuthState.getCredentials() != null) { - done = false; - - // Retry request - if (this.reuseStrategy.keepAlive(response, context)) { - LOG.debug("Connection kept alive"); - // Consume response content - HttpEntity entity = response.getEntity(); - if (entity != null) { - entity.consumeContent(); - } - } else { - this.managedConn.close(); - } - - } - - } else { - // Reset proxy auth scope - this.proxyAuthState.setAuthScope(null); - } - } - } - - int status = response.getStatusLine().getStatusCode(); - - if (status > 299) { - - // Buffer response content - HttpEntity entity = response.getEntity(); - if (entity != null) { - response.setEntity(new BufferedHttpEntity(entity)); - } - - this.managedConn.close(); - throw new TunnelRefusedException("CONNECT refused by proxy: " + - response.getStatusLine(), response); - } - - this.managedConn.markReusable(); - - // How to decide on security of the tunnelled connection? - // The socket factory knows only about the segment to the proxy. - // Even if that is secure, the hop to the target may be insecure. - // Leave it to derived classes, consider insecure by default here. - return false; - - } // createTunnelToTarget - - - - /** - * Creates a tunnel to an intermediate proxy. - * This method is not implemented in this class. - * It just throws an exception here. - * - * @param route the route to establish - * @param hop the hop in the route to establish now. - * route.getHopTarget(hop) - * will return the proxy to tunnel to. - * @param context the context for request execution - * - * @return true if the partially tunnelled connection - * is secure, false otherwise. - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected boolean createTunnelToProxy(HttpRoute route, int hop, - HttpContext context) - throws HttpException, IOException { - - // Have a look at createTunnelToTarget and replicate the parts - // you need in a custom derived class. If your proxies don't require - // authentication, it is not too hard. But for the stock version of - // HttpClient, we cannot make such simplifying assumptions and would - // have to include proxy authentication code. The HttpComponents team - // is currently not in a position to support rarely used code of this - // complexity. Feel free to submit patches that refactor the code in - // createTunnelToTarget to facilitate re-use for proxy tunnelling. - - throw new UnsupportedOperationException - ("Proxy chains are not supported."); - } - - - - /** - * Creates the CONNECT request for tunnelling. - * Called by {@link #createTunnelToTarget createTunnelToTarget}. - * - * @param route the route to establish - * @param context the context for request execution - * - * @return the CONNECT request for tunnelling - */ - protected HttpRequest createConnectRequest(HttpRoute route, - HttpContext context) { - // see RFC 2817, section 5.2 and - // INTERNET-DRAFT: Tunneling TCP based protocols through - // Web proxy servers - - HttpHost target = route.getTargetHost(); - - String host = target.getHostName(); - int port = target.getPort(); - if (port < 0) { - Scheme scheme = connManager.getSchemeRegistry(). - getScheme(target.getSchemeName()); - port = scheme.getDefaultPort(); - } - - StringBuilder buffer = new StringBuilder(host.length() + 6); - buffer.append(host); - buffer.append(":"); - buffer.append(Integer.toString(port)); - - String authority = buffer.toString(); - ProtocolVersion ver = HttpProtocolParams.getVersion(params); - HttpRequest req = new BasicHttpRequest - ("CONNECT", authority, ver); - - return req; - } - - - /** - * Analyzes a response to check need for a followup. - * - * @param roureq the request and route. - * @param response the response to analayze - * @param context the context used for the current request execution - * - * @return the followup request and route if there is a followup, or - * null if the response should be returned as is - * - * @throws HttpException in case of a problem - * @throws IOException in case of an IO problem - */ - protected RoutedRequest handleResponse(RoutedRequest roureq, - HttpResponse response, - HttpContext context) - throws HttpException, IOException { - - HttpRoute route = roureq.getRoute(); - HttpHost proxy = route.getProxyHost(); - RequestWrapper request = roureq.getRequest(); - - HttpParams params = request.getParams(); - if (HttpClientParams.isRedirecting(params) && - this.redirectHandler.isRedirectRequested(response, context)) { - - if (redirectCount >= maxRedirects) { - throw new RedirectException("Maximum redirects (" - + maxRedirects + ") exceeded"); - } - redirectCount++; - - URI uri = this.redirectHandler.getLocationURI(response, context); - - HttpHost newTarget = new HttpHost( - uri.getHost(), - uri.getPort(), - uri.getScheme()); - - HttpGet redirect = new HttpGet(uri); - - HttpRequest orig = request.getOriginal(); - redirect.setHeaders(orig.getAllHeaders()); - - RequestWrapper wrapper = new RequestWrapper(redirect); - wrapper.setParams(params); - - HttpRoute newRoute = determineRoute(newTarget, wrapper, context); - RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute); - - if (LOG.isDebugEnabled()) { - LOG.debug("Redirecting to '" + uri + "' via " + newRoute); - } - - return newRequest; - } - - CredentialsProvider credsProvider = (CredentialsProvider) - context.getAttribute(ClientContext.CREDS_PROVIDER); - - if (credsProvider != null && HttpClientParams.isAuthenticating(params)) { - - if (this.targetAuthHandler.isAuthenticationRequested(response, context)) { - - HttpHost target = (HttpHost) - context.getAttribute(ExecutionContext.HTTP_TARGET_HOST); - if (target == null) { - target = route.getTargetHost(); - } - - LOG.debug("Target requested authentication"); - Map challenges = this.targetAuthHandler.getChallenges( - response, context); - try { - processChallenges(challenges, - this.targetAuthState, this.targetAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - return null; - } - } - updateAuthState(this.targetAuthState, target, credsProvider); - - if (this.targetAuthState.getCredentials() != null) { - // Re-try the same request via the same route - return roureq; - } else { - return null; - } - } else { - // Reset target auth scope - this.targetAuthState.setAuthScope(null); - } - - if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) { - - LOG.debug("Proxy requested authentication"); - Map challenges = this.proxyAuthHandler.getChallenges( - response, context); - try { - processChallenges(challenges, - this.proxyAuthState, this.proxyAuthHandler, - response, context); - } catch (AuthenticationException ex) { - if (LOG.isWarnEnabled()) { - LOG.warn("Authentication error: " + ex.getMessage()); - return null; - } - } - updateAuthState(this.proxyAuthState, proxy, credsProvider); - - if (this.proxyAuthState.getCredentials() != null) { - // Re-try the same request via the same route - return roureq; - } else { - return null; - } - } else { - // Reset proxy auth scope - this.proxyAuthState.setAuthScope(null); - } - } - return null; - } // handleResponse - - - /** - * Shuts down the connection. - * This method is called from a catch block in - * {@link #execute execute} during exception handling. - * - * @throws IOException in case of an IO problem - */ - private void abortConnection() throws IOException { - ManagedClientConnection mcc = managedConn; - if (mcc != null) { - // we got here as the result of an exception - // no response will be returned, release the connection - managedConn = null; - try { - mcc.abortConnection(); - } catch (IOException ex) { - if (LOG.isDebugEnabled()) { - LOG.debug(ex.getMessage(), ex); - } - } - // ensure the connection manager properly releases this connection - connManager.releaseConnection(mcc); - } - } // abortConnection - - - private void processChallenges( - final Map challenges, - final AuthState authState, - final AuthenticationHandler authHandler, - final HttpResponse response, - final HttpContext context) - throws MalformedChallengeException, AuthenticationException { - - AuthScheme authScheme = authState.getAuthScheme(); - if (authScheme == null) { - // Authentication not attempted before - authScheme = authHandler.selectScheme(challenges, response, context); - authState.setAuthScheme(authScheme); - } - String id = authScheme.getSchemeName(); - - Header challenge = challenges.get(id.toLowerCase()); - if (challenge == null) { - throw new AuthenticationException(id + - " authorization challenge expected, but not found"); - } - authScheme.processChallenge(challenge); - LOG.debug("Authorization challenge processed"); - } - - - private void updateAuthState( - final AuthState authState, - final HttpHost host, - final CredentialsProvider credsProvider) { - - if (!authState.isValid()) { - return; - } - - String hostname = host.getHostName(); - int port = host.getPort(); - if (port < 0) { - Scheme scheme = connManager.getSchemeRegistry().getScheme(host); - port = scheme.getDefaultPort(); - } - - AuthScheme authScheme = authState.getAuthScheme(); - AuthScope authScope = new AuthScope( - hostname, - port, - authScheme.getRealm(), - authScheme.getSchemeName()); - - if (LOG.isDebugEnabled()) { - LOG.debug("Authentication scope: " + authScope); - } - Credentials creds = authState.getCredentials(); - if (creds == null) { - creds = credsProvider.getCredentials(authScope); - if (LOG.isDebugEnabled()) { - if (creds != null) { - LOG.debug("Found credentials"); - } else { - LOG.debug("Credentials not found"); - } - } - } else { - if (authScheme.isComplete()) { - LOG.debug("Authentication failed"); - creds = null; - } - } - authState.setAuthScope(authScope); - authState.setCredentials(creds); - } - -} // class DefaultClientRequestDirector diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/pair.info deleted file mode 100755 index 619ebb9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47336/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47336 -comSha:b7b8c7731d36aaa2291f03480716a30b82837f21 -parentComSha:7fd801fcfd89666d2404899a5a9388a3bbb1b18b -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/client/DefaultClientRequestDirector.java -StartLineNum:945 -EndLineNum:945 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/diff.diff deleted file mode 100755 index bbce570..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/client/AbstractAuthenticationHandler.java b/module-client/src/main/java/org/apache/http/impl/client/AbstractAuthenticationHandler.java -index 4c114fdad..88c83b0c8 100644 ---- a/module-client/src/main/java/org/apache/http/impl/client/AbstractAuthenticationHandler.java -+++ b/module-client/src/main/java/org/apache/http/impl/client/AbstractAuthenticationHandler.java -@@ -37,0 +38 @@ import java.util.List; -+import java.util.Locale; -@@ -100 +101 @@ public abstract class AbstractAuthenticationHandler implements AuthenticationHan -- map.put(s.toLowerCase(), header); -+ map.put(s.toLowerCase(Locale.ENGLISH), header); -@@ -129 +130 @@ public abstract class AbstractAuthenticationHandler implements AuthenticationHan -- Header challenge = challenges.get(id.toLowerCase()); -+ Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/new/AbstractAuthenticationHandler.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/new/AbstractAuthenticationHandler.java deleted file mode 100755 index 88c83b0..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/new/AbstractAuthenticationHandler.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthSchemeRegistry; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.client.AuthenticationHandler; -import org.apache.http.client.protocol.ClientContext; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.CharArrayBuffer; - -/** - * @author Oleg Kalnichevski - */ -public abstract class AbstractAuthenticationHandler implements AuthenticationHandler { - - private static final Log LOG = LogFactory.getLog(AbstractAuthenticationHandler.class); - - private static final List DEFAULT_SCHEME_PRIORITY = Arrays.asList(new String[] { - "digest", - "basic" - }); - - public AbstractAuthenticationHandler() { - super(); - } - - protected Map parseChallenges( - final Header[] headers) throws MalformedChallengeException { - - Map map = new HashMap(headers.length); - for (int i = 0; i < headers.length; i++) { - Header header = headers[i]; - CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int endIndex = pos; - String s = buffer.substring(beginIndex, endIndex); - map.put(s.toLowerCase(Locale.ENGLISH), header); - } - return map; - } - - protected List getAuthPreferences() { - return DEFAULT_SCHEME_PRIORITY; - } - - public AuthScheme selectScheme( - final Map challenges, - final HttpResponse response, - final HttpContext context) throws AuthenticationException { - - AuthSchemeRegistry registry = (AuthSchemeRegistry) context.getAttribute( - ClientContext.AUTHSCHEME_REGISTRY); - if (registry == null) { - throw new IllegalStateException("AuthScheme registry not set in HTTP context"); - } - - List authPrefs = getAuthPreferences(); - if (LOG.isDebugEnabled()) { - LOG.debug("Supported authentication schemes in the order of preference: " - + authPrefs); - } - - AuthScheme authScheme = null; - for (Iterator it = authPrefs.iterator(); it.hasNext(); ) { - String id = it.next(); - Header challenge = challenges.get(id.toLowerCase(Locale.ENGLISH)); - if (challenge != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(id + " authentication scheme selected"); - } - try { - authScheme = registry.getAuthScheme(id, response.getParams()); - } catch (IllegalStateException e) { - throw new AuthenticationException(e.getMessage()); - } - break; - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Challenge for " + id + " authentication scheme not available"); - // Try again - } - } - } - if (authScheme == null) { - // If none selected, something is wrong - throw new AuthenticationException( - "Unable to respond to any of these challenges: " - + challenges); - } - return authScheme; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/old/AbstractAuthenticationHandler.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/old/AbstractAuthenticationHandler.java deleted file mode 100755 index 4c114fd..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/old/AbstractAuthenticationHandler.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.client; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.http.FormattedHeader; -import org.apache.http.Header; -import org.apache.http.HttpResponse; -import org.apache.http.auth.AuthScheme; -import org.apache.http.auth.AuthSchemeRegistry; -import org.apache.http.auth.AuthenticationException; -import org.apache.http.auth.MalformedChallengeException; -import org.apache.http.client.AuthenticationHandler; -import org.apache.http.client.protocol.ClientContext; -import org.apache.http.protocol.HTTP; -import org.apache.http.protocol.HttpContext; -import org.apache.http.util.CharArrayBuffer; - -/** - * @author Oleg Kalnichevski - */ -public abstract class AbstractAuthenticationHandler implements AuthenticationHandler { - - private static final Log LOG = LogFactory.getLog(AbstractAuthenticationHandler.class); - - private static final List DEFAULT_SCHEME_PRIORITY = Arrays.asList(new String[] { - "digest", - "basic" - }); - - public AbstractAuthenticationHandler() { - super(); - } - - protected Map parseChallenges( - final Header[] headers) throws MalformedChallengeException { - - Map map = new HashMap(headers.length); - for (int i = 0; i < headers.length; i++) { - Header header = headers[i]; - CharArrayBuffer buffer; - int pos; - if (header instanceof FormattedHeader) { - buffer = ((FormattedHeader) header).getBuffer(); - pos = ((FormattedHeader) header).getValuePos(); - } else { - String s = header.getValue(); - if (s == null) { - throw new MalformedChallengeException("Header value is null"); - } - buffer = new CharArrayBuffer(s.length()); - buffer.append(s); - pos = 0; - } - while (pos < buffer.length() && HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int beginIndex = pos; - while (pos < buffer.length() && !HTTP.isWhitespace(buffer.charAt(pos))) { - pos++; - } - int endIndex = pos; - String s = buffer.substring(beginIndex, endIndex); - map.put(s.toLowerCase(), header); - } - return map; - } - - protected List getAuthPreferences() { - return DEFAULT_SCHEME_PRIORITY; - } - - public AuthScheme selectScheme( - final Map challenges, - final HttpResponse response, - final HttpContext context) throws AuthenticationException { - - AuthSchemeRegistry registry = (AuthSchemeRegistry) context.getAttribute( - ClientContext.AUTHSCHEME_REGISTRY); - if (registry == null) { - throw new IllegalStateException("AuthScheme registry not set in HTTP context"); - } - - List authPrefs = getAuthPreferences(); - if (LOG.isDebugEnabled()) { - LOG.debug("Supported authentication schemes in the order of preference: " - + authPrefs); - } - - AuthScheme authScheme = null; - for (Iterator it = authPrefs.iterator(); it.hasNext(); ) { - String id = it.next(); - Header challenge = challenges.get(id.toLowerCase()); - if (challenge != null) { - if (LOG.isDebugEnabled()) { - LOG.debug(id + " authentication scheme selected"); - } - try { - authScheme = registry.getAuthScheme(id, response.getParams()); - } catch (IllegalStateException e) { - throw new AuthenticationException(e.getMessage()); - } - break; - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("Challenge for " + id + " authentication scheme not available"); - // Try again - } - } - } - if (authScheme == null) { - // If none selected, something is wrong - throw new AuthenticationException( - "Unable to respond to any of these challenges: " - + challenges); - } - return authScheme; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/pair.info deleted file mode 100755 index 9119cf4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47349/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47349 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/client/AbstractAuthenticationHandler.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/client/AbstractAuthenticationHandler.java -StartLineNum:129 -EndLineNum:129 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/diff.diff deleted file mode 100755 index 61c4ebe..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/impl/cookie/NetscapeDomainHandler.java b/module-client/src/main/java/org/apache/http/impl/cookie/NetscapeDomainHandler.java -index 78a4489af..64729ec18 100644 ---- a/module-client/src/main/java/org/apache/http/impl/cookie/NetscapeDomainHandler.java -+++ b/module-client/src/main/java/org/apache/http/impl/cookie/NetscapeDomainHandler.java -@@ -32,0 +33 @@ package org.apache.http.impl.cookie; -+import java.util.Locale; -@@ -79 +80 @@ public class NetscapeDomainHandler extends BasicDomainHandler { -- final String ucDomain = domain.toUpperCase(); -+ final String ucDomain = domain.toUpperCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/new/NetscapeDomainHandler.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/new/NetscapeDomainHandler.java deleted file mode 100755 index 64729ec..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/new/NetscapeDomainHandler.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.Locale; -import java.util.StringTokenizer; - -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; - -public class NetscapeDomainHandler extends BasicDomainHandler { - - public NetscapeDomainHandler() { - super(); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - super.validate(cookie, origin); - // Perform Netscape Cookie draft specific validation - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (host.indexOf(".") >= 0) { - int domainParts = new StringTokenizer(domain, ".").countTokens(); - - if (isSpecialDomain(domain)) { - if (domainParts < 2) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates the Netscape cookie specification for " - + "special domains"); - } - } else { - if (domainParts < 3) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates the Netscape cookie specification"); - } - } - } - } - - /** - * Checks if the given domain is in one of the seven special - * top level domains defined by the Netscape cookie specification. - * @param domain The domain. - * @return True if the specified domain is "special" - */ - private static boolean isSpecialDomain(final String domain) { - final String ucDomain = domain.toUpperCase(Locale.ENGLISH); - if (ucDomain.endsWith(".COM") - || ucDomain.endsWith(".EDU") - || ucDomain.endsWith(".NET") - || ucDomain.endsWith(".GOV") - || ucDomain.endsWith(".MIL") - || ucDomain.endsWith(".ORG") - || ucDomain.endsWith(".INT")) { - return true; - } - return false; - } - - @Override -public boolean match(Cookie cookie, CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.endsWith(domain); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/old/NetscapeDomainHandler.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/old/NetscapeDomainHandler.java deleted file mode 100755 index 78a4489..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/old/NetscapeDomainHandler.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ -package org.apache.http.impl.cookie; - -import java.util.StringTokenizer; - -import org.apache.http.cookie.Cookie; -import org.apache.http.cookie.CookieOrigin; -import org.apache.http.cookie.MalformedCookieException; - -public class NetscapeDomainHandler extends BasicDomainHandler { - - public NetscapeDomainHandler() { - super(); - } - - @Override - public void validate(final Cookie cookie, final CookieOrigin origin) - throws MalformedCookieException { - super.validate(cookie, origin); - // Perform Netscape Cookie draft specific validation - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (host.indexOf(".") >= 0) { - int domainParts = new StringTokenizer(domain, ".").countTokens(); - - if (isSpecialDomain(domain)) { - if (domainParts < 2) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates the Netscape cookie specification for " - + "special domains"); - } - } else { - if (domainParts < 3) { - throw new MalformedCookieException("Domain attribute \"" - + domain - + "\" violates the Netscape cookie specification"); - } - } - } - } - - /** - * Checks if the given domain is in one of the seven special - * top level domains defined by the Netscape cookie specification. - * @param domain The domain. - * @return True if the specified domain is "special" - */ - private static boolean isSpecialDomain(final String domain) { - final String ucDomain = domain.toUpperCase(); - if (ucDomain.endsWith(".COM") - || ucDomain.endsWith(".EDU") - || ucDomain.endsWith(".NET") - || ucDomain.endsWith(".GOV") - || ucDomain.endsWith(".MIL") - || ucDomain.endsWith(".ORG") - || ucDomain.endsWith(".INT")) { - return true; - } - return false; - } - - @Override -public boolean match(Cookie cookie, CookieOrigin origin) { - if (cookie == null) { - throw new IllegalArgumentException("Cookie may not be null"); - } - if (origin == null) { - throw new IllegalArgumentException("Cookie origin may not be null"); - } - String host = origin.getHost(); - String domain = cookie.getDomain(); - if (domain == null) { - return false; - } - return host.endsWith(domain); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/pair.info deleted file mode 100755 index 6def25f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47351/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47351 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/impl/cookie/NetscapeDomainHandler.java -FixedFilePath:module-client/src/main/java/org/apache/http/impl/cookie/NetscapeDomainHandler.java -StartLineNum:79 -EndLineNum:79 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/comMsg.txt deleted file mode 100755 index bb4ca5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -HTTPCLIENT-765 - String.toLowerCase() / toUpperCase() should specify Locale.ENGLISH - -git-svn-id: https://svn.apache.org/repos/asf/httpcomponents/httpclient/trunk@652950 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/diff.diff deleted file mode 100755 index 3550eb1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/module-client/src/main/java/org/apache/http/conn/ssl/AbstractVerifier.java b/module-client/src/main/java/org/apache/http/conn/ssl/AbstractVerifier.java -index 59b20f243..2a3cb88df 100644 ---- a/module-client/src/main/java/org/apache/http/conn/ssl/AbstractVerifier.java -+++ b/module-client/src/main/java/org/apache/http/conn/ssl/AbstractVerifier.java -@@ -45,0 +46 @@ import java.util.List; -+import java.util.Locale; -@@ -181 +182 @@ public abstract class AbstractVerifier implements X509HostnameVerifier { -- String hostName = host.trim().toLowerCase(); -+ String hostName = host.trim().toLowerCase(Locale.ENGLISH); -@@ -186 +187 @@ public abstract class AbstractVerifier implements X509HostnameVerifier { -- cn = cn.toLowerCase(); -+ cn = cn.toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/new/AbstractVerifier.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/new/AbstractVerifier.java deleted file mode 100755 index 2a3cb88..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/new/AbstractVerifier.java +++ /dev/null @@ -1,341 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import org.apache.http.conn.util.InetAddressUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.security.cert.Certificate; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.StringTokenizer; - -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; - -/** - * Abstract base class for all standard {@link X509HostnameVerifier} - * implementations. - * - * @author Julius Davies - */ -public abstract class AbstractVerifier implements X509HostnameVerifier { - - /** - * This contains a list of 2nd-level domains that aren't allowed to - * have wildcards when combined with country-codes. - * For example: [*.co.uk]. - *

- * The [*.co.uk] problem is an interesting one. Should we just hope - * that CA's would never foolishly allow such a certificate to happen? - * Looks like we're the only implementation guarding against this. - * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check. - */ - private final static String[] BAD_COUNTRY_2LDS = - { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", - "lg", "ne", "net", "or", "org" }; - - static { - // Just in case developer forgot to manually sort the array. :-) - Arrays.sort(BAD_COUNTRY_2LDS); - } - - public AbstractVerifier() { - super(); - } - - public final void verify(String host, SSLSocket ssl) - throws IOException { - if(host == null) { - throw new NullPointerException("host to verify is null"); - } - - SSLSession session = ssl.getSession(); - if(session == null) { - // In our experience this only happens under IBM 1.4.x when - // spurious (unrelated) certificates show up in the server' - // chain. Hopefully this will unearth the real problem: - InputStream in = ssl.getInputStream(); - in.available(); - /* - If you're looking at the 2 lines of code above because - you're running into a problem, you probably have two - options: - - #1. Clean up the certificate chain that your server - is presenting (e.g. edit "/etc/apache2/server.crt" - or wherever it is your server's certificate chain - is defined). - - OR - - #2. Upgrade to an IBM 1.5.x or greater JVM, or switch - to a non-IBM JVM. - */ - - // If ssl.getInputStream().available() didn't cause an - // exception, maybe at least now the session is available? - session = ssl.getSession(); - if(session == null) { - // If it's still null, probably a startHandshake() will - // unearth the real problem. - ssl.startHandshake(); - - // Okay, if we still haven't managed to cause an exception, - // might as well go for the NPE. Or maybe we're okay now? - session = ssl.getSession(); - } - } - - Certificate[] certs = session.getPeerCertificates(); - X509Certificate x509 = (X509Certificate) certs[0]; - verify(host, x509); - } - - public final boolean verify(String host, SSLSession session) { - try { - Certificate[] certs = session.getPeerCertificates(); - X509Certificate x509 = (X509Certificate) certs[0]; - verify(host, x509); - return true; - } - catch(SSLException e) { - return false; - } - } - - public final void verify(String host, X509Certificate cert) - throws SSLException { - String[] cns = getCNs(cert); - String[] subjectAlts = getDNSSubjectAlts(cert); - verify(host, cns, subjectAlts); - } - - public final void verify(final String host, final String[] cns, - final String[] subjectAlts, - final boolean strictWithSubDomains) - throws SSLException { - - // Build the list of names we're going to check. Our DEFAULT and - // STRICT implementations of the HostnameVerifier only use the - // first CN provided. All other CNs are ignored. - // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way). - LinkedList names = new LinkedList(); - if(cns != null && cns.length > 0 && cns[0] != null) { - names.add(cns[0]); - } - if(subjectAlts != null) { - for(int i = 0; i < subjectAlts.length; i++) { - if(subjectAlts[i] != null) { - names.add(subjectAlts[i]); - } - } - } - - if(names.isEmpty()) { - String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt"; - throw new SSLException(msg); - } - - // StringBuffer for building the error message. - StringBuffer buf = new StringBuffer(); - - // We're can be case-insensitive when comparing the host we used to - // establish the socket to the hostname in the certificate. - String hostName = host.trim().toLowerCase(Locale.ENGLISH); - boolean match = false; - for(Iterator it = names.iterator(); it.hasNext();) { - // Don't trim the CN, though! - String cn = it.next(); - cn = cn.toLowerCase(Locale.ENGLISH); - // Store CN in StringBuffer in case we need to report an error. - buf.append(" <"); - buf.append(cn); - buf.append('>'); - if(it.hasNext()) { - buf.append(" OR"); - } - - // The CN better have at least two dots if it wants wildcard - // action. It also can't be [*.co.uk] or [*.co.jp] or - // [*.org.uk], etc... - boolean doWildcard = cn.startsWith("*.") && - cn.lastIndexOf('.') >= 0 && - acceptableCountryWildcard(cn) && - !InetAddressUtils.isIPv4Address(host); - - if(doWildcard) { - match = hostName.endsWith(cn.substring(1)); - if(match && strictWithSubDomains) { - // If we're in strict mode, then [*.foo.com] is not - // allowed to match [a.b.foo.com] - match = countDots(hostName) == countDots(cn); - } - } else { - match = hostName.equals(cn); - } - if(match) { - break; - } - } - if(!match) { - throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf); - } - } - - public static boolean acceptableCountryWildcard(String cn) { - int cnLen = cn.length(); - if(cnLen >= 7 && cnLen <= 9) { - // Look for the '.' in the 3rd-last position: - if(cn.charAt(cnLen - 3) == '.') { - // Trim off the [*.] and the [.XX]. - String s = cn.substring(2, cnLen - 3); - // And test against the sorted array of bad 2lds: - int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s); - return x < 0; - } - } - return true; - } - - public static String[] getCNs(X509Certificate cert) { - LinkedList cnList = new LinkedList(); - /* - Sebastian Hauer's original StrictSSLProtocolSocketFactory used - getName() and had the following comment: - - Parses a X.500 distinguished name for the value of the - "Common Name" field. This is done a bit sloppy right - now and should probably be done a bit more according to - RFC 2253. - - I've noticed that toString() seems to do a better job than - getName() on these X500Principal objects, so I'm hoping that - addresses Sebastian's concern. - - For example, getName() gives me this: - 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d - - whereas toString() gives me this: - EMAILADDRESS=juliusdavies@cucbc.com - - Looks like toString() even works with non-ascii domain names! - I tested it with "花子.co.jp" and it worked fine. - */ - String subjectPrincipal = cert.getSubjectX500Principal().toString(); - StringTokenizer st = new StringTokenizer(subjectPrincipal, ","); - while(st.hasMoreTokens()) { - String tok = st.nextToken(); - int x = tok.indexOf("CN="); - if(x >= 0) { - cnList.add(tok.substring(x + 3)); - } - } - if(!cnList.isEmpty()) { - String[] cns = new String[cnList.size()]; - cnList.toArray(cns); - return cns; - } else { - return null; - } - } - - - /** - * Extracts the array of SubjectAlt DNS names from an X509Certificate. - * Returns null if there aren't any. - *

- * Note: Java doesn't appear able to extract international characters - * from the SubjectAlts. It can only extract international characters - * from the CN field. - *

- * (Or maybe the version of OpenSSL I'm using to test isn't storing the - * international characters correctly in the SubjectAlts?). - * - * @param cert X509Certificate - * @return Array of SubjectALT DNS names stored in the certificate. - */ - public static String[] getDNSSubjectAlts(X509Certificate cert) { - LinkedList subjectAltList = new LinkedList(); - Collection> c = null; - try { - c = cert.getSubjectAlternativeNames(); - } - catch(CertificateParsingException cpe) { - // Should probably log.debug() this? - cpe.printStackTrace(); - } - if(c != null) { - Iterator> it = c.iterator(); - while(it.hasNext()) { - List list = it.next(); - int type = ((Integer) list.get(0)).intValue(); - // If type is 2, then we've got a dNSName - if(type == 2) { - String s = (String) list.get(1); - subjectAltList.add(s); - } - } - } - if(!subjectAltList.isEmpty()) { - String[] subjectAlts = new String[subjectAltList.size()]; - subjectAltList.toArray(subjectAlts); - return subjectAlts; - } else { - return null; - } - } - - /** - * Counts the number of dots "." in a string. - * @param s string to count dots from - * @return number of dots - */ - public static int countDots(final String s) { - int count = 0; - for(int i = 0; i < s.length(); i++) { - if(s.charAt(i) == '.') { - count++; - } - } - return count; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/old/AbstractVerifier.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/old/AbstractVerifier.java deleted file mode 100755 index 59b20f2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/old/AbstractVerifier.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * $HeadURL$ - * $Revision$ - * $Date$ - * - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.conn.ssl; - -import org.apache.http.conn.util.InetAddressUtils; - -import java.io.IOException; -import java.io.InputStream; -import java.security.cert.Certificate; -import java.security.cert.CertificateParsingException; -import java.security.cert.X509Certificate; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.StringTokenizer; - -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocket; - -/** - * Abstract base class for all standard {@link X509HostnameVerifier} - * implementations. - * - * @author Julius Davies - */ -public abstract class AbstractVerifier implements X509HostnameVerifier { - - /** - * This contains a list of 2nd-level domains that aren't allowed to - * have wildcards when combined with country-codes. - * For example: [*.co.uk]. - *

- * The [*.co.uk] problem is an interesting one. Should we just hope - * that CA's would never foolishly allow such a certificate to happen? - * Looks like we're the only implementation guarding against this. - * Firefox, Curl, Sun Java 1.4, 5, 6 don't bother with this check. - */ - private final static String[] BAD_COUNTRY_2LDS = - { "ac", "co", "com", "ed", "edu", "go", "gouv", "gov", "info", - "lg", "ne", "net", "or", "org" }; - - static { - // Just in case developer forgot to manually sort the array. :-) - Arrays.sort(BAD_COUNTRY_2LDS); - } - - public AbstractVerifier() { - super(); - } - - public final void verify(String host, SSLSocket ssl) - throws IOException { - if(host == null) { - throw new NullPointerException("host to verify is null"); - } - - SSLSession session = ssl.getSession(); - if(session == null) { - // In our experience this only happens under IBM 1.4.x when - // spurious (unrelated) certificates show up in the server' - // chain. Hopefully this will unearth the real problem: - InputStream in = ssl.getInputStream(); - in.available(); - /* - If you're looking at the 2 lines of code above because - you're running into a problem, you probably have two - options: - - #1. Clean up the certificate chain that your server - is presenting (e.g. edit "/etc/apache2/server.crt" - or wherever it is your server's certificate chain - is defined). - - OR - - #2. Upgrade to an IBM 1.5.x or greater JVM, or switch - to a non-IBM JVM. - */ - - // If ssl.getInputStream().available() didn't cause an - // exception, maybe at least now the session is available? - session = ssl.getSession(); - if(session == null) { - // If it's still null, probably a startHandshake() will - // unearth the real problem. - ssl.startHandshake(); - - // Okay, if we still haven't managed to cause an exception, - // might as well go for the NPE. Or maybe we're okay now? - session = ssl.getSession(); - } - } - - Certificate[] certs = session.getPeerCertificates(); - X509Certificate x509 = (X509Certificate) certs[0]; - verify(host, x509); - } - - public final boolean verify(String host, SSLSession session) { - try { - Certificate[] certs = session.getPeerCertificates(); - X509Certificate x509 = (X509Certificate) certs[0]; - verify(host, x509); - return true; - } - catch(SSLException e) { - return false; - } - } - - public final void verify(String host, X509Certificate cert) - throws SSLException { - String[] cns = getCNs(cert); - String[] subjectAlts = getDNSSubjectAlts(cert); - verify(host, cns, subjectAlts); - } - - public final void verify(final String host, final String[] cns, - final String[] subjectAlts, - final boolean strictWithSubDomains) - throws SSLException { - - // Build the list of names we're going to check. Our DEFAULT and - // STRICT implementations of the HostnameVerifier only use the - // first CN provided. All other CNs are ignored. - // (Firefox, wget, curl, Sun Java 1.4, 5, 6 all work this way). - LinkedList names = new LinkedList(); - if(cns != null && cns.length > 0 && cns[0] != null) { - names.add(cns[0]); - } - if(subjectAlts != null) { - for(int i = 0; i < subjectAlts.length; i++) { - if(subjectAlts[i] != null) { - names.add(subjectAlts[i]); - } - } - } - - if(names.isEmpty()) { - String msg = "Certificate for <" + host + "> doesn't contain CN or DNS subjectAlt"; - throw new SSLException(msg); - } - - // StringBuffer for building the error message. - StringBuffer buf = new StringBuffer(); - - // We're can be case-insensitive when comparing the host we used to - // establish the socket to the hostname in the certificate. - String hostName = host.trim().toLowerCase(); - boolean match = false; - for(Iterator it = names.iterator(); it.hasNext();) { - // Don't trim the CN, though! - String cn = it.next(); - cn = cn.toLowerCase(); - // Store CN in StringBuffer in case we need to report an error. - buf.append(" <"); - buf.append(cn); - buf.append('>'); - if(it.hasNext()) { - buf.append(" OR"); - } - - // The CN better have at least two dots if it wants wildcard - // action. It also can't be [*.co.uk] or [*.co.jp] or - // [*.org.uk], etc... - boolean doWildcard = cn.startsWith("*.") && - cn.lastIndexOf('.') >= 0 && - acceptableCountryWildcard(cn) && - !InetAddressUtils.isIPv4Address(host); - - if(doWildcard) { - match = hostName.endsWith(cn.substring(1)); - if(match && strictWithSubDomains) { - // If we're in strict mode, then [*.foo.com] is not - // allowed to match [a.b.foo.com] - match = countDots(hostName) == countDots(cn); - } - } else { - match = hostName.equals(cn); - } - if(match) { - break; - } - } - if(!match) { - throw new SSLException("hostname in certificate didn't match: <" + host + "> !=" + buf); - } - } - - public static boolean acceptableCountryWildcard(String cn) { - int cnLen = cn.length(); - if(cnLen >= 7 && cnLen <= 9) { - // Look for the '.' in the 3rd-last position: - if(cn.charAt(cnLen - 3) == '.') { - // Trim off the [*.] and the [.XX]. - String s = cn.substring(2, cnLen - 3); - // And test against the sorted array of bad 2lds: - int x = Arrays.binarySearch(BAD_COUNTRY_2LDS, s); - return x < 0; - } - } - return true; - } - - public static String[] getCNs(X509Certificate cert) { - LinkedList cnList = new LinkedList(); - /* - Sebastian Hauer's original StrictSSLProtocolSocketFactory used - getName() and had the following comment: - - Parses a X.500 distinguished name for the value of the - "Common Name" field. This is done a bit sloppy right - now and should probably be done a bit more according to - RFC 2253. - - I've noticed that toString() seems to do a better job than - getName() on these X500Principal objects, so I'm hoping that - addresses Sebastian's concern. - - For example, getName() gives me this: - 1.2.840.113549.1.9.1=#16166a756c6975736461766965734063756362632e636f6d - - whereas toString() gives me this: - EMAILADDRESS=juliusdavies@cucbc.com - - Looks like toString() even works with non-ascii domain names! - I tested it with "花子.co.jp" and it worked fine. - */ - String subjectPrincipal = cert.getSubjectX500Principal().toString(); - StringTokenizer st = new StringTokenizer(subjectPrincipal, ","); - while(st.hasMoreTokens()) { - String tok = st.nextToken(); - int x = tok.indexOf("CN="); - if(x >= 0) { - cnList.add(tok.substring(x + 3)); - } - } - if(!cnList.isEmpty()) { - String[] cns = new String[cnList.size()]; - cnList.toArray(cns); - return cns; - } else { - return null; - } - } - - - /** - * Extracts the array of SubjectAlt DNS names from an X509Certificate. - * Returns null if there aren't any. - *

- * Note: Java doesn't appear able to extract international characters - * from the SubjectAlts. It can only extract international characters - * from the CN field. - *

- * (Or maybe the version of OpenSSL I'm using to test isn't storing the - * international characters correctly in the SubjectAlts?). - * - * @param cert X509Certificate - * @return Array of SubjectALT DNS names stored in the certificate. - */ - public static String[] getDNSSubjectAlts(X509Certificate cert) { - LinkedList subjectAltList = new LinkedList(); - Collection> c = null; - try { - c = cert.getSubjectAlternativeNames(); - } - catch(CertificateParsingException cpe) { - // Should probably log.debug() this? - cpe.printStackTrace(); - } - if(c != null) { - Iterator> it = c.iterator(); - while(it.hasNext()) { - List list = it.next(); - int type = ((Integer) list.get(0)).intValue(); - // If type is 2, then we've got a dNSName - if(type == 2) { - String s = (String) list.get(1); - subjectAltList.add(s); - } - } - } - if(!subjectAltList.isEmpty()) { - String[] subjectAlts = new String[subjectAltList.size()]; - subjectAltList.toArray(subjectAlts); - return subjectAlts; - } else { - return null; - } - } - - /** - * Counts the number of dots "." in a string. - * @param s string to count dots from - * @return number of dots - */ - public static int countDots(final String s) { - int count = 0; - for(int i = 0; i < s.length(); i++) { - if(s.charAt(i) == '.') { - count++; - } - } - return count; - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/pair.info deleted file mode 100755 index 991516f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#47366/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:47366 -comSha:17bacf5e7f4c0b23999f5341aa0458c71d452fcf -parentComSha:f761a1746069932c13d918563c6e26fae2208cf0 -BuggyFilePath:module-client/src/main/java/org/apache/http/conn/ssl/AbstractVerifier.java -FixedFilePath:module-client/src/main/java/org/apache/http/conn/ssl/AbstractVerifier.java -StartLineNum:181 -EndLineNum:181 -repoName:apache#httpclient \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/comMsg.txt deleted file mode 100755 index 3564c01..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/comMsg.txt +++ /dev/null @@ -1,6 +0,0 @@ -Issue #1555: Add locale to lower case conversion - -Fixes `StringToUpperWithoutLocale` inspection violations introduced in recent commits. - -Description: ->Reports any call of toUpperCase() or toLowerCase() on String objects which do not specify a java.util.Locale. Such calls are usually incorrect in an internationalized environment. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/diff.diff deleted file mode 100755 index 374afdd..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java -index 3b283e3f6..335d581ea 100644 ---- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java -+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java -@@ -22,0 +23 @@ import static com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.MSG -+import static java.util.Locale.ENGLISH; -@@ -191 +192 @@ public class NewlineAtEndOfFileCheckTest -- if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { -+ if (System.getProperty("os.name").toLowerCase(ENGLISH).startsWith("windows")) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/new/NewlineAtEndOfFileCheckTest.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/new/NewlineAtEndOfFileCheckTest.java deleted file mode 100755 index 335d581..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/new/NewlineAtEndOfFileCheckTest.java +++ /dev/null @@ -1,200 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2015 the original author or authors. -// -// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.puppycrawl.tools.checkstyle.checks; - -import static com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.MSG_KEY_NO_NEWLINE_EOF; -import static java.util.Locale.ENGLISH; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Iterator; -import java.util.Set; - -import org.apache.commons.lang3.ArrayUtils; -import org.junit.Test; - -import com.google.common.collect.Lists; -import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; - -public class NewlineAtEndOfFileCheckTest - extends BaseCheckTestSupport { - @Override - protected DefaultConfiguration createCheckerConfig( - Configuration config) { - final DefaultConfiguration dc = new DefaultConfiguration("root"); - dc.addChild(config); - return dc; - } - - @Test - public void testNewlineLfAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verify( - createChecker(checkConfig), - getPath("InputNewlineLfAtEndOfFile.java"), - expected); - } - - @Test - public void testNewlineCrlfAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.CRLF.toString()); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verify( - createChecker(checkConfig), - getPath("InputNewlineCrlfAtEndOfFile.java"), - expected); - } - - @Test - public void testNewlineCrAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.CR.toString()); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verify( - createChecker(checkConfig), - getPath("InputNewlineCrAtEndOfFile.java"), - expected); - } - - @Test - public void testAnyNewlineAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF_CR_CRLF.toString()); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verify( - createChecker(checkConfig), - getPath("InputNewlineCrlfAtEndOfFile.java"), - expected); - verify( - createChecker(checkConfig), - getPath("InputNewlineLfAtEndOfFile.java"), - expected); - verify( - createChecker(checkConfig), - getPath("InputNewlineCrAtEndOfFile.java"), - expected); - } - - @Test - public void testNoNewlineLfAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); - final String[] expected = { - "0: " + getCheckMessage(MSG_KEY_NO_NEWLINE_EOF), - }; - verify( - createChecker(checkConfig), - getPath("InputNoNewlineAtEndOfFile.java"), - expected); - } - - @Test - public void testNoNewlineAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF_CR_CRLF.toString()); - final String[] expected = { - "0: " + getCheckMessage(MSG_KEY_NO_NEWLINE_EOF), - }; - verify( - createChecker(checkConfig), - getPath("InputNoNewlineAtEndOfFile.java"), - expected); - } - - @Test(expected = CheckstyleException.class) - public void testSetLineSeparatorFailure() - throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", "ct"); - createChecker(checkConfig); - } - - @Test - public void testEmptyFileFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); - final String[] expected = { - "0: " + getCheckMessage(MSG_KEY_NO_NEWLINE_EOF), - }; - verify( - createChecker(checkConfig), - getPath("InputEmptyFile.txt"), - expected); - } - - @Test - public void testWrongFile() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class); - NewlineAtEndOfFileCheck check = new NewlineAtEndOfFileCheck(); - check.configure(checkConfig); - File impossibleFile = new File(""); - Set messages = check.process(impossibleFile, Lists.newArrayList("txt")); - assertTrue(messages.size() == 1); - Iterator iter = messages.iterator(); - assertEquals(iter.next().getMessage(), "Unable to open ''."); - } - - @Test - public void testWrongSeparatorLength() throws Exception { - NewlineAtEndOfFileCheck check = new NewlineAtEndOfFileCheck(); - final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class); - check.configure(checkConfig); - - Method method = NewlineAtEndOfFileCheck.class - .getDeclaredMethod("endsWithNewline", RandomAccessFile.class); - method.setAccessible(true); - RandomAccessFile file = mock(RandomAccessFile.class); - when(file.length()).thenReturn(2000000L); - try { - method.invoke(new NewlineAtEndOfFileCheck(), file); - } - catch (InvocationTargetException ex) { - assertTrue(ex.getCause() instanceof IOException); - if (System.getProperty("os.name").toLowerCase(ENGLISH).startsWith("windows")) { - assertEquals(ex.getCause().getMessage(), "Unable to read 2 bytes, got 0"); - } - else { - assertEquals(ex.getCause().getMessage(), "Unable to read 1 bytes, got 0"); - } - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/old/NewlineAtEndOfFileCheckTest.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/old/NewlineAtEndOfFileCheckTest.java deleted file mode 100755 index 3b283e3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/old/NewlineAtEndOfFileCheckTest.java +++ /dev/null @@ -1,199 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2015 the original author or authors. -// -// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.puppycrawl.tools.checkstyle.checks; - -import static com.puppycrawl.tools.checkstyle.checks.NewlineAtEndOfFileCheck.MSG_KEY_NO_NEWLINE_EOF; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.powermock.api.mockito.PowerMockito.mock; -import static org.powermock.api.mockito.PowerMockito.when; - -import java.io.File; -import java.io.IOException; -import java.io.RandomAccessFile; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Iterator; -import java.util.Set; - -import org.apache.commons.lang3.ArrayUtils; -import org.junit.Test; - -import com.google.common.collect.Lists; -import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.api.LocalizedMessage; - -public class NewlineAtEndOfFileCheckTest - extends BaseCheckTestSupport { - @Override - protected DefaultConfiguration createCheckerConfig( - Configuration config) { - final DefaultConfiguration dc = new DefaultConfiguration("root"); - dc.addChild(config); - return dc; - } - - @Test - public void testNewlineLfAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verify( - createChecker(checkConfig), - getPath("InputNewlineLfAtEndOfFile.java"), - expected); - } - - @Test - public void testNewlineCrlfAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.CRLF.toString()); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verify( - createChecker(checkConfig), - getPath("InputNewlineCrlfAtEndOfFile.java"), - expected); - } - - @Test - public void testNewlineCrAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.CR.toString()); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verify( - createChecker(checkConfig), - getPath("InputNewlineCrAtEndOfFile.java"), - expected); - } - - @Test - public void testAnyNewlineAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF_CR_CRLF.toString()); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verify( - createChecker(checkConfig), - getPath("InputNewlineCrlfAtEndOfFile.java"), - expected); - verify( - createChecker(checkConfig), - getPath("InputNewlineLfAtEndOfFile.java"), - expected); - verify( - createChecker(checkConfig), - getPath("InputNewlineCrAtEndOfFile.java"), - expected); - } - - @Test - public void testNoNewlineLfAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); - final String[] expected = { - "0: " + getCheckMessage(MSG_KEY_NO_NEWLINE_EOF), - }; - verify( - createChecker(checkConfig), - getPath("InputNoNewlineAtEndOfFile.java"), - expected); - } - - @Test - public void testNoNewlineAtEndOfFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF_CR_CRLF.toString()); - final String[] expected = { - "0: " + getCheckMessage(MSG_KEY_NO_NEWLINE_EOF), - }; - verify( - createChecker(checkConfig), - getPath("InputNoNewlineAtEndOfFile.java"), - expected); - } - - @Test(expected = CheckstyleException.class) - public void testSetLineSeparatorFailure() - throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", "ct"); - createChecker(checkConfig); - } - - @Test - public void testEmptyFileFile() throws Exception { - final DefaultConfiguration checkConfig = - createCheckConfig(NewlineAtEndOfFileCheck.class); - checkConfig.addAttribute("lineSeparator", LineSeparatorOption.LF.toString()); - final String[] expected = { - "0: " + getCheckMessage(MSG_KEY_NO_NEWLINE_EOF), - }; - verify( - createChecker(checkConfig), - getPath("InputEmptyFile.txt"), - expected); - } - - @Test - public void testWrongFile() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class); - NewlineAtEndOfFileCheck check = new NewlineAtEndOfFileCheck(); - check.configure(checkConfig); - File impossibleFile = new File(""); - Set messages = check.process(impossibleFile, Lists.newArrayList("txt")); - assertTrue(messages.size() == 1); - Iterator iter = messages.iterator(); - assertEquals(iter.next().getMessage(), "Unable to open ''."); - } - - @Test - public void testWrongSeparatorLength() throws Exception { - NewlineAtEndOfFileCheck check = new NewlineAtEndOfFileCheck(); - final DefaultConfiguration checkConfig = createCheckConfig(NewlineAtEndOfFileCheck.class); - check.configure(checkConfig); - - Method method = NewlineAtEndOfFileCheck.class - .getDeclaredMethod("endsWithNewline", RandomAccessFile.class); - method.setAccessible(true); - RandomAccessFile file = mock(RandomAccessFile.class); - when(file.length()).thenReturn(2000000L); - try { - method.invoke(new NewlineAtEndOfFileCheck(), file); - } - catch (InvocationTargetException ex) { - assertTrue(ex.getCause() instanceof IOException); - if (System.getProperty("os.name").toLowerCase().startsWith("windows")) { - assertEquals(ex.getCause().getMessage(), "Unable to read 2 bytes, got 0"); - } - else { - assertEquals(ex.getCause().getMessage(), "Unable to read 1 bytes, got 0"); - } - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/pair.info deleted file mode 100755 index bb633c0..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#48988/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:48988 -comSha:ee7d6e9df391945a64c23210cd0fdc1a58fb7d95 -parentComSha:9ce956473be0ec029ee6738fb284659c17698518 -BuggyFilePath:src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java -FixedFilePath:src/test/java/com/puppycrawl/tools/checkstyle/checks/NewlineAtEndOfFileCheckTest.java -StartLineNum:191 -EndLineNum:191 -repoName:checkstyle#checkstyle \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/comMsg.txt deleted file mode 100755 index 3f5bdd3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/comMsg.txt +++ /dev/null @@ -1,5 +0,0 @@ -Listen: kleinere Schrift, falls Einträge zu lang verbessert - -Elternmithilfe: Nur erfassbar, falls noch nicht bei Geschwister erfasst - -Elternmithilfe-Liste: Korrekte Sortierung, auch wenn Vater anderen Nachnamen als Schüler hat \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/diff.diff deleted file mode 100755 index 09f2b0d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/ch/metzenthin/svm/domain/model/ListenExportModelImpl.java b/src/main/java/ch/metzenthin/svm/domain/model/ListenExportModelImpl.java -index f394f9c..ab0db69 100644 ---- a/src/main/java/ch/metzenthin/svm/domain/model/ListenExportModelImpl.java -+++ b/src/main/java/ch/metzenthin/svm/domain/model/ListenExportModelImpl.java -@@ -166 +166 @@ public class ListenExportModelImpl extends AbstractModel implements ListenExport -- titleInit = titleInit + " Gruppe " + schuelerSuchenTableModel.getGruppe().toString().toUpperCase(); -+ titleInit = titleInit + " Gruppe " + schuelerSuchenTableModel.getGruppe().toString(); -@@ -175 +175 @@ public class ListenExportModelImpl extends AbstractModel implements ListenExport -- titleInit = titleInit + " Gruppe " + schuelerSuchenTableModel.getGruppe().toString().toUpperCase(); -+ titleInit = titleInit + " Gruppe " + schuelerSuchenTableModel.getGruppe().toString(); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/new/ListenExportModelImpl.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/new/ListenExportModelImpl.java deleted file mode 100755 index ab0db69..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/new/ListenExportModelImpl.java +++ /dev/null @@ -1,223 +0,0 @@ -package ch.metzenthin.svm.domain.model; - -import ch.metzenthin.svm.common.dataTypes.Field; -import ch.metzenthin.svm.common.dataTypes.Listentyp; -import ch.metzenthin.svm.common.utils.SvmProperties; -import ch.metzenthin.svm.domain.SvmRequiredException; -import ch.metzenthin.svm.domain.SvmValidationException; -import ch.metzenthin.svm.domain.commands.*; -import ch.metzenthin.svm.persistence.entities.Kurs; -import ch.metzenthin.svm.ui.componentmodel.KurseTableModel; -import ch.metzenthin.svm.ui.componentmodel.LehrkraefteTableModel; -import ch.metzenthin.svm.ui.componentmodel.SchuelerSuchenTableModel; - -import java.io.File; -import java.util.Properties; - -import static ch.metzenthin.svm.common.utils.Converter.asString; - -/** - * @author Martin Schraner - */ -public class ListenExportModelImpl extends AbstractModel implements ListenExportModel { - - private Listentyp listentyp; - private String titel; - private File templateFile; - - public ListenExportModelImpl(CommandInvoker commandInvoker) { - super(commandInvoker); - } - - @Override - public Listentyp getListentyp() { - return listentyp; - } - - @Override - public void setListentyp(Listentyp listentyp) throws SvmRequiredException { - Listentyp oldValue = this.listentyp; - this.listentyp = listentyp; - firePropertyChange(Field.LISTENTYP, oldValue, this.listentyp); - if (listentyp == null) { - invalidate(); - throw new SvmRequiredException(Field.LISTENTYP); - } - } - - private final StringModelAttribute titelModelAttribute = new StringModelAttribute( - this, - Field.TITEL, 2, 110, - new AttributeAccessor() { - @Override - public String getValue() { - return titel; - } - - @Override - public void setValue(String value) { - titel = value; - } - } - ); - - @Override - public String getTitel() { - return titelModelAttribute.getValue(); - } - - @Override - public File getTemplateFile() { - return templateFile; - } - - @Override - public void setTitel(String titel) throws SvmValidationException { - titelModelAttribute.setNewValue(true, titel, isBulkUpdate()); - } - - @Override - public File getSaveFileInit() { - Properties prop = SvmProperties.getSvmProperties(); - File listenDirectoryInit = new File(prop.getProperty(SvmProperties.KEY_DEFAULT_OUTPUT_DIRECTORY) + File.separator); - if (!listenDirectoryInit.exists()) { - boolean success = listenDirectoryInit.mkdirs(); - if (!success) { - return null; - } - } - String outputFile = listentyp + "." + listentyp.getFiletyp().getFileExtension(); - outputFile = outputFile.replaceAll("\\p{Blank}", "_"); - outputFile = outputFile.replaceAll("ä", "ae"); - outputFile = outputFile.replaceAll("ö", "oe"); - outputFile = outputFile.replaceAll("ü", "ue"); - return new File(listenDirectoryInit.getAbsolutePath() + File.separator + outputFile); - } - - @Override - public CreateListeCommand.Result createListenFile(File outputFile, SchuelerSuchenTableModel schuelerSuchenTableModel, LehrkraefteTableModel lehrkraefteTableModel, KurseTableModel kurseTableModel) { - CommandInvoker commandInvoker = getCommandInvoker(); - CreateListeCommand.Result result = null; - switch (listentyp) { - case SCHUELER_ADRESSLISTE: - CreateSchuelerAdresslisteCommand createSchuelerAdresslisteCommand = new CreateSchuelerAdresslisteCommand(schuelerSuchenTableModel, titel, outputFile); - commandInvoker.executeCommand(createSchuelerAdresslisteCommand); - result = createSchuelerAdresslisteCommand.getResult(); - break; - case SCHUELER_ABSENZENLISTE: - CreateListeFromTemplateCommand createListeFromTemplateCommand = new CreateListeFromTemplateCommand(schuelerSuchenTableModel, titel, listentyp, outputFile); - commandInvoker.executeCommand(createListeFromTemplateCommand); - templateFile = createListeFromTemplateCommand.getTemplateFile(); - result = createListeFromTemplateCommand.getResult(); - break; - case SCHUELER_ADRESSETIKETTEN: - CreateAdressenCsvFileCommand createAdressenCsvFileCommandSchueler = new CreateAdressenCsvFileCommand(schuelerSuchenTableModel.getSchuelerList(), outputFile); - commandInvoker.executeCommand(createAdressenCsvFileCommandSchueler); - result = createAdressenCsvFileCommandSchueler.getResult(); - break; - case ROLLENLISTE: - CreateRollenlisteCommand createRollenlisteCommand = new CreateRollenlisteCommand(schuelerSuchenTableModel, titel, outputFile); - commandInvoker.executeCommand(createRollenlisteCommand); - result = createRollenlisteCommand.getResult(); - break; - case ELTERNMITHILFE_LISTE: - CreateElternmithilfeListeCommand createElternmithilfeListeCommand = new CreateElternmithilfeListeCommand(schuelerSuchenTableModel, titel, outputFile); - commandInvoker.executeCommand(createElternmithilfeListeCommand); - result = createElternmithilfeListeCommand.getResult(); - break; - case LEHRKRAEFTE_ADRESSLISTE: - CreateLehrkraefteAdresslisteCommand createLehrkraefteAdresslisteCommand = new CreateLehrkraefteAdresslisteCommand(lehrkraefteTableModel, titel, outputFile); - commandInvoker.executeCommand(createLehrkraefteAdresslisteCommand); - result = createLehrkraefteAdresslisteCommand.getResult(); - break; - case LEHRKRAEFTE_ADRESSETIKETTEN: - CreateAdressenCsvFileCommand createAdressenCsvFileCommandLehrkraefte = new CreateAdressenCsvFileCommand(lehrkraefteTableModel.getLehrkraefte(), outputFile); - commandInvoker.executeCommand(createAdressenCsvFileCommandLehrkraefte); - result = createAdressenCsvFileCommandLehrkraefte.getResult(); - break; - case KURSELISTE: - CreateKurselisteCommand kurselisteCommand = new CreateKurselisteCommand(kurseTableModel, titel, outputFile); - commandInvoker.executeCommand(kurselisteCommand); - result = kurselisteCommand.getResult(); - break; - } - return result; - } - - @Override - public String getTitleInit(SchuelerSuchenTableModel schuelerSuchenTableModel) { - String titleInit = ""; - switch (listentyp) { - case SCHUELER_ADRESSLISTE: - if (schuelerSuchenTableModel.getLehrkraft() != null) { - titleInit = getTitleSpecificKurs(schuelerSuchenTableModel); - } else { - titleInit = "Adressliste"; - } - break; - case SCHUELER_ABSENZENLISTE: - titleInit = getTitleSpecificKurs(schuelerSuchenTableModel); - break; - case SCHUELER_ADRESSETIKETTEN: - break; - case ROLLENLISTE: - titleInit = getTitleMaerchen(schuelerSuchenTableModel) + ": Rollenliste"; - if (schuelerSuchenTableModel.getGruppe() != null) { - titleInit = titleInit + " Gruppe " + schuelerSuchenTableModel.getGruppe().toString(); - } - break; - case ELTERNMITHILFE_LISTE: - titleInit = getTitleMaerchen(schuelerSuchenTableModel) + ": Eltern-Mithilfe"; - if (schuelerSuchenTableModel.getElternmithilfeCode() != null) { - titleInit = titleInit + " " + schuelerSuchenTableModel.getElternmithilfeCode().getBeschreibung(); - } - if (schuelerSuchenTableModel.getGruppe() != null) { - titleInit = titleInit + " Gruppe " + schuelerSuchenTableModel.getGruppe().toString(); - } - break; - case LEHRKRAEFTE_ADRESSLISTE: - titleInit = "Lehrkräfte"; - break; - case LEHRKRAEFTE_ADRESSETIKETTEN: - break; - case KURSELISTE: - titleInit = "Kurse"; - break; - } - return titleInit; - } - - private String getTitleSpecificKurs(SchuelerSuchenTableModel schuelerSuchenTableModel) { - if (schuelerSuchenTableModel.getWochentag() != null && schuelerSuchenTableModel.getZeitBeginn() != null) { - if (schuelerSuchenTableModel.getSchuelerList().size() > 0) { - String lehrkraefte = schuelerSuchenTableModel.getSchuelerList().get(0).getKurseAsList().get(0).getLehrkraefteAsStr(); - String zeitEnde = asString(schuelerSuchenTableModel.getSchuelerList().get(0).getKurseAsList().get(0).getZeitEnde()); - String kursort = schuelerSuchenTableModel.getSchuelerList().get(0).getKurseAsList().get(0).getKursort().getBezeichnung(); - return lehrkraefte + " (" + schuelerSuchenTableModel.getWochentag() + " " + asString(schuelerSuchenTableModel.getZeitBeginn()) + "-" + zeitEnde + ", " + kursort + ")"; - } else { - CommandInvoker commandInvoker = getCommandInvoker(); - FindKursCommand findKursCommand = new FindKursCommand(schuelerSuchenTableModel.getSemester(), schuelerSuchenTableModel.getWochentag(), schuelerSuchenTableModel.getZeitBeginn(), schuelerSuchenTableModel.getLehrkraft()); - commandInvoker.executeCommand(findKursCommand); - if (findKursCommand.getResult() == FindKursCommand.Result.KURS_EXISTIERT_NICHT) { - return ""; - } - Kurs kursFound = findKursCommand.getKursFound(); - return kursFound.getLehrkraefteAsStr() + " (" + kursFound.getWochentag() + " " + asString(kursFound.getZeitBeginn()) + "-" + asString(kursFound.getZeitEnde()) + ", " + kursFound.getKursort() + ")"; - } - } else { - return schuelerSuchenTableModel.getLehrkraft().toString(); - } - } - - private String getTitleMaerchen(SchuelerSuchenTableModel schuelerSuchenTableModel) { - return schuelerSuchenTableModel.getMaerchen().getBezeichnung(); - } - - @Override - public boolean isCompleted() { - return true; - } - - @Override - void doValidate() throws SvmValidationException {} -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/old/ListenExportModelImpl.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/old/ListenExportModelImpl.java deleted file mode 100755 index f394f9c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/old/ListenExportModelImpl.java +++ /dev/null @@ -1,223 +0,0 @@ -package ch.metzenthin.svm.domain.model; - -import ch.metzenthin.svm.common.dataTypes.Field; -import ch.metzenthin.svm.common.dataTypes.Listentyp; -import ch.metzenthin.svm.common.utils.SvmProperties; -import ch.metzenthin.svm.domain.SvmRequiredException; -import ch.metzenthin.svm.domain.SvmValidationException; -import ch.metzenthin.svm.domain.commands.*; -import ch.metzenthin.svm.persistence.entities.Kurs; -import ch.metzenthin.svm.ui.componentmodel.KurseTableModel; -import ch.metzenthin.svm.ui.componentmodel.LehrkraefteTableModel; -import ch.metzenthin.svm.ui.componentmodel.SchuelerSuchenTableModel; - -import java.io.File; -import java.util.Properties; - -import static ch.metzenthin.svm.common.utils.Converter.asString; - -/** - * @author Martin Schraner - */ -public class ListenExportModelImpl extends AbstractModel implements ListenExportModel { - - private Listentyp listentyp; - private String titel; - private File templateFile; - - public ListenExportModelImpl(CommandInvoker commandInvoker) { - super(commandInvoker); - } - - @Override - public Listentyp getListentyp() { - return listentyp; - } - - @Override - public void setListentyp(Listentyp listentyp) throws SvmRequiredException { - Listentyp oldValue = this.listentyp; - this.listentyp = listentyp; - firePropertyChange(Field.LISTENTYP, oldValue, this.listentyp); - if (listentyp == null) { - invalidate(); - throw new SvmRequiredException(Field.LISTENTYP); - } - } - - private final StringModelAttribute titelModelAttribute = new StringModelAttribute( - this, - Field.TITEL, 2, 110, - new AttributeAccessor() { - @Override - public String getValue() { - return titel; - } - - @Override - public void setValue(String value) { - titel = value; - } - } - ); - - @Override - public String getTitel() { - return titelModelAttribute.getValue(); - } - - @Override - public File getTemplateFile() { - return templateFile; - } - - @Override - public void setTitel(String titel) throws SvmValidationException { - titelModelAttribute.setNewValue(true, titel, isBulkUpdate()); - } - - @Override - public File getSaveFileInit() { - Properties prop = SvmProperties.getSvmProperties(); - File listenDirectoryInit = new File(prop.getProperty(SvmProperties.KEY_DEFAULT_OUTPUT_DIRECTORY) + File.separator); - if (!listenDirectoryInit.exists()) { - boolean success = listenDirectoryInit.mkdirs(); - if (!success) { - return null; - } - } - String outputFile = listentyp + "." + listentyp.getFiletyp().getFileExtension(); - outputFile = outputFile.replaceAll("\\p{Blank}", "_"); - outputFile = outputFile.replaceAll("ä", "ae"); - outputFile = outputFile.replaceAll("ö", "oe"); - outputFile = outputFile.replaceAll("ü", "ue"); - return new File(listenDirectoryInit.getAbsolutePath() + File.separator + outputFile); - } - - @Override - public CreateListeCommand.Result createListenFile(File outputFile, SchuelerSuchenTableModel schuelerSuchenTableModel, LehrkraefteTableModel lehrkraefteTableModel, KurseTableModel kurseTableModel) { - CommandInvoker commandInvoker = getCommandInvoker(); - CreateListeCommand.Result result = null; - switch (listentyp) { - case SCHUELER_ADRESSLISTE: - CreateSchuelerAdresslisteCommand createSchuelerAdresslisteCommand = new CreateSchuelerAdresslisteCommand(schuelerSuchenTableModel, titel, outputFile); - commandInvoker.executeCommand(createSchuelerAdresslisteCommand); - result = createSchuelerAdresslisteCommand.getResult(); - break; - case SCHUELER_ABSENZENLISTE: - CreateListeFromTemplateCommand createListeFromTemplateCommand = new CreateListeFromTemplateCommand(schuelerSuchenTableModel, titel, listentyp, outputFile); - commandInvoker.executeCommand(createListeFromTemplateCommand); - templateFile = createListeFromTemplateCommand.getTemplateFile(); - result = createListeFromTemplateCommand.getResult(); - break; - case SCHUELER_ADRESSETIKETTEN: - CreateAdressenCsvFileCommand createAdressenCsvFileCommandSchueler = new CreateAdressenCsvFileCommand(schuelerSuchenTableModel.getSchuelerList(), outputFile); - commandInvoker.executeCommand(createAdressenCsvFileCommandSchueler); - result = createAdressenCsvFileCommandSchueler.getResult(); - break; - case ROLLENLISTE: - CreateRollenlisteCommand createRollenlisteCommand = new CreateRollenlisteCommand(schuelerSuchenTableModel, titel, outputFile); - commandInvoker.executeCommand(createRollenlisteCommand); - result = createRollenlisteCommand.getResult(); - break; - case ELTERNMITHILFE_LISTE: - CreateElternmithilfeListeCommand createElternmithilfeListeCommand = new CreateElternmithilfeListeCommand(schuelerSuchenTableModel, titel, outputFile); - commandInvoker.executeCommand(createElternmithilfeListeCommand); - result = createElternmithilfeListeCommand.getResult(); - break; - case LEHRKRAEFTE_ADRESSLISTE: - CreateLehrkraefteAdresslisteCommand createLehrkraefteAdresslisteCommand = new CreateLehrkraefteAdresslisteCommand(lehrkraefteTableModel, titel, outputFile); - commandInvoker.executeCommand(createLehrkraefteAdresslisteCommand); - result = createLehrkraefteAdresslisteCommand.getResult(); - break; - case LEHRKRAEFTE_ADRESSETIKETTEN: - CreateAdressenCsvFileCommand createAdressenCsvFileCommandLehrkraefte = new CreateAdressenCsvFileCommand(lehrkraefteTableModel.getLehrkraefte(), outputFile); - commandInvoker.executeCommand(createAdressenCsvFileCommandLehrkraefte); - result = createAdressenCsvFileCommandLehrkraefte.getResult(); - break; - case KURSELISTE: - CreateKurselisteCommand kurselisteCommand = new CreateKurselisteCommand(kurseTableModel, titel, outputFile); - commandInvoker.executeCommand(kurselisteCommand); - result = kurselisteCommand.getResult(); - break; - } - return result; - } - - @Override - public String getTitleInit(SchuelerSuchenTableModel schuelerSuchenTableModel) { - String titleInit = ""; - switch (listentyp) { - case SCHUELER_ADRESSLISTE: - if (schuelerSuchenTableModel.getLehrkraft() != null) { - titleInit = getTitleSpecificKurs(schuelerSuchenTableModel); - } else { - titleInit = "Adressliste"; - } - break; - case SCHUELER_ABSENZENLISTE: - titleInit = getTitleSpecificKurs(schuelerSuchenTableModel); - break; - case SCHUELER_ADRESSETIKETTEN: - break; - case ROLLENLISTE: - titleInit = getTitleMaerchen(schuelerSuchenTableModel) + ": Rollenliste"; - if (schuelerSuchenTableModel.getGruppe() != null) { - titleInit = titleInit + " Gruppe " + schuelerSuchenTableModel.getGruppe().toString().toUpperCase(); - } - break; - case ELTERNMITHILFE_LISTE: - titleInit = getTitleMaerchen(schuelerSuchenTableModel) + ": Eltern-Mithilfe"; - if (schuelerSuchenTableModel.getElternmithilfeCode() != null) { - titleInit = titleInit + " " + schuelerSuchenTableModel.getElternmithilfeCode().getBeschreibung(); - } - if (schuelerSuchenTableModel.getGruppe() != null) { - titleInit = titleInit + " Gruppe " + schuelerSuchenTableModel.getGruppe().toString().toUpperCase(); - } - break; - case LEHRKRAEFTE_ADRESSLISTE: - titleInit = "Lehrkräfte"; - break; - case LEHRKRAEFTE_ADRESSETIKETTEN: - break; - case KURSELISTE: - titleInit = "Kurse"; - break; - } - return titleInit; - } - - private String getTitleSpecificKurs(SchuelerSuchenTableModel schuelerSuchenTableModel) { - if (schuelerSuchenTableModel.getWochentag() != null && schuelerSuchenTableModel.getZeitBeginn() != null) { - if (schuelerSuchenTableModel.getSchuelerList().size() > 0) { - String lehrkraefte = schuelerSuchenTableModel.getSchuelerList().get(0).getKurseAsList().get(0).getLehrkraefteAsStr(); - String zeitEnde = asString(schuelerSuchenTableModel.getSchuelerList().get(0).getKurseAsList().get(0).getZeitEnde()); - String kursort = schuelerSuchenTableModel.getSchuelerList().get(0).getKurseAsList().get(0).getKursort().getBezeichnung(); - return lehrkraefte + " (" + schuelerSuchenTableModel.getWochentag() + " " + asString(schuelerSuchenTableModel.getZeitBeginn()) + "-" + zeitEnde + ", " + kursort + ")"; - } else { - CommandInvoker commandInvoker = getCommandInvoker(); - FindKursCommand findKursCommand = new FindKursCommand(schuelerSuchenTableModel.getSemester(), schuelerSuchenTableModel.getWochentag(), schuelerSuchenTableModel.getZeitBeginn(), schuelerSuchenTableModel.getLehrkraft()); - commandInvoker.executeCommand(findKursCommand); - if (findKursCommand.getResult() == FindKursCommand.Result.KURS_EXISTIERT_NICHT) { - return ""; - } - Kurs kursFound = findKursCommand.getKursFound(); - return kursFound.getLehrkraefteAsStr() + " (" + kursFound.getWochentag() + " " + asString(kursFound.getZeitBeginn()) + "-" + asString(kursFound.getZeitEnde()) + ", " + kursFound.getKursort() + ")"; - } - } else { - return schuelerSuchenTableModel.getLehrkraft().toString(); - } - } - - private String getTitleMaerchen(SchuelerSuchenTableModel schuelerSuchenTableModel) { - return schuelerSuchenTableModel.getMaerchen().getBezeichnung(); - } - - @Override - public boolean isCompleted() { - return true; - } - - @Override - void doValidate() throws SvmValidationException {} -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/pair.info deleted file mode 100755 index b39f09c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#49777/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:49777 -comSha:ee15109108f67f0463520a7872941d99d206a868 -parentComSha:148b80b092f21edff2c233a9a82be37eb5eb2014 -BuggyFilePath:src/main/java/ch/metzenthin/svm/domain/model/ListenExportModelImpl.java -FixedFilePath:src/main/java/ch/metzenthin/svm/domain/model/ListenExportModelImpl.java -StartLineNum:166 -EndLineNum:166 -repoName:marschraner#svm \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/comMsg.txt deleted file mode 100755 index 197a716..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of DM_CONVERT_CASE from FindBugs. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/diff.diff deleted file mode 100755 index 180ead5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java b/util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -index 22e8d712..777346c6 100644 ---- a/util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -+++ b/util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -@@ -6,0 +7 @@ import java.util.Iterator; -+import java.util.Locale; -@@ -75 +76 @@ public class HttpServletRequestMap implements Map { -- String key = headerName.toUpperCase().replace('-', '_'); -+ String key = headerName.toUpperCase(Locale.ENGLISH).replace('-', '_'); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/new/HttpServletRequestMap.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/new/HttpServletRequestMap.java deleted file mode 100755 index 777346c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/new/HttpServletRequestMap.java +++ /dev/null @@ -1,217 +0,0 @@ -package com.psddev.dari.util; - -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - -/** @deprecated No replacement. */ -@Deprecated -@SuppressWarnings("all") -public class HttpServletRequestMap implements Map { - - public static final String AUTHORIZATION_KEY = "AUTHORIZATION"; - public static final String AUTH_TYPE_KEY = "AUTH_TYPE"; - public static final String CONTENT_LENGTH_KEY = "CONTENT_LENGTH"; - public static final String CONTENT_TYPE_KEY = "CONTENT_TYPE"; - public static final String GATEWAY_INTERFACE_KEY = "GATEWAY_INTERFACE"; - public static final String HTTP_PREFIX = "HTTP_"; - public static final String PATH_INFO_KEY = "PATH_INFO"; - public static final String PATH_TRANSLATED_KEY = "PATH_TRANSLATED"; - public static final String PROXY_AUTHORIZATION_KEY = "PROXY_AUTHORIZATION"; - public static final String QUERY_STRING_KEY = "QUERY_STRING"; - public static final String REMOTE_ADDR_KEY = "REMOTE_ADDR"; - public static final String REMOTE_HOST_KEY = "REMOTE_HOST"; - public static final String REMOTE_USER_KEY = "REMOTE_USER"; - public static final String REQUEST_METHOD_KEY = "REQUEST_METHOD"; - public static final String REQUEST_URI_KEY = "REQUEST_URI"; - public static final String SCRIPT_NAME_KEY = "SCRIPT_NAME"; - public static final String SERVER_NAME_KEY = "SERVER_NAME"; - public static final String SERVER_PORT_KEY = "SERVER_PORT"; - public static final String SERVER_PROTOCOL_KEY = "SERVER_PROTOCOL"; - public static final String SERVER_SOFTWARE_KEY = "SERVER_SOFTWARE"; - - private final ServletContext context; - private final HttpServletRequest request; - private final Map all = new HashMap(); - private final Map lazies = new HashMap(); - - /** - * Creates an instance based on the given {@code context} and - * {@code request}. - */ - public HttpServletRequestMap(ServletContext context, HttpServletRequest request) { - - this.context = context; - this.request = request; - - all.put(AUTH_TYPE_KEY, request.getAuthType()); - all.put(CONTENT_TYPE_KEY, request.getContentType()); - all.put(GATEWAY_INTERFACE_KEY, "CGI/1.1"); - all.put(PATH_INFO_KEY, request.getPathInfo()); - all.put(QUERY_STRING_KEY, request.getQueryString()); - all.put(REMOTE_ADDR_KEY, request.getRemoteAddr()); - all.put(REMOTE_USER_KEY, request.getRemoteUser()); - all.put(REQUEST_METHOD_KEY, request.getMethod()); - all.put(REQUEST_URI_KEY, request.getRequestURI()); - all.put(SCRIPT_NAME_KEY, request.getServletPath()); - all.put(SERVER_NAME_KEY, request.getServerName()); - all.put(SERVER_PROTOCOL_KEY, request.getProtocol()); - all.put(SERVER_SOFTWARE_KEY, context.getServerInfo()); - - int contentLength = request.getContentLength(); - all.put(CONTENT_LENGTH_KEY, contentLength > 0 ? String.valueOf(contentLength) : null); - - int port = request.getServerPort(); - all.put(SERVER_PORT_KEY, String.valueOf(port == 0 ? -1 : port)); - - for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) { - String headerName = e.nextElement(); - String key = headerName.toUpperCase(Locale.ENGLISH).replace('-', '_'); - if (!(AUTHORIZATION_KEY.equals(key) - || PROXY_AUTHORIZATION_KEY.equals(key))) { - all.put(HTTP_PREFIX + key, request.getHeader(headerName)); - } - } - - lazies.put(PATH_TRANSLATED_KEY, new Lazy() { - - @Override - public Object resolve(String key) { - return HttpServletRequestMap.this.request.getPathTranslated(); - } - }); - - lazies.put(REMOTE_HOST_KEY, new Lazy() { - - @Override - public Object resolve(String key) { - return HttpServletRequestMap.this.request.getRemoteHost(); - } - }); - } - - /** Resolves all the lazy values. */ - private void resolveAll() { - for (Iterator> i = lazies.entrySet().iterator(); i.hasNext(); ) { - Map.Entry e = i.next(); - i.remove(); - String key = e.getKey(); - Object value = e.getValue().resolve(key); - all.put(key, ObjectUtils.isBlank(value) ? null : value.toString()); - } - } - - // --- Map support --- - - @Override - public void clear() { - all.clear(); - lazies.clear(); - } - - @Override - public boolean containsKey(Object key) { - return all.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - resolveAll(); - return all.containsValue(value); - } - - @Override - public Set> entrySet() { - resolveAll(); - return all.entrySet(); - } - - @Override - public String get(Object key) { - Lazy lazy = lazies.get(key); - if (lazy != null) { - lazies.remove(key); - String keyString = (String) key; - Object value = lazy.resolve(keyString); - all.put(keyString, ObjectUtils.isBlank(value) ? null : value.toString()); - } - return all.get(key); - } - - @Override - public boolean isEmpty() { - return all.isEmpty(); - } - - @Override - public Set keySet() { - return all.keySet(); - } - - @Override - public String put(String key, String value) { - lazies.remove(key); - return all.put(key, value); - } - - @Override - public void putAll(Map map) { - lazies.keySet().removeAll(map.keySet()); - all.putAll(map); - } - - @Override - public String remove(Object key) { - lazies.remove(key); - return all.remove(key); - } - - @Override - public int size() { - return all.size(); - } - - @Override - public Collection values() { - resolveAll(); - return all.values(); - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } else if (other instanceof Map) { - resolveAll(); - return all.equals(other); - } else { - return false; - } - } - - @Override - public int hashCode() { - resolveAll(); - return all.hashCode(); - } - - @Override - public String toString() { - resolveAll(); - return all.toString(); - } - - // --- Nested --- - - private interface Lazy { - - public Object resolve(String key); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/old/HttpServletRequestMap.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/old/HttpServletRequestMap.java deleted file mode 100755 index 22e8d71..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/old/HttpServletRequestMap.java +++ /dev/null @@ -1,216 +0,0 @@ -package com.psddev.dari.util; - -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - -/** @deprecated No replacement. */ -@Deprecated -@SuppressWarnings("all") -public class HttpServletRequestMap implements Map { - - public static final String AUTHORIZATION_KEY = "AUTHORIZATION"; - public static final String AUTH_TYPE_KEY = "AUTH_TYPE"; - public static final String CONTENT_LENGTH_KEY = "CONTENT_LENGTH"; - public static final String CONTENT_TYPE_KEY = "CONTENT_TYPE"; - public static final String GATEWAY_INTERFACE_KEY = "GATEWAY_INTERFACE"; - public static final String HTTP_PREFIX = "HTTP_"; - public static final String PATH_INFO_KEY = "PATH_INFO"; - public static final String PATH_TRANSLATED_KEY = "PATH_TRANSLATED"; - public static final String PROXY_AUTHORIZATION_KEY = "PROXY_AUTHORIZATION"; - public static final String QUERY_STRING_KEY = "QUERY_STRING"; - public static final String REMOTE_ADDR_KEY = "REMOTE_ADDR"; - public static final String REMOTE_HOST_KEY = "REMOTE_HOST"; - public static final String REMOTE_USER_KEY = "REMOTE_USER"; - public static final String REQUEST_METHOD_KEY = "REQUEST_METHOD"; - public static final String REQUEST_URI_KEY = "REQUEST_URI"; - public static final String SCRIPT_NAME_KEY = "SCRIPT_NAME"; - public static final String SERVER_NAME_KEY = "SERVER_NAME"; - public static final String SERVER_PORT_KEY = "SERVER_PORT"; - public static final String SERVER_PROTOCOL_KEY = "SERVER_PROTOCOL"; - public static final String SERVER_SOFTWARE_KEY = "SERVER_SOFTWARE"; - - private final ServletContext context; - private final HttpServletRequest request; - private final Map all = new HashMap(); - private final Map lazies = new HashMap(); - - /** - * Creates an instance based on the given {@code context} and - * {@code request}. - */ - public HttpServletRequestMap(ServletContext context, HttpServletRequest request) { - - this.context = context; - this.request = request; - - all.put(AUTH_TYPE_KEY, request.getAuthType()); - all.put(CONTENT_TYPE_KEY, request.getContentType()); - all.put(GATEWAY_INTERFACE_KEY, "CGI/1.1"); - all.put(PATH_INFO_KEY, request.getPathInfo()); - all.put(QUERY_STRING_KEY, request.getQueryString()); - all.put(REMOTE_ADDR_KEY, request.getRemoteAddr()); - all.put(REMOTE_USER_KEY, request.getRemoteUser()); - all.put(REQUEST_METHOD_KEY, request.getMethod()); - all.put(REQUEST_URI_KEY, request.getRequestURI()); - all.put(SCRIPT_NAME_KEY, request.getServletPath()); - all.put(SERVER_NAME_KEY, request.getServerName()); - all.put(SERVER_PROTOCOL_KEY, request.getProtocol()); - all.put(SERVER_SOFTWARE_KEY, context.getServerInfo()); - - int contentLength = request.getContentLength(); - all.put(CONTENT_LENGTH_KEY, contentLength > 0 ? String.valueOf(contentLength) : null); - - int port = request.getServerPort(); - all.put(SERVER_PORT_KEY, String.valueOf(port == 0 ? -1 : port)); - - for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) { - String headerName = e.nextElement(); - String key = headerName.toUpperCase().replace('-', '_'); - if (!(AUTHORIZATION_KEY.equals(key) - || PROXY_AUTHORIZATION_KEY.equals(key))) { - all.put(HTTP_PREFIX + key, request.getHeader(headerName)); - } - } - - lazies.put(PATH_TRANSLATED_KEY, new Lazy() { - - @Override - public Object resolve(String key) { - return HttpServletRequestMap.this.request.getPathTranslated(); - } - }); - - lazies.put(REMOTE_HOST_KEY, new Lazy() { - - @Override - public Object resolve(String key) { - return HttpServletRequestMap.this.request.getRemoteHost(); - } - }); - } - - /** Resolves all the lazy values. */ - private void resolveAll() { - for (Iterator> i = lazies.entrySet().iterator(); i.hasNext(); ) { - Map.Entry e = i.next(); - i.remove(); - String key = e.getKey(); - Object value = e.getValue().resolve(key); - all.put(key, ObjectUtils.isBlank(value) ? null : value.toString()); - } - } - - // --- Map support --- - - @Override - public void clear() { - all.clear(); - lazies.clear(); - } - - @Override - public boolean containsKey(Object key) { - return all.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - resolveAll(); - return all.containsValue(value); - } - - @Override - public Set> entrySet() { - resolveAll(); - return all.entrySet(); - } - - @Override - public String get(Object key) { - Lazy lazy = lazies.get(key); - if (lazy != null) { - lazies.remove(key); - String keyString = (String) key; - Object value = lazy.resolve(keyString); - all.put(keyString, ObjectUtils.isBlank(value) ? null : value.toString()); - } - return all.get(key); - } - - @Override - public boolean isEmpty() { - return all.isEmpty(); - } - - @Override - public Set keySet() { - return all.keySet(); - } - - @Override - public String put(String key, String value) { - lazies.remove(key); - return all.put(key, value); - } - - @Override - public void putAll(Map map) { - lazies.keySet().removeAll(map.keySet()); - all.putAll(map); - } - - @Override - public String remove(Object key) { - lazies.remove(key); - return all.remove(key); - } - - @Override - public int size() { - return all.size(); - } - - @Override - public Collection values() { - resolveAll(); - return all.values(); - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } else if (other instanceof Map) { - resolveAll(); - return all.equals(other); - } else { - return false; - } - } - - @Override - public int hashCode() { - resolveAll(); - return all.hashCode(); - } - - @Override - public String toString() { - resolveAll(); - return all.toString(); - } - - // --- Nested --- - - private interface Lazy { - - public Object resolve(String key); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/pair.info deleted file mode 100755 index e60bd3d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51202/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:51202 -comSha:641bc27d5470a167d3ca2fefd6ae4c619a27c012 -parentComSha:5f098cd76c5e7aff3237dc54664709c515095ad4 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -StartLineNum:75 -EndLineNum:75 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/comMsg.txt deleted file mode 100755 index ee04a0c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of PMD design.xml/UseLocaleWithCaseConversions. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/diff.diff deleted file mode 100755 index a020fbd..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/DimsImageEditor.java b/util/src/main/java/com/psddev/dari/util/DimsImageEditor.java -index 3d736f26..a7736137 100644 ---- a/util/src/main/java/com/psddev/dari/util/DimsImageEditor.java -+++ b/util/src/main/java/com/psddev/dari/util/DimsImageEditor.java -@@ -12,0 +13 @@ import java.util.ListIterator; -+import java.util.Locale; -@@ -506 +507 @@ public class DimsImageEditor extends AbstractImageEditor { -- if (imagePath.toLowerCase().endsWith(".gif")) { -+ if (imagePath.toLowerCase(Locale.ENGLISH).endsWith(".gif")) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/new/DimsImageEditor.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/new/DimsImageEditor.java deleted file mode 100755 index a773613..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/new/DimsImageEditor.java +++ /dev/null @@ -1,1256 +0,0 @@ -package com.psddev.dari.util; - -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Locale; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Image editor backed by - * mod_dims. - */ -public class DimsImageEditor extends AbstractImageEditor { - - protected static final Logger LOGGER = LoggerFactory.getLogger(DimsImageEditor.class); - - /** Setting key for the base URL to the mod_dims installation. */ - public static final String BASE_URL_SETTING = "baseUrl"; - - /** Setting key for the shared secret to use when signing URLs. */ - public static final String SHARED_SECRET_SETTING = "sharedSecret"; - - /** Setting key for the expiration date of a signed URL. Only one of either - * this setting or {@link #EXPIRE_DURATION_SETTING} should be set. */ - public static final String EXPIRE_TIMESTAMP_SETTING = "expireTimestamp"; - - /** Setting key for the expiration duration (in seconds) of a signed URL. - * Only one of either this setting or {@link #EXPIRE_TIMESTAMP_SETTING} - * should be set. */ - public static final String EXPIRE_DURATION_SETTING = "expireDuration"; - - /** Setting key for quality to use for the output images. */ - public static final String QUALITY_SETTING = "quality"; - - /** Setting key for enabling the use of DIMS' legacy crop command. */ - public static final String USE_LEGACY_CROP_SETTING = "useLegacyCrop"; - - /** Setting key for enabling the use of DIMS' legacy thumbnail command. */ - public static final String USE_LEGACY_THUMBNAIL_SETTING = "useLegacyThumbnail"; - - /** Setting key for enabling the preservation of the image's metadata. */ - public static final String PRESERVE_METADATA_SETTING = "preserveMetadata"; - - /** Setting key for enabling appending image URLs instead of passing them as a parater. */ - public static final String APPEND_IMAGE_URLS_SETTING = "appendImageUrls"; - - private String baseUrl; - private String sharedSecret; - - private Date expireTimestamp; - private Long expireDuration; - - private Integer quality; - private boolean useLegacyCrop; - private boolean useLegacyThumbnail; - private boolean preserveMetadata; - private boolean appendImageUrls; - - /** Returns the base URL. */ - public String getBaseUrl() { - return baseUrl; - } - - /** Sets the base URL. */ - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; - } - - public String getSharedSecret() { - return sharedSecret; - } - - public void setSharedSecret(String sharedSecret) { - this.sharedSecret = sharedSecret; - } - - public Date getExpireTimestamp() { - return expireTimestamp; - } - - public void setExpireTimestamp(Date expireTimestamp) { - this.expireTimestamp = expireTimestamp; - } - - public Long getExpireDuration() { - return expireDuration; - } - - public void setExpireDuration(Long expireDuration) { - this.expireDuration = expireDuration; - } - - public Integer getQuality() { - return quality; - } - - public void setQuality(Integer quality) { - this.quality = quality; - } - - public boolean isUseLegacyCrop() { - return useLegacyCrop; - } - - public void setUseLegacyCrop(boolean useLegacyCrop) { - this.useLegacyCrop = useLegacyCrop; - } - - public boolean isUseLegacyThumbnail() { - return useLegacyThumbnail; - } - - public void setUseLegacyThumbnail(boolean useLegacyThumbnail) { - this.useLegacyThumbnail = useLegacyThumbnail; - } - - public boolean isPreserveMetadata() { - return preserveMetadata; - } - - public void setPreserveMetadata(boolean preserveMetadata) { - this.preserveMetadata = preserveMetadata; - } - - public boolean isAppendImageUrls() { - return appendImageUrls; - } - - public void setAppendImageUrls(boolean appendImageUrls) { - this.appendImageUrls = appendImageUrls; - } - - // --- AbstractImageEditor support --- - - @Override - public void initialize(String settingsKey, Map settings) { - setBaseUrl(ObjectUtils.to(String.class, settings.get(BASE_URL_SETTING))); - setSharedSecret(ObjectUtils.to(String.class, settings.get(SHARED_SECRET_SETTING))); - - setExpireTimestamp(ObjectUtils.to(Date.class, settings.get(EXPIRE_TIMESTAMP_SETTING))); - setExpireDuration(ObjectUtils.to(Long.class, settings.get(EXPIRE_DURATION_SETTING))); - - setQuality(ObjectUtils.to(Integer.class, settings.get(QUALITY_SETTING))); - - setUseLegacyCrop(ObjectUtils.to(boolean.class, settings.get(USE_LEGACY_CROP_SETTING))); - setUseLegacyThumbnail(ObjectUtils.to(boolean.class, settings.get(USE_LEGACY_THUMBNAIL_SETTING))); - setPreserveMetadata(ObjectUtils.to(boolean.class, settings.get(PRESERVE_METADATA_SETTING))); - setAppendImageUrls(ObjectUtils.to(boolean.class, settings.get(APPEND_IMAGE_URLS_SETTING))); - } - - @Override - public StorageItem edit( - StorageItem image, - String command, - Map options, - Object... arguments) { - - StorageItem newImage = null; - - DimsUrl dimsUrl = null; - try { - dimsUrl = this.new DimsUrl(image); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - } - if (dimsUrl != null) { - Object resizeOption = options != null ? options.get(ImageEditor.RESIZE_OPTION) : null; - Object cropOption = options != null ? options.get(ImageEditor.CROP_OPTION) : null; - - if (ImageEditor.CROP_COMMAND.equals(command)) { - Object x = arguments[0]; - Object y = arguments[1]; - Object width = arguments[2]; - Object height = arguments[3]; - - /* - * This logic is a bit confusing, but is here to preserve backward compatibility. ImageEditor.CROP_OPTION_AUTOMATIC - * is new and is meant to signify that no matter what, all crops should be done that way, regardless of whether other - * parameters like the x & y coordinates are present. It is synonymous with the DIMS thumbnail command which does - * a resize AND crop in a single operation. Before its addition, the behavior was such that if there were crop - * dimensions (x, y, width, height) defined then a normal crop would take place. If however, only the width and height - * are present then an "Automatic" crop (thumbnail command) would be done in its place. - */ - - if (ImageEditor.CROP_OPTION_AUTOMATIC.equals(cropOption) || (cropOption == null && x == null && y == null)) { - dimsUrl.thumbnail(width, height, resizeOption); - - } else if (ImageEditor.CROP_OPTION_NONE.equals(cropOption)) { - // don't do any cropping, just return the image. - return image; - - } else { - // the x & y coordinates cannot be null, otherwise just - // return the original image unchanged - if (x != null && y != null) { - dimsUrl.crop(x, y, width, height); - } else { - return image; - } - } - } else if (ImageEditor.RESIZE_COMMAND.equals(command)) { - - Integer width = ObjectUtils.to(Integer.class, arguments[0]); - Integer height = ObjectUtils.to(Integer.class, arguments[1]); - - /* - * Check the last command and if it was a thumbnail command - * with the same width and height as the arguments then don't do - * anything and just return the old URL "as is" since the - * thumbnail command already did both a crop AND a resize. - * - * We go into this if block even when the cropOption is null - * due to backward compatibility. See the block comment above. - */ - - if (ImageEditor.CROP_OPTION_AUTOMATIC.equals(cropOption) || cropOption == null) { - - Command lastResizeCommand = dimsUrl.getLastResizeCommand(); - if (lastResizeCommand instanceof ThumbnailCommand) { - ThumbnailCommand thumbnailCommand = (ThumbnailCommand) lastResizeCommand; - - Integer thumbnailWidth = thumbnailCommand.getWidth(); - Integer thumbnailHeight = thumbnailCommand.getHeight(); - - if (width != null && height != null && - width.equals(thumbnailWidth) && height.equals(thumbnailHeight)) { - return image; - } - } - } - - dimsUrl.resize(width, height, resizeOption); - - } else if ("brightness".equals(command)) { - Double brightness = ObjectUtils.to(Double.class, arguments[0]); - if (brightness != null) { - dimsUrl.addCommand(new BrightnessCommand((int) (brightness * 100 / 1.5), 0)); - } - - } else if ("contrast".equals(command)) { - Double contrast = ObjectUtils.to(Double.class, arguments[0]); - if (contrast != null) { - dimsUrl.addCommand(new BrightnessCommand(0, (int) (contrast * 100))); - } - - } else if ("flipH".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new FlipFlopCommand("horizontal")); - } - - } else if ("flipV".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new FlipFlopCommand("vertical")); - } - - } else if ("grayscale".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new GrayscaleCommand(true)); - } - - } else if ("invert".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new InvertCommand(true)); - } - - } else if ("rotate".equals(command)) { - Integer angle = ObjectUtils.to(Integer.class, arguments[0]); - if (angle != null) { - dimsUrl.addCommand(new RotateCommand(angle)); - } - - } else if ("sepia".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new SepiaCommand(0.8)); - } - } - - Command lastResizeCommand = dimsUrl.getLastResizeCommand(); - if (lastResizeCommand instanceof AbstractResizeCommand) { - AbstractResizeCommand lastResize = (AbstractResizeCommand) lastResizeCommand; - - StorageItem override = StorageItem.Static.createIn(image.getStorage()); - new ObjectMap(override).putAll(new ObjectMap(image)); - - boolean overridden = ImageResizeStorageItemListener.overridePathWithNearestSize(override, - lastResize.getWidth(), - lastResize.getHeight()); - - if (overridden) { - try { - dimsUrl.setImageUrl(new URL(override.getPublicUrl())); - } catch(MalformedURLException mue) { - } - } - } - - newImage = dimsUrl.toStorageItem(); - } - - if (newImage != null) { - return newImage; - } else { // failed to create a new DimsUrl so return the original - return image; - } - } - - private class DimsUrl { - - /** DIMS specific path to the original width of the image in the metadata */ - private static final String ORIGINAL_WIDTH_METADATA_PATH = "dims/originalWidth"; - - /** DIMS specific Path to the original height of the image in the metadata */ - private static final String ORIGINAL_HEIGHT_METADATA_PATH = "dims/originalHeight"; - - private List commands; - private final StorageItem item; - private URL imageUrl; - - public void setImageUrl(URL imageUrl) { - this.imageUrl = imageUrl; - } - - public DimsUrl(StorageItem item) throws MalformedURLException { - this.item = item; - - String url = item.getPublicUrl(); - LOGGER.trace("Creating new DIMS URL from [" + url + "]"); - if (url == null) { - throw new MalformedURLException("Cannot create DIMS URL for item [" + item + "] with url [null]"); - } - - String baseUrl = DimsImageEditor.this.getBaseUrl(); - if (url.startsWith(baseUrl)) { - - // It's an existing DIMS URL that we're further modifying - - String commandsString = null; - - int commandsOffset = baseUrl.length()+1; - if (DimsImageEditor.this.getSharedSecret() != null && baseUrl.contains("/dims4/")) { - - int slashAt = url.indexOf('/', commandsOffset); - commandsOffset = url.indexOf('/', slashAt+1) + 1; - } - - if (DimsImageEditor.this.isAppendImageUrls()) { - int httpAt = url.indexOf("http", 1); - commandsString = url.substring(commandsOffset, httpAt); - - imageUrl = new URL(url.substring(httpAt, url.length())); - - } else { - int questionAt = url.indexOf("?"); - commandsString = url.substring(commandsOffset, questionAt); - - imageUrl = new URL(StringUtils.getQueryParameterValue(url, "url")); - } - - String[] parts = commandsString.split("/"); - String name = null; - String value = null; - for (int i=0; i getCommands() { - if (commands == null) { - commands = new ArrayList(); - } - return commands; - } - - /** Inserts all ResizingCommands which can change the dimensions - * of the image after the last ResizingCommand found, and appends - * all other commands to the end of the list. */ - private void addCommand(Command command) { - List commands = getCommands(); - if (commands.size() > 0 && command instanceof ResizingCommand) { - int lastResizeIndex = 0; - for (Command cmd : commands) { - if (cmd instanceof ResizingCommand) { - lastResizeIndex++; - } else { - break; - } - } - commands.add(lastResizeIndex, command); - } else { - commands.add(command); - } - } - - /** Returns the last command that changed the dimensions of the image. */ - private Command getLastResizeCommand() { - for (ListIterator commandIter = getCommands().listIterator(getCommands().size()); commandIter.hasPrevious();) { - Command command = commandIter.previous(); - if (command instanceof ResizingCommand) { - return command; - } - } - return null; - } - - /** Adds a DIMS thumbnail command (resize+crop) to this URL */ - public DimsUrl thumbnail(Object width, Object height, Object option) { - addCommand(new ThumbnailCommand( - ObjectUtils.to(Integer.class, width), - ObjectUtils.to(Integer.class, height), - String.valueOf(option), - DimsImageEditor.this.isUseLegacyThumbnail())); - - // Special handling here because the thumbnail command does not - // behave properly when resizing GIF images, so we add an extra - // command that will convert the image to JPG so the thumbnail - // command can process it correctly. - String imagePath = imageUrl.getPath(); - if (imagePath.toLowerCase(Locale.ENGLISH).endsWith(".gif")) { - addCommand(new FormatCommand(ImageFormat.jpg)); - } - return this; - } - - /** Adds a DIMS resize command to this URL */ - public DimsUrl resize(Object width, Object height, Object option) { - addCommand(new ResizeCommand( - ObjectUtils.to(Integer.class, width), - ObjectUtils.to(Integer.class, height), - String.valueOf(option))); - return this; - } - - /** Adds a DIMS crop command to this URL */ - public DimsUrl crop(Object x, Object y, Object width, Object height) { - addCommand(new CropCommand( - ObjectUtils.to(Integer.class, x), - ObjectUtils.to(Integer.class, y), - ObjectUtils.to(Integer.class, width), - ObjectUtils.to(Integer.class, height), - DimsImageEditor.this.isUseLegacyCrop())); - return this; - } - - /** Returns a new StorageItem with the new dimensions of the image - * stored in the item's metadata. */ - public StorageItem toStorageItem() { - - Integer originalWidth = null; - Integer originalHeight = null; - Dimension outputDimension = null; - - Map oldMetadata = item.getMetadata(); - if (oldMetadata != null) { - - // grab the original width and height of the image - originalWidth = ObjectUtils.to(Integer.class, - CollectionUtils.getByPath(oldMetadata, ORIGINAL_WIDTH_METADATA_PATH)); - if (originalWidth == null) { - originalWidth = ObjectUtils.to(Integer.class, oldMetadata.get("width")); - } - - originalHeight = ObjectUtils.to(Integer.class, - CollectionUtils.getByPath(oldMetadata, ORIGINAL_HEIGHT_METADATA_PATH)); - if (originalHeight == null) { - originalHeight = ObjectUtils.to(Integer.class, oldMetadata.get("height")); - } - - // calculate the dimensions of the new image - outputDimension = new Dimension(originalWidth, originalHeight); - for (Command command : getCommands()) { - if (command instanceof ResizingCommand) { - outputDimension = ((ResizingCommand) command).getOutputDimension(outputDimension); - } - } - } - - UrlStorageItem item = StorageItem.Static.createUrl(toString()); - - Map metadata = new HashMap(); - - // store the new width and height in the metadata map - if (outputDimension != null && outputDimension.width != null) { - metadata.put("width", outputDimension.width); - } - if (outputDimension != null && outputDimension.height != null) { - metadata.put("height", outputDimension.height); - } - - // store the original width and height in the map for use with future image edits. - if (originalWidth != null) { - CollectionUtils.putByPath(metadata, ORIGINAL_WIDTH_METADATA_PATH, originalWidth); - } - if (originalHeight != null) { - CollectionUtils.putByPath(metadata, ORIGINAL_HEIGHT_METADATA_PATH, originalHeight); - } - - item.setMetadata(metadata); - - return item; - } - - @Override - public String toString() { - StringBuilder dimsUrlBuilder = new StringBuilder(); - - String imageUrl = this.imageUrl.toString(); - String baseUrl = DimsImageEditor.this.getBaseUrl(); - - dimsUrlBuilder.append(baseUrl); - if(!baseUrl.endsWith("/")) { - dimsUrlBuilder.append('/'); - } - - StringBuilder commandsBuilder = new StringBuilder(); - for(Command command : getCommands()) { - commandsBuilder - .append(command.getName()) - .append('/') - .append(command.getValue()) - .append('/'); - } - - Long expireTs = null; - if(expireTs == null || expireTs <= 0) { - // Sets it to 2038-01-19 - expireTs = (long)Integer.MAX_VALUE; - } - - String sharedSecret = DimsImageEditor.this.getSharedSecret(); - // construct url for dims developer key support - if(sharedSecret != null && baseUrl.contains("/dims4/")) { - String signature = expireTs + sharedSecret + commandsBuilder.toString() + imageUrl; - - String md5Hex = StringUtils.hex(StringUtils.md5(signature)); - // Get first 7 characters... I think it actually only needs 6 - String requestSig = md5Hex.substring(0, 7); - - dimsUrlBuilder - .append(requestSig).append('/') - .append(expireTs).append('/'); - } - - dimsUrlBuilder.append(commandsBuilder); - - if(!DimsImageEditor.this.isAppendImageUrls()) { - try { - // DIMS doesn't like the '+' character in the URL so convert - // them all to %20 - dimsUrlBuilder.append("?url=").append( - URLEncoder.encode( - imageUrl, "UTF-8").replaceAll("\\x2B", "%20")); - - } catch (UnsupportedEncodingException e) { - dimsUrlBuilder.append("?url=").append(imageUrl); - } - } else { - dimsUrlBuilder.append(imageUrl); - } - - return dimsUrlBuilder.toString(); - } - } - - /** Represents the various image formats that DIMS can convert an image to. */ - private static enum ImageFormat { - png,jpg,gif; - } - - /** Helper class so that width and height can be returned in a single object */ - private static class Dimension { - public final Integer width; - public final Integer height; - public Dimension(Integer width, Integer height) { - this.width = width; - this.height = height; - } - } - - /** Represents the various image manipulation commands supported by the DIMS API. */ - private static interface Command { - /** Returns the name of the DIMS command */ - public String getName(); - /** Returns the command's arguments as a String */ - public String getValue(); - } - - /** Sub-interface of Command signifying that the command may alter the - * dimensions of the image. */ - private static interface ResizingCommand extends Command { - /** Given a starting dimension, returns the resulting dimension after - * this command has been applied. */ - public Dimension getOutputDimension(Dimension originalDimension); - } - - /** An abstract ResizingCommand that alters the dimensions of an image - * based on a width and height parameter. */ - private static abstract class AbstractResizeCommand implements ResizingCommand { - protected Integer width; - protected Integer height; - - public Integer getWidth() { - return width; - } - - public Integer getHeight() { - return height; - } - - protected String parseResizeOption(String option) { - if (ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO.equals(option)) { - return "!"; - } else if (ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER.equals(option)) { - return ">"; - } else if (ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER.equals(option)) { - return "<"; - } else if (ImageEditor.RESIZE_OPTION_FILL_AREA.equals(option)) { - return "^"; - } else { - return null; - } - } - } - - private static class CropCommand extends AbstractResizeCommand { - private final Integer x; - private final Integer y; - private final boolean useLegacy; - - public CropCommand(String value, boolean useLegacy) { - // example crop value: 208x208+15+93 (none of the values can be empty) - - int plusAt = value.indexOf('+'); - String coords = value.substring(plusAt+1); - int coordsPlusAt = coords.indexOf('+'); - this.x = ObjectUtils.to(Integer.class, coords.substring(0, coordsPlusAt)); - this.y = ObjectUtils.to(Integer.class, coords.substring(coordsPlusAt+1)); - - String dimensions = value.substring(0, plusAt); - int xAt = dimensions.indexOf('x'); - this.width = ObjectUtils.to(Integer.class, dimensions.substring(0, xAt)); - this.height = ObjectUtils.to(Integer.class, dimensions.substring(xAt+1)); - - this.useLegacy = useLegacy; - - if (this.x == null || this.y == null || this.width == null || this.height == null) { - throw new IllegalArgumentException("All of x, y, width and height must not be null!"); - } - } - - public CropCommand(Integer x, Integer y, Integer width, Integer height, boolean useLegacy) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.useLegacy = useLegacy; - - if (this.x == null || this.y == null || this.width == null || this.height == null) { - throw new IllegalArgumentException("All of x, y, width and height must not be null!"); - } - } - - @Override - public String getName() { - if (useLegacy) { - return "legacy_crop"; - } else { - return "crop"; - } - } - - @Override - public String getValue() { - return width + "x" + height + "+" + x + "+" + y; - } - - @Override - public Dimension getOutputDimension(Dimension dimension) { - if (dimension != null && - dimension.width != null && dimension.height != null && - this.width != null && this.height != null) { - return new Dimension( - Math.min(this.width, dimension.width), - Math.min(this.height, dimension.height)); - } else { - return null; - } - } - } - - private static class ThumbnailCommand extends AbstractResizeCommand { - private String option; - private final boolean useLegacy; - - public ThumbnailCommand(String value, boolean useLegacy) { - // thumbnail value: 100x100> (width nor height can be empty, but option can be empty) - char last = value.charAt(value.length()-1); - if (!Character.isDigit(last) && last != 'x') { - this.option = String.valueOf(last); - value = value.substring(0, value.length()-1); - } - int xAt = value.indexOf('x'); - if (xAt != -1) { - this.width = xAt > 0 ? ObjectUtils.to(Integer.class, value.substring(0, xAt)) : null; - this.height = xAt < value.length()-1 ? ObjectUtils.to(Integer.class, value.substring(xAt+1)) : null; - } - this.useLegacy = useLegacy; - - if (width == null || height == null) { - throw new IllegalArgumentException("Both width and height must not be null!"); - } - } - - public ThumbnailCommand(Integer width, Integer height, String option, boolean useLegacy) { - this.width = width; - this.height = height; - this.option = parseResizeOption(option); - this.useLegacy = useLegacy; - - if (width == null || height == null) { - throw new IllegalArgumentException("Both width and height must not be null!"); - } - } - - @Override - public String getName() { - if (useLegacy) { - return "legacy_thumbnail"; - } else { - return "thumbnail"; - } - } - - @Override - public String getValue() { - return width + "x" + height + (option != null ? option : ""); - } - - @Override - public Dimension getOutputDimension(Dimension dimension) { - - if (dimension != null && - dimension.width != null && dimension.height != null && - this.width != null && this.height != null) { - - if (option == null || option.equals("!") || option.equals("^")) { - return new Dimension(this.width, this.height); - - } else if (">".equals(option)) { // only shrink larger images - return new Dimension( - Math.min(this.width, dimension.width), - Math.min(this.height, dimension.height)); - - } else if ("<".equals(option)) { // only enlarge smaller images - return new Dimension( - Math.max(this.width, dimension.width), - Math.max(this.height, dimension.height)); - } - } - - return null; - } - } - - private static class ResizeCommand extends AbstractResizeCommand { - private String option; - - public ResizeCommand(String value) { - // resize value: 400x300! (width or height can be empty but not both, and option can be empty) - char last = value.charAt(value.length()-1); - if (!Character.isDigit(last) && last != 'x') { - this.option = String.valueOf(last); - value = value.substring(0, value.length()-1); - } - int xAt = value.indexOf('x'); - if (xAt != -1) { - this.width = xAt > 0 ? ObjectUtils.to(Integer.class, value.substring(0, xAt)) : null; - this.height = xAt < value.length()-1 ? ObjectUtils.to(Integer.class, value.substring(xAt+1)) : null; - } - - if (this.width == null && this.height == null) { - throw new IllegalArgumentException("At least one of width or height must not be null!"); - } - } - - public ResizeCommand(Integer width, Integer height, String option) { - this.width = width; - this.height = height; - this.option = parseResizeOption(option); - - if (this.width == null && this.height == null) { - throw new IllegalArgumentException("At least one of width or height must not be null!"); - } - } - - @Override - public String getName() { - return "resize"; - } - - @Override - public String getValue() { - return (width == null ? "" : width) + "x" + (height == null ? "" : height) + (option != null ? option : ""); - } - - @Override - public Dimension getOutputDimension(Dimension original) { - Integer actualWidth = null; - Integer actualHeight = null; - - // in all cases we require the original dimensions to calculate the output dimensions - if (original != null && original.width != null && original.height != null) { - - if (option == null) { - Dimension actualDimension = getResizeDimension(original.width, original.height, this.width, this.height); - actualWidth = actualDimension.width; - actualHeight = actualDimension.height; - - } else if ("!".equals(option)) { // ignore aspect ratio - actualWidth = this.width != null ? this.width : original.width; - actualHeight = this.height != null ? this.height : original.height; - - } else if ("^".equals(option)) { // fill area - Dimension actualDimension = getFillAreaDimension(original.width, original.height, this.width, this.height); - actualWidth = actualDimension.width; - actualHeight = actualDimension.height; - - } else if (">".equals(option)) { // only shrink larger images - if ( (this.height == null && this.width >= original.width) || - (this.width == null && this.height >= original.height) || // --> <-- this is an AND - (this.width != null && this.height != null && this.width >= original.width && this.height >= original.height)) { - - actualWidth = original.width; - actualHeight = original.height; - - } else { - Dimension actualDimension = getResizeDimension(original.width, original.height, this.width, this.height); - actualWidth = actualDimension.width; - actualHeight = actualDimension.height; - } - - } else if ("<".equals(option)) { // only enlarge smaller images - if ( (this.height == null && this.width <= original.width) || - (this.width == null && this.height <= original.height) || // --> <-- This is an OR - (this.width != null && this.height != null && (this.width <= original.width || this.height <= original.height))) { - - actualWidth = original.width; - actualHeight = original.height; - - } else { - Dimension actualDimension = getResizeDimension(original.width, original.height, this.width, this.height); - actualWidth = actualDimension.width; - actualHeight = actualDimension.height; - } - } - } - - if (actualWidth != null || actualHeight != null) { - return new Dimension(actualWidth, actualHeight); - } else { - return null; - } - } - - private static Dimension getFillAreaDimension(Integer originalWidth, Integer originalHeight, Integer requestedWidth, Integer requestedHeight) { - Integer actualWidth = null; - Integer actualHeight = null; - - if (originalWidth != null && originalHeight != null && - (requestedWidth != null || requestedHeight != null)) { - - float originalRatio = (float) originalWidth / (float) originalHeight; - if (requestedWidth != null && requestedHeight != null) { - - Integer potentialWidth = Math.round((float) requestedHeight * originalRatio); - Integer potentialHeight = Math.round((float) requestedWidth / originalRatio); - - if (potentialWidth > requestedWidth) { - actualWidth = potentialWidth; - actualHeight = requestedHeight; - - } else { // potentialHeight > requestedHeight - actualWidth = requestedWidth; - actualHeight = potentialHeight; - } - - } else if (originalWidth > originalHeight) { - actualHeight = requestedHeight != null ? requestedHeight : requestedWidth; - actualWidth = Math.round((float) actualHeight * originalRatio); - - } else { // originalWidth <= originalHeight - actualWidth = requestedWidth != null ? requestedWidth : requestedHeight; - actualHeight = Math.round((float) actualWidth / originalRatio); - } - } - - return new Dimension(actualWidth, actualHeight); - } - - private static Dimension getResizeDimension(Integer originalWidth, Integer originalHeight, Integer requestedWidth, Integer requestedHeight) { - Integer actualWidth = null; - Integer actualHeight = null; - - if (originalWidth != null && originalHeight != null && - (requestedWidth != null || requestedHeight != null)) { - - float originalRatio = (float) originalWidth / (float) originalHeight; - if (requestedWidth != null && requestedHeight != null) { - - float requestedRatio = (float) requestedWidth / (float) requestedHeight; - if (originalRatio > requestedRatio) { - actualWidth = requestedWidth; - actualHeight = (int) Math.round((float) requestedWidth * originalHeight / originalWidth); - } else if (originalRatio < requestedRatio) { - actualWidth = (int) Math.round((float) requestedHeight * originalWidth / originalHeight); - actualHeight = requestedHeight; - } else { - actualWidth = requestedWidth; - actualHeight = requestedHeight; - } - } else if (requestedWidth == null) { - actualHeight = requestedHeight; - actualWidth = Math.round((float) requestedHeight * originalRatio); - } else if (requestedHeight == null) { - actualWidth = requestedWidth; - actualHeight = Math.round((float) requestedWidth / originalRatio); - } - } - - return new Dimension(actualWidth, actualHeight); - } - } - - private static class QualityCommand implements Command { - private final Integer quality; - - public QualityCommand(String quality) { - this(ObjectUtils.to(Integer.class, quality)); - } - - public QualityCommand(Integer quality) { - this.quality = quality; - } - - @Override - public String getName() { - return "quality"; - } - - @Override - public String getValue() { - return quality != null ? String.valueOf(quality) : null; - } - } - - private static class StripCommand implements Command { - private final Boolean doStripMetadata; - - public StripCommand(String value) { - this(ObjectUtils.to(Boolean.class, value)); - } - - public StripCommand(Boolean doStripMetadata) { - this.doStripMetadata = doStripMetadata; - } - - @Override - public String getName() { - return "strip"; - } - - @Override - public String getValue() { - return doStripMetadata != null ? String.valueOf(doStripMetadata) : null; - } - } - - private static class FormatCommand implements Command { - private final ImageFormat format; - - public FormatCommand(String value) { - this(ObjectUtils.to(ImageFormat.class, value)); - } - - public FormatCommand(ImageFormat format) { - this.format = format; - } - - @Override - public String getName() { - return "format"; - } - - @Override - public String getValue() { - return format != null ? format.name() : null; - } - } - - private static class BrightnessCommand implements Command { - - private Integer brightness; - private Integer contrast; - - public BrightnessCommand(Integer brightness, Integer contrast) { - this.brightness = brightness; - this.contrast = contrast; - } - - public BrightnessCommand(String argument) { - if (argument != null) { - int xAt = argument.indexOf('x'); - if (xAt > -1) { - brightness = ObjectUtils.to(Integer.class, argument.substring(0, xAt)); - contrast = ObjectUtils.to(Integer.class, argument.substring(xAt + 1)); - } - } - } - - @Override - public String getName() { - return "brightness"; - } - - @Override - public String getValue() { - if (brightness == null) { - if (contrast == null) { - return null; - - } else { - return "0x" + contrast; - } - - } else if (contrast == null) { - return brightness + "x0"; - - } else { - return brightness + "x" + contrast; - } - } - } - - private static class FlipFlopCommand implements Command { - - private final String orientation; - - public FlipFlopCommand(String orientation) { - this.orientation = orientation; - } - - @Override - public String getName() { - return "flipflop"; - } - - @Override - public String getValue() { - return orientation; - } - } - - private static class GrayscaleCommand implements Command { - - private final Boolean grayscale; - - public GrayscaleCommand(Boolean grayscale) { - this.grayscale = grayscale; - } - - public GrayscaleCommand(String grayscale) { - this(ObjectUtils.to(Boolean.class, grayscale)); - } - - @Override - public String getName() { - return "grayscale"; - } - - @Override - public String getValue() { - return grayscale != null ? grayscale.toString() : null; - } - } - - private static class InvertCommand implements Command { - - private final Boolean invert; - - public InvertCommand(Boolean invert) { - this.invert = invert; - } - - public InvertCommand(String invert) { - this(ObjectUtils.to(Boolean.class, invert)); - } - - @Override - public String getName() { - return "invert"; - } - - @Override - public String getValue() { - return invert != null ? invert.toString() : null; - } - } - - private static class RotateCommand implements ResizingCommand { - - private final Integer angle; - - public RotateCommand(Integer angle) { - this.angle = angle; - } - - public RotateCommand(String angle) { - this(ObjectUtils.to(Integer.class, angle)); - } - - @Override - public String getName() { - return "rotate"; - } - - @Override - public String getValue() { - return angle != null ? String.valueOf(angle) : null; - } - - @Override - public Dimension getOutputDimension(Dimension dimension) { - if (angle != null && angle % 90 == 0) { - if (angle % 180 != 0) { - return new Dimension(dimension.height, dimension.width); - } else { - return dimension; - } - } else { - // TODO: Handle the cases where the angle is not a multiple of 90. - return null; - } - } - } - - private static class SepiaCommand implements Command { - - private final Double threshold; - - public SepiaCommand(Double threshold) { - this.threshold = threshold; - } - - public SepiaCommand(String threshold) { - this(ObjectUtils.to(Double.class, threshold)); - } - - @Override - public String getName() { - return "sepia"; - } - - @Override - public String getValue() { - return threshold != null ? String.valueOf(threshold) : null; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/old/DimsImageEditor.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/old/DimsImageEditor.java deleted file mode 100755 index 3d736f2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/old/DimsImageEditor.java +++ /dev/null @@ -1,1255 +0,0 @@ -package com.psddev.dari.util; - -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.ListIterator; -import java.util.Map; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Image editor backed by - * mod_dims. - */ -public class DimsImageEditor extends AbstractImageEditor { - - protected static final Logger LOGGER = LoggerFactory.getLogger(DimsImageEditor.class); - - /** Setting key for the base URL to the mod_dims installation. */ - public static final String BASE_URL_SETTING = "baseUrl"; - - /** Setting key for the shared secret to use when signing URLs. */ - public static final String SHARED_SECRET_SETTING = "sharedSecret"; - - /** Setting key for the expiration date of a signed URL. Only one of either - * this setting or {@link #EXPIRE_DURATION_SETTING} should be set. */ - public static final String EXPIRE_TIMESTAMP_SETTING = "expireTimestamp"; - - /** Setting key for the expiration duration (in seconds) of a signed URL. - * Only one of either this setting or {@link #EXPIRE_TIMESTAMP_SETTING} - * should be set. */ - public static final String EXPIRE_DURATION_SETTING = "expireDuration"; - - /** Setting key for quality to use for the output images. */ - public static final String QUALITY_SETTING = "quality"; - - /** Setting key for enabling the use of DIMS' legacy crop command. */ - public static final String USE_LEGACY_CROP_SETTING = "useLegacyCrop"; - - /** Setting key for enabling the use of DIMS' legacy thumbnail command. */ - public static final String USE_LEGACY_THUMBNAIL_SETTING = "useLegacyThumbnail"; - - /** Setting key for enabling the preservation of the image's metadata. */ - public static final String PRESERVE_METADATA_SETTING = "preserveMetadata"; - - /** Setting key for enabling appending image URLs instead of passing them as a parater. */ - public static final String APPEND_IMAGE_URLS_SETTING = "appendImageUrls"; - - private String baseUrl; - private String sharedSecret; - - private Date expireTimestamp; - private Long expireDuration; - - private Integer quality; - private boolean useLegacyCrop; - private boolean useLegacyThumbnail; - private boolean preserveMetadata; - private boolean appendImageUrls; - - /** Returns the base URL. */ - public String getBaseUrl() { - return baseUrl; - } - - /** Sets the base URL. */ - public void setBaseUrl(String baseUrl) { - this.baseUrl = baseUrl; - } - - public String getSharedSecret() { - return sharedSecret; - } - - public void setSharedSecret(String sharedSecret) { - this.sharedSecret = sharedSecret; - } - - public Date getExpireTimestamp() { - return expireTimestamp; - } - - public void setExpireTimestamp(Date expireTimestamp) { - this.expireTimestamp = expireTimestamp; - } - - public Long getExpireDuration() { - return expireDuration; - } - - public void setExpireDuration(Long expireDuration) { - this.expireDuration = expireDuration; - } - - public Integer getQuality() { - return quality; - } - - public void setQuality(Integer quality) { - this.quality = quality; - } - - public boolean isUseLegacyCrop() { - return useLegacyCrop; - } - - public void setUseLegacyCrop(boolean useLegacyCrop) { - this.useLegacyCrop = useLegacyCrop; - } - - public boolean isUseLegacyThumbnail() { - return useLegacyThumbnail; - } - - public void setUseLegacyThumbnail(boolean useLegacyThumbnail) { - this.useLegacyThumbnail = useLegacyThumbnail; - } - - public boolean isPreserveMetadata() { - return preserveMetadata; - } - - public void setPreserveMetadata(boolean preserveMetadata) { - this.preserveMetadata = preserveMetadata; - } - - public boolean isAppendImageUrls() { - return appendImageUrls; - } - - public void setAppendImageUrls(boolean appendImageUrls) { - this.appendImageUrls = appendImageUrls; - } - - // --- AbstractImageEditor support --- - - @Override - public void initialize(String settingsKey, Map settings) { - setBaseUrl(ObjectUtils.to(String.class, settings.get(BASE_URL_SETTING))); - setSharedSecret(ObjectUtils.to(String.class, settings.get(SHARED_SECRET_SETTING))); - - setExpireTimestamp(ObjectUtils.to(Date.class, settings.get(EXPIRE_TIMESTAMP_SETTING))); - setExpireDuration(ObjectUtils.to(Long.class, settings.get(EXPIRE_DURATION_SETTING))); - - setQuality(ObjectUtils.to(Integer.class, settings.get(QUALITY_SETTING))); - - setUseLegacyCrop(ObjectUtils.to(boolean.class, settings.get(USE_LEGACY_CROP_SETTING))); - setUseLegacyThumbnail(ObjectUtils.to(boolean.class, settings.get(USE_LEGACY_THUMBNAIL_SETTING))); - setPreserveMetadata(ObjectUtils.to(boolean.class, settings.get(PRESERVE_METADATA_SETTING))); - setAppendImageUrls(ObjectUtils.to(boolean.class, settings.get(APPEND_IMAGE_URLS_SETTING))); - } - - @Override - public StorageItem edit( - StorageItem image, - String command, - Map options, - Object... arguments) { - - StorageItem newImage = null; - - DimsUrl dimsUrl = null; - try { - dimsUrl = this.new DimsUrl(image); - } catch (Exception e) { - LOGGER.error(e.getMessage(), e); - } - if (dimsUrl != null) { - Object resizeOption = options != null ? options.get(ImageEditor.RESIZE_OPTION) : null; - Object cropOption = options != null ? options.get(ImageEditor.CROP_OPTION) : null; - - if (ImageEditor.CROP_COMMAND.equals(command)) { - Object x = arguments[0]; - Object y = arguments[1]; - Object width = arguments[2]; - Object height = arguments[3]; - - /* - * This logic is a bit confusing, but is here to preserve backward compatibility. ImageEditor.CROP_OPTION_AUTOMATIC - * is new and is meant to signify that no matter what, all crops should be done that way, regardless of whether other - * parameters like the x & y coordinates are present. It is synonymous with the DIMS thumbnail command which does - * a resize AND crop in a single operation. Before its addition, the behavior was such that if there were crop - * dimensions (x, y, width, height) defined then a normal crop would take place. If however, only the width and height - * are present then an "Automatic" crop (thumbnail command) would be done in its place. - */ - - if (ImageEditor.CROP_OPTION_AUTOMATIC.equals(cropOption) || (cropOption == null && x == null && y == null)) { - dimsUrl.thumbnail(width, height, resizeOption); - - } else if (ImageEditor.CROP_OPTION_NONE.equals(cropOption)) { - // don't do any cropping, just return the image. - return image; - - } else { - // the x & y coordinates cannot be null, otherwise just - // return the original image unchanged - if (x != null && y != null) { - dimsUrl.crop(x, y, width, height); - } else { - return image; - } - } - } else if (ImageEditor.RESIZE_COMMAND.equals(command)) { - - Integer width = ObjectUtils.to(Integer.class, arguments[0]); - Integer height = ObjectUtils.to(Integer.class, arguments[1]); - - /* - * Check the last command and if it was a thumbnail command - * with the same width and height as the arguments then don't do - * anything and just return the old URL "as is" since the - * thumbnail command already did both a crop AND a resize. - * - * We go into this if block even when the cropOption is null - * due to backward compatibility. See the block comment above. - */ - - if (ImageEditor.CROP_OPTION_AUTOMATIC.equals(cropOption) || cropOption == null) { - - Command lastResizeCommand = dimsUrl.getLastResizeCommand(); - if (lastResizeCommand instanceof ThumbnailCommand) { - ThumbnailCommand thumbnailCommand = (ThumbnailCommand) lastResizeCommand; - - Integer thumbnailWidth = thumbnailCommand.getWidth(); - Integer thumbnailHeight = thumbnailCommand.getHeight(); - - if (width != null && height != null && - width.equals(thumbnailWidth) && height.equals(thumbnailHeight)) { - return image; - } - } - } - - dimsUrl.resize(width, height, resizeOption); - - } else if ("brightness".equals(command)) { - Double brightness = ObjectUtils.to(Double.class, arguments[0]); - if (brightness != null) { - dimsUrl.addCommand(new BrightnessCommand((int) (brightness * 100 / 1.5), 0)); - } - - } else if ("contrast".equals(command)) { - Double contrast = ObjectUtils.to(Double.class, arguments[0]); - if (contrast != null) { - dimsUrl.addCommand(new BrightnessCommand(0, (int) (contrast * 100))); - } - - } else if ("flipH".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new FlipFlopCommand("horizontal")); - } - - } else if ("flipV".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new FlipFlopCommand("vertical")); - } - - } else if ("grayscale".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new GrayscaleCommand(true)); - } - - } else if ("invert".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new InvertCommand(true)); - } - - } else if ("rotate".equals(command)) { - Integer angle = ObjectUtils.to(Integer.class, arguments[0]); - if (angle != null) { - dimsUrl.addCommand(new RotateCommand(angle)); - } - - } else if ("sepia".equals(command)) { - if (ObjectUtils.to(boolean.class, arguments[0])) { - dimsUrl.addCommand(new SepiaCommand(0.8)); - } - } - - Command lastResizeCommand = dimsUrl.getLastResizeCommand(); - if (lastResizeCommand instanceof AbstractResizeCommand) { - AbstractResizeCommand lastResize = (AbstractResizeCommand) lastResizeCommand; - - StorageItem override = StorageItem.Static.createIn(image.getStorage()); - new ObjectMap(override).putAll(new ObjectMap(image)); - - boolean overridden = ImageResizeStorageItemListener.overridePathWithNearestSize(override, - lastResize.getWidth(), - lastResize.getHeight()); - - if (overridden) { - try { - dimsUrl.setImageUrl(new URL(override.getPublicUrl())); - } catch(MalformedURLException mue) { - } - } - } - - newImage = dimsUrl.toStorageItem(); - } - - if (newImage != null) { - return newImage; - } else { // failed to create a new DimsUrl so return the original - return image; - } - } - - private class DimsUrl { - - /** DIMS specific path to the original width of the image in the metadata */ - private static final String ORIGINAL_WIDTH_METADATA_PATH = "dims/originalWidth"; - - /** DIMS specific Path to the original height of the image in the metadata */ - private static final String ORIGINAL_HEIGHT_METADATA_PATH = "dims/originalHeight"; - - private List commands; - private final StorageItem item; - private URL imageUrl; - - public void setImageUrl(URL imageUrl) { - this.imageUrl = imageUrl; - } - - public DimsUrl(StorageItem item) throws MalformedURLException { - this.item = item; - - String url = item.getPublicUrl(); - LOGGER.trace("Creating new DIMS URL from [" + url + "]"); - if (url == null) { - throw new MalformedURLException("Cannot create DIMS URL for item [" + item + "] with url [null]"); - } - - String baseUrl = DimsImageEditor.this.getBaseUrl(); - if (url.startsWith(baseUrl)) { - - // It's an existing DIMS URL that we're further modifying - - String commandsString = null; - - int commandsOffset = baseUrl.length()+1; - if (DimsImageEditor.this.getSharedSecret() != null && baseUrl.contains("/dims4/")) { - - int slashAt = url.indexOf('/', commandsOffset); - commandsOffset = url.indexOf('/', slashAt+1) + 1; - } - - if (DimsImageEditor.this.isAppendImageUrls()) { - int httpAt = url.indexOf("http", 1); - commandsString = url.substring(commandsOffset, httpAt); - - imageUrl = new URL(url.substring(httpAt, url.length())); - - } else { - int questionAt = url.indexOf("?"); - commandsString = url.substring(commandsOffset, questionAt); - - imageUrl = new URL(StringUtils.getQueryParameterValue(url, "url")); - } - - String[] parts = commandsString.split("/"); - String name = null; - String value = null; - for (int i=0; i getCommands() { - if (commands == null) { - commands = new ArrayList(); - } - return commands; - } - - /** Inserts all ResizingCommands which can change the dimensions - * of the image after the last ResizingCommand found, and appends - * all other commands to the end of the list. */ - private void addCommand(Command command) { - List commands = getCommands(); - if (commands.size() > 0 && command instanceof ResizingCommand) { - int lastResizeIndex = 0; - for (Command cmd : commands) { - if (cmd instanceof ResizingCommand) { - lastResizeIndex++; - } else { - break; - } - } - commands.add(lastResizeIndex, command); - } else { - commands.add(command); - } - } - - /** Returns the last command that changed the dimensions of the image. */ - private Command getLastResizeCommand() { - for (ListIterator commandIter = getCommands().listIterator(getCommands().size()); commandIter.hasPrevious();) { - Command command = commandIter.previous(); - if (command instanceof ResizingCommand) { - return command; - } - } - return null; - } - - /** Adds a DIMS thumbnail command (resize+crop) to this URL */ - public DimsUrl thumbnail(Object width, Object height, Object option) { - addCommand(new ThumbnailCommand( - ObjectUtils.to(Integer.class, width), - ObjectUtils.to(Integer.class, height), - String.valueOf(option), - DimsImageEditor.this.isUseLegacyThumbnail())); - - // Special handling here because the thumbnail command does not - // behave properly when resizing GIF images, so we add an extra - // command that will convert the image to JPG so the thumbnail - // command can process it correctly. - String imagePath = imageUrl.getPath(); - if (imagePath.toLowerCase().endsWith(".gif")) { - addCommand(new FormatCommand(ImageFormat.jpg)); - } - return this; - } - - /** Adds a DIMS resize command to this URL */ - public DimsUrl resize(Object width, Object height, Object option) { - addCommand(new ResizeCommand( - ObjectUtils.to(Integer.class, width), - ObjectUtils.to(Integer.class, height), - String.valueOf(option))); - return this; - } - - /** Adds a DIMS crop command to this URL */ - public DimsUrl crop(Object x, Object y, Object width, Object height) { - addCommand(new CropCommand( - ObjectUtils.to(Integer.class, x), - ObjectUtils.to(Integer.class, y), - ObjectUtils.to(Integer.class, width), - ObjectUtils.to(Integer.class, height), - DimsImageEditor.this.isUseLegacyCrop())); - return this; - } - - /** Returns a new StorageItem with the new dimensions of the image - * stored in the item's metadata. */ - public StorageItem toStorageItem() { - - Integer originalWidth = null; - Integer originalHeight = null; - Dimension outputDimension = null; - - Map oldMetadata = item.getMetadata(); - if (oldMetadata != null) { - - // grab the original width and height of the image - originalWidth = ObjectUtils.to(Integer.class, - CollectionUtils.getByPath(oldMetadata, ORIGINAL_WIDTH_METADATA_PATH)); - if (originalWidth == null) { - originalWidth = ObjectUtils.to(Integer.class, oldMetadata.get("width")); - } - - originalHeight = ObjectUtils.to(Integer.class, - CollectionUtils.getByPath(oldMetadata, ORIGINAL_HEIGHT_METADATA_PATH)); - if (originalHeight == null) { - originalHeight = ObjectUtils.to(Integer.class, oldMetadata.get("height")); - } - - // calculate the dimensions of the new image - outputDimension = new Dimension(originalWidth, originalHeight); - for (Command command : getCommands()) { - if (command instanceof ResizingCommand) { - outputDimension = ((ResizingCommand) command).getOutputDimension(outputDimension); - } - } - } - - UrlStorageItem item = StorageItem.Static.createUrl(toString()); - - Map metadata = new HashMap(); - - // store the new width and height in the metadata map - if (outputDimension != null && outputDimension.width != null) { - metadata.put("width", outputDimension.width); - } - if (outputDimension != null && outputDimension.height != null) { - metadata.put("height", outputDimension.height); - } - - // store the original width and height in the map for use with future image edits. - if (originalWidth != null) { - CollectionUtils.putByPath(metadata, ORIGINAL_WIDTH_METADATA_PATH, originalWidth); - } - if (originalHeight != null) { - CollectionUtils.putByPath(metadata, ORIGINAL_HEIGHT_METADATA_PATH, originalHeight); - } - - item.setMetadata(metadata); - - return item; - } - - @Override - public String toString() { - StringBuilder dimsUrlBuilder = new StringBuilder(); - - String imageUrl = this.imageUrl.toString(); - String baseUrl = DimsImageEditor.this.getBaseUrl(); - - dimsUrlBuilder.append(baseUrl); - if(!baseUrl.endsWith("/")) { - dimsUrlBuilder.append('/'); - } - - StringBuilder commandsBuilder = new StringBuilder(); - for(Command command : getCommands()) { - commandsBuilder - .append(command.getName()) - .append('/') - .append(command.getValue()) - .append('/'); - } - - Long expireTs = null; - if(expireTs == null || expireTs <= 0) { - // Sets it to 2038-01-19 - expireTs = (long)Integer.MAX_VALUE; - } - - String sharedSecret = DimsImageEditor.this.getSharedSecret(); - // construct url for dims developer key support - if(sharedSecret != null && baseUrl.contains("/dims4/")) { - String signature = expireTs + sharedSecret + commandsBuilder.toString() + imageUrl; - - String md5Hex = StringUtils.hex(StringUtils.md5(signature)); - // Get first 7 characters... I think it actually only needs 6 - String requestSig = md5Hex.substring(0, 7); - - dimsUrlBuilder - .append(requestSig).append('/') - .append(expireTs).append('/'); - } - - dimsUrlBuilder.append(commandsBuilder); - - if(!DimsImageEditor.this.isAppendImageUrls()) { - try { - // DIMS doesn't like the '+' character in the URL so convert - // them all to %20 - dimsUrlBuilder.append("?url=").append( - URLEncoder.encode( - imageUrl, "UTF-8").replaceAll("\\x2B", "%20")); - - } catch (UnsupportedEncodingException e) { - dimsUrlBuilder.append("?url=").append(imageUrl); - } - } else { - dimsUrlBuilder.append(imageUrl); - } - - return dimsUrlBuilder.toString(); - } - } - - /** Represents the various image formats that DIMS can convert an image to. */ - private static enum ImageFormat { - png,jpg,gif; - } - - /** Helper class so that width and height can be returned in a single object */ - private static class Dimension { - public final Integer width; - public final Integer height; - public Dimension(Integer width, Integer height) { - this.width = width; - this.height = height; - } - } - - /** Represents the various image manipulation commands supported by the DIMS API. */ - private static interface Command { - /** Returns the name of the DIMS command */ - public String getName(); - /** Returns the command's arguments as a String */ - public String getValue(); - } - - /** Sub-interface of Command signifying that the command may alter the - * dimensions of the image. */ - private static interface ResizingCommand extends Command { - /** Given a starting dimension, returns the resulting dimension after - * this command has been applied. */ - public Dimension getOutputDimension(Dimension originalDimension); - } - - /** An abstract ResizingCommand that alters the dimensions of an image - * based on a width and height parameter. */ - private static abstract class AbstractResizeCommand implements ResizingCommand { - protected Integer width; - protected Integer height; - - public Integer getWidth() { - return width; - } - - public Integer getHeight() { - return height; - } - - protected String parseResizeOption(String option) { - if (ImageEditor.RESIZE_OPTION_IGNORE_ASPECT_RATIO.equals(option)) { - return "!"; - } else if (ImageEditor.RESIZE_OPTION_ONLY_SHRINK_LARGER.equals(option)) { - return ">"; - } else if (ImageEditor.RESIZE_OPTION_ONLY_ENLARGE_SMALLER.equals(option)) { - return "<"; - } else if (ImageEditor.RESIZE_OPTION_FILL_AREA.equals(option)) { - return "^"; - } else { - return null; - } - } - } - - private static class CropCommand extends AbstractResizeCommand { - private final Integer x; - private final Integer y; - private final boolean useLegacy; - - public CropCommand(String value, boolean useLegacy) { - // example crop value: 208x208+15+93 (none of the values can be empty) - - int plusAt = value.indexOf('+'); - String coords = value.substring(plusAt+1); - int coordsPlusAt = coords.indexOf('+'); - this.x = ObjectUtils.to(Integer.class, coords.substring(0, coordsPlusAt)); - this.y = ObjectUtils.to(Integer.class, coords.substring(coordsPlusAt+1)); - - String dimensions = value.substring(0, plusAt); - int xAt = dimensions.indexOf('x'); - this.width = ObjectUtils.to(Integer.class, dimensions.substring(0, xAt)); - this.height = ObjectUtils.to(Integer.class, dimensions.substring(xAt+1)); - - this.useLegacy = useLegacy; - - if (this.x == null || this.y == null || this.width == null || this.height == null) { - throw new IllegalArgumentException("All of x, y, width and height must not be null!"); - } - } - - public CropCommand(Integer x, Integer y, Integer width, Integer height, boolean useLegacy) { - this.x = x; - this.y = y; - this.width = width; - this.height = height; - this.useLegacy = useLegacy; - - if (this.x == null || this.y == null || this.width == null || this.height == null) { - throw new IllegalArgumentException("All of x, y, width and height must not be null!"); - } - } - - @Override - public String getName() { - if (useLegacy) { - return "legacy_crop"; - } else { - return "crop"; - } - } - - @Override - public String getValue() { - return width + "x" + height + "+" + x + "+" + y; - } - - @Override - public Dimension getOutputDimension(Dimension dimension) { - if (dimension != null && - dimension.width != null && dimension.height != null && - this.width != null && this.height != null) { - return new Dimension( - Math.min(this.width, dimension.width), - Math.min(this.height, dimension.height)); - } else { - return null; - } - } - } - - private static class ThumbnailCommand extends AbstractResizeCommand { - private String option; - private final boolean useLegacy; - - public ThumbnailCommand(String value, boolean useLegacy) { - // thumbnail value: 100x100> (width nor height can be empty, but option can be empty) - char last = value.charAt(value.length()-1); - if (!Character.isDigit(last) && last != 'x') { - this.option = String.valueOf(last); - value = value.substring(0, value.length()-1); - } - int xAt = value.indexOf('x'); - if (xAt != -1) { - this.width = xAt > 0 ? ObjectUtils.to(Integer.class, value.substring(0, xAt)) : null; - this.height = xAt < value.length()-1 ? ObjectUtils.to(Integer.class, value.substring(xAt+1)) : null; - } - this.useLegacy = useLegacy; - - if (width == null || height == null) { - throw new IllegalArgumentException("Both width and height must not be null!"); - } - } - - public ThumbnailCommand(Integer width, Integer height, String option, boolean useLegacy) { - this.width = width; - this.height = height; - this.option = parseResizeOption(option); - this.useLegacy = useLegacy; - - if (width == null || height == null) { - throw new IllegalArgumentException("Both width and height must not be null!"); - } - } - - @Override - public String getName() { - if (useLegacy) { - return "legacy_thumbnail"; - } else { - return "thumbnail"; - } - } - - @Override - public String getValue() { - return width + "x" + height + (option != null ? option : ""); - } - - @Override - public Dimension getOutputDimension(Dimension dimension) { - - if (dimension != null && - dimension.width != null && dimension.height != null && - this.width != null && this.height != null) { - - if (option == null || option.equals("!") || option.equals("^")) { - return new Dimension(this.width, this.height); - - } else if (">".equals(option)) { // only shrink larger images - return new Dimension( - Math.min(this.width, dimension.width), - Math.min(this.height, dimension.height)); - - } else if ("<".equals(option)) { // only enlarge smaller images - return new Dimension( - Math.max(this.width, dimension.width), - Math.max(this.height, dimension.height)); - } - } - - return null; - } - } - - private static class ResizeCommand extends AbstractResizeCommand { - private String option; - - public ResizeCommand(String value) { - // resize value: 400x300! (width or height can be empty but not both, and option can be empty) - char last = value.charAt(value.length()-1); - if (!Character.isDigit(last) && last != 'x') { - this.option = String.valueOf(last); - value = value.substring(0, value.length()-1); - } - int xAt = value.indexOf('x'); - if (xAt != -1) { - this.width = xAt > 0 ? ObjectUtils.to(Integer.class, value.substring(0, xAt)) : null; - this.height = xAt < value.length()-1 ? ObjectUtils.to(Integer.class, value.substring(xAt+1)) : null; - } - - if (this.width == null && this.height == null) { - throw new IllegalArgumentException("At least one of width or height must not be null!"); - } - } - - public ResizeCommand(Integer width, Integer height, String option) { - this.width = width; - this.height = height; - this.option = parseResizeOption(option); - - if (this.width == null && this.height == null) { - throw new IllegalArgumentException("At least one of width or height must not be null!"); - } - } - - @Override - public String getName() { - return "resize"; - } - - @Override - public String getValue() { - return (width == null ? "" : width) + "x" + (height == null ? "" : height) + (option != null ? option : ""); - } - - @Override - public Dimension getOutputDimension(Dimension original) { - Integer actualWidth = null; - Integer actualHeight = null; - - // in all cases we require the original dimensions to calculate the output dimensions - if (original != null && original.width != null && original.height != null) { - - if (option == null) { - Dimension actualDimension = getResizeDimension(original.width, original.height, this.width, this.height); - actualWidth = actualDimension.width; - actualHeight = actualDimension.height; - - } else if ("!".equals(option)) { // ignore aspect ratio - actualWidth = this.width != null ? this.width : original.width; - actualHeight = this.height != null ? this.height : original.height; - - } else if ("^".equals(option)) { // fill area - Dimension actualDimension = getFillAreaDimension(original.width, original.height, this.width, this.height); - actualWidth = actualDimension.width; - actualHeight = actualDimension.height; - - } else if (">".equals(option)) { // only shrink larger images - if ( (this.height == null && this.width >= original.width) || - (this.width == null && this.height >= original.height) || // --> <-- this is an AND - (this.width != null && this.height != null && this.width >= original.width && this.height >= original.height)) { - - actualWidth = original.width; - actualHeight = original.height; - - } else { - Dimension actualDimension = getResizeDimension(original.width, original.height, this.width, this.height); - actualWidth = actualDimension.width; - actualHeight = actualDimension.height; - } - - } else if ("<".equals(option)) { // only enlarge smaller images - if ( (this.height == null && this.width <= original.width) || - (this.width == null && this.height <= original.height) || // --> <-- This is an OR - (this.width != null && this.height != null && (this.width <= original.width || this.height <= original.height))) { - - actualWidth = original.width; - actualHeight = original.height; - - } else { - Dimension actualDimension = getResizeDimension(original.width, original.height, this.width, this.height); - actualWidth = actualDimension.width; - actualHeight = actualDimension.height; - } - } - } - - if (actualWidth != null || actualHeight != null) { - return new Dimension(actualWidth, actualHeight); - } else { - return null; - } - } - - private static Dimension getFillAreaDimension(Integer originalWidth, Integer originalHeight, Integer requestedWidth, Integer requestedHeight) { - Integer actualWidth = null; - Integer actualHeight = null; - - if (originalWidth != null && originalHeight != null && - (requestedWidth != null || requestedHeight != null)) { - - float originalRatio = (float) originalWidth / (float) originalHeight; - if (requestedWidth != null && requestedHeight != null) { - - Integer potentialWidth = Math.round((float) requestedHeight * originalRatio); - Integer potentialHeight = Math.round((float) requestedWidth / originalRatio); - - if (potentialWidth > requestedWidth) { - actualWidth = potentialWidth; - actualHeight = requestedHeight; - - } else { // potentialHeight > requestedHeight - actualWidth = requestedWidth; - actualHeight = potentialHeight; - } - - } else if (originalWidth > originalHeight) { - actualHeight = requestedHeight != null ? requestedHeight : requestedWidth; - actualWidth = Math.round((float) actualHeight * originalRatio); - - } else { // originalWidth <= originalHeight - actualWidth = requestedWidth != null ? requestedWidth : requestedHeight; - actualHeight = Math.round((float) actualWidth / originalRatio); - } - } - - return new Dimension(actualWidth, actualHeight); - } - - private static Dimension getResizeDimension(Integer originalWidth, Integer originalHeight, Integer requestedWidth, Integer requestedHeight) { - Integer actualWidth = null; - Integer actualHeight = null; - - if (originalWidth != null && originalHeight != null && - (requestedWidth != null || requestedHeight != null)) { - - float originalRatio = (float) originalWidth / (float) originalHeight; - if (requestedWidth != null && requestedHeight != null) { - - float requestedRatio = (float) requestedWidth / (float) requestedHeight; - if (originalRatio > requestedRatio) { - actualWidth = requestedWidth; - actualHeight = (int) Math.round((float) requestedWidth * originalHeight / originalWidth); - } else if (originalRatio < requestedRatio) { - actualWidth = (int) Math.round((float) requestedHeight * originalWidth / originalHeight); - actualHeight = requestedHeight; - } else { - actualWidth = requestedWidth; - actualHeight = requestedHeight; - } - } else if (requestedWidth == null) { - actualHeight = requestedHeight; - actualWidth = Math.round((float) requestedHeight * originalRatio); - } else if (requestedHeight == null) { - actualWidth = requestedWidth; - actualHeight = Math.round((float) requestedWidth / originalRatio); - } - } - - return new Dimension(actualWidth, actualHeight); - } - } - - private static class QualityCommand implements Command { - private final Integer quality; - - public QualityCommand(String quality) { - this(ObjectUtils.to(Integer.class, quality)); - } - - public QualityCommand(Integer quality) { - this.quality = quality; - } - - @Override - public String getName() { - return "quality"; - } - - @Override - public String getValue() { - return quality != null ? String.valueOf(quality) : null; - } - } - - private static class StripCommand implements Command { - private final Boolean doStripMetadata; - - public StripCommand(String value) { - this(ObjectUtils.to(Boolean.class, value)); - } - - public StripCommand(Boolean doStripMetadata) { - this.doStripMetadata = doStripMetadata; - } - - @Override - public String getName() { - return "strip"; - } - - @Override - public String getValue() { - return doStripMetadata != null ? String.valueOf(doStripMetadata) : null; - } - } - - private static class FormatCommand implements Command { - private final ImageFormat format; - - public FormatCommand(String value) { - this(ObjectUtils.to(ImageFormat.class, value)); - } - - public FormatCommand(ImageFormat format) { - this.format = format; - } - - @Override - public String getName() { - return "format"; - } - - @Override - public String getValue() { - return format != null ? format.name() : null; - } - } - - private static class BrightnessCommand implements Command { - - private Integer brightness; - private Integer contrast; - - public BrightnessCommand(Integer brightness, Integer contrast) { - this.brightness = brightness; - this.contrast = contrast; - } - - public BrightnessCommand(String argument) { - if (argument != null) { - int xAt = argument.indexOf('x'); - if (xAt > -1) { - brightness = ObjectUtils.to(Integer.class, argument.substring(0, xAt)); - contrast = ObjectUtils.to(Integer.class, argument.substring(xAt + 1)); - } - } - } - - @Override - public String getName() { - return "brightness"; - } - - @Override - public String getValue() { - if (brightness == null) { - if (contrast == null) { - return null; - - } else { - return "0x" + contrast; - } - - } else if (contrast == null) { - return brightness + "x0"; - - } else { - return brightness + "x" + contrast; - } - } - } - - private static class FlipFlopCommand implements Command { - - private final String orientation; - - public FlipFlopCommand(String orientation) { - this.orientation = orientation; - } - - @Override - public String getName() { - return "flipflop"; - } - - @Override - public String getValue() { - return orientation; - } - } - - private static class GrayscaleCommand implements Command { - - private final Boolean grayscale; - - public GrayscaleCommand(Boolean grayscale) { - this.grayscale = grayscale; - } - - public GrayscaleCommand(String grayscale) { - this(ObjectUtils.to(Boolean.class, grayscale)); - } - - @Override - public String getName() { - return "grayscale"; - } - - @Override - public String getValue() { - return grayscale != null ? grayscale.toString() : null; - } - } - - private static class InvertCommand implements Command { - - private final Boolean invert; - - public InvertCommand(Boolean invert) { - this.invert = invert; - } - - public InvertCommand(String invert) { - this(ObjectUtils.to(Boolean.class, invert)); - } - - @Override - public String getName() { - return "invert"; - } - - @Override - public String getValue() { - return invert != null ? invert.toString() : null; - } - } - - private static class RotateCommand implements ResizingCommand { - - private final Integer angle; - - public RotateCommand(Integer angle) { - this.angle = angle; - } - - public RotateCommand(String angle) { - this(ObjectUtils.to(Integer.class, angle)); - } - - @Override - public String getName() { - return "rotate"; - } - - @Override - public String getValue() { - return angle != null ? String.valueOf(angle) : null; - } - - @Override - public Dimension getOutputDimension(Dimension dimension) { - if (angle != null && angle % 90 == 0) { - if (angle % 180 != 0) { - return new Dimension(dimension.height, dimension.width); - } else { - return dimension; - } - } else { - // TODO: Handle the cases where the angle is not a multiple of 90. - return null; - } - } - } - - private static class SepiaCommand implements Command { - - private final Double threshold; - - public SepiaCommand(Double threshold) { - this.threshold = threshold; - } - - public SepiaCommand(String threshold) { - this(ObjectUtils.to(Double.class, threshold)); - } - - @Override - public String getName() { - return "sepia"; - } - - @Override - public String getValue() { - return threshold != null ? String.valueOf(threshold) : null; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/pair.info deleted file mode 100755 index 461bccb..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51338/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:51338 -comSha:a2c1974da04a01bcebd1251b487b72e3c2ac90af -parentComSha:d019326625ce2c1c2469ada51de6696b9e3fca45 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/DimsImageEditor.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/DimsImageEditor.java -StartLineNum:506 -EndLineNum:506 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/comMsg.txt deleted file mode 100755 index 05ba6ac..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'master' of https://github.com/tpltnt/nodebox into tpltnt-master \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/diff.diff deleted file mode 100755 index 3d2f3dc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/nodebox/node/Port.java b/src/main/java/nodebox/node/Port.java -index b23a072f..d745a66b 100644 ---- a/src/main/java/nodebox/node/Port.java -+++ b/src/main/java/nodebox/node/Port.java -@@ -12,0 +13 @@ import java.util.List; -+import java.util.Locale; -@@ -165 +166 @@ public final class Port { -- return parsedPort(name, type, "", "", DEFAULT_RANGE.toString().toLowerCase(), stringValue, "", null, null, ImmutableList.of()); -+ return parsedPort(name, type, "", "", DEFAULT_RANGE.toString().toLowerCase(Locale.US), stringValue, "", null, null, ImmutableList.of()); -@@ -664 +665 @@ public final class Port { -- return Widget.valueOf(valueString.toUpperCase()); -+ return Widget.valueOf(valueString.toUpperCase(Locale.US)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/new/Port.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/new/Port.java deleted file mode 100755 index d745a66..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/new/Port.java +++ /dev/null @@ -1,810 +0,0 @@ -package nodebox.node; - -import com.google.common.base.Objects; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import nodebox.graphics.Color; -import nodebox.graphics.Point; -import nodebox.util.StringUtils; - -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import static com.google.common.base.Preconditions.*; - -public final class Port { - - public static final String TYPE_INT = "int"; - public static final String TYPE_FLOAT = "float"; - public static final String TYPE_STRING = "string"; - public static final String TYPE_BOOLEAN = "boolean"; - public static final String TYPE_POINT = "point"; - public static final String TYPE_COLOR = "color"; - public static final String TYPE_LIST = "list"; - public static final String TYPE_GEOMETRY = "geometry"; - public static final String TYPE_CONTEXT = "context"; - public static final String TYPE_STATE = "state"; - - public enum Attribute {NAME, TYPE, LABEL, CHILD_REFERENCE, WIDGET, RANGE, VALUE, DESCRIPTION, MINIMUM_VALUE, MAXIMUM_VALUE, MENU_ITEMS} - - /** - * The UI control for this port. This defines how the port is represented in the user interface. - */ - public enum Widget { - NONE, ANGLE, COLOR, DATA, FILE, FLOAT, FONT, GRADIENT, IMAGE, INT, MENU, SEED, STRING, TEXT, PASSWORD, TOGGLE, POINT - } - - public enum Direction { - INPUT, OUTPUT - } - - public enum Range { - VALUE, LIST - } - - public static final Range DEFAULT_RANGE = Range.VALUE; - - public static final ImmutableMap DEFAULT_VALUES; - public static final ImmutableSet STANDARD_TYPES; - public static final ImmutableMap> WIDGET_MAPPING; - - static { - ImmutableMap.Builder b = ImmutableMap.builder(); - b.put(TYPE_INT, 0L); - b.put(TYPE_FLOAT, 0.0); - b.put(TYPE_BOOLEAN, false); - b.put(TYPE_STRING, ""); - b.put(TYPE_POINT, Point.ZERO); - b.put(TYPE_COLOR, Color.BLACK); - DEFAULT_VALUES = b.build(); - STANDARD_TYPES = ImmutableSet.of(TYPE_INT, TYPE_FLOAT, TYPE_BOOLEAN, TYPE_STRING, TYPE_POINT, TYPE_COLOR); - - ImmutableMap.Builder> w = ImmutableMap.builder(); - w.put(TYPE_INT, ImmutableList.of(Widget.INT, Widget.SEED)); - w.put(TYPE_FLOAT, ImmutableList.of(Widget.ANGLE, Widget.FLOAT)); - w.put(TYPE_BOOLEAN, ImmutableList.of(Widget.TOGGLE)); - w.put(TYPE_STRING, ImmutableList.of(Widget.DATA, Widget.FILE, Widget.FONT, Widget.IMAGE, Widget.MENU, Widget.STRING, Widget.TEXT)); - w.put(TYPE_POINT, ImmutableList.of(Widget.POINT)); - w.put(TYPE_COLOR, ImmutableList.of(Widget.COLOR)); - WIDGET_MAPPING = w.build(); - } - - private final String name; - private final String type; - private final String label; - private final String description; - private final String childReference; - private final Widget widget; - private final Range range; - private final Object value; - private final Double minimumValue; - private final Double maximumValue; - private final ImmutableList menuItems; - - private final transient int hashCode; - - public static Port intPort(String name, long value) { - return intPort(name, value, null, null); - } - - public static Port intPort(String name, long value, Integer minimumValue, Integer maximumValue) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_INT, value, minimumValue != null ? minimumValue.doubleValue() : null, maximumValue != null ? maximumValue.doubleValue() : null); - } - - public static Port floatPort(String name, double value) { - return floatPort(name, value, null, null); - } - - public static Port floatPort(String name, double value, Double minimumValue, Double maximumValue) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_FLOAT, value, minimumValue, maximumValue); - } - - public static Port booleanPort(String name, boolean value) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_BOOLEAN, value); - } - - public static Port stringPort(String name, String value) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_STRING, value); - } - - public static Port stringPort(String name, String value, Iterable menuItems) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_STRING, value, menuItems); - } - - public static Port pointPort(String name, Point value) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_POINT, value); - } - - public static Port colorPort(String name, Color value) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_COLOR, value); - } - - public static Port customPort(String name, String type) { - checkNotNull(type, "Type cannot be null."); - return new Port(name, type, null); - } - - public static Port publishedPort(Node childNode, Port childPort, String publishedName) { - checkNotNull(childNode); - checkNotNull(childPort); - String childReference = buildChildReference(childNode, childPort); - return new Port(publishedName, childPort.getType(), "", childReference, childPort.getWidget(), childPort.getRange(), childPort.getValue(), childPort.getDescription(), childPort.getMinimumValue(), childPort.getMaximumValue(), childPort.getMenuItems()); - } - - /** - * Parse the type and create the appropriate Port. Use the default value appropriate for the port type. - * - * @param name The port name. - * @param type The port type. - * @return A new Port. - */ - public static Port portForType(String name, String type) { - checkNotNull(type, "Type cannot be null."); - // If the type is not found in the default values, get() returns null, which is what we need for custom types. - return new Port(name, type, "", null, defaultWidgetForType(type), DEFAULT_RANGE, DEFAULT_VALUES.get(type), "", null, null, ImmutableList.of()); - } - - /** - * Create a new Port with the given value as a string parsed to the correct format. - * - * @param name The port name. - * @param type The port type. - * @param stringValue The port value as a string, e.g. "32.5". - * @return A new Port. - */ - - public static Port parsedPort(String name, String type, String stringValue) { - return parsedPort(name, type, "", "", DEFAULT_RANGE.toString().toLowerCase(Locale.US), stringValue, "", null, null, ImmutableList.of()); - } - - /** - * Create a new Port with the given value as a string parsed to the correct format. - * - * @param name The port name. - * @param type The port type. - * @param valueString The port value as a string, e.g. "32.5". - * @param minString The minimum value as a string. - * @param maxString The maximum value as a string. - * @param menuItems The list of menu items. - * @return A new Port. - */ - public static Port parsedPort(String name, String type, String label, String widgetString, String rangeString, String valueString, String description, String minString, String maxString, ImmutableList menuItems) { - checkNotNull(name, "Name cannot be null."); - checkNotNull(type, "Type cannot be null."); - if (STANDARD_TYPES.contains(type)) { - Object value; - if (valueString == null) { - value = DEFAULT_VALUES.get(type); - checkNotNull(value); - } else { - if (type.equals("int")) { - value = Long.valueOf(valueString); - } else if (type.equals("float")) { - value = Double.valueOf(valueString); - } else if (type.equals("string")) { - value = valueString; - } else if (type.equals("boolean")) { - value = Boolean.valueOf(valueString); - } else if (type.equals("point")) { - value = Point.valueOf(valueString); - } else if (type.equals("color")) { - value = Color.valueOf(valueString); - } else { - throw new AssertionError("Unknown type " + type); - } - } - Widget widget; - if (widgetString != null && !widgetString.isEmpty()) { - widget = parseWidget(widgetString); - } else { - widget = Widget.NONE; - } - Range range = rangeString != null ? parseRange(rangeString) : DEFAULT_RANGE; - - Double minimumValue = null; - Double maximumValue = null; - if (minString != null) - minimumValue = Double.valueOf(minString); - if (maxString != null) - maximumValue = Double.valueOf(maxString); - return new Port(name, type, label, null, widget, range, value, description, minimumValue, maximumValue, menuItems); - } else { - return Port.customPort(name, type); - } - } - - public static Widget defaultWidgetForType(String type) { - checkNotNull(type, "Type cannot be null."); - if (type.equals(TYPE_INT)) { - return Widget.INT; - } else if (type.equals(TYPE_FLOAT)) { - return Widget.FLOAT; - } else if (type.equals(TYPE_STRING)) { - return Widget.STRING; - } else if (type.equals(TYPE_BOOLEAN)) { - return Widget.TOGGLE; - } else if (type.equals(TYPE_POINT)) { - return Widget.POINT; - } else if (type.equals(TYPE_COLOR)) { - return Widget.COLOR; - } else { - return Widget.NONE; - } - } - - private Port(String name, String type, Object value) { - this(name, type, "", null, defaultWidgetForType(type), DEFAULT_RANGE, value, "", null, null, ImmutableList.of()); - } - - private Port(String name, String type, Object value, Double minimumValue, Double maximumValue) { - this(name, type, "", null, defaultWidgetForType(type), DEFAULT_RANGE, value, "", minimumValue, maximumValue, ImmutableList.of()); - } - - private Port(String name, String type, Object value, Iterable menuItems) { - this(name, type, "", null, defaultWidgetForType(type), DEFAULT_RANGE, value, "", null, null, menuItems); - } - - private Port(String name, String type, String label, String childReference, Widget widget, Range range, Object value, String description, Double minimumValue, Double maximumValue, Iterable menuItems) { - checkNotNull(name, "Name cannot be null."); - checkNotNull(type, "Type cannot be null."); - checkNotNull(menuItems, "Menu items cannot be null."); - this.name = name; - this.type = type; - this.label = label; - this.childReference = childReference; - this.widget = widget; - this.range = range; - this.minimumValue = minimumValue; - this.maximumValue = maximumValue; - this.value = clampValue(value); - this.description = description; - this.menuItems = ImmutableList.copyOf(menuItems); - this.hashCode = Objects.hashCode(name, type, value); - } - - public String getName() { - return name; - } - - public String getLabel() { - return label; - } - - public String getDisplayLabel() { - if (label != null && ! label.isEmpty()) return label; - return StringUtils.humanizeName(name); - } - - public String getType() { - return type; - } - - public String getDescription() { - return description; - } - - public boolean isPublishedPort() { - return childReference != null; - } - - public String getChildReference() { - return childReference; - } - - public String getChildNodeName() { - return childReference == null ? null : childReference.split("\\.")[0]; - } - - public String getChildPortName() { - return childReference == null ? null : childReference.split("\\.")[1]; - } - - public Node getChildNode(Node network) { - return network.getChild(getChildNodeName()); - } - - public Port getChildPort(Node network) { - Node child = network.getChild(getChildNodeName()); - return child.getInput(getChildPortName()); - } - - public Range getRange() { - return range; - } - - public boolean hasValueRange() { - return range.equals(Range.VALUE); - } - - public boolean hasListRange() { - return range.equals(Range.LIST); - } - - public Double getMinimumValue() { - return minimumValue; - } - - public Double getMaximumValue() { - return maximumValue; - } - - public boolean hasMenu() { - return !menuItems.isEmpty(); - } - - public List getMenuItems() { - return menuItems; - } - - /** - * Check if the Port type is a standard type, meaning it can be persisted, and its value can be accessed. - * - * @return true if this is a standard type. - */ - public boolean isStandardType() { - return STANDARD_TYPES.contains(type); - } - - /** - * Check if the Port type is a custom type. - * - * @return true if this is a custom type. - */ - public boolean isCustomType() { - return !isStandardType(); - } - - /** - * Return the value stored in the port as a long. - *

    - *
  • Integers are returned as-is.
  • - *
  • Floats are rounded using Math.round().
  • - *
  • Other types return 0.
  • - *
- * - * @return The value as a long or 0 if the value cannot be converted. - */ - public long intValue() { - checkValueType(); - if (type.equals(TYPE_INT)) { - return (Long) value; - } else if (type.equals(TYPE_FLOAT)) { - return Math.round((Double) value); - } else { - return 0L; - } - } - - /** - * Return the value stored in the port as a Float. - *
    - *
  • Integers are converted to Floats.
  • - *
  • Floats are returned as-is.
  • - *
  • Other types return 0f.
  • - *
- * - * @return The value as a Float or 0f if the value cannot be converted. - */ - public double floatValue() { - checkValueType(); - if (type.equals(TYPE_INT)) { - return ((Long) value).doubleValue(); - } else if (type.equals(TYPE_FLOAT)) { - return (Double) value; - } else { - return 0.0; - } - } - - /** - * Return the value stored in the port as a String. - *

- * This conversion simply uses String.valueOf(), which does the right thing. - * - * @return The value as a String or "null" if the value is null. (for custom types) - * @see String#valueOf(Object) - */ - public String stringValue() { - checkValueType(); - return String.valueOf(value); - } - - /** - * Return the value stored in the port as a boolean. - *

- * If the port has a different type, false is returned. - * - * @return The value as a Float or 0f if the value cannot be converted. - */ - public boolean booleanValue() { - checkValueType(); - if (type.equals(TYPE_BOOLEAN)) { - return (Boolean) value; - } else { - return false; - } - } - - /** - * Return the value stored in the port as a Port. - *

- * If the port has a different type, Point.ZERO is returned. - * - * @return The value as a Point or Point.ZERO if the value is of an incorrect type. - */ - public Point pointValue() { - checkValueType(); - if (type.equals(TYPE_POINT)) { - return (Point) value; - } else { - return Point.ZERO; - } - } - - public Color colorValue() { - checkValueType(); - if (type.equals(TYPE_COLOR)) { - return (Color) value; - } else { - return Color.BLACK; - } - } - - /** - * Return the value stored in the port as an Object. - *

- * If this is a port with a custom type, this method returns null. - * - * @return The value as an Object or null. - */ - public Object getValue() { - checkValueType(); - return value; - } - - //// Shim implementations of methods //// - - public boolean hasExpression() { - return false; - } - - public String getExpression() { - return ""; - } - - public boolean isEnabled() { - return true; - } - - public Widget getWidget() { - return widget; - } - - public boolean isFileWidget() { - return widget == Widget.FILE || widget == Widget.IMAGE; - } - - //// Mutation methods //// - - public Port withLabel(String label) { - return new Port(getName(), getType(), label, getChildReference(), getWidget(), getRange(), getValue(), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - public Port withDescription(String description) { - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), getValue(), description, getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - public Port withChildReference(Node childNode, Port childPort) { - checkNotNull(childNode); - checkNotNull(childPort); - String childReference = buildChildReference(childNode, childPort); - return new Port(getName(), getType(), this.label, childReference, getWidget(), getRange(), getValue(), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - private static String buildChildReference(Node childNode, Port childPort) { - checkNotNull(childNode); - checkNotNull(childPort); - return String.format("%s.%s", childNode.getName(), childPort.getName()); - } - - /** - * Return a new Port with the value set to the given value. - * - * @param value The new value. This must be of the correct type. - * @return The new Port. - * @throws IllegalStateException If you're trying to change the value of a standard type, or you give the wrong value. - */ - public Port withValue(Object value) { - checkState(isStandardType(), "You can only change the value of a standard type."); - checkArgument(correctValueForType(value), "Value '%s' is not correct for %s port.", value, getType()); - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), clampValue(convertValue(getType(), value)), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - /** - * Return a new Port with the widget set to the given widget value. - * - * @param widget The new widget. - * @return The new Port. - */ - public Port withWidget(Widget widget) { - return new Port(getName(), getType(), getLabel(), getChildReference(), widget, getRange(), getValue(), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - /** - * Return a new Port with the range set to the given range value. - * - * @param range The new range. - * @return The new Port. - */ - public Port withRange(Range range) { - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), range, getValue(), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - /** - * Convert integers to longs and floats to doubles. All other values are passed through as-is. - * - * @param type The expected type. - * @param value The original value. - * @return The converted value. - */ - private Object convertValue(String type, Object value) { - if (value instanceof Integer) { - checkArgument(type.equals(TYPE_INT)); - return (long) ((Integer) value); - } else if (value instanceof Float) { - checkArgument(type.equals(TYPE_FLOAT)); - return (double) ((Float) value); - } else { - return value; - } - } - - /** - * Convert integers to longs and floats to doubles. All other values are passed through as-is. - * - * @param value The original value. - * @return The converted value. - */ - public Object clampValue(Object value) { - if (getType().equals(TYPE_FLOAT)) { - return clamp((Double) value); - } else if (getType().equals(TYPE_INT)) { - return (long) clamp(((Long) value).doubleValue()); - } else { - return value; - } - } - - private double clamp(double v) { - if (minimumValue != null && v < minimumValue) { - return minimumValue; - } else if (maximumValue != null && v > maximumValue) { - return maximumValue; - } else { - return v; - } - } - - private void checkValueType() { - checkState(correctValueForType(this.value), "The internal value %s is not a %s.", value, type); - } - - private boolean correctValueForType(Object value) { - if (type.equals(TYPE_INT)) { - return value instanceof Long || value instanceof Integer; - } else if (type.equals(TYPE_FLOAT)) { - return value instanceof Double || value instanceof Float; - } else if (type.equals(TYPE_STRING)) { - return value instanceof String; - } else if (type.equals(TYPE_BOOLEAN)) { - return value instanceof Boolean; - } else if (type.equals(TYPE_POINT)) { - return value instanceof Point; - } else if (type.equals(TYPE_COLOR)) { - return value instanceof Color; - } else { - // The value of a custom type should always be null. - return value == null; - } - } - - public Object getAttributeValue(Attribute attribute) { - if (attribute == Attribute.NAME) { - return getName(); - } else if (attribute == Attribute.TYPE) { - return getType(); - } else if (attribute == Attribute.LABEL) { - return getLabel(); - } else if (attribute == Attribute.DESCRIPTION) { - return getDescription(); - } else if (attribute == Attribute.CHILD_REFERENCE) { - return getChildReference(); - } else if (attribute == Attribute.WIDGET) { - return getWidget(); - } else if (attribute == Attribute.RANGE) { - return getRange(); - } else if (attribute == Attribute.MINIMUM_VALUE) { - return getMinimumValue(); - } else if (attribute == Attribute.MAXIMUM_VALUE) { - return getMaximumValue(); - } else if (attribute == Attribute.MENU_ITEMS) { - return getMenuItems(); - } else { - throw new AssertionError("Unknown port attribute " + attribute); - } - } - - public static Object parseValue(String type, String valueString) { - if (type.equals("int")) { - return Long.valueOf(valueString); - } else if (type.equals("float")) { - return Double.valueOf(valueString); - } else if (type.equals("string")) { - return valueString; - } else if (type.equals("boolean")) { - return Boolean.valueOf(valueString); - } else if (type.equals("point")) { - return Point.valueOf(valueString); - } else if (type.equals("color")) { - return Color.valueOf(valueString); - } else { - throw new AssertionError("Unknown type " + type); - } - } - - private static Widget parseWidget(String valueString) { - return Widget.valueOf(valueString.toUpperCase(Locale.US)); - } - - private static Range parseRange(String valueString) { - if (valueString.equals("value")) - return Range.VALUE; - else if (valueString.equals("list")) - return Range.LIST; - else - throw new AssertionError("Unknown range " + valueString); - } - - public Port withMinimumValue(Double minimumValue) { - checkArgument(type.equals(Port.TYPE_INT) || type.equals(Port.TYPE_FLOAT), - "You can only set a minimum value on int or float ports, not %s", this); - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), getValue(), getDescription(), minimumValue, getMaximumValue(), getMenuItems()); - } - - public Port withMaximumValue(Double maximumValue) { - checkArgument(type.equals(Port.TYPE_INT) || type.equals(Port.TYPE_FLOAT), - "You can only set a maximum value on int or float ports, not %s", this); - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), getValue(), getDescription(), getMinimumValue(), maximumValue, getMenuItems()); - } - - public Port withMenuItems(Iterable items) { - checkNotNull(items); - checkArgument(type.equals(Port.TYPE_STRING), "You can only use menu items on string ports, not %s", this); - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), getValue(), getDescription(), getMinimumValue(), getMaximumValue(), items); - } - - public Port withMenuItemAdded(String key, String label) { - ImmutableList.Builder b = ImmutableList.builder(); - b.addAll(menuItems); - b.add(new MenuItem(key, label)); - return withMenuItems(b.build()); - } - - public Port withMenuItemRemoved(MenuItem menuItem) { - ImmutableList.Builder b = ImmutableList.builder(); - for (MenuItem item : menuItems) { - if (item.equals(menuItem)) { - // Do nothing - } else { - b.add(item); - } - } - return withMenuItems(b.build()); - } - - public Port withMenuItemMovedUp(int index) { - checkArgument(0 < index && index < menuItems.size()); - return withMenuItemMoved(index, index - 1); - } - - public Port withMenuItemMovedDown(int index) { - checkArgument(0 <= index && index < menuItems.size() - 1); - return withMenuItemMoved(index, index + 1); - } - - private Port withMenuItemMoved(int fromIndex, int toIndex) { - List items = new ArrayList(0); - items.addAll(menuItems); - MenuItem item = items.get(fromIndex); - items.remove(item); - items.add(toIndex, item); - return withMenuItems(ImmutableList.copyOf(items)); - } - - public Port withMenuItemChanged(int index, String key, String label) { - checkArgument(0 <= index && index < menuItems.size()); - List items = new ArrayList(0); - items.addAll(menuItems); - items.set(index, new MenuItem(key, label)); - return withMenuItems(ImmutableList.copyOf(items)); - } - - public Port withParsedAttribute(Attribute attribute, String valueString) { - checkNotNull(valueString); - - String name = this.name; - String type = this.type; - String label = this.label; - String childReference = this.childReference; - Widget widget = this.widget; - Range range = this.range; - Object value = this.value; - String description = this.description; - Double minimumValue = this.minimumValue; - Double maximumValue = this.maximumValue; - - switch (attribute) { - case LABEL: - label = valueString; - break; - case DESCRIPTION: - description = valueString; - break; - case CHILD_REFERENCE: - childReference = valueString; - break; - case VALUE: - checkArgument(STANDARD_TYPES.contains(type), "Port %s: you can only set the value for one of the standard types, not %s (value=%s)", name, type, valueString); - value = parseValue(type, valueString); - break; - case WIDGET: - widget = parseWidget(valueString); - break; - case RANGE: - range = parseRange(valueString); - break; - case MINIMUM_VALUE: - minimumValue = Double.valueOf(valueString); - break; - case MAXIMUM_VALUE: - maximumValue = Double.valueOf(valueString); - break; - default: - throw new AssertionError("You cannot use withParsedAttribute with attribute " + attribute); - } - return new Port(name, type, label, childReference, widget, range, value, description, minimumValue, maximumValue, getMenuItems()); - } - - //// Object overrides //// - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof Port)) return false; - final Port other = (Port) o; - return Objects.equal(name, other.name) - && Objects.equal(type, other.type) - && Objects.equal(label, other.label) - && Objects.equal(value, other.value) - && Objects.equal(description, other.description); - } - - @Override - public String toString() { - return String.format("", name, type, value); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/old/Port.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/old/Port.java deleted file mode 100755 index b23a072..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/old/Port.java +++ /dev/null @@ -1,809 +0,0 @@ -package nodebox.node; - -import com.google.common.base.Objects; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import nodebox.graphics.Color; -import nodebox.graphics.Point; -import nodebox.util.StringUtils; - -import java.util.ArrayList; -import java.util.List; - -import static com.google.common.base.Preconditions.*; - -public final class Port { - - public static final String TYPE_INT = "int"; - public static final String TYPE_FLOAT = "float"; - public static final String TYPE_STRING = "string"; - public static final String TYPE_BOOLEAN = "boolean"; - public static final String TYPE_POINT = "point"; - public static final String TYPE_COLOR = "color"; - public static final String TYPE_LIST = "list"; - public static final String TYPE_GEOMETRY = "geometry"; - public static final String TYPE_CONTEXT = "context"; - public static final String TYPE_STATE = "state"; - - public enum Attribute {NAME, TYPE, LABEL, CHILD_REFERENCE, WIDGET, RANGE, VALUE, DESCRIPTION, MINIMUM_VALUE, MAXIMUM_VALUE, MENU_ITEMS} - - /** - * The UI control for this port. This defines how the port is represented in the user interface. - */ - public enum Widget { - NONE, ANGLE, COLOR, DATA, FILE, FLOAT, FONT, GRADIENT, IMAGE, INT, MENU, SEED, STRING, TEXT, PASSWORD, TOGGLE, POINT - } - - public enum Direction { - INPUT, OUTPUT - } - - public enum Range { - VALUE, LIST - } - - public static final Range DEFAULT_RANGE = Range.VALUE; - - public static final ImmutableMap DEFAULT_VALUES; - public static final ImmutableSet STANDARD_TYPES; - public static final ImmutableMap> WIDGET_MAPPING; - - static { - ImmutableMap.Builder b = ImmutableMap.builder(); - b.put(TYPE_INT, 0L); - b.put(TYPE_FLOAT, 0.0); - b.put(TYPE_BOOLEAN, false); - b.put(TYPE_STRING, ""); - b.put(TYPE_POINT, Point.ZERO); - b.put(TYPE_COLOR, Color.BLACK); - DEFAULT_VALUES = b.build(); - STANDARD_TYPES = ImmutableSet.of(TYPE_INT, TYPE_FLOAT, TYPE_BOOLEAN, TYPE_STRING, TYPE_POINT, TYPE_COLOR); - - ImmutableMap.Builder> w = ImmutableMap.builder(); - w.put(TYPE_INT, ImmutableList.of(Widget.INT, Widget.SEED)); - w.put(TYPE_FLOAT, ImmutableList.of(Widget.ANGLE, Widget.FLOAT)); - w.put(TYPE_BOOLEAN, ImmutableList.of(Widget.TOGGLE)); - w.put(TYPE_STRING, ImmutableList.of(Widget.DATA, Widget.FILE, Widget.FONT, Widget.IMAGE, Widget.MENU, Widget.STRING, Widget.TEXT)); - w.put(TYPE_POINT, ImmutableList.of(Widget.POINT)); - w.put(TYPE_COLOR, ImmutableList.of(Widget.COLOR)); - WIDGET_MAPPING = w.build(); - } - - private final String name; - private final String type; - private final String label; - private final String description; - private final String childReference; - private final Widget widget; - private final Range range; - private final Object value; - private final Double minimumValue; - private final Double maximumValue; - private final ImmutableList menuItems; - - private final transient int hashCode; - - public static Port intPort(String name, long value) { - return intPort(name, value, null, null); - } - - public static Port intPort(String name, long value, Integer minimumValue, Integer maximumValue) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_INT, value, minimumValue != null ? minimumValue.doubleValue() : null, maximumValue != null ? maximumValue.doubleValue() : null); - } - - public static Port floatPort(String name, double value) { - return floatPort(name, value, null, null); - } - - public static Port floatPort(String name, double value, Double minimumValue, Double maximumValue) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_FLOAT, value, minimumValue, maximumValue); - } - - public static Port booleanPort(String name, boolean value) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_BOOLEAN, value); - } - - public static Port stringPort(String name, String value) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_STRING, value); - } - - public static Port stringPort(String name, String value, Iterable menuItems) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_STRING, value, menuItems); - } - - public static Port pointPort(String name, Point value) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_POINT, value); - } - - public static Port colorPort(String name, Color value) { - checkNotNull(value, "Value cannot be null."); - return new Port(name, TYPE_COLOR, value); - } - - public static Port customPort(String name, String type) { - checkNotNull(type, "Type cannot be null."); - return new Port(name, type, null); - } - - public static Port publishedPort(Node childNode, Port childPort, String publishedName) { - checkNotNull(childNode); - checkNotNull(childPort); - String childReference = buildChildReference(childNode, childPort); - return new Port(publishedName, childPort.getType(), "", childReference, childPort.getWidget(), childPort.getRange(), childPort.getValue(), childPort.getDescription(), childPort.getMinimumValue(), childPort.getMaximumValue(), childPort.getMenuItems()); - } - - /** - * Parse the type and create the appropriate Port. Use the default value appropriate for the port type. - * - * @param name The port name. - * @param type The port type. - * @return A new Port. - */ - public static Port portForType(String name, String type) { - checkNotNull(type, "Type cannot be null."); - // If the type is not found in the default values, get() returns null, which is what we need for custom types. - return new Port(name, type, "", null, defaultWidgetForType(type), DEFAULT_RANGE, DEFAULT_VALUES.get(type), "", null, null, ImmutableList.of()); - } - - /** - * Create a new Port with the given value as a string parsed to the correct format. - * - * @param name The port name. - * @param type The port type. - * @param stringValue The port value as a string, e.g. "32.5". - * @return A new Port. - */ - - public static Port parsedPort(String name, String type, String stringValue) { - return parsedPort(name, type, "", "", DEFAULT_RANGE.toString().toLowerCase(), stringValue, "", null, null, ImmutableList.of()); - } - - /** - * Create a new Port with the given value as a string parsed to the correct format. - * - * @param name The port name. - * @param type The port type. - * @param valueString The port value as a string, e.g. "32.5". - * @param minString The minimum value as a string. - * @param maxString The maximum value as a string. - * @param menuItems The list of menu items. - * @return A new Port. - */ - public static Port parsedPort(String name, String type, String label, String widgetString, String rangeString, String valueString, String description, String minString, String maxString, ImmutableList menuItems) { - checkNotNull(name, "Name cannot be null."); - checkNotNull(type, "Type cannot be null."); - if (STANDARD_TYPES.contains(type)) { - Object value; - if (valueString == null) { - value = DEFAULT_VALUES.get(type); - checkNotNull(value); - } else { - if (type.equals("int")) { - value = Long.valueOf(valueString); - } else if (type.equals("float")) { - value = Double.valueOf(valueString); - } else if (type.equals("string")) { - value = valueString; - } else if (type.equals("boolean")) { - value = Boolean.valueOf(valueString); - } else if (type.equals("point")) { - value = Point.valueOf(valueString); - } else if (type.equals("color")) { - value = Color.valueOf(valueString); - } else { - throw new AssertionError("Unknown type " + type); - } - } - Widget widget; - if (widgetString != null && !widgetString.isEmpty()) { - widget = parseWidget(widgetString); - } else { - widget = Widget.NONE; - } - Range range = rangeString != null ? parseRange(rangeString) : DEFAULT_RANGE; - - Double minimumValue = null; - Double maximumValue = null; - if (minString != null) - minimumValue = Double.valueOf(minString); - if (maxString != null) - maximumValue = Double.valueOf(maxString); - return new Port(name, type, label, null, widget, range, value, description, minimumValue, maximumValue, menuItems); - } else { - return Port.customPort(name, type); - } - } - - public static Widget defaultWidgetForType(String type) { - checkNotNull(type, "Type cannot be null."); - if (type.equals(TYPE_INT)) { - return Widget.INT; - } else if (type.equals(TYPE_FLOAT)) { - return Widget.FLOAT; - } else if (type.equals(TYPE_STRING)) { - return Widget.STRING; - } else if (type.equals(TYPE_BOOLEAN)) { - return Widget.TOGGLE; - } else if (type.equals(TYPE_POINT)) { - return Widget.POINT; - } else if (type.equals(TYPE_COLOR)) { - return Widget.COLOR; - } else { - return Widget.NONE; - } - } - - private Port(String name, String type, Object value) { - this(name, type, "", null, defaultWidgetForType(type), DEFAULT_RANGE, value, "", null, null, ImmutableList.of()); - } - - private Port(String name, String type, Object value, Double minimumValue, Double maximumValue) { - this(name, type, "", null, defaultWidgetForType(type), DEFAULT_RANGE, value, "", minimumValue, maximumValue, ImmutableList.of()); - } - - private Port(String name, String type, Object value, Iterable menuItems) { - this(name, type, "", null, defaultWidgetForType(type), DEFAULT_RANGE, value, "", null, null, menuItems); - } - - private Port(String name, String type, String label, String childReference, Widget widget, Range range, Object value, String description, Double minimumValue, Double maximumValue, Iterable menuItems) { - checkNotNull(name, "Name cannot be null."); - checkNotNull(type, "Type cannot be null."); - checkNotNull(menuItems, "Menu items cannot be null."); - this.name = name; - this.type = type; - this.label = label; - this.childReference = childReference; - this.widget = widget; - this.range = range; - this.minimumValue = minimumValue; - this.maximumValue = maximumValue; - this.value = clampValue(value); - this.description = description; - this.menuItems = ImmutableList.copyOf(menuItems); - this.hashCode = Objects.hashCode(name, type, value); - } - - public String getName() { - return name; - } - - public String getLabel() { - return label; - } - - public String getDisplayLabel() { - if (label != null && ! label.isEmpty()) return label; - return StringUtils.humanizeName(name); - } - - public String getType() { - return type; - } - - public String getDescription() { - return description; - } - - public boolean isPublishedPort() { - return childReference != null; - } - - public String getChildReference() { - return childReference; - } - - public String getChildNodeName() { - return childReference == null ? null : childReference.split("\\.")[0]; - } - - public String getChildPortName() { - return childReference == null ? null : childReference.split("\\.")[1]; - } - - public Node getChildNode(Node network) { - return network.getChild(getChildNodeName()); - } - - public Port getChildPort(Node network) { - Node child = network.getChild(getChildNodeName()); - return child.getInput(getChildPortName()); - } - - public Range getRange() { - return range; - } - - public boolean hasValueRange() { - return range.equals(Range.VALUE); - } - - public boolean hasListRange() { - return range.equals(Range.LIST); - } - - public Double getMinimumValue() { - return minimumValue; - } - - public Double getMaximumValue() { - return maximumValue; - } - - public boolean hasMenu() { - return !menuItems.isEmpty(); - } - - public List getMenuItems() { - return menuItems; - } - - /** - * Check if the Port type is a standard type, meaning it can be persisted, and its value can be accessed. - * - * @return true if this is a standard type. - */ - public boolean isStandardType() { - return STANDARD_TYPES.contains(type); - } - - /** - * Check if the Port type is a custom type. - * - * @return true if this is a custom type. - */ - public boolean isCustomType() { - return !isStandardType(); - } - - /** - * Return the value stored in the port as a long. - *

    - *
  • Integers are returned as-is.
  • - *
  • Floats are rounded using Math.round().
  • - *
  • Other types return 0.
  • - *
- * - * @return The value as a long or 0 if the value cannot be converted. - */ - public long intValue() { - checkValueType(); - if (type.equals(TYPE_INT)) { - return (Long) value; - } else if (type.equals(TYPE_FLOAT)) { - return Math.round((Double) value); - } else { - return 0L; - } - } - - /** - * Return the value stored in the port as a Float. - *
    - *
  • Integers are converted to Floats.
  • - *
  • Floats are returned as-is.
  • - *
  • Other types return 0f.
  • - *
- * - * @return The value as a Float or 0f if the value cannot be converted. - */ - public double floatValue() { - checkValueType(); - if (type.equals(TYPE_INT)) { - return ((Long) value).doubleValue(); - } else if (type.equals(TYPE_FLOAT)) { - return (Double) value; - } else { - return 0.0; - } - } - - /** - * Return the value stored in the port as a String. - *

- * This conversion simply uses String.valueOf(), which does the right thing. - * - * @return The value as a String or "null" if the value is null. (for custom types) - * @see String#valueOf(Object) - */ - public String stringValue() { - checkValueType(); - return String.valueOf(value); - } - - /** - * Return the value stored in the port as a boolean. - *

- * If the port has a different type, false is returned. - * - * @return The value as a Float or 0f if the value cannot be converted. - */ - public boolean booleanValue() { - checkValueType(); - if (type.equals(TYPE_BOOLEAN)) { - return (Boolean) value; - } else { - return false; - } - } - - /** - * Return the value stored in the port as a Port. - *

- * If the port has a different type, Point.ZERO is returned. - * - * @return The value as a Point or Point.ZERO if the value is of an incorrect type. - */ - public Point pointValue() { - checkValueType(); - if (type.equals(TYPE_POINT)) { - return (Point) value; - } else { - return Point.ZERO; - } - } - - public Color colorValue() { - checkValueType(); - if (type.equals(TYPE_COLOR)) { - return (Color) value; - } else { - return Color.BLACK; - } - } - - /** - * Return the value stored in the port as an Object. - *

- * If this is a port with a custom type, this method returns null. - * - * @return The value as an Object or null. - */ - public Object getValue() { - checkValueType(); - return value; - } - - //// Shim implementations of methods //// - - public boolean hasExpression() { - return false; - } - - public String getExpression() { - return ""; - } - - public boolean isEnabled() { - return true; - } - - public Widget getWidget() { - return widget; - } - - public boolean isFileWidget() { - return widget == Widget.FILE || widget == Widget.IMAGE; - } - - //// Mutation methods //// - - public Port withLabel(String label) { - return new Port(getName(), getType(), label, getChildReference(), getWidget(), getRange(), getValue(), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - public Port withDescription(String description) { - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), getValue(), description, getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - public Port withChildReference(Node childNode, Port childPort) { - checkNotNull(childNode); - checkNotNull(childPort); - String childReference = buildChildReference(childNode, childPort); - return new Port(getName(), getType(), this.label, childReference, getWidget(), getRange(), getValue(), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - private static String buildChildReference(Node childNode, Port childPort) { - checkNotNull(childNode); - checkNotNull(childPort); - return String.format("%s.%s", childNode.getName(), childPort.getName()); - } - - /** - * Return a new Port with the value set to the given value. - * - * @param value The new value. This must be of the correct type. - * @return The new Port. - * @throws IllegalStateException If you're trying to change the value of a standard type, or you give the wrong value. - */ - public Port withValue(Object value) { - checkState(isStandardType(), "You can only change the value of a standard type."); - checkArgument(correctValueForType(value), "Value '%s' is not correct for %s port.", value, getType()); - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), clampValue(convertValue(getType(), value)), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - /** - * Return a new Port with the widget set to the given widget value. - * - * @param widget The new widget. - * @return The new Port. - */ - public Port withWidget(Widget widget) { - return new Port(getName(), getType(), getLabel(), getChildReference(), widget, getRange(), getValue(), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - /** - * Return a new Port with the range set to the given range value. - * - * @param range The new range. - * @return The new Port. - */ - public Port withRange(Range range) { - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), range, getValue(), getDescription(), getMinimumValue(), getMaximumValue(), getMenuItems()); - } - - /** - * Convert integers to longs and floats to doubles. All other values are passed through as-is. - * - * @param type The expected type. - * @param value The original value. - * @return The converted value. - */ - private Object convertValue(String type, Object value) { - if (value instanceof Integer) { - checkArgument(type.equals(TYPE_INT)); - return (long) ((Integer) value); - } else if (value instanceof Float) { - checkArgument(type.equals(TYPE_FLOAT)); - return (double) ((Float) value); - } else { - return value; - } - } - - /** - * Convert integers to longs and floats to doubles. All other values are passed through as-is. - * - * @param value The original value. - * @return The converted value. - */ - public Object clampValue(Object value) { - if (getType().equals(TYPE_FLOAT)) { - return clamp((Double) value); - } else if (getType().equals(TYPE_INT)) { - return (long) clamp(((Long) value).doubleValue()); - } else { - return value; - } - } - - private double clamp(double v) { - if (minimumValue != null && v < minimumValue) { - return minimumValue; - } else if (maximumValue != null && v > maximumValue) { - return maximumValue; - } else { - return v; - } - } - - private void checkValueType() { - checkState(correctValueForType(this.value), "The internal value %s is not a %s.", value, type); - } - - private boolean correctValueForType(Object value) { - if (type.equals(TYPE_INT)) { - return value instanceof Long || value instanceof Integer; - } else if (type.equals(TYPE_FLOAT)) { - return value instanceof Double || value instanceof Float; - } else if (type.equals(TYPE_STRING)) { - return value instanceof String; - } else if (type.equals(TYPE_BOOLEAN)) { - return value instanceof Boolean; - } else if (type.equals(TYPE_POINT)) { - return value instanceof Point; - } else if (type.equals(TYPE_COLOR)) { - return value instanceof Color; - } else { - // The value of a custom type should always be null. - return value == null; - } - } - - public Object getAttributeValue(Attribute attribute) { - if (attribute == Attribute.NAME) { - return getName(); - } else if (attribute == Attribute.TYPE) { - return getType(); - } else if (attribute == Attribute.LABEL) { - return getLabel(); - } else if (attribute == Attribute.DESCRIPTION) { - return getDescription(); - } else if (attribute == Attribute.CHILD_REFERENCE) { - return getChildReference(); - } else if (attribute == Attribute.WIDGET) { - return getWidget(); - } else if (attribute == Attribute.RANGE) { - return getRange(); - } else if (attribute == Attribute.MINIMUM_VALUE) { - return getMinimumValue(); - } else if (attribute == Attribute.MAXIMUM_VALUE) { - return getMaximumValue(); - } else if (attribute == Attribute.MENU_ITEMS) { - return getMenuItems(); - } else { - throw new AssertionError("Unknown port attribute " + attribute); - } - } - - public static Object parseValue(String type, String valueString) { - if (type.equals("int")) { - return Long.valueOf(valueString); - } else if (type.equals("float")) { - return Double.valueOf(valueString); - } else if (type.equals("string")) { - return valueString; - } else if (type.equals("boolean")) { - return Boolean.valueOf(valueString); - } else if (type.equals("point")) { - return Point.valueOf(valueString); - } else if (type.equals("color")) { - return Color.valueOf(valueString); - } else { - throw new AssertionError("Unknown type " + type); - } - } - - private static Widget parseWidget(String valueString) { - return Widget.valueOf(valueString.toUpperCase()); - } - - private static Range parseRange(String valueString) { - if (valueString.equals("value")) - return Range.VALUE; - else if (valueString.equals("list")) - return Range.LIST; - else - throw new AssertionError("Unknown range " + valueString); - } - - public Port withMinimumValue(Double minimumValue) { - checkArgument(type.equals(Port.TYPE_INT) || type.equals(Port.TYPE_FLOAT), - "You can only set a minimum value on int or float ports, not %s", this); - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), getValue(), getDescription(), minimumValue, getMaximumValue(), getMenuItems()); - } - - public Port withMaximumValue(Double maximumValue) { - checkArgument(type.equals(Port.TYPE_INT) || type.equals(Port.TYPE_FLOAT), - "You can only set a maximum value on int or float ports, not %s", this); - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), getValue(), getDescription(), getMinimumValue(), maximumValue, getMenuItems()); - } - - public Port withMenuItems(Iterable items) { - checkNotNull(items); - checkArgument(type.equals(Port.TYPE_STRING), "You can only use menu items on string ports, not %s", this); - return new Port(getName(), getType(), getLabel(), getChildReference(), getWidget(), getRange(), getValue(), getDescription(), getMinimumValue(), getMaximumValue(), items); - } - - public Port withMenuItemAdded(String key, String label) { - ImmutableList.Builder b = ImmutableList.builder(); - b.addAll(menuItems); - b.add(new MenuItem(key, label)); - return withMenuItems(b.build()); - } - - public Port withMenuItemRemoved(MenuItem menuItem) { - ImmutableList.Builder b = ImmutableList.builder(); - for (MenuItem item : menuItems) { - if (item.equals(menuItem)) { - // Do nothing - } else { - b.add(item); - } - } - return withMenuItems(b.build()); - } - - public Port withMenuItemMovedUp(int index) { - checkArgument(0 < index && index < menuItems.size()); - return withMenuItemMoved(index, index - 1); - } - - public Port withMenuItemMovedDown(int index) { - checkArgument(0 <= index && index < menuItems.size() - 1); - return withMenuItemMoved(index, index + 1); - } - - private Port withMenuItemMoved(int fromIndex, int toIndex) { - List items = new ArrayList(0); - items.addAll(menuItems); - MenuItem item = items.get(fromIndex); - items.remove(item); - items.add(toIndex, item); - return withMenuItems(ImmutableList.copyOf(items)); - } - - public Port withMenuItemChanged(int index, String key, String label) { - checkArgument(0 <= index && index < menuItems.size()); - List items = new ArrayList(0); - items.addAll(menuItems); - items.set(index, new MenuItem(key, label)); - return withMenuItems(ImmutableList.copyOf(items)); - } - - public Port withParsedAttribute(Attribute attribute, String valueString) { - checkNotNull(valueString); - - String name = this.name; - String type = this.type; - String label = this.label; - String childReference = this.childReference; - Widget widget = this.widget; - Range range = this.range; - Object value = this.value; - String description = this.description; - Double minimumValue = this.minimumValue; - Double maximumValue = this.maximumValue; - - switch (attribute) { - case LABEL: - label = valueString; - break; - case DESCRIPTION: - description = valueString; - break; - case CHILD_REFERENCE: - childReference = valueString; - break; - case VALUE: - checkArgument(STANDARD_TYPES.contains(type), "Port %s: you can only set the value for one of the standard types, not %s (value=%s)", name, type, valueString); - value = parseValue(type, valueString); - break; - case WIDGET: - widget = parseWidget(valueString); - break; - case RANGE: - range = parseRange(valueString); - break; - case MINIMUM_VALUE: - minimumValue = Double.valueOf(valueString); - break; - case MAXIMUM_VALUE: - maximumValue = Double.valueOf(valueString); - break; - default: - throw new AssertionError("You cannot use withParsedAttribute with attribute " + attribute); - } - return new Port(name, type, label, childReference, widget, range, value, description, minimumValue, maximumValue, getMenuItems()); - } - - //// Object overrides //// - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object o) { - if (!(o instanceof Port)) return false; - final Port other = (Port) o; - return Objects.equal(name, other.name) - && Objects.equal(type, other.type) - && Objects.equal(label, other.label) - && Objects.equal(value, other.value) - && Objects.equal(description, other.description); - } - - @Override - public String toString() { - return String.format("", name, type, value); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/pair.info deleted file mode 100755 index 9330c73..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5180/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:5180 -comSha:0c35772c49974aa16da5d6c7f012c01236f009d9 -parentComSha:7fa5fc401efad5d78b011241ff420f37dbf44366 -BuggyFilePath:src/main/java/nodebox/node/Port.java -FixedFilePath:src/main/java/nodebox/node/Port.java -StartLineNum:165 -EndLineNum:165 -repoName:nodebox#nodebox \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/comMsg.txt deleted file mode 100755 index 978c561..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Use US locale everywhere when converting case. - -This fixes #400. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/diff.diff deleted file mode 100755 index 4f219a9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/nodebox/client/ObjectsRenderer.java b/src/main/java/nodebox/client/ObjectsRenderer.java -index e1c87d43..6674c016 100644 ---- a/src/main/java/nodebox/client/ObjectsRenderer.java -+++ b/src/main/java/nodebox/client/ObjectsRenderer.java -@@ -17,0 +18 @@ import java.io.IOException; -+import java.util.Locale; -@@ -24 +25 @@ public class ObjectsRenderer { -- if (file.getName().toLowerCase().endsWith(".pdf")) { -+ if (file.getName().toLowerCase(Locale.US).endsWith(".pdf")) { -@@ -27 +28 @@ public class ObjectsRenderer { -- } else if (file.getName().toLowerCase().endsWith(".svg")) { -+ } else if (file.getName().toLowerCase(Locale.US).endsWith(".svg")) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/new/ObjectsRenderer.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/new/ObjectsRenderer.java deleted file mode 100755 index 6674c01..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/new/ObjectsRenderer.java +++ /dev/null @@ -1,78 +0,0 @@ -package nodebox.client; - -import nodebox.client.visualizer.Visualizer; -import nodebox.client.visualizer.VisualizerFactory; -import nodebox.graphics.Drawable; -import nodebox.graphics.PDFRenderer; -import nodebox.graphics.SVGRenderer; -import nodebox.util.FileUtils; -import nodebox.util.ListUtils; - -import javax.imageio.ImageIO; -import java.awt.Color; -import java.awt.*; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.Locale; - -public class ObjectsRenderer { - - public static void render(Iterable objects, Rectangle2D bounds, File file) { - // TODO Remove reference to Viewer.getVisualizer. - Visualizer v = VisualizerFactory.getVisualizer(objects, ListUtils.listClass(objects)); - if (file.getName().toLowerCase(Locale.US).endsWith(".pdf")) { - LinkedVisualizer linkedVisualizer = new LinkedVisualizer(v, objects); - PDFRenderer.render(linkedVisualizer, bounds, file); - } else if (file.getName().toLowerCase(Locale.US).endsWith(".svg")) { - SVGRenderer.renderToFile(objects, bounds, file); - } else { - try { - ImageIO.write(createImage(objects, v, bounds, null), FileUtils.getExtension(file), file); - } catch (IOException e) { - throw new RuntimeException("Could not write image file " + file, e); - } - } - } - - public static BufferedImage createMovieImage(Iterable objects, Rectangle2D bounds) { - Visualizer v = VisualizerFactory.getVisualizer(objects, ListUtils.listClass(objects)); - return createImage(objects, v, bounds, Color.WHITE); - } - - private static BufferedImage createImage(Iterable objects, Visualizer visualizer, Rectangle2D bounds, Color backgroundColor) { - final int width = (int) Math.round(bounds.getWidth()); - final int height = (int) Math.round(bounds.getHeight()); - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = img.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - if (backgroundColor != null) { - g.setColor(backgroundColor); - g.fillRect(0, 0, width, height); - } - g.translate(-bounds.getX(), -bounds.getY()); - visualizer.draw(g, objects); - img.flush(); - return img; - } - - /** - * A visualizer linked to its objects. - */ - private static class LinkedVisualizer implements Drawable { - private Visualizer visualizer; - private Iterable objects; - - private LinkedVisualizer(Visualizer visualizer, Iterable objects) { - this.visualizer = visualizer; - this.objects = objects; - } - - @Override - public void draw(Graphics2D g) { - visualizer.draw(g, objects); - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/old/ObjectsRenderer.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/old/ObjectsRenderer.java deleted file mode 100755 index e1c87d4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/old/ObjectsRenderer.java +++ /dev/null @@ -1,77 +0,0 @@ -package nodebox.client; - -import nodebox.client.visualizer.Visualizer; -import nodebox.client.visualizer.VisualizerFactory; -import nodebox.graphics.Drawable; -import nodebox.graphics.PDFRenderer; -import nodebox.graphics.SVGRenderer; -import nodebox.util.FileUtils; -import nodebox.util.ListUtils; - -import javax.imageio.ImageIO; -import java.awt.Color; -import java.awt.*; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; - -public class ObjectsRenderer { - - public static void render(Iterable objects, Rectangle2D bounds, File file) { - // TODO Remove reference to Viewer.getVisualizer. - Visualizer v = VisualizerFactory.getVisualizer(objects, ListUtils.listClass(objects)); - if (file.getName().toLowerCase().endsWith(".pdf")) { - LinkedVisualizer linkedVisualizer = new LinkedVisualizer(v, objects); - PDFRenderer.render(linkedVisualizer, bounds, file); - } else if (file.getName().toLowerCase().endsWith(".svg")) { - SVGRenderer.renderToFile(objects, bounds, file); - } else { - try { - ImageIO.write(createImage(objects, v, bounds, null), FileUtils.getExtension(file), file); - } catch (IOException e) { - throw new RuntimeException("Could not write image file " + file, e); - } - } - } - - public static BufferedImage createMovieImage(Iterable objects, Rectangle2D bounds) { - Visualizer v = VisualizerFactory.getVisualizer(objects, ListUtils.listClass(objects)); - return createImage(objects, v, bounds, Color.WHITE); - } - - private static BufferedImage createImage(Iterable objects, Visualizer visualizer, Rectangle2D bounds, Color backgroundColor) { - final int width = (int) Math.round(bounds.getWidth()); - final int height = (int) Math.round(bounds.getHeight()); - BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D g = img.createGraphics(); - g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - if (backgroundColor != null) { - g.setColor(backgroundColor); - g.fillRect(0, 0, width, height); - } - g.translate(-bounds.getX(), -bounds.getY()); - visualizer.draw(g, objects); - img.flush(); - return img; - } - - /** - * A visualizer linked to its objects. - */ - private static class LinkedVisualizer implements Drawable { - private Visualizer visualizer; - private Iterable objects; - - private LinkedVisualizer(Visualizer visualizer, Iterable objects) { - this.visualizer = visualizer; - this.objects = objects; - } - - @Override - public void draw(Graphics2D g) { - visualizer.draw(g, objects); - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/pair.info deleted file mode 100755 index 45233c0..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5185/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:5185 -comSha:2fc22b4e8894fc318ee21a5355df8815786190d3 -parentComSha:274890519fd60ac0097fe47e00ec510b285260d5 -BuggyFilePath:src/main/java/nodebox/client/ObjectsRenderer.java -FixedFilePath:src/main/java/nodebox/client/ObjectsRenderer.java -StartLineNum:24 -EndLineNum:24 -repoName:nodebox#nodebox \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/comMsg.txt deleted file mode 100755 index 3aa5042..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'release/2.1' \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/diff.diff deleted file mode 100755 index 927c7bd..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/TypeDefinition.java b/util/src/main/java/com/psddev/dari/util/TypeDefinition.java -index 6d89afc8..2141d3c2 100644 ---- a/util/src/main/java/com/psddev/dari/util/TypeDefinition.java -+++ b/util/src/main/java/com/psddev/dari/util/TypeDefinition.java -@@ -14,0 +15 @@ import java.util.List; -+import java.util.Locale; -@@ -372 +373 @@ public class TypeDefinition { -- ? nameMatcher.group(3).toLowerCase() + nameMatcher.group(4) -+ ? nameMatcher.group(3).toLowerCase(Locale.ENGLISH) + nameMatcher.group(4) -@@ -412 +413 @@ public class TypeDefinition { -- setters.put(nameMatcher.group(1).toLowerCase() + nameMatcher.group(2), method); -+ setters.put(nameMatcher.group(1).toLowerCase(Locale.ENGLISH) + nameMatcher.group(2), method); -@@ -425,3 +425,0 @@ public class TypeDefinition { -- private Static() { -- } -- \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/new/TypeDefinition.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/new/TypeDefinition.java deleted file mode 100755 index 2141d3c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/new/TypeDefinition.java +++ /dev/null @@ -1,431 +0,0 @@ -package com.psddev.dari.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; - -public class TypeDefinition { - - private final Type type; - - /** Returns an instance based on the given {@code type}. */ - public static TypeDefinition getInstance(Type type) { - return INSTANCES.get(type); - } - - private static final PullThroughCache> - INSTANCES = new PullThroughCache>() { - - @Override - protected TypeDefinition produce(Type type) { - return new TypeDefinition(type); - } - }; - - /** Returns an instance based on the given {@code objectClass}. */ - @SuppressWarnings("unchecked") - public static TypeDefinition getInstance(Class objectClass) { - return (TypeDefinition) getInstance((Type) objectClass); - } - - /** Returns an instance based on the given {@code typeReference}. */ - @SuppressWarnings("unchecked") - public static TypeDefinition getInstance(TypeReference typeReference) { - return (TypeDefinition) getInstance(typeReference.getType()); - } - - /** Creates an instance based on the given {@code type}. */ - protected TypeDefinition(Type type) { - this.type = type; - } - - /** - * Returns the defintion's Type, including any Generic Parameters it knows about - * ex. TypeDefinition.getInstance(new TypeReference>() { }).getType(); // List - * A TypeReference needs to be provided to getInstance in order for the Parameterized - * type information to be retained (type erasure) - */ - public Type getType() { - return type; - } - - /** - * Returns the defintion's Class, not including any Generic Parameters it knows about - * ex. TypeDefinition.getInstance(new TypeReference>() { }).getObjectClass(); // List - */ - @SuppressWarnings("unchecked") - public Class getObjectClass() { - - Type type = getType(); - if (type instanceof Class) { - return (Class) type; - - } else if (type instanceof ParameterizedType) { - return (Class) ((ParameterizedType) type).getRawType(); - - } else { - throw new IllegalStateException(String.format( - "Cannot find an object class based on [%s] type!", - type)); - } - } - - /** - * Returns an unmodifiable list of all the classes that can be assigned - * from this one with the most specific match (itself) first. - */ - public List> getAssignableClasses() { - return assignableClasses.get(); - } - - private final PullThroughValue>> - assignableClasses = new PullThroughValue>>() { - - @Override - protected List> produce() { - - Class objectClass = getObjectClass(); - List> classes = new ArrayList>(); - classes.add(objectClass); - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - classes.addAll(getInstance(superClass).getAssignableClasses()); - } - - return Collections.unmodifiableList(classes); - } - }; - - /** - * Returns an unmodifiable set of all classes and interfaces that are - * either the same as, or is a super class or super interface of, - * this type. - */ - public Set> getAssignableClassesAndInterfaces() { - return assignableClassesAndInterfaces.get(); - } - - private final transient PullThroughValue>> - assignableClassesAndInterfaces = new PullThroughValue>>() { - - @Override - protected Set> produce() { - Class objectClass = getObjectClass(); - Set> classes = new LinkedHashSet>(); - - classes.add(objectClass); - - for (Class interfaceClass : objectClass.getInterfaces()) { - classes.addAll(getInstance(interfaceClass).getAssignableClassesAndInterfaces()); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - classes.addAll(getInstance(superClass).getAssignableClassesAndInterfaces()); - } - - return Collections.unmodifiableSet(classes); - } - }; - - /** Returns an unmodifiable list of all the fields. */ - public List getAllFields() { - return allFields.get(); - } - - private final PullThroughValue> - allFields = new PullThroughValue>() { - - @Override - protected List produce() { - - Class objectClass = getObjectClass(); - List fields = new ArrayList(); - for (Field field : objectClass.getDeclaredFields()) { - field.setAccessible(true); - fields.add(field); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - fields.addAll(getInstance(superClass).getAllFields()); - } - - return Collections.unmodifiableList(fields); - } - }; - - /** - * Returns an unmodifiable map of all the serializable (non-static - * and non-transient) fields with the normalized names as keys. - */ - public Map> getAllSerializableFields() { - return allSerializableFields.get(); - } - - private final PullThroughValue>> - allSerializableFields = new PullThroughValue>>() { - - @Override - protected Map> produce() { - - Class objectClass = getObjectClass(); - Map> fieldsMap = new LinkedHashMap>(); - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - for (Map.Entry> entry : getInstance(superClass).getAllSerializableFields().entrySet()) { - fieldsMap.put(entry.getKey(), new ArrayList(entry.getValue())); - } - } - - for (Field field : objectClass.getDeclaredFields()) { - int mod = field.getModifiers(); - if (!Modifier.isStatic(mod) - && !Modifier.isTransient(mod)) { - - // Normalize common field name formats: - // _name, name_, fName or mName. - String name = field.getName(); - if (name.startsWith("_")) { - name = name.substring(1); - } else if (name.endsWith("_")) { - name = name.substring(0, name.length() - 1); - } else if (name.length() > 2 - && (name.charAt(0) == 'f' || name.charAt(0) == 'm') - && Character.isUpperCase(name.charAt(1))) { - name = Character.toLowerCase(name.charAt(1)) + name.substring(2); - } - - List fields = fieldsMap.get(name); - if (fields == null) { - fields = new ArrayList(); - fieldsMap.put(name, fields); - } - - field.setAccessible(true); - fields.add(field); - } - } - - return fieldsMap; - } - }; - - /** Returns the first field with the given {@code name}. */ - public Field getField(String name) { - for (Field field : getAllFields()) { - if (field.getName().equals(name)) { - return field; - } - } - List fields = getAllSerializableFields().get(name); - return ObjectUtils.isBlank(fields) ? null : fields.get(fields.size() - 1); - } - - /** Returns an unmodifiable list of all the constructors. */ - public List> getConstructors() { - return constructors.get(); - } - - private final PullThroughValue>> - constructors = new PullThroughValue>>() { - - @Override - @SuppressWarnings("unchecked") - protected List> produce() { - List> constructors = new ArrayList>(); - for (Constructor constructor : getObjectClass().getDeclaredConstructors()) { - constructor.setAccessible(true); - constructors.add((Constructor) constructor); - } - return Collections.unmodifiableList(constructors); - } - }; - - /** - * Returns the constructor that can be called with the given array of - * {@code parameterClasses}. - */ - public Constructor getConstructor(Class... parameterClasses) { - int length = parameterClasses.length; - NEXT_CONSTRUCTOR: - for (Constructor constructor : getConstructors()) { - Class[] declared = constructor.getParameterTypes(); - if (length == declared.length) { - - for (int i = 0; i < length; ++ i) { - if (!declared[i].isAssignableFrom(parameterClasses[i])) { - continue NEXT_CONSTRUCTOR; - } - } - - return (Constructor) constructor; - } - } - - return null; - } - - /** Creates a new instance. */ - public T newInstance() { - Constructor constructor = getConstructor(); - if (constructor == null) { - throw new IllegalStateException(String.format( - "Can't create an instance of [%s] without a nullary constructor!", - getObjectClass())); - } - - try { - return constructor.newInstance(); - - } catch (IllegalAccessException ex) { - throw new IllegalStateException(ex); - - } catch (InstantiationException ex) { - throw new IllegalStateException(String.format( - "Can't instantiate an instance of [%s]!", - getObjectClass()), ex); - - } catch (InvocationTargetException ex) { - Throwable cause = ex.getCause(); - if (cause == null) { - cause = ex; - } - throw cause instanceof RuntimeException ? - (RuntimeException) cause : - new RuntimeException(cause.getMessage(), cause); - } - } - - /** Returns an unmodifiable list of all the methods. */ - public List getAllMethods() { - return allMethods.get(); - } - - private final PullThroughValue> - allMethods = new PullThroughValue>() { - - @Override - protected List produce() { - - Class objectClass = getObjectClass(); - List methods = new ArrayList(); - for (Method method : objectClass.getDeclaredMethods()) { - method.setAccessible(true); - methods.add(method); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - methods.addAll(getInstance(superClass).getAllMethods()); - } - - return Collections.unmodifiableList(methods); - } - }; - - /** - * Returns an unmodifiable map of all the getters (public non-static - * methods that have no parameters and return a value) with the - * normalized names as keys. - */ - public Map getAllGetters() { - return allGetters.get(); - } - - private final PullThroughValue> - allGetters = new PullThroughValue>() { - - @Override - protected Map produce() { - - Map getters = new LinkedHashMap(); - for (Method method : getAllMethods()) { - if (method.getDeclaringClass() != Object.class) { - - int mod = method.getModifiers(); - if (Modifier.isPublic(mod) - && !Modifier.isStatic(mod) - && method.getReturnType() != void.class - && method.getReturnType() != Void.class - && method.getParameterTypes().length == 0) { - - String methodName = method.getName(); - Matcher nameMatcher = StringUtils.getMatcher(methodName, "^(get|(is|has))([^a-z])(.*)$"); - if (nameMatcher.matches()) { - - String name = ObjectUtils.isBlank(nameMatcher.group(2)) - ? nameMatcher.group(3).toLowerCase(Locale.ENGLISH) + nameMatcher.group(4) - : methodName; - getters.put(name, method); - } - } - } - } - - return Collections.unmodifiableMap(getters); - } - }; - - /** - * Returns an unmodifiable map of all the setters (public non-static - * methods that take one parameter and doesn't return anything) with the - * normalized names as keys. - */ - public Map getAllSetters() { - return allSetters.get(); - } - - private final PullThroughValue> - allSetters = new PullThroughValue>() { - - @Override - protected Map produce() { - - Map setters = new LinkedHashMap(); - for (Method method : getAllMethods()) { - if (method.getDeclaringClass() != Object.class) { - - int mod = method.getModifiers(); - if (Modifier.isPublic(mod) - && !Modifier.isStatic(mod) - && (method.getReturnType() == void.class || method.getReturnType() == Void.class) - && method.getParameterTypes().length == 1) { - - String methodName = method.getName(); - Matcher nameMatcher = StringUtils.getMatcher(methodName, "^set([^a-z])(.*)$"); - if (nameMatcher.matches()) { - setters.put(nameMatcher.group(1).toLowerCase(Locale.ENGLISH) + nameMatcher.group(2), method); - } - } - } - } - - return Collections.unmodifiableMap(setters); - } - }; - - /** {@link TypeDefinition} utility methods. */ - public static final class Static { - - /** Invalidates all caches. */ - public static void invalidateAll() { - INSTANCES.invalidate(); - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/old/TypeDefinition.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/old/TypeDefinition.java deleted file mode 100755 index 6d89afc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/old/TypeDefinition.java +++ /dev/null @@ -1,433 +0,0 @@ -package com.psddev.dari.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; - -public class TypeDefinition { - - private final Type type; - - /** Returns an instance based on the given {@code type}. */ - public static TypeDefinition getInstance(Type type) { - return INSTANCES.get(type); - } - - private static final PullThroughCache> - INSTANCES = new PullThroughCache>() { - - @Override - protected TypeDefinition produce(Type type) { - return new TypeDefinition(type); - } - }; - - /** Returns an instance based on the given {@code objectClass}. */ - @SuppressWarnings("unchecked") - public static TypeDefinition getInstance(Class objectClass) { - return (TypeDefinition) getInstance((Type) objectClass); - } - - /** Returns an instance based on the given {@code typeReference}. */ - @SuppressWarnings("unchecked") - public static TypeDefinition getInstance(TypeReference typeReference) { - return (TypeDefinition) getInstance(typeReference.getType()); - } - - /** Creates an instance based on the given {@code type}. */ - protected TypeDefinition(Type type) { - this.type = type; - } - - /** - * Returns the defintion's Type, including any Generic Parameters it knows about - * ex. TypeDefinition.getInstance(new TypeReference>() { }).getType(); // List - * A TypeReference needs to be provided to getInstance in order for the Parameterized - * type information to be retained (type erasure) - */ - public Type getType() { - return type; - } - - /** - * Returns the defintion's Class, not including any Generic Parameters it knows about - * ex. TypeDefinition.getInstance(new TypeReference>() { }).getObjectClass(); // List - */ - @SuppressWarnings("unchecked") - public Class getObjectClass() { - - Type type = getType(); - if (type instanceof Class) { - return (Class) type; - - } else if (type instanceof ParameterizedType) { - return (Class) ((ParameterizedType) type).getRawType(); - - } else { - throw new IllegalStateException(String.format( - "Cannot find an object class based on [%s] type!", - type)); - } - } - - /** - * Returns an unmodifiable list of all the classes that can be assigned - * from this one with the most specific match (itself) first. - */ - public List> getAssignableClasses() { - return assignableClasses.get(); - } - - private final PullThroughValue>> - assignableClasses = new PullThroughValue>>() { - - @Override - protected List> produce() { - - Class objectClass = getObjectClass(); - List> classes = new ArrayList>(); - classes.add(objectClass); - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - classes.addAll(getInstance(superClass).getAssignableClasses()); - } - - return Collections.unmodifiableList(classes); - } - }; - - /** - * Returns an unmodifiable set of all classes and interfaces that are - * either the same as, or is a super class or super interface of, - * this type. - */ - public Set> getAssignableClassesAndInterfaces() { - return assignableClassesAndInterfaces.get(); - } - - private final transient PullThroughValue>> - assignableClassesAndInterfaces = new PullThroughValue>>() { - - @Override - protected Set> produce() { - Class objectClass = getObjectClass(); - Set> classes = new LinkedHashSet>(); - - classes.add(objectClass); - - for (Class interfaceClass : objectClass.getInterfaces()) { - classes.addAll(getInstance(interfaceClass).getAssignableClassesAndInterfaces()); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - classes.addAll(getInstance(superClass).getAssignableClassesAndInterfaces()); - } - - return Collections.unmodifiableSet(classes); - } - }; - - /** Returns an unmodifiable list of all the fields. */ - public List getAllFields() { - return allFields.get(); - } - - private final PullThroughValue> - allFields = new PullThroughValue>() { - - @Override - protected List produce() { - - Class objectClass = getObjectClass(); - List fields = new ArrayList(); - for (Field field : objectClass.getDeclaredFields()) { - field.setAccessible(true); - fields.add(field); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - fields.addAll(getInstance(superClass).getAllFields()); - } - - return Collections.unmodifiableList(fields); - } - }; - - /** - * Returns an unmodifiable map of all the serializable (non-static - * and non-transient) fields with the normalized names as keys. - */ - public Map> getAllSerializableFields() { - return allSerializableFields.get(); - } - - private final PullThroughValue>> - allSerializableFields = new PullThroughValue>>() { - - @Override - protected Map> produce() { - - Class objectClass = getObjectClass(); - Map> fieldsMap = new LinkedHashMap>(); - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - for (Map.Entry> entry : getInstance(superClass).getAllSerializableFields().entrySet()) { - fieldsMap.put(entry.getKey(), new ArrayList(entry.getValue())); - } - } - - for (Field field : objectClass.getDeclaredFields()) { - int mod = field.getModifiers(); - if (!Modifier.isStatic(mod) - && !Modifier.isTransient(mod)) { - - // Normalize common field name formats: - // _name, name_, fName or mName. - String name = field.getName(); - if (name.startsWith("_")) { - name = name.substring(1); - } else if (name.endsWith("_")) { - name = name.substring(0, name.length() - 1); - } else if (name.length() > 2 - && (name.charAt(0) == 'f' || name.charAt(0) == 'm') - && Character.isUpperCase(name.charAt(1))) { - name = Character.toLowerCase(name.charAt(1)) + name.substring(2); - } - - List fields = fieldsMap.get(name); - if (fields == null) { - fields = new ArrayList(); - fieldsMap.put(name, fields); - } - - field.setAccessible(true); - fields.add(field); - } - } - - return fieldsMap; - } - }; - - /** Returns the first field with the given {@code name}. */ - public Field getField(String name) { - for (Field field : getAllFields()) { - if (field.getName().equals(name)) { - return field; - } - } - List fields = getAllSerializableFields().get(name); - return ObjectUtils.isBlank(fields) ? null : fields.get(fields.size() - 1); - } - - /** Returns an unmodifiable list of all the constructors. */ - public List> getConstructors() { - return constructors.get(); - } - - private final PullThroughValue>> - constructors = new PullThroughValue>>() { - - @Override - @SuppressWarnings("unchecked") - protected List> produce() { - List> constructors = new ArrayList>(); - for (Constructor constructor : getObjectClass().getDeclaredConstructors()) { - constructor.setAccessible(true); - constructors.add((Constructor) constructor); - } - return Collections.unmodifiableList(constructors); - } - }; - - /** - * Returns the constructor that can be called with the given array of - * {@code parameterClasses}. - */ - public Constructor getConstructor(Class... parameterClasses) { - int length = parameterClasses.length; - NEXT_CONSTRUCTOR: - for (Constructor constructor : getConstructors()) { - Class[] declared = constructor.getParameterTypes(); - if (length == declared.length) { - - for (int i = 0; i < length; ++ i) { - if (!declared[i].isAssignableFrom(parameterClasses[i])) { - continue NEXT_CONSTRUCTOR; - } - } - - return (Constructor) constructor; - } - } - - return null; - } - - /** Creates a new instance. */ - public T newInstance() { - Constructor constructor = getConstructor(); - if (constructor == null) { - throw new IllegalStateException(String.format( - "Can't create an instance of [%s] without a nullary constructor!", - getObjectClass())); - } - - try { - return constructor.newInstance(); - - } catch (IllegalAccessException ex) { - throw new IllegalStateException(ex); - - } catch (InstantiationException ex) { - throw new IllegalStateException(String.format( - "Can't instantiate an instance of [%s]!", - getObjectClass()), ex); - - } catch (InvocationTargetException ex) { - Throwable cause = ex.getCause(); - if (cause == null) { - cause = ex; - } - throw cause instanceof RuntimeException ? - (RuntimeException) cause : - new RuntimeException(cause.getMessage(), cause); - } - } - - /** Returns an unmodifiable list of all the methods. */ - public List getAllMethods() { - return allMethods.get(); - } - - private final PullThroughValue> - allMethods = new PullThroughValue>() { - - @Override - protected List produce() { - - Class objectClass = getObjectClass(); - List methods = new ArrayList(); - for (Method method : objectClass.getDeclaredMethods()) { - method.setAccessible(true); - methods.add(method); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - methods.addAll(getInstance(superClass).getAllMethods()); - } - - return Collections.unmodifiableList(methods); - } - }; - - /** - * Returns an unmodifiable map of all the getters (public non-static - * methods that have no parameters and return a value) with the - * normalized names as keys. - */ - public Map getAllGetters() { - return allGetters.get(); - } - - private final PullThroughValue> - allGetters = new PullThroughValue>() { - - @Override - protected Map produce() { - - Map getters = new LinkedHashMap(); - for (Method method : getAllMethods()) { - if (method.getDeclaringClass() != Object.class) { - - int mod = method.getModifiers(); - if (Modifier.isPublic(mod) - && !Modifier.isStatic(mod) - && method.getReturnType() != void.class - && method.getReturnType() != Void.class - && method.getParameterTypes().length == 0) { - - String methodName = method.getName(); - Matcher nameMatcher = StringUtils.getMatcher(methodName, "^(get|(is|has))([^a-z])(.*)$"); - if (nameMatcher.matches()) { - - String name = ObjectUtils.isBlank(nameMatcher.group(2)) - ? nameMatcher.group(3).toLowerCase() + nameMatcher.group(4) - : methodName; - getters.put(name, method); - } - } - } - } - - return Collections.unmodifiableMap(getters); - } - }; - - /** - * Returns an unmodifiable map of all the setters (public non-static - * methods that take one parameter and doesn't return anything) with the - * normalized names as keys. - */ - public Map getAllSetters() { - return allSetters.get(); - } - - private final PullThroughValue> - allSetters = new PullThroughValue>() { - - @Override - protected Map produce() { - - Map setters = new LinkedHashMap(); - for (Method method : getAllMethods()) { - if (method.getDeclaringClass() != Object.class) { - - int mod = method.getModifiers(); - if (Modifier.isPublic(mod) - && !Modifier.isStatic(mod) - && (method.getReturnType() == void.class || method.getReturnType() == Void.class) - && method.getParameterTypes().length == 1) { - - String methodName = method.getName(); - Matcher nameMatcher = StringUtils.getMatcher(methodName, "^set([^a-z])(.*)$"); - if (nameMatcher.matches()) { - setters.put(nameMatcher.group(1).toLowerCase() + nameMatcher.group(2), method); - } - } - } - } - - return Collections.unmodifiableMap(setters); - } - }; - - /** {@link TypeDefinition} utility methods. */ - public static final class Static { - - private Static() { - } - - /** Invalidates all caches. */ - public static void invalidateAll() { - INSTANCES.invalidate(); - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/pair.info deleted file mode 100755 index e67e094..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#51931/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:51931 -comSha:8970195fe3598264b52d39e5d8472321e48cce95 -parentComSha:954c97460f670ff5747bfaa8e5698f48cf37ce52 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/TypeDefinition.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/TypeDefinition.java -StartLineNum:412 -EndLineNum:412 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/comMsg.txt deleted file mode 100755 index 978c561..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Use US locale everywhere when converting case. - -This fixes #400. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/diff.diff deleted file mode 100755 index c105b89..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/nodebox/node/NDBXWriter.java b/src/main/java/nodebox/node/NDBXWriter.java -index f40d1ca6..06420ccc 100644 ---- a/src/main/java/nodebox/node/NDBXWriter.java -+++ b/src/main/java/nodebox/node/NDBXWriter.java -@@ -194 +194 @@ public class NDBXWriter { -- el.setAttribute("outputRange", node.getOutputRange().toString().toLowerCase()); -+ el.setAttribute("outputRange", node.getOutputRange().toString().toLowerCase(Locale.US)); -@@ -326 +326 @@ public class NDBXWriter { -- el.setAttribute("widget", port.getWidget().toString().toLowerCase()); -+ el.setAttribute("widget", port.getWidget().toString().toLowerCase(Locale.US)); -@@ -328 +328 @@ public class NDBXWriter { -- el.setAttribute("range", port.getRange().toString().toLowerCase()); -+ el.setAttribute("range", port.getRange().toString().toLowerCase(Locale.US)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/new/NDBXWriter.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/new/NDBXWriter.java deleted file mode 100755 index 06420cc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/new/NDBXWriter.java +++ /dev/null @@ -1,366 +0,0 @@ -package nodebox.node; - -import com.google.common.base.Objects; -import nodebox.function.CoreFunctions; -import nodebox.function.FunctionLibrary; -import nodebox.function.FunctionRepository; -import nodebox.graphics.Point; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.File; -import java.io.StringWriter; -import java.io.Writer; -import java.util.*; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Writes the ndbx file format. - */ -public class NDBXWriter { - - public static void write(NodeLibrary library, File file) { - StreamResult streamResult = new StreamResult(file); - write(library, streamResult, file); - - } - - public static void write(NodeLibrary library, Writer writer) { - StreamResult streamResult = new StreamResult(writer); - write(library, streamResult, null); - } - - public static void write(NodeLibrary library, StreamResult streamResult, File file) { - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.newDocument(); - - // Build the header. - Element rootElement = doc.createElement("ndbx"); - rootElement.setAttribute("type", "file"); - rootElement.setAttribute("formatVersion", NodeLibrary.CURRENT_FORMAT_VERSION); - rootElement.setAttribute("uuid", library.getUuid().toString()); - doc.appendChild(rootElement); - - // Write out all the document properties. - Set propertyNames = library.getPropertyNames(); - ArrayList orderedNames = new ArrayList(propertyNames); - Collections.sort(orderedNames); - for (String propertyName : orderedNames) { - String propertyValue = library.getProperty(propertyName); - Element e = doc.createElement("property"); - e.setAttribute("name", propertyName); - e.setAttribute("value", propertyValue); - rootElement.appendChild(e); - } - - // Write the function repository. - writeFunctionRepository(doc, rootElement, library.getFunctionRepository(), file); - - writeDevices(doc, rootElement, library.getDevices()); - - // Write the root node. - writeNode(doc, rootElement, library.getRoot(), library.getNodeRepository()); - - // Convert the document to XML. - DOMSource domSource = new DOMSource(doc); - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer serializer = tf.newTransformer(); - serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); - serializer.setOutputProperty(OutputKeys.INDENT, "yes"); - serializer.transform(domSource, streamResult); - } catch (ParserConfigurationException e) { - throw new RuntimeException(e); - } catch (TransformerException e) { - throw new RuntimeException(e); - } - } - - public static String asString(NodeLibrary library) { - StringWriter writer = new StringWriter(); - write(library, writer); - return writer.toString(); - } - - /** - * Write out links to the function repositories used. - * - * @param doc the XML document - * @param parent the parent element - * @param functionRepository the function repository to write - * @param baseFile the file to which the paths of the function libraries are relative to. - */ - private static void writeFunctionRepository(Document doc, Element parent, FunctionRepository functionRepository, File baseFile) { - for (FunctionLibrary library : functionRepository.getLibraries()) { - // The core functions library is implicitly included. - if (library == CoreFunctions.LIBRARY) continue; - Element el = doc.createElement("link"); - el.setAttribute("rel", "functions"); - el.setAttribute("href", library.getLink(baseFile)); - parent.appendChild(el); - } - } - - /** - * Write out external devices. - * - * @param doc the XML document - * @param parent the parent element - * @param devices the external devices to write - */ - private static void writeDevices(Document doc, Element parent, List devices) { - for (Device device : devices) { - Element el = doc.createElement("device"); - el.setAttribute("name", device.getName()); - el.setAttribute("type", device.getType()); - for (Map.Entry property : device.getProperties().entrySet()) { - Element e = doc.createElement("property"); - e.setAttribute("name", property.getKey()); - e.setAttribute("value", property.getValue()); - el.appendChild(e); - } - parent.appendChild(el); - } - } - - /** - * Find the libraryname.nodename of the given node. - * Searches the list of default node repositories to find it. - * - * @param node The node to find. - * @param nodeRepository The list of node libraries to look for the node. - * @return the node id, in the format libraryname.nodename. - */ - private static String findNodeId(Node node, NodeRepository nodeRepository) { - NodeLibrary library = nodeRepository.nodeLibraryForNode(node); - if (library == null) { - return node.getName(); - } else { - return String.format("%s.%s", library.getName(), node.getName()); - } - } - - /** - * Write out the node. - * - * @param doc the XML document - * @param parent the parent element - * @param node the node to write - * @param nodeRepository the repository that contains the node prototype - */ - private static void writeNode(Document doc, Element parent, Node node, NodeRepository nodeRepository) { - Element el = doc.createElement("node"); - parent.appendChild(el); - - // Write prototype - if (shouldWriteAttribute(node, Node.Attribute.PROTOTYPE)) { - if (node.getPrototype() != Node.ROOT) - el.setAttribute("prototype", findNodeId(node.getPrototype(), nodeRepository)); - } - - // Write name - if (shouldWriteAttribute(node, Node.Attribute.NAME)) - el.setAttribute("name", node.getName()); - - // Write comment - if (shouldWriteAttribute(node, Node.Attribute.COMMENT)) - el.setAttribute("comment", node.getComment()); - - // Write category - if (shouldWriteAttribute(node, Node.Attribute.CATEGORY)) - el.setAttribute("category", node.getCategory()); - - // Write description - if (shouldWriteAttribute(node, Node.Attribute.DESCRIPTION)) - el.setAttribute("description", node.getDescription()); - - // Write output type - if (shouldWriteAttribute(node, Node.Attribute.OUTPUT_TYPE)) - el.setAttribute("outputType", node.getOutputType()); - - // Write output range - if (shouldWriteAttribute(node, Node.Attribute.OUTPUT_RANGE)) - el.setAttribute("outputRange", node.getOutputRange().toString().toLowerCase(Locale.US)); - - // Write image - if (shouldWriteAttribute(node, Node.Attribute.IMAGE)) - el.setAttribute("image", node.getImage()); - - // Write function - if (shouldWriteAttribute(node, Node.Attribute.FUNCTION)) - el.setAttribute("function", node.getFunction()); - - // Write handle function - if (shouldWriteAttribute(node, Node.Attribute.HANDLE)) - el.setAttribute("handle", node.getHandle()); - - // Write position - if (shouldWriteAttribute(node, Node.Attribute.POSITION)) { - Point position = node.getPosition(); - el.setAttribute("position", String.valueOf(position)); - } - - // Write rendered child - if (shouldWriteAttribute(node, Node.Attribute.RENDERED_CHILD_NAME)) - el.setAttribute("renderedChild", node.getRenderedChildName()); - - // Add the children - if (shouldWriteAttribute(node, Node.Attribute.CHILDREN)) { - // Sort the children. - ArrayList children = new ArrayList(); - children.addAll(node.getChildren()); - Collections.sort(children, new NodeNameComparator()); - // The order in which the nodes are written is important! - // Since a library can potentially store an instance and its prototype, make sure that the prototype gets - // stored sequentially before its instance. - // The reader expects prototypes to be defined before their instances. - while (!children.isEmpty()) { - Node child = children.get(0); - writeOrderedChild(doc, el, children, child, nodeRepository); - } - } - - // Add the input ports - if (shouldWriteAttribute(node, Node.Attribute.INPUTS)) { - for (Port port : node.getInputs()) { - writePort(doc, el, node, port, Port.Direction.INPUT); - } - } - - // Add all child connections - if (shouldWriteAttribute(node, Node.Attribute.CONNECTIONS)) { - for (Connection conn : node.getConnections()) { - writeConnection(doc, el, conn); - } - } - } - - /** - * Check if the given attribute should be written. - *

- * The attribute should be written if it's value is different from the prototype value. - * - * @param node The node. - * @param attribute The name of the attribute. - * @return true if the attribute should be written. - */ - private static boolean shouldWriteAttribute(Node node, Node.Attribute attribute) { - checkArgument(node != Node.ROOT, "You cannot write out the ROOT node."); - Object prototypeValue = node.getPrototype().getAttributeValue(attribute); - Object nodeValue = node.getAttributeValue(attribute); - if (attribute != Node.Attribute.PROTOTYPE) { - checkNotNull(prototypeValue, "Attribute %s of node %s is empty.", attribute, node.getPrototype()); - checkNotNull(nodeValue, "Attribute %s of node %s is empty.", attribute, node); - return !prototypeValue.equals(nodeValue); - } else { - return prototypeValue != nodeValue; - } - } - - /** - * Write out the child. If the prototype of the child is also in this library, write that out first, recursively. - * - * @param doc the XML document - * @param parent the parent element - * @param children a list of children that were written already. - * When a child is written, we remove it from the list. - * @param child the child to write - * @param nodeRepository the node repository that contains the node prototype - */ - private static void writeOrderedChild(Document doc, Element parent, List children, Node child, NodeRepository nodeRepository) { - Node prototype = child.getPrototype(); - if (children.contains(prototype)) - writeOrderedChild(doc, parent, children, prototype, nodeRepository); - writeNode(doc, parent, child, nodeRepository); - children.remove(child); - } - - /** - * Check if the given attribute should be written. - *

- * The attribute should be written if it's value is different from the prototype value. - * - * @param node The node. - * @param port The port. - * @param attribute The name of the attribute. - * @return true if the attribute should be written. - */ - private static boolean shouldWriteAttribute(Node node, Port port, Port.Attribute attribute) { - checkArgument(node != Node.ROOT, "You cannot write out the ROOT node."); - Port prototypePort = node.getPrototype().getInput(port.getName()); - // If there is no prototype port, we should always write the attribute. - if (prototypePort == null) return true; - Object prototypeValue = prototypePort.getAttributeValue(attribute); - Object value = port.getAttributeValue(attribute); - // Objects.equal does the correct null-comparison for min / max values. - return !Objects.equal(prototypeValue, value); - } - - private static void writePort(Document doc, Element parent, Node node, Port port, Port.Direction direction) { - // We only write out the ports that have changed with regards to the prototype. - Node protoNode = node.getPrototype(); - Port protoPort = null; - if (protoNode != null) - protoPort = protoNode.getInput(port.getName()); - // If the port and its prototype are equal, don't write anything. - if (port.equals(protoPort)) return; - Element el = doc.createElement("port"); - el.setAttribute("name", port.getName()); - el.setAttribute("type", port.getType()); - if (shouldWriteAttribute(node, port, Port.Attribute.LABEL)) - el.setAttribute("label", port.getLabel()); - if (shouldWriteAttribute(node, port, Port.Attribute.CHILD_REFERENCE) && port.getChildReference() != null) - el.setAttribute("childReference", port.getChildReference()); - if (shouldWriteAttribute(node, port, Port.Attribute.WIDGET)) - el.setAttribute("widget", port.getWidget().toString().toLowerCase(Locale.US)); - if (shouldWriteAttribute(node, port, Port.Attribute.RANGE)) - el.setAttribute("range", port.getRange().toString().toLowerCase(Locale.US)); - if (port.isStandardType()) - el.setAttribute("value", port.stringValue()); - if (shouldWriteAttribute(node, port, Port.Attribute.DESCRIPTION)) - el.setAttribute("description", port.getDescription()); - if (shouldWriteAttribute(node, port, Port.Attribute.MINIMUM_VALUE)) - if (port.getMinimumValue() != null) - el.setAttribute("min", String.format(Locale.US, "%s", port.getMinimumValue())); - if (shouldWriteAttribute(node, port, Port.Attribute.MAXIMUM_VALUE)) - if (port.getMaximumValue() != null) - el.setAttribute("max", String.format(Locale.US, "%s", port.getMaximumValue())); - if (shouldWriteAttribute(node, port, Port.Attribute.MENU_ITEMS)) - writeMenuItems(doc, el, port.getMenuItems()); - parent.appendChild(el); - } - - private static void writeMenuItems(Document doc, Element parent, List menuItems) { - for (MenuItem item : menuItems) { - Element el = doc.createElement("menu"); - el.setAttribute("key", item.getKey()); - el.setAttribute("label", item.getLabel()); - parent.appendChild(el); - } - } - - private static void writeConnection(Document doc, Element parent, Connection conn) { - Element connElement = doc.createElement("conn"); - connElement.setAttribute("output", String.format("%s", conn.getOutputNode())); - connElement.setAttribute("input", String.format("%s.%s", conn.getInputNode(), conn.getInputPort())); - parent.appendChild(connElement); - } - - private static class NodeNameComparator implements Comparator { - public int compare(Node node1, Node node2) { - return node1.getName().compareTo(node2.getName()); - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/old/NDBXWriter.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/old/NDBXWriter.java deleted file mode 100755 index f40d1ca..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/old/NDBXWriter.java +++ /dev/null @@ -1,366 +0,0 @@ -package nodebox.node; - -import com.google.common.base.Objects; -import nodebox.function.CoreFunctions; -import nodebox.function.FunctionLibrary; -import nodebox.function.FunctionRepository; -import nodebox.graphics.Point; -import org.w3c.dom.Document; -import org.w3c.dom.Element; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.transform.OutputKeys; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.dom.DOMSource; -import javax.xml.transform.stream.StreamResult; -import java.io.File; -import java.io.StringWriter; -import java.io.Writer; -import java.util.*; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Preconditions.checkNotNull; - -/** - * Writes the ndbx file format. - */ -public class NDBXWriter { - - public static void write(NodeLibrary library, File file) { - StreamResult streamResult = new StreamResult(file); - write(library, streamResult, file); - - } - - public static void write(NodeLibrary library, Writer writer) { - StreamResult streamResult = new StreamResult(writer); - write(library, streamResult, null); - } - - public static void write(NodeLibrary library, StreamResult streamResult, File file) { - try { - DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = builder.newDocument(); - - // Build the header. - Element rootElement = doc.createElement("ndbx"); - rootElement.setAttribute("type", "file"); - rootElement.setAttribute("formatVersion", NodeLibrary.CURRENT_FORMAT_VERSION); - rootElement.setAttribute("uuid", library.getUuid().toString()); - doc.appendChild(rootElement); - - // Write out all the document properties. - Set propertyNames = library.getPropertyNames(); - ArrayList orderedNames = new ArrayList(propertyNames); - Collections.sort(orderedNames); - for (String propertyName : orderedNames) { - String propertyValue = library.getProperty(propertyName); - Element e = doc.createElement("property"); - e.setAttribute("name", propertyName); - e.setAttribute("value", propertyValue); - rootElement.appendChild(e); - } - - // Write the function repository. - writeFunctionRepository(doc, rootElement, library.getFunctionRepository(), file); - - writeDevices(doc, rootElement, library.getDevices()); - - // Write the root node. - writeNode(doc, rootElement, library.getRoot(), library.getNodeRepository()); - - // Convert the document to XML. - DOMSource domSource = new DOMSource(doc); - TransformerFactory tf = TransformerFactory.newInstance(); - Transformer serializer = tf.newTransformer(); - serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); - serializer.setOutputProperty(OutputKeys.INDENT, "yes"); - serializer.transform(domSource, streamResult); - } catch (ParserConfigurationException e) { - throw new RuntimeException(e); - } catch (TransformerException e) { - throw new RuntimeException(e); - } - } - - public static String asString(NodeLibrary library) { - StringWriter writer = new StringWriter(); - write(library, writer); - return writer.toString(); - } - - /** - * Write out links to the function repositories used. - * - * @param doc the XML document - * @param parent the parent element - * @param functionRepository the function repository to write - * @param baseFile the file to which the paths of the function libraries are relative to. - */ - private static void writeFunctionRepository(Document doc, Element parent, FunctionRepository functionRepository, File baseFile) { - for (FunctionLibrary library : functionRepository.getLibraries()) { - // The core functions library is implicitly included. - if (library == CoreFunctions.LIBRARY) continue; - Element el = doc.createElement("link"); - el.setAttribute("rel", "functions"); - el.setAttribute("href", library.getLink(baseFile)); - parent.appendChild(el); - } - } - - /** - * Write out external devices. - * - * @param doc the XML document - * @param parent the parent element - * @param devices the external devices to write - */ - private static void writeDevices(Document doc, Element parent, List devices) { - for (Device device : devices) { - Element el = doc.createElement("device"); - el.setAttribute("name", device.getName()); - el.setAttribute("type", device.getType()); - for (Map.Entry property : device.getProperties().entrySet()) { - Element e = doc.createElement("property"); - e.setAttribute("name", property.getKey()); - e.setAttribute("value", property.getValue()); - el.appendChild(e); - } - parent.appendChild(el); - } - } - - /** - * Find the libraryname.nodename of the given node. - * Searches the list of default node repositories to find it. - * - * @param node The node to find. - * @param nodeRepository The list of node libraries to look for the node. - * @return the node id, in the format libraryname.nodename. - */ - private static String findNodeId(Node node, NodeRepository nodeRepository) { - NodeLibrary library = nodeRepository.nodeLibraryForNode(node); - if (library == null) { - return node.getName(); - } else { - return String.format("%s.%s", library.getName(), node.getName()); - } - } - - /** - * Write out the node. - * - * @param doc the XML document - * @param parent the parent element - * @param node the node to write - * @param nodeRepository the repository that contains the node prototype - */ - private static void writeNode(Document doc, Element parent, Node node, NodeRepository nodeRepository) { - Element el = doc.createElement("node"); - parent.appendChild(el); - - // Write prototype - if (shouldWriteAttribute(node, Node.Attribute.PROTOTYPE)) { - if (node.getPrototype() != Node.ROOT) - el.setAttribute("prototype", findNodeId(node.getPrototype(), nodeRepository)); - } - - // Write name - if (shouldWriteAttribute(node, Node.Attribute.NAME)) - el.setAttribute("name", node.getName()); - - // Write comment - if (shouldWriteAttribute(node, Node.Attribute.COMMENT)) - el.setAttribute("comment", node.getComment()); - - // Write category - if (shouldWriteAttribute(node, Node.Attribute.CATEGORY)) - el.setAttribute("category", node.getCategory()); - - // Write description - if (shouldWriteAttribute(node, Node.Attribute.DESCRIPTION)) - el.setAttribute("description", node.getDescription()); - - // Write output type - if (shouldWriteAttribute(node, Node.Attribute.OUTPUT_TYPE)) - el.setAttribute("outputType", node.getOutputType()); - - // Write output range - if (shouldWriteAttribute(node, Node.Attribute.OUTPUT_RANGE)) - el.setAttribute("outputRange", node.getOutputRange().toString().toLowerCase()); - - // Write image - if (shouldWriteAttribute(node, Node.Attribute.IMAGE)) - el.setAttribute("image", node.getImage()); - - // Write function - if (shouldWriteAttribute(node, Node.Attribute.FUNCTION)) - el.setAttribute("function", node.getFunction()); - - // Write handle function - if (shouldWriteAttribute(node, Node.Attribute.HANDLE)) - el.setAttribute("handle", node.getHandle()); - - // Write position - if (shouldWriteAttribute(node, Node.Attribute.POSITION)) { - Point position = node.getPosition(); - el.setAttribute("position", String.valueOf(position)); - } - - // Write rendered child - if (shouldWriteAttribute(node, Node.Attribute.RENDERED_CHILD_NAME)) - el.setAttribute("renderedChild", node.getRenderedChildName()); - - // Add the children - if (shouldWriteAttribute(node, Node.Attribute.CHILDREN)) { - // Sort the children. - ArrayList children = new ArrayList(); - children.addAll(node.getChildren()); - Collections.sort(children, new NodeNameComparator()); - // The order in which the nodes are written is important! - // Since a library can potentially store an instance and its prototype, make sure that the prototype gets - // stored sequentially before its instance. - // The reader expects prototypes to be defined before their instances. - while (!children.isEmpty()) { - Node child = children.get(0); - writeOrderedChild(doc, el, children, child, nodeRepository); - } - } - - // Add the input ports - if (shouldWriteAttribute(node, Node.Attribute.INPUTS)) { - for (Port port : node.getInputs()) { - writePort(doc, el, node, port, Port.Direction.INPUT); - } - } - - // Add all child connections - if (shouldWriteAttribute(node, Node.Attribute.CONNECTIONS)) { - for (Connection conn : node.getConnections()) { - writeConnection(doc, el, conn); - } - } - } - - /** - * Check if the given attribute should be written. - *

- * The attribute should be written if it's value is different from the prototype value. - * - * @param node The node. - * @param attribute The name of the attribute. - * @return true if the attribute should be written. - */ - private static boolean shouldWriteAttribute(Node node, Node.Attribute attribute) { - checkArgument(node != Node.ROOT, "You cannot write out the ROOT node."); - Object prototypeValue = node.getPrototype().getAttributeValue(attribute); - Object nodeValue = node.getAttributeValue(attribute); - if (attribute != Node.Attribute.PROTOTYPE) { - checkNotNull(prototypeValue, "Attribute %s of node %s is empty.", attribute, node.getPrototype()); - checkNotNull(nodeValue, "Attribute %s of node %s is empty.", attribute, node); - return !prototypeValue.equals(nodeValue); - } else { - return prototypeValue != nodeValue; - } - } - - /** - * Write out the child. If the prototype of the child is also in this library, write that out first, recursively. - * - * @param doc the XML document - * @param parent the parent element - * @param children a list of children that were written already. - * When a child is written, we remove it from the list. - * @param child the child to write - * @param nodeRepository the node repository that contains the node prototype - */ - private static void writeOrderedChild(Document doc, Element parent, List children, Node child, NodeRepository nodeRepository) { - Node prototype = child.getPrototype(); - if (children.contains(prototype)) - writeOrderedChild(doc, parent, children, prototype, nodeRepository); - writeNode(doc, parent, child, nodeRepository); - children.remove(child); - } - - /** - * Check if the given attribute should be written. - *

- * The attribute should be written if it's value is different from the prototype value. - * - * @param node The node. - * @param port The port. - * @param attribute The name of the attribute. - * @return true if the attribute should be written. - */ - private static boolean shouldWriteAttribute(Node node, Port port, Port.Attribute attribute) { - checkArgument(node != Node.ROOT, "You cannot write out the ROOT node."); - Port prototypePort = node.getPrototype().getInput(port.getName()); - // If there is no prototype port, we should always write the attribute. - if (prototypePort == null) return true; - Object prototypeValue = prototypePort.getAttributeValue(attribute); - Object value = port.getAttributeValue(attribute); - // Objects.equal does the correct null-comparison for min / max values. - return !Objects.equal(prototypeValue, value); - } - - private static void writePort(Document doc, Element parent, Node node, Port port, Port.Direction direction) { - // We only write out the ports that have changed with regards to the prototype. - Node protoNode = node.getPrototype(); - Port protoPort = null; - if (protoNode != null) - protoPort = protoNode.getInput(port.getName()); - // If the port and its prototype are equal, don't write anything. - if (port.equals(protoPort)) return; - Element el = doc.createElement("port"); - el.setAttribute("name", port.getName()); - el.setAttribute("type", port.getType()); - if (shouldWriteAttribute(node, port, Port.Attribute.LABEL)) - el.setAttribute("label", port.getLabel()); - if (shouldWriteAttribute(node, port, Port.Attribute.CHILD_REFERENCE) && port.getChildReference() != null) - el.setAttribute("childReference", port.getChildReference()); - if (shouldWriteAttribute(node, port, Port.Attribute.WIDGET)) - el.setAttribute("widget", port.getWidget().toString().toLowerCase()); - if (shouldWriteAttribute(node, port, Port.Attribute.RANGE)) - el.setAttribute("range", port.getRange().toString().toLowerCase()); - if (port.isStandardType()) - el.setAttribute("value", port.stringValue()); - if (shouldWriteAttribute(node, port, Port.Attribute.DESCRIPTION)) - el.setAttribute("description", port.getDescription()); - if (shouldWriteAttribute(node, port, Port.Attribute.MINIMUM_VALUE)) - if (port.getMinimumValue() != null) - el.setAttribute("min", String.format(Locale.US, "%s", port.getMinimumValue())); - if (shouldWriteAttribute(node, port, Port.Attribute.MAXIMUM_VALUE)) - if (port.getMaximumValue() != null) - el.setAttribute("max", String.format(Locale.US, "%s", port.getMaximumValue())); - if (shouldWriteAttribute(node, port, Port.Attribute.MENU_ITEMS)) - writeMenuItems(doc, el, port.getMenuItems()); - parent.appendChild(el); - } - - private static void writeMenuItems(Document doc, Element parent, List menuItems) { - for (MenuItem item : menuItems) { - Element el = doc.createElement("menu"); - el.setAttribute("key", item.getKey()); - el.setAttribute("label", item.getLabel()); - parent.appendChild(el); - } - } - - private static void writeConnection(Document doc, Element parent, Connection conn) { - Element connElement = doc.createElement("conn"); - connElement.setAttribute("output", String.format("%s", conn.getOutputNode())); - connElement.setAttribute("input", String.format("%s.%s", conn.getInputNode(), conn.getInputPort())); - parent.appendChild(connElement); - } - - private static class NodeNameComparator implements Comparator { - public int compare(Node node1, Node node2) { - return node1.getName().compareTo(node2.getName()); - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/pair.info deleted file mode 100755 index 3e9676d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5201/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:5201 -comSha:2fc22b4e8894fc318ee21a5355df8815786190d3 -parentComSha:274890519fd60ac0097fe47e00ec510b285260d5 -BuggyFilePath:src/main/java/nodebox/node/NDBXWriter.java -FixedFilePath:src/main/java/nodebox/node/NDBXWriter.java -StartLineNum:326 -EndLineNum:326 -repoName:nodebox#nodebox \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/comMsg.txt deleted file mode 100755 index 3aa5042..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'release/2.1' \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/diff.diff deleted file mode 100755 index 5fd9081..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java b/util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -index 0435d1ae..e419ad80 100644 ---- a/util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -+++ b/util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -@@ -6,0 +7 @@ import java.util.List; -+import java.util.Locale; -@@ -83 +84 @@ public class LogCaptureFilter extends AbstractFilter { -- contentType = contentType.toLowerCase(); -+ contentType = contentType.toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/new/LogCaptureFilter.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/new/LogCaptureFilter.java deleted file mode 100755 index e419ad8..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/new/LogCaptureFilter.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Enumeration; -import java.util.List; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Captures log messages and writes them to the response based on request - * parameters. - */ -public class LogCaptureFilter extends AbstractFilter { - - /** - * Setting key for prefix to parameters that control which logs to - * capture. - */ - public static final String PARAMETER_PREFIX_SETTING = "dari/logCaptureFilterParameterPrefix"; - - /** Default prefix to parameters that control which logs to capture. */ - public static final String DEFAULT_PARAMETER_PREFIX = "_log."; - - // --- AbstractFilter support --- - - @Override - @SuppressWarnings("unchecked") - protected void doRequest( - HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws IOException, ServletException { - - if (!Settings.isProduction()) { - chain.doFilter(request, response); - return; - } - - String parameterPrefix = Settings.getOrDefault(String.class, PARAMETER_PREFIX_SETTING, DEFAULT_PARAMETER_PREFIX); - LogCapture capture = null; - - for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) { - String name = e.nextElement(); - - if (name.startsWith(parameterPrefix)) { - if (capture == null) { - capture = new LogCapture(); - } - capture.putLogger( - Logger.getLogger(name.substring(parameterPrefix.length())), - Level.parse(request.getParameter(name))); - } - } - - if (capture == null) { - chain.doFilter(request, response); - return; - } - - try { - capture.start(); - - chain.doFilter(request, response); - - } finally { - List logs = capture.stop(); - String contentType = response.getContentType(); - PrintWriter writer = null; - - try { - writer = response.getWriter(); - } catch (IllegalStateException ex) { - writer = new PrintWriter(response.getOutputStream()); - } - - if (contentType != null) { - contentType = contentType.toLowerCase(Locale.ENGLISH); - - if (contentType.contains("json") || - contentType.contains("javascript")) { - writer.println("/*"); - for (String log : logs) { - writer.println(log); - } - writer.println("*/"); - return; - - } else if (contentType.contains("html")) { - writer.println("

");
-                    for (String log : logs) {
-                        writer.println(StringUtils.escapeHtml(log));
-                    }
-                    writer.println("
"); - return; - } - } - - for (String log : logs) { - writer.println(log); - } - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/old/LogCaptureFilter.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/old/LogCaptureFilter.java deleted file mode 100755 index 0435d1a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/old/LogCaptureFilter.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Enumeration; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Captures log messages and writes them to the response based on request - * parameters. - */ -public class LogCaptureFilter extends AbstractFilter { - - /** - * Setting key for prefix to parameters that control which logs to - * capture. - */ - public static final String PARAMETER_PREFIX_SETTING = "dari/logCaptureFilterParameterPrefix"; - - /** Default prefix to parameters that control which logs to capture. */ - public static final String DEFAULT_PARAMETER_PREFIX = "_log."; - - // --- AbstractFilter support --- - - @Override - @SuppressWarnings("unchecked") - protected void doRequest( - HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws IOException, ServletException { - - if (!Settings.isProduction()) { - chain.doFilter(request, response); - return; - } - - String parameterPrefix = Settings.getOrDefault(String.class, PARAMETER_PREFIX_SETTING, DEFAULT_PARAMETER_PREFIX); - LogCapture capture = null; - - for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) { - String name = e.nextElement(); - - if (name.startsWith(parameterPrefix)) { - if (capture == null) { - capture = new LogCapture(); - } - capture.putLogger( - Logger.getLogger(name.substring(parameterPrefix.length())), - Level.parse(request.getParameter(name))); - } - } - - if (capture == null) { - chain.doFilter(request, response); - return; - } - - try { - capture.start(); - - chain.doFilter(request, response); - - } finally { - List logs = capture.stop(); - String contentType = response.getContentType(); - PrintWriter writer = null; - - try { - writer = response.getWriter(); - } catch (IllegalStateException ex) { - writer = new PrintWriter(response.getOutputStream()); - } - - if (contentType != null) { - contentType = contentType.toLowerCase(); - - if (contentType.contains("json") || - contentType.contains("javascript")) { - writer.println("/*"); - for (String log : logs) { - writer.println(log); - } - writer.println("*/"); - return; - - } else if (contentType.contains("html")) { - writer.println("
");
-                    for (String log : logs) {
-                        writer.println(StringUtils.escapeHtml(log));
-                    }
-                    writer.println("
"); - return; - } - } - - for (String log : logs) { - writer.println(log); - } - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/pair.info deleted file mode 100755 index 1469ada..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52152/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:52152 -comSha:2d3b35e6aac1466d93e5f7829098a195efc59449 -parentComSha:ab0e3ab960cdf03bea6e38a1a6738ff68450b6a6 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -StartLineNum:83 -EndLineNum:83 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/comMsg.txt deleted file mode 100755 index 156a5db..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'master' of github.com:perfectsense/dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/diff.diff deleted file mode 100755 index 400ff2f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/diff.diff +++ /dev/null @@ -1,19 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/StringUtils.java b/util/src/main/java/com/psddev/dari/util/StringUtils.java -index 884d1982..18c3b5ec 100644 ---- a/util/src/main/java/com/psddev/dari/util/StringUtils.java -+++ b/util/src/main/java/com/psddev/dari/util/StringUtils.java -@@ -155 +155 @@ public final class StringUtils { -- words.add(string.substring(m, i).toLowerCase()); -+ words.add(string.substring(m, i).toLowerCase(Locale.ENGLISH)); -@@ -160 +160 @@ public final class StringUtils { -- words.add(string.substring(m, i).toLowerCase()); -+ words.add(string.substring(m, i).toLowerCase(Locale.ENGLISH)); -@@ -165 +165 @@ public final class StringUtils { -- words.add(string.substring(m).toLowerCase()); -+ words.add(string.substring(m).toLowerCase(Locale.ENGLISH)); -@@ -235 +235 @@ public final class StringUtils { -- if (words.size() > 0 && "is".equals(words.get(0))) { -+ if (!words.isEmpty() && "is".equals(words.get(0))) { -@@ -283 +283 @@ public final class StringUtils { -- ).toLowerCase(); -+ ).toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/new/StringUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/new/StringUtils.java deleted file mode 100755 index 18c3b5e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/new/StringUtils.java +++ /dev/null @@ -1,1214 +0,0 @@ -package com.psddev.dari.util; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.lang.StringEscapeUtils; - -/** String utility methods. */ -public final class StringUtils { - - public static final Charset US_ASCII = Charset.forName("US-ASCII"); - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - public static final Charset UTF_8 = Charset.forName("UTF-8"); - public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); - public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); - public static final Charset UTF_16 = Charset.forName("UTF-16"); - - private static final Set - ABBREVIATIONS = new HashSet(Arrays.asList( - "cms", "css", "id", "js", "seo", "uri", "url")); - - private static final char[] HEX_CHARACTERS = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f' }; - - /** - * Converts given string into a value of given type, throwing an exception - * if conversion was unsuccessful. - * - * If the return type is an array, an array is returned. - * fromString(int[].class, "1", "2") => int[] {1,2} - * - * If no values are provided and the return type is an array, an empty array is returned. - * fromString(int[].class) => int[] {} - * - * If no values are provided and the return type is not an array, an exception - * appropriate to the conversion type is thrown. - * fromString(int.class) => NumberFormatException - * - * If the {@code strings} contains more than one value and the {@code returnType} is not - * an array, all but the first value are ignored. - * - * If the method cannot convert to the class specified, an IllegalArgumentException is thrown. - * - * @param - * @param returnType The class for the String input(s) to be converted to - * @param strings the input(s) to be converted - * @return the converted value - */ - public static T fromString(Class returnType, String... strings) { - - // heavy voodoo follows... - // need to return an array - Class componentType = returnType.getComponentType(); - if (componentType != null) { - if (strings == null) { - return null; - } else { - int length = strings.length; - Object typed = Array.newInstance(componentType, length); - for (int i = 0; i < length; i++) { - Array.set(typed, i, fromString(componentType, strings[i])); - } - return (T) typed; - } - - // single value - } else { - String string = strings == null || strings.length == 0 ? null : strings[0]; - - // string to string - if (String.class == returnType) { - return (T) string; - - // primitives - // pass null through if returnType allows it - } else if (string == null && !returnType.isPrimitive()) { - return null; - - // any way to avoid boxing/unboxing on primitives? - } else if (boolean.class == returnType || Boolean.class.isAssignableFrom(returnType)) { - return (T) Boolean.valueOf(string); - } else if (byte.class == returnType || Byte.class.isAssignableFrom(returnType)) { - return (T) Byte.valueOf(string); - } else if (short.class == returnType || Short.class.isAssignableFrom(returnType)) { - return (T) Short.valueOf(string); - } else if (int.class == returnType || Integer.class.isAssignableFrom(returnType)) { - return (T) Integer.valueOf(string); - } else if (long.class == returnType || Long.class.isAssignableFrom(returnType)) { - return (T) Long.valueOf(string); - } else if (float.class == returnType || Float.class.isAssignableFrom(returnType)) { - return (T) Float.valueOf(string); - } else if (double.class == returnType || Double.class.isAssignableFrom(returnType)) { - return (T) Double.valueOf(string); - } else if (char.class == returnType || Character.class.isAssignableFrom(returnType)) { - if (string.length() == 1) { - return (T) Character.valueOf(string.charAt(0)); - } - - // others - } else if (Date.class.isAssignableFrom(returnType)) { - return (T) DateUtils.fromString(string); - } - throw new IllegalArgumentException(String.format( - "Cannot convert [%s] string to [%s] type!", - string, - returnType.getName() - )); - } - } - - - /** - * Helper method to split a string by case change or common delimiters. - * - * Multiple delimeters in a row are reduced to a single word boundry. - * - * Leading delimeters (a space at the beginning of the string) will cause an - * empty first word to be detected (bug?). Trailing delemeters do not cause empty - * words to be detected. - * - * Returned words are all lowercased. - * - * @param string - * @return the list of words detected in the string - */ - protected static List splitString(String string) { - List words = new ArrayList(); - int m = 0, l = string.length(); - for (int i = 0; i < l; i++) { - char c = string.charAt(i); - if (" -_.$".indexOf(c) > -1) { - words.add(string.substring(m, i).toLowerCase(Locale.ENGLISH)); - while (++i < l && " -_.$".indexOf(string.charAt(i)) > -1) { - } - m = i; - } else if (Character.isUpperCase(c) && i > 0 && Character.isLowerCase(string.charAt(i - 1))) { - words.add(string.substring(m, i).toLowerCase(Locale.ENGLISH)); - m = i; - } - } - if (m + 1 < l) { - words.add(string.substring(m).toLowerCase(Locale.ENGLISH)); - } - return words; - } - - /** - * Tries to detect words within a given string and join them with the given delimiter. - */ - public static String toDelimited(String string, String delimiter) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(word).append(delimiter); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - delimiter.length()); - } - return nb.toString(); - } - - /** - * Converts the given string into a-hyphenated-string. - */ - public static String toHyphenated(String string) { - return toDelimited(string, "-"); - } - - /** - * Converts the given string into a_underscored_string. - */ - public static String toUnderscored(String string) { - return toDelimited(string, "_"); - } - - /** - * Converts the given string into APascalCaseString. - */ - public static String toPascalCase(String string) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); - } - return nb.toString(); - } - - /** - * Converts the given string into aCamelCaseString. - */ - public static String toCamelCase(String string) { - string = toPascalCase(string); - return Character.toLowerCase(string.charAt(0)) + string.substring(1); - } - - /** - * Converts the string to one suitable for use as "a label"? - * - * Splits {@code string} into words, joining it back together "In Title Case" - * with known {@code ABBREVIATIONS} replaced in all caps. If the first word of - * {@code string} is "is", that word is removed and a question mark is - * added to the end of the resulting string. - * - * @param string - */ - public static String toLabel(String string) { - - if (string == null) { - return null; - } - - boolean isQuestion = false; - List words = splitString(string); - if (!words.isEmpty() && "is".equals(words.get(0))) { - isQuestion = true; - words.remove(0); - } - - StringBuilder nb = new StringBuilder(); - for (String word : words) { - if (word.length() == 0) { - continue; - } - - if (ABBREVIATIONS.contains(word)) { - nb.append(word.toUpperCase(Locale.ENGLISH)); - } else { - nb.append(Character.toUpperCase(word.charAt(0))); - nb.append(word.substring(1)); - } - nb.append(' '); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - 1); - } - - if (isQuestion) { - nb.append('?'); - } - - return nb.toString(); - } - - /** - * Normalizes a string, removing or replacing non-alphanumeric characters and lowercasing - * - * - Removes all accented characters. - * - Removes single quotes - * - Replaces non-alphanumeric characters remaining with a dash - * - Removes dashes - * - * Lowercases the result - */ - public static String toNormalized(CharSequence string) { - return string == null ? null : replaceAll( - Normalizer.normalize(string, Normalizer.Form.NFD), - "[^\\p{ASCII}]", "", - "'", "", - "\\.", "", - "[^a-zA-Z0-9]+", "-", - "^-+|-+$", "" - ).toLowerCase(Locale.ENGLISH); - } - - /** Splits the given string by commas, and returns each part unescaped. - * Calling {@link #toCsv(String...)} on an array of Strings and then - * passing the result to this method will always return the same array - * as specified by the Arrays.equals() method. */ - public static String[] fromCsv(String string) { - if(string == null) { - return null; - } else { - // replaces a call to string.split(",") - char[] charArr = string.toCharArray(); - int commaCount = 0; - for (char c : charArr) { - if (c == ',') { - commaCount++; - } - } - String[] escaped = new String[commaCount+1]; - int index = 0; - int offset = 0; - int count = 0; - for (char c : charArr) { - if (c == ',') { - escaped[index++] = new String(charArr, offset, count); - offset += count+1; - count = 0; - } else { - count++; - } - } - if (index == commaCount) { - escaped[index] = new String(charArr, offset, count); - } - // end string.split(",") replacement code - - int length = escaped.length; - List unescaped = new ArrayList(); - for(int i = 0; i < length; i ++) { - String value = escaped[i]; - if(value.startsWith("\"")) { // there are commas and/or double quotes escaped within - StringBuilder builder = new StringBuilder(); - int quoteCount = 0; - do { - builder.append(value); - for(char c : value.toCharArray()) { - if(c == '"') { - quoteCount++; - } - } - if(quoteCount % 2 == 1) { - value = escaped[++i]; - builder.append(','); - } - } while(quoteCount % 2 == 1); - value = builder.toString(); - } - unescaped.add(StringUtils.unescapeCsv(value)); - } - return unescaped.toArray(new String[unescaped.size()]); - } - } - - /** Converts an array of Strings to a single String in comma separated - * values format, escaping each string as necessary. */ - public static String toCsv(String... strings) { - if (strings == null) { - return null; - } - StringBuilder builder = new StringBuilder(); - for (String string : strings) { - builder.append(escapeCsv(string)).append(','); - } - if (builder.length() > 0) { - builder.setLength(builder.length()-1); - } - return builder.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string, int maxWordLength) { - if (string == null) { - return null; - } - Matcher matcher = getMatcher(string, String.format("(\\S{%d,})", maxWordLength)); - StringBuilder output = new StringBuilder(); - int marker = 0; - while (matcher.find()) { - String longWord = matcher.group(1); - - // similar to Matcher.appendReplacement - // re-implemented so that $ and \ does not have to be escaped - if (matcher.start() > marker) { - output.append(string.substring(marker, matcher.start())); - } - int i = 0; - for (; i < longWord.length() - maxWordLength; i += maxWordLength) { - output.append(escapeHtml(longWord.substring(i, i + maxWordLength))); - output.append(""); - } - output.append(escapeHtml(longWord.substring(i))); - marker = matcher.end(); - } - - // similar to Matcher.appendTail - output.append(string.substring(marker)); - return output.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string) { - return escapeHtmlAndBreak(string, 20); - } - - /** Converts the given {@code bytes} into a hex string. */ - public static String hex(byte[] bytes) { - if (bytes == null) { - return null; - } - - int bytesLength = bytes.length; - byte currentByte; - char[] hex = new char[bytesLength * 2]; - - for (int byteIndex = 0, hexIndex = 0; - byteIndex < bytesLength; - ++ byteIndex, hexIndex += 2) { - - currentByte = bytes[byteIndex]; - hex[hexIndex] = HEX_CHARACTERS[(currentByte & 0xf0) >> 4]; - hex[hexIndex + 1] = HEX_CHARACTERS[(currentByte & 0x0f)]; - } - - return new String(hex); - } - - /** Hashes the given {@code string} using the given {@code algorithm}. */ - public static byte[] hash(String algorithm, String string) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance(algorithm); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid hash algorithm!", algorithm), ex); - } - - byte[] bytes; - try { - bytes = string.getBytes("UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - - return digest.digest(bytes); - } - - /** Hashes the given {@code string} using the MD5 algorithm. */ - public static byte[] md5(String string) { - return hash("MD5", string); - } - - /** Hashes the given {@code string} using the SHA-1 algorithm. */ - public static byte[] sha1(String string) { - return hash("SHA-1", string); - } - - /** Hashes the given {@code string} using the SHA-512 algorithm. */ - public static byte[] sha512(String string) { - return hash("SHA-512", string); - } - - /** - * Hashes the given {@code string} using the given HMAC {@code algorithm} - * and {@code key}. - */ - public static byte[] hmac(String algorithm, String key, String string) { - try { - Mac mac = Mac.getInstance(algorithm); - mac.init(new SecretKeySpec(key.getBytes(StringUtils.UTF_8), algorithm)); - return mac.doFinal(string.getBytes(StringUtils.UTF_8)); - - } catch (NoSuchAlgorithmException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid HMAC algorithm!", algorithm), error); - - } catch (InvalidKeyException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid key!", key), error); - } - } - - /** - * Hashes the given {@code string} using the HMAC SHA-1 algorithm - * and the given {@code key}. - */ - public static byte[] hmacSha1(String key, String string) { - return hmac("HmacSHA1", key, string); - } - - // --- URL/URI --- - - /** - * Encodes the given UTF-8 {@code string} so that it's safe for use - * within an URI. - */ - public static String encodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLEncoder.encode(string, "UTF-8").replace("+", "%20"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** Decodes the given URI-encoded, UTF-8 {@code string}. */ - public static String decodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLDecoder.decode(string, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** - * Adds the given {@code parameters} as a query string to the given - * {@code uri}. - */ - public static String addQueryParameters(String uri, Object... parameters) { - if (uri == null) { - return null; - } - - // Convert "path?a=b&c=d" to "&a=b&c=d". - StringBuilder query = new StringBuilder(); - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - - String queryString = uri.substring(questionAt + 1); - int beginAt = 0; - - // make sure all the query parameters are encoded - while (true) { - int ampIndex = queryString.indexOf('&', beginAt); - - String param = queryString.substring(beginAt, ampIndex > -1 ? ampIndex : queryString.length()); - - if (!param.isEmpty() || ampIndex > -1) { - query.append('&'); - - int equalsIndex = param.indexOf('='); - if (equalsIndex > -1) { - query.append(encodeUri(decodeUri(param.substring(0, equalsIndex)))); - query.append('='); - query.append(encodeUri(decodeUri(param.substring(equalsIndex+1)))); - - } else { - query.append(encodeUri(decodeUri(param))); - } - } - - if (ampIndex > -1) { - beginAt = ampIndex+1; - } else { - break; - } - } - - uri = uri.substring(0, questionAt); - } - - int parametersLength = parameters != null ? parameters.length : 0; - - for (int i = 0; i < parametersLength; i += 2) { - - // Remove all occurrences of "&name=". - String name = parameters[i].toString(); - String prefix = "&" + name + "="; - int prefixLength = prefix.length(); - int beginAt = 0; - int endAt; - while (true) { - - beginAt = query.indexOf(prefix, beginAt); - if (beginAt < 0) { - break; - } - - endAt = query.indexOf("&", beginAt + prefixLength); - if (endAt > -1) { - query.delete(beginAt, endAt); - - } else { - query.delete(beginAt, query.length()); - break; - } - } - - // Append "&name=value". - if (i + 1 < parametersLength) { - Object value = parameters[i + 1]; - if (value != null) { - for (Object item : ObjectUtils.to(Iterable.class, value)) { - if (item != null) { - query.append('&'); - query.append(encodeUri(name)); - query.append('='); - query.append(encodeUri(item instanceof Enum ? - ((Enum) item).name() : - item.toString())); - } - } - } - } - } - - // Reconstruct the URI. - if (query.length() <= 1) { - return uri; - - } else { - query.delete(0, 1); - query.insert(0, "?"); - query.insert(0, uri); - return query.toString(); - } - } - - /** - * Returns the first query parameter value associated with the given - * {@code name} from the given {@code uri}. - */ - public static String getQueryParameterValue(String uri, String name) { - for (String value : getQueryParameterValues(uri, name)) { - return value; - } - return null; - } - - /** - * Returns a list of query parameter values associated with the given - * {@code name} from the given {@code uri}. - */ - public static List getQueryParameterValues(String uri, String name) { - List values = new ArrayList(); - if (uri != null) { - - // Strip out the path before the query string. - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - uri = uri.substring(questionAt + 1); - } - uri = "&" + uri; - - // Find all occurences of "&name=". - String prefix = "&" + encodeUri(name) + "="; - int prefixLength = prefix.length(); - for (int nameAt = 0; (nameAt = uri.indexOf(prefix, nameAt)) > -1;) { - nameAt += prefixLength; - int andAt = uri.indexOf('&', nameAt); - values.add(decodeUri(andAt > -1 ? - uri.substring(nameAt, andAt) : - uri.substring(nameAt))); - } - } - - return values; - } - - /** Returns a map of query parameters from the given {@code url}. */ - public static Map> getQueryParameterMap(String url) { - Map> map = new LinkedHashMap>(); - - if (url != null) { - int questionAt = url.indexOf('?'); - - if (questionAt > -1) { - url = url.substring(questionAt + 1); - } - - int lastAndAt = 0; - - for (int andAt; - (andAt = url.indexOf('&', lastAndAt)) > -1; - lastAndAt = andAt + 1) { - addParameter(map, url.substring(lastAndAt, andAt)); - } - - addParameter(map, url.substring(lastAndAt)); - } - - return map; - } - - private static void addParameter(Map> map, String pair) { - if (pair == null || pair.length() == 0) { - return; - } - - int equalAt = pair.indexOf('='); - String name; - String value; - - if (equalAt > -1) { - name = decodeUri(pair.substring(0, equalAt)); - value = decodeUri(pair.substring(equalAt + 1)); - - } else { - name = decodeUri(pair); - value = null; - } - - List parameters = map.get(name); - - if (parameters == null) { - parameters = new ArrayList(); - map.put(name, parameters); - } - - parameters.add(value); - } - - /** @deprecated Use {@link #addQueryParameters instead}. */ - @Deprecated - public static String transformUri(String uri, Object... parameters) { - return addQueryParameters(uri, parameters); - } - - /** @deprecated Use {@link #getQueryParameterValue instead}. */ - @Deprecated - public static String getParameter(String uri, String name) { - return getQueryParameterValue(uri, name); - } - - /** @deprecated Use {@link #getQueryParameterValues instead}. */ - @Deprecated - public static String[] getParameterValues(String uri, String name) { - List values = getQueryParameterValues(uri, name); - return values.toArray(new String[values.size()]); - } - - // --- Pattern bridge --- - private static final Map _patterns = new PullThroughCache() { - @Override - protected Pattern produce(String pattern) { - return Pattern.compile(pattern); - } - }; - - /** - * Gets a cached regular expression pattern object based on the given string. - */ - public static Pattern getPattern(String pattern) { - return _patterns.get(pattern); - } - - /** - * Gets a regular expression matcher based on the given string and pattern. - * - * @see #getPattern(String) - */ - public static Matcher getMatcher(CharSequence string, String pattern) { - return getPattern(pattern).matcher(string); - } - - /** - * Helper function that finds all groups in a regex and returns them in a result. find() is called automatically. - */ - public static MatchResult getMatcherResult(CharSequence string, String pattern) { - Matcher matcher = getMatcher(string, pattern); - matcher.find(); - final MatchResult result = matcher.toMatchResult(); - - - return new MatchResult() { - @Override - public int start() { - return result.start(); - } - - @Override - public int start(int group) { - return result.start(group); - } - - @Override - public int end() { - return result.end(); - } - - @Override - public int end(int group) { - return result.end(group); - } - - @Override - public String group() { - return result.group(); - } - - @Override - public String group(int group) { - try { - return result.group(group); - } catch (IllegalStateException e) { - return null; - } catch (IndexOutOfBoundsException e) { - return null; - } - } - - @Override - public int groupCount() { - return result.groupCount(); - } - }; - } - - /** - * Compiles the given regular expression pattern and attempts to match the given string against it. - * - * @see #getMatcher(CharSequence, String). - */ - public static boolean matches(CharSequence string, String pattern) { - return getMatcher(string, pattern).matches(); - } - - public static boolean matchAll(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return false; - } - } - - return true; - } - - public static boolean matchAny(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return true; - } - } - - return false; - } - - public static int matchCount(CharSequence string, String... patterns) { - int count = 0; - for (String pattern : patterns) { - if (matches(string, pattern)) { - ++count; - } - } - - return count; - } - - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #getMatcher(CharSequence, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement) { - return getMatcher(string, pattern).replaceAll(replacement); - } - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #replaceAll(CharSequence, String, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement, String... more) { - String r = replaceAll(string, pattern, replacement); - for (int i = 0, l = more.length; i < l; i += 2) { - r = replaceAll(r, more[i], i + 1 < l ? more[i + 1] : ""); - } - return r; - } - - /** - * Removes a without using regex * - */ - public static String removeAll(CharSequence string, CharSequence pattern) { - if (string == null) { - throw new IllegalArgumentException("String input is null"); - } - if (pattern != null) { - StringBuilder builder = new StringBuilder(string); - String p = pattern.toString(); - int l = pattern.length(); - for (int index; (index = builder.indexOf(p)) > -1;) { - builder.delete(index, index + l); - } - return builder.toString(); - } else { - return string.toString(); - } - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern, int limit) { - return getPattern(pattern).split(string, limit); - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern) { - return getPattern(pattern).split(string); - } - - // --- StringEscapeUtils bridge --- - - public static String escapeCsv(String string) { - return string == null ? null : StringEscapeUtils.escapeCsv(string); - } - - public static String escapeHtml(String string) { - return string == null ? null : StringUtils.replaceAll( - StringEscapeUtils.escapeHtml(string), - "\\x22", """, // double quote - "\\x27", "'"); // single quote - } - - public static String escapeJava(String string) { - return string == null ? null : StringEscapeUtils.escapeJava(string); - } - - /** - * Escapes the input string so that the resulting output can be used - * inside a JavaScript string AND none of the characters in the output - * need to be HTML escaped. - * @param string - * @return the escaped string, or null if the input was null - * This is not the same as HTML escaping a JavaScript escaped string, - * since the output can be used directly in a JavaScript string even - * when HTML-unescaping won't happen. - */ - public static String escapeJavaScript(String string) { - if (string == null) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0, s = string.length(); i < s; ++ i) { - char c = string.charAt(i); - if (0x30 <= c && c <= 0x39 - || 0x41 <= c && c <= 0x5A - || 0x61 <= c && c <= 0x7A) { - sb.append(c); - } else { - String hex = Integer.toHexString(c); - int hexLen = hex.length(); - if (c < 256) { - sb.append("\\x").append("00".substring(hexLen)); - } else { - sb.append("\\u").append("0000".substring(hexLen)); - } - sb.append(hex); - } - } - return sb.toString(); - } - - public static String escapeQuotes(String string) { - return string == null ? null : string.replace("\\", "\\\\").replace("\"", "\\\""); - } - - public static String escapeSql(String string) { - return string == null ? null : StringEscapeUtils.escapeSql(string); - } - - public static String escapeXml(String string) { - return string == null ? null : StringEscapeUtils.escapeXml(string); - } - - public static String unescapeCsv(String string) { - return string == null ? null : StringEscapeUtils.unescapeCsv(string); - } - - public static String unescapeHtml(String string) { - return string == null ? null : StringEscapeUtils.unescapeHtml(string); - } - - public static String unescapeJava(String string) { - return string == null ? null : StringEscapeUtils.unescapeJava(string); - } - - public static String unescapeJavaScript(String string) { - return string == null ? null : StringEscapeUtils.unescapeJavaScript(string); - } - - public static String unescapeXml(String string) { - return string == null ? null : StringEscapeUtils.unescapeXml(string); - } - - // --- StringUtils bridge --- - - /** - * Joins the given list of strings with the given delimiter in between. - */ - public static String join(List strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Joins the given array of strings with the given delimiter in between. - */ - public static String join(String[] strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Checks if a String is empty ("") or null. - */ - public static boolean isEmpty(String string) { - return org.apache.commons.lang.StringUtils.isEmpty(string); - } - - /** - * Checks if a String is whitespace, empty ("") or null. - */ - public static boolean isBlank(String string) { - return org.apache.commons.lang.StringUtils.isBlank(string); - } - - /** - * Null-safe comparison of two Strings, returning true if they are equal. - */ - public static boolean equals(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equals(str1, str2); - } - - /** - * Null-safe, case-insensitive comparison of two Strings, returning true if they are equal. - */ - public static boolean equalsIgnoreCase(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equalsIgnoreCase(str1, str2); - } - - public static String stripHtml(CharSequence sequence) { - Matcher m = StringUtils.getPattern("<[^>]*>").matcher(sequence); - return m.replaceAll(""); - } - - /** - * Ensures that the given {@code string} starts with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - return string; - } - - /** - * Ensures that the given {@code string} ends with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - - /** - * Ensures that the given {@code string} starts and ends with - * the given {@code delimiter}, adding them if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts or ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - } - - /** - * @param path If {@code null}, returns {@code null}. - * @param servletPath If {@code null}, returns {@code null}. - */ - public static String getPathInfo(String path, String servletPath) { - if (path != null && servletPath != null) { - path = ensureStart(path, "/"); - servletPath = removeEnd(ensureStart(servletPath, "/"), "/"); - - if (path.startsWith(servletPath)) { - String pathInfo = path.substring(servletPath.length()); - - if (pathInfo.length() == 0) { - return "/"; - - } else if (pathInfo.startsWith("/")) { - return pathInfo; - } - } - } - - return null; - } - - private static final int ASCII_SIZE = 256; - private static final char[] LOWER_CASE_ASCII; - - static { - LOWER_CASE_ASCII = new char[ASCII_SIZE]; - - for (int i = 0; i < ASCII_SIZE; ++ i) { - LOWER_CASE_ASCII[i] = (char) Character.toLowerCase(i); - } - } - - /** - * @param string Can't be {@code null}. - */ - public static String toLowerCaseAscii(String string) { - char[] letters = string.toCharArray(); - char letter; - - for (int i = 0, length = letters.length; i < length; ++ i) { - letter = letters[i]; - - if (letter < ASCII_SIZE) { - letters[i] = LOWER_CASE_ASCII[letter]; - } - } - - return new String(letters); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/old/StringUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/old/StringUtils.java deleted file mode 100755 index 884d198..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/old/StringUtils.java +++ /dev/null @@ -1,1214 +0,0 @@ -package com.psddev.dari.util; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.lang.StringEscapeUtils; - -/** String utility methods. */ -public final class StringUtils { - - public static final Charset US_ASCII = Charset.forName("US-ASCII"); - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - public static final Charset UTF_8 = Charset.forName("UTF-8"); - public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); - public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); - public static final Charset UTF_16 = Charset.forName("UTF-16"); - - private static final Set - ABBREVIATIONS = new HashSet(Arrays.asList( - "cms", "css", "id", "js", "seo", "uri", "url")); - - private static final char[] HEX_CHARACTERS = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f' }; - - /** - * Converts given string into a value of given type, throwing an exception - * if conversion was unsuccessful. - * - * If the return type is an array, an array is returned. - * fromString(int[].class, "1", "2") => int[] {1,2} - * - * If no values are provided and the return type is an array, an empty array is returned. - * fromString(int[].class) => int[] {} - * - * If no values are provided and the return type is not an array, an exception - * appropriate to the conversion type is thrown. - * fromString(int.class) => NumberFormatException - * - * If the {@code strings} contains more than one value and the {@code returnType} is not - * an array, all but the first value are ignored. - * - * If the method cannot convert to the class specified, an IllegalArgumentException is thrown. - * - * @param - * @param returnType The class for the String input(s) to be converted to - * @param strings the input(s) to be converted - * @return the converted value - */ - public static T fromString(Class returnType, String... strings) { - - // heavy voodoo follows... - // need to return an array - Class componentType = returnType.getComponentType(); - if (componentType != null) { - if (strings == null) { - return null; - } else { - int length = strings.length; - Object typed = Array.newInstance(componentType, length); - for (int i = 0; i < length; i++) { - Array.set(typed, i, fromString(componentType, strings[i])); - } - return (T) typed; - } - - // single value - } else { - String string = strings == null || strings.length == 0 ? null : strings[0]; - - // string to string - if (String.class == returnType) { - return (T) string; - - // primitives - // pass null through if returnType allows it - } else if (string == null && !returnType.isPrimitive()) { - return null; - - // any way to avoid boxing/unboxing on primitives? - } else if (boolean.class == returnType || Boolean.class.isAssignableFrom(returnType)) { - return (T) Boolean.valueOf(string); - } else if (byte.class == returnType || Byte.class.isAssignableFrom(returnType)) { - return (T) Byte.valueOf(string); - } else if (short.class == returnType || Short.class.isAssignableFrom(returnType)) { - return (T) Short.valueOf(string); - } else if (int.class == returnType || Integer.class.isAssignableFrom(returnType)) { - return (T) Integer.valueOf(string); - } else if (long.class == returnType || Long.class.isAssignableFrom(returnType)) { - return (T) Long.valueOf(string); - } else if (float.class == returnType || Float.class.isAssignableFrom(returnType)) { - return (T) Float.valueOf(string); - } else if (double.class == returnType || Double.class.isAssignableFrom(returnType)) { - return (T) Double.valueOf(string); - } else if (char.class == returnType || Character.class.isAssignableFrom(returnType)) { - if (string.length() == 1) { - return (T) Character.valueOf(string.charAt(0)); - } - - // others - } else if (Date.class.isAssignableFrom(returnType)) { - return (T) DateUtils.fromString(string); - } - throw new IllegalArgumentException(String.format( - "Cannot convert [%s] string to [%s] type!", - string, - returnType.getName() - )); - } - } - - - /** - * Helper method to split a string by case change or common delimiters. - * - * Multiple delimeters in a row are reduced to a single word boundry. - * - * Leading delimeters (a space at the beginning of the string) will cause an - * empty first word to be detected (bug?). Trailing delemeters do not cause empty - * words to be detected. - * - * Returned words are all lowercased. - * - * @param string - * @return the list of words detected in the string - */ - protected static List splitString(String string) { - List words = new ArrayList(); - int m = 0, l = string.length(); - for (int i = 0; i < l; i++) { - char c = string.charAt(i); - if (" -_.$".indexOf(c) > -1) { - words.add(string.substring(m, i).toLowerCase()); - while (++i < l && " -_.$".indexOf(string.charAt(i)) > -1) { - } - m = i; - } else if (Character.isUpperCase(c) && i > 0 && Character.isLowerCase(string.charAt(i - 1))) { - words.add(string.substring(m, i).toLowerCase()); - m = i; - } - } - if (m + 1 < l) { - words.add(string.substring(m).toLowerCase()); - } - return words; - } - - /** - * Tries to detect words within a given string and join them with the given delimiter. - */ - public static String toDelimited(String string, String delimiter) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(word).append(delimiter); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - delimiter.length()); - } - return nb.toString(); - } - - /** - * Converts the given string into a-hyphenated-string. - */ - public static String toHyphenated(String string) { - return toDelimited(string, "-"); - } - - /** - * Converts the given string into a_underscored_string. - */ - public static String toUnderscored(String string) { - return toDelimited(string, "_"); - } - - /** - * Converts the given string into APascalCaseString. - */ - public static String toPascalCase(String string) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); - } - return nb.toString(); - } - - /** - * Converts the given string into aCamelCaseString. - */ - public static String toCamelCase(String string) { - string = toPascalCase(string); - return Character.toLowerCase(string.charAt(0)) + string.substring(1); - } - - /** - * Converts the string to one suitable for use as "a label"? - * - * Splits {@code string} into words, joining it back together "In Title Case" - * with known {@code ABBREVIATIONS} replaced in all caps. If the first word of - * {@code string} is "is", that word is removed and a question mark is - * added to the end of the resulting string. - * - * @param string - */ - public static String toLabel(String string) { - - if (string == null) { - return null; - } - - boolean isQuestion = false; - List words = splitString(string); - if (words.size() > 0 && "is".equals(words.get(0))) { - isQuestion = true; - words.remove(0); - } - - StringBuilder nb = new StringBuilder(); - for (String word : words) { - if (word.length() == 0) { - continue; - } - - if (ABBREVIATIONS.contains(word)) { - nb.append(word.toUpperCase(Locale.ENGLISH)); - } else { - nb.append(Character.toUpperCase(word.charAt(0))); - nb.append(word.substring(1)); - } - nb.append(' '); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - 1); - } - - if (isQuestion) { - nb.append('?'); - } - - return nb.toString(); - } - - /** - * Normalizes a string, removing or replacing non-alphanumeric characters and lowercasing - * - * - Removes all accented characters. - * - Removes single quotes - * - Replaces non-alphanumeric characters remaining with a dash - * - Removes dashes - * - * Lowercases the result - */ - public static String toNormalized(CharSequence string) { - return string == null ? null : replaceAll( - Normalizer.normalize(string, Normalizer.Form.NFD), - "[^\\p{ASCII}]", "", - "'", "", - "\\.", "", - "[^a-zA-Z0-9]+", "-", - "^-+|-+$", "" - ).toLowerCase(); - } - - /** Splits the given string by commas, and returns each part unescaped. - * Calling {@link #toCsv(String...)} on an array of Strings and then - * passing the result to this method will always return the same array - * as specified by the Arrays.equals() method. */ - public static String[] fromCsv(String string) { - if(string == null) { - return null; - } else { - // replaces a call to string.split(",") - char[] charArr = string.toCharArray(); - int commaCount = 0; - for (char c : charArr) { - if (c == ',') { - commaCount++; - } - } - String[] escaped = new String[commaCount+1]; - int index = 0; - int offset = 0; - int count = 0; - for (char c : charArr) { - if (c == ',') { - escaped[index++] = new String(charArr, offset, count); - offset += count+1; - count = 0; - } else { - count++; - } - } - if (index == commaCount) { - escaped[index] = new String(charArr, offset, count); - } - // end string.split(",") replacement code - - int length = escaped.length; - List unescaped = new ArrayList(); - for(int i = 0; i < length; i ++) { - String value = escaped[i]; - if(value.startsWith("\"")) { // there are commas and/or double quotes escaped within - StringBuilder builder = new StringBuilder(); - int quoteCount = 0; - do { - builder.append(value); - for(char c : value.toCharArray()) { - if(c == '"') { - quoteCount++; - } - } - if(quoteCount % 2 == 1) { - value = escaped[++i]; - builder.append(','); - } - } while(quoteCount % 2 == 1); - value = builder.toString(); - } - unescaped.add(StringUtils.unescapeCsv(value)); - } - return unescaped.toArray(new String[unescaped.size()]); - } - } - - /** Converts an array of Strings to a single String in comma separated - * values format, escaping each string as necessary. */ - public static String toCsv(String... strings) { - if (strings == null) { - return null; - } - StringBuilder builder = new StringBuilder(); - for (String string : strings) { - builder.append(escapeCsv(string)).append(','); - } - if (builder.length() > 0) { - builder.setLength(builder.length()-1); - } - return builder.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string, int maxWordLength) { - if (string == null) { - return null; - } - Matcher matcher = getMatcher(string, String.format("(\\S{%d,})", maxWordLength)); - StringBuilder output = new StringBuilder(); - int marker = 0; - while (matcher.find()) { - String longWord = matcher.group(1); - - // similar to Matcher.appendReplacement - // re-implemented so that $ and \ does not have to be escaped - if (matcher.start() > marker) { - output.append(string.substring(marker, matcher.start())); - } - int i = 0; - for (; i < longWord.length() - maxWordLength; i += maxWordLength) { - output.append(escapeHtml(longWord.substring(i, i + maxWordLength))); - output.append(""); - } - output.append(escapeHtml(longWord.substring(i))); - marker = matcher.end(); - } - - // similar to Matcher.appendTail - output.append(string.substring(marker)); - return output.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string) { - return escapeHtmlAndBreak(string, 20); - } - - /** Converts the given {@code bytes} into a hex string. */ - public static String hex(byte[] bytes) { - if (bytes == null) { - return null; - } - - int bytesLength = bytes.length; - byte currentByte; - char[] hex = new char[bytesLength * 2]; - - for (int byteIndex = 0, hexIndex = 0; - byteIndex < bytesLength; - ++ byteIndex, hexIndex += 2) { - - currentByte = bytes[byteIndex]; - hex[hexIndex] = HEX_CHARACTERS[(currentByte & 0xf0) >> 4]; - hex[hexIndex + 1] = HEX_CHARACTERS[(currentByte & 0x0f)]; - } - - return new String(hex); - } - - /** Hashes the given {@code string} using the given {@code algorithm}. */ - public static byte[] hash(String algorithm, String string) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance(algorithm); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid hash algorithm!", algorithm), ex); - } - - byte[] bytes; - try { - bytes = string.getBytes("UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - - return digest.digest(bytes); - } - - /** Hashes the given {@code string} using the MD5 algorithm. */ - public static byte[] md5(String string) { - return hash("MD5", string); - } - - /** Hashes the given {@code string} using the SHA-1 algorithm. */ - public static byte[] sha1(String string) { - return hash("SHA-1", string); - } - - /** Hashes the given {@code string} using the SHA-512 algorithm. */ - public static byte[] sha512(String string) { - return hash("SHA-512", string); - } - - /** - * Hashes the given {@code string} using the given HMAC {@code algorithm} - * and {@code key}. - */ - public static byte[] hmac(String algorithm, String key, String string) { - try { - Mac mac = Mac.getInstance(algorithm); - mac.init(new SecretKeySpec(key.getBytes(StringUtils.UTF_8), algorithm)); - return mac.doFinal(string.getBytes(StringUtils.UTF_8)); - - } catch (NoSuchAlgorithmException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid HMAC algorithm!", algorithm), error); - - } catch (InvalidKeyException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid key!", key), error); - } - } - - /** - * Hashes the given {@code string} using the HMAC SHA-1 algorithm - * and the given {@code key}. - */ - public static byte[] hmacSha1(String key, String string) { - return hmac("HmacSHA1", key, string); - } - - // --- URL/URI --- - - /** - * Encodes the given UTF-8 {@code string} so that it's safe for use - * within an URI. - */ - public static String encodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLEncoder.encode(string, "UTF-8").replace("+", "%20"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** Decodes the given URI-encoded, UTF-8 {@code string}. */ - public static String decodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLDecoder.decode(string, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** - * Adds the given {@code parameters} as a query string to the given - * {@code uri}. - */ - public static String addQueryParameters(String uri, Object... parameters) { - if (uri == null) { - return null; - } - - // Convert "path?a=b&c=d" to "&a=b&c=d". - StringBuilder query = new StringBuilder(); - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - - String queryString = uri.substring(questionAt + 1); - int beginAt = 0; - - // make sure all the query parameters are encoded - while (true) { - int ampIndex = queryString.indexOf('&', beginAt); - - String param = queryString.substring(beginAt, ampIndex > -1 ? ampIndex : queryString.length()); - - if (!param.isEmpty() || ampIndex > -1) { - query.append('&'); - - int equalsIndex = param.indexOf('='); - if (equalsIndex > -1) { - query.append(encodeUri(decodeUri(param.substring(0, equalsIndex)))); - query.append('='); - query.append(encodeUri(decodeUri(param.substring(equalsIndex+1)))); - - } else { - query.append(encodeUri(decodeUri(param))); - } - } - - if (ampIndex > -1) { - beginAt = ampIndex+1; - } else { - break; - } - } - - uri = uri.substring(0, questionAt); - } - - int parametersLength = parameters != null ? parameters.length : 0; - - for (int i = 0; i < parametersLength; i += 2) { - - // Remove all occurrences of "&name=". - String name = parameters[i].toString(); - String prefix = "&" + name + "="; - int prefixLength = prefix.length(); - int beginAt = 0; - int endAt; - while (true) { - - beginAt = query.indexOf(prefix, beginAt); - if (beginAt < 0) { - break; - } - - endAt = query.indexOf("&", beginAt + prefixLength); - if (endAt > -1) { - query.delete(beginAt, endAt); - - } else { - query.delete(beginAt, query.length()); - break; - } - } - - // Append "&name=value". - if (i + 1 < parametersLength) { - Object value = parameters[i + 1]; - if (value != null) { - for (Object item : ObjectUtils.to(Iterable.class, value)) { - if (item != null) { - query.append('&'); - query.append(encodeUri(name)); - query.append('='); - query.append(encodeUri(item instanceof Enum ? - ((Enum) item).name() : - item.toString())); - } - } - } - } - } - - // Reconstruct the URI. - if (query.length() <= 1) { - return uri; - - } else { - query.delete(0, 1); - query.insert(0, "?"); - query.insert(0, uri); - return query.toString(); - } - } - - /** - * Returns the first query parameter value associated with the given - * {@code name} from the given {@code uri}. - */ - public static String getQueryParameterValue(String uri, String name) { - for (String value : getQueryParameterValues(uri, name)) { - return value; - } - return null; - } - - /** - * Returns a list of query parameter values associated with the given - * {@code name} from the given {@code uri}. - */ - public static List getQueryParameterValues(String uri, String name) { - List values = new ArrayList(); - if (uri != null) { - - // Strip out the path before the query string. - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - uri = uri.substring(questionAt + 1); - } - uri = "&" + uri; - - // Find all occurences of "&name=". - String prefix = "&" + encodeUri(name) + "="; - int prefixLength = prefix.length(); - for (int nameAt = 0; (nameAt = uri.indexOf(prefix, nameAt)) > -1;) { - nameAt += prefixLength; - int andAt = uri.indexOf('&', nameAt); - values.add(decodeUri(andAt > -1 ? - uri.substring(nameAt, andAt) : - uri.substring(nameAt))); - } - } - - return values; - } - - /** Returns a map of query parameters from the given {@code url}. */ - public static Map> getQueryParameterMap(String url) { - Map> map = new LinkedHashMap>(); - - if (url != null) { - int questionAt = url.indexOf('?'); - - if (questionAt > -1) { - url = url.substring(questionAt + 1); - } - - int lastAndAt = 0; - - for (int andAt; - (andAt = url.indexOf('&', lastAndAt)) > -1; - lastAndAt = andAt + 1) { - addParameter(map, url.substring(lastAndAt, andAt)); - } - - addParameter(map, url.substring(lastAndAt)); - } - - return map; - } - - private static void addParameter(Map> map, String pair) { - if (pair == null || pair.length() == 0) { - return; - } - - int equalAt = pair.indexOf('='); - String name; - String value; - - if (equalAt > -1) { - name = decodeUri(pair.substring(0, equalAt)); - value = decodeUri(pair.substring(equalAt + 1)); - - } else { - name = decodeUri(pair); - value = null; - } - - List parameters = map.get(name); - - if (parameters == null) { - parameters = new ArrayList(); - map.put(name, parameters); - } - - parameters.add(value); - } - - /** @deprecated Use {@link #addQueryParameters instead}. */ - @Deprecated - public static String transformUri(String uri, Object... parameters) { - return addQueryParameters(uri, parameters); - } - - /** @deprecated Use {@link #getQueryParameterValue instead}. */ - @Deprecated - public static String getParameter(String uri, String name) { - return getQueryParameterValue(uri, name); - } - - /** @deprecated Use {@link #getQueryParameterValues instead}. */ - @Deprecated - public static String[] getParameterValues(String uri, String name) { - List values = getQueryParameterValues(uri, name); - return values.toArray(new String[values.size()]); - } - - // --- Pattern bridge --- - private static final Map _patterns = new PullThroughCache() { - @Override - protected Pattern produce(String pattern) { - return Pattern.compile(pattern); - } - }; - - /** - * Gets a cached regular expression pattern object based on the given string. - */ - public static Pattern getPattern(String pattern) { - return _patterns.get(pattern); - } - - /** - * Gets a regular expression matcher based on the given string and pattern. - * - * @see #getPattern(String) - */ - public static Matcher getMatcher(CharSequence string, String pattern) { - return getPattern(pattern).matcher(string); - } - - /** - * Helper function that finds all groups in a regex and returns them in a result. find() is called automatically. - */ - public static MatchResult getMatcherResult(CharSequence string, String pattern) { - Matcher matcher = getMatcher(string, pattern); - matcher.find(); - final MatchResult result = matcher.toMatchResult(); - - - return new MatchResult() { - @Override - public int start() { - return result.start(); - } - - @Override - public int start(int group) { - return result.start(group); - } - - @Override - public int end() { - return result.end(); - } - - @Override - public int end(int group) { - return result.end(group); - } - - @Override - public String group() { - return result.group(); - } - - @Override - public String group(int group) { - try { - return result.group(group); - } catch (IllegalStateException e) { - return null; - } catch (IndexOutOfBoundsException e) { - return null; - } - } - - @Override - public int groupCount() { - return result.groupCount(); - } - }; - } - - /** - * Compiles the given regular expression pattern and attempts to match the given string against it. - * - * @see #getMatcher(CharSequence, String). - */ - public static boolean matches(CharSequence string, String pattern) { - return getMatcher(string, pattern).matches(); - } - - public static boolean matchAll(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return false; - } - } - - return true; - } - - public static boolean matchAny(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return true; - } - } - - return false; - } - - public static int matchCount(CharSequence string, String... patterns) { - int count = 0; - for (String pattern : patterns) { - if (matches(string, pattern)) { - ++count; - } - } - - return count; - } - - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #getMatcher(CharSequence, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement) { - return getMatcher(string, pattern).replaceAll(replacement); - } - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #replaceAll(CharSequence, String, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement, String... more) { - String r = replaceAll(string, pattern, replacement); - for (int i = 0, l = more.length; i < l; i += 2) { - r = replaceAll(r, more[i], i + 1 < l ? more[i + 1] : ""); - } - return r; - } - - /** - * Removes a without using regex * - */ - public static String removeAll(CharSequence string, CharSequence pattern) { - if (string == null) { - throw new IllegalArgumentException("String input is null"); - } - if (pattern != null) { - StringBuilder builder = new StringBuilder(string); - String p = pattern.toString(); - int l = pattern.length(); - for (int index; (index = builder.indexOf(p)) > -1;) { - builder.delete(index, index + l); - } - return builder.toString(); - } else { - return string.toString(); - } - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern, int limit) { - return getPattern(pattern).split(string, limit); - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern) { - return getPattern(pattern).split(string); - } - - // --- StringEscapeUtils bridge --- - - public static String escapeCsv(String string) { - return string == null ? null : StringEscapeUtils.escapeCsv(string); - } - - public static String escapeHtml(String string) { - return string == null ? null : StringUtils.replaceAll( - StringEscapeUtils.escapeHtml(string), - "\\x22", """, // double quote - "\\x27", "'"); // single quote - } - - public static String escapeJava(String string) { - return string == null ? null : StringEscapeUtils.escapeJava(string); - } - - /** - * Escapes the input string so that the resulting output can be used - * inside a JavaScript string AND none of the characters in the output - * need to be HTML escaped. - * @param string - * @return the escaped string, or null if the input was null - * This is not the same as HTML escaping a JavaScript escaped string, - * since the output can be used directly in a JavaScript string even - * when HTML-unescaping won't happen. - */ - public static String escapeJavaScript(String string) { - if (string == null) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0, s = string.length(); i < s; ++ i) { - char c = string.charAt(i); - if (0x30 <= c && c <= 0x39 - || 0x41 <= c && c <= 0x5A - || 0x61 <= c && c <= 0x7A) { - sb.append(c); - } else { - String hex = Integer.toHexString(c); - int hexLen = hex.length(); - if (c < 256) { - sb.append("\\x").append("00".substring(hexLen)); - } else { - sb.append("\\u").append("0000".substring(hexLen)); - } - sb.append(hex); - } - } - return sb.toString(); - } - - public static String escapeQuotes(String string) { - return string == null ? null : string.replace("\\", "\\\\").replace("\"", "\\\""); - } - - public static String escapeSql(String string) { - return string == null ? null : StringEscapeUtils.escapeSql(string); - } - - public static String escapeXml(String string) { - return string == null ? null : StringEscapeUtils.escapeXml(string); - } - - public static String unescapeCsv(String string) { - return string == null ? null : StringEscapeUtils.unescapeCsv(string); - } - - public static String unescapeHtml(String string) { - return string == null ? null : StringEscapeUtils.unescapeHtml(string); - } - - public static String unescapeJava(String string) { - return string == null ? null : StringEscapeUtils.unescapeJava(string); - } - - public static String unescapeJavaScript(String string) { - return string == null ? null : StringEscapeUtils.unescapeJavaScript(string); - } - - public static String unescapeXml(String string) { - return string == null ? null : StringEscapeUtils.unescapeXml(string); - } - - // --- StringUtils bridge --- - - /** - * Joins the given list of strings with the given delimiter in between. - */ - public static String join(List strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Joins the given array of strings with the given delimiter in between. - */ - public static String join(String[] strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Checks if a String is empty ("") or null. - */ - public static boolean isEmpty(String string) { - return org.apache.commons.lang.StringUtils.isEmpty(string); - } - - /** - * Checks if a String is whitespace, empty ("") or null. - */ - public static boolean isBlank(String string) { - return org.apache.commons.lang.StringUtils.isBlank(string); - } - - /** - * Null-safe comparison of two Strings, returning true if they are equal. - */ - public static boolean equals(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equals(str1, str2); - } - - /** - * Null-safe, case-insensitive comparison of two Strings, returning true if they are equal. - */ - public static boolean equalsIgnoreCase(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equalsIgnoreCase(str1, str2); - } - - public static String stripHtml(CharSequence sequence) { - Matcher m = StringUtils.getPattern("<[^>]*>").matcher(sequence); - return m.replaceAll(""); - } - - /** - * Ensures that the given {@code string} starts with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - return string; - } - - /** - * Ensures that the given {@code string} ends with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - - /** - * Ensures that the given {@code string} starts and ends with - * the given {@code delimiter}, adding them if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts or ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - } - - /** - * @param path If {@code null}, returns {@code null}. - * @param servletPath If {@code null}, returns {@code null}. - */ - public static String getPathInfo(String path, String servletPath) { - if (path != null && servletPath != null) { - path = ensureStart(path, "/"); - servletPath = removeEnd(ensureStart(servletPath, "/"), "/"); - - if (path.startsWith(servletPath)) { - String pathInfo = path.substring(servletPath.length()); - - if (pathInfo.length() == 0) { - return "/"; - - } else if (pathInfo.startsWith("/")) { - return pathInfo; - } - } - } - - return null; - } - - private static final int ASCII_SIZE = 256; - private static final char[] LOWER_CASE_ASCII; - - static { - LOWER_CASE_ASCII = new char[ASCII_SIZE]; - - for (int i = 0; i < ASCII_SIZE; ++ i) { - LOWER_CASE_ASCII[i] = (char) Character.toLowerCase(i); - } - } - - /** - * @param string Can't be {@code null}. - */ - public static String toLowerCaseAscii(String string) { - char[] letters = string.toCharArray(); - char letter; - - for (int i = 0, length = letters.length; i < length; ++ i) { - letter = letters[i]; - - if (letter < ASCII_SIZE) { - letters[i] = LOWER_CASE_ASCII[letter]; - } - } - - return new String(letters); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/pair.info deleted file mode 100755 index 0cf57fe..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52191/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:52191 -comSha:19c5adce2eddd8f66c48a851ffa213410093b297 -parentComSha:109e21ae4416431beaa4ddcbf159b8e410a2bdfa -BuggyFilePath:util/src/main/java/com/psddev/dari/util/StringUtils.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/StringUtils.java -StartLineNum:155 -EndLineNum:155 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/comMsg.txt deleted file mode 100755 index 978c561..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Use US locale everywhere when converting case. - -This fixes #400. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/diff.diff deleted file mode 100755 index fc8bc9c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/nodebox/ui/ImageFormat.java b/src/main/java/nodebox/ui/ImageFormat.java -index ce440449..1400148e 100644 ---- a/src/main/java/nodebox/ui/ImageFormat.java -+++ b/src/main/java/nodebox/ui/ImageFormat.java -@@ -4,0 +5 @@ import java.util.HashMap; -+import java.util.Locale; -@@ -23 +24 @@ public final class ImageFormat { -- return FORMAT_MAP.get(name.toUpperCase()); -+ return FORMAT_MAP.get(name.toUpperCase(Locale.US)); -@@ -47 +48 @@ public final class ImageFormat { -- if (file.toLowerCase().endsWith("." + getExtension())) -+ if (file.toLowerCase(Locale.US).endsWith("." + getExtension())) \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/new/ImageFormat.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/new/ImageFormat.java deleted file mode 100755 index 1400148..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/new/ImageFormat.java +++ /dev/null @@ -1,53 +0,0 @@ -package nodebox.ui; - -import java.io.File; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; - -public final class ImageFormat { - - public static final ImageFormat PDF = new ImageFormat("PDF", "pdf"); - public static final ImageFormat PNG = new ImageFormat("PNG", "png"); - public static final ImageFormat SVG = new ImageFormat("SVG", "svg"); - - private static final Map FORMAT_MAP; - - static { - FORMAT_MAP = new HashMap(); - FORMAT_MAP.put("PDF", PDF); - FORMAT_MAP.put("PNG", PNG); - FORMAT_MAP.put("SVG", SVG); - } - - public static ImageFormat of(String name) { - return FORMAT_MAP.get(name.toUpperCase(Locale.US)); - } - - private final String label; - private final String extension; - - public ImageFormat(String label, String extension) { - this.label = label; - this.extension = extension; - } - - public String getLabel() { - return label; - } - - public String getExtension() { - return extension; - } - - public File ensureFileExtension(File file) { - return new File(ensureFileExtension(file.getPath())); - } - - public String ensureFileExtension(String file) { - if (file.toLowerCase(Locale.US).endsWith("." + getExtension())) - return file; - return file + "." + getExtension(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/old/ImageFormat.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/old/ImageFormat.java deleted file mode 100755 index ce44044..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/old/ImageFormat.java +++ /dev/null @@ -1,52 +0,0 @@ -package nodebox.ui; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -public final class ImageFormat { - - public static final ImageFormat PDF = new ImageFormat("PDF", "pdf"); - public static final ImageFormat PNG = new ImageFormat("PNG", "png"); - public static final ImageFormat SVG = new ImageFormat("SVG", "svg"); - - private static final Map FORMAT_MAP; - - static { - FORMAT_MAP = new HashMap(); - FORMAT_MAP.put("PDF", PDF); - FORMAT_MAP.put("PNG", PNG); - FORMAT_MAP.put("SVG", SVG); - } - - public static ImageFormat of(String name) { - return FORMAT_MAP.get(name.toUpperCase()); - } - - private final String label; - private final String extension; - - public ImageFormat(String label, String extension) { - this.label = label; - this.extension = extension; - } - - public String getLabel() { - return label; - } - - public String getExtension() { - return extension; - } - - public File ensureFileExtension(File file) { - return new File(ensureFileExtension(file.getPath())); - } - - public String ensureFileExtension(String file) { - if (file.toLowerCase().endsWith("." + getExtension())) - return file; - return file + "." + getExtension(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/pair.info deleted file mode 100755 index b241be3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5239/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:5239 -comSha:2fc22b4e8894fc318ee21a5355df8815786190d3 -parentComSha:274890519fd60ac0097fe47e00ec510b285260d5 -BuggyFilePath:src/main/java/nodebox/ui/ImageFormat.java -FixedFilePath:src/main/java/nodebox/ui/ImageFormat.java -StartLineNum:47 -EndLineNum:47 -repoName:nodebox#nodebox \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/comMsg.txt deleted file mode 100755 index 59490ec..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/comMsg.txt +++ /dev/null @@ -1,4 +0,0 @@ -Merge branch 'feature/pmd' - -Conflicts: - db/src/main/java/com/psddev/dari/db/SqlDatabase.java \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/diff.diff deleted file mode 100755 index f4ae169..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/FormTag.java b/util/src/main/java/com/psddev/dari/util/FormTag.java -index b473a60a..ffa31658 100644 ---- a/util/src/main/java/com/psddev/dari/util/FormTag.java -+++ b/util/src/main/java/com/psddev/dari/util/FormTag.java -@@ -5,0 +6 @@ import java.util.LinkedHashMap; -+import java.util.Locale; -@@ -174 +175 @@ public class FormTag extends TagSupport implements DynamicAttributes { -- "method", method.toLowerCase(), -+ "method", method.toLowerCase(Locale.ENGLISH), -@@ -263,0 +265,3 @@ public class FormTag extends TagSupport implements DynamicAttributes { -+ private Static() { -+ } -+ \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/new/FormTag.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/new/FormTag.java deleted file mode 100755 index ffa3165..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/new/FormTag.java +++ /dev/null @@ -1,304 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.DynamicAttributes; -import javax.servlet.jsp.tagext.TagSupport; - -@SuppressWarnings("serial") -public class FormTag extends TagSupport implements DynamicAttributes { - - private static final String PARAMETER_PREFIX = "_f."; - public static final String ID_PARAMETER = PARAMETER_PREFIX + "id"; - - private static final String ATTRIBUTE_PREFIX = FormTag.class.getName() + "."; - private static final String PROCESSOR_ATTRIBUTE_PREFIX = ATTRIBUTE_PREFIX + "processor/"; - - /** Map of the MD5 hash of a processor class name to the Class object itself. */ - private static final ConcurrentHashMap> PROCESSOR_CLASSES = - new ConcurrentHashMap>(); - - private String method; - private Class processorClass; - - private String varProcessor; - private String varSuccess; - private String varError; - private String varResult; - - private transient Boolean success; - private transient Object result; - private transient Object error; - - private final Map attributes = new LinkedHashMap(); - - /** - * Sets the form submission method. - * - * @param method Can't be {@code null}. - */ - public void setMethod(String method) { - ErrorUtils.errorIfNull(method, "method"); - - this.method = method; - } - - /** - * Sets the name of the processor class. - * - * @param processor The class name must be valid, and the class must - * implement {@link FormProcessor}. - */ - @SuppressWarnings("unchecked") - public void setProcessor(String processor) { - Class pc = ObjectUtils.getClassByName(processor); - - ErrorUtils.errorIf(pc == null, processor, "isn't a valid class name!"); - ErrorUtils.errorIf(!FormProcessor.class.isAssignableFrom(pc), pc.getName(), "doesn't implement [" + FormProcessor.class.getName() + "]!"); - - this.processorClass = (Class) pc; - } - - public Class getProcessorClass() { - return this.processorClass; - } - - /** - * Sets the name of the page-scoped variable to store the processor - * instance. - */ - public void setVarProcessor(String varProcessor) { - this.varProcessor = varProcessor; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * success flag. - */ - public void setVarSuccess(String varSuccess) { - this.varSuccess = varSuccess; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * error. - */ - public void setVarError(String varError) { - this.varError = varError; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * result. - * - * @return May be {@code null}. - */ - public void setVarResult(String varResult) { - this.varResult = varResult; - } - - /** Returns a unique identifier for this form. */ - public String getFormId() { - return Static.getProcessorId(processorClass) + (getId() != null ? ("/" + getId()) : ""); - } - - /** Returns the processor for this form. */ - public FormProcessor getProcessorInstance() { - return Static.getProcessorById(getFormId(), (HttpServletRequest) pageContext.getRequest()); - } - - // --- Getters for the transient variables --- - - /** - * Return true if this form was processed successfully, or false if not. - * Null is returned if this method is called outside the context of this - * form's start and end tags. - * - * @return - */ - public Boolean isSuccess() { - return success; - } - - /** - * Returns the result of processing this form, or null if there was an error - * or this method is called outside the context of this form's start and - * end tags. - * - * @return - */ - public Object getResult() { - return result; - } - - /** - * Returns the error generated attempting to process this form, or null if - * if the form was processed successfully or this method is called outside - * the context of this form's start and end tags. - * - * @return - */ - public Object getError() { - return error; - } - - // --- TagSupport support --- - - @Override - public int doStartTag() throws JspException { - - HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); - - String formId = getFormId(); - FormProcessor processor = getProcessorInstance(); - - if (!ObjectUtils.isBlank(varProcessor)) { - pageContext.setAttribute(varProcessor, processor); - } - - // Write the FORM start tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("form", - "id", getId(), - "method", method.toLowerCase(Locale.ENGLISH), - "action", "", - attributes); - writer.writeTag("input", - "type", "hidden", - "name", ID_PARAMETER, - "value", formId); - - - // If process() was already called by FormFilter - String bufferedOutput = FormFilter.Static.getBufferedOutput(formId, request); - if (bufferedOutput != null) { - writer.write(bufferedOutput); - - success = FormFilter.Static.isFormSuccess(request); - result = FormFilter.Static.getFormResult(request); - error = FormFilter.Static.getFormError(request); - - } else { - // process it - try { - result = processor.process(request, new HttpServletResponseWrapper((HttpServletResponse) pageContext.getResponse()) { - private PrintWriter writer; { - writer = new PrintWriter(pageContext.getOut()); - } - @Override - public PrintWriter getWriter() { - return writer; - } - }); - success = true; - - } catch (IOException e) { - throw e; - - } catch (Throwable e) { - error = e; - success = false; - } - } - - // Set the status vars if they are defined - if (!ObjectUtils.isBlank(varSuccess)) { - pageContext.setAttribute(varSuccess, isSuccess()); - } - if (!ObjectUtils.isBlank(varResult)) { - pageContext.setAttribute(varResult, getResult()); - } - if (!ObjectUtils.isBlank(varError)) { - pageContext.setAttribute(varError, getError()); - } - - } catch (IOException error) { - throw new JspException(error); - } - - return EVAL_BODY_INCLUDE; - } - - @Override - public int doEndTag() throws JspException { - // Write the FORM end tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("/form"); - - } catch (IOException error) { - throw new JspException(error); - - } finally { - // null out the transient variables - success = null; - error = null; - result = null; - } - - return EVAL_PAGE; - } - - // --- DynamicAttribute support --- - - @Override - public void setDynamicAttribute(String uri, String localName, Object value) { - attributes.put(localName, value != null ? value.toString() : null); - } - - public static final class Static { - - private Static() { - } - - public static FormProcessor getProcessorById(String id, HttpServletRequest request) { - if (id == null) { - return null; - } - - // Strip off the form ID attribute part of the ID if it exists. - String processorId; - int slashAt = id.indexOf('/'); - if (slashAt < 0) { - processorId = id; - - } else { - processorId = id.substring(0, slashAt); - } - - FormProcessor processor = (FormProcessor) request.getAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id); - - if (processor == null) { - Class processorClass = PROCESSOR_CLASSES.get(processorId); - if (processorClass != null) { - processor = TypeDefinition.getInstance(processorClass).newInstance(); - } - if (processor != null) { - request.setAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id, processor); - } - } - - return processor; - } - - private static String getProcessorId(Class processorClass) { - String hashId = StringUtils.hex(StringUtils.md5(processorClass.getName())); - PROCESSOR_CLASSES.putIfAbsent(hashId, processorClass); - return hashId; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/old/FormTag.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/old/FormTag.java deleted file mode 100755 index b473a60..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/old/FormTag.java +++ /dev/null @@ -1,300 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.DynamicAttributes; -import javax.servlet.jsp.tagext.TagSupport; - -@SuppressWarnings("serial") -public class FormTag extends TagSupport implements DynamicAttributes { - - private static final String PARAMETER_PREFIX = "_f."; - public static final String ID_PARAMETER = PARAMETER_PREFIX + "id"; - - private static final String ATTRIBUTE_PREFIX = FormTag.class.getName() + "."; - private static final String PROCESSOR_ATTRIBUTE_PREFIX = ATTRIBUTE_PREFIX + "processor/"; - - /** Map of the MD5 hash of a processor class name to the Class object itself. */ - private static final ConcurrentHashMap> PROCESSOR_CLASSES = - new ConcurrentHashMap>(); - - private String method; - private Class processorClass; - - private String varProcessor; - private String varSuccess; - private String varError; - private String varResult; - - private transient Boolean success; - private transient Object result; - private transient Object error; - - private final Map attributes = new LinkedHashMap(); - - /** - * Sets the form submission method. - * - * @param method Can't be {@code null}. - */ - public void setMethod(String method) { - ErrorUtils.errorIfNull(method, "method"); - - this.method = method; - } - - /** - * Sets the name of the processor class. - * - * @param processor The class name must be valid, and the class must - * implement {@link FormProcessor}. - */ - @SuppressWarnings("unchecked") - public void setProcessor(String processor) { - Class pc = ObjectUtils.getClassByName(processor); - - ErrorUtils.errorIf(pc == null, processor, "isn't a valid class name!"); - ErrorUtils.errorIf(!FormProcessor.class.isAssignableFrom(pc), pc.getName(), "doesn't implement [" + FormProcessor.class.getName() + "]!"); - - this.processorClass = (Class) pc; - } - - public Class getProcessorClass() { - return this.processorClass; - } - - /** - * Sets the name of the page-scoped variable to store the processor - * instance. - */ - public void setVarProcessor(String varProcessor) { - this.varProcessor = varProcessor; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * success flag. - */ - public void setVarSuccess(String varSuccess) { - this.varSuccess = varSuccess; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * error. - */ - public void setVarError(String varError) { - this.varError = varError; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * result. - * - * @return May be {@code null}. - */ - public void setVarResult(String varResult) { - this.varResult = varResult; - } - - /** Returns a unique identifier for this form. */ - public String getFormId() { - return Static.getProcessorId(processorClass) + (getId() != null ? ("/" + getId()) : ""); - } - - /** Returns the processor for this form. */ - public FormProcessor getProcessorInstance() { - return Static.getProcessorById(getFormId(), (HttpServletRequest) pageContext.getRequest()); - } - - // --- Getters for the transient variables --- - - /** - * Return true if this form was processed successfully, or false if not. - * Null is returned if this method is called outside the context of this - * form's start and end tags. - * - * @return - */ - public Boolean isSuccess() { - return success; - } - - /** - * Returns the result of processing this form, or null if there was an error - * or this method is called outside the context of this form's start and - * end tags. - * - * @return - */ - public Object getResult() { - return result; - } - - /** - * Returns the error generated attempting to process this form, or null if - * if the form was processed successfully or this method is called outside - * the context of this form's start and end tags. - * - * @return - */ - public Object getError() { - return error; - } - - // --- TagSupport support --- - - @Override - public int doStartTag() throws JspException { - - HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); - - String formId = getFormId(); - FormProcessor processor = getProcessorInstance(); - - if (!ObjectUtils.isBlank(varProcessor)) { - pageContext.setAttribute(varProcessor, processor); - } - - // Write the FORM start tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("form", - "id", getId(), - "method", method.toLowerCase(), - "action", "", - attributes); - writer.writeTag("input", - "type", "hidden", - "name", ID_PARAMETER, - "value", formId); - - - // If process() was already called by FormFilter - String bufferedOutput = FormFilter.Static.getBufferedOutput(formId, request); - if (bufferedOutput != null) { - writer.write(bufferedOutput); - - success = FormFilter.Static.isFormSuccess(request); - result = FormFilter.Static.getFormResult(request); - error = FormFilter.Static.getFormError(request); - - } else { - // process it - try { - result = processor.process(request, new HttpServletResponseWrapper((HttpServletResponse) pageContext.getResponse()) { - private PrintWriter writer; { - writer = new PrintWriter(pageContext.getOut()); - } - @Override - public PrintWriter getWriter() { - return writer; - } - }); - success = true; - - } catch (IOException e) { - throw e; - - } catch (Throwable e) { - error = e; - success = false; - } - } - - // Set the status vars if they are defined - if (!ObjectUtils.isBlank(varSuccess)) { - pageContext.setAttribute(varSuccess, isSuccess()); - } - if (!ObjectUtils.isBlank(varResult)) { - pageContext.setAttribute(varResult, getResult()); - } - if (!ObjectUtils.isBlank(varError)) { - pageContext.setAttribute(varError, getError()); - } - - } catch (IOException error) { - throw new JspException(error); - } - - return EVAL_BODY_INCLUDE; - } - - @Override - public int doEndTag() throws JspException { - // Write the FORM end tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("/form"); - - } catch (IOException error) { - throw new JspException(error); - - } finally { - // null out the transient variables - success = null; - error = null; - result = null; - } - - return EVAL_PAGE; - } - - // --- DynamicAttribute support --- - - @Override - public void setDynamicAttribute(String uri, String localName, Object value) { - attributes.put(localName, value != null ? value.toString() : null); - } - - public static final class Static { - - public static FormProcessor getProcessorById(String id, HttpServletRequest request) { - if (id == null) { - return null; - } - - // Strip off the form ID attribute part of the ID if it exists. - String processorId; - int slashAt = id.indexOf('/'); - if (slashAt < 0) { - processorId = id; - - } else { - processorId = id.substring(0, slashAt); - } - - FormProcessor processor = (FormProcessor) request.getAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id); - - if (processor == null) { - Class processorClass = PROCESSOR_CLASSES.get(processorId); - if (processorClass != null) { - processor = TypeDefinition.getInstance(processorClass).newInstance(); - } - if (processor != null) { - request.setAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id, processor); - } - } - - return processor; - } - - private static String getProcessorId(Class processorClass) { - String hashId = StringUtils.hex(StringUtils.md5(processorClass.getName())); - PROCESSOR_CLASSES.putIfAbsent(hashId, processorClass); - return hashId; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/pair.info deleted file mode 100755 index 5aad6ab..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52416/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:52416 -comSha:c568ff5daf72cc9ff0bdd67a12abc384e52e4bb9 -parentComSha:c6f2e2ca6efb081bb1448cd0728297174ae643a0 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/FormTag.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/FormTag.java -StartLineNum:172 -EndLineNum:172 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/comMsg.txt deleted file mode 100755 index 05ba6ac..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'master' of https://github.com/tpltnt/nodebox into tpltnt-master \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/diff.diff deleted file mode 100755 index c5a42f8..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/nodebox/client/NodeBoxDocument.java b/src/main/java/nodebox/client/NodeBoxDocument.java -index 5c0c4150..f0b1e844 100644 ---- a/src/main/java/nodebox/client/NodeBoxDocument.java -+++ b/src/main/java/nodebox/client/NodeBoxDocument.java -@@ -29,2 +29 @@ import java.io.StringWriter; --import java.util.ArrayList; --import java.util.HashMap; -+import java.util.*; -@@ -32 +30,0 @@ import java.util.List; --import java.util.Map; -@@ -1522 +1520 @@ public class NodeBoxDocument extends JFrame implements WindowListener, HandleDel -- if (file.getName().toLowerCase().endsWith(".pdf")) -+ if (file.getName().toLowerCase(Locale.US).endsWith(".pdf")) \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/new/NodeBoxDocument.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/new/NodeBoxDocument.java deleted file mode 100755 index f0b1e84..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/new/NodeBoxDocument.java +++ /dev/null @@ -1,1931 +0,0 @@ -package nodebox.client; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import nodebox.client.devicehandler.DeviceHandler; -import nodebox.client.devicehandler.DeviceHandlerFactory; -import nodebox.function.Function; -import nodebox.function.FunctionRepository; -import nodebox.handle.Handle; -import nodebox.handle.HandleDelegate; -import nodebox.movie.Movie; -import nodebox.movie.VideoFormat; -import nodebox.node.*; -import nodebox.node.MenuItem; -import nodebox.ui.*; -import nodebox.util.FileUtils; -import nodebox.util.LoadException; - -import javax.imageio.ImageIO; -import javax.swing.*; -import javax.swing.undo.UndoManager; -import java.awt.*; -import java.awt.event.*; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.util.*; -import java.util.List; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static com.google.common.base.Preconditions.*; - -/** - * A NodeBoxDocument manages a NodeLibrary. - */ -public class NodeBoxDocument extends JFrame implements WindowListener, HandleDelegate { - - private static final Logger LOG = Logger.getLogger(NodeBoxDocument.class.getName()); - private static final String WINDOW_MODIFIED = "windowModified"; - public static String lastFilePath; - public static String lastExportPath; - private static NodeClipboard nodeClipboard; - private static Image APPLICATION_ICON_IMAGE; - - static { - try { - APPLICATION_ICON_IMAGE = ImageIO.read(NodeBoxDocument.class.getResourceAsStream("/application-logo.png")); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - // State - private final NodeLibraryController controller; - // Rendering - private final AtomicBoolean isRendering = new AtomicBoolean(false); - private final AtomicBoolean shouldRender = new AtomicBoolean(false); - // GUI components - private final NodeBoxMenuBar menuBar; - private final AnimationBar animationBar; - private final AddressBar addressBar; - private final ViewerPane viewerPane; - private final DataSheet dataSheet; - private final PortView portView; - private final NetworkPane networkPane; - private final NetworkView networkView; - private final ProgressPanel progressPanel; - private File documentFile; - private boolean documentChanged; - private boolean needsResave; - private AnimationTimer animationTimer; - private boolean loaded = false; - private UndoManager undoManager = new UndoManager(); - private boolean holdEdits = false; - private String lastEditType = null; - private String lastEditObjectId = null; - private FunctionRepository functionRepository; - private String activeNetworkPath = ""; - private String activeNodeName = ""; - private boolean restoring = false; - private boolean invalidateFunctionRepository = false; - private double frame = 1; - private Map networkPanZoomValues = new HashMap(); - private SwingWorker, Node> currentRender = null; - private Iterable lastRenderResult = null; - private Map> renderResults = ImmutableMap.of(); - private JSplitPane parameterNetworkSplit; - private JSplitPane topSplit; - private FullScreenFrame fullScreenFrame = null; - private List zoomListeners = new ArrayList(); - private List deviceHandlers = new ArrayList(); - private DevicesDialog devicesDialog; - - public NodeBoxDocument() { - this(createNewLibrary()); - } - - public NodeBoxDocument(NodeLibrary nodeLibrary) { - if (!nodeLibrary.hasProperty("canvasX")) - nodeLibrary = nodeLibrary.withProperty("canvasX", "0"); - if (!nodeLibrary.hasProperty("canvasY")) - nodeLibrary = nodeLibrary.withProperty("canvasY", "0"); - if (!nodeLibrary.hasProperty("canvasWidth")) - nodeLibrary = nodeLibrary.withProperty("canvasWidth", "1000"); - if (!nodeLibrary.hasProperty("canvasHeight")) - nodeLibrary = nodeLibrary.withProperty("canvasHeight", "1000"); - - controller = NodeLibraryController.withLibrary(nodeLibrary); - invalidateFunctionRepository = true; - JPanel rootPanel = new JPanel(new BorderLayout()); - this.viewerPane = new ViewerPane(this); - viewerPane.getViewer().setCanvasBounds(getCanvasBounds()); - dataSheet = viewerPane.getDataSheet(); - PortPane portPane = new PortPane(this); - portView = portPane.getPortView(); - networkPane = new NetworkPane(this); - networkView = networkPane.getNetworkView(); - parameterNetworkSplit = new CustomSplitPane(JSplitPane.VERTICAL_SPLIT, portPane, networkPane); - topSplit = new CustomSplitPane(JSplitPane.HORIZONTAL_SPLIT, viewerPane, parameterNetworkSplit); - - addressBar = new AddressBar(); - addressBar.setOnSegmentClickListener(new AddressBar.OnSegmentClickListener() { - public void onSegmentClicked(String fullPath) { - setActiveNetwork(fullPath); - } - }); - progressPanel = new ProgressPanel(this); - JPanel addressPanel = new JPanel(new BorderLayout()); - addressPanel.add(addressBar, BorderLayout.CENTER); - addressPanel.add(progressPanel, BorderLayout.EAST); - - rootPanel.add(addressPanel, BorderLayout.NORTH); - rootPanel.add(topSplit, BorderLayout.CENTER); - - // Animation properties. - animationTimer = new AnimationTimer(this); - animationBar = new AnimationBar(this); - rootPanel.add(animationBar, BorderLayout.SOUTH); - - // Zoom in / out shortcuts. - KeyStroke zoomInStroke1 = KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_MASK); - KeyStroke zoomInStroke2 = KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); - KeyStroke zoomInStroke3 = KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); - ActionListener zoomInHandler = new ZoomInHandler(); - getRootPane().registerKeyboardAction(zoomInHandler, zoomInStroke1, JComponent.WHEN_IN_FOCUSED_WINDOW); - getRootPane().registerKeyboardAction(zoomInHandler, zoomInStroke2, JComponent.WHEN_IN_FOCUSED_WINDOW); - getRootPane().registerKeyboardAction(zoomInHandler, zoomInStroke3, JComponent.WHEN_IN_FOCUSED_WINDOW); - KeyStroke zoomOutStroke = KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); - getRootPane().registerKeyboardAction(new ZoomOutHandler(), zoomOutStroke, JComponent.WHEN_IN_FOCUSED_WINDOW); - - setContentPane(rootPanel); - setLocationByPlatform(true); - setSize(1100, 800); - setIconImage(APPLICATION_ICON_IMAGE); - setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - addWindowListener(this); - updateTitle(); - menuBar = new NodeBoxMenuBar(this); - setJMenuBar(menuBar); - loaded = true; - - if (Application.ENABLE_DEVICE_SUPPORT) { - for (Device device : getNodeLibrary().getDevices()) { - DeviceHandler handler = DeviceHandlerFactory.createDeviceHandler(device); - if (handler != null) - deviceHandlers.add(handler); - } - devicesDialog = new DevicesDialog(this); -// addressBar.setMessage("OSC Port " + getOSCPort()); - } - } - - public static NodeBoxDocument getCurrentDocument() { - return Application.getInstance().getCurrentDocument(); - } - - /** - * Static factory method to create a NodeBoxDocument from a file. - *

- * This method can handle file upgrades. - * - * @param file the file to load. - * @return A NodeBoxDocument. - */ - public static NodeBoxDocument load(File file) { - NodeLibrary library; - NodeBoxDocument document; - try { - library = NodeLibrary.load(file, Application.getInstance().getSystemRepository()); - document = new NodeBoxDocument(library); - document.setDocumentFile(file); - } catch (OutdatedLibraryException e) { - UpgradeResult result = NodeLibraryUpgrades.upgrade(file); - // The file is used here as the base name for finding relative libraries. - library = result.getLibrary(file, Application.getInstance().getSystemRepository()); - document = new NodeBoxDocument(library); - document.setDocumentFile(file); - document.showUpgradeResult(result); - } catch (LoadException e) { - throw new RuntimeException("Could not load " + file, e); - } - lastFilePath = file.getParentFile().getAbsolutePath(); - return document; - } - - private static NodeLibrary createNewLibrary() { - NodeRepository nodeRepository = Application.getInstance().getSystemRepository(); - Node root = Node.NETWORK.withName("root"); - Node rectPrototype = nodeRepository.getNode("corevector.rect"); - String name = root.uniqueName(rectPrototype.getName()); - Node rect1 = rectPrototype.extend().withName(name).withPosition(new nodebox.graphics.Point(1, 1)); - root = root - .withChildAdded(rect1) - .withRenderedChild(rect1); - return NodeLibrary.create("untitled", root, nodeRepository, FunctionRepository.of()); - } - - /** - * Display the result of upgrading in a dialog box. - * - * @param result The UpgradeResult. - */ - private void showUpgradeResult(UpgradeResult result) { - checkNotNull(result); - if (result.getWarnings().isEmpty()) return; - final UpgradeWarningsDialog dialog = new UpgradeWarningsDialog(result); - dialog.setLocationRelativeTo(this); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - dialog.setVisible(true); - } - }); - } - - public List getDeviceHandlers() { - return ImmutableList.copyOf(deviceHandlers); - } - - //// Node Library management //// - - public NodeLibrary getNodeLibrary() { - return controller.getNodeLibrary(); - } - - public NodeRepository getNodeRepository() { - return Application.getInstance().getSystemRepository(); - } - - public FunctionRepository getFunctionRepository() { - if (invalidateFunctionRepository) { - functionRepository = FunctionRepository.combine(getNodeRepository().getFunctionRepository(), getNodeLibrary().getFunctionRepository()); - invalidateFunctionRepository = false; - } - return functionRepository; - } - - /** - * Restore the node library to a different undo state. - * - * @param nodeLibrary The node library to restore. - * @param networkPath The active network path. - * @param nodeName The active node name. Can be an empty string. - */ - public void restoreState(NodeLibrary nodeLibrary, String networkPath, String nodeName) { - controller.setNodeLibrary(nodeLibrary); - invalidateFunctionRepository = true; - restoring = true; - setActiveNetwork(networkPath); - setActiveNode(nodeName); - restoring = false; - } - - //// Node operations //// - - /** - * Create a node in the active network. - * This node is based on a prototype. - * - * @param prototype The prototype node. - * @param pt The initial node position. - */ - public void createNode(Node prototype, nodebox.graphics.Point pt) { - startEdits("Create Node"); - Node newNode = controller.createNode(activeNetworkPath, prototype); - String newNodePath = Node.path(activeNetworkPath, newNode); - controller.setNodePosition(newNodePath, pt); - controller.setRenderedChild(activeNetworkPath, newNode.getName()); - setActiveNode(newNode); - stopEdits(); - - Node activeNode = getActiveNode(); - networkView.updateNodes(); - networkView.singleSelect(activeNode); - portView.updateAll(); - - requestRender(); - } - - /** - * Change the node position of the given node. - * - * @param node The node to move. - * @param point The point to move to. - */ - public void setNodePosition(Node node, nodebox.graphics.Point point) { - checkNotNull(node); - checkNotNull(point); - checkArgument(getActiveNetwork().hasChild(node)); - // Note that we're passing in the parent network of the node. - // This means that all move changes to the parent network are grouped - // together under one edit, instead of for each node individually. - addEdit("Move Node", "moveNode", getActiveNetworkPath()); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodePosition(nodePath, point); - - networkView.updatePosition(node); - } - - /** - * Change the node name. - * - * @param node The node to rename. - * @param name The new node name. - */ - public void setNodeName(Node node, String name) { - checkNotNull(node); - checkNotNull(name); - controller.renameNode(activeNetworkPath, node.getName(), name); - - String nodePath = Node.path(activeNetworkPath, node.getName()); - if (networkPanZoomValues.containsKey(nodePath)) { - String newNodePath = Node.path(activeNetworkPath, name); - for (String key : ImmutableList.copyOf(networkPanZoomValues.keySet())) { - if (key.equals(nodePath) || key.startsWith(nodePath + "/")) { - String newKey = key.replace(nodePath, newNodePath); - networkPanZoomValues.put(newKey, networkPanZoomValues.get(key)); - } - } - } - - setActiveNode(name); - networkView.updateNodes(); - networkView.singleSelect(getActiveNode()); - requestRender(); - } - - /** - * Change the comment for the node. - * - * @param node The node to be commented. - * @param comment The new comment. - */ - public void setNodeComment(Node node, String comment) { - checkNotNull(node); - checkNotNull(comment); - addEdit("Set Node Comment"); - controller.commentNode(activeNetworkPath, node.getName(), comment.trim()); - } - - /** - * Change the category for the node. - * - * @param node The node to change. - * @param category The new category. - */ - public void setNodeCategory(Node node, String category) { - checkNotNull(node); - checkNotNull(category); - addEdit("Set Node Category"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeCategory(nodePath, category); - } - - /** - * Change the description for the node. - * - * @param node The node to change. - * @param description The new description. - */ - public void setNodeDescription(Node node, String description) { - checkNotNull(node); - checkNotNull(description); - addEdit("Set Node Description"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeDescription(nodePath, description); - } - - /** - * Change the node image icon. - * - * @param node The node to change. - * @param image The new image icon. - */ - public void setNodeImage(Node node, String image) { - checkNotNull(node); - checkNotNull(image); - addEdit("Set Node Image"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeImage(nodePath, image); - networkView.updateNodes(); - } - - /** - * Change the output type for the node. - * - * @param node The node to change. - * @param outputType The new output type. - */ - public void setNodeOutputType(Node node, String outputType) { - checkNotNull(node); - checkNotNull(outputType); - addEdit("Set Output Type"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeOutputType(nodePath, outputType); - networkView.updateNodes(); - } - - /** - * Change the output range for the node. - * - * @param node The node to change. - * @param outputRange The new output range. - */ - public void setNodeOutputRange(Node node, Port.Range outputRange) { - checkNotNull(node); - addEdit("Change Node Output Range"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeOutputRange(nodePath, outputRange); - requestRender(); - } - - /** - * Change the node function. - * - * @param node The node to change. - * @param function The new function. - */ - public void setNodeFunction(Node node, String function) { - checkNotNull(node); - checkNotNull(function); - addEdit("Set Node Function"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeFunction(nodePath, function); - networkView.updateNodes(); - requestRender(); - } - - /** - * Change the node handle function. - * - * @param node The node to change. - * @param handle The new handle function. - */ - public void setNodeHandle(Node node, String handle) { - checkNotNull(node); - checkNotNull(handle); - addEdit("Set Node Handle"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeHandle(nodePath, handle); - createHandleForActiveNode(); - networkView.updateNodes(); - requestRender(); - } - - /** - * Set the node metadata to the given metadata. - * Note that this method is not called when the node position or name changes. - * - * @param node The node to change. - * @param metadata A map of metadata. - */ - public void setNodeMetadata(Node node, Object metadata) { - // TODO: Implement - // TODO: Make NodeAttributesEditor use this. - // Metadata changes could mean the icon has changed. - networkView.updateNodes(); - if (node == getActiveNode()) { - portView.updateAll(); - // Updating the metadata could cause changes to a handle. - viewerPane.repaint(); - dataSheet.repaint(); - } - requestRender(); - } - - public void setNodeExported(Node node, boolean exported) { - throw new UnsupportedOperationException("Not implemented yet."); - //addEdit("Set Exported"); - } - - /** - * Remove the given node from the active network. - * - * @param node The node to remove. - */ - public void removeNode(Node node) { - addEdit("Remove Node"); - removeNodeImpl(node); - networkView.updateAll(); - requestRender(); - } - - /** - * Remove the given nodes from the active network. - * - * @param nodes The node to remove. - */ - public void removeNodes(Iterable nodes) { - addEdit("Delete Nodes"); - for (Node node : nodes) { - removeNodeImpl(node); - } - networkView.updateAll(); - portView.updateAll(); - requestRender(); - } - - /** - * Helper method used by removeNode and removeNodes to do the removal and update the port view, if needed. - * - * @param node The node to remove. - */ - private void removeNodeImpl(Node node) { - checkNotNull(node, "Node to remove cannot be null."); - checkArgument(getActiveNetwork().hasChild(node), "Node to remove is not in active network."); - controller.removeNode(activeNetworkPath, node.getName()); - - // If the removed node was the active one, reset the port view. - if (node == getActiveNode()) { - setActiveNode((Node) null); - } - } - - /** - * Create a connection from the given output to the given input. - * - * @param outputNode The output node. - * @param inputNode The input node. - * @param inputPort The input port. - */ - public void connect(String outputNode, String inputNode, String inputPort) { - addEdit("Connect"); - controller.connect(activeNetworkPath, outputNode, inputNode, inputPort); - - portView.updateAll(); - viewerPane.updateHandle(); - requestRender(); - } - - /** - * Remove the given connection from the network. - * - * @param connection the connection to remove - */ - public void disconnect(Connection connection) { - addEdit("Disconnect"); - controller.disconnect(activeNetworkPath, connection); - - portView.updateAll(); - networkView.updateConnections(); - viewerPane.updateHandle(); - requestRender(); - } - - public void publish(String inputNode, String inputPort, String publishedName) { - addEdit("Publish"); - controller.publish(activeNetworkPath, inputNode, inputPort, publishedName); - } - - public void unpublish(String publishedName) { - addEdit("Unpublish"); - controller.unpublish(activeNetworkPath, publishedName); - } - - /** - * @param node the node on which to add the port - * @param portName the name of the new port - * @param portType the type of the new port - */ - public void addPort(Node node, String portName, String portType) { - checkArgument(getActiveNetwork().hasChild(node)); - addEdit("Add Port"); - controller.addPort(Node.path(activeNetworkPath, node), portName, portType); - portView.updateAll(); - networkView.updateAll(); - } - - /** - * Remove the port from the node. - * - * @param node The node on which to remove the port. - * @param portName The name of the port - */ - public void removePort(Node node, String portName) { - checkArgument(getActiveNetwork().hasChild(node)); - addEdit("Remove Port"); - controller.removePort(activeNetworkPath, node.getName(), portName); - - if (node == getActiveNode()) { - portView.updateAll(); - viewerPane.repaint(); - dataSheet.repaint(); - } - } - - /** - * Change the label for the given port - * - * @param portName The name of the port to change. - * @param label The new label. - */ - public void setPortLabel(String portName, String label) { - checkValidPort(portName); - addEdit("Change Label"); - controller.setPortLabel(getActiveNodePath(), portName, label); - portView.updateAll(); - requestRender(); - } - - /** - * Change the description for the given port - * - * @param portName The name of the port to change. - * @param description The new description. - */ - public void setPortDescription(String portName, String description) { - checkValidPort(portName); - addEdit("Change Description"); - controller.setPortDescription(getActiveNodePath(), portName, description); - portView.updateAll(); - requestRender(); - } - - /** - * Change the widget for the given port - * - * @param portName The name of the port to change. - * @param widget The new widget. - */ - public void setPortWidget(String portName, Port.Widget widget) { - checkValidPort(portName); - addEdit("Change Widget"); - controller.setPortWidget(getActiveNodePath(), portName, widget); - portView.updateAll(); - requestRender(); - } - - /** - * Change the port range of the given port - * - * @param portName The name of the port to change. - * @param range The new port range. - */ - public void setPortRange(String portName, Port.Range range) { - checkValidPort(portName); - addEdit("Change Port Range"); - controller.setPortRange(getActiveNodePath(), portName, range); - requestRender(); - } - - /** - * Change the minimum value for the given port - * - * @param portName The name of the port to change. - * @param minimumValue The new minimum value. - */ - public void setPortMinimumValue(String portName, Double minimumValue) { - checkValidPort(portName); - addEdit("Change Minimum Value"); - controller.setPortMinimumValue(getActiveNodePath(), portName, minimumValue); - portView.updateAll(); - requestRender(); - } - - /** - * Change the maximum value for the given port - * - * @param portName The name of the port to change. - * @param maximumValue The new maximum value. - */ - public void setPortMaximumValue(String portName, Double maximumValue) { - checkValidPort(portName); - addEdit("Change Maximum Value"); - controller.setPortMaximumValue(getActiveNodePath(), portName, maximumValue); - portView.updateAll(); - requestRender(); - } - - /** - * Add a new menu item for the given port's menu. - * - * @param portName The name of the port to add a new menu item for. - * @param key The key of the new menu item. - * @param label The label of the new menu item. - */ - public void addPortMenuItem(String portName, String key, String label) { - checkValidPort(portName); - addEdit("Add Port Menu Item"); - - controller.addPortMenuItem(getActiveNodePath(), portName, key, label); - - portView.updateAll(); - requestRender(); - } - - /** - * Remove a menu item from the given port's menu. - * - * @param portName The name of the port to remove the menu item from. - * @param item The menu item to remove - */ - public void removePortMenuItem(String portName, MenuItem item) { - checkValidPort(portName); - addEdit("Remove Parameter Menu Item"); - - controller.removePortMenuItem(getActiveNodePath(), portName, item); - - Node n = getActiveNode(); - portView.updateAll(); - requestRender(); - } - - /** - * Move a menu item down from the given port's menu. - * - * @param portName The name of the port of which to update the menu. - * @param itemIndex The index of the menu item to move down. - */ - public void movePortMenuItemDown(String portName, int itemIndex) { - checkValidPort(portName); - addEdit("Move Port Item Down"); - controller.movePortMenuItemDown(getActiveNodePath(), portName, itemIndex); - portView.updateAll(); - } - - /** - * Move a menu item up from the given port's menu. - * - * @param portName The name of the port of which to update the menu. - * @param itemIndex The index of the menu item to move up. - */ - public void movePortMenuItemUp(String portName, int itemIndex) { - checkValidPort(portName); - addEdit("Move Port Item Up"); - controller.movePortMenuItemUp(getActiveNodePath(), portName, itemIndex); - portView.updateAll(); - } - - /** - * Change a menu item's key and label in the given port's menu. - * - * @param portName The name of the port of which to update the menu. - * @param itemIndex The index of the menu item to change. - * @param key The new key of the menu item. - * @param label The new label of the menu item. - */ - public void updatePortMenuItem(String portName, int itemIndex, String key, String label) { - checkValidPort(portName); - addEdit("Update Port Menu Item"); - controller.updatePortMenuItem(getActiveNodePath(), portName, itemIndex, key, label); - portView.updateAll(); - } - - public Object getValue(String portName) { - if (getActiveNode() == null) { - return null; - } - Port port = checkValidPort(portName); - return port.getValue(); - } - - /** - * Set the port with the given node path to a new value. - * - * @param nodePath The path inside the network of the node the port belongs to. - * @param portName The name of the port. - * @param value The new value. - */ - public void setValue(String nodePath, String portName, Object value) { - checkNotNull(getNodeLibrary().getNodeForPath(nodePath)); - addEdit("Change Value", "changeValue", nodePath + "#" + portName); - - controller.setPortValue(nodePath, portName, value); - - // TODO set variables on the root port. -// if (port.getNode() == nodeLibrary.getRoot()) { -// nodeLibrary.setVariable(port.getName(), port.asString()); -// } - - portView.updatePortValue(portName, value); - // Setting a port might change enable expressions, and thus change the enabled state of a port row. - portView.updateEnabledState(); - // Setting a port might change the enabled state of the handle. - // viewer.setHandleEnabled(activeNode != null && activeNode.hasEnabledHandle()); - requestRender(); - } - - public void revertPortToDefault(String portName) { - Port port = checkValidPort(portName); - addEdit("Revert Port to Default"); - controller.revertToDefaultPortValue(getActiveNodePath(), portName); - portView.updateAll(); - portView.updateEnabledState(); - requestRender(); - } - - public void addDevice(String deviceType, String deviceName) { - // todo: undo / redo - Device device = controller.addDevice(deviceType, deviceName); - DeviceHandler handler = DeviceHandlerFactory.createDeviceHandler(device); - if (handler != null) - deviceHandlers.add(handler); - } - - public void removeDevice(String deviceName) { - // todo: undo / redo - for (DeviceHandler handler : getDeviceHandlers()) { - if (handler.getName().equals(deviceName)) { - handler.stop(); - deviceHandlers.remove(handler); - controller.removeDevice(deviceName); - } - } - } - - public void startDeviceHandlers() { - if (Application.ENABLE_DEVICE_SUPPORT) { - for (DeviceHandler handler : deviceHandlers) { - if (handler.isSyncedWithTimeline()) { - handler.resume(); - } - } - if (devicesDialog.isVisible()) - devicesDialog.rebuildInterface(); - } - } - - public void stopDeviceHandlers(boolean pause) { - if (Application.ENABLE_DEVICE_SUPPORT) { - for (DeviceHandler handler : deviceHandlers) { - if (handler.isSyncedWithTimeline()) { - if (pause) { - handler.pause(); - } else { - handler.stop(); - } - } - } - if (devicesDialog.isVisible()) - devicesDialog.rebuildInterface(); - } - } - - public void setDeviceProperty(String deviceName, String propertyName, String propertyValue) { - checkNotNull(deviceName, "Device name cannot be null."); - checkArgument(getNodeLibrary().hasDevice(deviceName)); - addEdit("Change Device Property"); - controller.setDeviceProperty(deviceName, propertyName, propertyValue); - } - - public void setPortMetadata(Port port, String key, String value) { - addEdit("Change Port Metadata"); - throw new UnsupportedOperationException("Not implemented yet."); - } - - private Port checkValidPort(String portName) { - checkNotNull(portName, "Port cannot be null."); - Port port = getActiveNode().getInput(portName); - checkArgument(port != null, "Port %s does not exist on node %s", portName, getActiveNode()); - return port; - } - - public void editMetadata() { - if (getActiveNode() == null) return; - JDialog editorDialog = new NodeAttributesDialog(NodeBoxDocument.this); - editorDialog.setSize(580, 751); - editorDialog.setLocationRelativeTo(NodeBoxDocument.this); - editorDialog.setVisible(true); - } - - //// Port pane callbacks //// - - public void takeScreenshot(File outputFile) { - Container c = getContentPane(); - BufferedImage img = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_RGB); - Graphics2D g2 = img.createGraphics(); - c.paint(g2); - try { - ImageIO.write(img, "png", outputFile); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - //// Screen shot //// - - public void silentSet(String portName, Object value) { - try { - setValue(getActiveNodePath(), portName, value); - } catch (Exception ignored) { - } - } - - //// HandleDelegate implementation //// - - public void stopEditing() { - stopCombiningEdits(); - } - - // TODO Merge stopEditing and stopCombiningEdits. - - public void updateHandle() { - if (viewerPane.getHandle() != null) - viewerPane.getHandle().update(); - // TODO Make viewer repaint more fine-grained. - viewerPane.repaint(); - } - - /** - * Return the network that is currently "open": shown in the network view. - * - * @return The currently active network. - */ - public Node getActiveNetwork() { - // TODO This might be a potential bottleneck. - return getNodeLibrary().getNodeForPath(activeNetworkPath); - } - - //// Active network / node //// - - public void setActiveNetwork(String path) { - checkNotNull(path); - activeNetworkPath = path; - Node network = getNodeLibrary().getNodeForPath(path); - - if (!restoring) { - if (network.getRenderedChild() != null) { - setActiveNode(network.getRenderedChildName()); - } else if (!network.isEmpty()) { - // Set the active node to the first child. - setActiveNode(network.getChildren().iterator().next()); - } else { - setActiveNode((Node) null); - } - } - - addressBar.setPath(activeNetworkPath); - //viewer.setHandleEnabled(activeNode != null && activeNode.hasEnabledHandle()); - networkView.updateNodes(); - if (networkPanZoomValues.containsKey(activeNetworkPath)) { - double[] pz = networkPanZoomValues.get(activeNetworkPath); - networkView.setViewTransform(pz[0], pz[1], pz[2]); - } else if (!restoring) - networkView.resetViewTransform(); - if (!restoring) - networkView.singleSelect(getActiveNode()); - viewerPane.repaint(); - dataSheet.repaint(); - - requestRender(); - } - - public String getActiveNetworkPath() { - return activeNetworkPath; - } - - private Node getRenderedNode() { - if (viewerPane.shouldAlwaysRenderRoot()) return getNodeLibrary().getRoot(); - return getActiveNetwork(); - } - - /** - * Change the rendered node to the given node - * - * @param node the node to set rendered - */ - public void setRenderedNode(Node node) { - checkNotNull(node); - checkArgument(getActiveNetwork().hasChild(node)); - addEdit("Set Rendered"); - controller.setRenderedChild(activeNetworkPath, node.getName()); - - networkView.updateNodes(); - networkView.singleSelect(node); - requestRender(); - } - - /** - * Set the active network to the parent network. - */ - public void goUp() { - throw new UnsupportedOperationException("Not implemented yet."); - } - - /** - * Return the node that is currently focused: - * visible in the port view, and whose handles are displayed in the viewer. - * - * @return The active node. Can be null. - */ - public Node getActiveNode() { - if (activeNodeName.isEmpty()) { - return getActiveNetwork(); - } else { - return getNodeLibrary().getNodeForPath(getActiveNodePath()); - } - } - - public void setActiveNode(String nodeName) { - if (!restoring && getActiveNodeName().equals(nodeName)) return; - stopCombiningEdits(); - if (nodeName.isEmpty()) { - activeNodeName = ""; - } else { - checkArgument(getActiveNetwork().hasChild(nodeName)); - activeNodeName = nodeName; - } - - Node n = getActiveNode(); - createHandleForActiveNode(); - //editorPane.setActiveNode(activeNode); - // TODO If we draw handles again, we should repaint the viewer pane. - //viewerPane.repaint(); // For the handle - portView.updateAll(); - restoring = false; - networkView.singleSelect(n); - } - - /** - * Set the active node to the given node. - *

- * The active node is the one whose parameters are displayed in the port pane, - * and whose handle is displayed in the viewer. - *

- * This will also change the active network if necessary. - * - * @param node the node to change to. - */ - public void setActiveNode(Node node) { - setActiveNode(node != null ? node.getName() : ""); - } - - public String getActiveNodePath() { - return Node.path(activeNetworkPath, activeNodeName); - } - - public String getActiveNodeName() { - return activeNodeName; - } - - private void createHandleForActiveNode() { - Node activeNode = getActiveNode(); - if (activeNode != null) { - Handle handle = null; - - if (getFunctionRepository().hasFunction(activeNode.getHandle())) { - Function handleFunction = getFunctionRepository().getFunction(activeNode.getHandle()); - try { - handle = (Handle) handleFunction.invoke(); - } catch (Exception e) { - LOG.log(Level.WARNING, "Error while creating handle for " + activeNode, e); - } - } - - if (handle != null) { - handle.setHandleDelegate(this); - handle.update(); - viewerPane.setHandle(handle); - } else { - viewerPane.setHandle(null); - } - } - } -// if (activeNode != null) { -// Handle handle = null; -// try { -// handle = activeNode.createHandle(); -// // If the handle was created successfully, remove the messages. -// editorPane.clearMessages(); -// } catch (Exception e) { -// editorPane.setMessages(e.toString()); -// } -// if (handle != null) { -// handle.setHandleDelegate(this); -// // TODO Remove this. Find out why the handle needs access to the viewer (only repaint?) and put that in the HandleDelegate. -// handle.setViewer(viewer); -// viewer.setHandleEnabled(activeNode.hasEnabledHandle()); -// } -// viewer.setHandle(handle); -// } else { -// viewer.setHandle(null); -// } -// } - - // todo: this method feels like it doesn't belong here (maybe rename it?) - public boolean hasInput(String portName) { - Node node = getActiveNode(); - return node.hasInput(portName); - } - - public boolean isConnected(String portName) { - Node network = getActiveNetwork(); - Node node = getActiveNode(); - if (network == null || node == null) return false; - for (Connection c : network.getConnections()) { - if (c.getInputNode().equals(node.getName()) && c.getInputPort().equals(portName)) - return true; - } - return false; - } - - - //// Animation //// - - public double getFrame() { - return frame; - } - - public void setFrame(double frame) { - this.frame = frame; - - animationBar.setFrame(frame); - requestRender(); - } - - public void nextFrame() { - setFrame(getFrame() + 1); - } - - public void toggleAnimation() { - animationBar.toggleAnimation(); - } - - public void doRewind() { - animationBar.rewindAnimation(); - } - - public void playAnimation() { - startDeviceHandlers(); - animationTimer.start(); - } - - public void stopAnimation() { - stopDeviceHandlers(true); - animationTimer.stop(); - } - - public void rewindAnimation() { - stopAnimation(); - stopDeviceHandlers(false); - resetRenderResults(); - setFrame(1); - } - - //// Rendering //// - - /** - * Request a renderNetwork operation. - *

- * This method does a number of checks to see if the renderNetwork goes through. - *

- * The renderer could already be running. - *

- * If all checks pass, a renderNetwork request is made. - */ - public void requestRender() { - // If we're already rendering, request the next renderNetwork. - if (isRendering.compareAndSet(false, true)) { - // If we're not rendering, start rendering. - render(); - } else { - shouldRender.set(true); - } - } - - public void renderFullScreen() { - if (fullScreenFrame != null) - closeFullScreenWindow(); - fullScreenFrame = new FullScreenFrame(this); - fullScreenFrame.setVisible(true); - fullScreenFrame.setOutputValues(lastRenderResult); - } - - public void closeFullScreenWindow() { - if (fullScreenFrame != null) { - fullScreenFrame.setVisible(false); - fullScreenFrame.dispose(); - fullScreenFrame = null; - viewerPane.setOutputValues(lastRenderResult); - } - } - - private Viewer getViewer() { - if (fullScreenFrame != null) - return fullScreenFrame.getViewer(); - else - return viewerPane.getViewer(); - } - - /** - * Ask the document to stop the active rendering. - */ - public synchronized void stopRendering() { - if (currentRender != null) { - currentRender.cancel(true); - } - } - - private void render() { - checkState(SwingUtilities.isEventDispatchThread()); - checkState(currentRender == null); - progressPanel.setInProgress(true); - final NodeLibrary renderLibrary = getNodeLibrary(); - final Node renderNetwork = getRenderedNode(); - - Map dataMap = new HashMap(); - dataMap.put("frame", frame); - dataMap.put("mouse.position", viewerPane.getViewer().getLastMousePosition()); - for (DeviceHandler handler : deviceHandlers) - handler.addData(dataMap); - final ImmutableMap data = ImmutableMap.copyOf(dataMap); - - final NodeContext context = new NodeContext(renderLibrary, getFunctionRepository(), data, renderResults, ImmutableMap.of()); - currentRender = new SwingWorker, Node>() { - @Override - protected List doInBackground() throws Exception { - List results = context.renderNode(renderNetwork); - context.renderAlwaysRenderedNodes(renderNetwork); - renderResults = context.getRenderResults(); - return results; - } - - @Override - protected void done() { - networkPane.clearError(); - isRendering.set(false); - currentRender = null; - List results; - try { - results = get(); - } catch (CancellationException e) { - results = ImmutableList.of(); - } catch (InterruptedException e) { - results = ImmutableList.of(); - } catch (ExecutionException e) { - networkPane.setError(e.getCause()); - results = ImmutableList.of(); - } - - lastRenderResult = results; - - networkView.checkErrorAndRepaint(); - progressPanel.setInProgress(false); - if (fullScreenFrame != null) - fullScreenFrame.setOutputValues(results); - else - viewerPane.setOutputValues(results); - - if (shouldRender.getAndSet(false)) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - requestRender(); - } - }); - } - } - }; - currentRender.execute(); - } - - /** - * Returns the first output value, or null if the map of output values is empty. - * - * @param outputValues The map of output values. - * @return The output value. - */ - private Object firstOutputValue(final Map outputValues) { - if (outputValues.isEmpty()) return null; - return outputValues.values().iterator().next(); - } - - private synchronized void resetRenderResults() { - renderResults = ImmutableMap.of(); - } - - //// Undo //// - - /** - * Edits are no longer recorded until you call stopEdits. This allows you to batch edits. - * - * @param command the command name of the edit batch - */ - public void startEdits(String command) { - addEdit(command); - holdEdits = true; - } - - /** - * Edits are recorded again. - */ - public void stopEdits() { - holdEdits = false; - } - - /** - * Add an edit to the undo manager. - *

- * Since we don't specify the edit type or name, further edits will not be staggered. - * - * @param command the command name. - */ - public void addEdit(String command) { - if (!holdEdits) { - markChanged(); - undoManager.addEdit(new NodeLibraryUndoableEdit(this, command)); - menuBar.updateUndoRedoState(); - stopCombiningEdits(); - } - } - - /** - * Add an edit to the undo manager. - * - * @param command the command name. - * @param type the type of edit - * @param objectId the id for the edited object. This will be compared against. - */ - public void addEdit(String command, String type, String objectId) { - if (!holdEdits) { - markChanged(); - - if (lastEditType != null && lastEditType.equals(type) && lastEditObjectId.equals(objectId)) { - // If the last edit type and last edit id are the same, - // we combine the two edits into one. - // Since we've already saved the last state, we don't need to do anything. - } else { - addEdit(command); - lastEditType = type; - lastEditObjectId = objectId; - } - } - } - - /** - * Normally edits of the same type and object are combined into one. - * Calling this method will ensure that you create a new edit. - *

- * Use this method e.g. for breaking apart overzealous edit grouping. - */ - public void stopCombiningEdits() { - // We just reset the last edit type and object so that addEdit will be forced to create a new edit. - lastEditType = null; - lastEditObjectId = null; - stopEdits(); - } - - public UndoManager getUndoManager() { - return undoManager; - } - - public void undo() { - if (!undoManager.canUndo()) return; - undoManager.undo(); - menuBar.updateUndoRedoState(); - } - - public void redo() { - if (!undoManager.canRedo()) return; - undoManager.redo(); - menuBar.updateUndoRedoState(); - } - - //// Code editor actions //// - - public void fireCodeChanged(Node node, boolean changed) { - networkView.codeChanged(node, changed); - } - - //// Document actions //// - - public File getDocumentFile() { - return documentFile; - } - - public void setDocumentFile(File documentFile) { - this.documentFile = documentFile; - controller.setNodeLibraryFile(documentFile); - updateTitle(); - } - - public boolean isChanged() { - return documentChanged; - } - - public boolean close() { - stopAnimation(); - if (shouldClose()) { - Application.getInstance().removeDocument(this); - for (DeviceHandler handler : deviceHandlers) - handler.stop(); - dispose(); - // On Mac the application does not close if the last window is closed. - if (!Platform.onMac()) { - // If there are no more documents, exit the application. - if (Application.getInstance().getDocumentCount() == 0) { - System.exit(0); - } - } - return true; - } else { - return false; - } - } - - private boolean shouldClose() { - if (isChanged()) { - SaveDialog sd = new SaveDialog(); - int retVal = sd.show(this); - if (retVal == JOptionPane.YES_OPTION) { - return save(); - } else if (retVal == JOptionPane.NO_OPTION) { - return true; - } else if (retVal == JOptionPane.CANCEL_OPTION) { - return false; - } - } - return true; - } - - public boolean save() { - if (documentFile == null || needsResave()) { - return saveAs(); - } else { - boolean saved = saveToFile(documentFile); - if (saved) - NodeBoxMenuBar.addRecentFile(documentFile); - return saved; - } - } - - public boolean saveAs() { - File chosenFile = FileUtils.showSaveDialog(this, lastFilePath, "ndbx", "NodeBox File"); - if (chosenFile != null) { - if (!chosenFile.getAbsolutePath().endsWith(".ndbx")) { - chosenFile = new File(chosenFile.getAbsolutePath() + ".ndbx"); - if (chosenFile.exists()) { - boolean shouldReplace = ReplaceDialog.showForFile(chosenFile); - if (shouldReplace) { - return saveAs(); - } - } - } - lastFilePath = chosenFile.getParentFile().getAbsolutePath(); - setDocumentFile(chosenFile); - boolean saved = saveToFile(documentFile); - if (saved) { - setNeedsResave(false); - NodeBoxMenuBar.addRecentFile(documentFile); - } - return saved; - } - return false; - } - - public void revert() { - // TODO: Implement revert - JOptionPane.showMessageDialog(this, "Revert is not implemented yet.", "NodeBox", JOptionPane.ERROR_MESSAGE); - } - - private boolean saveToFile(File file) { - try { - getNodeLibrary().store(file); - } catch (IOException e) { - JOptionPane.showMessageDialog(this, "An error occurred while saving the file.", "NodeBox", JOptionPane.ERROR_MESSAGE); - LOG.log(Level.SEVERE, "An error occurred while saving the file.", e); - return false; - } - documentChanged = false; - updateTitle(); - return true; - } - - private void markChanged() { - if (!documentChanged && loaded) { - documentChanged = true; - updateTitle(); - getRootPane().putClientProperty(WINDOW_MODIFIED, Boolean.TRUE); - } - } - - private void updateTitle() { - String postfix = ""; - if (!Platform.onMac()) { - postfix = (documentChanged ? " *" : ""); - } else { - getRootPane().putClientProperty("Window.documentModified", documentChanged); - } - if (documentFile == null) { - setTitle("Untitled" + postfix); - } else { - setTitle(documentFile.getName() + postfix); - getRootPane().putClientProperty("Window.documentFile", documentFile); - } - } - - public void focusNetworkView() { - networkView.requestFocus(); - } - - //// Export //// - - private ImageFormat imageFormatForFile(File file) { - if (file.getName().toLowerCase(Locale.US).endsWith(".pdf")) - return ImageFormat.PDF; - return ImageFormat.PNG; - } - - public void doExport() { - ExportDialog d = new ExportDialog(this); - d.setLocationRelativeTo(this); - d.setVisible(true); - if (!d.isDialogSuccessful()) return; - nodebox.ui.ImageFormat chosenFormat = d.getFormat(); - File chosenFile = FileUtils.showSaveDialog(this, lastExportPath, "png,pdf,svg", "Image file"); - if (chosenFile == null) return; - lastExportPath = chosenFile.getParentFile().getAbsolutePath(); - exportToFile(chosenFile, chosenFormat); - } - - private void exportToFile(File file, ImageFormat format) { - // get data from last export. - if (lastRenderResult == null) { - JOptionPane.showMessageDialog(this, "There is no last render result."); - } else { - exportToFile(file, lastRenderResult, format); - } - } - - private void exportToFile(File file, Iterable objects, ImageFormat format) { - file = format.ensureFileExtension(file); - ObjectsRenderer.render(objects, getCanvasBounds().getBounds2D(), file); - } - - public boolean exportRange() { - File exportDirectory = lastExportPath == null ? null : new File(lastExportPath); - if (exportDirectory != null && !exportDirectory.exists()) - exportDirectory = null; - ExportRangeDialog d = new ExportRangeDialog(this, exportDirectory); - d.setLocationRelativeTo(this); - d.setVisible(true); - if (!d.isDialogSuccessful()) return false; - String exportPrefix = d.getExportPrefix(); - File directory = d.getExportDirectory(); - int fromValue = d.getFromValue(); - int toValue = d.getToValue(); - nodebox.ui.ImageFormat format = d.getFormat(); - if (directory == null) return false; - lastExportPath = directory.getAbsolutePath(); - exportRange(exportPrefix, directory, fromValue, toValue, format); - return true; - } - - public void exportRange(final String exportPrefix, final File directory, final int fromValue, final int toValue, final ImageFormat format) { - exportThreadedRange(getNodeLibrary(), fromValue, toValue, new ExportDelegate() { - int count = 1; - - @Override - public void frameDone(double frame, Iterable results) { - File exportFile = new File(directory, exportPrefix + "-" + String.format("%05d", count)); - exportToFile(exportFile, results, format); - count += 1; - } - }); - } - - public boolean exportMovie() { - ExportMovieDialog d = new ExportMovieDialog(this, lastExportPath == null ? null : new File(lastExportPath)); - d.setLocationRelativeTo(this); - d.setVisible(true); - if (!d.isDialogSuccessful()) return false; - File chosenFile = d.getExportPath(); - if (chosenFile != null) { - lastExportPath = chosenFile.getParentFile().getAbsolutePath(); - exportToMovieFile(chosenFile, d.getVideoFormat(), d.getFromValue(), d.getToValue()); - return true; - } - return false; - } - - private void exportToMovieFile(File file, final VideoFormat videoFormat, final int fromValue, final int toValue) { - file = videoFormat.ensureFileExtension(file); - final Rectangle2D bounds = getCanvasBounds().getBounds2D(); - final int width = (int) Math.round(bounds.getWidth()); - final int height = (int) Math.round(bounds.getHeight()); - final Movie movie = new Movie(file.getAbsolutePath(), videoFormat, width, height, false); - exportThreadedRange(controller.getNodeLibrary(), fromValue, toValue, new ExportDelegate() { - @Override - public void frameDone(double frame, Iterable results) { - movie.addFrame(ObjectsRenderer.createMovieImage(results, bounds)); - } - - @Override - void exportDone() { - progressDialog.setTitle("Converting frames to movie..."); - progressDialog.reset(); - FramesWriter w = new FramesWriter(progressDialog); - movie.save(w); - } - }); - } - - public boolean needsResave() { - return needsResave; - } - - public void setNeedsResave(boolean needsResave) { - this.needsResave = needsResave; - } - - private void exportThreadedRange(final NodeLibrary library, final int fromValue, final int toValue, final ExportDelegate exportDelegate) { - int frameCount = toValue - fromValue; - final InterruptibleProgressDialog d = new InterruptibleProgressDialog(this, "Exporting " + frameCount + " frames..."); - d.setTaskCount(toValue - fromValue + 1); - d.setVisible(true); - exportDelegate.progressDialog = d; - - final NodeLibrary exportLibrary = getNodeLibrary(); - final FunctionRepository exportFunctionRepository = getFunctionRepository(); - final Node exportNetwork = library.getRoot(); - final Viewer viewer = new Viewer(); - - final JFrame frame = new JFrame(); - frame.setLayout(new BorderLayout()); - frame.setSize(getCanvasWidth(), getCanvasHeight()); - frame.setTitle("Exporting..."); - frame.add(viewer, BorderLayout.CENTER); - frame.setLocationRelativeTo(null); - - Thread t = new Thread(new Runnable() { - public void run() { - try { - Map> renderResults = ImmutableMap.of(); - for (int frame = fromValue; frame <= toValue; frame++) { - if (Thread.currentThread().isInterrupted()) - break; - HashMap data = new HashMap(); - data.put("frame", (double) frame); - data.put("mouse.position", viewer.getLastMousePosition()); - NodeContext context = new NodeContext(exportLibrary, exportFunctionRepository, data, renderResults, ImmutableMap.of()); - - List results = context.renderNode(exportNetwork); - renderResults = context.getRenderResults(); - viewer.setOutputValues((List) results); - exportDelegate.frameDone(frame, results); - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - d.tick(); - } - }); - } - exportDelegate.exportDone(); - } catch (Exception e) { - LOG.log(Level.WARNING, "Error while exporting", e); - } finally { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - d.setVisible(false); - frame.setVisible(false); - } - }); - } - } - }); - d.setThread(t); - t.start(); - frame.setVisible(true); - } - - private Rectangle getCanvasBounds() { - return new Rectangle(-(getCanvasX() + getCanvasWidth() / 2), -(getCanvasY() + getCanvasHeight() / 2), getCanvasWidth(), getCanvasHeight()); - } - - private int getCanvasX() { - return getIntProperty("canvasX", 0); - } - - private int getCanvasY() { - return getIntProperty("canvasY", 0); - } - - private int getCanvasWidth() { - return getIntProperty("canvasWidth", 1000); - } - - private int getCanvasHeight() { - return getIntProperty("canvasHeight", 1000); - } - - private int getIntProperty(String name, int defaultValue) { - try { - return Integer.parseInt(getNodeLibrary().getProperty(name, String.valueOf(defaultValue))); - } catch (NumberFormatException e) { - return defaultValue; - } - } - - //// Copy / Paste //// - - public void cut() { - copy(); - deleteSelection(); - } - - public void copy() { - // When copying, save a reference to the nodes and the parent network. - // Since the model is immutable, we don't need to make defensive copies. - nodeClipboard = new NodeClipboard(getActiveNetwork(), networkView.getSelectedNodes()); - } - - public void paste() { - addEdit("Paste node"); - if (nodeClipboard == null) return; - List newNodes = controller.pasteNodes(activeNetworkPath, nodeClipboard.network, nodeClipboard.nodes); - - networkView.updateAll(); - setActiveNode(newNodes.get(0)); - networkView.select(newNodes); - } - - public void dragCopy() { - List newNodes = controller.pasteNodes(activeNetworkPath, getActiveNetwork(), networkView.getSelectedNodes(), 0, 0); - networkView.updateAll(); - networkView.select(newNodes); - } - - public void deleteSelection() { - networkView.deleteSelection(); - } - - public void groupIntoNetwork(nodebox.graphics.Point pt) { - String networkName = getActiveNetwork().uniqueName("network"); - String name = JOptionPane.showInputDialog(this, "Network name:", networkName); - if (name == null) return; - - startEdits("Group into Network"); - String renderedChild = getActiveNetwork().getRenderedChildName(); - Node subnet = controller.groupIntoNetwork(activeNetworkPath, networkView.getSelectedNodes(), networkName); - controller.setNodePosition(Node.path(activeNetworkPath, subnet.getName()), pt); - if (renderedChild.equals(subnet.getRenderedChildName())) - controller.setRenderedChild(activeNetworkPath, subnet.getName()); - - if (!name.equals(subnet.getName())) { - controller.renameNode(activeNetworkPath, subnet.getName(), name); - subnet = getActiveNetwork().getChild(name); - } - - if (networkPanZoomValues.containsKey(activeNetworkPath)) - networkPanZoomValues.put(Node.path(activeNetworkPath, name), networkPanZoomValues.get(activeNetworkPath)); - - stopEdits(); - - setActiveNode(subnet); - networkView.updateAll(); - networkView.select(subnet); - requestRender(); - } - - /** - * Start the dialog that allows a user to create a new node. - */ - public void showNodeSelectionDialog() { - showNodeSelectionDialog(networkView.centerGridPoint()); - } - - /** - * Start the dialog that allows a user to create a new node. - * - * @param pt The point in "grid space" - */ - public void showNodeSelectionDialog(Point pt) { - NodeRepository repository = getNodeRepository(); - NodeSelectionDialog dialog = new NodeSelectionDialog(this, controller.getNodeLibrary(), repository); - dialog.setVisible(true); - if (dialog.getSelectedNode() != null) { - createNode(dialog.getSelectedNode(), new nodebox.graphics.Point(pt)); - } - } - - public void showCodeLibraries() { - CodeLibrariesDialog dialog = new CodeLibrariesDialog(this, getNodeLibrary().getFunctionRepository()); - dialog.setVisible(true); - FunctionRepository functionRepository = dialog.getFunctionRepository(); - if (functionRepository != null) { - addEdit("Change function repository"); - controller.setFunctionRepository(functionRepository); - invalidateFunctionRepository = true; - requestRender(); - } - } - - public void showDocumentProperties() { - DocumentPropertiesDialog dialog = new DocumentPropertiesDialog(this); - dialog.setVisible(true); - if (dialog.isCommitted()) { - addEdit("Change document properties"); - controller.setProperties(dialog.getProperties()); - getViewer().setCanvasBounds(getCanvasBounds().getBounds2D()); - requestRender(); - } - } - - public void showDevices() { - devicesDialog.setVisible(true); - } - - public void reload() { - controller.reloadFunctionRepository(); - functionRepository.invalidateFunctionCache(); - requestRender(); - } - - public void zoomView(double scaleDelta) { - PointerInfo a = MouseInfo.getPointerInfo(); - Point point = new Point(a.getLocation()); - for (Zoom zoomListener : zoomListeners) { - if (zoomListener.containsPoint(point)) - zoomListener.zoom(scaleDelta); - } - } - - public void addZoomListener(Zoom listener) { - zoomListeners.add(listener); - } - - public void removeZoomListener(Zoom listener) { - zoomListeners.remove(listener); - } - - public void setActiveNetworkPanZoom(double viewX, double viewY, double viewScale) { - double[] pz = new double[]{viewX, viewY, viewScale}; - networkPanZoomValues.put(getActiveNetworkPath(), pz); - } - - public void windowOpened(WindowEvent e) { - //viewEditorSplit.setDividerLocation(0.5); - parameterNetworkSplit.setDividerLocation(0.5); - topSplit.setDividerLocation(0.5); - } - - public void windowClosing(WindowEvent e) { - close(); - } - - //// Window events //// - - public void windowClosed(WindowEvent e) { - } - - public void windowIconified(WindowEvent e) { - } - - public void windowDeiconified(WindowEvent e) { - } - - public void windowActivated(WindowEvent e) { - Application.getInstance().setCurrentDocument(this); - } - - public void windowDeactivated(WindowEvent e) { - } - - private abstract class ExportDelegate { - protected InterruptibleProgressDialog progressDialog; - - void frameDone(double frame, Iterable results) { - } - - void exportDone() { - } - } - - private class NodeClipboard { - private final Node network; - private final ImmutableList nodes; - - private NodeClipboard(Node network, Iterable nodes) { - this.network = network; - this.nodes = ImmutableList.copyOf(nodes); - } - } - - private class ZoomInHandler implements ActionListener { - @Override - public void actionPerformed(ActionEvent actionEvent) { - zoomView(1.05); - } - } - - private class ZoomOutHandler implements ActionListener { - @Override - public void actionPerformed(ActionEvent actionEvent) { - zoomView(0.95); - } - } - - private class FramesWriter extends StringWriter { - private final ProgressDialog dialog; - - public FramesWriter(ProgressDialog d) { - super(); - dialog = d; - } - - @Override - public void write(String s, int n1, int n2) { - super.write(s, n1, n2); - if (s.startsWith("frame=")) { - int frame = Integer.parseInt(s.substring(6, s.indexOf("fps")).trim()); - dialog.updateProgress(frame); - } - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/old/NodeBoxDocument.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/old/NodeBoxDocument.java deleted file mode 100755 index 5c0c415..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/old/NodeBoxDocument.java +++ /dev/null @@ -1,1933 +0,0 @@ -package nodebox.client; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import nodebox.client.devicehandler.DeviceHandler; -import nodebox.client.devicehandler.DeviceHandlerFactory; -import nodebox.function.Function; -import nodebox.function.FunctionRepository; -import nodebox.handle.Handle; -import nodebox.handle.HandleDelegate; -import nodebox.movie.Movie; -import nodebox.movie.VideoFormat; -import nodebox.node.*; -import nodebox.node.MenuItem; -import nodebox.ui.*; -import nodebox.util.FileUtils; -import nodebox.util.LoadException; - -import javax.imageio.ImageIO; -import javax.swing.*; -import javax.swing.undo.UndoManager; -import java.awt.*; -import java.awt.event.*; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.logging.Level; -import java.util.logging.Logger; - -import static com.google.common.base.Preconditions.*; - -/** - * A NodeBoxDocument manages a NodeLibrary. - */ -public class NodeBoxDocument extends JFrame implements WindowListener, HandleDelegate { - - private static final Logger LOG = Logger.getLogger(NodeBoxDocument.class.getName()); - private static final String WINDOW_MODIFIED = "windowModified"; - public static String lastFilePath; - public static String lastExportPath; - private static NodeClipboard nodeClipboard; - private static Image APPLICATION_ICON_IMAGE; - - static { - try { - APPLICATION_ICON_IMAGE = ImageIO.read(NodeBoxDocument.class.getResourceAsStream("/application-logo.png")); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - // State - private final NodeLibraryController controller; - // Rendering - private final AtomicBoolean isRendering = new AtomicBoolean(false); - private final AtomicBoolean shouldRender = new AtomicBoolean(false); - // GUI components - private final NodeBoxMenuBar menuBar; - private final AnimationBar animationBar; - private final AddressBar addressBar; - private final ViewerPane viewerPane; - private final DataSheet dataSheet; - private final PortView portView; - private final NetworkPane networkPane; - private final NetworkView networkView; - private final ProgressPanel progressPanel; - private File documentFile; - private boolean documentChanged; - private boolean needsResave; - private AnimationTimer animationTimer; - private boolean loaded = false; - private UndoManager undoManager = new UndoManager(); - private boolean holdEdits = false; - private String lastEditType = null; - private String lastEditObjectId = null; - private FunctionRepository functionRepository; - private String activeNetworkPath = ""; - private String activeNodeName = ""; - private boolean restoring = false; - private boolean invalidateFunctionRepository = false; - private double frame = 1; - private Map networkPanZoomValues = new HashMap(); - private SwingWorker, Node> currentRender = null; - private Iterable lastRenderResult = null; - private Map> renderResults = ImmutableMap.of(); - private JSplitPane parameterNetworkSplit; - private JSplitPane topSplit; - private FullScreenFrame fullScreenFrame = null; - private List zoomListeners = new ArrayList(); - private List deviceHandlers = new ArrayList(); - private DevicesDialog devicesDialog; - - public NodeBoxDocument() { - this(createNewLibrary()); - } - - public NodeBoxDocument(NodeLibrary nodeLibrary) { - if (!nodeLibrary.hasProperty("canvasX")) - nodeLibrary = nodeLibrary.withProperty("canvasX", "0"); - if (!nodeLibrary.hasProperty("canvasY")) - nodeLibrary = nodeLibrary.withProperty("canvasY", "0"); - if (!nodeLibrary.hasProperty("canvasWidth")) - nodeLibrary = nodeLibrary.withProperty("canvasWidth", "1000"); - if (!nodeLibrary.hasProperty("canvasHeight")) - nodeLibrary = nodeLibrary.withProperty("canvasHeight", "1000"); - - controller = NodeLibraryController.withLibrary(nodeLibrary); - invalidateFunctionRepository = true; - JPanel rootPanel = new JPanel(new BorderLayout()); - this.viewerPane = new ViewerPane(this); - viewerPane.getViewer().setCanvasBounds(getCanvasBounds()); - dataSheet = viewerPane.getDataSheet(); - PortPane portPane = new PortPane(this); - portView = portPane.getPortView(); - networkPane = new NetworkPane(this); - networkView = networkPane.getNetworkView(); - parameterNetworkSplit = new CustomSplitPane(JSplitPane.VERTICAL_SPLIT, portPane, networkPane); - topSplit = new CustomSplitPane(JSplitPane.HORIZONTAL_SPLIT, viewerPane, parameterNetworkSplit); - - addressBar = new AddressBar(); - addressBar.setOnSegmentClickListener(new AddressBar.OnSegmentClickListener() { - public void onSegmentClicked(String fullPath) { - setActiveNetwork(fullPath); - } - }); - progressPanel = new ProgressPanel(this); - JPanel addressPanel = new JPanel(new BorderLayout()); - addressPanel.add(addressBar, BorderLayout.CENTER); - addressPanel.add(progressPanel, BorderLayout.EAST); - - rootPanel.add(addressPanel, BorderLayout.NORTH); - rootPanel.add(topSplit, BorderLayout.CENTER); - - // Animation properties. - animationTimer = new AnimationTimer(this); - animationBar = new AnimationBar(this); - rootPanel.add(animationBar, BorderLayout.SOUTH); - - // Zoom in / out shortcuts. - KeyStroke zoomInStroke1 = KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask() + InputEvent.SHIFT_MASK); - KeyStroke zoomInStroke2 = KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); - KeyStroke zoomInStroke3 = KeyStroke.getKeyStroke(KeyEvent.VK_PLUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); - ActionListener zoomInHandler = new ZoomInHandler(); - getRootPane().registerKeyboardAction(zoomInHandler, zoomInStroke1, JComponent.WHEN_IN_FOCUSED_WINDOW); - getRootPane().registerKeyboardAction(zoomInHandler, zoomInStroke2, JComponent.WHEN_IN_FOCUSED_WINDOW); - getRootPane().registerKeyboardAction(zoomInHandler, zoomInStroke3, JComponent.WHEN_IN_FOCUSED_WINDOW); - KeyStroke zoomOutStroke = KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); - getRootPane().registerKeyboardAction(new ZoomOutHandler(), zoomOutStroke, JComponent.WHEN_IN_FOCUSED_WINDOW); - - setContentPane(rootPanel); - setLocationByPlatform(true); - setSize(1100, 800); - setIconImage(APPLICATION_ICON_IMAGE); - setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); - addWindowListener(this); - updateTitle(); - menuBar = new NodeBoxMenuBar(this); - setJMenuBar(menuBar); - loaded = true; - - if (Application.ENABLE_DEVICE_SUPPORT) { - for (Device device : getNodeLibrary().getDevices()) { - DeviceHandler handler = DeviceHandlerFactory.createDeviceHandler(device); - if (handler != null) - deviceHandlers.add(handler); - } - devicesDialog = new DevicesDialog(this); -// addressBar.setMessage("OSC Port " + getOSCPort()); - } - } - - public static NodeBoxDocument getCurrentDocument() { - return Application.getInstance().getCurrentDocument(); - } - - /** - * Static factory method to create a NodeBoxDocument from a file. - *

- * This method can handle file upgrades. - * - * @param file the file to load. - * @return A NodeBoxDocument. - */ - public static NodeBoxDocument load(File file) { - NodeLibrary library; - NodeBoxDocument document; - try { - library = NodeLibrary.load(file, Application.getInstance().getSystemRepository()); - document = new NodeBoxDocument(library); - document.setDocumentFile(file); - } catch (OutdatedLibraryException e) { - UpgradeResult result = NodeLibraryUpgrades.upgrade(file); - // The file is used here as the base name for finding relative libraries. - library = result.getLibrary(file, Application.getInstance().getSystemRepository()); - document = new NodeBoxDocument(library); - document.setDocumentFile(file); - document.showUpgradeResult(result); - } catch (LoadException e) { - throw new RuntimeException("Could not load " + file, e); - } - lastFilePath = file.getParentFile().getAbsolutePath(); - return document; - } - - private static NodeLibrary createNewLibrary() { - NodeRepository nodeRepository = Application.getInstance().getSystemRepository(); - Node root = Node.NETWORK.withName("root"); - Node rectPrototype = nodeRepository.getNode("corevector.rect"); - String name = root.uniqueName(rectPrototype.getName()); - Node rect1 = rectPrototype.extend().withName(name).withPosition(new nodebox.graphics.Point(1, 1)); - root = root - .withChildAdded(rect1) - .withRenderedChild(rect1); - return NodeLibrary.create("untitled", root, nodeRepository, FunctionRepository.of()); - } - - /** - * Display the result of upgrading in a dialog box. - * - * @param result The UpgradeResult. - */ - private void showUpgradeResult(UpgradeResult result) { - checkNotNull(result); - if (result.getWarnings().isEmpty()) return; - final UpgradeWarningsDialog dialog = new UpgradeWarningsDialog(result); - dialog.setLocationRelativeTo(this); - SwingUtilities.invokeLater(new Runnable() { - public void run() { - dialog.setVisible(true); - } - }); - } - - public List getDeviceHandlers() { - return ImmutableList.copyOf(deviceHandlers); - } - - //// Node Library management //// - - public NodeLibrary getNodeLibrary() { - return controller.getNodeLibrary(); - } - - public NodeRepository getNodeRepository() { - return Application.getInstance().getSystemRepository(); - } - - public FunctionRepository getFunctionRepository() { - if (invalidateFunctionRepository) { - functionRepository = FunctionRepository.combine(getNodeRepository().getFunctionRepository(), getNodeLibrary().getFunctionRepository()); - invalidateFunctionRepository = false; - } - return functionRepository; - } - - /** - * Restore the node library to a different undo state. - * - * @param nodeLibrary The node library to restore. - * @param networkPath The active network path. - * @param nodeName The active node name. Can be an empty string. - */ - public void restoreState(NodeLibrary nodeLibrary, String networkPath, String nodeName) { - controller.setNodeLibrary(nodeLibrary); - invalidateFunctionRepository = true; - restoring = true; - setActiveNetwork(networkPath); - setActiveNode(nodeName); - restoring = false; - } - - //// Node operations //// - - /** - * Create a node in the active network. - * This node is based on a prototype. - * - * @param prototype The prototype node. - * @param pt The initial node position. - */ - public void createNode(Node prototype, nodebox.graphics.Point pt) { - startEdits("Create Node"); - Node newNode = controller.createNode(activeNetworkPath, prototype); - String newNodePath = Node.path(activeNetworkPath, newNode); - controller.setNodePosition(newNodePath, pt); - controller.setRenderedChild(activeNetworkPath, newNode.getName()); - setActiveNode(newNode); - stopEdits(); - - Node activeNode = getActiveNode(); - networkView.updateNodes(); - networkView.singleSelect(activeNode); - portView.updateAll(); - - requestRender(); - } - - /** - * Change the node position of the given node. - * - * @param node The node to move. - * @param point The point to move to. - */ - public void setNodePosition(Node node, nodebox.graphics.Point point) { - checkNotNull(node); - checkNotNull(point); - checkArgument(getActiveNetwork().hasChild(node)); - // Note that we're passing in the parent network of the node. - // This means that all move changes to the parent network are grouped - // together under one edit, instead of for each node individually. - addEdit("Move Node", "moveNode", getActiveNetworkPath()); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodePosition(nodePath, point); - - networkView.updatePosition(node); - } - - /** - * Change the node name. - * - * @param node The node to rename. - * @param name The new node name. - */ - public void setNodeName(Node node, String name) { - checkNotNull(node); - checkNotNull(name); - controller.renameNode(activeNetworkPath, node.getName(), name); - - String nodePath = Node.path(activeNetworkPath, node.getName()); - if (networkPanZoomValues.containsKey(nodePath)) { - String newNodePath = Node.path(activeNetworkPath, name); - for (String key : ImmutableList.copyOf(networkPanZoomValues.keySet())) { - if (key.equals(nodePath) || key.startsWith(nodePath + "/")) { - String newKey = key.replace(nodePath, newNodePath); - networkPanZoomValues.put(newKey, networkPanZoomValues.get(key)); - } - } - } - - setActiveNode(name); - networkView.updateNodes(); - networkView.singleSelect(getActiveNode()); - requestRender(); - } - - /** - * Change the comment for the node. - * - * @param node The node to be commented. - * @param comment The new comment. - */ - public void setNodeComment(Node node, String comment) { - checkNotNull(node); - checkNotNull(comment); - addEdit("Set Node Comment"); - controller.commentNode(activeNetworkPath, node.getName(), comment.trim()); - } - - /** - * Change the category for the node. - * - * @param node The node to change. - * @param category The new category. - */ - public void setNodeCategory(Node node, String category) { - checkNotNull(node); - checkNotNull(category); - addEdit("Set Node Category"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeCategory(nodePath, category); - } - - /** - * Change the description for the node. - * - * @param node The node to change. - * @param description The new description. - */ - public void setNodeDescription(Node node, String description) { - checkNotNull(node); - checkNotNull(description); - addEdit("Set Node Description"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeDescription(nodePath, description); - } - - /** - * Change the node image icon. - * - * @param node The node to change. - * @param image The new image icon. - */ - public void setNodeImage(Node node, String image) { - checkNotNull(node); - checkNotNull(image); - addEdit("Set Node Image"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeImage(nodePath, image); - networkView.updateNodes(); - } - - /** - * Change the output type for the node. - * - * @param node The node to change. - * @param outputType The new output type. - */ - public void setNodeOutputType(Node node, String outputType) { - checkNotNull(node); - checkNotNull(outputType); - addEdit("Set Output Type"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeOutputType(nodePath, outputType); - networkView.updateNodes(); - } - - /** - * Change the output range for the node. - * - * @param node The node to change. - * @param outputRange The new output range. - */ - public void setNodeOutputRange(Node node, Port.Range outputRange) { - checkNotNull(node); - addEdit("Change Node Output Range"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeOutputRange(nodePath, outputRange); - requestRender(); - } - - /** - * Change the node function. - * - * @param node The node to change. - * @param function The new function. - */ - public void setNodeFunction(Node node, String function) { - checkNotNull(node); - checkNotNull(function); - addEdit("Set Node Function"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeFunction(nodePath, function); - networkView.updateNodes(); - requestRender(); - } - - /** - * Change the node handle function. - * - * @param node The node to change. - * @param handle The new handle function. - */ - public void setNodeHandle(Node node, String handle) { - checkNotNull(node); - checkNotNull(handle); - addEdit("Set Node Handle"); - String nodePath = Node.path(activeNetworkPath, node); - controller.setNodeHandle(nodePath, handle); - createHandleForActiveNode(); - networkView.updateNodes(); - requestRender(); - } - - /** - * Set the node metadata to the given metadata. - * Note that this method is not called when the node position or name changes. - * - * @param node The node to change. - * @param metadata A map of metadata. - */ - public void setNodeMetadata(Node node, Object metadata) { - // TODO: Implement - // TODO: Make NodeAttributesEditor use this. - // Metadata changes could mean the icon has changed. - networkView.updateNodes(); - if (node == getActiveNode()) { - portView.updateAll(); - // Updating the metadata could cause changes to a handle. - viewerPane.repaint(); - dataSheet.repaint(); - } - requestRender(); - } - - public void setNodeExported(Node node, boolean exported) { - throw new UnsupportedOperationException("Not implemented yet."); - //addEdit("Set Exported"); - } - - /** - * Remove the given node from the active network. - * - * @param node The node to remove. - */ - public void removeNode(Node node) { - addEdit("Remove Node"); - removeNodeImpl(node); - networkView.updateAll(); - requestRender(); - } - - /** - * Remove the given nodes from the active network. - * - * @param nodes The node to remove. - */ - public void removeNodes(Iterable nodes) { - addEdit("Delete Nodes"); - for (Node node : nodes) { - removeNodeImpl(node); - } - networkView.updateAll(); - portView.updateAll(); - requestRender(); - } - - /** - * Helper method used by removeNode and removeNodes to do the removal and update the port view, if needed. - * - * @param node The node to remove. - */ - private void removeNodeImpl(Node node) { - checkNotNull(node, "Node to remove cannot be null."); - checkArgument(getActiveNetwork().hasChild(node), "Node to remove is not in active network."); - controller.removeNode(activeNetworkPath, node.getName()); - - // If the removed node was the active one, reset the port view. - if (node == getActiveNode()) { - setActiveNode((Node) null); - } - } - - /** - * Create a connection from the given output to the given input. - * - * @param outputNode The output node. - * @param inputNode The input node. - * @param inputPort The input port. - */ - public void connect(String outputNode, String inputNode, String inputPort) { - addEdit("Connect"); - controller.connect(activeNetworkPath, outputNode, inputNode, inputPort); - - portView.updateAll(); - viewerPane.updateHandle(); - requestRender(); - } - - /** - * Remove the given connection from the network. - * - * @param connection the connection to remove - */ - public void disconnect(Connection connection) { - addEdit("Disconnect"); - controller.disconnect(activeNetworkPath, connection); - - portView.updateAll(); - networkView.updateConnections(); - viewerPane.updateHandle(); - requestRender(); - } - - public void publish(String inputNode, String inputPort, String publishedName) { - addEdit("Publish"); - controller.publish(activeNetworkPath, inputNode, inputPort, publishedName); - } - - public void unpublish(String publishedName) { - addEdit("Unpublish"); - controller.unpublish(activeNetworkPath, publishedName); - } - - /** - * @param node the node on which to add the port - * @param portName the name of the new port - * @param portType the type of the new port - */ - public void addPort(Node node, String portName, String portType) { - checkArgument(getActiveNetwork().hasChild(node)); - addEdit("Add Port"); - controller.addPort(Node.path(activeNetworkPath, node), portName, portType); - portView.updateAll(); - networkView.updateAll(); - } - - /** - * Remove the port from the node. - * - * @param node The node on which to remove the port. - * @param portName The name of the port - */ - public void removePort(Node node, String portName) { - checkArgument(getActiveNetwork().hasChild(node)); - addEdit("Remove Port"); - controller.removePort(activeNetworkPath, node.getName(), portName); - - if (node == getActiveNode()) { - portView.updateAll(); - viewerPane.repaint(); - dataSheet.repaint(); - } - } - - /** - * Change the label for the given port - * - * @param portName The name of the port to change. - * @param label The new label. - */ - public void setPortLabel(String portName, String label) { - checkValidPort(portName); - addEdit("Change Label"); - controller.setPortLabel(getActiveNodePath(), portName, label); - portView.updateAll(); - requestRender(); - } - - /** - * Change the description for the given port - * - * @param portName The name of the port to change. - * @param description The new description. - */ - public void setPortDescription(String portName, String description) { - checkValidPort(portName); - addEdit("Change Description"); - controller.setPortDescription(getActiveNodePath(), portName, description); - portView.updateAll(); - requestRender(); - } - - /** - * Change the widget for the given port - * - * @param portName The name of the port to change. - * @param widget The new widget. - */ - public void setPortWidget(String portName, Port.Widget widget) { - checkValidPort(portName); - addEdit("Change Widget"); - controller.setPortWidget(getActiveNodePath(), portName, widget); - portView.updateAll(); - requestRender(); - } - - /** - * Change the port range of the given port - * - * @param portName The name of the port to change. - * @param range The new port range. - */ - public void setPortRange(String portName, Port.Range range) { - checkValidPort(portName); - addEdit("Change Port Range"); - controller.setPortRange(getActiveNodePath(), portName, range); - requestRender(); - } - - /** - * Change the minimum value for the given port - * - * @param portName The name of the port to change. - * @param minimumValue The new minimum value. - */ - public void setPortMinimumValue(String portName, Double minimumValue) { - checkValidPort(portName); - addEdit("Change Minimum Value"); - controller.setPortMinimumValue(getActiveNodePath(), portName, minimumValue); - portView.updateAll(); - requestRender(); - } - - /** - * Change the maximum value for the given port - * - * @param portName The name of the port to change. - * @param maximumValue The new maximum value. - */ - public void setPortMaximumValue(String portName, Double maximumValue) { - checkValidPort(portName); - addEdit("Change Maximum Value"); - controller.setPortMaximumValue(getActiveNodePath(), portName, maximumValue); - portView.updateAll(); - requestRender(); - } - - /** - * Add a new menu item for the given port's menu. - * - * @param portName The name of the port to add a new menu item for. - * @param key The key of the new menu item. - * @param label The label of the new menu item. - */ - public void addPortMenuItem(String portName, String key, String label) { - checkValidPort(portName); - addEdit("Add Port Menu Item"); - - controller.addPortMenuItem(getActiveNodePath(), portName, key, label); - - portView.updateAll(); - requestRender(); - } - - /** - * Remove a menu item from the given port's menu. - * - * @param portName The name of the port to remove the menu item from. - * @param item The menu item to remove - */ - public void removePortMenuItem(String portName, MenuItem item) { - checkValidPort(portName); - addEdit("Remove Parameter Menu Item"); - - controller.removePortMenuItem(getActiveNodePath(), portName, item); - - Node n = getActiveNode(); - portView.updateAll(); - requestRender(); - } - - /** - * Move a menu item down from the given port's menu. - * - * @param portName The name of the port of which to update the menu. - * @param itemIndex The index of the menu item to move down. - */ - public void movePortMenuItemDown(String portName, int itemIndex) { - checkValidPort(portName); - addEdit("Move Port Item Down"); - controller.movePortMenuItemDown(getActiveNodePath(), portName, itemIndex); - portView.updateAll(); - } - - /** - * Move a menu item up from the given port's menu. - * - * @param portName The name of the port of which to update the menu. - * @param itemIndex The index of the menu item to move up. - */ - public void movePortMenuItemUp(String portName, int itemIndex) { - checkValidPort(portName); - addEdit("Move Port Item Up"); - controller.movePortMenuItemUp(getActiveNodePath(), portName, itemIndex); - portView.updateAll(); - } - - /** - * Change a menu item's key and label in the given port's menu. - * - * @param portName The name of the port of which to update the menu. - * @param itemIndex The index of the menu item to change. - * @param key The new key of the menu item. - * @param label The new label of the menu item. - */ - public void updatePortMenuItem(String portName, int itemIndex, String key, String label) { - checkValidPort(portName); - addEdit("Update Port Menu Item"); - controller.updatePortMenuItem(getActiveNodePath(), portName, itemIndex, key, label); - portView.updateAll(); - } - - public Object getValue(String portName) { - if (getActiveNode() == null) { - return null; - } - Port port = checkValidPort(portName); - return port.getValue(); - } - - /** - * Set the port with the given node path to a new value. - * - * @param nodePath The path inside the network of the node the port belongs to. - * @param portName The name of the port. - * @param value The new value. - */ - public void setValue(String nodePath, String portName, Object value) { - checkNotNull(getNodeLibrary().getNodeForPath(nodePath)); - addEdit("Change Value", "changeValue", nodePath + "#" + portName); - - controller.setPortValue(nodePath, portName, value); - - // TODO set variables on the root port. -// if (port.getNode() == nodeLibrary.getRoot()) { -// nodeLibrary.setVariable(port.getName(), port.asString()); -// } - - portView.updatePortValue(portName, value); - // Setting a port might change enable expressions, and thus change the enabled state of a port row. - portView.updateEnabledState(); - // Setting a port might change the enabled state of the handle. - // viewer.setHandleEnabled(activeNode != null && activeNode.hasEnabledHandle()); - requestRender(); - } - - public void revertPortToDefault(String portName) { - Port port = checkValidPort(portName); - addEdit("Revert Port to Default"); - controller.revertToDefaultPortValue(getActiveNodePath(), portName); - portView.updateAll(); - portView.updateEnabledState(); - requestRender(); - } - - public void addDevice(String deviceType, String deviceName) { - // todo: undo / redo - Device device = controller.addDevice(deviceType, deviceName); - DeviceHandler handler = DeviceHandlerFactory.createDeviceHandler(device); - if (handler != null) - deviceHandlers.add(handler); - } - - public void removeDevice(String deviceName) { - // todo: undo / redo - for (DeviceHandler handler : getDeviceHandlers()) { - if (handler.getName().equals(deviceName)) { - handler.stop(); - deviceHandlers.remove(handler); - controller.removeDevice(deviceName); - } - } - } - - public void startDeviceHandlers() { - if (Application.ENABLE_DEVICE_SUPPORT) { - for (DeviceHandler handler : deviceHandlers) { - if (handler.isSyncedWithTimeline()) { - handler.resume(); - } - } - if (devicesDialog.isVisible()) - devicesDialog.rebuildInterface(); - } - } - - public void stopDeviceHandlers(boolean pause) { - if (Application.ENABLE_DEVICE_SUPPORT) { - for (DeviceHandler handler : deviceHandlers) { - if (handler.isSyncedWithTimeline()) { - if (pause) { - handler.pause(); - } else { - handler.stop(); - } - } - } - if (devicesDialog.isVisible()) - devicesDialog.rebuildInterface(); - } - } - - public void setDeviceProperty(String deviceName, String propertyName, String propertyValue) { - checkNotNull(deviceName, "Device name cannot be null."); - checkArgument(getNodeLibrary().hasDevice(deviceName)); - addEdit("Change Device Property"); - controller.setDeviceProperty(deviceName, propertyName, propertyValue); - } - - public void setPortMetadata(Port port, String key, String value) { - addEdit("Change Port Metadata"); - throw new UnsupportedOperationException("Not implemented yet."); - } - - private Port checkValidPort(String portName) { - checkNotNull(portName, "Port cannot be null."); - Port port = getActiveNode().getInput(portName); - checkArgument(port != null, "Port %s does not exist on node %s", portName, getActiveNode()); - return port; - } - - public void editMetadata() { - if (getActiveNode() == null) return; - JDialog editorDialog = new NodeAttributesDialog(NodeBoxDocument.this); - editorDialog.setSize(580, 751); - editorDialog.setLocationRelativeTo(NodeBoxDocument.this); - editorDialog.setVisible(true); - } - - //// Port pane callbacks //// - - public void takeScreenshot(File outputFile) { - Container c = getContentPane(); - BufferedImage img = new BufferedImage(c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_RGB); - Graphics2D g2 = img.createGraphics(); - c.paint(g2); - try { - ImageIO.write(img, "png", outputFile); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - //// Screen shot //// - - public void silentSet(String portName, Object value) { - try { - setValue(getActiveNodePath(), portName, value); - } catch (Exception ignored) { - } - } - - //// HandleDelegate implementation //// - - public void stopEditing() { - stopCombiningEdits(); - } - - // TODO Merge stopEditing and stopCombiningEdits. - - public void updateHandle() { - if (viewerPane.getHandle() != null) - viewerPane.getHandle().update(); - // TODO Make viewer repaint more fine-grained. - viewerPane.repaint(); - } - - /** - * Return the network that is currently "open": shown in the network view. - * - * @return The currently active network. - */ - public Node getActiveNetwork() { - // TODO This might be a potential bottleneck. - return getNodeLibrary().getNodeForPath(activeNetworkPath); - } - - //// Active network / node //// - - public void setActiveNetwork(String path) { - checkNotNull(path); - activeNetworkPath = path; - Node network = getNodeLibrary().getNodeForPath(path); - - if (!restoring) { - if (network.getRenderedChild() != null) { - setActiveNode(network.getRenderedChildName()); - } else if (!network.isEmpty()) { - // Set the active node to the first child. - setActiveNode(network.getChildren().iterator().next()); - } else { - setActiveNode((Node) null); - } - } - - addressBar.setPath(activeNetworkPath); - //viewer.setHandleEnabled(activeNode != null && activeNode.hasEnabledHandle()); - networkView.updateNodes(); - if (networkPanZoomValues.containsKey(activeNetworkPath)) { - double[] pz = networkPanZoomValues.get(activeNetworkPath); - networkView.setViewTransform(pz[0], pz[1], pz[2]); - } else if (!restoring) - networkView.resetViewTransform(); - if (!restoring) - networkView.singleSelect(getActiveNode()); - viewerPane.repaint(); - dataSheet.repaint(); - - requestRender(); - } - - public String getActiveNetworkPath() { - return activeNetworkPath; - } - - private Node getRenderedNode() { - if (viewerPane.shouldAlwaysRenderRoot()) return getNodeLibrary().getRoot(); - return getActiveNetwork(); - } - - /** - * Change the rendered node to the given node - * - * @param node the node to set rendered - */ - public void setRenderedNode(Node node) { - checkNotNull(node); - checkArgument(getActiveNetwork().hasChild(node)); - addEdit("Set Rendered"); - controller.setRenderedChild(activeNetworkPath, node.getName()); - - networkView.updateNodes(); - networkView.singleSelect(node); - requestRender(); - } - - /** - * Set the active network to the parent network. - */ - public void goUp() { - throw new UnsupportedOperationException("Not implemented yet."); - } - - /** - * Return the node that is currently focused: - * visible in the port view, and whose handles are displayed in the viewer. - * - * @return The active node. Can be null. - */ - public Node getActiveNode() { - if (activeNodeName.isEmpty()) { - return getActiveNetwork(); - } else { - return getNodeLibrary().getNodeForPath(getActiveNodePath()); - } - } - - public void setActiveNode(String nodeName) { - if (!restoring && getActiveNodeName().equals(nodeName)) return; - stopCombiningEdits(); - if (nodeName.isEmpty()) { - activeNodeName = ""; - } else { - checkArgument(getActiveNetwork().hasChild(nodeName)); - activeNodeName = nodeName; - } - - Node n = getActiveNode(); - createHandleForActiveNode(); - //editorPane.setActiveNode(activeNode); - // TODO If we draw handles again, we should repaint the viewer pane. - //viewerPane.repaint(); // For the handle - portView.updateAll(); - restoring = false; - networkView.singleSelect(n); - } - - /** - * Set the active node to the given node. - *

- * The active node is the one whose parameters are displayed in the port pane, - * and whose handle is displayed in the viewer. - *

- * This will also change the active network if necessary. - * - * @param node the node to change to. - */ - public void setActiveNode(Node node) { - setActiveNode(node != null ? node.getName() : ""); - } - - public String getActiveNodePath() { - return Node.path(activeNetworkPath, activeNodeName); - } - - public String getActiveNodeName() { - return activeNodeName; - } - - private void createHandleForActiveNode() { - Node activeNode = getActiveNode(); - if (activeNode != null) { - Handle handle = null; - - if (getFunctionRepository().hasFunction(activeNode.getHandle())) { - Function handleFunction = getFunctionRepository().getFunction(activeNode.getHandle()); - try { - handle = (Handle) handleFunction.invoke(); - } catch (Exception e) { - LOG.log(Level.WARNING, "Error while creating handle for " + activeNode, e); - } - } - - if (handle != null) { - handle.setHandleDelegate(this); - handle.update(); - viewerPane.setHandle(handle); - } else { - viewerPane.setHandle(null); - } - } - } -// if (activeNode != null) { -// Handle handle = null; -// try { -// handle = activeNode.createHandle(); -// // If the handle was created successfully, remove the messages. -// editorPane.clearMessages(); -// } catch (Exception e) { -// editorPane.setMessages(e.toString()); -// } -// if (handle != null) { -// handle.setHandleDelegate(this); -// // TODO Remove this. Find out why the handle needs access to the viewer (only repaint?) and put that in the HandleDelegate. -// handle.setViewer(viewer); -// viewer.setHandleEnabled(activeNode.hasEnabledHandle()); -// } -// viewer.setHandle(handle); -// } else { -// viewer.setHandle(null); -// } -// } - - // todo: this method feels like it doesn't belong here (maybe rename it?) - public boolean hasInput(String portName) { - Node node = getActiveNode(); - return node.hasInput(portName); - } - - public boolean isConnected(String portName) { - Node network = getActiveNetwork(); - Node node = getActiveNode(); - if (network == null || node == null) return false; - for (Connection c : network.getConnections()) { - if (c.getInputNode().equals(node.getName()) && c.getInputPort().equals(portName)) - return true; - } - return false; - } - - - //// Animation //// - - public double getFrame() { - return frame; - } - - public void setFrame(double frame) { - this.frame = frame; - - animationBar.setFrame(frame); - requestRender(); - } - - public void nextFrame() { - setFrame(getFrame() + 1); - } - - public void toggleAnimation() { - animationBar.toggleAnimation(); - } - - public void doRewind() { - animationBar.rewindAnimation(); - } - - public void playAnimation() { - startDeviceHandlers(); - animationTimer.start(); - } - - public void stopAnimation() { - stopDeviceHandlers(true); - animationTimer.stop(); - } - - public void rewindAnimation() { - stopAnimation(); - stopDeviceHandlers(false); - resetRenderResults(); - setFrame(1); - } - - //// Rendering //// - - /** - * Request a renderNetwork operation. - *

- * This method does a number of checks to see if the renderNetwork goes through. - *

- * The renderer could already be running. - *

- * If all checks pass, a renderNetwork request is made. - */ - public void requestRender() { - // If we're already rendering, request the next renderNetwork. - if (isRendering.compareAndSet(false, true)) { - // If we're not rendering, start rendering. - render(); - } else { - shouldRender.set(true); - } - } - - public void renderFullScreen() { - if (fullScreenFrame != null) - closeFullScreenWindow(); - fullScreenFrame = new FullScreenFrame(this); - fullScreenFrame.setVisible(true); - fullScreenFrame.setOutputValues(lastRenderResult); - } - - public void closeFullScreenWindow() { - if (fullScreenFrame != null) { - fullScreenFrame.setVisible(false); - fullScreenFrame.dispose(); - fullScreenFrame = null; - viewerPane.setOutputValues(lastRenderResult); - } - } - - private Viewer getViewer() { - if (fullScreenFrame != null) - return fullScreenFrame.getViewer(); - else - return viewerPane.getViewer(); - } - - /** - * Ask the document to stop the active rendering. - */ - public synchronized void stopRendering() { - if (currentRender != null) { - currentRender.cancel(true); - } - } - - private void render() { - checkState(SwingUtilities.isEventDispatchThread()); - checkState(currentRender == null); - progressPanel.setInProgress(true); - final NodeLibrary renderLibrary = getNodeLibrary(); - final Node renderNetwork = getRenderedNode(); - - Map dataMap = new HashMap(); - dataMap.put("frame", frame); - dataMap.put("mouse.position", viewerPane.getViewer().getLastMousePosition()); - for (DeviceHandler handler : deviceHandlers) - handler.addData(dataMap); - final ImmutableMap data = ImmutableMap.copyOf(dataMap); - - final NodeContext context = new NodeContext(renderLibrary, getFunctionRepository(), data, renderResults, ImmutableMap.of()); - currentRender = new SwingWorker, Node>() { - @Override - protected List doInBackground() throws Exception { - List results = context.renderNode(renderNetwork); - context.renderAlwaysRenderedNodes(renderNetwork); - renderResults = context.getRenderResults(); - return results; - } - - @Override - protected void done() { - networkPane.clearError(); - isRendering.set(false); - currentRender = null; - List results; - try { - results = get(); - } catch (CancellationException e) { - results = ImmutableList.of(); - } catch (InterruptedException e) { - results = ImmutableList.of(); - } catch (ExecutionException e) { - networkPane.setError(e.getCause()); - results = ImmutableList.of(); - } - - lastRenderResult = results; - - networkView.checkErrorAndRepaint(); - progressPanel.setInProgress(false); - if (fullScreenFrame != null) - fullScreenFrame.setOutputValues(results); - else - viewerPane.setOutputValues(results); - - if (shouldRender.getAndSet(false)) { - SwingUtilities.invokeLater(new Runnable() { - @Override - public void run() { - requestRender(); - } - }); - } - } - }; - currentRender.execute(); - } - - /** - * Returns the first output value, or null if the map of output values is empty. - * - * @param outputValues The map of output values. - * @return The output value. - */ - private Object firstOutputValue(final Map outputValues) { - if (outputValues.isEmpty()) return null; - return outputValues.values().iterator().next(); - } - - private synchronized void resetRenderResults() { - renderResults = ImmutableMap.of(); - } - - //// Undo //// - - /** - * Edits are no longer recorded until you call stopEdits. This allows you to batch edits. - * - * @param command the command name of the edit batch - */ - public void startEdits(String command) { - addEdit(command); - holdEdits = true; - } - - /** - * Edits are recorded again. - */ - public void stopEdits() { - holdEdits = false; - } - - /** - * Add an edit to the undo manager. - *

- * Since we don't specify the edit type or name, further edits will not be staggered. - * - * @param command the command name. - */ - public void addEdit(String command) { - if (!holdEdits) { - markChanged(); - undoManager.addEdit(new NodeLibraryUndoableEdit(this, command)); - menuBar.updateUndoRedoState(); - stopCombiningEdits(); - } - } - - /** - * Add an edit to the undo manager. - * - * @param command the command name. - * @param type the type of edit - * @param objectId the id for the edited object. This will be compared against. - */ - public void addEdit(String command, String type, String objectId) { - if (!holdEdits) { - markChanged(); - - if (lastEditType != null && lastEditType.equals(type) && lastEditObjectId.equals(objectId)) { - // If the last edit type and last edit id are the same, - // we combine the two edits into one. - // Since we've already saved the last state, we don't need to do anything. - } else { - addEdit(command); - lastEditType = type; - lastEditObjectId = objectId; - } - } - } - - /** - * Normally edits of the same type and object are combined into one. - * Calling this method will ensure that you create a new edit. - *

- * Use this method e.g. for breaking apart overzealous edit grouping. - */ - public void stopCombiningEdits() { - // We just reset the last edit type and object so that addEdit will be forced to create a new edit. - lastEditType = null; - lastEditObjectId = null; - stopEdits(); - } - - public UndoManager getUndoManager() { - return undoManager; - } - - public void undo() { - if (!undoManager.canUndo()) return; - undoManager.undo(); - menuBar.updateUndoRedoState(); - } - - public void redo() { - if (!undoManager.canRedo()) return; - undoManager.redo(); - menuBar.updateUndoRedoState(); - } - - //// Code editor actions //// - - public void fireCodeChanged(Node node, boolean changed) { - networkView.codeChanged(node, changed); - } - - //// Document actions //// - - public File getDocumentFile() { - return documentFile; - } - - public void setDocumentFile(File documentFile) { - this.documentFile = documentFile; - controller.setNodeLibraryFile(documentFile); - updateTitle(); - } - - public boolean isChanged() { - return documentChanged; - } - - public boolean close() { - stopAnimation(); - if (shouldClose()) { - Application.getInstance().removeDocument(this); - for (DeviceHandler handler : deviceHandlers) - handler.stop(); - dispose(); - // On Mac the application does not close if the last window is closed. - if (!Platform.onMac()) { - // If there are no more documents, exit the application. - if (Application.getInstance().getDocumentCount() == 0) { - System.exit(0); - } - } - return true; - } else { - return false; - } - } - - private boolean shouldClose() { - if (isChanged()) { - SaveDialog sd = new SaveDialog(); - int retVal = sd.show(this); - if (retVal == JOptionPane.YES_OPTION) { - return save(); - } else if (retVal == JOptionPane.NO_OPTION) { - return true; - } else if (retVal == JOptionPane.CANCEL_OPTION) { - return false; - } - } - return true; - } - - public boolean save() { - if (documentFile == null || needsResave()) { - return saveAs(); - } else { - boolean saved = saveToFile(documentFile); - if (saved) - NodeBoxMenuBar.addRecentFile(documentFile); - return saved; - } - } - - public boolean saveAs() { - File chosenFile = FileUtils.showSaveDialog(this, lastFilePath, "ndbx", "NodeBox File"); - if (chosenFile != null) { - if (!chosenFile.getAbsolutePath().endsWith(".ndbx")) { - chosenFile = new File(chosenFile.getAbsolutePath() + ".ndbx"); - if (chosenFile.exists()) { - boolean shouldReplace = ReplaceDialog.showForFile(chosenFile); - if (shouldReplace) { - return saveAs(); - } - } - } - lastFilePath = chosenFile.getParentFile().getAbsolutePath(); - setDocumentFile(chosenFile); - boolean saved = saveToFile(documentFile); - if (saved) { - setNeedsResave(false); - NodeBoxMenuBar.addRecentFile(documentFile); - } - return saved; - } - return false; - } - - public void revert() { - // TODO: Implement revert - JOptionPane.showMessageDialog(this, "Revert is not implemented yet.", "NodeBox", JOptionPane.ERROR_MESSAGE); - } - - private boolean saveToFile(File file) { - try { - getNodeLibrary().store(file); - } catch (IOException e) { - JOptionPane.showMessageDialog(this, "An error occurred while saving the file.", "NodeBox", JOptionPane.ERROR_MESSAGE); - LOG.log(Level.SEVERE, "An error occurred while saving the file.", e); - return false; - } - documentChanged = false; - updateTitle(); - return true; - } - - private void markChanged() { - if (!documentChanged && loaded) { - documentChanged = true; - updateTitle(); - getRootPane().putClientProperty(WINDOW_MODIFIED, Boolean.TRUE); - } - } - - private void updateTitle() { - String postfix = ""; - if (!Platform.onMac()) { - postfix = (documentChanged ? " *" : ""); - } else { - getRootPane().putClientProperty("Window.documentModified", documentChanged); - } - if (documentFile == null) { - setTitle("Untitled" + postfix); - } else { - setTitle(documentFile.getName() + postfix); - getRootPane().putClientProperty("Window.documentFile", documentFile); - } - } - - public void focusNetworkView() { - networkView.requestFocus(); - } - - //// Export //// - - private ImageFormat imageFormatForFile(File file) { - if (file.getName().toLowerCase().endsWith(".pdf")) - return ImageFormat.PDF; - return ImageFormat.PNG; - } - - public void doExport() { - ExportDialog d = new ExportDialog(this); - d.setLocationRelativeTo(this); - d.setVisible(true); - if (!d.isDialogSuccessful()) return; - nodebox.ui.ImageFormat chosenFormat = d.getFormat(); - File chosenFile = FileUtils.showSaveDialog(this, lastExportPath, "png,pdf,svg", "Image file"); - if (chosenFile == null) return; - lastExportPath = chosenFile.getParentFile().getAbsolutePath(); - exportToFile(chosenFile, chosenFormat); - } - - private void exportToFile(File file, ImageFormat format) { - // get data from last export. - if (lastRenderResult == null) { - JOptionPane.showMessageDialog(this, "There is no last render result."); - } else { - exportToFile(file, lastRenderResult, format); - } - } - - private void exportToFile(File file, Iterable objects, ImageFormat format) { - file = format.ensureFileExtension(file); - ObjectsRenderer.render(objects, getCanvasBounds().getBounds2D(), file); - } - - public boolean exportRange() { - File exportDirectory = lastExportPath == null ? null : new File(lastExportPath); - if (exportDirectory != null && !exportDirectory.exists()) - exportDirectory = null; - ExportRangeDialog d = new ExportRangeDialog(this, exportDirectory); - d.setLocationRelativeTo(this); - d.setVisible(true); - if (!d.isDialogSuccessful()) return false; - String exportPrefix = d.getExportPrefix(); - File directory = d.getExportDirectory(); - int fromValue = d.getFromValue(); - int toValue = d.getToValue(); - nodebox.ui.ImageFormat format = d.getFormat(); - if (directory == null) return false; - lastExportPath = directory.getAbsolutePath(); - exportRange(exportPrefix, directory, fromValue, toValue, format); - return true; - } - - public void exportRange(final String exportPrefix, final File directory, final int fromValue, final int toValue, final ImageFormat format) { - exportThreadedRange(getNodeLibrary(), fromValue, toValue, new ExportDelegate() { - int count = 1; - - @Override - public void frameDone(double frame, Iterable results) { - File exportFile = new File(directory, exportPrefix + "-" + String.format("%05d", count)); - exportToFile(exportFile, results, format); - count += 1; - } - }); - } - - public boolean exportMovie() { - ExportMovieDialog d = new ExportMovieDialog(this, lastExportPath == null ? null : new File(lastExportPath)); - d.setLocationRelativeTo(this); - d.setVisible(true); - if (!d.isDialogSuccessful()) return false; - File chosenFile = d.getExportPath(); - if (chosenFile != null) { - lastExportPath = chosenFile.getParentFile().getAbsolutePath(); - exportToMovieFile(chosenFile, d.getVideoFormat(), d.getFromValue(), d.getToValue()); - return true; - } - return false; - } - - private void exportToMovieFile(File file, final VideoFormat videoFormat, final int fromValue, final int toValue) { - file = videoFormat.ensureFileExtension(file); - final Rectangle2D bounds = getCanvasBounds().getBounds2D(); - final int width = (int) Math.round(bounds.getWidth()); - final int height = (int) Math.round(bounds.getHeight()); - final Movie movie = new Movie(file.getAbsolutePath(), videoFormat, width, height, false); - exportThreadedRange(controller.getNodeLibrary(), fromValue, toValue, new ExportDelegate() { - @Override - public void frameDone(double frame, Iterable results) { - movie.addFrame(ObjectsRenderer.createMovieImage(results, bounds)); - } - - @Override - void exportDone() { - progressDialog.setTitle("Converting frames to movie..."); - progressDialog.reset(); - FramesWriter w = new FramesWriter(progressDialog); - movie.save(w); - } - }); - } - - public boolean needsResave() { - return needsResave; - } - - public void setNeedsResave(boolean needsResave) { - this.needsResave = needsResave; - } - - private void exportThreadedRange(final NodeLibrary library, final int fromValue, final int toValue, final ExportDelegate exportDelegate) { - int frameCount = toValue - fromValue; - final InterruptibleProgressDialog d = new InterruptibleProgressDialog(this, "Exporting " + frameCount + " frames..."); - d.setTaskCount(toValue - fromValue + 1); - d.setVisible(true); - exportDelegate.progressDialog = d; - - final NodeLibrary exportLibrary = getNodeLibrary(); - final FunctionRepository exportFunctionRepository = getFunctionRepository(); - final Node exportNetwork = library.getRoot(); - final Viewer viewer = new Viewer(); - - final JFrame frame = new JFrame(); - frame.setLayout(new BorderLayout()); - frame.setSize(getCanvasWidth(), getCanvasHeight()); - frame.setTitle("Exporting..."); - frame.add(viewer, BorderLayout.CENTER); - frame.setLocationRelativeTo(null); - - Thread t = new Thread(new Runnable() { - public void run() { - try { - Map> renderResults = ImmutableMap.of(); - for (int frame = fromValue; frame <= toValue; frame++) { - if (Thread.currentThread().isInterrupted()) - break; - HashMap data = new HashMap(); - data.put("frame", (double) frame); - data.put("mouse.position", viewer.getLastMousePosition()); - NodeContext context = new NodeContext(exportLibrary, exportFunctionRepository, data, renderResults, ImmutableMap.of()); - - List results = context.renderNode(exportNetwork); - renderResults = context.getRenderResults(); - viewer.setOutputValues((List) results); - exportDelegate.frameDone(frame, results); - - SwingUtilities.invokeLater(new Runnable() { - public void run() { - d.tick(); - } - }); - } - exportDelegate.exportDone(); - } catch (Exception e) { - LOG.log(Level.WARNING, "Error while exporting", e); - } finally { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - d.setVisible(false); - frame.setVisible(false); - } - }); - } - } - }); - d.setThread(t); - t.start(); - frame.setVisible(true); - } - - private Rectangle getCanvasBounds() { - return new Rectangle(-(getCanvasX() + getCanvasWidth() / 2), -(getCanvasY() + getCanvasHeight() / 2), getCanvasWidth(), getCanvasHeight()); - } - - private int getCanvasX() { - return getIntProperty("canvasX", 0); - } - - private int getCanvasY() { - return getIntProperty("canvasY", 0); - } - - private int getCanvasWidth() { - return getIntProperty("canvasWidth", 1000); - } - - private int getCanvasHeight() { - return getIntProperty("canvasHeight", 1000); - } - - private int getIntProperty(String name, int defaultValue) { - try { - return Integer.parseInt(getNodeLibrary().getProperty(name, String.valueOf(defaultValue))); - } catch (NumberFormatException e) { - return defaultValue; - } - } - - //// Copy / Paste //// - - public void cut() { - copy(); - deleteSelection(); - } - - public void copy() { - // When copying, save a reference to the nodes and the parent network. - // Since the model is immutable, we don't need to make defensive copies. - nodeClipboard = new NodeClipboard(getActiveNetwork(), networkView.getSelectedNodes()); - } - - public void paste() { - addEdit("Paste node"); - if (nodeClipboard == null) return; - List newNodes = controller.pasteNodes(activeNetworkPath, nodeClipboard.network, nodeClipboard.nodes); - - networkView.updateAll(); - setActiveNode(newNodes.get(0)); - networkView.select(newNodes); - } - - public void dragCopy() { - List newNodes = controller.pasteNodes(activeNetworkPath, getActiveNetwork(), networkView.getSelectedNodes(), 0, 0); - networkView.updateAll(); - networkView.select(newNodes); - } - - public void deleteSelection() { - networkView.deleteSelection(); - } - - public void groupIntoNetwork(nodebox.graphics.Point pt) { - String networkName = getActiveNetwork().uniqueName("network"); - String name = JOptionPane.showInputDialog(this, "Network name:", networkName); - if (name == null) return; - - startEdits("Group into Network"); - String renderedChild = getActiveNetwork().getRenderedChildName(); - Node subnet = controller.groupIntoNetwork(activeNetworkPath, networkView.getSelectedNodes(), networkName); - controller.setNodePosition(Node.path(activeNetworkPath, subnet.getName()), pt); - if (renderedChild.equals(subnet.getRenderedChildName())) - controller.setRenderedChild(activeNetworkPath, subnet.getName()); - - if (!name.equals(subnet.getName())) { - controller.renameNode(activeNetworkPath, subnet.getName(), name); - subnet = getActiveNetwork().getChild(name); - } - - if (networkPanZoomValues.containsKey(activeNetworkPath)) - networkPanZoomValues.put(Node.path(activeNetworkPath, name), networkPanZoomValues.get(activeNetworkPath)); - - stopEdits(); - - setActiveNode(subnet); - networkView.updateAll(); - networkView.select(subnet); - requestRender(); - } - - /** - * Start the dialog that allows a user to create a new node. - */ - public void showNodeSelectionDialog() { - showNodeSelectionDialog(networkView.centerGridPoint()); - } - - /** - * Start the dialog that allows a user to create a new node. - * - * @param pt The point in "grid space" - */ - public void showNodeSelectionDialog(Point pt) { - NodeRepository repository = getNodeRepository(); - NodeSelectionDialog dialog = new NodeSelectionDialog(this, controller.getNodeLibrary(), repository); - dialog.setVisible(true); - if (dialog.getSelectedNode() != null) { - createNode(dialog.getSelectedNode(), new nodebox.graphics.Point(pt)); - } - } - - public void showCodeLibraries() { - CodeLibrariesDialog dialog = new CodeLibrariesDialog(this, getNodeLibrary().getFunctionRepository()); - dialog.setVisible(true); - FunctionRepository functionRepository = dialog.getFunctionRepository(); - if (functionRepository != null) { - addEdit("Change function repository"); - controller.setFunctionRepository(functionRepository); - invalidateFunctionRepository = true; - requestRender(); - } - } - - public void showDocumentProperties() { - DocumentPropertiesDialog dialog = new DocumentPropertiesDialog(this); - dialog.setVisible(true); - if (dialog.isCommitted()) { - addEdit("Change document properties"); - controller.setProperties(dialog.getProperties()); - getViewer().setCanvasBounds(getCanvasBounds().getBounds2D()); - requestRender(); - } - } - - public void showDevices() { - devicesDialog.setVisible(true); - } - - public void reload() { - controller.reloadFunctionRepository(); - functionRepository.invalidateFunctionCache(); - requestRender(); - } - - public void zoomView(double scaleDelta) { - PointerInfo a = MouseInfo.getPointerInfo(); - Point point = new Point(a.getLocation()); - for (Zoom zoomListener : zoomListeners) { - if (zoomListener.containsPoint(point)) - zoomListener.zoom(scaleDelta); - } - } - - public void addZoomListener(Zoom listener) { - zoomListeners.add(listener); - } - - public void removeZoomListener(Zoom listener) { - zoomListeners.remove(listener); - } - - public void setActiveNetworkPanZoom(double viewX, double viewY, double viewScale) { - double[] pz = new double[]{viewX, viewY, viewScale}; - networkPanZoomValues.put(getActiveNetworkPath(), pz); - } - - public void windowOpened(WindowEvent e) { - //viewEditorSplit.setDividerLocation(0.5); - parameterNetworkSplit.setDividerLocation(0.5); - topSplit.setDividerLocation(0.5); - } - - public void windowClosing(WindowEvent e) { - close(); - } - - //// Window events //// - - public void windowClosed(WindowEvent e) { - } - - public void windowIconified(WindowEvent e) { - } - - public void windowDeiconified(WindowEvent e) { - } - - public void windowActivated(WindowEvent e) { - Application.getInstance().setCurrentDocument(this); - } - - public void windowDeactivated(WindowEvent e) { - } - - private abstract class ExportDelegate { - protected InterruptibleProgressDialog progressDialog; - - void frameDone(double frame, Iterable results) { - } - - void exportDone() { - } - } - - private class NodeClipboard { - private final Node network; - private final ImmutableList nodes; - - private NodeClipboard(Node network, Iterable nodes) { - this.network = network; - this.nodes = ImmutableList.copyOf(nodes); - } - } - - private class ZoomInHandler implements ActionListener { - @Override - public void actionPerformed(ActionEvent actionEvent) { - zoomView(1.05); - } - } - - private class ZoomOutHandler implements ActionListener { - @Override - public void actionPerformed(ActionEvent actionEvent) { - zoomView(0.95); - } - } - - private class FramesWriter extends StringWriter { - private final ProgressDialog dialog; - - public FramesWriter(ProgressDialog d) { - super(); - dialog = d; - } - - @Override - public void write(String s, int n1, int n2) { - super.write(s, n1, n2); - if (s.startsWith("frame=")) { - int frame = Integer.parseInt(s.substring(6, s.indexOf("fps")).trim()); - dialog.updateProgress(frame); - } - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/pair.info deleted file mode 100755 index 38220d8..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#5243/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:5243 -comSha:0c35772c49974aa16da5d6c7f012c01236f009d9 -parentComSha:7fa5fc401efad5d78b011241ff420f37dbf44366 -BuggyFilePath:src/main/java/nodebox/client/NodeBoxDocument.java -FixedFilePath:src/main/java/nodebox/client/NodeBoxDocument.java -StartLineNum:1522 -EndLineNum:1522 -repoName:nodebox#nodebox \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/comMsg.txt deleted file mode 100755 index ee04a0c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of PMD design.xml/UseLocaleWithCaseConversions. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/diff.diff deleted file mode 100755 index 982534b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/StringUtils.java b/util/src/main/java/com/psddev/dari/util/StringUtils.java -index 24b96d83..0c658fee 100644 ---- a/util/src/main/java/com/psddev/dari/util/StringUtils.java -+++ b/util/src/main/java/com/psddev/dari/util/StringUtils.java -@@ -17,0 +18 @@ import java.util.List; -+import java.util.Locale; -@@ -249 +250 @@ public final class StringUtils { -- nb.append(word.toUpperCase()); -+ nb.append(word.toUpperCase(Locale.ENGLISH)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/new/StringUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/new/StringUtils.java deleted file mode 100755 index 0c658fe..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/new/StringUtils.java +++ /dev/null @@ -1,1217 +0,0 @@ -package com.psddev.dari.util; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.lang.StringEscapeUtils; - -/** String utility methods. */ -public final class StringUtils { - - private StringUtils() { - } - - public static final Charset US_ASCII = Charset.forName("US-ASCII"); - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - public static final Charset UTF_8 = Charset.forName("UTF-8"); - public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); - public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); - public static final Charset UTF_16 = Charset.forName("UTF-16"); - - private static final Set - ABBREVIATIONS = new HashSet(Arrays.asList( - "cms", "css", "id", "js", "seo", "uri", "url")); - - private static final char[] HEX_CHARACTERS = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f' }; - - /** - * Converts given string into a value of given type, throwing an exception - * if conversion was unsuccessful. - * - * If the return type is an array, an array is returned. - * fromString(int[].class, "1", "2") => int[] {1,2} - * - * If no values are provided and the return type is an array, an empty array is returned. - * fromString(int[].class) => int[] {} - * - * If no values are provided and the return type is not an array, an exception - * appropriate to the conversion type is thrown. - * fromString(int.class) => NumberFormatException - * - * If the {@code strings} contains more than one value and the {@code returnType} is not - * an array, all but the first value are ignored. - * - * If the method cannot convert to the class specified, an IllegalArgumentException is thrown. - * - * @param - * @param returnType The class for the String input(s) to be converted to - * @param strings the input(s) to be converted - * @return the converted value - */ - public static T fromString(Class returnType, String... strings) { - - // heavy voodoo follows... - // need to return an array - Class componentType = returnType.getComponentType(); - if (componentType != null) { - if (strings == null) { - return null; - } else { - int length = strings.length; - Object typed = Array.newInstance(componentType, length); - for (int i = 0; i < length; i++) { - Array.set(typed, i, fromString(componentType, strings[i])); - } - return (T) typed; - } - - // single value - } else { - String string = strings == null || strings.length == 0 ? null : strings[0]; - - // string to string - if (String.class == returnType) { - return (T) string; - - // primitives - // pass null through if returnType allows it - } else if (string == null && !returnType.isPrimitive()) { - return null; - - // any way to avoid boxing/unboxing on primitives? - } else if (boolean.class == returnType || Boolean.class.isAssignableFrom(returnType)) { - return (T) Boolean.valueOf(string); - } else if (byte.class == returnType || Byte.class.isAssignableFrom(returnType)) { - return (T) Byte.valueOf(string); - } else if (short.class == returnType || Short.class.isAssignableFrom(returnType)) { - return (T) Short.valueOf(string); - } else if (int.class == returnType || Integer.class.isAssignableFrom(returnType)) { - return (T) Integer.valueOf(string); - } else if (long.class == returnType || Long.class.isAssignableFrom(returnType)) { - return (T) Long.valueOf(string); - } else if (float.class == returnType || Float.class.isAssignableFrom(returnType)) { - return (T) Float.valueOf(string); - } else if (double.class == returnType || Double.class.isAssignableFrom(returnType)) { - return (T) Double.valueOf(string); - } else if (char.class == returnType || Character.class.isAssignableFrom(returnType)) { - if (string.length() == 1) { - return (T) Character.valueOf(string.charAt(0)); - } - - // others - } else if (Date.class.isAssignableFrom(returnType)) { - return (T) DateUtils.fromString(string); - } - throw new IllegalArgumentException(String.format( - "Cannot convert [%s] string to [%s] type!", - string, - returnType.getName() - )); - } - } - - - /** - * Helper method to split a string by case change or common delimiters. - * - * Multiple delimeters in a row are reduced to a single word boundry. - * - * Leading delimeters (a space at the beginning of the string) will cause an - * empty first word to be detected (bug?). Trailing delemeters do not cause empty - * words to be detected. - * - * Returned words are all lowercased. - * - * @param string - * @return the list of words detected in the string - */ - protected static List splitString(String string) { - List words = new ArrayList(); - int m = 0, l = string.length(); - for (int i = 0; i < l; i++) { - char c = string.charAt(i); - if (" -_.$".indexOf(c) > -1) { - words.add(string.substring(m, i).toLowerCase()); - while (++i < l && " -_.$".indexOf(string.charAt(i)) > -1) { - } - m = i; - } else if (Character.isUpperCase(c) && i > 0 && Character.isLowerCase(string.charAt(i - 1))) { - words.add(string.substring(m, i).toLowerCase()); - m = i; - } - } - if (m + 1 < l) { - words.add(string.substring(m).toLowerCase()); - } - return words; - } - - /** - * Tries to detect words within a given string and join them with the given delimiter. - */ - public static String toDelimited(String string, String delimiter) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(word).append(delimiter); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - delimiter.length()); - } - return nb.toString(); - } - - /** - * Converts the given string into a-hyphenated-string. - */ - public static String toHyphenated(String string) { - return toDelimited(string, "-"); - } - - /** - * Converts the given string into a_underscored_string. - */ - public static String toUnderscored(String string) { - return toDelimited(string, "_"); - } - - /** - * Converts the given string into APascalCaseString. - */ - public static String toPascalCase(String string) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); - } - return nb.toString(); - } - - /** - * Converts the given string into aCamelCaseString. - */ - public static String toCamelCase(String string) { - string = toPascalCase(string); - return Character.toLowerCase(string.charAt(0)) + string.substring(1); - } - - /** - * Converts the string to one suitable for use as "a label"? - * - * Splits {@code string} into words, joining it back together "In Title Case" - * with known {@code ABBREVIATIONS} replaced in all caps. If the first word of - * {@code string} is "is", that word is removed and a question mark is - * added to the end of the resulting string. - * - * @param string - */ - public static String toLabel(String string) { - - if (string == null) { - return null; - } - - boolean isQuestion = false; - List words = splitString(string); - if (words.size() > 0 && "is".equals(words.get(0))) { - isQuestion = true; - words.remove(0); - } - - StringBuilder nb = new StringBuilder(); - for (String word : words) { - if (word.length() == 0) { - continue; - } - - if (ABBREVIATIONS.contains(word)) { - nb.append(word.toUpperCase(Locale.ENGLISH)); - } else { - nb.append(Character.toUpperCase(word.charAt(0))); - nb.append(word.substring(1)); - } - nb.append(' '); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - 1); - } - - if (isQuestion) { - nb.append('?'); - } - - return nb.toString(); - } - - /** - * Normalizes a string, removing or replacing non-alphanumeric characters and lowercasing - * - * - Removes all accented characters. - * - Removes single quotes - * - Replaces non-alphanumeric characters remaining with a dash - * - Removes dashes - * - * Lowercases the result - */ - public static String toNormalized(CharSequence string) { - return string == null ? null : replaceAll( - Normalizer.normalize(string, Normalizer.Form.NFD), - "[^\\p{ASCII}]", "", - "'", "", - "\\.", "", - "[^a-zA-Z0-9]+", "-", - "^-+|-+$", "" - ).toLowerCase(); - } - - /** Splits the given string by commas, and returns each part unescaped. - * Calling {@link #toCsv(String...)} on an array of Strings and then - * passing the result to this method will always return the same array - * as specified by the Arrays.equals() method. */ - public static String[] fromCsv(String string) { - if(string == null) { - return null; - } else { - // replaces a call to string.split(",") - char[] charArr = string.toCharArray(); - int commaCount = 0; - for (char c : charArr) { - if (c == ',') { - commaCount++; - } - } - String[] escaped = new String[commaCount+1]; - int index = 0; - int offset = 0; - int count = 0; - for (char c : charArr) { - if (c == ',') { - escaped[index++] = new String(charArr, offset, count); - offset += count+1; - count = 0; - } else { - count++; - } - } - if (index == commaCount) { - escaped[index] = new String(charArr, offset, count); - } - // end string.split(",") replacement code - - int length = escaped.length; - List unescaped = new ArrayList(); - for(int i = 0; i < length; i ++) { - String value = escaped[i]; - if(value.startsWith("\"")) { // there are commas and/or double quotes escaped within - StringBuilder builder = new StringBuilder(); - int quoteCount = 0; - do { - builder.append(value); - for(char c : value.toCharArray()) { - if(c == '"') { - quoteCount++; - } - } - if(quoteCount % 2 == 1) { - value = escaped[++i]; - builder.append(','); - } - } while(quoteCount % 2 == 1); - value = builder.toString(); - } - unescaped.add(StringUtils.unescapeCsv(value)); - } - return unescaped.toArray(new String[unescaped.size()]); - } - } - - /** Converts an array of Strings to a single String in comma separated - * values format, escaping each string as necessary. */ - public static String toCsv(String... strings) { - if (strings == null) { - return null; - } - StringBuilder builder = new StringBuilder(); - for (String string : strings) { - builder.append(escapeCsv(string)).append(','); - } - if (builder.length() > 0) { - builder.setLength(builder.length()-1); - } - return builder.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string, int maxWordLength) { - if (string == null) { - return null; - } - Matcher matcher = getMatcher(string, String.format("(\\S{%d,})", maxWordLength)); - StringBuilder output = new StringBuilder(); - int marker = 0; - while (matcher.find()) { - String longWord = matcher.group(1); - - // similar to Matcher.appendReplacement - // re-implemented so that $ and \ does not have to be escaped - if (matcher.start() > marker) { - output.append(string.substring(marker, matcher.start())); - } - int i = 0; - for (; i < longWord.length() - maxWordLength; i += maxWordLength) { - output.append(escapeHtml(longWord.substring(i, i + maxWordLength))); - output.append(""); - } - output.append(escapeHtml(longWord.substring(i))); - marker = matcher.end(); - } - - // similar to Matcher.appendTail - output.append(string.substring(marker)); - return output.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string) { - return escapeHtmlAndBreak(string, 20); - } - - /** Converts the given {@code bytes} into a hex string. */ - public static String hex(byte[] bytes) { - if (bytes == null) { - return null; - } - - int bytesLength = bytes.length; - byte currentByte; - char[] hex = new char[bytesLength * 2]; - - for (int byteIndex = 0, hexIndex = 0; - byteIndex < bytesLength; - ++ byteIndex, hexIndex += 2) { - - currentByte = bytes[byteIndex]; - hex[hexIndex] = HEX_CHARACTERS[(currentByte & 0xf0) >> 4]; - hex[hexIndex + 1] = HEX_CHARACTERS[(currentByte & 0x0f)]; - } - - return new String(hex); - } - - /** Hashes the given {@code string} using the given {@code algorithm}. */ - public static byte[] hash(String algorithm, String string) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance(algorithm); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid hash algorithm!", algorithm), ex); - } - - byte[] bytes; - try { - bytes = string.getBytes("UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - - return digest.digest(bytes); - } - - /** Hashes the given {@code string} using the MD5 algorithm. */ - public static byte[] md5(String string) { - return hash("MD5", string); - } - - /** Hashes the given {@code string} using the SHA-1 algorithm. */ - public static byte[] sha1(String string) { - return hash("SHA-1", string); - } - - /** Hashes the given {@code string} using the SHA-512 algorithm. */ - public static byte[] sha512(String string) { - return hash("SHA-512", string); - } - - /** - * Hashes the given {@code string} using the given HMAC {@code algorithm} - * and {@code key}. - */ - public static byte[] hmac(String algorithm, String key, String string) { - try { - Mac mac = Mac.getInstance(algorithm); - mac.init(new SecretKeySpec(key.getBytes(StringUtils.UTF_8), algorithm)); - return mac.doFinal(string.getBytes(StringUtils.UTF_8)); - - } catch (NoSuchAlgorithmException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid HMAC algorithm!", algorithm), error); - - } catch (InvalidKeyException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid key!", key), error); - } - } - - /** - * Hashes the given {@code string} using the HMAC SHA-1 algorithm - * and the given {@code key}. - */ - public static byte[] hmacSha1(String key, String string) { - return hmac("HmacSHA1", key, string); - } - - // --- URL/URI --- - - /** - * Encodes the given UTF-8 {@code string} so that it's safe for use - * within an URI. - */ - public static String encodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLEncoder.encode(string, "UTF-8").replace("+", "%20"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** Decodes the given URI-encoded, UTF-8 {@code string}. */ - public static String decodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLDecoder.decode(string, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** - * Adds the given {@code parameters} as a query string to the given - * {@code uri}. - */ - public static String addQueryParameters(String uri, Object... parameters) { - if (uri == null) { - return null; - } - - // Convert "path?a=b&c=d" to "&a=b&c=d". - StringBuilder query = new StringBuilder(); - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - - String queryString = uri.substring(questionAt + 1); - int beginAt = 0; - - // make sure all the query parameters are encoded - while (true) { - int ampIndex = queryString.indexOf('&', beginAt); - - String param = queryString.substring(beginAt, ampIndex > -1 ? ampIndex : queryString.length()); - - if (!param.isEmpty() || ampIndex > -1) { - query.append('&'); - - int equalsIndex = param.indexOf('='); - if (equalsIndex > -1) { - query.append(encodeUri(decodeUri(param.substring(0, equalsIndex)))); - query.append('='); - query.append(encodeUri(decodeUri(param.substring(equalsIndex+1)))); - - } else { - query.append(encodeUri(decodeUri(param))); - } - } - - if (ampIndex > -1) { - beginAt = ampIndex+1; - } else { - break; - } - } - - uri = uri.substring(0, questionAt); - } - - int parametersLength = parameters != null ? parameters.length : 0; - - for (int i = 0; i < parametersLength; i += 2) { - - // Remove all occurrences of "&name=". - String name = parameters[i].toString(); - String prefix = "&" + name + "="; - int prefixLength = prefix.length(); - int beginAt = 0; - int endAt; - while (true) { - - beginAt = query.indexOf(prefix, beginAt); - if (beginAt < 0) { - break; - } - - endAt = query.indexOf("&", beginAt + prefixLength); - if (endAt > -1) { - query.delete(beginAt, endAt); - - } else { - query.delete(beginAt, query.length()); - break; - } - } - - // Append "&name=value". - if (i + 1 < parametersLength) { - Object value = parameters[i + 1]; - if (value != null) { - for (Object item : ObjectUtils.to(Iterable.class, value)) { - if (item != null) { - query.append('&'); - query.append(encodeUri(name)); - query.append('='); - query.append(encodeUri(item instanceof Enum ? - ((Enum) item).name() : - item.toString())); - } - } - } - } - } - - // Reconstruct the URI. - if (query.length() <= 1) { - return uri; - - } else { - query.delete(0, 1); - query.insert(0, "?"); - query.insert(0, uri); - return query.toString(); - } - } - - /** - * Returns the first query parameter value associated with the given - * {@code name} from the given {@code uri}. - */ - public static String getQueryParameterValue(String uri, String name) { - for (String value : getQueryParameterValues(uri, name)) { - return value; - } - return null; - } - - /** - * Returns a list of query parameter values associated with the given - * {@code name} from the given {@code uri}. - */ - public static List getQueryParameterValues(String uri, String name) { - List values = new ArrayList(); - if (uri != null) { - - // Strip out the path before the query string. - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - uri = uri.substring(questionAt + 1); - } - uri = "&" + uri; - - // Find all occurences of "&name=". - String prefix = "&" + encodeUri(name) + "="; - int prefixLength = prefix.length(); - for (int nameAt = 0; (nameAt = uri.indexOf(prefix, nameAt)) > -1;) { - nameAt += prefixLength; - int andAt = uri.indexOf('&', nameAt); - values.add(decodeUri(andAt > -1 ? - uri.substring(nameAt, andAt) : - uri.substring(nameAt))); - } - } - - return values; - } - - /** Returns a map of query parameters from the given {@code url}. */ - public static Map> getQueryParameterMap(String url) { - Map> map = new LinkedHashMap>(); - - if (url != null) { - int questionAt = url.indexOf('?'); - - if (questionAt > -1) { - url = url.substring(questionAt + 1); - } - - int lastAndAt = 0; - - for (int andAt; - (andAt = url.indexOf('&', lastAndAt)) > -1; - lastAndAt = andAt + 1) { - addParameter(map, url.substring(lastAndAt, andAt)); - } - - addParameter(map, url.substring(lastAndAt)); - } - - return map; - } - - private static void addParameter(Map> map, String pair) { - if (pair == null || pair.length() == 0) { - return; - } - - int equalAt = pair.indexOf('='); - String name; - String value; - - if (equalAt > -1) { - name = decodeUri(pair.substring(0, equalAt)); - value = decodeUri(pair.substring(equalAt + 1)); - - } else { - name = decodeUri(pair); - value = null; - } - - List parameters = map.get(name); - - if (parameters == null) { - parameters = new ArrayList(); - map.put(name, parameters); - } - - parameters.add(value); - } - - /** @deprecated Use {@link #addQueryParameters instead}. */ - @Deprecated - public static String transformUri(String uri, Object... parameters) { - return addQueryParameters(uri, parameters); - } - - /** @deprecated Use {@link #getQueryParameterValue instead}. */ - @Deprecated - public static String getParameter(String uri, String name) { - return getQueryParameterValue(uri, name); - } - - /** @deprecated Use {@link #getQueryParameterValues instead}. */ - @Deprecated - public static String[] getParameterValues(String uri, String name) { - List values = getQueryParameterValues(uri, name); - return values.toArray(new String[values.size()]); - } - - // --- Pattern bridge --- - private static final Map _patterns = new PullThroughCache() { - @Override - protected Pattern produce(String pattern) { - return Pattern.compile(pattern); - } - }; - - /** - * Gets a cached regular expression pattern object based on the given string. - */ - public static Pattern getPattern(String pattern) { - return _patterns.get(pattern); - } - - /** - * Gets a regular expression matcher based on the given string and pattern. - * - * @see #getPattern(String) - */ - public static Matcher getMatcher(CharSequence string, String pattern) { - return getPattern(pattern).matcher(string); - } - - /** - * Helper function that finds all groups in a regex and returns them in a result. find() is called automatically. - */ - public static MatchResult getMatcherResult(CharSequence string, String pattern) { - Matcher matcher = getMatcher(string, pattern); - matcher.find(); - final MatchResult result = matcher.toMatchResult(); - - - return new MatchResult() { - @Override - public int start() { - return result.start(); - } - - @Override - public int start(int group) { - return result.start(group); - } - - @Override - public int end() { - return result.end(); - } - - @Override - public int end(int group) { - return result.end(group); - } - - @Override - public String group() { - return result.group(); - } - - @Override - public String group(int group) { - try { - return result.group(group); - } catch (IllegalStateException e) { - return null; - } catch (IndexOutOfBoundsException e) { - return null; - } - } - - @Override - public int groupCount() { - return result.groupCount(); - } - }; - } - - /** - * Compiles the given regular expression pattern and attempts to match the given string against it. - * - * @see #getMatcher(CharSequence, String). - */ - public static boolean matches(CharSequence string, String pattern) { - return getMatcher(string, pattern).matches(); - } - - public static boolean matchAll(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return false; - } - } - - return true; - } - - public static boolean matchAny(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return true; - } - } - - return false; - } - - public static int matchCount(CharSequence string, String... patterns) { - int count = 0; - for (String pattern : patterns) { - if (matches(string, pattern)) { - ++count; - } - } - - return count; - } - - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #getMatcher(CharSequence, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement) { - return getMatcher(string, pattern).replaceAll(replacement); - } - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #replaceAll(CharSequence, String, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement, String... more) { - String r = replaceAll(string, pattern, replacement); - for (int i = 0, l = more.length; i < l; i += 2) { - r = replaceAll(r, more[i], i + 1 < l ? more[i + 1] : ""); - } - return r; - } - - /** - * Removes a without using regex * - */ - public static String removeAll(CharSequence string, CharSequence pattern) { - if (string == null) { - throw new IllegalArgumentException("String input is null"); - } - if (pattern != null) { - StringBuilder builder = new StringBuilder(string); - String p = pattern.toString(); - int l = pattern.length(); - for (int index; (index = builder.indexOf(p)) > -1;) { - builder.delete(index, index + l); - } - return builder.toString(); - } else { - return string.toString(); - } - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern, int limit) { - return getPattern(pattern).split(string, limit); - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern) { - return getPattern(pattern).split(string); - } - - // --- StringEscapeUtils bridge --- - - public static String escapeCsv(String string) { - return string == null ? null : StringEscapeUtils.escapeCsv(string); - } - - public static String escapeHtml(String string) { - return string == null ? null : StringUtils.replaceAll( - StringEscapeUtils.escapeHtml(string), - "\\x22", """, // double quote - "\\x27", "'"); // single quote - } - - public static String escapeJava(String string) { - return string == null ? null : StringEscapeUtils.escapeJava(string); - } - - /** - * Escapes the input string so that the resulting output can be used - * inside a JavaScript string AND none of the characters in the output - * need to be HTML escaped. - * @param string - * @return the escaped string, or null if the input was null - * This is not the same as HTML escaping a JavaScript escaped string, - * since the output can be used directly in a JavaScript string even - * when HTML-unescaping won't happen. - */ - public static String escapeJavaScript(String string) { - if (string == null) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0, s = string.length(); i < s; ++ i) { - char c = string.charAt(i); - if (0x30 <= c && c <= 0x39 - || 0x41 <= c && c <= 0x5A - || 0x61 <= c && c <= 0x7A) { - sb.append(c); - } else { - String hex = Integer.toHexString(c); - int hexLen = hex.length(); - if (c < 256) { - sb.append("\\x").append("00".substring(hexLen)); - } else { - sb.append("\\u").append("0000".substring(hexLen)); - } - sb.append(hex); - } - } - return sb.toString(); - } - - public static String escapeQuotes(String string) { - return string == null ? null : string.replace("\\", "\\\\").replace("\"", "\\\""); - } - - public static String escapeSql(String string) { - return string == null ? null : StringEscapeUtils.escapeSql(string); - } - - public static String escapeXml(String string) { - return string == null ? null : StringEscapeUtils.escapeXml(string); - } - - public static String unescapeCsv(String string) { - return string == null ? null : StringEscapeUtils.unescapeCsv(string); - } - - public static String unescapeHtml(String string) { - return string == null ? null : StringEscapeUtils.unescapeHtml(string); - } - - public static String unescapeJava(String string) { - return string == null ? null : StringEscapeUtils.unescapeJava(string); - } - - public static String unescapeJavaScript(String string) { - return string == null ? null : StringEscapeUtils.unescapeJavaScript(string); - } - - public static String unescapeXml(String string) { - return string == null ? null : StringEscapeUtils.unescapeXml(string); - } - - // --- StringUtils bridge --- - - /** - * Joins the given list of strings with the given delimiter in between. - */ - public static String join(List strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Joins the given array of strings with the given delimiter in between. - */ - public static String join(String[] strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Checks if a String is empty ("") or null. - */ - public static boolean isEmpty(String string) { - return org.apache.commons.lang.StringUtils.isEmpty(string); - } - - /** - * Checks if a String is whitespace, empty ("") or null. - */ - public static boolean isBlank(String string) { - return org.apache.commons.lang.StringUtils.isBlank(string); - } - - /** - * Null-safe comparison of two Strings, returning true if they are equal. - */ - public static boolean equals(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equals(str1, str2); - } - - /** - * Null-safe, case-insensitive comparison of two Strings, returning true if they are equal. - */ - public static boolean equalsIgnoreCase(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equalsIgnoreCase(str1, str2); - } - - public static String stripHtml(CharSequence sequence) { - Matcher m = StringUtils.getPattern("<[^>]*>").matcher(sequence); - return m.replaceAll(""); - } - - /** - * Ensures that the given {@code string} starts with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - return string; - } - - /** - * Ensures that the given {@code string} ends with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - - /** - * Ensures that the given {@code string} starts and ends with - * the given {@code delimiter}, adding them if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts or ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - } - - /** - * @param path If {@code null}, returns {@code null}. - * @param servletPath If {@code null}, returns {@code null}. - */ - public static String getPathInfo(String path, String servletPath) { - if (path != null && servletPath != null) { - path = ensureStart(path, "/"); - servletPath = removeEnd(ensureStart(servletPath, "/"), "/"); - - if (path.startsWith(servletPath)) { - String pathInfo = path.substring(servletPath.length()); - - if (pathInfo.length() == 0) { - return "/"; - - } else if (pathInfo.startsWith("/")) { - return pathInfo; - } - } - } - - return null; - } - - private static final int ASCII_SIZE = 256; - private static final char[] LOWER_CASE_ASCII; - - static { - LOWER_CASE_ASCII = new char[ASCII_SIZE]; - - for (int i = 0; i < ASCII_SIZE; ++ i) { - LOWER_CASE_ASCII[i] = (char) Character.toLowerCase(i); - } - } - - /** - * @param string Can't be {@code null}. - */ - public static String toLowerCaseAscii(String string) { - char[] letters = string.toCharArray(); - char letter; - - for (int i = 0, length = letters.length; i < length; ++ i) { - letter = letters[i]; - - if (letter < ASCII_SIZE) { - letters[i] = LOWER_CASE_ASCII[letter]; - } - } - - return new String(letters); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/old/StringUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/old/StringUtils.java deleted file mode 100755 index 24b96d8..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/old/StringUtils.java +++ /dev/null @@ -1,1216 +0,0 @@ -package com.psddev.dari.util; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.lang.StringEscapeUtils; - -/** String utility methods. */ -public final class StringUtils { - - private StringUtils() { - } - - public static final Charset US_ASCII = Charset.forName("US-ASCII"); - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - public static final Charset UTF_8 = Charset.forName("UTF-8"); - public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); - public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); - public static final Charset UTF_16 = Charset.forName("UTF-16"); - - private static final Set - ABBREVIATIONS = new HashSet(Arrays.asList( - "cms", "css", "id", "js", "seo", "uri", "url")); - - private static final char[] HEX_CHARACTERS = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f' }; - - /** - * Converts given string into a value of given type, throwing an exception - * if conversion was unsuccessful. - * - * If the return type is an array, an array is returned. - * fromString(int[].class, "1", "2") => int[] {1,2} - * - * If no values are provided and the return type is an array, an empty array is returned. - * fromString(int[].class) => int[] {} - * - * If no values are provided and the return type is not an array, an exception - * appropriate to the conversion type is thrown. - * fromString(int.class) => NumberFormatException - * - * If the {@code strings} contains more than one value and the {@code returnType} is not - * an array, all but the first value are ignored. - * - * If the method cannot convert to the class specified, an IllegalArgumentException is thrown. - * - * @param - * @param returnType The class for the String input(s) to be converted to - * @param strings the input(s) to be converted - * @return the converted value - */ - public static T fromString(Class returnType, String... strings) { - - // heavy voodoo follows... - // need to return an array - Class componentType = returnType.getComponentType(); - if (componentType != null) { - if (strings == null) { - return null; - } else { - int length = strings.length; - Object typed = Array.newInstance(componentType, length); - for (int i = 0; i < length; i++) { - Array.set(typed, i, fromString(componentType, strings[i])); - } - return (T) typed; - } - - // single value - } else { - String string = strings == null || strings.length == 0 ? null : strings[0]; - - // string to string - if (String.class == returnType) { - return (T) string; - - // primitives - // pass null through if returnType allows it - } else if (string == null && !returnType.isPrimitive()) { - return null; - - // any way to avoid boxing/unboxing on primitives? - } else if (boolean.class == returnType || Boolean.class.isAssignableFrom(returnType)) { - return (T) Boolean.valueOf(string); - } else if (byte.class == returnType || Byte.class.isAssignableFrom(returnType)) { - return (T) Byte.valueOf(string); - } else if (short.class == returnType || Short.class.isAssignableFrom(returnType)) { - return (T) Short.valueOf(string); - } else if (int.class == returnType || Integer.class.isAssignableFrom(returnType)) { - return (T) Integer.valueOf(string); - } else if (long.class == returnType || Long.class.isAssignableFrom(returnType)) { - return (T) Long.valueOf(string); - } else if (float.class == returnType || Float.class.isAssignableFrom(returnType)) { - return (T) Float.valueOf(string); - } else if (double.class == returnType || Double.class.isAssignableFrom(returnType)) { - return (T) Double.valueOf(string); - } else if (char.class == returnType || Character.class.isAssignableFrom(returnType)) { - if (string.length() == 1) { - return (T) Character.valueOf(string.charAt(0)); - } - - // others - } else if (Date.class.isAssignableFrom(returnType)) { - return (T) DateUtils.fromString(string); - } - throw new IllegalArgumentException(String.format( - "Cannot convert [%s] string to [%s] type!", - string, - returnType.getName() - )); - } - } - - - /** - * Helper method to split a string by case change or common delimiters. - * - * Multiple delimeters in a row are reduced to a single word boundry. - * - * Leading delimeters (a space at the beginning of the string) will cause an - * empty first word to be detected (bug?). Trailing delemeters do not cause empty - * words to be detected. - * - * Returned words are all lowercased. - * - * @param string - * @return the list of words detected in the string - */ - protected static List splitString(String string) { - List words = new ArrayList(); - int m = 0, l = string.length(); - for (int i = 0; i < l; i++) { - char c = string.charAt(i); - if (" -_.$".indexOf(c) > -1) { - words.add(string.substring(m, i).toLowerCase()); - while (++i < l && " -_.$".indexOf(string.charAt(i)) > -1) { - } - m = i; - } else if (Character.isUpperCase(c) && i > 0 && Character.isLowerCase(string.charAt(i - 1))) { - words.add(string.substring(m, i).toLowerCase()); - m = i; - } - } - if (m + 1 < l) { - words.add(string.substring(m).toLowerCase()); - } - return words; - } - - /** - * Tries to detect words within a given string and join them with the given delimiter. - */ - public static String toDelimited(String string, String delimiter) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(word).append(delimiter); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - delimiter.length()); - } - return nb.toString(); - } - - /** - * Converts the given string into a-hyphenated-string. - */ - public static String toHyphenated(String string) { - return toDelimited(string, "-"); - } - - /** - * Converts the given string into a_underscored_string. - */ - public static String toUnderscored(String string) { - return toDelimited(string, "_"); - } - - /** - * Converts the given string into APascalCaseString. - */ - public static String toPascalCase(String string) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); - } - return nb.toString(); - } - - /** - * Converts the given string into aCamelCaseString. - */ - public static String toCamelCase(String string) { - string = toPascalCase(string); - return Character.toLowerCase(string.charAt(0)) + string.substring(1); - } - - /** - * Converts the string to one suitable for use as "a label"? - * - * Splits {@code string} into words, joining it back together "In Title Case" - * with known {@code ABBREVIATIONS} replaced in all caps. If the first word of - * {@code string} is "is", that word is removed and a question mark is - * added to the end of the resulting string. - * - * @param string - */ - public static String toLabel(String string) { - - if (string == null) { - return null; - } - - boolean isQuestion = false; - List words = splitString(string); - if (words.size() > 0 && "is".equals(words.get(0))) { - isQuestion = true; - words.remove(0); - } - - StringBuilder nb = new StringBuilder(); - for (String word : words) { - if (word.length() == 0) { - continue; - } - - if (ABBREVIATIONS.contains(word)) { - nb.append(word.toUpperCase()); - } else { - nb.append(Character.toUpperCase(word.charAt(0))); - nb.append(word.substring(1)); - } - nb.append(' '); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - 1); - } - - if (isQuestion) { - nb.append('?'); - } - - return nb.toString(); - } - - /** - * Normalizes a string, removing or replacing non-alphanumeric characters and lowercasing - * - * - Removes all accented characters. - * - Removes single quotes - * - Replaces non-alphanumeric characters remaining with a dash - * - Removes dashes - * - * Lowercases the result - */ - public static String toNormalized(CharSequence string) { - return string == null ? null : replaceAll( - Normalizer.normalize(string, Normalizer.Form.NFD), - "[^\\p{ASCII}]", "", - "'", "", - "\\.", "", - "[^a-zA-Z0-9]+", "-", - "^-+|-+$", "" - ).toLowerCase(); - } - - /** Splits the given string by commas, and returns each part unescaped. - * Calling {@link #toCsv(String...)} on an array of Strings and then - * passing the result to this method will always return the same array - * as specified by the Arrays.equals() method. */ - public static String[] fromCsv(String string) { - if(string == null) { - return null; - } else { - // replaces a call to string.split(",") - char[] charArr = string.toCharArray(); - int commaCount = 0; - for (char c : charArr) { - if (c == ',') { - commaCount++; - } - } - String[] escaped = new String[commaCount+1]; - int index = 0; - int offset = 0; - int count = 0; - for (char c : charArr) { - if (c == ',') { - escaped[index++] = new String(charArr, offset, count); - offset += count+1; - count = 0; - } else { - count++; - } - } - if (index == commaCount) { - escaped[index] = new String(charArr, offset, count); - } - // end string.split(",") replacement code - - int length = escaped.length; - List unescaped = new ArrayList(); - for(int i = 0; i < length; i ++) { - String value = escaped[i]; - if(value.startsWith("\"")) { // there are commas and/or double quotes escaped within - StringBuilder builder = new StringBuilder(); - int quoteCount = 0; - do { - builder.append(value); - for(char c : value.toCharArray()) { - if(c == '"') { - quoteCount++; - } - } - if(quoteCount % 2 == 1) { - value = escaped[++i]; - builder.append(','); - } - } while(quoteCount % 2 == 1); - value = builder.toString(); - } - unescaped.add(StringUtils.unescapeCsv(value)); - } - return unescaped.toArray(new String[unescaped.size()]); - } - } - - /** Converts an array of Strings to a single String in comma separated - * values format, escaping each string as necessary. */ - public static String toCsv(String... strings) { - if (strings == null) { - return null; - } - StringBuilder builder = new StringBuilder(); - for (String string : strings) { - builder.append(escapeCsv(string)).append(','); - } - if (builder.length() > 0) { - builder.setLength(builder.length()-1); - } - return builder.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string, int maxWordLength) { - if (string == null) { - return null; - } - Matcher matcher = getMatcher(string, String.format("(\\S{%d,})", maxWordLength)); - StringBuilder output = new StringBuilder(); - int marker = 0; - while (matcher.find()) { - String longWord = matcher.group(1); - - // similar to Matcher.appendReplacement - // re-implemented so that $ and \ does not have to be escaped - if (matcher.start() > marker) { - output.append(string.substring(marker, matcher.start())); - } - int i = 0; - for (; i < longWord.length() - maxWordLength; i += maxWordLength) { - output.append(escapeHtml(longWord.substring(i, i + maxWordLength))); - output.append(""); - } - output.append(escapeHtml(longWord.substring(i))); - marker = matcher.end(); - } - - // similar to Matcher.appendTail - output.append(string.substring(marker)); - return output.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string) { - return escapeHtmlAndBreak(string, 20); - } - - /** Converts the given {@code bytes} into a hex string. */ - public static String hex(byte[] bytes) { - if (bytes == null) { - return null; - } - - int bytesLength = bytes.length; - byte currentByte; - char[] hex = new char[bytesLength * 2]; - - for (int byteIndex = 0, hexIndex = 0; - byteIndex < bytesLength; - ++ byteIndex, hexIndex += 2) { - - currentByte = bytes[byteIndex]; - hex[hexIndex] = HEX_CHARACTERS[(currentByte & 0xf0) >> 4]; - hex[hexIndex + 1] = HEX_CHARACTERS[(currentByte & 0x0f)]; - } - - return new String(hex); - } - - /** Hashes the given {@code string} using the given {@code algorithm}. */ - public static byte[] hash(String algorithm, String string) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance(algorithm); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid hash algorithm!", algorithm), ex); - } - - byte[] bytes; - try { - bytes = string.getBytes("UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - - return digest.digest(bytes); - } - - /** Hashes the given {@code string} using the MD5 algorithm. */ - public static byte[] md5(String string) { - return hash("MD5", string); - } - - /** Hashes the given {@code string} using the SHA-1 algorithm. */ - public static byte[] sha1(String string) { - return hash("SHA-1", string); - } - - /** Hashes the given {@code string} using the SHA-512 algorithm. */ - public static byte[] sha512(String string) { - return hash("SHA-512", string); - } - - /** - * Hashes the given {@code string} using the given HMAC {@code algorithm} - * and {@code key}. - */ - public static byte[] hmac(String algorithm, String key, String string) { - try { - Mac mac = Mac.getInstance(algorithm); - mac.init(new SecretKeySpec(key.getBytes(StringUtils.UTF_8), algorithm)); - return mac.doFinal(string.getBytes(StringUtils.UTF_8)); - - } catch (NoSuchAlgorithmException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid HMAC algorithm!", algorithm), error); - - } catch (InvalidKeyException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid key!", key), error); - } - } - - /** - * Hashes the given {@code string} using the HMAC SHA-1 algorithm - * and the given {@code key}. - */ - public static byte[] hmacSha1(String key, String string) { - return hmac("HmacSHA1", key, string); - } - - // --- URL/URI --- - - /** - * Encodes the given UTF-8 {@code string} so that it's safe for use - * within an URI. - */ - public static String encodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLEncoder.encode(string, "UTF-8").replace("+", "%20"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** Decodes the given URI-encoded, UTF-8 {@code string}. */ - public static String decodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLDecoder.decode(string, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** - * Adds the given {@code parameters} as a query string to the given - * {@code uri}. - */ - public static String addQueryParameters(String uri, Object... parameters) { - if (uri == null) { - return null; - } - - // Convert "path?a=b&c=d" to "&a=b&c=d". - StringBuilder query = new StringBuilder(); - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - - String queryString = uri.substring(questionAt + 1); - int beginAt = 0; - - // make sure all the query parameters are encoded - while (true) { - int ampIndex = queryString.indexOf('&', beginAt); - - String param = queryString.substring(beginAt, ampIndex > -1 ? ampIndex : queryString.length()); - - if (!param.isEmpty() || ampIndex > -1) { - query.append('&'); - - int equalsIndex = param.indexOf('='); - if (equalsIndex > -1) { - query.append(encodeUri(decodeUri(param.substring(0, equalsIndex)))); - query.append('='); - query.append(encodeUri(decodeUri(param.substring(equalsIndex+1)))); - - } else { - query.append(encodeUri(decodeUri(param))); - } - } - - if (ampIndex > -1) { - beginAt = ampIndex+1; - } else { - break; - } - } - - uri = uri.substring(0, questionAt); - } - - int parametersLength = parameters != null ? parameters.length : 0; - - for (int i = 0; i < parametersLength; i += 2) { - - // Remove all occurrences of "&name=". - String name = parameters[i].toString(); - String prefix = "&" + name + "="; - int prefixLength = prefix.length(); - int beginAt = 0; - int endAt; - while (true) { - - beginAt = query.indexOf(prefix, beginAt); - if (beginAt < 0) { - break; - } - - endAt = query.indexOf("&", beginAt + prefixLength); - if (endAt > -1) { - query.delete(beginAt, endAt); - - } else { - query.delete(beginAt, query.length()); - break; - } - } - - // Append "&name=value". - if (i + 1 < parametersLength) { - Object value = parameters[i + 1]; - if (value != null) { - for (Object item : ObjectUtils.to(Iterable.class, value)) { - if (item != null) { - query.append('&'); - query.append(encodeUri(name)); - query.append('='); - query.append(encodeUri(item instanceof Enum ? - ((Enum) item).name() : - item.toString())); - } - } - } - } - } - - // Reconstruct the URI. - if (query.length() <= 1) { - return uri; - - } else { - query.delete(0, 1); - query.insert(0, "?"); - query.insert(0, uri); - return query.toString(); - } - } - - /** - * Returns the first query parameter value associated with the given - * {@code name} from the given {@code uri}. - */ - public static String getQueryParameterValue(String uri, String name) { - for (String value : getQueryParameterValues(uri, name)) { - return value; - } - return null; - } - - /** - * Returns a list of query parameter values associated with the given - * {@code name} from the given {@code uri}. - */ - public static List getQueryParameterValues(String uri, String name) { - List values = new ArrayList(); - if (uri != null) { - - // Strip out the path before the query string. - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - uri = uri.substring(questionAt + 1); - } - uri = "&" + uri; - - // Find all occurences of "&name=". - String prefix = "&" + encodeUri(name) + "="; - int prefixLength = prefix.length(); - for (int nameAt = 0; (nameAt = uri.indexOf(prefix, nameAt)) > -1;) { - nameAt += prefixLength; - int andAt = uri.indexOf('&', nameAt); - values.add(decodeUri(andAt > -1 ? - uri.substring(nameAt, andAt) : - uri.substring(nameAt))); - } - } - - return values; - } - - /** Returns a map of query parameters from the given {@code url}. */ - public static Map> getQueryParameterMap(String url) { - Map> map = new LinkedHashMap>(); - - if (url != null) { - int questionAt = url.indexOf('?'); - - if (questionAt > -1) { - url = url.substring(questionAt + 1); - } - - int lastAndAt = 0; - - for (int andAt; - (andAt = url.indexOf('&', lastAndAt)) > -1; - lastAndAt = andAt + 1) { - addParameter(map, url.substring(lastAndAt, andAt)); - } - - addParameter(map, url.substring(lastAndAt)); - } - - return map; - } - - private static void addParameter(Map> map, String pair) { - if (pair == null || pair.length() == 0) { - return; - } - - int equalAt = pair.indexOf('='); - String name; - String value; - - if (equalAt > -1) { - name = decodeUri(pair.substring(0, equalAt)); - value = decodeUri(pair.substring(equalAt + 1)); - - } else { - name = decodeUri(pair); - value = null; - } - - List parameters = map.get(name); - - if (parameters == null) { - parameters = new ArrayList(); - map.put(name, parameters); - } - - parameters.add(value); - } - - /** @deprecated Use {@link #addQueryParameters instead}. */ - @Deprecated - public static String transformUri(String uri, Object... parameters) { - return addQueryParameters(uri, parameters); - } - - /** @deprecated Use {@link #getQueryParameterValue instead}. */ - @Deprecated - public static String getParameter(String uri, String name) { - return getQueryParameterValue(uri, name); - } - - /** @deprecated Use {@link #getQueryParameterValues instead}. */ - @Deprecated - public static String[] getParameterValues(String uri, String name) { - List values = getQueryParameterValues(uri, name); - return values.toArray(new String[values.size()]); - } - - // --- Pattern bridge --- - private static final Map _patterns = new PullThroughCache() { - @Override - protected Pattern produce(String pattern) { - return Pattern.compile(pattern); - } - }; - - /** - * Gets a cached regular expression pattern object based on the given string. - */ - public static Pattern getPattern(String pattern) { - return _patterns.get(pattern); - } - - /** - * Gets a regular expression matcher based on the given string and pattern. - * - * @see #getPattern(String) - */ - public static Matcher getMatcher(CharSequence string, String pattern) { - return getPattern(pattern).matcher(string); - } - - /** - * Helper function that finds all groups in a regex and returns them in a result. find() is called automatically. - */ - public static MatchResult getMatcherResult(CharSequence string, String pattern) { - Matcher matcher = getMatcher(string, pattern); - matcher.find(); - final MatchResult result = matcher.toMatchResult(); - - - return new MatchResult() { - @Override - public int start() { - return result.start(); - } - - @Override - public int start(int group) { - return result.start(group); - } - - @Override - public int end() { - return result.end(); - } - - @Override - public int end(int group) { - return result.end(group); - } - - @Override - public String group() { - return result.group(); - } - - @Override - public String group(int group) { - try { - return result.group(group); - } catch (IllegalStateException e) { - return null; - } catch (IndexOutOfBoundsException e) { - return null; - } - } - - @Override - public int groupCount() { - return result.groupCount(); - } - }; - } - - /** - * Compiles the given regular expression pattern and attempts to match the given string against it. - * - * @see #getMatcher(CharSequence, String). - */ - public static boolean matches(CharSequence string, String pattern) { - return getMatcher(string, pattern).matches(); - } - - public static boolean matchAll(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return false; - } - } - - return true; - } - - public static boolean matchAny(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return true; - } - } - - return false; - } - - public static int matchCount(CharSequence string, String... patterns) { - int count = 0; - for (String pattern : patterns) { - if (matches(string, pattern)) { - ++count; - } - } - - return count; - } - - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #getMatcher(CharSequence, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement) { - return getMatcher(string, pattern).replaceAll(replacement); - } - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #replaceAll(CharSequence, String, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement, String... more) { - String r = replaceAll(string, pattern, replacement); - for (int i = 0, l = more.length; i < l; i += 2) { - r = replaceAll(r, more[i], i + 1 < l ? more[i + 1] : ""); - } - return r; - } - - /** - * Removes a without using regex * - */ - public static String removeAll(CharSequence string, CharSequence pattern) { - if (string == null) { - throw new IllegalArgumentException("String input is null"); - } - if (pattern != null) { - StringBuilder builder = new StringBuilder(string); - String p = pattern.toString(); - int l = pattern.length(); - for (int index; (index = builder.indexOf(p)) > -1;) { - builder.delete(index, index + l); - } - return builder.toString(); - } else { - return string.toString(); - } - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern, int limit) { - return getPattern(pattern).split(string, limit); - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern) { - return getPattern(pattern).split(string); - } - - // --- StringEscapeUtils bridge --- - - public static String escapeCsv(String string) { - return string == null ? null : StringEscapeUtils.escapeCsv(string); - } - - public static String escapeHtml(String string) { - return string == null ? null : StringUtils.replaceAll( - StringEscapeUtils.escapeHtml(string), - "\\x22", """, // double quote - "\\x27", "'"); // single quote - } - - public static String escapeJava(String string) { - return string == null ? null : StringEscapeUtils.escapeJava(string); - } - - /** - * Escapes the input string so that the resulting output can be used - * inside a JavaScript string AND none of the characters in the output - * need to be HTML escaped. - * @param string - * @return the escaped string, or null if the input was null - * This is not the same as HTML escaping a JavaScript escaped string, - * since the output can be used directly in a JavaScript string even - * when HTML-unescaping won't happen. - */ - public static String escapeJavaScript(String string) { - if (string == null) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0, s = string.length(); i < s; ++ i) { - char c = string.charAt(i); - if (0x30 <= c && c <= 0x39 - || 0x41 <= c && c <= 0x5A - || 0x61 <= c && c <= 0x7A) { - sb.append(c); - } else { - String hex = Integer.toHexString(c); - int hexLen = hex.length(); - if (c < 256) { - sb.append("\\x").append("00".substring(hexLen)); - } else { - sb.append("\\u").append("0000".substring(hexLen)); - } - sb.append(hex); - } - } - return sb.toString(); - } - - public static String escapeQuotes(String string) { - return string == null ? null : string.replace("\\", "\\\\").replace("\"", "\\\""); - } - - public static String escapeSql(String string) { - return string == null ? null : StringEscapeUtils.escapeSql(string); - } - - public static String escapeXml(String string) { - return string == null ? null : StringEscapeUtils.escapeXml(string); - } - - public static String unescapeCsv(String string) { - return string == null ? null : StringEscapeUtils.unescapeCsv(string); - } - - public static String unescapeHtml(String string) { - return string == null ? null : StringEscapeUtils.unescapeHtml(string); - } - - public static String unescapeJava(String string) { - return string == null ? null : StringEscapeUtils.unescapeJava(string); - } - - public static String unescapeJavaScript(String string) { - return string == null ? null : StringEscapeUtils.unescapeJavaScript(string); - } - - public static String unescapeXml(String string) { - return string == null ? null : StringEscapeUtils.unescapeXml(string); - } - - // --- StringUtils bridge --- - - /** - * Joins the given list of strings with the given delimiter in between. - */ - public static String join(List strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Joins the given array of strings with the given delimiter in between. - */ - public static String join(String[] strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Checks if a String is empty ("") or null. - */ - public static boolean isEmpty(String string) { - return org.apache.commons.lang.StringUtils.isEmpty(string); - } - - /** - * Checks if a String is whitespace, empty ("") or null. - */ - public static boolean isBlank(String string) { - return org.apache.commons.lang.StringUtils.isBlank(string); - } - - /** - * Null-safe comparison of two Strings, returning true if they are equal. - */ - public static boolean equals(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equals(str1, str2); - } - - /** - * Null-safe, case-insensitive comparison of two Strings, returning true if they are equal. - */ - public static boolean equalsIgnoreCase(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equalsIgnoreCase(str1, str2); - } - - public static String stripHtml(CharSequence sequence) { - Matcher m = StringUtils.getPattern("<[^>]*>").matcher(sequence); - return m.replaceAll(""); - } - - /** - * Ensures that the given {@code string} starts with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - return string; - } - - /** - * Ensures that the given {@code string} ends with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - - /** - * Ensures that the given {@code string} starts and ends with - * the given {@code delimiter}, adding them if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts or ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - } - - /** - * @param path If {@code null}, returns {@code null}. - * @param servletPath If {@code null}, returns {@code null}. - */ - public static String getPathInfo(String path, String servletPath) { - if (path != null && servletPath != null) { - path = ensureStart(path, "/"); - servletPath = removeEnd(ensureStart(servletPath, "/"), "/"); - - if (path.startsWith(servletPath)) { - String pathInfo = path.substring(servletPath.length()); - - if (pathInfo.length() == 0) { - return "/"; - - } else if (pathInfo.startsWith("/")) { - return pathInfo; - } - } - } - - return null; - } - - private static final int ASCII_SIZE = 256; - private static final char[] LOWER_CASE_ASCII; - - static { - LOWER_CASE_ASCII = new char[ASCII_SIZE]; - - for (int i = 0; i < ASCII_SIZE; ++ i) { - LOWER_CASE_ASCII[i] = (char) Character.toLowerCase(i); - } - } - - /** - * @param string Can't be {@code null}. - */ - public static String toLowerCaseAscii(String string) { - char[] letters = string.toCharArray(); - char letter; - - for (int i = 0, length = letters.length; i < length; ++ i) { - letter = letters[i]; - - if (letter < ASCII_SIZE) { - letters[i] = LOWER_CASE_ASCII[letter]; - } - } - - return new String(letters); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/pair.info deleted file mode 100755 index 2a4311b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52742/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:52742 -comSha:a2c1974da04a01bcebd1251b487b72e3c2ac90af -parentComSha:d019326625ce2c1c2469ada51de6696b9e3fca45 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/StringUtils.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/StringUtils.java -StartLineNum:249 -EndLineNum:249 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/comMsg.txt deleted file mode 100755 index 197a716..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of DM_CONVERT_CASE from FindBugs. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/diff.diff deleted file mode 100755 index 46575c1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/StringUtils.java b/util/src/main/java/com/psddev/dari/util/StringUtils.java -index 884d1982..428c3cf1 100644 ---- a/util/src/main/java/com/psddev/dari/util/StringUtils.java -+++ b/util/src/main/java/com/psddev/dari/util/StringUtils.java -@@ -155 +155 @@ public final class StringUtils { -- words.add(string.substring(m, i).toLowerCase()); -+ words.add(string.substring(m, i).toLowerCase(Locale.ENGLISH)); -@@ -160 +160 @@ public final class StringUtils { -- words.add(string.substring(m, i).toLowerCase()); -+ words.add(string.substring(m, i).toLowerCase(Locale.ENGLISH)); -@@ -165 +165 @@ public final class StringUtils { -- words.add(string.substring(m).toLowerCase()); -+ words.add(string.substring(m).toLowerCase(Locale.ENGLISH)); -@@ -283 +283 @@ public final class StringUtils { -- ).toLowerCase(); -+ ).toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/new/StringUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/new/StringUtils.java deleted file mode 100755 index 428c3cf..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/new/StringUtils.java +++ /dev/null @@ -1,1214 +0,0 @@ -package com.psddev.dari.util; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.lang.StringEscapeUtils; - -/** String utility methods. */ -public final class StringUtils { - - public static final Charset US_ASCII = Charset.forName("US-ASCII"); - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - public static final Charset UTF_8 = Charset.forName("UTF-8"); - public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); - public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); - public static final Charset UTF_16 = Charset.forName("UTF-16"); - - private static final Set - ABBREVIATIONS = new HashSet(Arrays.asList( - "cms", "css", "id", "js", "seo", "uri", "url")); - - private static final char[] HEX_CHARACTERS = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f' }; - - /** - * Converts given string into a value of given type, throwing an exception - * if conversion was unsuccessful. - * - * If the return type is an array, an array is returned. - * fromString(int[].class, "1", "2") => int[] {1,2} - * - * If no values are provided and the return type is an array, an empty array is returned. - * fromString(int[].class) => int[] {} - * - * If no values are provided and the return type is not an array, an exception - * appropriate to the conversion type is thrown. - * fromString(int.class) => NumberFormatException - * - * If the {@code strings} contains more than one value and the {@code returnType} is not - * an array, all but the first value are ignored. - * - * If the method cannot convert to the class specified, an IllegalArgumentException is thrown. - * - * @param - * @param returnType The class for the String input(s) to be converted to - * @param strings the input(s) to be converted - * @return the converted value - */ - public static T fromString(Class returnType, String... strings) { - - // heavy voodoo follows... - // need to return an array - Class componentType = returnType.getComponentType(); - if (componentType != null) { - if (strings == null) { - return null; - } else { - int length = strings.length; - Object typed = Array.newInstance(componentType, length); - for (int i = 0; i < length; i++) { - Array.set(typed, i, fromString(componentType, strings[i])); - } - return (T) typed; - } - - // single value - } else { - String string = strings == null || strings.length == 0 ? null : strings[0]; - - // string to string - if (String.class == returnType) { - return (T) string; - - // primitives - // pass null through if returnType allows it - } else if (string == null && !returnType.isPrimitive()) { - return null; - - // any way to avoid boxing/unboxing on primitives? - } else if (boolean.class == returnType || Boolean.class.isAssignableFrom(returnType)) { - return (T) Boolean.valueOf(string); - } else if (byte.class == returnType || Byte.class.isAssignableFrom(returnType)) { - return (T) Byte.valueOf(string); - } else if (short.class == returnType || Short.class.isAssignableFrom(returnType)) { - return (T) Short.valueOf(string); - } else if (int.class == returnType || Integer.class.isAssignableFrom(returnType)) { - return (T) Integer.valueOf(string); - } else if (long.class == returnType || Long.class.isAssignableFrom(returnType)) { - return (T) Long.valueOf(string); - } else if (float.class == returnType || Float.class.isAssignableFrom(returnType)) { - return (T) Float.valueOf(string); - } else if (double.class == returnType || Double.class.isAssignableFrom(returnType)) { - return (T) Double.valueOf(string); - } else if (char.class == returnType || Character.class.isAssignableFrom(returnType)) { - if (string.length() == 1) { - return (T) Character.valueOf(string.charAt(0)); - } - - // others - } else if (Date.class.isAssignableFrom(returnType)) { - return (T) DateUtils.fromString(string); - } - throw new IllegalArgumentException(String.format( - "Cannot convert [%s] string to [%s] type!", - string, - returnType.getName() - )); - } - } - - - /** - * Helper method to split a string by case change or common delimiters. - * - * Multiple delimeters in a row are reduced to a single word boundry. - * - * Leading delimeters (a space at the beginning of the string) will cause an - * empty first word to be detected (bug?). Trailing delemeters do not cause empty - * words to be detected. - * - * Returned words are all lowercased. - * - * @param string - * @return the list of words detected in the string - */ - protected static List splitString(String string) { - List words = new ArrayList(); - int m = 0, l = string.length(); - for (int i = 0; i < l; i++) { - char c = string.charAt(i); - if (" -_.$".indexOf(c) > -1) { - words.add(string.substring(m, i).toLowerCase(Locale.ENGLISH)); - while (++i < l && " -_.$".indexOf(string.charAt(i)) > -1) { - } - m = i; - } else if (Character.isUpperCase(c) && i > 0 && Character.isLowerCase(string.charAt(i - 1))) { - words.add(string.substring(m, i).toLowerCase(Locale.ENGLISH)); - m = i; - } - } - if (m + 1 < l) { - words.add(string.substring(m).toLowerCase(Locale.ENGLISH)); - } - return words; - } - - /** - * Tries to detect words within a given string and join them with the given delimiter. - */ - public static String toDelimited(String string, String delimiter) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(word).append(delimiter); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - delimiter.length()); - } - return nb.toString(); - } - - /** - * Converts the given string into a-hyphenated-string. - */ - public static String toHyphenated(String string) { - return toDelimited(string, "-"); - } - - /** - * Converts the given string into a_underscored_string. - */ - public static String toUnderscored(String string) { - return toDelimited(string, "_"); - } - - /** - * Converts the given string into APascalCaseString. - */ - public static String toPascalCase(String string) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); - } - return nb.toString(); - } - - /** - * Converts the given string into aCamelCaseString. - */ - public static String toCamelCase(String string) { - string = toPascalCase(string); - return Character.toLowerCase(string.charAt(0)) + string.substring(1); - } - - /** - * Converts the string to one suitable for use as "a label"? - * - * Splits {@code string} into words, joining it back together "In Title Case" - * with known {@code ABBREVIATIONS} replaced in all caps. If the first word of - * {@code string} is "is", that word is removed and a question mark is - * added to the end of the resulting string. - * - * @param string - */ - public static String toLabel(String string) { - - if (string == null) { - return null; - } - - boolean isQuestion = false; - List words = splitString(string); - if (words.size() > 0 && "is".equals(words.get(0))) { - isQuestion = true; - words.remove(0); - } - - StringBuilder nb = new StringBuilder(); - for (String word : words) { - if (word.length() == 0) { - continue; - } - - if (ABBREVIATIONS.contains(word)) { - nb.append(word.toUpperCase(Locale.ENGLISH)); - } else { - nb.append(Character.toUpperCase(word.charAt(0))); - nb.append(word.substring(1)); - } - nb.append(' '); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - 1); - } - - if (isQuestion) { - nb.append('?'); - } - - return nb.toString(); - } - - /** - * Normalizes a string, removing or replacing non-alphanumeric characters and lowercasing - * - * - Removes all accented characters. - * - Removes single quotes - * - Replaces non-alphanumeric characters remaining with a dash - * - Removes dashes - * - * Lowercases the result - */ - public static String toNormalized(CharSequence string) { - return string == null ? null : replaceAll( - Normalizer.normalize(string, Normalizer.Form.NFD), - "[^\\p{ASCII}]", "", - "'", "", - "\\.", "", - "[^a-zA-Z0-9]+", "-", - "^-+|-+$", "" - ).toLowerCase(Locale.ENGLISH); - } - - /** Splits the given string by commas, and returns each part unescaped. - * Calling {@link #toCsv(String...)} on an array of Strings and then - * passing the result to this method will always return the same array - * as specified by the Arrays.equals() method. */ - public static String[] fromCsv(String string) { - if(string == null) { - return null; - } else { - // replaces a call to string.split(",") - char[] charArr = string.toCharArray(); - int commaCount = 0; - for (char c : charArr) { - if (c == ',') { - commaCount++; - } - } - String[] escaped = new String[commaCount+1]; - int index = 0; - int offset = 0; - int count = 0; - for (char c : charArr) { - if (c == ',') { - escaped[index++] = new String(charArr, offset, count); - offset += count+1; - count = 0; - } else { - count++; - } - } - if (index == commaCount) { - escaped[index] = new String(charArr, offset, count); - } - // end string.split(",") replacement code - - int length = escaped.length; - List unescaped = new ArrayList(); - for(int i = 0; i < length; i ++) { - String value = escaped[i]; - if(value.startsWith("\"")) { // there are commas and/or double quotes escaped within - StringBuilder builder = new StringBuilder(); - int quoteCount = 0; - do { - builder.append(value); - for(char c : value.toCharArray()) { - if(c == '"') { - quoteCount++; - } - } - if(quoteCount % 2 == 1) { - value = escaped[++i]; - builder.append(','); - } - } while(quoteCount % 2 == 1); - value = builder.toString(); - } - unescaped.add(StringUtils.unescapeCsv(value)); - } - return unescaped.toArray(new String[unescaped.size()]); - } - } - - /** Converts an array of Strings to a single String in comma separated - * values format, escaping each string as necessary. */ - public static String toCsv(String... strings) { - if (strings == null) { - return null; - } - StringBuilder builder = new StringBuilder(); - for (String string : strings) { - builder.append(escapeCsv(string)).append(','); - } - if (builder.length() > 0) { - builder.setLength(builder.length()-1); - } - return builder.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string, int maxWordLength) { - if (string == null) { - return null; - } - Matcher matcher = getMatcher(string, String.format("(\\S{%d,})", maxWordLength)); - StringBuilder output = new StringBuilder(); - int marker = 0; - while (matcher.find()) { - String longWord = matcher.group(1); - - // similar to Matcher.appendReplacement - // re-implemented so that $ and \ does not have to be escaped - if (matcher.start() > marker) { - output.append(string.substring(marker, matcher.start())); - } - int i = 0; - for (; i < longWord.length() - maxWordLength; i += maxWordLength) { - output.append(escapeHtml(longWord.substring(i, i + maxWordLength))); - output.append(""); - } - output.append(escapeHtml(longWord.substring(i))); - marker = matcher.end(); - } - - // similar to Matcher.appendTail - output.append(string.substring(marker)); - return output.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string) { - return escapeHtmlAndBreak(string, 20); - } - - /** Converts the given {@code bytes} into a hex string. */ - public static String hex(byte[] bytes) { - if (bytes == null) { - return null; - } - - int bytesLength = bytes.length; - byte currentByte; - char[] hex = new char[bytesLength * 2]; - - for (int byteIndex = 0, hexIndex = 0; - byteIndex < bytesLength; - ++ byteIndex, hexIndex += 2) { - - currentByte = bytes[byteIndex]; - hex[hexIndex] = HEX_CHARACTERS[(currentByte & 0xf0) >> 4]; - hex[hexIndex + 1] = HEX_CHARACTERS[(currentByte & 0x0f)]; - } - - return new String(hex); - } - - /** Hashes the given {@code string} using the given {@code algorithm}. */ - public static byte[] hash(String algorithm, String string) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance(algorithm); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid hash algorithm!", algorithm), ex); - } - - byte[] bytes; - try { - bytes = string.getBytes("UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - - return digest.digest(bytes); - } - - /** Hashes the given {@code string} using the MD5 algorithm. */ - public static byte[] md5(String string) { - return hash("MD5", string); - } - - /** Hashes the given {@code string} using the SHA-1 algorithm. */ - public static byte[] sha1(String string) { - return hash("SHA-1", string); - } - - /** Hashes the given {@code string} using the SHA-512 algorithm. */ - public static byte[] sha512(String string) { - return hash("SHA-512", string); - } - - /** - * Hashes the given {@code string} using the given HMAC {@code algorithm} - * and {@code key}. - */ - public static byte[] hmac(String algorithm, String key, String string) { - try { - Mac mac = Mac.getInstance(algorithm); - mac.init(new SecretKeySpec(key.getBytes(StringUtils.UTF_8), algorithm)); - return mac.doFinal(string.getBytes(StringUtils.UTF_8)); - - } catch (NoSuchAlgorithmException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid HMAC algorithm!", algorithm), error); - - } catch (InvalidKeyException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid key!", key), error); - } - } - - /** - * Hashes the given {@code string} using the HMAC SHA-1 algorithm - * and the given {@code key}. - */ - public static byte[] hmacSha1(String key, String string) { - return hmac("HmacSHA1", key, string); - } - - // --- URL/URI --- - - /** - * Encodes the given UTF-8 {@code string} so that it's safe for use - * within an URI. - */ - public static String encodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLEncoder.encode(string, "UTF-8").replace("+", "%20"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** Decodes the given URI-encoded, UTF-8 {@code string}. */ - public static String decodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLDecoder.decode(string, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** - * Adds the given {@code parameters} as a query string to the given - * {@code uri}. - */ - public static String addQueryParameters(String uri, Object... parameters) { - if (uri == null) { - return null; - } - - // Convert "path?a=b&c=d" to "&a=b&c=d". - StringBuilder query = new StringBuilder(); - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - - String queryString = uri.substring(questionAt + 1); - int beginAt = 0; - - // make sure all the query parameters are encoded - while (true) { - int ampIndex = queryString.indexOf('&', beginAt); - - String param = queryString.substring(beginAt, ampIndex > -1 ? ampIndex : queryString.length()); - - if (!param.isEmpty() || ampIndex > -1) { - query.append('&'); - - int equalsIndex = param.indexOf('='); - if (equalsIndex > -1) { - query.append(encodeUri(decodeUri(param.substring(0, equalsIndex)))); - query.append('='); - query.append(encodeUri(decodeUri(param.substring(equalsIndex+1)))); - - } else { - query.append(encodeUri(decodeUri(param))); - } - } - - if (ampIndex > -1) { - beginAt = ampIndex+1; - } else { - break; - } - } - - uri = uri.substring(0, questionAt); - } - - int parametersLength = parameters != null ? parameters.length : 0; - - for (int i = 0; i < parametersLength; i += 2) { - - // Remove all occurrences of "&name=". - String name = parameters[i].toString(); - String prefix = "&" + name + "="; - int prefixLength = prefix.length(); - int beginAt = 0; - int endAt; - while (true) { - - beginAt = query.indexOf(prefix, beginAt); - if (beginAt < 0) { - break; - } - - endAt = query.indexOf("&", beginAt + prefixLength); - if (endAt > -1) { - query.delete(beginAt, endAt); - - } else { - query.delete(beginAt, query.length()); - break; - } - } - - // Append "&name=value". - if (i + 1 < parametersLength) { - Object value = parameters[i + 1]; - if (value != null) { - for (Object item : ObjectUtils.to(Iterable.class, value)) { - if (item != null) { - query.append('&'); - query.append(encodeUri(name)); - query.append('='); - query.append(encodeUri(item instanceof Enum ? - ((Enum) item).name() : - item.toString())); - } - } - } - } - } - - // Reconstruct the URI. - if (query.length() <= 1) { - return uri; - - } else { - query.delete(0, 1); - query.insert(0, "?"); - query.insert(0, uri); - return query.toString(); - } - } - - /** - * Returns the first query parameter value associated with the given - * {@code name} from the given {@code uri}. - */ - public static String getQueryParameterValue(String uri, String name) { - for (String value : getQueryParameterValues(uri, name)) { - return value; - } - return null; - } - - /** - * Returns a list of query parameter values associated with the given - * {@code name} from the given {@code uri}. - */ - public static List getQueryParameterValues(String uri, String name) { - List values = new ArrayList(); - if (uri != null) { - - // Strip out the path before the query string. - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - uri = uri.substring(questionAt + 1); - } - uri = "&" + uri; - - // Find all occurences of "&name=". - String prefix = "&" + encodeUri(name) + "="; - int prefixLength = prefix.length(); - for (int nameAt = 0; (nameAt = uri.indexOf(prefix, nameAt)) > -1;) { - nameAt += prefixLength; - int andAt = uri.indexOf('&', nameAt); - values.add(decodeUri(andAt > -1 ? - uri.substring(nameAt, andAt) : - uri.substring(nameAt))); - } - } - - return values; - } - - /** Returns a map of query parameters from the given {@code url}. */ - public static Map> getQueryParameterMap(String url) { - Map> map = new LinkedHashMap>(); - - if (url != null) { - int questionAt = url.indexOf('?'); - - if (questionAt > -1) { - url = url.substring(questionAt + 1); - } - - int lastAndAt = 0; - - for (int andAt; - (andAt = url.indexOf('&', lastAndAt)) > -1; - lastAndAt = andAt + 1) { - addParameter(map, url.substring(lastAndAt, andAt)); - } - - addParameter(map, url.substring(lastAndAt)); - } - - return map; - } - - private static void addParameter(Map> map, String pair) { - if (pair == null || pair.length() == 0) { - return; - } - - int equalAt = pair.indexOf('='); - String name; - String value; - - if (equalAt > -1) { - name = decodeUri(pair.substring(0, equalAt)); - value = decodeUri(pair.substring(equalAt + 1)); - - } else { - name = decodeUri(pair); - value = null; - } - - List parameters = map.get(name); - - if (parameters == null) { - parameters = new ArrayList(); - map.put(name, parameters); - } - - parameters.add(value); - } - - /** @deprecated Use {@link #addQueryParameters instead}. */ - @Deprecated - public static String transformUri(String uri, Object... parameters) { - return addQueryParameters(uri, parameters); - } - - /** @deprecated Use {@link #getQueryParameterValue instead}. */ - @Deprecated - public static String getParameter(String uri, String name) { - return getQueryParameterValue(uri, name); - } - - /** @deprecated Use {@link #getQueryParameterValues instead}. */ - @Deprecated - public static String[] getParameterValues(String uri, String name) { - List values = getQueryParameterValues(uri, name); - return values.toArray(new String[values.size()]); - } - - // --- Pattern bridge --- - private static final Map _patterns = new PullThroughCache() { - @Override - protected Pattern produce(String pattern) { - return Pattern.compile(pattern); - } - }; - - /** - * Gets a cached regular expression pattern object based on the given string. - */ - public static Pattern getPattern(String pattern) { - return _patterns.get(pattern); - } - - /** - * Gets a regular expression matcher based on the given string and pattern. - * - * @see #getPattern(String) - */ - public static Matcher getMatcher(CharSequence string, String pattern) { - return getPattern(pattern).matcher(string); - } - - /** - * Helper function that finds all groups in a regex and returns them in a result. find() is called automatically. - */ - public static MatchResult getMatcherResult(CharSequence string, String pattern) { - Matcher matcher = getMatcher(string, pattern); - matcher.find(); - final MatchResult result = matcher.toMatchResult(); - - - return new MatchResult() { - @Override - public int start() { - return result.start(); - } - - @Override - public int start(int group) { - return result.start(group); - } - - @Override - public int end() { - return result.end(); - } - - @Override - public int end(int group) { - return result.end(group); - } - - @Override - public String group() { - return result.group(); - } - - @Override - public String group(int group) { - try { - return result.group(group); - } catch (IllegalStateException e) { - return null; - } catch (IndexOutOfBoundsException e) { - return null; - } - } - - @Override - public int groupCount() { - return result.groupCount(); - } - }; - } - - /** - * Compiles the given regular expression pattern and attempts to match the given string against it. - * - * @see #getMatcher(CharSequence, String). - */ - public static boolean matches(CharSequence string, String pattern) { - return getMatcher(string, pattern).matches(); - } - - public static boolean matchAll(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return false; - } - } - - return true; - } - - public static boolean matchAny(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return true; - } - } - - return false; - } - - public static int matchCount(CharSequence string, String... patterns) { - int count = 0; - for (String pattern : patterns) { - if (matches(string, pattern)) { - ++count; - } - } - - return count; - } - - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #getMatcher(CharSequence, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement) { - return getMatcher(string, pattern).replaceAll(replacement); - } - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #replaceAll(CharSequence, String, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement, String... more) { - String r = replaceAll(string, pattern, replacement); - for (int i = 0, l = more.length; i < l; i += 2) { - r = replaceAll(r, more[i], i + 1 < l ? more[i + 1] : ""); - } - return r; - } - - /** - * Removes a without using regex * - */ - public static String removeAll(CharSequence string, CharSequence pattern) { - if (string == null) { - throw new IllegalArgumentException("String input is null"); - } - if (pattern != null) { - StringBuilder builder = new StringBuilder(string); - String p = pattern.toString(); - int l = pattern.length(); - for (int index; (index = builder.indexOf(p)) > -1;) { - builder.delete(index, index + l); - } - return builder.toString(); - } else { - return string.toString(); - } - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern, int limit) { - return getPattern(pattern).split(string, limit); - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern) { - return getPattern(pattern).split(string); - } - - // --- StringEscapeUtils bridge --- - - public static String escapeCsv(String string) { - return string == null ? null : StringEscapeUtils.escapeCsv(string); - } - - public static String escapeHtml(String string) { - return string == null ? null : StringUtils.replaceAll( - StringEscapeUtils.escapeHtml(string), - "\\x22", """, // double quote - "\\x27", "'"); // single quote - } - - public static String escapeJava(String string) { - return string == null ? null : StringEscapeUtils.escapeJava(string); - } - - /** - * Escapes the input string so that the resulting output can be used - * inside a JavaScript string AND none of the characters in the output - * need to be HTML escaped. - * @param string - * @return the escaped string, or null if the input was null - * This is not the same as HTML escaping a JavaScript escaped string, - * since the output can be used directly in a JavaScript string even - * when HTML-unescaping won't happen. - */ - public static String escapeJavaScript(String string) { - if (string == null) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0, s = string.length(); i < s; ++ i) { - char c = string.charAt(i); - if (0x30 <= c && c <= 0x39 - || 0x41 <= c && c <= 0x5A - || 0x61 <= c && c <= 0x7A) { - sb.append(c); - } else { - String hex = Integer.toHexString(c); - int hexLen = hex.length(); - if (c < 256) { - sb.append("\\x").append("00".substring(hexLen)); - } else { - sb.append("\\u").append("0000".substring(hexLen)); - } - sb.append(hex); - } - } - return sb.toString(); - } - - public static String escapeQuotes(String string) { - return string == null ? null : string.replace("\\", "\\\\").replace("\"", "\\\""); - } - - public static String escapeSql(String string) { - return string == null ? null : StringEscapeUtils.escapeSql(string); - } - - public static String escapeXml(String string) { - return string == null ? null : StringEscapeUtils.escapeXml(string); - } - - public static String unescapeCsv(String string) { - return string == null ? null : StringEscapeUtils.unescapeCsv(string); - } - - public static String unescapeHtml(String string) { - return string == null ? null : StringEscapeUtils.unescapeHtml(string); - } - - public static String unescapeJava(String string) { - return string == null ? null : StringEscapeUtils.unescapeJava(string); - } - - public static String unescapeJavaScript(String string) { - return string == null ? null : StringEscapeUtils.unescapeJavaScript(string); - } - - public static String unescapeXml(String string) { - return string == null ? null : StringEscapeUtils.unescapeXml(string); - } - - // --- StringUtils bridge --- - - /** - * Joins the given list of strings with the given delimiter in between. - */ - public static String join(List strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Joins the given array of strings with the given delimiter in between. - */ - public static String join(String[] strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Checks if a String is empty ("") or null. - */ - public static boolean isEmpty(String string) { - return org.apache.commons.lang.StringUtils.isEmpty(string); - } - - /** - * Checks if a String is whitespace, empty ("") or null. - */ - public static boolean isBlank(String string) { - return org.apache.commons.lang.StringUtils.isBlank(string); - } - - /** - * Null-safe comparison of two Strings, returning true if they are equal. - */ - public static boolean equals(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equals(str1, str2); - } - - /** - * Null-safe, case-insensitive comparison of two Strings, returning true if they are equal. - */ - public static boolean equalsIgnoreCase(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equalsIgnoreCase(str1, str2); - } - - public static String stripHtml(CharSequence sequence) { - Matcher m = StringUtils.getPattern("<[^>]*>").matcher(sequence); - return m.replaceAll(""); - } - - /** - * Ensures that the given {@code string} starts with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - return string; - } - - /** - * Ensures that the given {@code string} ends with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - - /** - * Ensures that the given {@code string} starts and ends with - * the given {@code delimiter}, adding them if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts or ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - } - - /** - * @param path If {@code null}, returns {@code null}. - * @param servletPath If {@code null}, returns {@code null}. - */ - public static String getPathInfo(String path, String servletPath) { - if (path != null && servletPath != null) { - path = ensureStart(path, "/"); - servletPath = removeEnd(ensureStart(servletPath, "/"), "/"); - - if (path.startsWith(servletPath)) { - String pathInfo = path.substring(servletPath.length()); - - if (pathInfo.length() == 0) { - return "/"; - - } else if (pathInfo.startsWith("/")) { - return pathInfo; - } - } - } - - return null; - } - - private static final int ASCII_SIZE = 256; - private static final char[] LOWER_CASE_ASCII; - - static { - LOWER_CASE_ASCII = new char[ASCII_SIZE]; - - for (int i = 0; i < ASCII_SIZE; ++ i) { - LOWER_CASE_ASCII[i] = (char) Character.toLowerCase(i); - } - } - - /** - * @param string Can't be {@code null}. - */ - public static String toLowerCaseAscii(String string) { - char[] letters = string.toCharArray(); - char letter; - - for (int i = 0, length = letters.length; i < length; ++ i) { - letter = letters[i]; - - if (letter < ASCII_SIZE) { - letters[i] = LOWER_CASE_ASCII[letter]; - } - } - - return new String(letters); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/old/StringUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/old/StringUtils.java deleted file mode 100755 index 884d198..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/old/StringUtils.java +++ /dev/null @@ -1,1214 +0,0 @@ -package com.psddev.dari.util; - -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Array; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.nio.charset.Charset; -import java.security.InvalidKeyException; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.MatchResult; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.crypto.Mac; -import javax.crypto.spec.SecretKeySpec; - -import org.apache.commons.lang.StringEscapeUtils; - -/** String utility methods. */ -public final class StringUtils { - - public static final Charset US_ASCII = Charset.forName("US-ASCII"); - public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); - public static final Charset UTF_8 = Charset.forName("UTF-8"); - public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); - public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); - public static final Charset UTF_16 = Charset.forName("UTF-16"); - - private static final Set - ABBREVIATIONS = new HashSet(Arrays.asList( - "cms", "css", "id", "js", "seo", "uri", "url")); - - private static final char[] HEX_CHARACTERS = { - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', - 'a', 'b', 'c', 'd', 'e', 'f' }; - - /** - * Converts given string into a value of given type, throwing an exception - * if conversion was unsuccessful. - * - * If the return type is an array, an array is returned. - * fromString(int[].class, "1", "2") => int[] {1,2} - * - * If no values are provided and the return type is an array, an empty array is returned. - * fromString(int[].class) => int[] {} - * - * If no values are provided and the return type is not an array, an exception - * appropriate to the conversion type is thrown. - * fromString(int.class) => NumberFormatException - * - * If the {@code strings} contains more than one value and the {@code returnType} is not - * an array, all but the first value are ignored. - * - * If the method cannot convert to the class specified, an IllegalArgumentException is thrown. - * - * @param - * @param returnType The class for the String input(s) to be converted to - * @param strings the input(s) to be converted - * @return the converted value - */ - public static T fromString(Class returnType, String... strings) { - - // heavy voodoo follows... - // need to return an array - Class componentType = returnType.getComponentType(); - if (componentType != null) { - if (strings == null) { - return null; - } else { - int length = strings.length; - Object typed = Array.newInstance(componentType, length); - for (int i = 0; i < length; i++) { - Array.set(typed, i, fromString(componentType, strings[i])); - } - return (T) typed; - } - - // single value - } else { - String string = strings == null || strings.length == 0 ? null : strings[0]; - - // string to string - if (String.class == returnType) { - return (T) string; - - // primitives - // pass null through if returnType allows it - } else if (string == null && !returnType.isPrimitive()) { - return null; - - // any way to avoid boxing/unboxing on primitives? - } else if (boolean.class == returnType || Boolean.class.isAssignableFrom(returnType)) { - return (T) Boolean.valueOf(string); - } else if (byte.class == returnType || Byte.class.isAssignableFrom(returnType)) { - return (T) Byte.valueOf(string); - } else if (short.class == returnType || Short.class.isAssignableFrom(returnType)) { - return (T) Short.valueOf(string); - } else if (int.class == returnType || Integer.class.isAssignableFrom(returnType)) { - return (T) Integer.valueOf(string); - } else if (long.class == returnType || Long.class.isAssignableFrom(returnType)) { - return (T) Long.valueOf(string); - } else if (float.class == returnType || Float.class.isAssignableFrom(returnType)) { - return (T) Float.valueOf(string); - } else if (double.class == returnType || Double.class.isAssignableFrom(returnType)) { - return (T) Double.valueOf(string); - } else if (char.class == returnType || Character.class.isAssignableFrom(returnType)) { - if (string.length() == 1) { - return (T) Character.valueOf(string.charAt(0)); - } - - // others - } else if (Date.class.isAssignableFrom(returnType)) { - return (T) DateUtils.fromString(string); - } - throw new IllegalArgumentException(String.format( - "Cannot convert [%s] string to [%s] type!", - string, - returnType.getName() - )); - } - } - - - /** - * Helper method to split a string by case change or common delimiters. - * - * Multiple delimeters in a row are reduced to a single word boundry. - * - * Leading delimeters (a space at the beginning of the string) will cause an - * empty first word to be detected (bug?). Trailing delemeters do not cause empty - * words to be detected. - * - * Returned words are all lowercased. - * - * @param string - * @return the list of words detected in the string - */ - protected static List splitString(String string) { - List words = new ArrayList(); - int m = 0, l = string.length(); - for (int i = 0; i < l; i++) { - char c = string.charAt(i); - if (" -_.$".indexOf(c) > -1) { - words.add(string.substring(m, i).toLowerCase()); - while (++i < l && " -_.$".indexOf(string.charAt(i)) > -1) { - } - m = i; - } else if (Character.isUpperCase(c) && i > 0 && Character.isLowerCase(string.charAt(i - 1))) { - words.add(string.substring(m, i).toLowerCase()); - m = i; - } - } - if (m + 1 < l) { - words.add(string.substring(m).toLowerCase()); - } - return words; - } - - /** - * Tries to detect words within a given string and join them with the given delimiter. - */ - public static String toDelimited(String string, String delimiter) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(word).append(delimiter); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - delimiter.length()); - } - return nb.toString(); - } - - /** - * Converts the given string into a-hyphenated-string. - */ - public static String toHyphenated(String string) { - return toDelimited(string, "-"); - } - - /** - * Converts the given string into a_underscored_string. - */ - public static String toUnderscored(String string) { - return toDelimited(string, "_"); - } - - /** - * Converts the given string into APascalCaseString. - */ - public static String toPascalCase(String string) { - StringBuilder nb = new StringBuilder(); - for (String word : splitString(string)) { - nb.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)); - } - return nb.toString(); - } - - /** - * Converts the given string into aCamelCaseString. - */ - public static String toCamelCase(String string) { - string = toPascalCase(string); - return Character.toLowerCase(string.charAt(0)) + string.substring(1); - } - - /** - * Converts the string to one suitable for use as "a label"? - * - * Splits {@code string} into words, joining it back together "In Title Case" - * with known {@code ABBREVIATIONS} replaced in all caps. If the first word of - * {@code string} is "is", that word is removed and a question mark is - * added to the end of the resulting string. - * - * @param string - */ - public static String toLabel(String string) { - - if (string == null) { - return null; - } - - boolean isQuestion = false; - List words = splitString(string); - if (words.size() > 0 && "is".equals(words.get(0))) { - isQuestion = true; - words.remove(0); - } - - StringBuilder nb = new StringBuilder(); - for (String word : words) { - if (word.length() == 0) { - continue; - } - - if (ABBREVIATIONS.contains(word)) { - nb.append(word.toUpperCase(Locale.ENGLISH)); - } else { - nb.append(Character.toUpperCase(word.charAt(0))); - nb.append(word.substring(1)); - } - nb.append(' '); - } - if (nb.length() > 0) { - nb.setLength(nb.length() - 1); - } - - if (isQuestion) { - nb.append('?'); - } - - return nb.toString(); - } - - /** - * Normalizes a string, removing or replacing non-alphanumeric characters and lowercasing - * - * - Removes all accented characters. - * - Removes single quotes - * - Replaces non-alphanumeric characters remaining with a dash - * - Removes dashes - * - * Lowercases the result - */ - public static String toNormalized(CharSequence string) { - return string == null ? null : replaceAll( - Normalizer.normalize(string, Normalizer.Form.NFD), - "[^\\p{ASCII}]", "", - "'", "", - "\\.", "", - "[^a-zA-Z0-9]+", "-", - "^-+|-+$", "" - ).toLowerCase(); - } - - /** Splits the given string by commas, and returns each part unescaped. - * Calling {@link #toCsv(String...)} on an array of Strings and then - * passing the result to this method will always return the same array - * as specified by the Arrays.equals() method. */ - public static String[] fromCsv(String string) { - if(string == null) { - return null; - } else { - // replaces a call to string.split(",") - char[] charArr = string.toCharArray(); - int commaCount = 0; - for (char c : charArr) { - if (c == ',') { - commaCount++; - } - } - String[] escaped = new String[commaCount+1]; - int index = 0; - int offset = 0; - int count = 0; - for (char c : charArr) { - if (c == ',') { - escaped[index++] = new String(charArr, offset, count); - offset += count+1; - count = 0; - } else { - count++; - } - } - if (index == commaCount) { - escaped[index] = new String(charArr, offset, count); - } - // end string.split(",") replacement code - - int length = escaped.length; - List unescaped = new ArrayList(); - for(int i = 0; i < length; i ++) { - String value = escaped[i]; - if(value.startsWith("\"")) { // there are commas and/or double quotes escaped within - StringBuilder builder = new StringBuilder(); - int quoteCount = 0; - do { - builder.append(value); - for(char c : value.toCharArray()) { - if(c == '"') { - quoteCount++; - } - } - if(quoteCount % 2 == 1) { - value = escaped[++i]; - builder.append(','); - } - } while(quoteCount % 2 == 1); - value = builder.toString(); - } - unescaped.add(StringUtils.unescapeCsv(value)); - } - return unescaped.toArray(new String[unescaped.size()]); - } - } - - /** Converts an array of Strings to a single String in comma separated - * values format, escaping each string as necessary. */ - public static String toCsv(String... strings) { - if (strings == null) { - return null; - } - StringBuilder builder = new StringBuilder(); - for (String string : strings) { - builder.append(escapeCsv(string)).append(','); - } - if (builder.length() > 0) { - builder.setLength(builder.length()-1); - } - return builder.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string, int maxWordLength) { - if (string == null) { - return null; - } - Matcher matcher = getMatcher(string, String.format("(\\S{%d,})", maxWordLength)); - StringBuilder output = new StringBuilder(); - int marker = 0; - while (matcher.find()) { - String longWord = matcher.group(1); - - // similar to Matcher.appendReplacement - // re-implemented so that $ and \ does not have to be escaped - if (matcher.start() > marker) { - output.append(string.substring(marker, matcher.start())); - } - int i = 0; - for (; i < longWord.length() - maxWordLength; i += maxWordLength) { - output.append(escapeHtml(longWord.substring(i, i + maxWordLength))); - output.append(""); - } - output.append(escapeHtml(longWord.substring(i))); - marker = matcher.end(); - } - - // similar to Matcher.appendTail - output.append(string.substring(marker)); - return output.toString(); - } - - /** - * Escapes given string so that it's usable in HTML and breaks it apart so that it can wrap. - */ - public static String escapeHtmlAndBreak(String string) { - return escapeHtmlAndBreak(string, 20); - } - - /** Converts the given {@code bytes} into a hex string. */ - public static String hex(byte[] bytes) { - if (bytes == null) { - return null; - } - - int bytesLength = bytes.length; - byte currentByte; - char[] hex = new char[bytesLength * 2]; - - for (int byteIndex = 0, hexIndex = 0; - byteIndex < bytesLength; - ++ byteIndex, hexIndex += 2) { - - currentByte = bytes[byteIndex]; - hex[hexIndex] = HEX_CHARACTERS[(currentByte & 0xf0) >> 4]; - hex[hexIndex + 1] = HEX_CHARACTERS[(currentByte & 0x0f)]; - } - - return new String(hex); - } - - /** Hashes the given {@code string} using the given {@code algorithm}. */ - public static byte[] hash(String algorithm, String string) { - MessageDigest digest; - try { - digest = MessageDigest.getInstance(algorithm); - } catch (NoSuchAlgorithmException ex) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid hash algorithm!", algorithm), ex); - } - - byte[] bytes; - try { - bytes = string.getBytes("UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - - return digest.digest(bytes); - } - - /** Hashes the given {@code string} using the MD5 algorithm. */ - public static byte[] md5(String string) { - return hash("MD5", string); - } - - /** Hashes the given {@code string} using the SHA-1 algorithm. */ - public static byte[] sha1(String string) { - return hash("SHA-1", string); - } - - /** Hashes the given {@code string} using the SHA-512 algorithm. */ - public static byte[] sha512(String string) { - return hash("SHA-512", string); - } - - /** - * Hashes the given {@code string} using the given HMAC {@code algorithm} - * and {@code key}. - */ - public static byte[] hmac(String algorithm, String key, String string) { - try { - Mac mac = Mac.getInstance(algorithm); - mac.init(new SecretKeySpec(key.getBytes(StringUtils.UTF_8), algorithm)); - return mac.doFinal(string.getBytes(StringUtils.UTF_8)); - - } catch (NoSuchAlgorithmException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid HMAC algorithm!", algorithm), error); - - } catch (InvalidKeyException error) { - throw new IllegalArgumentException(String.format("[%s] isn't a valid key!", key), error); - } - } - - /** - * Hashes the given {@code string} using the HMAC SHA-1 algorithm - * and the given {@code key}. - */ - public static byte[] hmacSha1(String key, String string) { - return hmac("HmacSHA1", key, string); - } - - // --- URL/URI --- - - /** - * Encodes the given UTF-8 {@code string} so that it's safe for use - * within an URI. - */ - public static String encodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLEncoder.encode(string, "UTF-8").replace("+", "%20"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** Decodes the given URI-encoded, UTF-8 {@code string}. */ - public static String decodeUri(String string) { - if (string == null) { - return null; - } - try { - return URLDecoder.decode(string, "UTF-8"); - } catch (UnsupportedEncodingException ex) { - throw new IllegalStateException(ex); - } - } - - /** - * Adds the given {@code parameters} as a query string to the given - * {@code uri}. - */ - public static String addQueryParameters(String uri, Object... parameters) { - if (uri == null) { - return null; - } - - // Convert "path?a=b&c=d" to "&a=b&c=d". - StringBuilder query = new StringBuilder(); - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - - String queryString = uri.substring(questionAt + 1); - int beginAt = 0; - - // make sure all the query parameters are encoded - while (true) { - int ampIndex = queryString.indexOf('&', beginAt); - - String param = queryString.substring(beginAt, ampIndex > -1 ? ampIndex : queryString.length()); - - if (!param.isEmpty() || ampIndex > -1) { - query.append('&'); - - int equalsIndex = param.indexOf('='); - if (equalsIndex > -1) { - query.append(encodeUri(decodeUri(param.substring(0, equalsIndex)))); - query.append('='); - query.append(encodeUri(decodeUri(param.substring(equalsIndex+1)))); - - } else { - query.append(encodeUri(decodeUri(param))); - } - } - - if (ampIndex > -1) { - beginAt = ampIndex+1; - } else { - break; - } - } - - uri = uri.substring(0, questionAt); - } - - int parametersLength = parameters != null ? parameters.length : 0; - - for (int i = 0; i < parametersLength; i += 2) { - - // Remove all occurrences of "&name=". - String name = parameters[i].toString(); - String prefix = "&" + name + "="; - int prefixLength = prefix.length(); - int beginAt = 0; - int endAt; - while (true) { - - beginAt = query.indexOf(prefix, beginAt); - if (beginAt < 0) { - break; - } - - endAt = query.indexOf("&", beginAt + prefixLength); - if (endAt > -1) { - query.delete(beginAt, endAt); - - } else { - query.delete(beginAt, query.length()); - break; - } - } - - // Append "&name=value". - if (i + 1 < parametersLength) { - Object value = parameters[i + 1]; - if (value != null) { - for (Object item : ObjectUtils.to(Iterable.class, value)) { - if (item != null) { - query.append('&'); - query.append(encodeUri(name)); - query.append('='); - query.append(encodeUri(item instanceof Enum ? - ((Enum) item).name() : - item.toString())); - } - } - } - } - } - - // Reconstruct the URI. - if (query.length() <= 1) { - return uri; - - } else { - query.delete(0, 1); - query.insert(0, "?"); - query.insert(0, uri); - return query.toString(); - } - } - - /** - * Returns the first query parameter value associated with the given - * {@code name} from the given {@code uri}. - */ - public static String getQueryParameterValue(String uri, String name) { - for (String value : getQueryParameterValues(uri, name)) { - return value; - } - return null; - } - - /** - * Returns a list of query parameter values associated with the given - * {@code name} from the given {@code uri}. - */ - public static List getQueryParameterValues(String uri, String name) { - List values = new ArrayList(); - if (uri != null) { - - // Strip out the path before the query string. - int questionAt = uri.indexOf('?'); - if (questionAt > -1) { - uri = uri.substring(questionAt + 1); - } - uri = "&" + uri; - - // Find all occurences of "&name=". - String prefix = "&" + encodeUri(name) + "="; - int prefixLength = prefix.length(); - for (int nameAt = 0; (nameAt = uri.indexOf(prefix, nameAt)) > -1;) { - nameAt += prefixLength; - int andAt = uri.indexOf('&', nameAt); - values.add(decodeUri(andAt > -1 ? - uri.substring(nameAt, andAt) : - uri.substring(nameAt))); - } - } - - return values; - } - - /** Returns a map of query parameters from the given {@code url}. */ - public static Map> getQueryParameterMap(String url) { - Map> map = new LinkedHashMap>(); - - if (url != null) { - int questionAt = url.indexOf('?'); - - if (questionAt > -1) { - url = url.substring(questionAt + 1); - } - - int lastAndAt = 0; - - for (int andAt; - (andAt = url.indexOf('&', lastAndAt)) > -1; - lastAndAt = andAt + 1) { - addParameter(map, url.substring(lastAndAt, andAt)); - } - - addParameter(map, url.substring(lastAndAt)); - } - - return map; - } - - private static void addParameter(Map> map, String pair) { - if (pair == null || pair.length() == 0) { - return; - } - - int equalAt = pair.indexOf('='); - String name; - String value; - - if (equalAt > -1) { - name = decodeUri(pair.substring(0, equalAt)); - value = decodeUri(pair.substring(equalAt + 1)); - - } else { - name = decodeUri(pair); - value = null; - } - - List parameters = map.get(name); - - if (parameters == null) { - parameters = new ArrayList(); - map.put(name, parameters); - } - - parameters.add(value); - } - - /** @deprecated Use {@link #addQueryParameters instead}. */ - @Deprecated - public static String transformUri(String uri, Object... parameters) { - return addQueryParameters(uri, parameters); - } - - /** @deprecated Use {@link #getQueryParameterValue instead}. */ - @Deprecated - public static String getParameter(String uri, String name) { - return getQueryParameterValue(uri, name); - } - - /** @deprecated Use {@link #getQueryParameterValues instead}. */ - @Deprecated - public static String[] getParameterValues(String uri, String name) { - List values = getQueryParameterValues(uri, name); - return values.toArray(new String[values.size()]); - } - - // --- Pattern bridge --- - private static final Map _patterns = new PullThroughCache() { - @Override - protected Pattern produce(String pattern) { - return Pattern.compile(pattern); - } - }; - - /** - * Gets a cached regular expression pattern object based on the given string. - */ - public static Pattern getPattern(String pattern) { - return _patterns.get(pattern); - } - - /** - * Gets a regular expression matcher based on the given string and pattern. - * - * @see #getPattern(String) - */ - public static Matcher getMatcher(CharSequence string, String pattern) { - return getPattern(pattern).matcher(string); - } - - /** - * Helper function that finds all groups in a regex and returns them in a result. find() is called automatically. - */ - public static MatchResult getMatcherResult(CharSequence string, String pattern) { - Matcher matcher = getMatcher(string, pattern); - matcher.find(); - final MatchResult result = matcher.toMatchResult(); - - - return new MatchResult() { - @Override - public int start() { - return result.start(); - } - - @Override - public int start(int group) { - return result.start(group); - } - - @Override - public int end() { - return result.end(); - } - - @Override - public int end(int group) { - return result.end(group); - } - - @Override - public String group() { - return result.group(); - } - - @Override - public String group(int group) { - try { - return result.group(group); - } catch (IllegalStateException e) { - return null; - } catch (IndexOutOfBoundsException e) { - return null; - } - } - - @Override - public int groupCount() { - return result.groupCount(); - } - }; - } - - /** - * Compiles the given regular expression pattern and attempts to match the given string against it. - * - * @see #getMatcher(CharSequence, String). - */ - public static boolean matches(CharSequence string, String pattern) { - return getMatcher(string, pattern).matches(); - } - - public static boolean matchAll(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return false; - } - } - - return true; - } - - public static boolean matchAny(CharSequence string, String... patterns) { - for (String pattern : patterns) { - if (!matches(string, pattern)) { - return true; - } - } - - return false; - } - - public static int matchCount(CharSequence string, String... patterns) { - int count = 0; - for (String pattern : patterns) { - if (matches(string, pattern)) { - ++count; - } - } - - return count; - } - - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #getMatcher(CharSequence, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement) { - return getMatcher(string, pattern).replaceAll(replacement); - } - - /** - * Replaces each substring of the given string that matches the given regular expression pattern with the given replacement. - * - * @see #replaceAll(CharSequence, String, String). - */ - public static String replaceAll(CharSequence string, String pattern, String replacement, String... more) { - String r = replaceAll(string, pattern, replacement); - for (int i = 0, l = more.length; i < l; i += 2) { - r = replaceAll(r, more[i], i + 1 < l ? more[i + 1] : ""); - } - return r; - } - - /** - * Removes a without using regex * - */ - public static String removeAll(CharSequence string, CharSequence pattern) { - if (string == null) { - throw new IllegalArgumentException("String input is null"); - } - if (pattern != null) { - StringBuilder builder = new StringBuilder(string); - String p = pattern.toString(); - int l = pattern.length(); - for (int index; (index = builder.indexOf(p)) > -1;) { - builder.delete(index, index + l); - } - return builder.toString(); - } else { - return string.toString(); - } - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern, int limit) { - return getPattern(pattern).split(string, limit); - } - - /** - * Splits the given string around matches of the given regular expression pattern. - * - * @see #getPattern(String) - */ - public static String[] split(CharSequence string, String pattern) { - return getPattern(pattern).split(string); - } - - // --- StringEscapeUtils bridge --- - - public static String escapeCsv(String string) { - return string == null ? null : StringEscapeUtils.escapeCsv(string); - } - - public static String escapeHtml(String string) { - return string == null ? null : StringUtils.replaceAll( - StringEscapeUtils.escapeHtml(string), - "\\x22", """, // double quote - "\\x27", "'"); // single quote - } - - public static String escapeJava(String string) { - return string == null ? null : StringEscapeUtils.escapeJava(string); - } - - /** - * Escapes the input string so that the resulting output can be used - * inside a JavaScript string AND none of the characters in the output - * need to be HTML escaped. - * @param string - * @return the escaped string, or null if the input was null - * This is not the same as HTML escaping a JavaScript escaped string, - * since the output can be used directly in a JavaScript string even - * when HTML-unescaping won't happen. - */ - public static String escapeJavaScript(String string) { - if (string == null) { - return null; - } - StringBuilder sb = new StringBuilder(); - for (int i = 0, s = string.length(); i < s; ++ i) { - char c = string.charAt(i); - if (0x30 <= c && c <= 0x39 - || 0x41 <= c && c <= 0x5A - || 0x61 <= c && c <= 0x7A) { - sb.append(c); - } else { - String hex = Integer.toHexString(c); - int hexLen = hex.length(); - if (c < 256) { - sb.append("\\x").append("00".substring(hexLen)); - } else { - sb.append("\\u").append("0000".substring(hexLen)); - } - sb.append(hex); - } - } - return sb.toString(); - } - - public static String escapeQuotes(String string) { - return string == null ? null : string.replace("\\", "\\\\").replace("\"", "\\\""); - } - - public static String escapeSql(String string) { - return string == null ? null : StringEscapeUtils.escapeSql(string); - } - - public static String escapeXml(String string) { - return string == null ? null : StringEscapeUtils.escapeXml(string); - } - - public static String unescapeCsv(String string) { - return string == null ? null : StringEscapeUtils.unescapeCsv(string); - } - - public static String unescapeHtml(String string) { - return string == null ? null : StringEscapeUtils.unescapeHtml(string); - } - - public static String unescapeJava(String string) { - return string == null ? null : StringEscapeUtils.unescapeJava(string); - } - - public static String unescapeJavaScript(String string) { - return string == null ? null : StringEscapeUtils.unescapeJavaScript(string); - } - - public static String unescapeXml(String string) { - return string == null ? null : StringEscapeUtils.unescapeXml(string); - } - - // --- StringUtils bridge --- - - /** - * Joins the given list of strings with the given delimiter in between. - */ - public static String join(List strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Joins the given array of strings with the given delimiter in between. - */ - public static String join(String[] strings, String delimiter) { - return strings == null ? null : org.apache.commons.lang.StringUtils.join(strings, delimiter); - } - - /** - * Checks if a String is empty ("") or null. - */ - public static boolean isEmpty(String string) { - return org.apache.commons.lang.StringUtils.isEmpty(string); - } - - /** - * Checks if a String is whitespace, empty ("") or null. - */ - public static boolean isBlank(String string) { - return org.apache.commons.lang.StringUtils.isBlank(string); - } - - /** - * Null-safe comparison of two Strings, returning true if they are equal. - */ - public static boolean equals(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equals(str1, str2); - } - - /** - * Null-safe, case-insensitive comparison of two Strings, returning true if they are equal. - */ - public static boolean equalsIgnoreCase(String str1, String str2) { - return org.apache.commons.lang.StringUtils.equalsIgnoreCase(str1, str2); - } - - public static String stripHtml(CharSequence sequence) { - Matcher m = StringUtils.getPattern("<[^>]*>").matcher(sequence); - return m.replaceAll(""); - } - - /** - * Ensures that the given {@code string} starts with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - return string; - } - - /** - * Ensures that the given {@code string} ends with the given - * {@code delimiter}, adding it if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - - /** - * Ensures that the given {@code string} starts and ends with - * the given {@code delimiter}, adding them if necessary. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, does nothing. - */ - public static String ensureSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (!string.startsWith(delimiter)) { - string = delimiter + string; - } - if (!string.endsWith(delimiter)) { - string = string + delimiter; - } - return string; - } - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeStart(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeEnd(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - - /** - * Removes the given {@code delimiter} if the given {@code string} - * starts or ends with it. - * - * @param string If {@code null}, returns {@code null}. - * @param delimiter If {@code null}, returns the given {@code string} - * as is. - */ - public static String removeSurrounding(String string, String delimiter) { - if (string == null) { - return null; - } else if (delimiter == null) { - return string; - } else { - if (string.startsWith(delimiter)) { - string = string.substring(delimiter.length()); - } - if (string.endsWith(delimiter)) { - string = string.substring(0, string.length() - delimiter.length()); - } - return string; - } - } - - /** - * @param path If {@code null}, returns {@code null}. - * @param servletPath If {@code null}, returns {@code null}. - */ - public static String getPathInfo(String path, String servletPath) { - if (path != null && servletPath != null) { - path = ensureStart(path, "/"); - servletPath = removeEnd(ensureStart(servletPath, "/"), "/"); - - if (path.startsWith(servletPath)) { - String pathInfo = path.substring(servletPath.length()); - - if (pathInfo.length() == 0) { - return "/"; - - } else if (pathInfo.startsWith("/")) { - return pathInfo; - } - } - } - - return null; - } - - private static final int ASCII_SIZE = 256; - private static final char[] LOWER_CASE_ASCII; - - static { - LOWER_CASE_ASCII = new char[ASCII_SIZE]; - - for (int i = 0; i < ASCII_SIZE; ++ i) { - LOWER_CASE_ASCII[i] = (char) Character.toLowerCase(i); - } - } - - /** - * @param string Can't be {@code null}. - */ - public static String toLowerCaseAscii(String string) { - char[] letters = string.toCharArray(); - char letter; - - for (int i = 0, length = letters.length; i < length; ++ i) { - letter = letters[i]; - - if (letter < ASCII_SIZE) { - letters[i] = LOWER_CASE_ASCII[letter]; - } - } - - return new String(letters); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/pair.info deleted file mode 100755 index c477067..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52784/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:52784 -comSha:641bc27d5470a167d3ca2fefd6ae4c619a27c012 -parentComSha:5f098cd76c5e7aff3237dc54664709c515095ad4 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/StringUtils.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/StringUtils.java -StartLineNum:276 -EndLineNum:276 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/comMsg.txt deleted file mode 100755 index 197a716..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of DM_CONVERT_CASE from FindBugs. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/diff.diff deleted file mode 100755 index f6207b7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/ObjectUtils.java b/util/src/main/java/com/psddev/dari/util/ObjectUtils.java -index 41e929b4..b5c8291c 100644 ---- a/util/src/main/java/com/psddev/dari/util/ObjectUtils.java -+++ b/util/src/main/java/com/psddev/dari/util/ObjectUtils.java -@@ -18,0 +19 @@ import java.util.List; -+import java.util.Locale; -@@ -392 +393 @@ public abstract class ObjectUtils { -- String contentType = items[0].toLowerCase(); -+ String contentType = items[0].toLowerCase(Locale.ENGLISH); -@@ -395 +396 @@ public abstract class ObjectUtils { -- contentTypes.put(items[j].toLowerCase(), contentType); -+ contentTypes.put(items[j].toLowerCase(Locale.ENGLISH), contentType); -@@ -416 +417 @@ public abstract class ObjectUtils { -- String type = CONTENT_TYPES.get().get(fileName.substring(dotAt + 1).toLowerCase()); -+ String type = CONTENT_TYPES.get().get(fileName.substring(dotAt + 1).toLowerCase(Locale.ENGLISH)); -@@ -600 +601 @@ public abstract class ObjectUtils { -- string.substring(0, 1).toUpperCase() + string.substring(1); -+ string.substring(0, 1).toUpperCase(Locale.ENGLISH) + string.substring(1); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/new/ObjectUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/new/ObjectUtils.java deleted file mode 100755 index b5c8291..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/new/ObjectUtils.java +++ /dev/null @@ -1,688 +0,0 @@ -package com.psddev.dari.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.UUID; - -/** Object utility methods. */ -public abstract class ObjectUtils { - - private static final ClassFinder CLASS_FINDER = new ClassFinder(); - private static final JsonProcessor JSON_PROCESSOR = new JsonProcessor(); - - private static final Map> PRIMITIVE_CLASSES; static { - Map> m = new HashMap>(); - for (Class c : new Class[] { - byte.class, short.class, int.class, long.class, - float.class, double.class, boolean.class, char.class }) { - m.put(c.getName(), c); - } - PRIMITIVE_CLASSES = m; - } - - // Because Class.forName is pretty slow. - private static final Map>> - CLASSES_BY_LOADER = new PullThroughCache>>() { - - @Override - protected Map> produce(final ClassLoader loader) { - return new PullThroughCache>() { - - @Override - protected Class produce(String name) { - if (name != null) { - try { - return Class.forName(name, false, loader); - } catch (ClassNotFoundException error) { - // Falls through to return null below. - } catch (NoClassDefFoundError error) { - // Falls through to return null below. - } - } - return null; - } - }; - } - }; - - /** - * Returns {@code true} if the given {@code object1} and {@code object2}, - * either of which may be {@code null}, are equal. - * - * @see Object#equals(Object) - */ - public static boolean equals(Object object1, Object object2) { - if (object1 == object2) { - return true; - - } else if (object1 == null || object2 == null) { - return false; - - } else if (object1 instanceof Enum && object2 instanceof String) { - return ((Enum) object1).name().equals(object2); - - } else if (object1 instanceof String && object2 instanceof Enum) { - return object1.equals(((Enum) object2).name()); - - } else { - return object1.equals(object2); - } - } - - /** - * Returns the hash code value for the given {@code objects}, - * or 0 if it's {@code null}. - */ - public static int hashCode(Object... objects) { - if (objects == null) { - return 0; - - } else if (objects.length == 1) { - Object object = objects[0]; - return object == null ? 0 : object.hashCode(); - - } else { - return Arrays.hashCode(objects); - } - } - - /** - * Returns the first non-{@code null} value among the given - * {@code values}. - */ - public static T coalesce(T... values) { - if (values != null) { - for (T value : values) { - if (value != null) { - return value; - } - } - } - return null; - } - - /** - * Returns either the {@linkplain Thread#getContextClassLoader - * context class loader} from the current thread or the one - * that loaded this class. - */ - public static ClassLoader getCurrentClassLoader() { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - return loader != null ? loader : ObjectUtils.class.getClassLoader(); - } - - /** - * Returns the class with the given {@code name} from the given - * class {@code loader}. - * - * @return {@code null} if the class with the given {@code name} - * doesn't exist. - */ - public static Class getClassFromLoader(ClassLoader loader, String name) { - return CLASSES_BY_LOADER.get(loader).get(name); - } - - /** - * Returns the class with the given {@code name} from the - * {@linkplain #getCurrentClassLoader current class loader}. - * - * @return {@code null} if the class with the given {@code name} - * doesn't exist. - */ - public static Class getClassByName(String name) { - Class c = PRIMITIVE_CLASSES.get(name); - return c != null ? c : getClassFromLoader(getCurrentClassLoader(), name); - } - - /** - * Compares the given {@code object1} and {@code object2} without - * throwing any errors. - * - * @param isNullGreatest If {@code null} is considered to be greater - * than any other value. - * @return A negative integer, zero, or a positive integer, depending - * on whether the given {@code object1} is less than, equal to, - * or greater than the given {@code object2}. If the parameters - * aren't {@linkplain Comparable comparable}, this method - * always returns {@code -1}. - */ - public static int compare(Object object1, Object object2, boolean isNullGreatest) { - if (object1 == null) { - return object2 == null ? 0 : (isNullGreatest ? 1 : -1); - - } else if (object2 == null) { - return isNullGreatest ? -1 : 1; - - } else { - Class object1Class = object1.getClass(); - Class object2Class = object2.getClass(); - - if (Comparable.class.isAssignableFrom(object1Class) && - object1Class.isAssignableFrom(object2Class)) { - @SuppressWarnings("unchecked") - Comparable object1Comparable = (Comparable) object1; - return object1Comparable.compareTo(object2); - - } else if (Comparable.class.isAssignableFrom(object2Class) && - object2Class.isAssignableFrom(object1Class)) { - @SuppressWarnings("unchecked") - Comparable object2Comparable = (Comparable) object2; - return 0 - object2Comparable.compareTo(object1); - - } else { - return -1; - } - } - } - - /** Sorts the given {@code list} using {@link #compare}. */ - public static void sort(List list, boolean isNullGreatest) { - Collections.sort(list, isNullGreatest ? - NULL_GREATEST_COMPARATOR : - NULL_LEAST_COMPARATOR); - } - - private static final Comparator NULL_GREATEST_COMPARATOR = new Comparator() { - @Override - public int compare(Object object1, Object object2) { - return ObjectUtils.compare(object1, object2, true); - } - }; - - private static final Comparator NULL_LEAST_COMPARATOR = new Comparator() { - @Override - public int compare(Object object1, Object object2) { - return ObjectUtils.compare(object1, object2, false); - } - }; - - /** - * Returns {@code true} if the given object is {@code null}, an empty - * string, a string that consists of only whitespaces, an empty - * collection, an empty map, an empty array, or an iterable without - * any elements. - */ - public static boolean isBlank(Object object) { - if (object == null) { - return true; - - } else if (object instanceof String) { - String string = (String) object; - - for (int i = 0, length = string.length(); i < length; ++ i) { - if (!Character.isWhitespace(string.charAt(i))) { - return false; - } - } - - return true; - - } else if (object instanceof Collection) { - return ((Collection) object).isEmpty(); - - } else if (object instanceof Map) { - return ((Map) object).isEmpty(); - - } else if (object.getClass().isArray()) { - return Array.getLength(object) == 0; - - } else if (object instanceof Iterable) { - return !((Iterable) object).iterator().hasNext(); - - } else { - return false; - } - } - - // --- ClassFinder bridge --- - - /** - * {@linkplain ClassFinder#find Finds all classes} that are - * compatible with the given {@code baseClass} within the given - * class {@code loader}. - */ - public static Set> findClassesFromLoader(ClassLoader loader, Class baseClass) { - return CLASS_FINDER.find(loader, baseClass); - } - - /** - * {@linkplain ClassFinder#find Finds all classes} that are - * compatible with the given {@code baseClass} within the - * {@linkplain #getCurrentClassLoader current class loader}. - */ - public static Set> findClasses(Class baseClass) { - return findClassesFromLoader(getCurrentClassLoader(), baseClass); - } - - // --- Converter bridge --- - - private static final Converter CONVERTER; static { - CONVERTER = new Converter(); - CONVERTER.putAllStandardFunctions(); - } - - /** - * Converts the given {@code object} into an instance of the given - * {@code returnType}. - * - * @see Converter#convert(Type, Object) - */ - public static Object to(Type returnType, Object object) { - return CONVERTER.convert(returnType, object); - } - - /** - * Converts the given {@code object} into an instance of the given - * {@code returnClass}. - * - * @see Converter#convert(Class, Object) - */ - public static T to(Class returnClass, Object object) { - return CONVERTER.convert(returnClass, object); - } - - /** - * Converts the given {@code object} into an instance of the type - * referenced by the given {@code returnTypeReference}. - * - * @see Converter#convert(TypeReference, Object) - */ - public static T to(TypeReference returnTypeReference, Object object) { - return CONVERTER.convert(returnTypeReference, object); - } - - // --- JsonProcessor bridge --- - - /** - * Parses the given JSON {@code string} into an object. - * - * @see JsonProcessor#parse(String) - */ - public static Object fromJson(String string) { - return JSON_PROCESSOR.parse(string); - } - - /** - * Parses the given JSON {@code bytes} into an object. - * - * @param bytes If {@code null}, returns {@code null}. - * @see JsonProcessor#parse(byte[]) - */ - public static Object fromJson(byte[] bytes) { - return JSON_PROCESSOR.parse(bytes); - } - - /** - * Generates a JSON string based on the given {@code object}. - * - * @see JsonProcessor#generate(Object) - */ - public static String toJson(Object object) { - return JSON_PROCESSOR.generate(object); - } - - /** - * Generates a JSON string, indented if the given {@code isIndentOutput} - * is {@code true}, based on the given {@code object}. - * - * @see JsonProcessor#setIndentOutput(boolean) - * @see JsonProcessor#generate(Object) - */ - public static String toJson(Object object, boolean isIndentOutput) { - JsonProcessor processor = new JsonProcessor(); - processor.setIndentOutput(isIndentOutput); - return processor.generate(object); - } - - /** - * Generates a JSON string, indented if the given {@code isIndentOutput} - * is {@code true}, based on the given {@code object}, after transforming - * it using the given {@code transformer}. - * - * @see JsonProcessor#setIndentOutput(boolean) - * @see JsonProcessor#setTransformer(Transformer) - * @see JsonProcessor#generate(Object) - */ - public static String toJson(Object object, boolean isIndentOutput, Transformer transformer) { - JsonProcessor processor = new JsonProcessor(); - processor.setIndentOutput(isIndentOutput); - processor.setTransformer(transformer); - return processor.generate(object); - } - - // --- Content type --- - - /** Default content type for {@link #getContentType}. */ - public static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; - - /** - * File name extensions to content types cache from: - * http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types - */ - private static final PullThroughValue> CONTENT_TYPES = new PullThroughValue>() { - - @Override - protected Map produce() throws IOException { - Map contentTypes = new HashMap(); - InputStream mimeInput = getClass().getResourceAsStream("mime.types"); - BufferedReader mimeInputReader = new BufferedReader(new InputStreamReader(mimeInput, StringUtils.UTF_8)); - - try { - for (String line; (line = mimeInputReader.readLine()) != null; ) { - if (!line.startsWith("#")) { - String[] items = StringUtils.split(line.trim(), "\\s+"); - String contentType = items[0].toLowerCase(Locale.ENGLISH); - - for (int j = 1, length = items.length; j < length; ++ j) { - contentTypes.put(items[j].toLowerCase(Locale.ENGLISH), contentType); - } - } - } - - } finally { - mimeInputReader.close(); - } - - return contentTypes; - } - }; - - /** - * Returns the content type associated with the given {@code fileName} - * extension, or {@value DEFAULT_CONTENT_TYPE} if not found. - */ - public static String getContentType(String fileName) { - int dotAt = fileName.lastIndexOf('.'); - - if (dotAt > -1) { - String type = CONTENT_TYPES.get().get(fileName.substring(dotAt + 1).toLowerCase(Locale.ENGLISH)); - if (type != null) { - return type; - } - } - - return DEFAULT_CONTENT_TYPE; - } - - // --- Randomization --- - - private static final Random JITTER_RANDOM = new Random(); - - /** - * Returns a random number between {@code number - amount} and - * {@code number + amount}. - */ - public static double jitterAbsolutely(double number, double amount) { - return number - amount + (JITTER_RANDOM.nextDouble() * amount * 2); - } - - /** - * Returns a random number between {@code number - amount} and - * {@code number + amount}. - */ - public static long jitterAbsolutely(long number, long amount) { - return (number - amount + ((long) (JITTER_RANDOM.nextDouble() * (amount * 2 + 1)))); - } - - /** - * Returns a random number between {@code number - number * scale} - * and {@code number + number * scale}. - */ - public static double jitter(double number, double scale) { - return jitterAbsolutely(number, number * scale); - } - - /** - * Returns a random number between {@code number - number * scale} - * and {@code number + number * scale}. - */ - public static long jitter(long number, double scale) { - return jitterAbsolutely(number, (long) (number * scale)); - } - - // --- Deprecated --- - - /** - * Compares the given {@code object1} and {@code object2}. - * - * @return A negative integer, zero, or a positive integer, depending - * on whether the given {@code object1} is less than, equal to, - * or greater than the given {@code object2}. - * @throws IllegalArgumentException If the parameters aren't comparable - * or compatible with each other. - * @throws NullPointerException If one or more parameters are - * {@code null}. - * - * @deprecated Use {@link #compare} instead. - */ - @Deprecated - public static int compareTo(Object object1, Object object2) { - if (object1 == null || object2 == null) { - throw new NullPointerException( - "The [object1] and [object2] parameters cannot be null!"); - - } else { - Class o1c = object1.getClass(); - Class o2c = object2.getClass(); - - if (Comparable.class.isAssignableFrom(o1c) && - o1c.isAssignableFrom(o2c)) { - @SuppressWarnings("unchecked") - Comparable object1Comparable = (Comparable) object1; - return object1Comparable.compareTo(object2); - - } else if (Comparable.class.isAssignableFrom(o2c) && - o2c.isAssignableFrom(o1c)) { - @SuppressWarnings("unchecked") - Comparable object2Comparable = (Comparable) object2; - return 0 - object2Comparable.compareTo(object1); - - } else { - throw new IllegalArgumentException( - "The [object1] and [object2] parameters must be" + - " compatible and comparable!"); - } - } - } - - /** @deprecated Use {@link TypeDefinition#newInstance} instead. */ - @Deprecated - public static T newInstance(Class objectClass) { - return TypeDefinition.getInstance(objectClass).newInstance(); - } - - /** - * Returns a value using any fields or methods with the given - * {@code name} from the given {@code object}. - * - * The order of priority for values returned (if more than one - * are defined) is: - * - actual method {@code name} - * - getter method "get{@code name}" - * - field {@code name} - * - underscore "_{@code name}" field name - * - * Can return value from private methods, but not private fields - * - * @deprecated No replacement. - */ - @Deprecated - public static Object getValue(Object object, String name) { - Class objectClass = object.getClass(); - - for (Class c = objectClass; c != null; c = c.getSuperclass()) { - Method getter = null; - - try { - getter = c.getDeclaredMethod(name); - } catch (NoSuchMethodException error) { - // Try the next getter check. - } - - if (getter == null) { - try { - getter = c.getDeclaredMethod("get" + capitalize(name)); - } catch (NoSuchMethodException error) { - // Getter doesn't exist. Oh well. - } - } - - if (getter != null) { - getter.setAccessible(true); - - try { - return getter.invoke(object); - - } catch (IllegalAccessException ex) { - throw new IllegalStateException(ex); - - } catch (InvocationTargetException ex) { - Throwable cause = ex.getCause(); - throw cause instanceof RuntimeException ? - (RuntimeException) cause : - new RuntimeException(cause); - } - - } else { - Field field = null; - - try { - field = c.getDeclaredField(name); - } catch (NoSuchFieldException error) { - // Try the next field check. - } - - if (field == null) { - try { - field = c.getDeclaredField("_" + name); - } catch (NoSuchFieldException error) { - // Field doesn't exist. Oh well. - } - } - - if (field != null) { - try { - return field.get(object); - } catch (IllegalAccessException ex) { - throw new IllegalStateException(ex); - } - } - } - } - - throw new IllegalArgumentException(String.format( - "[%s] class does not contain a getter named [%s]!", - objectClass.getName(), name)); - } - - // Captializes the given string. - private static String capitalize(String string) { - return string == null || string.length() == 0 ? - string : - string.substring(0, 1).toUpperCase(Locale.ENGLISH) + string.substring(1); - } - - /** @deprecated Use {@link #findClassesFromLoader} instead. */ - @Deprecated - @SuppressWarnings("all") - public static Set> findClasses(ClassLoader loader, Class baseClass) { - return (Set) findClassesFromLoader(loader, baseClass); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Byte asByte(Object byteLike) { - return to(Byte.class, byteLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Date asDate(Object dateLike) { - return to(Date.class, dateLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static > T asEnum(Class type, Object enumLike) { - return to(type, enumLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Double asDouble(Object doubleLike) { - return to(Double.class, doubleLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Float asFloat(Object floatLike) { - return to(Float.class, floatLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Integer asInteger(Object integerLike) { - return to(Integer.class, integerLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Long asLong(Object longLike) { - return to(Long.class, longLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Short asShort(Object shortLike) { - return to(Short.class, shortLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static UUID asUuid(Object uuidLike) { - return to(UUID.class, uuidLike); - } - - /** @deprecated Use {@link ErrorUtils#errorIf} instead. */ - @Deprecated - public static void errorIf(boolean condition, String parameterName, String message) { - ErrorUtils.errorIf(condition, parameterName, message); - } - - /** @deprecated Use {@link ErrorUtils#errorIfNull} instead. */ - @Deprecated - public static void errorIfNull(Object object, String parameterName) { - ErrorUtils.errorIfNull(object, parameterName); - } - - /** @deprecated Use {@link ErrorUtils#errorIfBlank} instead. */ - @Deprecated - public static void errorIfBlank(Object object, String parameterName) { - ErrorUtils.errorIfBlank(object, parameterName); - } - - /** @deprecated Use {@link CollectionUtils#getByPath} instead. */ - @Deprecated - public static Object getByPath(Object object, String path) { - return CollectionUtils.getByPath(object, path); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/old/ObjectUtils.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/old/ObjectUtils.java deleted file mode 100755 index 41e929b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/old/ObjectUtils.java +++ /dev/null @@ -1,687 +0,0 @@ -package com.psddev.dari.util; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.lang.reflect.Array; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Random; -import java.util.Set; -import java.util.UUID; - -/** Object utility methods. */ -public abstract class ObjectUtils { - - private static final ClassFinder CLASS_FINDER = new ClassFinder(); - private static final JsonProcessor JSON_PROCESSOR = new JsonProcessor(); - - private static final Map> PRIMITIVE_CLASSES; static { - Map> m = new HashMap>(); - for (Class c : new Class[] { - byte.class, short.class, int.class, long.class, - float.class, double.class, boolean.class, char.class }) { - m.put(c.getName(), c); - } - PRIMITIVE_CLASSES = m; - } - - // Because Class.forName is pretty slow. - private static final Map>> - CLASSES_BY_LOADER = new PullThroughCache>>() { - - @Override - protected Map> produce(final ClassLoader loader) { - return new PullThroughCache>() { - - @Override - protected Class produce(String name) { - if (name != null) { - try { - return Class.forName(name, false, loader); - } catch (ClassNotFoundException error) { - // Falls through to return null below. - } catch (NoClassDefFoundError error) { - // Falls through to return null below. - } - } - return null; - } - }; - } - }; - - /** - * Returns {@code true} if the given {@code object1} and {@code object2}, - * either of which may be {@code null}, are equal. - * - * @see Object#equals(Object) - */ - public static boolean equals(Object object1, Object object2) { - if (object1 == object2) { - return true; - - } else if (object1 == null || object2 == null) { - return false; - - } else if (object1 instanceof Enum && object2 instanceof String) { - return ((Enum) object1).name().equals(object2); - - } else if (object1 instanceof String && object2 instanceof Enum) { - return object1.equals(((Enum) object2).name()); - - } else { - return object1.equals(object2); - } - } - - /** - * Returns the hash code value for the given {@code objects}, - * or 0 if it's {@code null}. - */ - public static int hashCode(Object... objects) { - if (objects == null) { - return 0; - - } else if (objects.length == 1) { - Object object = objects[0]; - return object == null ? 0 : object.hashCode(); - - } else { - return Arrays.hashCode(objects); - } - } - - /** - * Returns the first non-{@code null} value among the given - * {@code values}. - */ - public static T coalesce(T... values) { - if (values != null) { - for (T value : values) { - if (value != null) { - return value; - } - } - } - return null; - } - - /** - * Returns either the {@linkplain Thread#getContextClassLoader - * context class loader} from the current thread or the one - * that loaded this class. - */ - public static ClassLoader getCurrentClassLoader() { - ClassLoader loader = Thread.currentThread().getContextClassLoader(); - return loader != null ? loader : ObjectUtils.class.getClassLoader(); - } - - /** - * Returns the class with the given {@code name} from the given - * class {@code loader}. - * - * @return {@code null} if the class with the given {@code name} - * doesn't exist. - */ - public static Class getClassFromLoader(ClassLoader loader, String name) { - return CLASSES_BY_LOADER.get(loader).get(name); - } - - /** - * Returns the class with the given {@code name} from the - * {@linkplain #getCurrentClassLoader current class loader}. - * - * @return {@code null} if the class with the given {@code name} - * doesn't exist. - */ - public static Class getClassByName(String name) { - Class c = PRIMITIVE_CLASSES.get(name); - return c != null ? c : getClassFromLoader(getCurrentClassLoader(), name); - } - - /** - * Compares the given {@code object1} and {@code object2} without - * throwing any errors. - * - * @param isNullGreatest If {@code null} is considered to be greater - * than any other value. - * @return A negative integer, zero, or a positive integer, depending - * on whether the given {@code object1} is less than, equal to, - * or greater than the given {@code object2}. If the parameters - * aren't {@linkplain Comparable comparable}, this method - * always returns {@code -1}. - */ - public static int compare(Object object1, Object object2, boolean isNullGreatest) { - if (object1 == null) { - return object2 == null ? 0 : (isNullGreatest ? 1 : -1); - - } else if (object2 == null) { - return isNullGreatest ? -1 : 1; - - } else { - Class object1Class = object1.getClass(); - Class object2Class = object2.getClass(); - - if (Comparable.class.isAssignableFrom(object1Class) && - object1Class.isAssignableFrom(object2Class)) { - @SuppressWarnings("unchecked") - Comparable object1Comparable = (Comparable) object1; - return object1Comparable.compareTo(object2); - - } else if (Comparable.class.isAssignableFrom(object2Class) && - object2Class.isAssignableFrom(object1Class)) { - @SuppressWarnings("unchecked") - Comparable object2Comparable = (Comparable) object2; - return 0 - object2Comparable.compareTo(object1); - - } else { - return -1; - } - } - } - - /** Sorts the given {@code list} using {@link #compare}. */ - public static void sort(List list, boolean isNullGreatest) { - Collections.sort(list, isNullGreatest ? - NULL_GREATEST_COMPARATOR : - NULL_LEAST_COMPARATOR); - } - - private static final Comparator NULL_GREATEST_COMPARATOR = new Comparator() { - @Override - public int compare(Object object1, Object object2) { - return ObjectUtils.compare(object1, object2, true); - } - }; - - private static final Comparator NULL_LEAST_COMPARATOR = new Comparator() { - @Override - public int compare(Object object1, Object object2) { - return ObjectUtils.compare(object1, object2, false); - } - }; - - /** - * Returns {@code true} if the given object is {@code null}, an empty - * string, a string that consists of only whitespaces, an empty - * collection, an empty map, an empty array, or an iterable without - * any elements. - */ - public static boolean isBlank(Object object) { - if (object == null) { - return true; - - } else if (object instanceof String) { - String string = (String) object; - - for (int i = 0, length = string.length(); i < length; ++ i) { - if (!Character.isWhitespace(string.charAt(i))) { - return false; - } - } - - return true; - - } else if (object instanceof Collection) { - return ((Collection) object).isEmpty(); - - } else if (object instanceof Map) { - return ((Map) object).isEmpty(); - - } else if (object.getClass().isArray()) { - return Array.getLength(object) == 0; - - } else if (object instanceof Iterable) { - return !((Iterable) object).iterator().hasNext(); - - } else { - return false; - } - } - - // --- ClassFinder bridge --- - - /** - * {@linkplain ClassFinder#find Finds all classes} that are - * compatible with the given {@code baseClass} within the given - * class {@code loader}. - */ - public static Set> findClassesFromLoader(ClassLoader loader, Class baseClass) { - return CLASS_FINDER.find(loader, baseClass); - } - - /** - * {@linkplain ClassFinder#find Finds all classes} that are - * compatible with the given {@code baseClass} within the - * {@linkplain #getCurrentClassLoader current class loader}. - */ - public static Set> findClasses(Class baseClass) { - return findClassesFromLoader(getCurrentClassLoader(), baseClass); - } - - // --- Converter bridge --- - - private static final Converter CONVERTER; static { - CONVERTER = new Converter(); - CONVERTER.putAllStandardFunctions(); - } - - /** - * Converts the given {@code object} into an instance of the given - * {@code returnType}. - * - * @see Converter#convert(Type, Object) - */ - public static Object to(Type returnType, Object object) { - return CONVERTER.convert(returnType, object); - } - - /** - * Converts the given {@code object} into an instance of the given - * {@code returnClass}. - * - * @see Converter#convert(Class, Object) - */ - public static T to(Class returnClass, Object object) { - return CONVERTER.convert(returnClass, object); - } - - /** - * Converts the given {@code object} into an instance of the type - * referenced by the given {@code returnTypeReference}. - * - * @see Converter#convert(TypeReference, Object) - */ - public static T to(TypeReference returnTypeReference, Object object) { - return CONVERTER.convert(returnTypeReference, object); - } - - // --- JsonProcessor bridge --- - - /** - * Parses the given JSON {@code string} into an object. - * - * @see JsonProcessor#parse(String) - */ - public static Object fromJson(String string) { - return JSON_PROCESSOR.parse(string); - } - - /** - * Parses the given JSON {@code bytes} into an object. - * - * @param bytes If {@code null}, returns {@code null}. - * @see JsonProcessor#parse(byte[]) - */ - public static Object fromJson(byte[] bytes) { - return JSON_PROCESSOR.parse(bytes); - } - - /** - * Generates a JSON string based on the given {@code object}. - * - * @see JsonProcessor#generate(Object) - */ - public static String toJson(Object object) { - return JSON_PROCESSOR.generate(object); - } - - /** - * Generates a JSON string, indented if the given {@code isIndentOutput} - * is {@code true}, based on the given {@code object}. - * - * @see JsonProcessor#setIndentOutput(boolean) - * @see JsonProcessor#generate(Object) - */ - public static String toJson(Object object, boolean isIndentOutput) { - JsonProcessor processor = new JsonProcessor(); - processor.setIndentOutput(isIndentOutput); - return processor.generate(object); - } - - /** - * Generates a JSON string, indented if the given {@code isIndentOutput} - * is {@code true}, based on the given {@code object}, after transforming - * it using the given {@code transformer}. - * - * @see JsonProcessor#setIndentOutput(boolean) - * @see JsonProcessor#setTransformer(Transformer) - * @see JsonProcessor#generate(Object) - */ - public static String toJson(Object object, boolean isIndentOutput, Transformer transformer) { - JsonProcessor processor = new JsonProcessor(); - processor.setIndentOutput(isIndentOutput); - processor.setTransformer(transformer); - return processor.generate(object); - } - - // --- Content type --- - - /** Default content type for {@link #getContentType}. */ - public static final String DEFAULT_CONTENT_TYPE = "application/octet-stream"; - - /** - * File name extensions to content types cache from: - * http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types - */ - private static final PullThroughValue> CONTENT_TYPES = new PullThroughValue>() { - - @Override - protected Map produce() throws IOException { - Map contentTypes = new HashMap(); - InputStream mimeInput = getClass().getResourceAsStream("mime.types"); - BufferedReader mimeInputReader = new BufferedReader(new InputStreamReader(mimeInput, StringUtils.UTF_8)); - - try { - for (String line; (line = mimeInputReader.readLine()) != null; ) { - if (!line.startsWith("#")) { - String[] items = StringUtils.split(line.trim(), "\\s+"); - String contentType = items[0].toLowerCase(); - - for (int j = 1, length = items.length; j < length; ++ j) { - contentTypes.put(items[j].toLowerCase(), contentType); - } - } - } - - } finally { - mimeInputReader.close(); - } - - return contentTypes; - } - }; - - /** - * Returns the content type associated with the given {@code fileName} - * extension, or {@value DEFAULT_CONTENT_TYPE} if not found. - */ - public static String getContentType(String fileName) { - int dotAt = fileName.lastIndexOf('.'); - - if (dotAt > -1) { - String type = CONTENT_TYPES.get().get(fileName.substring(dotAt + 1).toLowerCase()); - if (type != null) { - return type; - } - } - - return DEFAULT_CONTENT_TYPE; - } - - // --- Randomization --- - - private static final Random JITTER_RANDOM = new Random(); - - /** - * Returns a random number between {@code number - amount} and - * {@code number + amount}. - */ - public static double jitterAbsolutely(double number, double amount) { - return number - amount + (JITTER_RANDOM.nextDouble() * amount * 2); - } - - /** - * Returns a random number between {@code number - amount} and - * {@code number + amount}. - */ - public static long jitterAbsolutely(long number, long amount) { - return (number - amount + ((long) (JITTER_RANDOM.nextDouble() * (amount * 2 + 1)))); - } - - /** - * Returns a random number between {@code number - number * scale} - * and {@code number + number * scale}. - */ - public static double jitter(double number, double scale) { - return jitterAbsolutely(number, number * scale); - } - - /** - * Returns a random number between {@code number - number * scale} - * and {@code number + number * scale}. - */ - public static long jitter(long number, double scale) { - return jitterAbsolutely(number, (long) (number * scale)); - } - - // --- Deprecated --- - - /** - * Compares the given {@code object1} and {@code object2}. - * - * @return A negative integer, zero, or a positive integer, depending - * on whether the given {@code object1} is less than, equal to, - * or greater than the given {@code object2}. - * @throws IllegalArgumentException If the parameters aren't comparable - * or compatible with each other. - * @throws NullPointerException If one or more parameters are - * {@code null}. - * - * @deprecated Use {@link #compare} instead. - */ - @Deprecated - public static int compareTo(Object object1, Object object2) { - if (object1 == null || object2 == null) { - throw new NullPointerException( - "The [object1] and [object2] parameters cannot be null!"); - - } else { - Class o1c = object1.getClass(); - Class o2c = object2.getClass(); - - if (Comparable.class.isAssignableFrom(o1c) && - o1c.isAssignableFrom(o2c)) { - @SuppressWarnings("unchecked") - Comparable object1Comparable = (Comparable) object1; - return object1Comparable.compareTo(object2); - - } else if (Comparable.class.isAssignableFrom(o2c) && - o2c.isAssignableFrom(o1c)) { - @SuppressWarnings("unchecked") - Comparable object2Comparable = (Comparable) object2; - return 0 - object2Comparable.compareTo(object1); - - } else { - throw new IllegalArgumentException( - "The [object1] and [object2] parameters must be" + - " compatible and comparable!"); - } - } - } - - /** @deprecated Use {@link TypeDefinition#newInstance} instead. */ - @Deprecated - public static T newInstance(Class objectClass) { - return TypeDefinition.getInstance(objectClass).newInstance(); - } - - /** - * Returns a value using any fields or methods with the given - * {@code name} from the given {@code object}. - * - * The order of priority for values returned (if more than one - * are defined) is: - * - actual method {@code name} - * - getter method "get{@code name}" - * - field {@code name} - * - underscore "_{@code name}" field name - * - * Can return value from private methods, but not private fields - * - * @deprecated No replacement. - */ - @Deprecated - public static Object getValue(Object object, String name) { - Class objectClass = object.getClass(); - - for (Class c = objectClass; c != null; c = c.getSuperclass()) { - Method getter = null; - - try { - getter = c.getDeclaredMethod(name); - } catch (NoSuchMethodException error) { - // Try the next getter check. - } - - if (getter == null) { - try { - getter = c.getDeclaredMethod("get" + capitalize(name)); - } catch (NoSuchMethodException error) { - // Getter doesn't exist. Oh well. - } - } - - if (getter != null) { - getter.setAccessible(true); - - try { - return getter.invoke(object); - - } catch (IllegalAccessException ex) { - throw new IllegalStateException(ex); - - } catch (InvocationTargetException ex) { - Throwable cause = ex.getCause(); - throw cause instanceof RuntimeException ? - (RuntimeException) cause : - new RuntimeException(cause); - } - - } else { - Field field = null; - - try { - field = c.getDeclaredField(name); - } catch (NoSuchFieldException error) { - // Try the next field check. - } - - if (field == null) { - try { - field = c.getDeclaredField("_" + name); - } catch (NoSuchFieldException error) { - // Field doesn't exist. Oh well. - } - } - - if (field != null) { - try { - return field.get(object); - } catch (IllegalAccessException ex) { - throw new IllegalStateException(ex); - } - } - } - } - - throw new IllegalArgumentException(String.format( - "[%s] class does not contain a getter named [%s]!", - objectClass.getName(), name)); - } - - // Captializes the given string. - private static String capitalize(String string) { - return string == null || string.length() == 0 ? - string : - string.substring(0, 1).toUpperCase() + string.substring(1); - } - - /** @deprecated Use {@link #findClassesFromLoader} instead. */ - @Deprecated - @SuppressWarnings("all") - public static Set> findClasses(ClassLoader loader, Class baseClass) { - return (Set) findClassesFromLoader(loader, baseClass); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Byte asByte(Object byteLike) { - return to(Byte.class, byteLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Date asDate(Object dateLike) { - return to(Date.class, dateLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static > T asEnum(Class type, Object enumLike) { - return to(type, enumLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Double asDouble(Object doubleLike) { - return to(Double.class, doubleLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Float asFloat(Object floatLike) { - return to(Float.class, floatLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Integer asInteger(Object integerLike) { - return to(Integer.class, integerLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Long asLong(Object longLike) { - return to(Long.class, longLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static Short asShort(Object shortLike) { - return to(Short.class, shortLike); - } - - /** @deprecated Use {@link #to} instead. */ - @Deprecated - public static UUID asUuid(Object uuidLike) { - return to(UUID.class, uuidLike); - } - - /** @deprecated Use {@link ErrorUtils#errorIf} instead. */ - @Deprecated - public static void errorIf(boolean condition, String parameterName, String message) { - ErrorUtils.errorIf(condition, parameterName, message); - } - - /** @deprecated Use {@link ErrorUtils#errorIfNull} instead. */ - @Deprecated - public static void errorIfNull(Object object, String parameterName) { - ErrorUtils.errorIfNull(object, parameterName); - } - - /** @deprecated Use {@link ErrorUtils#errorIfBlank} instead. */ - @Deprecated - public static void errorIfBlank(Object object, String parameterName) { - ErrorUtils.errorIfBlank(object, parameterName); - } - - /** @deprecated Use {@link CollectionUtils#getByPath} instead. */ - @Deprecated - public static Object getByPath(Object object, String path) { - return CollectionUtils.getByPath(object, path); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/pair.info deleted file mode 100755 index eed80d5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#52860/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:52860 -comSha:641bc27d5470a167d3ca2fefd6ae4c619a27c012 -parentComSha:5f098cd76c5e7aff3237dc54664709c515095ad4 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/ObjectUtils.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/ObjectUtils.java -StartLineNum:598 -EndLineNum:598 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/comMsg.txt deleted file mode 100755 index ee04a0c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of PMD design.xml/UseLocaleWithCaseConversions. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/diff.diff deleted file mode 100755 index e31a082..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/SettingsDebugServlet.java b/util/src/main/java/com/psddev/dari/util/SettingsDebugServlet.java -index a57de671..cf2cc11f 100644 ---- a/util/src/main/java/com/psddev/dari/util/SettingsDebugServlet.java -+++ b/util/src/main/java/com/psddev/dari/util/SettingsDebugServlet.java -@@ -7,0 +8 @@ import java.lang.reflect.Method; -+import java.util.Locale; -@@ -42 +43 @@ public class SettingsDebugServlet extends HttpServlet { -- String keyLowered = key.toLowerCase(); -+ String keyLowered = key.toLowerCase(Locale.ENGLISH); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/new/SettingsDebugServlet.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/new/SettingsDebugServlet.java deleted file mode 100755 index cf2cc11..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/new/SettingsDebugServlet.java +++ /dev/null @@ -1,109 +0,0 @@ -package com.psddev.dari.util; - -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.Locale; -import java.util.Map; -import java.util.TreeMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.sql.DataSource; - -/** Debug servlet for inspecting {@linkplain Settings global settings}. */ -@DebugFilter.Path("settings") -public class SettingsDebugServlet extends HttpServlet { - - private static final long serialVersionUID = 1L; - - // --- HttpServlet support --- - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - new DebugFilter.PageWriter(getServletContext(), request, response) {{ - startPage("Settings"); - - writeStart("table", "class", "table table-condensed table-striped"); - writeStart("thead"); - writeStart("tr"); - writeStart("th").writeHtml("Key").writeEnd(); - writeStart("th").writeHtml("Value").writeEnd(); - writeStart("th").writeHtml("Class").writeEnd(); - writeEnd(); - writeEnd(); - - writeStart("tbody"); - for (Map.Entry entry : flatten(Settings.asMap()).entrySet()) { - String key = entry.getKey(); - String keyLowered = key.toLowerCase(Locale.ENGLISH); - Object value = entry.getValue(); - - writeStart("tr"); - writeStart("td").writeHtml(key).writeEnd(); - - writeStart("td"); - if (keyLowered.contains("password") || - keyLowered.contains("secret")) { - writeStart("span", "class", "label label-warning").writeHtml("Hidden").writeEnd(); - } else { - writeHtml(value); - } - - writeStart("td"); - writeHtml(value != null ? value.getClass().getName() : "N/A"); - writeEnd(); - writeEnd(); - } - writeEnd(); - writeEnd(); - - endPage(); - }}; - } - - private Map flatten(Map map) { - Map flattened = new TreeMap(String.CASE_INSENSITIVE_ORDER); - collectFlattenedValues(flattened, null, map); - return flattened; - } - - private void collectFlattenedValues(Map flattened, String key, Object value) { - if (value instanceof Map) { - String prefix = key == null ? "" : key + "/"; - for (Map.Entry entry : ((Map) value).entrySet()) { - collectFlattenedValues(flattened, prefix + entry.getKey(), entry.getValue()); - } - - } else if (value instanceof DataSource) { - try { - Map map = new TreeMap(); - - for (PropertyDescriptor desc : Introspector.getBeanInfo(value.getClass()).getPropertyDescriptors()) { - try { - Method getter = desc.getReadMethod(); - Method setter = desc.getWriteMethod(); - - if (getter != null && setter != null) { - getter.setAccessible(true); - map.put(desc.getName(), getter.invoke(value)); - } - } catch (Exception error) { - } - } - - collectFlattenedValues(flattened, key, map); - - } catch (IntrospectionException error) { - flattened.put(key, value); - } - - } else { - flattened.put(key, value); - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/old/SettingsDebugServlet.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/old/SettingsDebugServlet.java deleted file mode 100755 index a57de67..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/old/SettingsDebugServlet.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.psddev.dari.util; - -import java.beans.IntrospectionException; -import java.beans.Introspector; -import java.beans.PropertyDescriptor; -import java.io.IOException; -import java.lang.reflect.Method; -import java.util.Map; -import java.util.TreeMap; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.sql.DataSource; - -/** Debug servlet for inspecting {@linkplain Settings global settings}. */ -@DebugFilter.Path("settings") -public class SettingsDebugServlet extends HttpServlet { - - private static final long serialVersionUID = 1L; - - // --- HttpServlet support --- - - @Override - protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { - new DebugFilter.PageWriter(getServletContext(), request, response) {{ - startPage("Settings"); - - writeStart("table", "class", "table table-condensed table-striped"); - writeStart("thead"); - writeStart("tr"); - writeStart("th").writeHtml("Key").writeEnd(); - writeStart("th").writeHtml("Value").writeEnd(); - writeStart("th").writeHtml("Class").writeEnd(); - writeEnd(); - writeEnd(); - - writeStart("tbody"); - for (Map.Entry entry : flatten(Settings.asMap()).entrySet()) { - String key = entry.getKey(); - String keyLowered = key.toLowerCase(); - Object value = entry.getValue(); - - writeStart("tr"); - writeStart("td").writeHtml(key).writeEnd(); - - writeStart("td"); - if (keyLowered.contains("password") || - keyLowered.contains("secret")) { - writeStart("span", "class", "label label-warning").writeHtml("Hidden").writeEnd(); - } else { - writeHtml(value); - } - - writeStart("td"); - writeHtml(value != null ? value.getClass().getName() : "N/A"); - writeEnd(); - writeEnd(); - } - writeEnd(); - writeEnd(); - - endPage(); - }}; - } - - private Map flatten(Map map) { - Map flattened = new TreeMap(String.CASE_INSENSITIVE_ORDER); - collectFlattenedValues(flattened, null, map); - return flattened; - } - - private void collectFlattenedValues(Map flattened, String key, Object value) { - if (value instanceof Map) { - String prefix = key == null ? "" : key + "/"; - for (Map.Entry entry : ((Map) value).entrySet()) { - collectFlattenedValues(flattened, prefix + entry.getKey(), entry.getValue()); - } - - } else if (value instanceof DataSource) { - try { - Map map = new TreeMap(); - - for (PropertyDescriptor desc : Introspector.getBeanInfo(value.getClass()).getPropertyDescriptors()) { - try { - Method getter = desc.getReadMethod(); - Method setter = desc.getWriteMethod(); - - if (getter != null && setter != null) { - getter.setAccessible(true); - map.put(desc.getName(), getter.invoke(value)); - } - } catch (Exception error) { - } - } - - collectFlattenedValues(flattened, key, map); - - } catch (IntrospectionException error) { - flattened.put(key, value); - } - - } else { - flattened.put(key, value); - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/pair.info deleted file mode 100755 index 93f05c5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53053/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:53053 -comSha:a2c1974da04a01bcebd1251b487b72e3c2ac90af -parentComSha:d019326625ce2c1c2469ada51de6696b9e3fca45 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/SettingsDebugServlet.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/SettingsDebugServlet.java -StartLineNum:42 -EndLineNum:42 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/comMsg.txt deleted file mode 100755 index 3aa5042..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'release/2.1' \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/diff.diff deleted file mode 100755 index 0f2df24..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java b/util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -index a964be7e..777346c6 100644 ---- a/util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -+++ b/util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -@@ -6,0 +7 @@ import java.util.Iterator; -+import java.util.Locale; -@@ -75 +76 @@ public class HttpServletRequestMap implements Map { -- String key = headerName.toUpperCase().replace('-', '_'); -+ String key = headerName.toUpperCase(Locale.ENGLISH).replace('-', '_'); -@@ -138 +139 @@ public class HttpServletRequestMap implements Map { -- if (lazy != null) { -+ if (lazy != null) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/new/HttpServletRequestMap.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/new/HttpServletRequestMap.java deleted file mode 100755 index 777346c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/new/HttpServletRequestMap.java +++ /dev/null @@ -1,217 +0,0 @@ -package com.psddev.dari.util; - -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - -/** @deprecated No replacement. */ -@Deprecated -@SuppressWarnings("all") -public class HttpServletRequestMap implements Map { - - public static final String AUTHORIZATION_KEY = "AUTHORIZATION"; - public static final String AUTH_TYPE_KEY = "AUTH_TYPE"; - public static final String CONTENT_LENGTH_KEY = "CONTENT_LENGTH"; - public static final String CONTENT_TYPE_KEY = "CONTENT_TYPE"; - public static final String GATEWAY_INTERFACE_KEY = "GATEWAY_INTERFACE"; - public static final String HTTP_PREFIX = "HTTP_"; - public static final String PATH_INFO_KEY = "PATH_INFO"; - public static final String PATH_TRANSLATED_KEY = "PATH_TRANSLATED"; - public static final String PROXY_AUTHORIZATION_KEY = "PROXY_AUTHORIZATION"; - public static final String QUERY_STRING_KEY = "QUERY_STRING"; - public static final String REMOTE_ADDR_KEY = "REMOTE_ADDR"; - public static final String REMOTE_HOST_KEY = "REMOTE_HOST"; - public static final String REMOTE_USER_KEY = "REMOTE_USER"; - public static final String REQUEST_METHOD_KEY = "REQUEST_METHOD"; - public static final String REQUEST_URI_KEY = "REQUEST_URI"; - public static final String SCRIPT_NAME_KEY = "SCRIPT_NAME"; - public static final String SERVER_NAME_KEY = "SERVER_NAME"; - public static final String SERVER_PORT_KEY = "SERVER_PORT"; - public static final String SERVER_PROTOCOL_KEY = "SERVER_PROTOCOL"; - public static final String SERVER_SOFTWARE_KEY = "SERVER_SOFTWARE"; - - private final ServletContext context; - private final HttpServletRequest request; - private final Map all = new HashMap(); - private final Map lazies = new HashMap(); - - /** - * Creates an instance based on the given {@code context} and - * {@code request}. - */ - public HttpServletRequestMap(ServletContext context, HttpServletRequest request) { - - this.context = context; - this.request = request; - - all.put(AUTH_TYPE_KEY, request.getAuthType()); - all.put(CONTENT_TYPE_KEY, request.getContentType()); - all.put(GATEWAY_INTERFACE_KEY, "CGI/1.1"); - all.put(PATH_INFO_KEY, request.getPathInfo()); - all.put(QUERY_STRING_KEY, request.getQueryString()); - all.put(REMOTE_ADDR_KEY, request.getRemoteAddr()); - all.put(REMOTE_USER_KEY, request.getRemoteUser()); - all.put(REQUEST_METHOD_KEY, request.getMethod()); - all.put(REQUEST_URI_KEY, request.getRequestURI()); - all.put(SCRIPT_NAME_KEY, request.getServletPath()); - all.put(SERVER_NAME_KEY, request.getServerName()); - all.put(SERVER_PROTOCOL_KEY, request.getProtocol()); - all.put(SERVER_SOFTWARE_KEY, context.getServerInfo()); - - int contentLength = request.getContentLength(); - all.put(CONTENT_LENGTH_KEY, contentLength > 0 ? String.valueOf(contentLength) : null); - - int port = request.getServerPort(); - all.put(SERVER_PORT_KEY, String.valueOf(port == 0 ? -1 : port)); - - for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) { - String headerName = e.nextElement(); - String key = headerName.toUpperCase(Locale.ENGLISH).replace('-', '_'); - if (!(AUTHORIZATION_KEY.equals(key) - || PROXY_AUTHORIZATION_KEY.equals(key))) { - all.put(HTTP_PREFIX + key, request.getHeader(headerName)); - } - } - - lazies.put(PATH_TRANSLATED_KEY, new Lazy() { - - @Override - public Object resolve(String key) { - return HttpServletRequestMap.this.request.getPathTranslated(); - } - }); - - lazies.put(REMOTE_HOST_KEY, new Lazy() { - - @Override - public Object resolve(String key) { - return HttpServletRequestMap.this.request.getRemoteHost(); - } - }); - } - - /** Resolves all the lazy values. */ - private void resolveAll() { - for (Iterator> i = lazies.entrySet().iterator(); i.hasNext(); ) { - Map.Entry e = i.next(); - i.remove(); - String key = e.getKey(); - Object value = e.getValue().resolve(key); - all.put(key, ObjectUtils.isBlank(value) ? null : value.toString()); - } - } - - // --- Map support --- - - @Override - public void clear() { - all.clear(); - lazies.clear(); - } - - @Override - public boolean containsKey(Object key) { - return all.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - resolveAll(); - return all.containsValue(value); - } - - @Override - public Set> entrySet() { - resolveAll(); - return all.entrySet(); - } - - @Override - public String get(Object key) { - Lazy lazy = lazies.get(key); - if (lazy != null) { - lazies.remove(key); - String keyString = (String) key; - Object value = lazy.resolve(keyString); - all.put(keyString, ObjectUtils.isBlank(value) ? null : value.toString()); - } - return all.get(key); - } - - @Override - public boolean isEmpty() { - return all.isEmpty(); - } - - @Override - public Set keySet() { - return all.keySet(); - } - - @Override - public String put(String key, String value) { - lazies.remove(key); - return all.put(key, value); - } - - @Override - public void putAll(Map map) { - lazies.keySet().removeAll(map.keySet()); - all.putAll(map); - } - - @Override - public String remove(Object key) { - lazies.remove(key); - return all.remove(key); - } - - @Override - public int size() { - return all.size(); - } - - @Override - public Collection values() { - resolveAll(); - return all.values(); - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } else if (other instanceof Map) { - resolveAll(); - return all.equals(other); - } else { - return false; - } - } - - @Override - public int hashCode() { - resolveAll(); - return all.hashCode(); - } - - @Override - public String toString() { - resolveAll(); - return all.toString(); - } - - // --- Nested --- - - private interface Lazy { - - public Object resolve(String key); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/old/HttpServletRequestMap.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/old/HttpServletRequestMap.java deleted file mode 100755 index a964be7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/old/HttpServletRequestMap.java +++ /dev/null @@ -1,216 +0,0 @@ -package com.psddev.dari.util; - -import java.util.Collection; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; - -/** @deprecated No replacement. */ -@Deprecated -@SuppressWarnings("all") -public class HttpServletRequestMap implements Map { - - public static final String AUTHORIZATION_KEY = "AUTHORIZATION"; - public static final String AUTH_TYPE_KEY = "AUTH_TYPE"; - public static final String CONTENT_LENGTH_KEY = "CONTENT_LENGTH"; - public static final String CONTENT_TYPE_KEY = "CONTENT_TYPE"; - public static final String GATEWAY_INTERFACE_KEY = "GATEWAY_INTERFACE"; - public static final String HTTP_PREFIX = "HTTP_"; - public static final String PATH_INFO_KEY = "PATH_INFO"; - public static final String PATH_TRANSLATED_KEY = "PATH_TRANSLATED"; - public static final String PROXY_AUTHORIZATION_KEY = "PROXY_AUTHORIZATION"; - public static final String QUERY_STRING_KEY = "QUERY_STRING"; - public static final String REMOTE_ADDR_KEY = "REMOTE_ADDR"; - public static final String REMOTE_HOST_KEY = "REMOTE_HOST"; - public static final String REMOTE_USER_KEY = "REMOTE_USER"; - public static final String REQUEST_METHOD_KEY = "REQUEST_METHOD"; - public static final String REQUEST_URI_KEY = "REQUEST_URI"; - public static final String SCRIPT_NAME_KEY = "SCRIPT_NAME"; - public static final String SERVER_NAME_KEY = "SERVER_NAME"; - public static final String SERVER_PORT_KEY = "SERVER_PORT"; - public static final String SERVER_PROTOCOL_KEY = "SERVER_PROTOCOL"; - public static final String SERVER_SOFTWARE_KEY = "SERVER_SOFTWARE"; - - private final ServletContext context; - private final HttpServletRequest request; - private final Map all = new HashMap(); - private final Map lazies = new HashMap(); - - /** - * Creates an instance based on the given {@code context} and - * {@code request}. - */ - public HttpServletRequestMap(ServletContext context, HttpServletRequest request) { - - this.context = context; - this.request = request; - - all.put(AUTH_TYPE_KEY, request.getAuthType()); - all.put(CONTENT_TYPE_KEY, request.getContentType()); - all.put(GATEWAY_INTERFACE_KEY, "CGI/1.1"); - all.put(PATH_INFO_KEY, request.getPathInfo()); - all.put(QUERY_STRING_KEY, request.getQueryString()); - all.put(REMOTE_ADDR_KEY, request.getRemoteAddr()); - all.put(REMOTE_USER_KEY, request.getRemoteUser()); - all.put(REQUEST_METHOD_KEY, request.getMethod()); - all.put(REQUEST_URI_KEY, request.getRequestURI()); - all.put(SCRIPT_NAME_KEY, request.getServletPath()); - all.put(SERVER_NAME_KEY, request.getServerName()); - all.put(SERVER_PROTOCOL_KEY, request.getProtocol()); - all.put(SERVER_SOFTWARE_KEY, context.getServerInfo()); - - int contentLength = request.getContentLength(); - all.put(CONTENT_LENGTH_KEY, contentLength > 0 ? String.valueOf(contentLength) : null); - - int port = request.getServerPort(); - all.put(SERVER_PORT_KEY, String.valueOf(port == 0 ? -1 : port)); - - for (Enumeration e = request.getHeaderNames(); e.hasMoreElements(); ) { - String headerName = e.nextElement(); - String key = headerName.toUpperCase().replace('-', '_'); - if (!(AUTHORIZATION_KEY.equals(key) - || PROXY_AUTHORIZATION_KEY.equals(key))) { - all.put(HTTP_PREFIX + key, request.getHeader(headerName)); - } - } - - lazies.put(PATH_TRANSLATED_KEY, new Lazy() { - - @Override - public Object resolve(String key) { - return HttpServletRequestMap.this.request.getPathTranslated(); - } - }); - - lazies.put(REMOTE_HOST_KEY, new Lazy() { - - @Override - public Object resolve(String key) { - return HttpServletRequestMap.this.request.getRemoteHost(); - } - }); - } - - /** Resolves all the lazy values. */ - private void resolveAll() { - for (Iterator> i = lazies.entrySet().iterator(); i.hasNext(); ) { - Map.Entry e = i.next(); - i.remove(); - String key = e.getKey(); - Object value = e.getValue().resolve(key); - all.put(key, ObjectUtils.isBlank(value) ? null : value.toString()); - } - } - - // --- Map support --- - - @Override - public void clear() { - all.clear(); - lazies.clear(); - } - - @Override - public boolean containsKey(Object key) { - return all.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - resolveAll(); - return all.containsValue(value); - } - - @Override - public Set> entrySet() { - resolveAll(); - return all.entrySet(); - } - - @Override - public String get(Object key) { - Lazy lazy = lazies.get(key); - if (lazy != null) { - lazies.remove(key); - String keyString = (String) key; - Object value = lazy.resolve(keyString); - all.put(keyString, ObjectUtils.isBlank(value) ? null : value.toString()); - } - return all.get(key); - } - - @Override - public boolean isEmpty() { - return all.isEmpty(); - } - - @Override - public Set keySet() { - return all.keySet(); - } - - @Override - public String put(String key, String value) { - lazies.remove(key); - return all.put(key, value); - } - - @Override - public void putAll(Map map) { - lazies.keySet().removeAll(map.keySet()); - all.putAll(map); - } - - @Override - public String remove(Object key) { - lazies.remove(key); - return all.remove(key); - } - - @Override - public int size() { - return all.size(); - } - - @Override - public Collection values() { - resolveAll(); - return all.values(); - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } else if (other instanceof Map) { - resolveAll(); - return all.equals(other); - } else { - return false; - } - } - - @Override - public int hashCode() { - resolveAll(); - return all.hashCode(); - } - - @Override - public String toString() { - resolveAll(); - return all.toString(); - } - - // --- Nested --- - - private interface Lazy { - - public Object resolve(String key); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/pair.info deleted file mode 100755 index cb52da3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53134/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:53134 -comSha:6233bf6c2a08cf1b4daef5ff9a16c0c97a874522 -parentComSha:ddc6eb4d3bdc5fd4f1893f96b3ed2bae7842f258 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/HttpServletRequestMap.java -StartLineNum:75 -EndLineNum:75 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/comMsg.txt deleted file mode 100755 index 2685419..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/comMsg.txt +++ /dev/null @@ -1,4 +0,0 @@ -Merge branch 'release/2.1' - -Conflicts: - db/src/main/java/com/psddev/dari/db/SqlDatabase.java \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/diff.diff deleted file mode 100755 index fc84623..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/FormTag.java b/util/src/main/java/com/psddev/dari/util/FormTag.java -index b473a60a..4d974c93 100644 ---- a/util/src/main/java/com/psddev/dari/util/FormTag.java -+++ b/util/src/main/java/com/psddev/dari/util/FormTag.java -@@ -5,0 +6 @@ import java.util.LinkedHashMap; -+import java.util.Locale; -@@ -174 +175 @@ public class FormTag extends TagSupport implements DynamicAttributes { -- "method", method.toLowerCase(), -+ "method", method.toLowerCase(Locale.ENGLISH), \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/new/FormTag.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/new/FormTag.java deleted file mode 100755 index 4d974c9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/new/FormTag.java +++ /dev/null @@ -1,301 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.DynamicAttributes; -import javax.servlet.jsp.tagext.TagSupport; - -@SuppressWarnings("serial") -public class FormTag extends TagSupport implements DynamicAttributes { - - private static final String PARAMETER_PREFIX = "_f."; - public static final String ID_PARAMETER = PARAMETER_PREFIX + "id"; - - private static final String ATTRIBUTE_PREFIX = FormTag.class.getName() + "."; - private static final String PROCESSOR_ATTRIBUTE_PREFIX = ATTRIBUTE_PREFIX + "processor/"; - - /** Map of the MD5 hash of a processor class name to the Class object itself. */ - private static final ConcurrentHashMap> PROCESSOR_CLASSES = - new ConcurrentHashMap>(); - - private String method; - private Class processorClass; - - private String varProcessor; - private String varSuccess; - private String varError; - private String varResult; - - private transient Boolean success; - private transient Object result; - private transient Object error; - - private final Map attributes = new LinkedHashMap(); - - /** - * Sets the form submission method. - * - * @param method Can't be {@code null}. - */ - public void setMethod(String method) { - ErrorUtils.errorIfNull(method, "method"); - - this.method = method; - } - - /** - * Sets the name of the processor class. - * - * @param processor The class name must be valid, and the class must - * implement {@link FormProcessor}. - */ - @SuppressWarnings("unchecked") - public void setProcessor(String processor) { - Class pc = ObjectUtils.getClassByName(processor); - - ErrorUtils.errorIf(pc == null, processor, "isn't a valid class name!"); - ErrorUtils.errorIf(!FormProcessor.class.isAssignableFrom(pc), pc.getName(), "doesn't implement [" + FormProcessor.class.getName() + "]!"); - - this.processorClass = (Class) pc; - } - - public Class getProcessorClass() { - return this.processorClass; - } - - /** - * Sets the name of the page-scoped variable to store the processor - * instance. - */ - public void setVarProcessor(String varProcessor) { - this.varProcessor = varProcessor; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * success flag. - */ - public void setVarSuccess(String varSuccess) { - this.varSuccess = varSuccess; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * error. - */ - public void setVarError(String varError) { - this.varError = varError; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * result. - * - * @return May be {@code null}. - */ - public void setVarResult(String varResult) { - this.varResult = varResult; - } - - /** Returns a unique identifier for this form. */ - public String getFormId() { - return Static.getProcessorId(processorClass) + (getId() != null ? ("/" + getId()) : ""); - } - - /** Returns the processor for this form. */ - public FormProcessor getProcessorInstance() { - return Static.getProcessorById(getFormId(), (HttpServletRequest) pageContext.getRequest()); - } - - // --- Getters for the transient variables --- - - /** - * Return true if this form was processed successfully, or false if not. - * Null is returned if this method is called outside the context of this - * form's start and end tags. - * - * @return - */ - public Boolean isSuccess() { - return success; - } - - /** - * Returns the result of processing this form, or null if there was an error - * or this method is called outside the context of this form's start and - * end tags. - * - * @return - */ - public Object getResult() { - return result; - } - - /** - * Returns the error generated attempting to process this form, or null if - * if the form was processed successfully or this method is called outside - * the context of this form's start and end tags. - * - * @return - */ - public Object getError() { - return error; - } - - // --- TagSupport support --- - - @Override - public int doStartTag() throws JspException { - - HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); - - String formId = getFormId(); - FormProcessor processor = getProcessorInstance(); - - if (!ObjectUtils.isBlank(varProcessor)) { - pageContext.setAttribute(varProcessor, processor); - } - - // Write the FORM start tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("form", - "id", getId(), - "method", method.toLowerCase(Locale.ENGLISH), - "action", "", - attributes); - writer.writeTag("input", - "type", "hidden", - "name", ID_PARAMETER, - "value", formId); - - - // If process() was already called by FormFilter - String bufferedOutput = FormFilter.Static.getBufferedOutput(formId, request); - if (bufferedOutput != null) { - writer.write(bufferedOutput); - - success = FormFilter.Static.isFormSuccess(request); - result = FormFilter.Static.getFormResult(request); - error = FormFilter.Static.getFormError(request); - - } else { - // process it - try { - result = processor.process(request, new HttpServletResponseWrapper((HttpServletResponse) pageContext.getResponse()) { - private PrintWriter writer; { - writer = new PrintWriter(pageContext.getOut()); - } - @Override - public PrintWriter getWriter() { - return writer; - } - }); - success = true; - - } catch (IOException e) { - throw e; - - } catch (Throwable e) { - error = e; - success = false; - } - } - - // Set the status vars if they are defined - if (!ObjectUtils.isBlank(varSuccess)) { - pageContext.setAttribute(varSuccess, isSuccess()); - } - if (!ObjectUtils.isBlank(varResult)) { - pageContext.setAttribute(varResult, getResult()); - } - if (!ObjectUtils.isBlank(varError)) { - pageContext.setAttribute(varError, getError()); - } - - } catch (IOException error) { - throw new JspException(error); - } - - return EVAL_BODY_INCLUDE; - } - - @Override - public int doEndTag() throws JspException { - // Write the FORM end tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("/form"); - - } catch (IOException error) { - throw new JspException(error); - - } finally { - // null out the transient variables - success = null; - error = null; - result = null; - } - - return EVAL_PAGE; - } - - // --- DynamicAttribute support --- - - @Override - public void setDynamicAttribute(String uri, String localName, Object value) { - attributes.put(localName, value != null ? value.toString() : null); - } - - public static final class Static { - - public static FormProcessor getProcessorById(String id, HttpServletRequest request) { - if (id == null) { - return null; - } - - // Strip off the form ID attribute part of the ID if it exists. - String processorId; - int slashAt = id.indexOf('/'); - if (slashAt < 0) { - processorId = id; - - } else { - processorId = id.substring(0, slashAt); - } - - FormProcessor processor = (FormProcessor) request.getAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id); - - if (processor == null) { - Class processorClass = PROCESSOR_CLASSES.get(processorId); - if (processorClass != null) { - processor = TypeDefinition.getInstance(processorClass).newInstance(); - } - if (processor != null) { - request.setAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id, processor); - } - } - - return processor; - } - - private static String getProcessorId(Class processorClass) { - String hashId = StringUtils.hex(StringUtils.md5(processorClass.getName())); - PROCESSOR_CLASSES.putIfAbsent(hashId, processorClass); - return hashId; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/old/FormTag.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/old/FormTag.java deleted file mode 100755 index b473a60..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/old/FormTag.java +++ /dev/null @@ -1,300 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.DynamicAttributes; -import javax.servlet.jsp.tagext.TagSupport; - -@SuppressWarnings("serial") -public class FormTag extends TagSupport implements DynamicAttributes { - - private static final String PARAMETER_PREFIX = "_f."; - public static final String ID_PARAMETER = PARAMETER_PREFIX + "id"; - - private static final String ATTRIBUTE_PREFIX = FormTag.class.getName() + "."; - private static final String PROCESSOR_ATTRIBUTE_PREFIX = ATTRIBUTE_PREFIX + "processor/"; - - /** Map of the MD5 hash of a processor class name to the Class object itself. */ - private static final ConcurrentHashMap> PROCESSOR_CLASSES = - new ConcurrentHashMap>(); - - private String method; - private Class processorClass; - - private String varProcessor; - private String varSuccess; - private String varError; - private String varResult; - - private transient Boolean success; - private transient Object result; - private transient Object error; - - private final Map attributes = new LinkedHashMap(); - - /** - * Sets the form submission method. - * - * @param method Can't be {@code null}. - */ - public void setMethod(String method) { - ErrorUtils.errorIfNull(method, "method"); - - this.method = method; - } - - /** - * Sets the name of the processor class. - * - * @param processor The class name must be valid, and the class must - * implement {@link FormProcessor}. - */ - @SuppressWarnings("unchecked") - public void setProcessor(String processor) { - Class pc = ObjectUtils.getClassByName(processor); - - ErrorUtils.errorIf(pc == null, processor, "isn't a valid class name!"); - ErrorUtils.errorIf(!FormProcessor.class.isAssignableFrom(pc), pc.getName(), "doesn't implement [" + FormProcessor.class.getName() + "]!"); - - this.processorClass = (Class) pc; - } - - public Class getProcessorClass() { - return this.processorClass; - } - - /** - * Sets the name of the page-scoped variable to store the processor - * instance. - */ - public void setVarProcessor(String varProcessor) { - this.varProcessor = varProcessor; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * success flag. - */ - public void setVarSuccess(String varSuccess) { - this.varSuccess = varSuccess; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * error. - */ - public void setVarError(String varError) { - this.varError = varError; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * result. - * - * @return May be {@code null}. - */ - public void setVarResult(String varResult) { - this.varResult = varResult; - } - - /** Returns a unique identifier for this form. */ - public String getFormId() { - return Static.getProcessorId(processorClass) + (getId() != null ? ("/" + getId()) : ""); - } - - /** Returns the processor for this form. */ - public FormProcessor getProcessorInstance() { - return Static.getProcessorById(getFormId(), (HttpServletRequest) pageContext.getRequest()); - } - - // --- Getters for the transient variables --- - - /** - * Return true if this form was processed successfully, or false if not. - * Null is returned if this method is called outside the context of this - * form's start and end tags. - * - * @return - */ - public Boolean isSuccess() { - return success; - } - - /** - * Returns the result of processing this form, or null if there was an error - * or this method is called outside the context of this form's start and - * end tags. - * - * @return - */ - public Object getResult() { - return result; - } - - /** - * Returns the error generated attempting to process this form, or null if - * if the form was processed successfully or this method is called outside - * the context of this form's start and end tags. - * - * @return - */ - public Object getError() { - return error; - } - - // --- TagSupport support --- - - @Override - public int doStartTag() throws JspException { - - HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); - - String formId = getFormId(); - FormProcessor processor = getProcessorInstance(); - - if (!ObjectUtils.isBlank(varProcessor)) { - pageContext.setAttribute(varProcessor, processor); - } - - // Write the FORM start tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("form", - "id", getId(), - "method", method.toLowerCase(), - "action", "", - attributes); - writer.writeTag("input", - "type", "hidden", - "name", ID_PARAMETER, - "value", formId); - - - // If process() was already called by FormFilter - String bufferedOutput = FormFilter.Static.getBufferedOutput(formId, request); - if (bufferedOutput != null) { - writer.write(bufferedOutput); - - success = FormFilter.Static.isFormSuccess(request); - result = FormFilter.Static.getFormResult(request); - error = FormFilter.Static.getFormError(request); - - } else { - // process it - try { - result = processor.process(request, new HttpServletResponseWrapper((HttpServletResponse) pageContext.getResponse()) { - private PrintWriter writer; { - writer = new PrintWriter(pageContext.getOut()); - } - @Override - public PrintWriter getWriter() { - return writer; - } - }); - success = true; - - } catch (IOException e) { - throw e; - - } catch (Throwable e) { - error = e; - success = false; - } - } - - // Set the status vars if they are defined - if (!ObjectUtils.isBlank(varSuccess)) { - pageContext.setAttribute(varSuccess, isSuccess()); - } - if (!ObjectUtils.isBlank(varResult)) { - pageContext.setAttribute(varResult, getResult()); - } - if (!ObjectUtils.isBlank(varError)) { - pageContext.setAttribute(varError, getError()); - } - - } catch (IOException error) { - throw new JspException(error); - } - - return EVAL_BODY_INCLUDE; - } - - @Override - public int doEndTag() throws JspException { - // Write the FORM end tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("/form"); - - } catch (IOException error) { - throw new JspException(error); - - } finally { - // null out the transient variables - success = null; - error = null; - result = null; - } - - return EVAL_PAGE; - } - - // --- DynamicAttribute support --- - - @Override - public void setDynamicAttribute(String uri, String localName, Object value) { - attributes.put(localName, value != null ? value.toString() : null); - } - - public static final class Static { - - public static FormProcessor getProcessorById(String id, HttpServletRequest request) { - if (id == null) { - return null; - } - - // Strip off the form ID attribute part of the ID if it exists. - String processorId; - int slashAt = id.indexOf('/'); - if (slashAt < 0) { - processorId = id; - - } else { - processorId = id.substring(0, slashAt); - } - - FormProcessor processor = (FormProcessor) request.getAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id); - - if (processor == null) { - Class processorClass = PROCESSOR_CLASSES.get(processorId); - if (processorClass != null) { - processor = TypeDefinition.getInstance(processorClass).newInstance(); - } - if (processor != null) { - request.setAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id, processor); - } - } - - return processor; - } - - private static String getProcessorId(Class processorClass) { - String hashId = StringUtils.hex(StringUtils.md5(processorClass.getName())); - PROCESSOR_CLASSES.putIfAbsent(hashId, processorClass); - return hashId; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/pair.info deleted file mode 100755 index fbf715d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53212/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:53212 -comSha:bae48433b954d0929ab995e886d9a4a4096d1d60 -parentComSha:0650ca0caf24acee6294a892a393d63060088104 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/FormTag.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/FormTag.java -StartLineNum:172 -EndLineNum:172 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/comMsg.txt deleted file mode 100755 index 197a716..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of DM_CONVERT_CASE from FindBugs. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/diff.diff deleted file mode 100755 index 1252766..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/TypeDefinition.java b/util/src/main/java/com/psddev/dari/util/TypeDefinition.java -index 24e280c2..2141d3c2 100644 ---- a/util/src/main/java/com/psddev/dari/util/TypeDefinition.java -+++ b/util/src/main/java/com/psddev/dari/util/TypeDefinition.java -@@ -14,0 +15 @@ import java.util.List; -+import java.util.Locale; -@@ -372 +373 @@ public class TypeDefinition { -- ? nameMatcher.group(3).toLowerCase() + nameMatcher.group(4) -+ ? nameMatcher.group(3).toLowerCase(Locale.ENGLISH) + nameMatcher.group(4) -@@ -412 +413 @@ public class TypeDefinition { -- setters.put(nameMatcher.group(1).toLowerCase() + nameMatcher.group(2), method); -+ setters.put(nameMatcher.group(1).toLowerCase(Locale.ENGLISH) + nameMatcher.group(2), method); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/new/TypeDefinition.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/new/TypeDefinition.java deleted file mode 100755 index 2141d3c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/new/TypeDefinition.java +++ /dev/null @@ -1,431 +0,0 @@ -package com.psddev.dari.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; - -public class TypeDefinition { - - private final Type type; - - /** Returns an instance based on the given {@code type}. */ - public static TypeDefinition getInstance(Type type) { - return INSTANCES.get(type); - } - - private static final PullThroughCache> - INSTANCES = new PullThroughCache>() { - - @Override - protected TypeDefinition produce(Type type) { - return new TypeDefinition(type); - } - }; - - /** Returns an instance based on the given {@code objectClass}. */ - @SuppressWarnings("unchecked") - public static TypeDefinition getInstance(Class objectClass) { - return (TypeDefinition) getInstance((Type) objectClass); - } - - /** Returns an instance based on the given {@code typeReference}. */ - @SuppressWarnings("unchecked") - public static TypeDefinition getInstance(TypeReference typeReference) { - return (TypeDefinition) getInstance(typeReference.getType()); - } - - /** Creates an instance based on the given {@code type}. */ - protected TypeDefinition(Type type) { - this.type = type; - } - - /** - * Returns the defintion's Type, including any Generic Parameters it knows about - * ex. TypeDefinition.getInstance(new TypeReference>() { }).getType(); // List - * A TypeReference needs to be provided to getInstance in order for the Parameterized - * type information to be retained (type erasure) - */ - public Type getType() { - return type; - } - - /** - * Returns the defintion's Class, not including any Generic Parameters it knows about - * ex. TypeDefinition.getInstance(new TypeReference>() { }).getObjectClass(); // List - */ - @SuppressWarnings("unchecked") - public Class getObjectClass() { - - Type type = getType(); - if (type instanceof Class) { - return (Class) type; - - } else if (type instanceof ParameterizedType) { - return (Class) ((ParameterizedType) type).getRawType(); - - } else { - throw new IllegalStateException(String.format( - "Cannot find an object class based on [%s] type!", - type)); - } - } - - /** - * Returns an unmodifiable list of all the classes that can be assigned - * from this one with the most specific match (itself) first. - */ - public List> getAssignableClasses() { - return assignableClasses.get(); - } - - private final PullThroughValue>> - assignableClasses = new PullThroughValue>>() { - - @Override - protected List> produce() { - - Class objectClass = getObjectClass(); - List> classes = new ArrayList>(); - classes.add(objectClass); - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - classes.addAll(getInstance(superClass).getAssignableClasses()); - } - - return Collections.unmodifiableList(classes); - } - }; - - /** - * Returns an unmodifiable set of all classes and interfaces that are - * either the same as, or is a super class or super interface of, - * this type. - */ - public Set> getAssignableClassesAndInterfaces() { - return assignableClassesAndInterfaces.get(); - } - - private final transient PullThroughValue>> - assignableClassesAndInterfaces = new PullThroughValue>>() { - - @Override - protected Set> produce() { - Class objectClass = getObjectClass(); - Set> classes = new LinkedHashSet>(); - - classes.add(objectClass); - - for (Class interfaceClass : objectClass.getInterfaces()) { - classes.addAll(getInstance(interfaceClass).getAssignableClassesAndInterfaces()); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - classes.addAll(getInstance(superClass).getAssignableClassesAndInterfaces()); - } - - return Collections.unmodifiableSet(classes); - } - }; - - /** Returns an unmodifiable list of all the fields. */ - public List getAllFields() { - return allFields.get(); - } - - private final PullThroughValue> - allFields = new PullThroughValue>() { - - @Override - protected List produce() { - - Class objectClass = getObjectClass(); - List fields = new ArrayList(); - for (Field field : objectClass.getDeclaredFields()) { - field.setAccessible(true); - fields.add(field); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - fields.addAll(getInstance(superClass).getAllFields()); - } - - return Collections.unmodifiableList(fields); - } - }; - - /** - * Returns an unmodifiable map of all the serializable (non-static - * and non-transient) fields with the normalized names as keys. - */ - public Map> getAllSerializableFields() { - return allSerializableFields.get(); - } - - private final PullThroughValue>> - allSerializableFields = new PullThroughValue>>() { - - @Override - protected Map> produce() { - - Class objectClass = getObjectClass(); - Map> fieldsMap = new LinkedHashMap>(); - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - for (Map.Entry> entry : getInstance(superClass).getAllSerializableFields().entrySet()) { - fieldsMap.put(entry.getKey(), new ArrayList(entry.getValue())); - } - } - - for (Field field : objectClass.getDeclaredFields()) { - int mod = field.getModifiers(); - if (!Modifier.isStatic(mod) - && !Modifier.isTransient(mod)) { - - // Normalize common field name formats: - // _name, name_, fName or mName. - String name = field.getName(); - if (name.startsWith("_")) { - name = name.substring(1); - } else if (name.endsWith("_")) { - name = name.substring(0, name.length() - 1); - } else if (name.length() > 2 - && (name.charAt(0) == 'f' || name.charAt(0) == 'm') - && Character.isUpperCase(name.charAt(1))) { - name = Character.toLowerCase(name.charAt(1)) + name.substring(2); - } - - List fields = fieldsMap.get(name); - if (fields == null) { - fields = new ArrayList(); - fieldsMap.put(name, fields); - } - - field.setAccessible(true); - fields.add(field); - } - } - - return fieldsMap; - } - }; - - /** Returns the first field with the given {@code name}. */ - public Field getField(String name) { - for (Field field : getAllFields()) { - if (field.getName().equals(name)) { - return field; - } - } - List fields = getAllSerializableFields().get(name); - return ObjectUtils.isBlank(fields) ? null : fields.get(fields.size() - 1); - } - - /** Returns an unmodifiable list of all the constructors. */ - public List> getConstructors() { - return constructors.get(); - } - - private final PullThroughValue>> - constructors = new PullThroughValue>>() { - - @Override - @SuppressWarnings("unchecked") - protected List> produce() { - List> constructors = new ArrayList>(); - for (Constructor constructor : getObjectClass().getDeclaredConstructors()) { - constructor.setAccessible(true); - constructors.add((Constructor) constructor); - } - return Collections.unmodifiableList(constructors); - } - }; - - /** - * Returns the constructor that can be called with the given array of - * {@code parameterClasses}. - */ - public Constructor getConstructor(Class... parameterClasses) { - int length = parameterClasses.length; - NEXT_CONSTRUCTOR: - for (Constructor constructor : getConstructors()) { - Class[] declared = constructor.getParameterTypes(); - if (length == declared.length) { - - for (int i = 0; i < length; ++ i) { - if (!declared[i].isAssignableFrom(parameterClasses[i])) { - continue NEXT_CONSTRUCTOR; - } - } - - return (Constructor) constructor; - } - } - - return null; - } - - /** Creates a new instance. */ - public T newInstance() { - Constructor constructor = getConstructor(); - if (constructor == null) { - throw new IllegalStateException(String.format( - "Can't create an instance of [%s] without a nullary constructor!", - getObjectClass())); - } - - try { - return constructor.newInstance(); - - } catch (IllegalAccessException ex) { - throw new IllegalStateException(ex); - - } catch (InstantiationException ex) { - throw new IllegalStateException(String.format( - "Can't instantiate an instance of [%s]!", - getObjectClass()), ex); - - } catch (InvocationTargetException ex) { - Throwable cause = ex.getCause(); - if (cause == null) { - cause = ex; - } - throw cause instanceof RuntimeException ? - (RuntimeException) cause : - new RuntimeException(cause.getMessage(), cause); - } - } - - /** Returns an unmodifiable list of all the methods. */ - public List getAllMethods() { - return allMethods.get(); - } - - private final PullThroughValue> - allMethods = new PullThroughValue>() { - - @Override - protected List produce() { - - Class objectClass = getObjectClass(); - List methods = new ArrayList(); - for (Method method : objectClass.getDeclaredMethods()) { - method.setAccessible(true); - methods.add(method); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - methods.addAll(getInstance(superClass).getAllMethods()); - } - - return Collections.unmodifiableList(methods); - } - }; - - /** - * Returns an unmodifiable map of all the getters (public non-static - * methods that have no parameters and return a value) with the - * normalized names as keys. - */ - public Map getAllGetters() { - return allGetters.get(); - } - - private final PullThroughValue> - allGetters = new PullThroughValue>() { - - @Override - protected Map produce() { - - Map getters = new LinkedHashMap(); - for (Method method : getAllMethods()) { - if (method.getDeclaringClass() != Object.class) { - - int mod = method.getModifiers(); - if (Modifier.isPublic(mod) - && !Modifier.isStatic(mod) - && method.getReturnType() != void.class - && method.getReturnType() != Void.class - && method.getParameterTypes().length == 0) { - - String methodName = method.getName(); - Matcher nameMatcher = StringUtils.getMatcher(methodName, "^(get|(is|has))([^a-z])(.*)$"); - if (nameMatcher.matches()) { - - String name = ObjectUtils.isBlank(nameMatcher.group(2)) - ? nameMatcher.group(3).toLowerCase(Locale.ENGLISH) + nameMatcher.group(4) - : methodName; - getters.put(name, method); - } - } - } - } - - return Collections.unmodifiableMap(getters); - } - }; - - /** - * Returns an unmodifiable map of all the setters (public non-static - * methods that take one parameter and doesn't return anything) with the - * normalized names as keys. - */ - public Map getAllSetters() { - return allSetters.get(); - } - - private final PullThroughValue> - allSetters = new PullThroughValue>() { - - @Override - protected Map produce() { - - Map setters = new LinkedHashMap(); - for (Method method : getAllMethods()) { - if (method.getDeclaringClass() != Object.class) { - - int mod = method.getModifiers(); - if (Modifier.isPublic(mod) - && !Modifier.isStatic(mod) - && (method.getReturnType() == void.class || method.getReturnType() == Void.class) - && method.getParameterTypes().length == 1) { - - String methodName = method.getName(); - Matcher nameMatcher = StringUtils.getMatcher(methodName, "^set([^a-z])(.*)$"); - if (nameMatcher.matches()) { - setters.put(nameMatcher.group(1).toLowerCase(Locale.ENGLISH) + nameMatcher.group(2), method); - } - } - } - } - - return Collections.unmodifiableMap(setters); - } - }; - - /** {@link TypeDefinition} utility methods. */ - public static final class Static { - - /** Invalidates all caches. */ - public static void invalidateAll() { - INSTANCES.invalidate(); - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/old/TypeDefinition.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/old/TypeDefinition.java deleted file mode 100755 index 24e280c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/old/TypeDefinition.java +++ /dev/null @@ -1,430 +0,0 @@ -package com.psddev.dari.util; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; - -public class TypeDefinition { - - private final Type type; - - /** Returns an instance based on the given {@code type}. */ - public static TypeDefinition getInstance(Type type) { - return INSTANCES.get(type); - } - - private static final PullThroughCache> - INSTANCES = new PullThroughCache>() { - - @Override - protected TypeDefinition produce(Type type) { - return new TypeDefinition(type); - } - }; - - /** Returns an instance based on the given {@code objectClass}. */ - @SuppressWarnings("unchecked") - public static TypeDefinition getInstance(Class objectClass) { - return (TypeDefinition) getInstance((Type) objectClass); - } - - /** Returns an instance based on the given {@code typeReference}. */ - @SuppressWarnings("unchecked") - public static TypeDefinition getInstance(TypeReference typeReference) { - return (TypeDefinition) getInstance(typeReference.getType()); - } - - /** Creates an instance based on the given {@code type}. */ - protected TypeDefinition(Type type) { - this.type = type; - } - - /** - * Returns the defintion's Type, including any Generic Parameters it knows about - * ex. TypeDefinition.getInstance(new TypeReference>() { }).getType(); // List - * A TypeReference needs to be provided to getInstance in order for the Parameterized - * type information to be retained (type erasure) - */ - public Type getType() { - return type; - } - - /** - * Returns the defintion's Class, not including any Generic Parameters it knows about - * ex. TypeDefinition.getInstance(new TypeReference>() { }).getObjectClass(); // List - */ - @SuppressWarnings("unchecked") - public Class getObjectClass() { - - Type type = getType(); - if (type instanceof Class) { - return (Class) type; - - } else if (type instanceof ParameterizedType) { - return (Class) ((ParameterizedType) type).getRawType(); - - } else { - throw new IllegalStateException(String.format( - "Cannot find an object class based on [%s] type!", - type)); - } - } - - /** - * Returns an unmodifiable list of all the classes that can be assigned - * from this one with the most specific match (itself) first. - */ - public List> getAssignableClasses() { - return assignableClasses.get(); - } - - private final PullThroughValue>> - assignableClasses = new PullThroughValue>>() { - - @Override - protected List> produce() { - - Class objectClass = getObjectClass(); - List> classes = new ArrayList>(); - classes.add(objectClass); - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - classes.addAll(getInstance(superClass).getAssignableClasses()); - } - - return Collections.unmodifiableList(classes); - } - }; - - /** - * Returns an unmodifiable set of all classes and interfaces that are - * either the same as, or is a super class or super interface of, - * this type. - */ - public Set> getAssignableClassesAndInterfaces() { - return assignableClassesAndInterfaces.get(); - } - - private final transient PullThroughValue>> - assignableClassesAndInterfaces = new PullThroughValue>>() { - - @Override - protected Set> produce() { - Class objectClass = getObjectClass(); - Set> classes = new LinkedHashSet>(); - - classes.add(objectClass); - - for (Class interfaceClass : objectClass.getInterfaces()) { - classes.addAll(getInstance(interfaceClass).getAssignableClassesAndInterfaces()); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - classes.addAll(getInstance(superClass).getAssignableClassesAndInterfaces()); - } - - return Collections.unmodifiableSet(classes); - } - }; - - /** Returns an unmodifiable list of all the fields. */ - public List getAllFields() { - return allFields.get(); - } - - private final PullThroughValue> - allFields = new PullThroughValue>() { - - @Override - protected List produce() { - - Class objectClass = getObjectClass(); - List fields = new ArrayList(); - for (Field field : objectClass.getDeclaredFields()) { - field.setAccessible(true); - fields.add(field); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - fields.addAll(getInstance(superClass).getAllFields()); - } - - return Collections.unmodifiableList(fields); - } - }; - - /** - * Returns an unmodifiable map of all the serializable (non-static - * and non-transient) fields with the normalized names as keys. - */ - public Map> getAllSerializableFields() { - return allSerializableFields.get(); - } - - private final PullThroughValue>> - allSerializableFields = new PullThroughValue>>() { - - @Override - protected Map> produce() { - - Class objectClass = getObjectClass(); - Map> fieldsMap = new LinkedHashMap>(); - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - for (Map.Entry> entry : getInstance(superClass).getAllSerializableFields().entrySet()) { - fieldsMap.put(entry.getKey(), new ArrayList(entry.getValue())); - } - } - - for (Field field : objectClass.getDeclaredFields()) { - int mod = field.getModifiers(); - if (!Modifier.isStatic(mod) - && !Modifier.isTransient(mod)) { - - // Normalize common field name formats: - // _name, name_, fName or mName. - String name = field.getName(); - if (name.startsWith("_")) { - name = name.substring(1); - } else if (name.endsWith("_")) { - name = name.substring(0, name.length() - 1); - } else if (name.length() > 2 - && (name.charAt(0) == 'f' || name.charAt(0) == 'm') - && Character.isUpperCase(name.charAt(1))) { - name = Character.toLowerCase(name.charAt(1)) + name.substring(2); - } - - List fields = fieldsMap.get(name); - if (fields == null) { - fields = new ArrayList(); - fieldsMap.put(name, fields); - } - - field.setAccessible(true); - fields.add(field); - } - } - - return fieldsMap; - } - }; - - /** Returns the first field with the given {@code name}. */ - public Field getField(String name) { - for (Field field : getAllFields()) { - if (field.getName().equals(name)) { - return field; - } - } - List fields = getAllSerializableFields().get(name); - return ObjectUtils.isBlank(fields) ? null : fields.get(fields.size() - 1); - } - - /** Returns an unmodifiable list of all the constructors. */ - public List> getConstructors() { - return constructors.get(); - } - - private final PullThroughValue>> - constructors = new PullThroughValue>>() { - - @Override - @SuppressWarnings("unchecked") - protected List> produce() { - List> constructors = new ArrayList>(); - for (Constructor constructor : getObjectClass().getDeclaredConstructors()) { - constructor.setAccessible(true); - constructors.add((Constructor) constructor); - } - return Collections.unmodifiableList(constructors); - } - }; - - /** - * Returns the constructor that can be called with the given array of - * {@code parameterClasses}. - */ - public Constructor getConstructor(Class... parameterClasses) { - int length = parameterClasses.length; - NEXT_CONSTRUCTOR: - for (Constructor constructor : getConstructors()) { - Class[] declared = constructor.getParameterTypes(); - if (length == declared.length) { - - for (int i = 0; i < length; ++ i) { - if (!declared[i].isAssignableFrom(parameterClasses[i])) { - continue NEXT_CONSTRUCTOR; - } - } - - return (Constructor) constructor; - } - } - - return null; - } - - /** Creates a new instance. */ - public T newInstance() { - Constructor constructor = getConstructor(); - if (constructor == null) { - throw new IllegalStateException(String.format( - "Can't create an instance of [%s] without a nullary constructor!", - getObjectClass())); - } - - try { - return constructor.newInstance(); - - } catch (IllegalAccessException ex) { - throw new IllegalStateException(ex); - - } catch (InstantiationException ex) { - throw new IllegalStateException(String.format( - "Can't instantiate an instance of [%s]!", - getObjectClass()), ex); - - } catch (InvocationTargetException ex) { - Throwable cause = ex.getCause(); - if (cause == null) { - cause = ex; - } - throw cause instanceof RuntimeException ? - (RuntimeException) cause : - new RuntimeException(cause.getMessage(), cause); - } - } - - /** Returns an unmodifiable list of all the methods. */ - public List getAllMethods() { - return allMethods.get(); - } - - private final PullThroughValue> - allMethods = new PullThroughValue>() { - - @Override - protected List produce() { - - Class objectClass = getObjectClass(); - List methods = new ArrayList(); - for (Method method : objectClass.getDeclaredMethods()) { - method.setAccessible(true); - methods.add(method); - } - - Class superClass = objectClass.getSuperclass(); - if (superClass != null) { - methods.addAll(getInstance(superClass).getAllMethods()); - } - - return Collections.unmodifiableList(methods); - } - }; - - /** - * Returns an unmodifiable map of all the getters (public non-static - * methods that have no parameters and return a value) with the - * normalized names as keys. - */ - public Map getAllGetters() { - return allGetters.get(); - } - - private final PullThroughValue> - allGetters = new PullThroughValue>() { - - @Override - protected Map produce() { - - Map getters = new LinkedHashMap(); - for (Method method : getAllMethods()) { - if (method.getDeclaringClass() != Object.class) { - - int mod = method.getModifiers(); - if (Modifier.isPublic(mod) - && !Modifier.isStatic(mod) - && method.getReturnType() != void.class - && method.getReturnType() != Void.class - && method.getParameterTypes().length == 0) { - - String methodName = method.getName(); - Matcher nameMatcher = StringUtils.getMatcher(methodName, "^(get|(is|has))([^a-z])(.*)$"); - if (nameMatcher.matches()) { - - String name = ObjectUtils.isBlank(nameMatcher.group(2)) - ? nameMatcher.group(3).toLowerCase() + nameMatcher.group(4) - : methodName; - getters.put(name, method); - } - } - } - } - - return Collections.unmodifiableMap(getters); - } - }; - - /** - * Returns an unmodifiable map of all the setters (public non-static - * methods that take one parameter and doesn't return anything) with the - * normalized names as keys. - */ - public Map getAllSetters() { - return allSetters.get(); - } - - private final PullThroughValue> - allSetters = new PullThroughValue>() { - - @Override - protected Map produce() { - - Map setters = new LinkedHashMap(); - for (Method method : getAllMethods()) { - if (method.getDeclaringClass() != Object.class) { - - int mod = method.getModifiers(); - if (Modifier.isPublic(mod) - && !Modifier.isStatic(mod) - && (method.getReturnType() == void.class || method.getReturnType() == Void.class) - && method.getParameterTypes().length == 1) { - - String methodName = method.getName(); - Matcher nameMatcher = StringUtils.getMatcher(methodName, "^set([^a-z])(.*)$"); - if (nameMatcher.matches()) { - setters.put(nameMatcher.group(1).toLowerCase() + nameMatcher.group(2), method); - } - } - } - } - - return Collections.unmodifiableMap(setters); - } - }; - - /** {@link TypeDefinition} utility methods. */ - public static final class Static { - - /** Invalidates all caches. */ - public static void invalidateAll() { - INSTANCES.invalidate(); - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/pair.info deleted file mode 100755 index 83c45ba..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53250/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:53250 -comSha:641bc27d5470a167d3ca2fefd6ae4c619a27c012 -parentComSha:5f098cd76c5e7aff3237dc54664709c515095ad4 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/TypeDefinition.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/TypeDefinition.java -StartLineNum:412 -EndLineNum:412 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/comMsg.txt deleted file mode 100755 index ee04a0c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of PMD design.xml/UseLocaleWithCaseConversions. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/diff.diff deleted file mode 100755 index ef86662..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/FormTag.java b/util/src/main/java/com/psddev/dari/util/FormTag.java -index 34a3dd33..ffa31658 100644 ---- a/util/src/main/java/com/psddev/dari/util/FormTag.java -+++ b/util/src/main/java/com/psddev/dari/util/FormTag.java -@@ -5,0 +6 @@ import java.util.LinkedHashMap; -+import java.util.Locale; -@@ -174 +175 @@ public class FormTag extends TagSupport implements DynamicAttributes { -- "method", method.toLowerCase(), -+ "method", method.toLowerCase(Locale.ENGLISH), \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/new/FormTag.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/new/FormTag.java deleted file mode 100755 index ffa3165..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/new/FormTag.java +++ /dev/null @@ -1,304 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.DynamicAttributes; -import javax.servlet.jsp.tagext.TagSupport; - -@SuppressWarnings("serial") -public class FormTag extends TagSupport implements DynamicAttributes { - - private static final String PARAMETER_PREFIX = "_f."; - public static final String ID_PARAMETER = PARAMETER_PREFIX + "id"; - - private static final String ATTRIBUTE_PREFIX = FormTag.class.getName() + "."; - private static final String PROCESSOR_ATTRIBUTE_PREFIX = ATTRIBUTE_PREFIX + "processor/"; - - /** Map of the MD5 hash of a processor class name to the Class object itself. */ - private static final ConcurrentHashMap> PROCESSOR_CLASSES = - new ConcurrentHashMap>(); - - private String method; - private Class processorClass; - - private String varProcessor; - private String varSuccess; - private String varError; - private String varResult; - - private transient Boolean success; - private transient Object result; - private transient Object error; - - private final Map attributes = new LinkedHashMap(); - - /** - * Sets the form submission method. - * - * @param method Can't be {@code null}. - */ - public void setMethod(String method) { - ErrorUtils.errorIfNull(method, "method"); - - this.method = method; - } - - /** - * Sets the name of the processor class. - * - * @param processor The class name must be valid, and the class must - * implement {@link FormProcessor}. - */ - @SuppressWarnings("unchecked") - public void setProcessor(String processor) { - Class pc = ObjectUtils.getClassByName(processor); - - ErrorUtils.errorIf(pc == null, processor, "isn't a valid class name!"); - ErrorUtils.errorIf(!FormProcessor.class.isAssignableFrom(pc), pc.getName(), "doesn't implement [" + FormProcessor.class.getName() + "]!"); - - this.processorClass = (Class) pc; - } - - public Class getProcessorClass() { - return this.processorClass; - } - - /** - * Sets the name of the page-scoped variable to store the processor - * instance. - */ - public void setVarProcessor(String varProcessor) { - this.varProcessor = varProcessor; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * success flag. - */ - public void setVarSuccess(String varSuccess) { - this.varSuccess = varSuccess; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * error. - */ - public void setVarError(String varError) { - this.varError = varError; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * result. - * - * @return May be {@code null}. - */ - public void setVarResult(String varResult) { - this.varResult = varResult; - } - - /** Returns a unique identifier for this form. */ - public String getFormId() { - return Static.getProcessorId(processorClass) + (getId() != null ? ("/" + getId()) : ""); - } - - /** Returns the processor for this form. */ - public FormProcessor getProcessorInstance() { - return Static.getProcessorById(getFormId(), (HttpServletRequest) pageContext.getRequest()); - } - - // --- Getters for the transient variables --- - - /** - * Return true if this form was processed successfully, or false if not. - * Null is returned if this method is called outside the context of this - * form's start and end tags. - * - * @return - */ - public Boolean isSuccess() { - return success; - } - - /** - * Returns the result of processing this form, or null if there was an error - * or this method is called outside the context of this form's start and - * end tags. - * - * @return - */ - public Object getResult() { - return result; - } - - /** - * Returns the error generated attempting to process this form, or null if - * if the form was processed successfully or this method is called outside - * the context of this form's start and end tags. - * - * @return - */ - public Object getError() { - return error; - } - - // --- TagSupport support --- - - @Override - public int doStartTag() throws JspException { - - HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); - - String formId = getFormId(); - FormProcessor processor = getProcessorInstance(); - - if (!ObjectUtils.isBlank(varProcessor)) { - pageContext.setAttribute(varProcessor, processor); - } - - // Write the FORM start tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("form", - "id", getId(), - "method", method.toLowerCase(Locale.ENGLISH), - "action", "", - attributes); - writer.writeTag("input", - "type", "hidden", - "name", ID_PARAMETER, - "value", formId); - - - // If process() was already called by FormFilter - String bufferedOutput = FormFilter.Static.getBufferedOutput(formId, request); - if (bufferedOutput != null) { - writer.write(bufferedOutput); - - success = FormFilter.Static.isFormSuccess(request); - result = FormFilter.Static.getFormResult(request); - error = FormFilter.Static.getFormError(request); - - } else { - // process it - try { - result = processor.process(request, new HttpServletResponseWrapper((HttpServletResponse) pageContext.getResponse()) { - private PrintWriter writer; { - writer = new PrintWriter(pageContext.getOut()); - } - @Override - public PrintWriter getWriter() { - return writer; - } - }); - success = true; - - } catch (IOException e) { - throw e; - - } catch (Throwable e) { - error = e; - success = false; - } - } - - // Set the status vars if they are defined - if (!ObjectUtils.isBlank(varSuccess)) { - pageContext.setAttribute(varSuccess, isSuccess()); - } - if (!ObjectUtils.isBlank(varResult)) { - pageContext.setAttribute(varResult, getResult()); - } - if (!ObjectUtils.isBlank(varError)) { - pageContext.setAttribute(varError, getError()); - } - - } catch (IOException error) { - throw new JspException(error); - } - - return EVAL_BODY_INCLUDE; - } - - @Override - public int doEndTag() throws JspException { - // Write the FORM end tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("/form"); - - } catch (IOException error) { - throw new JspException(error); - - } finally { - // null out the transient variables - success = null; - error = null; - result = null; - } - - return EVAL_PAGE; - } - - // --- DynamicAttribute support --- - - @Override - public void setDynamicAttribute(String uri, String localName, Object value) { - attributes.put(localName, value != null ? value.toString() : null); - } - - public static final class Static { - - private Static() { - } - - public static FormProcessor getProcessorById(String id, HttpServletRequest request) { - if (id == null) { - return null; - } - - // Strip off the form ID attribute part of the ID if it exists. - String processorId; - int slashAt = id.indexOf('/'); - if (slashAt < 0) { - processorId = id; - - } else { - processorId = id.substring(0, slashAt); - } - - FormProcessor processor = (FormProcessor) request.getAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id); - - if (processor == null) { - Class processorClass = PROCESSOR_CLASSES.get(processorId); - if (processorClass != null) { - processor = TypeDefinition.getInstance(processorClass).newInstance(); - } - if (processor != null) { - request.setAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id, processor); - } - } - - return processor; - } - - private static String getProcessorId(Class processorClass) { - String hashId = StringUtils.hex(StringUtils.md5(processorClass.getName())); - PROCESSOR_CLASSES.putIfAbsent(hashId, processorClass); - return hashId; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/old/FormTag.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/old/FormTag.java deleted file mode 100755 index 34a3dd3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/old/FormTag.java +++ /dev/null @@ -1,303 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.servlet.jsp.JspException; -import javax.servlet.jsp.tagext.DynamicAttributes; -import javax.servlet.jsp.tagext.TagSupport; - -@SuppressWarnings("serial") -public class FormTag extends TagSupport implements DynamicAttributes { - - private static final String PARAMETER_PREFIX = "_f."; - public static final String ID_PARAMETER = PARAMETER_PREFIX + "id"; - - private static final String ATTRIBUTE_PREFIX = FormTag.class.getName() + "."; - private static final String PROCESSOR_ATTRIBUTE_PREFIX = ATTRIBUTE_PREFIX + "processor/"; - - /** Map of the MD5 hash of a processor class name to the Class object itself. */ - private static final ConcurrentHashMap> PROCESSOR_CLASSES = - new ConcurrentHashMap>(); - - private String method; - private Class processorClass; - - private String varProcessor; - private String varSuccess; - private String varError; - private String varResult; - - private transient Boolean success; - private transient Object result; - private transient Object error; - - private final Map attributes = new LinkedHashMap(); - - /** - * Sets the form submission method. - * - * @param method Can't be {@code null}. - */ - public void setMethod(String method) { - ErrorUtils.errorIfNull(method, "method"); - - this.method = method; - } - - /** - * Sets the name of the processor class. - * - * @param processor The class name must be valid, and the class must - * implement {@link FormProcessor}. - */ - @SuppressWarnings("unchecked") - public void setProcessor(String processor) { - Class pc = ObjectUtils.getClassByName(processor); - - ErrorUtils.errorIf(pc == null, processor, "isn't a valid class name!"); - ErrorUtils.errorIf(!FormProcessor.class.isAssignableFrom(pc), pc.getName(), "doesn't implement [" + FormProcessor.class.getName() + "]!"); - - this.processorClass = (Class) pc; - } - - public Class getProcessorClass() { - return this.processorClass; - } - - /** - * Sets the name of the page-scoped variable to store the processor - * instance. - */ - public void setVarProcessor(String varProcessor) { - this.varProcessor = varProcessor; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * success flag. - */ - public void setVarSuccess(String varSuccess) { - this.varSuccess = varSuccess; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * error. - */ - public void setVarError(String varError) { - this.varError = varError; - } - - /** - * Sets the name of the page-scoped variable to store the form processing - * result. - * - * @return May be {@code null}. - */ - public void setVarResult(String varResult) { - this.varResult = varResult; - } - - /** Returns a unique identifier for this form. */ - public String getFormId() { - return Static.getProcessorId(processorClass) + (getId() != null ? ("/" + getId()) : ""); - } - - /** Returns the processor for this form. */ - public FormProcessor getProcessorInstance() { - return Static.getProcessorById(getFormId(), (HttpServletRequest) pageContext.getRequest()); - } - - // --- Getters for the transient variables --- - - /** - * Return true if this form was processed successfully, or false if not. - * Null is returned if this method is called outside the context of this - * form's start and end tags. - * - * @return - */ - public Boolean isSuccess() { - return success; - } - - /** - * Returns the result of processing this form, or null if there was an error - * or this method is called outside the context of this form's start and - * end tags. - * - * @return - */ - public Object getResult() { - return result; - } - - /** - * Returns the error generated attempting to process this form, or null if - * if the form was processed successfully or this method is called outside - * the context of this form's start and end tags. - * - * @return - */ - public Object getError() { - return error; - } - - // --- TagSupport support --- - - @Override - public int doStartTag() throws JspException { - - HttpServletRequest request = (HttpServletRequest) pageContext.getRequest(); - - String formId = getFormId(); - FormProcessor processor = getProcessorInstance(); - - if (!ObjectUtils.isBlank(varProcessor)) { - pageContext.setAttribute(varProcessor, processor); - } - - // Write the FORM start tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("form", - "id", getId(), - "method", method.toLowerCase(), - "action", "", - attributes); - writer.writeTag("input", - "type", "hidden", - "name", ID_PARAMETER, - "value", formId); - - - // If process() was already called by FormFilter - String bufferedOutput = FormFilter.Static.getBufferedOutput(formId, request); - if (bufferedOutput != null) { - writer.write(bufferedOutput); - - success = FormFilter.Static.isFormSuccess(request); - result = FormFilter.Static.getFormResult(request); - error = FormFilter.Static.getFormError(request); - - } else { - // process it - try { - result = processor.process(request, new HttpServletResponseWrapper((HttpServletResponse) pageContext.getResponse()) { - private PrintWriter writer; { - writer = new PrintWriter(pageContext.getOut()); - } - @Override - public PrintWriter getWriter() { - return writer; - } - }); - success = true; - - } catch (IOException e) { - throw e; - - } catch (Throwable e) { - error = e; - success = false; - } - } - - // Set the status vars if they are defined - if (!ObjectUtils.isBlank(varSuccess)) { - pageContext.setAttribute(varSuccess, isSuccess()); - } - if (!ObjectUtils.isBlank(varResult)) { - pageContext.setAttribute(varResult, getResult()); - } - if (!ObjectUtils.isBlank(varError)) { - pageContext.setAttribute(varError, getError()); - } - - } catch (IOException error) { - throw new JspException(error); - } - - return EVAL_BODY_INCLUDE; - } - - @Override - public int doEndTag() throws JspException { - // Write the FORM end tag. - try { - @SuppressWarnings("all") - HtmlWriter writer = new HtmlWriter(pageContext.getOut()); - - writer.writeTag("/form"); - - } catch (IOException error) { - throw new JspException(error); - - } finally { - // null out the transient variables - success = null; - error = null; - result = null; - } - - return EVAL_PAGE; - } - - // --- DynamicAttribute support --- - - @Override - public void setDynamicAttribute(String uri, String localName, Object value) { - attributes.put(localName, value != null ? value.toString() : null); - } - - public static final class Static { - - private Static() { - } - - public static FormProcessor getProcessorById(String id, HttpServletRequest request) { - if (id == null) { - return null; - } - - // Strip off the form ID attribute part of the ID if it exists. - String processorId; - int slashAt = id.indexOf('/'); - if (slashAt < 0) { - processorId = id; - - } else { - processorId = id.substring(0, slashAt); - } - - FormProcessor processor = (FormProcessor) request.getAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id); - - if (processor == null) { - Class processorClass = PROCESSOR_CLASSES.get(processorId); - if (processorClass != null) { - processor = TypeDefinition.getInstance(processorClass).newInstance(); - } - if (processor != null) { - request.setAttribute(PROCESSOR_ATTRIBUTE_PREFIX + id, processor); - } - } - - return processor; - } - - private static String getProcessorId(Class processorClass) { - String hashId = StringUtils.hex(StringUtils.md5(processorClass.getName())); - PROCESSOR_CLASSES.putIfAbsent(hashId, processorClass); - return hashId; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/pair.info deleted file mode 100755 index 2ae1fcc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#53371/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:53371 -comSha:a2c1974da04a01bcebd1251b487b72e3c2ac90af -parentComSha:d019326625ce2c1c2469ada51de6696b9e3fca45 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/FormTag.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/FormTag.java -StartLineNum:172 -EndLineNum:172 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/comMsg.txt deleted file mode 100755 index e7ee623..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/comMsg.txt +++ /dev/null @@ -1,4 +0,0 @@ -updates and bug fixes for CPE data - - -Former-commit-id: 83635e150d5030b81a6b56d55115bb4ca19089f9 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/diff.diff deleted file mode 100755 index 3958a03..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/org/codesecure/dependencycheck/dependency/Dependency.java b/src/main/java/org/codesecure/dependencycheck/dependency/Dependency.java -index 6053026e1..579cd1385 100644 ---- a/src/main/java/org/codesecure/dependencycheck/dependency/Dependency.java -+++ b/src/main/java/org/codesecure/dependencycheck/dependency/Dependency.java -@@ -379,2 +378,0 @@ public class Dependency { -- String fnd = str.toLowerCase(); -- -@@ -387 +385 @@ public class Dependency { -- if (versionEvidence.containsUsedString(fnd)) { -+ if (versionEvidence.containsUsedString(str)) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/new/Dependency.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/new/Dependency.java deleted file mode 100755 index 579cd13..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/new/Dependency.java +++ /dev/null @@ -1,436 +0,0 @@ -package org.codesecure.dependencycheck.dependency; -/* - * This file is part of DependencyCheck. - * - * DependencyCheck is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * DependencyCheck is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * DependencyCheck. If not, see http://www.gnu.org/licenses/. - * - * Copyright (c) 2012 Jeremy Long. All Rights Reserved. - */ - -import java.io.File; -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.codesecure.dependencycheck.utils.Checksum; -import org.codesecure.dependencycheck.utils.FileUtils; - -/** - * A program dependency. This object is one of the core components within - * DependencyCheck. It is used to collect information about the dependency in - * the form of evidence. The Evidence is then used to determine if there are any - * known, published, vulnerabilities associated with the program dependency. - * - * @author Jeremy Long (jeremy.long@gmail.com) - */ -public class Dependency { - - /** - * The actual file path of the dependency on disk. - */ - private String actualFilePath = null; - /** - * The file path to display. - */ - private String filePath = null; - /** - * The file name of the dependency. - */ - private String fileName = null; - /** - * The file extension of the dependency. - */ - private String fileExtension = null; - /** - * The md5 hash of the dependency. - */ - private String md5sum = null; - /** - * The SHA1 hash of the dependency. - */ - private String sha1sum = null; - /** - * A list of Identifiers. - */ - private List identifiers = null; - /** - * A collection of vendor evidence. - */ - protected EvidenceCollection vendorEvidence = null; - /** - * A collection of product evidence. - */ - protected EvidenceCollection productEvidence = null; - /** - * A collection of version evidence. - */ - protected EvidenceCollection versionEvidence = null; - - /** - * Constructs a new Dependency object. - */ - public Dependency() { - vendorEvidence = new EvidenceCollection(); - productEvidence = new EvidenceCollection(); - versionEvidence = new EvidenceCollection(); - identifiers = new ArrayList(); - vulnerabilities = new ArrayList(); - } - - /** - * Constructs a new Dependency object. - * - * @param file the File to create the dependency object from. - */ - public Dependency(File file) { - this(); - this.actualFilePath = file.getPath(); - this.filePath = this.actualFilePath; - this.fileName = file.getName(); - this.fileExtension = FileUtils.getFileExtension(fileName); - determineHashes(file); - } - - /** - * Returns the file name of the dependency. - * - * @return the file name of the dependency. - */ - public String getFileName() { - return this.fileName; - } - - /** - * Sets the file name of the dependency. - * - * @param fileName the file name of the dependency. - */ - public void setFileName(String fileName) { - this.fileName = fileName; - } - - /** - * Sets the actual file path of the dependency on disk. - * - * @param actualFilePath the file path of the dependency. - */ - public void setActualFilePath(String actualFilePath) { - this.actualFilePath = actualFilePath; - } - - /** - * Gets the file path of the dependency. - * - * @return the file path of the dependency. - */ - public String getActualFilePath() { - return this.actualFilePath; - } - - /** - * Sets the file path of the dependency. - * - * @param filePath the file path of the dependency. - */ - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - /** - *

Gets the file path of the dependency.

NOTE: This may not - * be the actual path of the file on disk. The actual path of the file on - * disk can be obtained via the getActualFilePath().

- * - * @return the file path of the dependency. - */ - public String getFilePath() { - return this.filePath; - } - - /** - * Sets the file name of the dependency. - * - * @param fileExtension the file name of the dependency. - */ - public void setFileExtension(String fileExtension) { - this.fileExtension = fileExtension; - } - - /** - * Gets the file extension of the dependency. - * - * @return the file extension of the dependency. - */ - public String getFileExtension() { - return this.fileExtension; - } - - /** - * Returns the MD5 Checksum of the dependency file. - * - * @return the MD5 Checksum - */ - public String getMd5sum() { - return this.md5sum; - } - - /** - * Sets the MD5 Checksum of the dependency. - * - * @param md5sum the MD5 Checksum - */ - public void setMd5sum(String md5sum) { - this.md5sum = md5sum; - } - - /** - * Returns the SHA1 Checksum of the dependency. - * - * @return the SHA1 Checksum - */ - public String getSha1sum() { - return this.sha1sum; - } - - /** - * Sets the SHA1 Checksum of the dependency. - * - * @param sha1sum the SHA1 Checksum - */ - public void setSha1sum(String sha1sum) { - this.sha1sum = sha1sum; - } - - /** - * Returns a List of Identifiers. - * - * @return an ArrayList of Identifiers. - */ - public List getIdentifiers() { - return this.identifiers; - } - - /** - * Sets a List of Identifiers. - * - * @param identifiers A list of Identifiers. - */ - public void setIdentifiers(List identifiers) { - this.identifiers = identifiers; - } - - /** - * Adds an entry to the list of detected Identifiers for the dependency - * file. - * - * @param type the type of identifier (such as CPE). - * @param value the value of the identifier. - * @param url the URL of the identifier. - */ - public void addIdentifier(String type, String value, String url) { - Identifier i = new Identifier(type, value, url); - this.identifiers.add(i); - } - - /** - * Returns the evidence used to identify this dependency. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getEvidence() { - return EvidenceCollection.merge(this.productEvidence, this.vendorEvidence, this.versionEvidence); - } - - /** - * Returns the evidence used to identify this dependency. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getEvidenceUsed() { - return EvidenceCollection.mergeUsed(this.productEvidence, this.vendorEvidence, this.versionEvidence); - } - - /** - * Gets the Vendor Evidence. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getVendorEvidence() { - return this.vendorEvidence; - } - - /** - * Gets the Product Evidence. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getProductEvidence() { - return this.productEvidence; - } - - /** - * Gets the Version Evidence. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getVersionEvidence() { - return this.versionEvidence; - } - /** - * A list of exceptions that occured during analysis of this dependency. - */ - protected List analysisExceptions = new ArrayList(); - - /** - * Get the value of analysisExceptions - * - * @return the value of analysisExceptions - */ - public List getAnalysisExceptions() { - return analysisExceptions; - } - - /** - * Set the value of analysisExceptions - * - * @param analysisExceptions new value of analysisExceptions - */ - public void setAnalysisExceptions(List analysisExceptions) { - this.analysisExceptions = analysisExceptions; - } - - /** - * Adds an exception to the analysis exceptions collection. - * - * @param ex an exception. - */ - public void addAnalysisException(Exception ex) { - this.analysisExceptions.add(ex); - } - /** - * The description of the JAR file. - */ - protected String description; - - /** - * Get the value of description - * - * @return the value of description - */ - public String getDescription() { - return description; - } - - /** - * Set the value of description - * - * @param description new value of description - */ - public void setDescription(String description) { - this.description = description; - } - /** - * The license that this dependency uses. - */ - private String license; - - /** - * Get the value of license - * - * @return the value of license - */ - public String getLicense() { - return license; - } - - /** - * Set the value of license - * - * @param license new value of license - */ - public void setLicense(String license) { - this.license = license; - } - - /** - * Determines if the specified string was used when searching. - * - * @param str is the string that is being checked if it was used. - * @return true or false. - */ - public boolean containsUsedString(String str) { - if (str == null) { - return false; - } - - if (vendorEvidence.containsUsedString(str)) { - return true; - } - if (productEvidence.containsUsedString(str)) { - return true; - } - if (versionEvidence.containsUsedString(str)) { - return true; - } - return false; - } - /** - * A list of vulnerabilities for this dependency - */ - private List vulnerabilities; - - /** - * Get the list of vulnerabilities - * - * @return the list of vulnerabilities - */ - public List getVulnerabilities() { - return vulnerabilities; - } - - /** - * Set the value of vulnerabilities - * - * @param vulnerabilities new value of vulnerabilities - */ - public void setVulnerabilities(List vulnerabilities) { - this.vulnerabilities = vulnerabilities; - } - - private void determineHashes(File file) { - String md5 = null; - String sha1 = null; - try { - md5 = Checksum.getMD5Checksum(file); - sha1 = Checksum.getSHA1Checksum(file); - } catch (IOException ex) { - Logger.getLogger(Dependency.class.getName()).log(Level.SEVERE, null, ex); - } catch (NoSuchAlgorithmException ex) { - Logger.getLogger(Dependency.class.getName()).log(Level.SEVERE, null, ex); - } - this.setMd5sum(md5); - this.setSha1sum(sha1); - } - - /** - * Adds a vulnerability to the dependency. - * - * @param vulnerability a vulnerability outlining a vulnerability. - */ - public void addVulnerability(Vulnerability vulnerability) { - this.vulnerabilities.add(vulnerability); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/old/Dependency.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/old/Dependency.java deleted file mode 100755 index 6053026..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/old/Dependency.java +++ /dev/null @@ -1,438 +0,0 @@ -package org.codesecure.dependencycheck.dependency; -/* - * This file is part of DependencyCheck. - * - * DependencyCheck is free software: you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by the Free - * Software Foundation, either version 3 of the License, or (at your option) any - * later version. - * - * DependencyCheck is distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more - * details. - * - * You should have received a copy of the GNU General Public License along with - * DependencyCheck. If not, see http://www.gnu.org/licenses/. - * - * Copyright (c) 2012 Jeremy Long. All Rights Reserved. - */ - -import java.io.File; -import java.io.IOException; -import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.codesecure.dependencycheck.utils.Checksum; -import org.codesecure.dependencycheck.utils.FileUtils; - -/** - * A program dependency. This object is one of the core components within - * DependencyCheck. It is used to collect information about the dependency in - * the form of evidence. The Evidence is then used to determine if there are any - * known, published, vulnerabilities associated with the program dependency. - * - * @author Jeremy Long (jeremy.long@gmail.com) - */ -public class Dependency { - - /** - * The actual file path of the dependency on disk. - */ - private String actualFilePath = null; - /** - * The file path to display. - */ - private String filePath = null; - /** - * The file name of the dependency. - */ - private String fileName = null; - /** - * The file extension of the dependency. - */ - private String fileExtension = null; - /** - * The md5 hash of the dependency. - */ - private String md5sum = null; - /** - * The SHA1 hash of the dependency. - */ - private String sha1sum = null; - /** - * A list of Identifiers. - */ - private List identifiers = null; - /** - * A collection of vendor evidence. - */ - protected EvidenceCollection vendorEvidence = null; - /** - * A collection of product evidence. - */ - protected EvidenceCollection productEvidence = null; - /** - * A collection of version evidence. - */ - protected EvidenceCollection versionEvidence = null; - - /** - * Constructs a new Dependency object. - */ - public Dependency() { - vendorEvidence = new EvidenceCollection(); - productEvidence = new EvidenceCollection(); - versionEvidence = new EvidenceCollection(); - identifiers = new ArrayList(); - vulnerabilities = new ArrayList(); - } - - /** - * Constructs a new Dependency object. - * - * @param file the File to create the dependency object from. - */ - public Dependency(File file) { - this(); - this.actualFilePath = file.getPath(); - this.filePath = this.actualFilePath; - this.fileName = file.getName(); - this.fileExtension = FileUtils.getFileExtension(fileName); - determineHashes(file); - } - - /** - * Returns the file name of the dependency. - * - * @return the file name of the dependency. - */ - public String getFileName() { - return this.fileName; - } - - /** - * Sets the file name of the dependency. - * - * @param fileName the file name of the dependency. - */ - public void setFileName(String fileName) { - this.fileName = fileName; - } - - /** - * Sets the actual file path of the dependency on disk. - * - * @param actualFilePath the file path of the dependency. - */ - public void setActualFilePath(String actualFilePath) { - this.actualFilePath = actualFilePath; - } - - /** - * Gets the file path of the dependency. - * - * @return the file path of the dependency. - */ - public String getActualFilePath() { - return this.actualFilePath; - } - - /** - * Sets the file path of the dependency. - * - * @param filePath the file path of the dependency. - */ - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - /** - *

Gets the file path of the dependency.

NOTE: This may not - * be the actual path of the file on disk. The actual path of the file on - * disk can be obtained via the getActualFilePath().

- * - * @return the file path of the dependency. - */ - public String getFilePath() { - return this.filePath; - } - - /** - * Sets the file name of the dependency. - * - * @param fileExtension the file name of the dependency. - */ - public void setFileExtension(String fileExtension) { - this.fileExtension = fileExtension; - } - - /** - * Gets the file extension of the dependency. - * - * @return the file extension of the dependency. - */ - public String getFileExtension() { - return this.fileExtension; - } - - /** - * Returns the MD5 Checksum of the dependency file. - * - * @return the MD5 Checksum - */ - public String getMd5sum() { - return this.md5sum; - } - - /** - * Sets the MD5 Checksum of the dependency. - * - * @param md5sum the MD5 Checksum - */ - public void setMd5sum(String md5sum) { - this.md5sum = md5sum; - } - - /** - * Returns the SHA1 Checksum of the dependency. - * - * @return the SHA1 Checksum - */ - public String getSha1sum() { - return this.sha1sum; - } - - /** - * Sets the SHA1 Checksum of the dependency. - * - * @param sha1sum the SHA1 Checksum - */ - public void setSha1sum(String sha1sum) { - this.sha1sum = sha1sum; - } - - /** - * Returns a List of Identifiers. - * - * @return an ArrayList of Identifiers. - */ - public List getIdentifiers() { - return this.identifiers; - } - - /** - * Sets a List of Identifiers. - * - * @param identifiers A list of Identifiers. - */ - public void setIdentifiers(List identifiers) { - this.identifiers = identifiers; - } - - /** - * Adds an entry to the list of detected Identifiers for the dependency - * file. - * - * @param type the type of identifier (such as CPE). - * @param value the value of the identifier. - * @param url the URL of the identifier. - */ - public void addIdentifier(String type, String value, String url) { - Identifier i = new Identifier(type, value, url); - this.identifiers.add(i); - } - - /** - * Returns the evidence used to identify this dependency. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getEvidence() { - return EvidenceCollection.merge(this.productEvidence, this.vendorEvidence, this.versionEvidence); - } - - /** - * Returns the evidence used to identify this dependency. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getEvidenceUsed() { - return EvidenceCollection.mergeUsed(this.productEvidence, this.vendorEvidence, this.versionEvidence); - } - - /** - * Gets the Vendor Evidence. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getVendorEvidence() { - return this.vendorEvidence; - } - - /** - * Gets the Product Evidence. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getProductEvidence() { - return this.productEvidence; - } - - /** - * Gets the Version Evidence. - * - * @return an EvidenceCollection. - */ - public EvidenceCollection getVersionEvidence() { - return this.versionEvidence; - } - /** - * A list of exceptions that occured during analysis of this dependency. - */ - protected List analysisExceptions = new ArrayList(); - - /** - * Get the value of analysisExceptions - * - * @return the value of analysisExceptions - */ - public List getAnalysisExceptions() { - return analysisExceptions; - } - - /** - * Set the value of analysisExceptions - * - * @param analysisExceptions new value of analysisExceptions - */ - public void setAnalysisExceptions(List analysisExceptions) { - this.analysisExceptions = analysisExceptions; - } - - /** - * Adds an exception to the analysis exceptions collection. - * - * @param ex an exception. - */ - public void addAnalysisException(Exception ex) { - this.analysisExceptions.add(ex); - } - /** - * The description of the JAR file. - */ - protected String description; - - /** - * Get the value of description - * - * @return the value of description - */ - public String getDescription() { - return description; - } - - /** - * Set the value of description - * - * @param description new value of description - */ - public void setDescription(String description) { - this.description = description; - } - /** - * The license that this dependency uses. - */ - private String license; - - /** - * Get the value of license - * - * @return the value of license - */ - public String getLicense() { - return license; - } - - /** - * Set the value of license - * - * @param license new value of license - */ - public void setLicense(String license) { - this.license = license; - } - - /** - * Determines if the specified string was used when searching. - * - * @param str is the string that is being checked if it was used. - * @return true or false. - */ - public boolean containsUsedString(String str) { - if (str == null) { - return false; - } - - String fnd = str.toLowerCase(); - - if (vendorEvidence.containsUsedString(str)) { - return true; - } - if (productEvidence.containsUsedString(str)) { - return true; - } - if (versionEvidence.containsUsedString(fnd)) { - return true; - } - return false; - } - /** - * A list of vulnerabilities for this dependency - */ - private List vulnerabilities; - - /** - * Get the list of vulnerabilities - * - * @return the list of vulnerabilities - */ - public List getVulnerabilities() { - return vulnerabilities; - } - - /** - * Set the value of vulnerabilities - * - * @param vulnerabilities new value of vulnerabilities - */ - public void setVulnerabilities(List vulnerabilities) { - this.vulnerabilities = vulnerabilities; - } - - private void determineHashes(File file) { - String md5 = null; - String sha1 = null; - try { - md5 = Checksum.getMD5Checksum(file); - sha1 = Checksum.getSHA1Checksum(file); - } catch (IOException ex) { - Logger.getLogger(Dependency.class.getName()).log(Level.SEVERE, null, ex); - } catch (NoSuchAlgorithmException ex) { - Logger.getLogger(Dependency.class.getName()).log(Level.SEVERE, null, ex); - } - this.setMd5sum(md5); - this.setSha1sum(sha1); - } - - /** - * Adds a vulnerability to the dependency. - * - * @param vulnerability a vulnerability outlining a vulnerability. - */ - public void addVulnerability(Vulnerability vulnerability) { - this.vulnerabilities.add(vulnerability); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/pair.info deleted file mode 100755 index 4bf9a92..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#54616/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:54616 -comSha:0cf6cfc2b043c1a83e131d48f6db239f6c486339 -parentComSha:6f19360da5159c26727c071046da9010d95f57e3 -BuggyFilePath:src/main/java/org/codesecure/dependencycheck/dependency/Dependency.java -FixedFilePath:src/main/java/org/codesecure/dependencycheck/dependency/Dependency.java -StartLineNum:379 -EndLineNum:379 -repoName:jeremylong#DependencyCheck \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/comMsg.txt deleted file mode 100755 index 1a5457b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -variable mode names are no longer all uppercase \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/diff.diff deleted file mode 100755 index 445be66..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/diff.diff +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java b/src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java -index baf3f941..0056c802 100644 ---- a/src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java -+++ b/src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java -@@ -1214,2 +1214 @@ public class VCGenerator extends TreeWalkerVisitor { -- + " (Condition from \"" -- + p.getMode().getModeName().toUpperCase() -+ + " (Condition from \"" + p.getMode().getModeName() -@@ -1267 +1266 @@ public class VCGenerator extends TreeWalkerVisitor { -- + p.getMode().getModeName().toUpperCase() -+ + p.getMode().getModeName() -@@ -1434 +1433 @@ public class VCGenerator extends TreeWalkerVisitor { -- + p.getMode().getModeName().toUpperCase() -+ + p.getMode().getModeName() -@@ -1481 +1480 @@ public class VCGenerator extends TreeWalkerVisitor { -- + p.getMode().getModeName().toUpperCase() -+ + p.getMode().getModeName() \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/new/VCGenerator.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/new/VCGenerator.java deleted file mode 100755 index 0056c80..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/new/VCGenerator.java +++ /dev/null @@ -1,3356 +0,0 @@ -/** - * VCGenerator.java - * --------------------------------- - * Copyright (c) 2014 - * RESOLVE Software Research Group - * School of Computing - * Clemson University - * All rights reserved. - * --------------------------------- - * This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. - */ -package edu.clemson.cs.r2jt.vcgeneration; - -/* - * Libraries - */ -import edu.clemson.cs.r2jt.ResolveCompiler; -import edu.clemson.cs.r2jt.absyn.*; -import edu.clemson.cs.r2jt.data.*; -import edu.clemson.cs.r2jt.init.CompileEnvironment; -import edu.clemson.cs.r2jt.proving2.VC; -import edu.clemson.cs.r2jt.treewalk.TreeWalkerVisitor; -import edu.clemson.cs.r2jt.typeandpopulate.*; -import edu.clemson.cs.r2jt.typeandpopulate.entry.*; -import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.FacilityStrategy; -import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.ImportStrategy; -import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType; -import edu.clemson.cs.r2jt.typeandpopulate.query.NameQuery; -import edu.clemson.cs.r2jt.typeandpopulate.query.OperationQuery; -import edu.clemson.cs.r2jt.typeandpopulate.query.UnqualifiedNameQuery; -import edu.clemson.cs.r2jt.typereasoning.TypeGraph; -import edu.clemson.cs.r2jt.utilities.Flag; -import edu.clemson.cs.r2jt.utilities.FlagDependencies; -import edu.clemson.cs.r2jt.utilities.SourceErrorException; - -import java.io.File; -import java.util.*; -import java.util.List; - -/** - * TODO: Write a description of this module - */ -public class VCGenerator extends TreeWalkerVisitor { - - // =========================================================== - // Global Variables - // =========================================================== - - // Symbol table related items - private final MathSymbolTableBuilder mySymbolTable; - private final TypeGraph myTypeGraph; - private final MTType BOOLEAN; - private final MTType MTYPE; - private final MTType Z; - private ModuleScope myCurrentModuleScope; - - // Module level global variables - private Exp myGlobalRequiresExp; - private Exp myGlobalConstraintExp; - - // Operation/Procedure level global variables - private OperationEntry myCurrentOperationEntry; - private Exp myOperationDecreasingExp; - - /** - *

The current assertion we are applying - * VC rules to.

- */ - private AssertiveCode myCurrentAssertiveCode; - - /** - *

The current compile environment used throughout - * the compiler.

- */ - private CompileEnvironment myInstanceEnvironment; - - /** - *

A list that will be built up with AssertiveCode - * objects, each representing a VC or group of VCs that must be - * satisfied to verify a parsed program.

- */ - private Collection myFinalAssertiveCodeList; - - /** - *

This object creates the different VC outputs.

- */ - private OutputVCs myOutputGenerator; - - /** - *

A stack that is used to keep track of the AssertiveCode - * that we still need to apply proof rules to.

- */ - private Stack myIncAssertiveCodeStack; - - /** - *

A stack that is used to keep track of the information that we - * haven't printed for the AssertiveCode - * that we still need to apply proof rules to.

- */ - private Stack myIncAssertiveCodeStackInfo; - - /** - *

This string buffer holds all the steps - * the VC generator takes to generate VCs.

- */ - private StringBuffer myVCBuffer; - - // =========================================================== - // Flag Strings - // =========================================================== - - private static final String FLAG_ALTSECTION_NAME = "GenerateVCs"; - private static final String FLAG_DESC_ATLVERIFY_VC = "Generate VCs."; - private static final String FLAG_DESC_ATTLISTVCS_VC = ""; - - // =========================================================== - // Flags - // =========================================================== - - public static final Flag FLAG_ALTVERIFY_VC = - new Flag(FLAG_ALTSECTION_NAME, "altVCs", FLAG_DESC_ATLVERIFY_VC); - - public static final Flag FLAG_ALTLISTVCS_VC = - new Flag(FLAG_ALTSECTION_NAME, "altListVCs", - FLAG_DESC_ATTLISTVCS_VC, Flag.Type.HIDDEN); - - public static final void setUpFlags() { - FlagDependencies.addImplies(FLAG_ALTVERIFY_VC, FLAG_ALTLISTVCS_VC); - } - - // =========================================================== - // Constructors - // =========================================================== - - public VCGenerator(ScopeRepository table, final CompileEnvironment env) { - // Symbol table items - mySymbolTable = (MathSymbolTableBuilder) table; - myTypeGraph = mySymbolTable.getTypeGraph(); - BOOLEAN = myTypeGraph.BOOLEAN; - MTYPE = myTypeGraph.MTYPE; - Z = myTypeGraph.Z; - - // Current items - myCurrentModuleScope = null; - myCurrentOperationEntry = null; - myGlobalConstraintExp = null; - myGlobalRequiresExp = null; - myOperationDecreasingExp = null; - - // Instance Environment - myInstanceEnvironment = env; - - // VCs + Debugging String - myCurrentAssertiveCode = null; - myFinalAssertiveCodeList = new LinkedList(); - myOutputGenerator = null; - myIncAssertiveCodeStack = new Stack(); - myIncAssertiveCodeStackInfo = new Stack(); - myVCBuffer = new StringBuffer(); - } - - // =========================================================== - // Visitor Methods - // =========================================================== - - // ----------------------------------------------------------- - // ConceptBodyModuleDec - // ----------------------------------------------------------- - - @Override - public void preConceptBodyModuleDec(ConceptBodyModuleDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" VC Generation Details "); - myVCBuffer.append(" =========================\n"); - myVCBuffer.append("\n Concept Realization Name:\t"); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append("\n Concept Name:\t"); - myVCBuffer.append(dec.getConceptName().getName()); - myVCBuffer.append("\n"); - myVCBuffer.append("\n===================================="); - myVCBuffer.append("======================================\n"); - myVCBuffer.append("\n"); - - // Set the current module scope - try { - myCurrentModuleScope = - mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); - - // From the list of imports, obtain the global constraints - // of the imported modules. - myGlobalConstraintExp = - getConstraints(dec.getLocation(), myCurrentModuleScope - .getImports()); - - // Store the global requires clause - myGlobalRequiresExp = getRequiresClause(dec); - } - catch (NoSuchSymbolException e) { - System.err.println("Module " + dec.getName() - + " does not exist or is not in scope."); - noSuchModule(dec.getLocation()); - } - } - - @Override - public void postConceptBodyModuleDec(ConceptBodyModuleDec dec) { - // Set the module level global variables to null - myCurrentModuleScope = null; - myGlobalConstraintExp = null; - myGlobalRequiresExp = null; - } - - // ----------------------------------------------------------- - // EnhancementBodyModuleDec - // ----------------------------------------------------------- - - @Override - public void preEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" VC Generation Details "); - myVCBuffer.append(" =========================\n"); - myVCBuffer.append("\n Enhancement Realization Name:\t"); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append("\n Enhancement Name:\t"); - myVCBuffer.append(dec.getEnhancementName().getName()); - myVCBuffer.append("\n Concept Name:\t"); - myVCBuffer.append(dec.getConceptName().getName()); - myVCBuffer.append("\n"); - myVCBuffer.append("\n===================================="); - myVCBuffer.append("======================================\n"); - myVCBuffer.append("\n"); - - // Set the current module scope - try { - myCurrentModuleScope = - mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); - - // From the list of imports, obtain the global constraints - // of the imported modules. - myGlobalConstraintExp = - getConstraints(dec.getLocation(), myCurrentModuleScope - .getImports()); - - // Store the global requires clause - myGlobalRequiresExp = getRequiresClause(dec); - } - catch (NoSuchSymbolException e) { - System.err.println("Module " + dec.getName() - + " does not exist or is not in scope."); - noSuchModule(dec.getLocation()); - } - } - - @Override - public void postEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { - // Set the module level global variables to null - myCurrentModuleScope = null; - myGlobalConstraintExp = null; - myGlobalRequiresExp = null; - } - - // ----------------------------------------------------------- - // FacilityModuleDec - // ----------------------------------------------------------- - - @Override - public void preFacilityModuleDec(FacilityModuleDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" VC Generation Details "); - myVCBuffer.append(" =========================\n"); - myVCBuffer.append("\n Facility Name:\t"); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append("\n"); - myVCBuffer.append("\n===================================="); - myVCBuffer.append("======================================\n"); - myVCBuffer.append("\n"); - - // Set the current module scope - try { - myCurrentModuleScope = - mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); - - // From the list of imports, obtain the global constraints - // of the imported modules. - myGlobalConstraintExp = - getConstraints(dec.getLocation(), myCurrentModuleScope - .getImports()); - - // Store the global requires clause - myGlobalRequiresExp = getRequiresClause(dec); - } - catch (NoSuchSymbolException e) { - System.err.println("Module " + dec.getName() - + " does not exist or is not in scope."); - noSuchModule(dec.getLocation()); - } - } - - @Override - public void postFacilityModuleDec(FacilityModuleDec dec) { - // Set the module level global variables to null - myCurrentModuleScope = null; - myGlobalConstraintExp = null; - myGlobalRequiresExp = null; - } - - // ----------------------------------------------------------- - // FacilityOperationDec - // ----------------------------------------------------------- - - @Override - public void preFacilityOperationDec(FacilityOperationDec dec) { - // Keep the current operation dec - List argTypes = new LinkedList(); - for (ParameterVarDec p : dec.getParameters()) { - argTypes.add(p.getTy().getProgramTypeValue()); - } - myCurrentOperationEntry = - searchOperation(dec.getLocation(), null, dec.getName(), - argTypes); - } - - @Override - public void postFacilityOperationDec(FacilityOperationDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" Procedure: "); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append(" =========================\n"); - - // The current assertive code - int curAssertiveCodeNum = 1; - myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment); - - // Obtains items from the current operation - Location loc = dec.getLocation(); - String name = dec.getName().getName(); - Exp requires = modifyRequiresClause(getRequiresClause(dec), loc, name); - Exp ensures = modifyEnsuresClause(getEnsuresClause(dec), loc, name); - List statementList = dec.getStatements(); - List variableList = dec.getAllVariables(); - Exp decreasing = dec.getDecreasing(); - - // Apply the procedure declaration rule - applyProcedureDeclRule(requires, ensures, decreasing, variableList, - statementList); - - // Add this to our stack of to be processed assertive codes. - myIncAssertiveCodeStack.push(myCurrentAssertiveCode); - myIncAssertiveCodeStackInfo.push(""); - - // Set the current assertive code to null - // YS: (We the modify requires and ensures clause needs to have - // and current assertive code to work. Not very clean way to - // solve the problem, but should work.) - myCurrentAssertiveCode = null; - - // Loop until our to process assertive code stack is empty - while (!myIncAssertiveCodeStack.empty()) { - // Set the incoming assertive code as our current assertive - // code we are working on. - myCurrentAssertiveCode = myIncAssertiveCodeStack.pop(); - - myVCBuffer.append("\n***********************"); - myVCBuffer.append(" Begin Path: "); - myVCBuffer.append(curAssertiveCodeNum); - myVCBuffer.append(" ***********************\n"); - - // Append any information that still needs to be added to our - // Debug VC Buffer - myVCBuffer.append(myIncAssertiveCodeStackInfo.pop()); - - // Apply proof rules - applyEBRules(); - - myVCBuffer.append("\n***********************"); - myVCBuffer.append(" End Path: "); - myVCBuffer.append(curAssertiveCodeNum); - myVCBuffer.append(" ***********************\n"); - curAssertiveCodeNum++; - - // Add it to our list of final assertive codes - myFinalAssertiveCodeList.add(myCurrentAssertiveCode); - - // Set the current assertive code to null - myCurrentAssertiveCode = null; - } - - myOperationDecreasingExp = null; - myCurrentOperationEntry = null; - } - - // ----------------------------------------------------------- - // ModuleDec - // ----------------------------------------------------------- - - @Override - public void postModuleDec(ModuleDec dec) { - // Create the output generator and finalize output - myOutputGenerator = - new OutputVCs(myInstanceEnvironment, myFinalAssertiveCodeList, - myVCBuffer); - - // Check if it is generating VCs for WebIDE or not. - if (myInstanceEnvironment.flags.isFlagSet(ResolveCompiler.FLAG_XML_OUT)) { - myOutputGenerator.outputToJSON(); - } - else { - // Print to file if we are in debug mode - // TODO: Add debug flag here - String filename; - if (myInstanceEnvironment.getOutputFilename() != null) { - filename = myInstanceEnvironment.getOutputFilename(); - } - else { - filename = createVCFileName(); - } - myOutputGenerator.outputToFile(filename); - } - } - - // ----------------------------------------------------------- - // ProcedureDec - // ----------------------------------------------------------- - - @Override - public void preProcedureDec(ProcedureDec dec) { - // Keep the current operation dec - List argTypes = new LinkedList(); - for (ParameterVarDec p : dec.getParameters()) { - argTypes.add(p.getTy().getProgramTypeValue()); - } - myCurrentOperationEntry = - searchOperation(dec.getLocation(), null, dec.getName(), - argTypes); - } - - @Override - public void postProcedureDec(ProcedureDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" Procedure: "); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append(" =========================\n"); - - // The current assertive code - int curAssertiveCodeNum = 1; - myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment); - - // Obtains items from the current operation - Location loc = dec.getLocation(); - String name = dec.getName().getName(); - Exp requires = modifyRequiresClause(getRequiresClause(dec), loc, name); - Exp ensures = modifyEnsuresClause(getEnsuresClause(dec), loc, name); - List statementList = dec.getStatements(); - List variableList = dec.getAllVariables(); - Exp decreasing = dec.getDecreasing(); - - // Apply the procedure declaration rule - applyProcedureDeclRule(requires, ensures, decreasing, variableList, - statementList); - - // Add this to our stack of to be processed assertive codes. - myIncAssertiveCodeStack.push(myCurrentAssertiveCode); - myIncAssertiveCodeStackInfo.push(""); - - // Set the current assertive code to null - // YS: (We the modify requires and ensures clause needs to have - // and current assertive code to work. Not very clean way to - // solve the problem, but should work.) - myCurrentAssertiveCode = null; - - // Loop until our to process assertive code stack is empty - while (!myIncAssertiveCodeStack.empty()) { - // Set the incoming assertive code as our current assertive - // code we are working on. - myCurrentAssertiveCode = myIncAssertiveCodeStack.pop(); - - myVCBuffer.append("\n***********************"); - myVCBuffer.append(" Begin Path: "); - myVCBuffer.append(curAssertiveCodeNum); - myVCBuffer.append(" ***********************\n"); - - // Append any information that still needs to be added to our - // Debug VC Buffer - myVCBuffer.append(myIncAssertiveCodeStackInfo.pop()); - - // Apply proof rules - applyEBRules(); - - myVCBuffer.append("\n***********************"); - myVCBuffer.append(" End Path: "); - myVCBuffer.append(curAssertiveCodeNum); - myVCBuffer.append(" ***********************\n"); - curAssertiveCodeNum++; - - // Add it to our list of final assertive codes - myFinalAssertiveCodeList.add(myCurrentAssertiveCode); - - // Set the current assertive code to null - myCurrentAssertiveCode = null; - } - - myOperationDecreasingExp = null; - myCurrentOperationEntry = null; - } - - // =========================================================== - // Public Methods - // =========================================================== - - // ----------------------------------------------------------- - // Error Handling - // ----------------------------------------------------------- - - public void expNotHandled(Exp exp, Location l) { - String message = "Exp not handled: " + exp.toString(); - throw new SourceErrorException(message, l); - } - - public void illegalOperationEnsures(Location l) { - // TODO: Move this to sanity check. - String message = - "Ensures clauses of operations that return a value should be of the form = "; - throw new SourceErrorException(message, l); - } - - public void notAType(SymbolTableEntry entry, Location l) { - throw new SourceErrorException(entry.getSourceModuleIdentifier() - .fullyQualifiedRepresentation(entry.getName()) - + " is not known to be a type.", l); - } - - public void notInFreeVarList(PosSymbol name, Location l) { - String message = - "State variable " + name + " not in free variable list"; - throw new SourceErrorException(message, l); - } - - public void noSuchModule(Location location) { - throw new SourceErrorException( - "Module does not exist or is not in scope.", location); - } - - public void noSuchSymbol(PosSymbol qualifier, String symbolName, Location l) { - - String message; - - if (qualifier == null) { - message = "No such symbol: " + symbolName; - } - else { - message = - "No such symbol in module: " + qualifier.getName() + "." - + symbolName; - } - - throw new SourceErrorException(message, l); - } - - public void tyNotHandled(Ty ty, Location location) { - String message = "Ty not handled: " + ty.toString(); - throw new SourceErrorException(message, location); - } - - // ----------------------------------------------------------- - // Prover Mode - // ----------------------------------------------------------- - - /** - *

The set of immmutable VCs that the in house provers can use.

- * - * @return VCs to be proved. - */ - public List proverOutput() { - return myOutputGenerator.getProverOutput(); - } - - // =========================================================== - // Private Methods - // =========================================================== - - /** - *

Loop through the list of VarDec, search - * for their corresponding ProgramVariableEntry - * and add the result to the list of free variables.

- * - * @param variableList List of the all variables as - * VarDec. - */ - public void addVarDecsAsFreeVars(List variableList) { - // Loop through the variable list - for (VarDec v : variableList) { - myCurrentAssertiveCode.addFreeVar(createVarExp(v.getLocation(), v - .getName(), v.getTy().getMathTypeValue())); - } - } - - /** - *

Append VC Generator step details to the expression's - * location.

- * - * @param exp The current expression we are dealing with. - * @param text VC Generator step details. - * - * @return The modified expression. - */ - private Exp appendToLocation(Exp exp, String text) { - // Check if the expression is empty or not - // and it must have a valid location. - if (exp != null && exp.getLocation() != null) { - // Recursively apply to infix expressions. - if (exp instanceof InfixExp) { - appendToLocation(((InfixExp) exp).getLeft(), text); - appendToLocation(((InfixExp) exp).getRight(), text); - } - else { - Location loc = exp.getLocation(); - if (loc.getDetails() == null) { - loc.setDetails(text); - } - else { - String details = loc.getDetails().concat(text); - loc.setDetails(details); - } - } - } - - return exp; - } - - /** - *

Converts the different types of Exp to the - * ones used by the VC Generator.

- * - * @param oldExp The expression to be converted. - * - * @return An Exp. - */ - private Exp convertExp(Exp oldExp) { - // Case #1: ProgramIntegerExp - if (oldExp instanceof ProgramIntegerExp) { - IntegerExp exp = new IntegerExp(); - exp.setValue(((ProgramIntegerExp) oldExp).getValue()); - exp.setMathType(Z); - return exp; - } - // Case #2: VariableDotExp - else if (oldExp instanceof VariableDotExp) { - DotExp exp = new DotExp(); - List segments = - ((VariableDotExp) oldExp).getSegments(); - edu.clemson.cs.r2jt.collections.List newSegments = - new edu.clemson.cs.r2jt.collections.List(); - - // Need to replace each of the segments in a dot expression - MTType lastMathType = null; - MTType lastMathTypeValue = null; - for (VariableExp v : segments) { - VarExp varExp = new VarExp(); - - // Can only be a VariableNameExp. Anything else - // is a case we have not handled. - if (v instanceof VariableNameExp) { - varExp.setName(((VariableNameExp) v).getName()); - lastMathType = v.getMathType(); - lastMathTypeValue = v.getMathTypeValue(); - newSegments.add(varExp); - } - else { - expNotHandled(v, v.getLocation()); - } - } - - // Set the segments and the type information. - exp.setSegments(newSegments); - exp.setMathType(lastMathType); - exp.setMathTypeValue(lastMathTypeValue); - return exp; - } - // Case #3: VariableNameExp - else if (oldExp instanceof VariableNameExp) { - VarExp exp = new VarExp(); - exp.setName(((VariableNameExp) oldExp).getName()); - exp.setMathType(oldExp.getMathType()); - exp.setMathTypeValue(oldExp.getMathTypeValue()); - return exp; - } - - return oldExp; - } - - /** - *

Returns a newly created PosSymbol - * with the string provided.

- * - * @param name String of the new PosSymbol. - * - * @return The new PosSymbol. - */ - private PosSymbol createPosSymbol(String name) { - // Create the PosSymbol - PosSymbol posSym = new PosSymbol(); - posSym.setSymbol(Symbol.symbol(name)); - return posSym; - } - - /** - *

Returns an DotExp with the VarDec - * and its initialization ensures clause.

- * - * @param var The declared variable. - * - * @return The new DotExp. - */ - private DotExp createInitExp(VarDec var) { - // Convert the declared variable into a VarExp - VarExp varExp = - createVarExp(var.getLocation(), var.getName(), var.getTy() - .getMathTypeValue()); - - // Left hand side of the expression - VarExp left = null; - - // NameTy - if (var.getTy() instanceof NameTy) { - NameTy ty = (NameTy) var.getTy(); - left = createVarExp(ty.getLocation(), ty.getName(), MTYPE); - } - else { - tyNotHandled(var.getTy(), var.getTy().getLocation()); - } - - // Complicated steps to construct the argument list - // YS: No idea why it is so complicated! - edu.clemson.cs.r2jt.collections.List expList = - new edu.clemson.cs.r2jt.collections.List(); - expList.add(varExp); - FunctionArgList argList = new FunctionArgList(); - argList.setArguments(expList); - edu.clemson.cs.r2jt.collections.List functionArgLists = - new edu.clemson.cs.r2jt.collections.List(); - functionArgLists.add(argList); - - // Right hand side of the expression - FunctionExp right = - new FunctionExp(var.getLocation(), null, - createPosSymbol("Is_Initial"), null, functionArgLists); - right.setMathType(BOOLEAN); - - // Create the DotExp - edu.clemson.cs.r2jt.collections.List exps = - new edu.clemson.cs.r2jt.collections.List(); - exps.add(left); - exps.add(right); - DotExp exp = new DotExp(var.getLocation(), exps, null); - exp.setMathType(BOOLEAN); - - return exp; - } - - /** - *

Creates a variable expression with the name - * "P_val" and has type "N".

- * - * @param location Location that wants to create - * this variable. - * - * @return The created VarExp. - */ - private VarExp createPValExp(Location location) { - // Locate "N" (Natural Number) - MathSymbolEntry mse = searchMathSymbol(location, "N"); - try { - // Create a variable with the name P_val - return createVarExp(location, createPosSymbol("P_val"), mse - .getTypeValue()); - } - catch (SymbolNotOfKindTypeException e) { - notAType(mse, location); - } - - return null; - } - - /** - *

Create a question mark variable with the oldVar - * passed in.

- * - * @param exp The full expression clause. - * @param oldVar The old variable expression. - * - * @return A new variable with the question mark in VarExp form. - */ - private VarExp createQuestionMarkVariable(Exp exp, VarExp oldVar) { - // Add an extra question mark to the front of oldVar - VarExp newOldVar = - new VarExp(null, null, createPosSymbol("?" - + oldVar.getName().getName())); - newOldVar.setMathType(oldVar.getMathType()); - newOldVar.setMathTypeValue(oldVar.getMathTypeValue()); - - // Applies the question mark to oldVar if it is our first time visiting. - if (exp.containsVar(oldVar.getName().getName(), false)) { - return createQuestionMarkVariable(exp, newOldVar); - } - // Don't need to apply the question mark here. - else if (exp.containsVar(newOldVar.getName().toString(), false)) { - return createQuestionMarkVariable(exp, newOldVar); - } - else { - // Return the new variable expression with the question mark - if (oldVar.getName().getName().charAt(0) != '?') { - return newOldVar; - } - } - - // Return our old self. - return oldVar; - } - - /** - *

Returns a newly created VarExp - * with the PosSymbol and math type provided.

- * - * @param loc Location of the new VarExp - * @param name PosSymbol of the new VarExp. - * @param type Math type of the new VarExp. - * - * @return The new VarExp. - */ - private VarExp createVarExp(Location loc, PosSymbol name, MTType type) { - // Create the VarExp - VarExp exp = new VarExp(loc, null, name); - exp.setMathType(type); - return exp; - } - - /** - *

Creates the name of the output file.

- * - * @return Name of the file - */ - private String createVCFileName() { - File file = myInstanceEnvironment.getTargetFile(); - ModuleID cid = myInstanceEnvironment.getModuleID(file); - file = myInstanceEnvironment.getFile(cid); - String filename = file.toString(); - int temp = filename.indexOf("."); - String tempfile = filename.substring(0, temp); - String mainFileName; - - mainFileName = tempfile + ".asrt_new"; - - return mainFileName; - } - - /** - *

Returns all the constraint clauses combined together for the - * for the current ModuleDec.

- * - * @param loc The location of the ModuleDec. - * @param imports The list of imported modules. - * - * @return The constraint clause Exp. - */ - private Exp getConstraints(Location loc, List imports) { - Exp retExp = null; - - // Loop - for (ModuleIdentifier mi : imports) { - try { - ModuleDec dec = - mySymbolTable.getModuleScope(mi).getDefiningElement(); - List contraintExpList = null; - - // Handling for facility imports - if (dec instanceof ShortFacilityModuleDec) { - FacilityDec facDec = - ((ShortFacilityModuleDec) dec).getDec(); - dec = - mySymbolTable.getModuleScope( - new ModuleIdentifier(facDec - .getConceptName().getName())) - .getDefiningElement(); - } - - if (dec instanceof ConceptModuleDec) { - contraintExpList = - ((ConceptModuleDec) dec).getConstraints(); - - // Copy all the constraints - for (Exp e : contraintExpList) { - // Deep copy and set the location detail - Exp constraint = Exp.copy(e); - if (constraint.getLocation() != null) { - Location theLoc = constraint.getLocation(); - theLoc.setDetails("Constraint of Module: " - + dec.getName()); - setLocation(constraint, theLoc); - } - - // Form conjunct if needed. - if (retExp == null) { - retExp = Exp.copy(e); - } - else { - retExp = - myTypeGraph.formConjunct(retExp, Exp - .copy(e)); - } - } - } - } - catch (NoSuchSymbolException e) { - System.err.println("Module " + mi.toString() - + " does not exist or is not in scope."); - noSuchModule(loc); - } - } - - return retExp; - } - - /** - *

Returns the ensures clause for the current Dec.

- * - * @param dec The corresponding Dec. - * - * @return The ensures clause Exp. - */ - private Exp getEnsuresClause(Dec dec) { - PosSymbol name = dec.getName(); - Exp ensures = null; - Exp retExp = null; - - // Check for each kind of ModuleDec possible - if (dec instanceof FacilityOperationDec) { - ensures = ((FacilityOperationDec) dec).getEnsures(); - } - else if (dec instanceof OperationDec) { - ensures = ((OperationDec) dec).getEnsures(); - } - - // Deep copy and fill in the details of this location - if (ensures != null) { - retExp = Exp.copy(ensures); - if (retExp.getLocation() != null) { - Location myLoc = retExp.getLocation(); - myLoc.setDetails("Ensures Clause of " + name); - setLocation(retExp, myLoc); - } - } - - return retExp; - } - - /** - *

Locate and return the corresponding operation dec based on the qualifier, - * name, and arguments.

- * - * @param loc Location of the calling statement. - * @param qual Qualifier of the operation - * @param name Name of the operation. - * @param args List of arguments for the operation. - * - * @return The operation corresponding to the calling statement in OperationDec form. - */ - private OperationDec getOperationDec(Location loc, PosSymbol qual, - PosSymbol name, List args) { - // Obtain the corresponding OperationEntry and OperationDec - List argTypes = new LinkedList(); - for (ProgramExp arg : args) { - argTypes.add(arg.getProgramType()); - } - OperationEntry opEntry = searchOperation(loc, qual, name, argTypes); - - // Obtain an OperationDec from the OperationEntry - ResolveConceptualElement element = opEntry.getDefiningElement(); - OperationDec opDec; - if (element instanceof OperationDec) { - opDec = (OperationDec) opEntry.getDefiningElement(); - } - else { - FacilityOperationDec fOpDec = - (FacilityOperationDec) opEntry.getDefiningElement(); - opDec = - new OperationDec(fOpDec.getName(), fOpDec.getParameters(), - fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec - .getRequires(), fOpDec.getEnsures()); - } - - return opDec; - } - - /** - *

Returns the requires clause for the current Dec.

- * - * @param dec The corresponding Dec. - * - * @return The requires clause Exp. - */ - private Exp getRequiresClause(Dec dec) { - PosSymbol name = dec.getName(); - Exp requires = null; - Exp retExp = null; - - // Check for each kind of ModuleDec possible - if (dec instanceof FacilityOperationDec) { - requires = ((FacilityOperationDec) dec).getRequires(); - } - else if (dec instanceof OperationDec) { - requires = ((OperationDec) dec).getRequires(); - } - else if (dec instanceof ConceptModuleDec) { - requires = ((ConceptModuleDec) dec).getRequirement(); - } - else if (dec instanceof ConceptBodyModuleDec) { - requires = ((ConceptBodyModuleDec) dec).getRequires(); - } - else if (dec instanceof EnhancementModuleDec) { - requires = ((EnhancementModuleDec) dec).getRequirement(); - } - else if (dec instanceof EnhancementBodyModuleDec) { - requires = ((EnhancementBodyModuleDec) dec).getRequires(); - } - else if (dec instanceof FacilityModuleDec) { - requires = ((FacilityModuleDec) dec).getRequirement(); - } - - // Deep copy and fill in the details of this location - if (requires != null) { - retExp = Exp.copy(requires); - if (retExp.getLocation() != null) { - Location myLoc = retExp.getLocation(); - myLoc.setDetails("Requires Clause for " + name); - setLocation(retExp, myLoc); - } - } - - return retExp; - } - - /** - *

Get the PosSymbol associated with the - * VariableExp left.

- * - * @param left The variable expression. - * - * @return The PosSymbol of left. - */ - private PosSymbol getVarName(VariableExp left) { - // Return value - PosSymbol name; - - // Variable Name Expression - if (left instanceof VariableNameExp) { - name = ((VariableNameExp) left).getName(); - } - // Variable Dot Expression - else if (left instanceof VariableDotExp) { - VariableRecordExp varRecExp = - (VariableRecordExp) ((VariableDotExp) left) - .getSemanticExp(); - name = varRecExp.getName(); - } - // Variable Record Expression - else if (left instanceof VariableRecordExp) { - VariableRecordExp varRecExp = (VariableRecordExp) left; - name = varRecExp.getName(); - } - // - // Creates an expression with "false" as its name - else { - name = createPosSymbol("false"); - } - - return name; - } - - /** - *

Checks to see if the initialization ensures clause - * passed is in the simple form where one side has a - * VarExp.

- * - * @param initEnsures The initialization ensures clause, - * or part of it that we are currently - * checking. - * - * @return True/False - */ - private boolean isInitEnsuresSimpleForm(Exp initEnsures) { - boolean isSimple = false; - - // Case #1: EqualExp in initEnsures - if (initEnsures instanceof EqualsExp) { - EqualsExp exp = (EqualsExp) initEnsures; - // Recursively call this on the left and - // right hand side. Only one of the sides - // needs to be a VarExp. - if (isInitEnsuresSimpleForm(exp.getLeft()) - || isInitEnsuresSimpleForm(exp.getRight())) { - isSimple = true; - } - } - // Case #2: InfixExp in initEnsures - else if (initEnsures instanceof InfixExp) { - InfixExp exp = (InfixExp) initEnsures; - // Only check if we have an "and" expression - if (exp.getOpName().equals("and")) { - // Recursively call this on the left and - // right hand side. Both sides need to be - // a VarExp. - if (isInitEnsuresSimpleForm(exp.getLeft()) - && isInitEnsuresSimpleForm(exp.getRight())) { - isSimple = true; - } - } - } - // Case #3: VarExp = initEnsures - else if (initEnsures instanceof VarExp) { - isSimple = true; - } - - return isSimple; - } - - /** - *

Checks to see if the expression passed in is a - * verification variable or not. A verification variable - * is either "P_val" or starts with "?".

- * - * @param name Expression that we want to check - * - * @return True/False - */ - private boolean isVerificationVar(Exp name) { - // VarExp - if (name instanceof VarExp) { - String strName = ((VarExp) name).getName().getName(); - // Case #1: Question mark variables - if (strName.charAt(0) == '?') { - return true; - } - // Case #2: P_val - else if (strName.equals("P_val")) { - return true; - } - } - // DotExp - else if (name instanceof DotExp) { - // Recursively call this method until we get - // either true or false. - List names = ((DotExp) name).getSegments(); - return isVerificationVar(names.get(0)); - } - - // Definitely not a verification variable. - return false; - } - - /** - *

Modifies the ensures clause based on the parameter mode.

- * - * @param ensures The Exp containing the ensures clause. - * @param opLocation The Location for the operation - * @param opName The name of the operation. - * @param parameterVarDecList The list of parameter variables for the operation. - * - * @return The modified ensures clause Exp. - */ - private Exp modifyEnsuresByParameter(Exp ensures, Location opLocation, - String opName, List parameterVarDecList) { - // Loop through each parameter - for (ParameterVarDec p : parameterVarDecList) { - // Ty is NameTy - if (p.getTy() instanceof NameTy) { - NameTy pNameTy = (NameTy) p.getTy(); - - // Exp form of the parameter variable - VarExp parameterExp = - new VarExp(p.getLocation(), null, p.getName().copy()); - parameterExp.setMathType(pNameTy.getMathTypeValue()); - - // Create an old exp (#parameterExp) - OldExp oldParameterExp = - new OldExp(p.getLocation(), Exp.copy(parameterExp)); - oldParameterExp.setMathType(pNameTy.getMathTypeValue()); - - // Preserves or Restores mode - if (p.getMode() == Mode.PRESERVES - || p.getMode() == Mode.RESTORES) { - // Create an equals expression of the form "#parameterExp = parameterExp" - EqualsExp equalsExp = - new EqualsExp(opLocation, oldParameterExp, - EqualsExp.EQUAL, parameterExp); - equalsExp.setMathType(BOOLEAN); - - // Set the details for the new location - Location equalLoc; - if (ensures != null && ensures.getLocation() != null) { - Location enLoc = ensures.getLocation(); - equalLoc = ((Location) enLoc.clone()); - } - else { - equalLoc = ((Location) opLocation.clone()); - equalLoc.setDetails("Ensures Clause of " + opName); - } - equalLoc.setDetails(equalLoc.getDetails() - + " (Condition from \"" + p.getMode().getModeName() - + "\" parameter mode)"); - equalsExp.setLocation(equalLoc); - - // Create an AND infix expression with the ensures clause - if (ensures != null - && !ensures.equals(myTypeGraph.getTrueVarExp())) { - ensures = myTypeGraph.formConjunct(ensures, equalsExp); - } - // Make new expression the ensures clause - else { - ensures = equalsExp; - } - } - // Clears mode - else if (p.getMode() == Mode.CLEARS) { - // Query for the type entry in the symbol table - ProgramTypeEntry typeEntry = - searchProgramType(pNameTy.getLocation(), pNameTy - .getName()); - - Exp init; - if (typeEntry.getDefiningElement() instanceof TypeDec) { - // Obtain the original dec from the AST - TypeDec type = (TypeDec) typeEntry.getDefiningElement(); - - // Obtain the exemplar in VarExp form - VarExp exemplar = - new VarExp(null, null, type.getExemplar()); - exemplar.setMathType(pNameTy.getMathTypeValue()); - - // Deep copy the original initialization ensures and the constraint - init = Exp.copy(type.getInitialization().getEnsures()); - - // Replace the formal with the actual - init = replace(init, exemplar, parameterExp); - - // Set the details for the new location - if (init.getLocation() != null) { - Location initLoc; - if (ensures != null - && ensures.getLocation() != null) { - Location reqLoc = ensures.getLocation(); - initLoc = ((Location) reqLoc.clone()); - } - else { - initLoc = ((Location) opLocation.clone()); - initLoc.setDetails("Ensures Clause of " - + opName); - } - initLoc.setDetails(initLoc.getDetails() - + " (Condition from \"" - + p.getMode().getModeName() - + "\" parameter mode)"); - init.setLocation(initLoc); - } - } - // Since the type is generic, we can only use the is_initial predicate - // to ensure that the value is initial value. - else { - // Obtain the original dec from the AST - Location varLoc = p.getLocation(); - - // Create an is_initial dot expression - init = - createInitExp(new VarDec(p.getName(), p.getTy())); - if (varLoc != null) { - Location loc = (Location) varLoc.clone(); - loc.setDetails("Initial Value for " - + p.getName().getName()); - setLocation(init, loc); - } - } - - // Create an AND infix expression with the ensures clause - if (ensures != null - && !ensures.equals(myTypeGraph.getTrueVarExp())) { - ensures = myTypeGraph.formConjunct(ensures, init); - } - // Make initialization expression the ensures clause - else { - ensures = init; - } - } - } - else { - // Ty not handled. - tyNotHandled(p.getTy(), p.getLocation()); - } - } - - return ensures; - } - - /** - *

Returns the ensures clause.

- * - * @param ensures The Exp containing the ensures clause. - * @param opLocation The Location for the operation. - * @param opName The name for the operation. - * - * @return The modified ensures clause Exp. - */ - private Exp modifyEnsuresClause(Exp ensures, Location opLocation, - String opName) { - // Obtain the list of parameters for the current operation - List parameterVarDecList; - if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) { - parameterVarDecList = - ((FacilityOperationDec) myCurrentOperationEntry - .getDefiningElement()).getParameters(); - } - else { - parameterVarDecList = - ((OperationDec) myCurrentOperationEntry - .getDefiningElement()).getParameters(); - } - - // Modifies the existing ensures clause based on - // the parameter modes. - ensures = - modifyEnsuresByParameter(ensures, opLocation, opName, - parameterVarDecList); - - return ensures; - } - - /** - *

Modifies the requires clause based on .

- * - * @param requires The Exp containing the requires clause. - * - * @return The modified requires clause Exp. - */ - private Exp modifyRequiresByGlobalMode(Exp requires) { - return requires; - } - - /** - *

Modifies the requires clause based on the parameter mode.

- * - * @param requires The Exp containing the requires clause. - * @param opLocation The Location for the operation. - * @param opName The name for the operation. - * - * @return The modified requires clause Exp. - */ - private Exp modifyRequiresByParameter(Exp requires, Location opLocation, - String opName) { - // Obtain the list of parameters - List parameterVarDecList; - if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) { - parameterVarDecList = - ((FacilityOperationDec) myCurrentOperationEntry - .getDefiningElement()).getParameters(); - } - else { - parameterVarDecList = - ((OperationDec) myCurrentOperationEntry - .getDefiningElement()).getParameters(); - } - - // Loop through each parameter - for (ParameterVarDec p : parameterVarDecList) { - ProgramTypeEntry typeEntry; - - // Ty is NameTy - if (p.getTy() instanceof NameTy) { - NameTy pNameTy = (NameTy) p.getTy(); - - // Query for the type entry in the symbol table - typeEntry = - searchProgramType(pNameTy.getLocation(), pNameTy - .getName()); - - // Obtain the original dec from the AST - TypeDec type = (TypeDec) typeEntry.getDefiningElement(); - - // Convert p to a VarExp - VarExp pExp = new VarExp(null, null, p.getName()); - pExp.setMathType(pNameTy.getMathTypeValue()); - - // Obtain the exemplar in VarExp form - VarExp exemplar = new VarExp(null, null, type.getExemplar()); - exemplar.setMathType(pNameTy.getMathTypeValue()); - - // Deep copy the original initialization ensures and the constraint - Exp init = Exp.copy(type.getInitialization().getEnsures()); - Exp constraint = Exp.copy(type.getConstraint()); - - // Only worry about replaces mode parameters - if (p.getMode() == Mode.REPLACES && init != null) { - // Replace the formal with the actual - init = replace(init, exemplar, pExp); - - // Set the details for the new location - if (init.getLocation() != null) { - Location initLoc; - if (requires != null && requires.getLocation() != null) { - Location reqLoc = requires.getLocation(); - initLoc = ((Location) reqLoc.clone()); - } - else { - // Append the name of the current procedure - String details = ""; - if (myCurrentOperationEntry != null) { - details = - " in Procedure " - + myCurrentOperationEntry - .getName(); - } - - // Set the details of the current location - initLoc = ((Location) opLocation.clone()); - initLoc.setDetails("Requires Clause of " + opName - + details); - } - initLoc.setDetails(initLoc.getDetails() - + " (Assumption from \"" - + p.getMode().getModeName() - + "\" parameter mode)"); - init.setLocation(initLoc); - } - - // Create an AND infix expression with the requires clause - if (requires != null - && !requires.equals(myTypeGraph.getTrueVarExp())) { - requires = myTypeGraph.formConjunct(requires, init); - } - // Make initialization expression the requires clause - else { - requires = init; - } - } - // Constraints for the other parameter modes needs to be added - // to the requires clause as conjuncts. - else { - if (constraint != null - && !constraint.equals(myTypeGraph.getTrueVarExp())) { - // Replace the formal with the actual - constraint = replace(constraint, exemplar, pExp); - - // Set the details for the new location - if (constraint.getLocation() != null) { - Location constLoc; - if (requires != null - && requires.getLocation() != null) { - Location reqLoc = requires.getLocation(); - constLoc = ((Location) reqLoc.clone()); - } - else { - // Append the name of the current procedure - String details = ""; - if (myCurrentOperationEntry != null) { - details = - " in Procedure " - + myCurrentOperationEntry - .getName(); - } - - constLoc = ((Location) opLocation.clone()); - constLoc.setDetails("Requires Clause of " - + opName + details); - } - constLoc.setDetails(constLoc.getDetails() - + " (Constraint from \"" - + p.getMode().getModeName() - + "\" parameter mode)"); - constraint.setLocation(constLoc); - } - - // Create an AND infix expression with the requires clause - if (requires != null - && !requires - .equals(myTypeGraph.getTrueVarExp())) { - requires = - myTypeGraph.formConjunct(requires, - constraint); - } - // Make constraint expression the requires clause - else { - requires = constraint; - } - } - } - - // Add the current variable to our list of free variables - myCurrentAssertiveCode.addFreeVar(createVarExp(p.getLocation(), - p.getName(), pNameTy.getMathTypeValue())); - } - else { - // Ty not handled. - tyNotHandled(p.getTy(), p.getLocation()); - } - } - - return requires; - } - - /** - *

Modifies the requires clause.

- * - * @param requires The Exp containing the requires clause. - * @param opLocation The Location for the operation. - * @param opName The name of the operation. - * - * @return The modified requires clause Exp. - */ - private Exp modifyRequiresClause(Exp requires, Location opLocation, - String opName) { - // Modifies the existing requires clause based on - // the parameter modes. - requires = modifyRequiresByParameter(requires, opLocation, opName); - - // Modifies the existing requires clause based on - // the parameter modes. - // TODO: Ask Murali what this means - requires = modifyRequiresByGlobalMode(requires); - - return requires; - } - - /** - *

Negate the incoming expression.

- * - * @param exp Expression to be negated. - * - * @return Negated expression. - */ - private Exp negateExp(Exp exp) { - Exp retExp = Exp.copy(exp); - if (exp instanceof EqualsExp) { - if (((EqualsExp) exp).getOperator() == EqualsExp.EQUAL) - ((EqualsExp) retExp).setOperator(EqualsExp.NOT_EQUAL); - else - ((EqualsExp) retExp).setOperator(EqualsExp.EQUAL); - } - else if (exp instanceof PrefixExp) { - if (((PrefixExp) exp).getSymbol().getName().toString() - .equals("not")) { - retExp = ((PrefixExp) exp).getArgument(); - } - } - else { - PrefixExp tmp = new PrefixExp(); - setLocation(tmp, exp.getLocation()); - tmp.setArgument(exp); - tmp.setSymbol(createPosSymbol("not")); - tmp.setMathType(BOOLEAN); - retExp = tmp; - } - return retExp; - } - - /** - *

Copy and replace the old Exp.

- * - * @param exp The Exp to be replaced. - * @param old The old sub-expression of exp. - * @param repl The new sub-expression of exp. - * - * @return The new Exp. - */ - private Exp replace(Exp exp, Exp old, Exp repl) { - // Clone old and repl and use the Exp replace to do all its work - Exp tmp = Exp.replace(exp, Exp.copy(old), Exp.copy(repl)); - - // Return the corresponding Exp - if (tmp != null) - return tmp; - else - return exp; - } - - /** - *

Replace the formal with the actual variables - * inside the ensures clause.

- * - * @param ensures The ensures clause. - * @param paramList The list of parameter variables. - * @param stateVarList The list of state variables. - * @param argList The list of arguments from the operation call. - * @param isSimple Check if it is a simple replacement. - * - * @return The ensures clause in Exp form. - */ - private Exp replaceFormalWithActualEns(Exp ensures, - List paramList, List stateVarList, - List argList, boolean isSimple) { - // Current final confirm - Exp newConfirm = myCurrentAssertiveCode.getFinalConfirm(); - - // List to hold temp and real values of variables in case - // of duplicate spec and real variables - List undRepList = new ArrayList(); - List replList = new ArrayList(); - - // Replace state variables in the ensures clause - // and create new confirm statements if needed. - for (int i = 0; i < stateVarList.size(); i++) { - newConfirm = myCurrentAssertiveCode.getFinalConfirm(); - AffectsItem stateVar = stateVarList.get(i); - - // Only deal with Alters/Reassigns/Replaces/Updates modes - if (stateVar.getMode() == Mode.ALTERS - || stateVar.getMode() == Mode.REASSIGNS - || stateVar.getMode() == Mode.REPLACES - || stateVar.getMode() == Mode.UPDATES) { - // Obtain the variable from our free variable list - Exp globalFreeVar = - myCurrentAssertiveCode.getFreeVar(stateVar.getName(), - true); - if (globalFreeVar != null) { - VarExp oldNamesVar = new VarExp(); - oldNamesVar.setName(stateVar.getName()); - - // Create a local free variable if it is not there - Exp localFreeVar = - myCurrentAssertiveCode.getFreeVar(stateVar - .getName(), false); - if (localFreeVar == null) { - // TODO: Don't have a type for state variables? - localFreeVar = - new VarExp(null, null, stateVar.getName()); - localFreeVar = - createQuestionMarkVariable(myTypeGraph - .formConjunct(ensures, newConfirm), - (VarExp) localFreeVar); - myCurrentAssertiveCode.addFreeVar(localFreeVar); - } - else { - localFreeVar = - createQuestionMarkVariable(myTypeGraph - .formConjunct(ensures, newConfirm), - (VarExp) localFreeVar); - } - - // Creating "#" expressions and replace these in the - // ensures clause. - OldExp osVar = new OldExp(null, Exp.copy(globalFreeVar)); - OldExp oldNameOSVar = - new OldExp(null, Exp.copy(oldNamesVar)); - ensures = replace(ensures, oldNamesVar, globalFreeVar); - ensures = replace(ensures, oldNameOSVar, osVar); - - // If it is not simple replacement, replace all ensures clauses - // with the appropriate expressions. - if (!isSimple) { - ensures = replace(ensures, globalFreeVar, localFreeVar); - ensures = replace(ensures, osVar, globalFreeVar); - newConfirm = - replace(newConfirm, globalFreeVar, localFreeVar); - } - - // Set newConfirm as our new final confirm statement - myCurrentAssertiveCode.setFinalConfirm(newConfirm); - } - // Error: Why isn't it a free variable. - else { - notInFreeVarList(stateVar.getName(), stateVar.getLocation()); - } - } - } - - // Replace postcondition variables in the ensures clause - for (int i = 0; i < argList.size(); i++) { - ParameterVarDec varDec = paramList.get(i); - ProgramExp pExp = argList.get(i); - PosSymbol VDName = varDec.getName(); - - // VarExp form of the parameter variable - VarExp oldExp = new VarExp(null, null, VDName); - oldExp.setMathType(pExp.getMathType()); - oldExp.setMathTypeValue(pExp.getMathTypeValue()); - - // Convert the pExp into a something we can use - Exp repl = convertExp(pExp); - Exp undqRep = null, quesRep = null; - OldExp oSpecVar, oRealVar; - String replName = null; - - // Case #1: ProgramIntegerExp - if (pExp instanceof ProgramIntegerExp) { - replName = - Integer.toString(((ProgramIntegerExp) repl).getValue()); - - // Create a variable expression of the form "_?[Argument Name]" - undqRep = - new VarExp(null, null, createPosSymbol("_?" + replName)); - undqRep.setMathType(pExp.getMathType()); - undqRep.setMathTypeValue(pExp.getMathTypeValue()); - - // Create a variable expression of the form "?[Argument Name]" - quesRep = - new VarExp(null, null, createPosSymbol("?" + replName)); - quesRep.setMathType(pExp.getMathType()); - quesRep.setMathTypeValue(pExp.getMathTypeValue()); - } - // Case #2: VariableDotExp - else if (pExp instanceof VariableDotExp) { - if (repl instanceof DotExp) { - Exp pE = ((DotExp) repl).getSegments().get(0); - replName = pE.toString(0); - - // Create a variable expression of the form "_?[Argument Name]" - undqRep = Exp.copy(repl); - edu.clemson.cs.r2jt.collections.List segList = - ((DotExp) undqRep).getSegments(); - VariableNameExp undqNameRep = - new VariableNameExp(null, null, - createPosSymbol("_?" + replName)); - undqNameRep.setMathType(pE.getMathType()); - segList.set(0, undqNameRep); - ((DotExp) undqRep).setSegments(segList); - - // Create a variable expression of the form "?[Argument Name]" - quesRep = Exp.copy(repl); - segList = ((DotExp) quesRep).getSegments(); - segList - .set(0, ((VariableDotExp) pExp).getSegments() - .get(0)); - ((DotExp) quesRep).setSegments(segList); - } - else if (repl instanceof VariableDotExp) { - Exp pE = ((VariableDotExp) repl).getSegments().get(0); - replName = pE.toString(0); - - // Create a variable expression of the form "_?[Argument Name]" - undqRep = Exp.copy(repl); - edu.clemson.cs.r2jt.collections.List segList = - ((VariableDotExp) undqRep).getSegments(); - VariableNameExp undqNameRep = - new VariableNameExp(null, null, - createPosSymbol("_?" + replName)); - undqNameRep.setMathType(pE.getMathType()); - segList.set(0, undqNameRep); - ((VariableDotExp) undqRep).setSegments(segList); - - // Create a variable expression of the form "?[Argument Name]" - quesRep = Exp.copy(repl); - segList = ((VariableDotExp) quesRep).getSegments(); - segList - .set(0, ((VariableDotExp) pExp).getSegments() - .get(0)); - ((VariableDotExp) quesRep).setSegments(segList); - } - // Error: Case not handled! - else { - expNotHandled(pExp, pExp.getLocation()); - } - } - // Case #3: VariableNameExp - else if (pExp instanceof VariableNameExp) { - // Name of repl in string form - replName = ((VariableNameExp) pExp).getName().getName(); - - // Create a variable expression of the form "_?[Argument Name]" - undqRep = - new VarExp(null, null, createPosSymbol("_?" + replName)); - undqRep.setMathType(pExp.getMathType()); - undqRep.setMathTypeValue(pExp.getMathTypeValue()); - - // Create a variable expression of the form "?[Argument Name]" - quesRep = - new VarExp(null, null, createPosSymbol("?" + replName)); - quesRep.setMathType(pExp.getMathType()); - quesRep.setMathTypeValue(pExp.getMathTypeValue()); - } - // Error: Case not handled! - else { - expNotHandled(pExp, pExp.getLocation()); - } - - // "#" versions of oldExp and repl - oSpecVar = new OldExp(null, Exp.copy(oldExp)); - oRealVar = new OldExp(null, Exp.copy(repl)); - - // Nothing can be null! - if (oldExp != null && quesRep != null && oSpecVar != null - && repl != null && oRealVar != null) { - // Alters, Clears, Reassigns, Replaces, Updates - if (varDec.getMode() == Mode.ALTERS - || varDec.getMode() == Mode.CLEARS - || varDec.getMode() == Mode.REASSIGNS - || varDec.getMode() == Mode.REPLACES - || varDec.getMode() == Mode.UPDATES) { - Exp quesVar; - - // Obtain the free variable - VarExp freeVar = - (VarExp) myCurrentAssertiveCode.getFreeVar( - createPosSymbol(replName), false); - if (freeVar == null) { - freeVar = - createVarExp(varDec.getLocation(), - createPosSymbol(replName), varDec - .getTy().getMathTypeValue()); - } - - // Apply the question mark to the free variable - freeVar = - createQuestionMarkVariable(myTypeGraph - .formConjunct(ensures, newConfirm), freeVar); - - if (pExp instanceof ProgramDotExp - || pExp instanceof VariableDotExp) { - // Make a copy from repl - quesVar = Exp.copy(repl); - - // Replace the free variable in the question mark variable as the first element - // in the dot expression. - VarExp tmpVar = - new VarExp(null, null, freeVar.getName()); - tmpVar.setMathType(myTypeGraph.BOOLEAN); - edu.clemson.cs.r2jt.collections.List segs = - ((DotExp) quesVar).getSegments(); - segs.set(0, tmpVar); - ((DotExp) quesVar).setSegments(segs); - } - else { - // Create a variable expression from free variable - quesVar = new VarExp(null, null, freeVar.getName()); - quesVar.setMathType(freeVar.getMathType()); - quesVar.setMathTypeValue(freeVar.getMathTypeValue()); - } - - // Add the new free variable to free variable list - myCurrentAssertiveCode.addFreeVar(freeVar); - - // Check if our ensures clause has the parameter variable in it. - if (ensures.containsVar(VDName.getName(), true) - || ensures.containsVar(VDName.getName(), false)) { - // Replace the ensures clause - ensures = replace(ensures, oldExp, undqRep); - ensures = replace(ensures, oSpecVar, repl); - - // Add it to our list of variables to be replaced later - undRepList.add(undqRep); - replList.add(quesVar); - } - else { - // Replace the ensures clause - ensures = replace(ensures, oldExp, quesRep); - ensures = replace(ensures, oSpecVar, repl); - } - - // Update our final confirm with the parameter argument - newConfirm = replace(newConfirm, repl, quesVar); - myCurrentAssertiveCode.setFinalConfirm(newConfirm); - } - // All other modes - else { - // Check if our ensures clause has the parameter variable in it. - if (ensures.containsVar(VDName.getName(), true) - || ensures.containsVar(VDName.getName(), false)) { - // Replace the ensures clause - ensures = replace(ensures, oldExp, undqRep); - ensures = replace(ensures, oSpecVar, undqRep); - - // Add it to our list of variables to be replaced later - undRepList.add(undqRep); - replList.add(repl); - } - else { - // Replace the ensures clause - ensures = replace(ensures, oldExp, repl); - ensures = replace(ensures, oSpecVar, repl); - } - } - } - } - - // Replace the temp values with the actual values - for (int i = 0; i < undRepList.size(); i++) { - ensures = replace(ensures, undRepList.get(i), replList.get(i)); - } - - return ensures; - } - - /** - *

Replace the formal with the actual variables - * inside the requires clause.

- * - * @param requires The requires clause. - * @param paramList The list of parameter variables. - * @param argList The list of arguments from the operation call. - * - * @return The requires clause in Exp form. - */ - private Exp replaceFormalWithActualReq(Exp requires, - List paramList, List argList) { - // List to hold temp and real values of variables in case - // of duplicate spec and real variables - List undRepList = new ArrayList(); - List replList = new ArrayList(); - - // Replace precondition variables in the requires clause - for (int i = 0; i < argList.size(); i++) { - ParameterVarDec varDec = paramList.get(i); - ProgramExp pExp = argList.get(i); - - // Convert the pExp into a something we can use - Exp repl = convertExp(pExp); - - // VarExp form of the parameter variable - VarExp oldExp = new VarExp(null, null, varDec.getName()); - oldExp.setMathType(pExp.getMathType()); - oldExp.setMathTypeValue(pExp.getMathTypeValue()); - - // New VarExp - VarExp newExp = - new VarExp(null, null, createPosSymbol("_" - + varDec.getName().getName())); - newExp.setMathType(repl.getMathType()); - newExp.setMathTypeValue(repl.getMathTypeValue()); - - // Replace the old with the new in the requires clause - requires = replace(requires, oldExp, newExp); - - // Add it to our list - undRepList.add(newExp); - replList.add(repl); - } - - // Replace the temp values with the actual values - for (int i = 0; i < undRepList.size(); i++) { - requires = replace(requires, undRepList.get(i), replList.get(i)); - } - - return requires; - } - - /** - *

Given a math symbol name, locate and return - * the MathSymbolEntry stored in the - * symbol table.

- * - * @param loc The location in the AST that we are - * currently visiting. - * @param name The string name of the math symbol. - * - * @return An MathSymbolEntry from the - * symbol table. - */ - private MathSymbolEntry searchMathSymbol(Location loc, String name) { - // Query for the corresponding math symbol - MathSymbolEntry ms = null; - try { - ms = - myCurrentModuleScope.queryForOne( - new UnqualifiedNameQuery(name, - ImportStrategy.IMPORT_RECURSIVE, - FacilityStrategy.FACILITY_IGNORE, true, - true)).toMathSymbolEntry(loc); - } - catch (NoSuchSymbolException nsse) { - noSuchSymbol(null, name, loc); - } - catch (DuplicateSymbolException dse) { - //This should be caught earlier, when the duplicate symbol is - //created - throw new RuntimeException(dse); - } - - return ms; - } - - /** - *

Given the qualifier, name and the list of argument - * types, locate and return the OperationEntry - * stored in the symbol table.

- * - * @param loc The location in the AST that we are - * currently visiting. - * @param qualifier The qualifier of the operation. - * @param name The name of the operation. - * @param argTypes The list of argument types. - * - * @return An OperationEntry from the - * symbol table. - */ - private OperationEntry searchOperation(Location loc, PosSymbol qualifier, - PosSymbol name, List argTypes) { - // Query for the corresponding operation - OperationEntry op = null; - try { - op = - myCurrentModuleScope.queryForOne(new OperationQuery( - qualifier, name, argTypes)); - } - catch (NoSuchSymbolException nsse) { - noSuchSymbol(null, name.getName(), loc); - } - catch (DuplicateSymbolException dse) { - //This should be caught earlier, when the duplicate operation is - //created - throw new RuntimeException(dse); - } - - return op; - } - - /** - *

Given the name of the type locate and return - * the ProgramTypeEntry stored in the - * symbol table.

- * - * @param loc The location in the AST that we are - * currently visiting. - * @param name The name of the type. - * - * @return An ProgramTypeEntry from the - * symbol table. - */ - private ProgramTypeEntry searchProgramType(Location loc, PosSymbol name) { - // Query for the corresponding operation - ProgramTypeEntry pt = null; - try { - pt = - myCurrentModuleScope.queryForOne( - new NameQuery(null, name, - ImportStrategy.IMPORT_NAMED, - FacilityStrategy.FACILITY_INSTANTIATE, - false)).toProgramTypeEntry(loc); - } - catch (NoSuchSymbolException nsse) { - noSuchSymbol(null, name.getName(), loc); - } - catch (DuplicateSymbolException dse) { - //This should be caught earlier, when the duplicate type is - //created - throw new RuntimeException(dse); - } - - return pt; - } - - /** - *

Changes the Exp with the new - * Location.

- * - * @param exp The Exp that needs to be modified. - * @param loc The new Location. - */ - private void setLocation(Exp exp, Location loc) { - // Special handling for InfixExp - if (exp instanceof InfixExp) { - ((InfixExp) exp).setAllLocations(loc); - } - else { - exp.setLocation(loc); - } - } - - /** - *

Simplify the assume statement where possible.

- * - * @param stmt The assume statement we want to simplify. - * @param exp The current expression we are dealing with. - * - * @return The modified expression in Exp/code> form. - */ - private Exp simplifyAssumeRule(AssumeStmt stmt, Exp exp) { - // Variables - Exp assertion = stmt.getAssertion(); - boolean keepAssumption = false; - - // EqualsExp - if (assertion instanceof EqualsExp) { - EqualsExp equalsExp = (EqualsExp) assertion; - - // Only do simplifications if we have an equals - if (equalsExp.getOperator() == EqualsExp.EQUAL) { - boolean verificationVariable = - isVerificationVar(equalsExp.getLeft()); - - // Create a temp expression where left is replaced with the right - Exp tmp = - replace(exp, equalsExp.getLeft(), equalsExp.getRight()); - if (equalsExp.getLeft() instanceof VarExp) { - // If left is still part of confirm - VarExp left = (VarExp) equalsExp.getLeft(); - if (tmp.containsVar(left.getName().getName(), false)) { - keepAssumption = true; - } - } - - // If tmp is not null, then it means we have to check the right - if (tmp == null) { - // Create a temp expression where right is replaced with the left - verificationVariable = - isVerificationVar(equalsExp.getRight()); - tmp = - replace(exp, equalsExp.getRight(), equalsExp - .getLeft()); - if (equalsExp.getRight() instanceof VarExp) { - // If right is still part of confirm - VarExp right = (VarExp) equalsExp.getRight(); - if (tmp.containsVar(right.getName().getName(), false)) { - keepAssumption = true; - } - } - } - - // We clear our assertion for this assumes if - // we have a verification variable and we don't have to - // keep this assumption. - if (verificationVariable && !keepAssumption) { - assertion = null; - } - - // Update exp - if (!tmp.equals(exp)) { - exp = tmp; - } - } - } - // InfixExp - else if (assertion instanceof InfixExp) { - InfixExp infixExp = (InfixExp) assertion; - - // Only do simplifications if we have an and operator - if (infixExp.getOpName().equals("and")) { - // Recursively call simplify on the left and on the right - AssumeStmt left = new AssumeStmt(Exp.copy(infixExp.getLeft())); - AssumeStmt right = - new AssumeStmt(Exp.copy(infixExp.getRight())); - exp = simplifyAssumeRule(left, exp); - exp = simplifyAssumeRule(right, exp); - - // Case #1: Nothing left - if (left.getAssertion() == null && right.getAssertion() == null) { - assertion = null; - } - // Case #2: Both still have assertions - else if (left.getAssertion() != null - && right.getAssertion() != null) { - assertion = - myTypeGraph.formConjunct(left.getAssertion(), right - .getAssertion()); - } - // Case #3: Left still has assertions - else if (left.getAssertion() != null) { - assertion = left.getAssertion(); - } - // Case #r: Right still has assertions - else { - assertion = right.getAssertion(); - } - } - } - - // Store the new assertion - stmt.setAssertion(assertion); - - return exp; - } - - // ----------------------------------------------------------- - // Proof Rules - // ----------------------------------------------------------- - - /** - *

Applies the assume rule.

- * - * @param assume The assume clause - */ - private void applyAssumeRule(VerificationStatement assume) { - if (assume.getAssertion() instanceof VarExp - && ((VarExp) assume.getAssertion()).equals(Exp - .getTrueVarExp(myTypeGraph))) { - // Verbose Mode Debug Messages - myVCBuffer.append("\nAssume Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - else { - // Obtain the current final confirm clause - Exp conf = myCurrentAssertiveCode.getFinalConfirm(); - - // Create a new implies expression - InfixExp newConf = - myTypeGraph.formImplies((Exp) assume.getAssertion(), conf); - - // Set this new expression as the new final confirm - myCurrentAssertiveCode.setFinalConfirm(newConf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nAssume Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - } - - /** - *

Applies the change rule.

- * - * @param change The change clause - */ - private void applyChangeRule(VerificationStatement change) { - List changeList = - (List) change.getAssertion(); - Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); - - // Loop through each variable - for (VariableExp v : changeList) { - // v is an instance of VariableNameExp - if (v instanceof VariableNameExp) { - VariableNameExp vNameExp = (VariableNameExp) v; - - // Create VarExp for vNameExp - VarExp vExp = - createVarExp(vNameExp.getLocation(), - vNameExp.getName(), vNameExp.getMathType()); - - // Create a new question mark variable - VarExp newV = createQuestionMarkVariable(finalConfirm, vExp); - - // Add this new variable to our list of free variables - myCurrentAssertiveCode.addFreeVar(newV); - - // Replace all instances of vExp with newV - finalConfirm = replace(finalConfirm, vExp, newV); - } - } - - // Set the modified statement as our new final confirm - myCurrentAssertiveCode.setFinalConfirm(finalConfirm); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nChange Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies different rules to code statements.

- * - * @param statement The different statements. - */ - private void applyCodeRules(Statement statement) { - // Apply each statement rule here. - if (statement instanceof AssumeStmt) { - applyEBAssumeStmtRule((AssumeStmt) statement); - } - else if (statement instanceof CallStmt) { - applyEBCallStmtRule((CallStmt) statement); - } - else if (statement instanceof ConfirmStmt) { - applyEBConfirmStmtRule((ConfirmStmt) statement); - } - else if (statement instanceof FuncAssignStmt) { - applyEBFuncAssignStmtRule((FuncAssignStmt) statement); - } - else if (statement instanceof IfStmt) { - applyEBIfStmtRule((IfStmt) statement); - } - else if (statement instanceof SwapStmt) { - applyEBSwapStmtRule((SwapStmt) statement); - } - else if (statement instanceof WhileStmt) { - applyEBWhileStmtRule((WhileStmt) statement); - } - } - - /** - *

Applies the confirm rule.

- * - * @param confirm The confirm clause - */ - private void applyConfirmRule(VerificationStatement confirm) { - if (confirm.getAssertion() instanceof VarExp - && ((VarExp) confirm.getAssertion()).equals(Exp - .getTrueVarExp(myTypeGraph))) { - myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - else { - // Obtain the current final confirm clause - Exp conf = myCurrentAssertiveCode.getFinalConfirm(); - - // Create a new and expression - InfixExp newConf = - myTypeGraph - .formConjunct((Exp) confirm.getAssertion(), conf); - - // Set this new expression as the new final confirm - myCurrentAssertiveCode.setFinalConfirm(newConf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nConfirm Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - } - - /** - *

Applies the assume rule to the - * Statement.

- * - * @param stmt Our current AssumeStmt. - */ - private void applyEBAssumeStmtRule(AssumeStmt stmt) { - // Check to see if our assertion just has "True" - Exp assertion = stmt.getAssertion(); - if (assertion instanceof VarExp - && assertion.equals(myTypeGraph.getTrueVarExp())) { - // Verbose Mode Debug Messages - myVCBuffer.append("\nAssume Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - - return; - } - - // Apply simplification - Exp currentFinalConfirm = - simplifyAssumeRule(stmt, myCurrentAssertiveCode - .getFinalConfirm()); - if (stmt.getAssertion() != null) { - // Create a new implies expression - currentFinalConfirm = - myTypeGraph.formImplies(stmt.getAssertion(), - currentFinalConfirm); - } - - // Set this as our new final confirm - myCurrentAssertiveCode.setFinalConfirm(currentFinalConfirm); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nAssume Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the call statement rule to the - * Statement.

- * - * @param stmt Our current CallStmt. - */ - private void applyEBCallStmtRule(CallStmt stmt) { - // Call a method to locate the operation dec for this call - OperationDec opDec = - getOperationDec(stmt.getLocation(), stmt.getQualifier(), stmt - .getName(), stmt.getArguments()); - - // Get the ensures clause for this operation - // Note: If there isn't an ensures clause, it is set to "True" - Exp ensures; - if (opDec.getEnsures() != null) { - ensures = Exp.copy(opDec.getEnsures()); - } - else { - ensures = myTypeGraph.getTrueVarExp(); - } - - // Get the requires clause for this operation - Exp requires; - if (opDec.getRequires() != null) { - requires = Exp.copy(opDec.getRequires()); - } - else { - requires = myTypeGraph.getTrueVarExp(); - } - - // Check for recursive call of itself - if (myCurrentOperationEntry.getName().equals(opDec.getName()) - && myCurrentOperationEntry.getReturnType() != null) { - // Create a new confirm statement using P_val and the decreasing clause - VarExp pVal = createPValExp(myOperationDecreasingExp.getLocation()); - - // Create a new infix expression - InfixExp exp = - new InfixExp(stmt.getLocation(), Exp - .copy(myOperationDecreasingExp), - createPosSymbol("<"), pVal); - exp.setMathType(BOOLEAN); - - // Create the new confirm statement - Location loc; - if (myOperationDecreasingExp.getLocation() != null) { - loc = (Location) myOperationDecreasingExp.getLocation().clone(); - } - else { - loc = (Location) stmt.getLocation().clone(); - } - loc.setDetails("Show Termination of Recursive Call"); - setLocation(exp, loc); - ConfirmStmt conf = new ConfirmStmt(loc, exp); - - // Add it to our list of assertions - myCurrentAssertiveCode.addCode(conf); - } - - // Modify ensures using the parameter modes - ensures = - modifyEnsuresByParameter(ensures, stmt.getLocation(), opDec - .getName().getName(), opDec.getParameters()); - - // Replace PreCondition variables in the requires clause - requires = - replaceFormalWithActualReq(requires, opDec.getParameters(), - stmt.getArguments()); - - // Replace PostCondition variables in the ensures clause - ensures = - replaceFormalWithActualEns(ensures, opDec.getParameters(), - opDec.getStateVars(), stmt.getArguments(), false); - - // Modify the location of the requires clause and add it to myCurrentAssertiveCode - if (requires != null) { - // Obtain the current location - // Note: If we don't have a location, we create one - Location loc; - if (stmt.getName().getLocation() != null) { - loc = (Location) stmt.getName().getLocation().clone(); - } - else { - loc = new Location(null, null); - } - - // Append the name of the current procedure - String details = ""; - if (myCurrentOperationEntry != null) { - details = " in Procedure " + myCurrentOperationEntry.getName(); - } - - // Set the details of the current location - loc.setDetails("Requires Clause of " + opDec.getName() + details); - setLocation(requires, loc); - - // Add this to our list of things to confirm - myCurrentAssertiveCode.addConfirm(requires); - } - - // Modify the location of the requires clause and add it to myCurrentAssertiveCode - if (ensures != null) { - // Obtain the current location - if (stmt.getName().getLocation() != null) { - // Set the details of the current location - Location loc = (Location) stmt.getName().getLocation().clone(); - loc.setDetails("Ensures Clause of " + opDec.getName()); - setLocation(ensures, loc); - } - - // Add this to our list of things to assume - myCurrentAssertiveCode.addAssume(ensures); - } - - // Verbose Mode Debug Messages - myVCBuffer.append("\nOperation Call Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the confirm rule to the - * Statement.

- * - * @param stmt Our current ConfirmStmt. - */ - private void applyEBConfirmStmtRule(ConfirmStmt stmt) { - // Check to see if our assertion just has "True" - Exp assertion = stmt.getAssertion(); - if (assertion instanceof VarExp - && assertion.equals(myTypeGraph.getTrueVarExp())) { - // Verbose Mode Debug Messages - myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - - return; - } - - // Obtain the current final confirm statement - Exp currentFinalConfirm = myCurrentAssertiveCode.getFinalConfirm(); - - // Check to see if we have a final confirm of "True" - if (currentFinalConfirm instanceof VarExp - && currentFinalConfirm.equals(myTypeGraph.getTrueVarExp())) { - - // Obtain the current location - if (assertion.getLocation() != null) { - // Set the details of the current location - Location loc = (Location) assertion.getLocation().clone(); - setLocation(assertion, loc); - } - - myCurrentAssertiveCode.setFinalConfirm(assertion); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - else { - // Create a new and expression - InfixExp newConf = - myTypeGraph.formConjunct(assertion, currentFinalConfirm); - - // Set this new expression as the new final confirm - myCurrentAssertiveCode.setFinalConfirm(newConf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nConfirm Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - } - - /** - *

Applies each of the proof rules. This AssertiveCode will be - * stored for later use and therefore should be considered immutable after - * a call to this method.

- */ - private void applyEBRules() { - // Apply a proof rule to each of the assertions - while (myCurrentAssertiveCode.hasAnotherAssertion()) { - // Work our way from the last assertion - VerificationStatement curAssertion = - myCurrentAssertiveCode.getLastAssertion(); - - switch (curAssertion.getType()) { - // Assume Assertion - case VerificationStatement.ASSUME: - applyAssumeRule(curAssertion); - break; - // Change Assertion - case VerificationStatement.CHANGE: - applyChangeRule(curAssertion); - break; - // Confirm Assertion - case VerificationStatement.CONFIRM: - applyConfirmRule(curAssertion); - break; - // Code - case VerificationStatement.CODE: - applyCodeRules((Statement) curAssertion.getAssertion()); - break; - // Remember Assertion - case VerificationStatement.REMEMBER: - applyRememberRule(); - break; - // Variable Declaration Assertion - case VerificationStatement.VARIABLE: - applyVarDeclRule(curAssertion); - break; - } - } - } - - /** - *

Applies the function assignment rule to the - * Statement.

- * - * @param stmt Our current FuncAssignStmt. - */ - private void applyEBFuncAssignStmtRule(FuncAssignStmt stmt) { - PosSymbol qualifier = null; - ProgramExp assignExp = stmt.getAssign(); - ProgramParamExp assignParamExp = null; - - // Check to see what kind of expression is on the right hand side - if (assignExp instanceof ProgramParamExp) { - // Cast to a ProgramParamExp - assignParamExp = (ProgramParamExp) assignExp; - } - else if (assignExp instanceof ProgramDotExp) { - // Cast to a ProgramParamExp - ProgramDotExp dotExp = (ProgramDotExp) assignExp; - assignParamExp = (ProgramParamExp) dotExp.getExp(); - qualifier = dotExp.getQualifier(); - } - else { - // TODO: ERROR! - } - - // Call a method to locate the operation dec for this call - OperationDec opDec = - getOperationDec(stmt.getLocation(), qualifier, assignParamExp - .getName(), assignParamExp.getArguments()); - - // Check for recursive call of itself - if (myCurrentOperationEntry.getName().equals(opDec.getName()) - && myCurrentOperationEntry.getReturnType() != null) { - // Create a new confirm statement using P_val and the decreasing clause - VarExp pVal = createPValExp(myOperationDecreasingExp.getLocation()); - - // Create a new infix expression - InfixExp exp = - new InfixExp(stmt.getLocation(), Exp - .copy(myOperationDecreasingExp), - createPosSymbol("<"), pVal); - exp.setMathType(BOOLEAN); - - // Create the new confirm statement - Location loc; - if (myOperationDecreasingExp.getLocation() != null) { - loc = (Location) myOperationDecreasingExp.getLocation().clone(); - } - else { - loc = (Location) stmt.getLocation().clone(); - } - loc.setDetails("Show Termination of Recursive Call"); - setLocation(exp, loc); - ConfirmStmt conf = new ConfirmStmt(loc, exp); - - // Add it to our list of assertions - myCurrentAssertiveCode.addCode(conf); - } - - // Get the requires clause for this operation - Exp requires; - if (opDec.getRequires() != null) { - requires = Exp.copy(opDec.getRequires()); - } - else { - requires = myTypeGraph.getTrueVarExp(); - } - - // Replace PreCondition variables in the requires clause - requires = - replaceFormalWithActualReq(requires, opDec.getParameters(), - assignParamExp.getArguments()); - - // Modify the location of the requires clause and add it to myCurrentAssertiveCode - // Obtain the current location - // Note: If we don't have a location, we create one - Location reqloc; - if (assignParamExp.getName().getLocation() != null) { - reqloc = (Location) assignParamExp.getName().getLocation().clone(); - } - else { - reqloc = new Location(null, null); - } - - // Append the name of the current procedure - String details = ""; - if (myCurrentOperationEntry != null) { - details = " in Procedure " + myCurrentOperationEntry.getName(); - } - - // Set the details of the current location - reqloc.setDetails("Requires Clause of " + opDec.getName() + details); - setLocation(requires, reqloc); - - // Add this to our list of things to confirm - myCurrentAssertiveCode.addConfirm(requires); - - // Get the ensures clause for this operation - // Note: If there isn't an ensures clause, it is set to "True" - Exp ensures, opEnsures; - if (opDec.getEnsures() != null) { - opEnsures = Exp.copy(opDec.getEnsures()); - - // Make sure we have an EqualsExp, else it is an error. - if (opEnsures instanceof EqualsExp) { - // Has to be a VarExp on the left hand side (containing the name - // of the function operation) - if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { - VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); - - // Check if it has the name of the operation - if (leftExp.getName().equals(opDec.getName())) { - ensures = ((EqualsExp) opEnsures).getRight(); - - // Obtain the current location - if (assignParamExp.getName().getLocation() != null) { - // Set the details of the current location - Location loc = - (Location) assignParamExp.getName() - .getLocation().clone(); - loc.setDetails("Ensures Clause of " - + opDec.getName()); - setLocation(ensures, loc); - } - - // Replace all instances of the variable on the left hand side - // in the ensures clause with the expression on the right. - Exp leftVariable; - - // We have a variable inside a record as the variable being assigned. - if (stmt.getVar() instanceof VariableDotExp) { - VariableDotExp v = (VariableDotExp) stmt.getVar(); - List vList = v.getSegments(); - edu.clemson.cs.r2jt.collections.List newSegments = - new edu.clemson.cs.r2jt.collections.List(); - - // Loot through each variable expression and add it to our dot list - for (VariableExp vr : vList) { - VarExp varExp = new VarExp(); - if (vr instanceof VariableNameExp) { - varExp.setName(((VariableNameExp) vr) - .getName()); - varExp.setMathType(vr.getMathType()); - varExp.setMathTypeValue(vr - .getMathTypeValue()); - newSegments.add(varExp); - } - } - - // Expression to be replaced - leftVariable = - new DotExp(v.getLocation(), newSegments, - null); - leftVariable.setMathType(v.getMathType()); - leftVariable.setMathTypeValue(v.getMathTypeValue()); - } - // We have a regular variable being assigned. - else { - // Expression to be replaced - VariableNameExp v = (VariableNameExp) stmt.getVar(); - leftVariable = - new VarExp(v.getLocation(), null, v - .getName()); - leftVariable.setMathType(v.getMathType()); - leftVariable.setMathTypeValue(v.getMathTypeValue()); - } - - // Replace all instances of the left hand side - // variable in the current final confirm statement. - Exp newConf = myCurrentAssertiveCode.getFinalConfirm(); - newConf = replace(newConf, leftVariable, ensures); - - // Replace the formals with the actuals. - newConf = - replaceFormalWithActualEns(newConf, opDec - .getParameters(), opDec.getStateVars(), - assignParamExp.getArguments(), false); - - // Set this as our new final confirm statement. - myCurrentAssertiveCode.setFinalConfirm(newConf); - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - - // Verbose Mode Debug Messages - myVCBuffer.append("\nFunction Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the if statement rule to the - * Statement.

- * - * @param stmt Our current IfStmt. - */ - private void applyEBIfStmtRule(IfStmt stmt) { - // Note: In the If Rule, we will have two instances of the assertive code. - // One for when the if condition is true and one for the else condition. - // The current global assertive code variable is going to be used for the if path, - // and we are going to create a new assertive code for the else path (this includes - // the case when there is no else clause). - ProgramExp ifCondition = stmt.getTest(); - - // Negation of If (Need to make a copy before we start modifying - // the current assertive code for the if part) - AssertiveCode negIfAssertiveCode = - new AssertiveCode(myCurrentAssertiveCode); - - // TODO: Might need to take this out when we figure out the evaluates mode business - // Call a method to locate the operation dec for this call - PosSymbol qualifier = null; - ProgramParamExp testParamExp = null; - - // Check to see what kind of expression is on the right hand side - if (ifCondition instanceof ProgramParamExp) { - // Cast to a ProgramParamExp - testParamExp = (ProgramParamExp) ifCondition; - } - else if (ifCondition instanceof ProgramDotExp) { - // Cast to a ProgramParamExp - ProgramDotExp dotExp = (ProgramDotExp) ifCondition; - testParamExp = (ProgramParamExp) dotExp.getExp(); - qualifier = dotExp.getQualifier(); - } - else { - // TODO: ERROR! - } - OperationDec opDec = - getOperationDec(ifCondition.getLocation(), qualifier, - testParamExp.getName(), testParamExp.getArguments()); - - // Confirm the invoking condition - // Get the requires clause for this operation - Exp requires; - if (opDec.getRequires() != null) { - requires = Exp.copy(opDec.getRequires()); - } - else { - requires = myTypeGraph.getTrueVarExp(); - } - - // Replace PreCondition variables in the requires clause - requires = - replaceFormalWithActualReq(requires, opDec.getParameters(), - testParamExp.getArguments()); - - // Modify the location of the requires clause and add it to myCurrentAssertiveCode - // Obtain the current location - // Note: If we don't have a location, we create one - Location reqloc; - if (testParamExp.getName().getLocation() != null) { - reqloc = (Location) testParamExp.getName().getLocation().clone(); - } - else { - reqloc = new Location(null, null); - } - - // Append the name of the current procedure - String details = " from If Statement Condition"; - - // Set the details of the current location - reqloc.setDetails("Requires Clause of " + opDec.getName() + details); - setLocation(requires, reqloc); - - // Add this to our list of things to confirm - myCurrentAssertiveCode.addConfirm(requires); - - // Add the if condition as the assume clause - // Get the ensures clause for this operation - // Note: If there isn't an ensures clause, it is set to "True" - Exp ensures, negEnsures = null, opEnsures; - if (opDec.getEnsures() != null) { - opEnsures = Exp.copy(opDec.getEnsures()); - - // Make sure we have an EqualsExp, else it is an error. - if (opEnsures instanceof EqualsExp) { - // Has to be a VarExp on the left hand side (containing the name - // of the function operation) - if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { - VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); - - // Check if it has the name of the operation - if (leftExp.getName().equals(opDec.getName())) { - ensures = ((EqualsExp) opEnsures).getRight(); - - // Obtain the current location - if (testParamExp.getName().getLocation() != null) { - // Set the details of the current location - Location loc = - (Location) testParamExp.getName() - .getLocation().clone(); - loc.setDetails("If Statement Condition"); - setLocation(ensures, loc); - } - - // Replace the formals with the actuals. - ensures = - replaceFormalWithActualEns(ensures, opDec - .getParameters(), opDec.getStateVars(), - testParamExp.getArguments(), false); - myCurrentAssertiveCode.addAssume(ensures); - - // Negation of the condition - negEnsures = negateExp(ensures); - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - - // Add any statements inside the then clause - if (stmt.getThenclause() != null) { - myCurrentAssertiveCode.addStatements(stmt.getThenclause()); - } - - // Modify the confirm details - Exp ifConfirm = myCurrentAssertiveCode.getFinalConfirm(); - String ifDetail = - " , If \"if\" condition at " - + ifCondition.getLocation().toString() + " is true"; - ifConfirm = appendToLocation(ifConfirm, ifDetail); - myCurrentAssertiveCode.setFinalConfirm(ifConfirm); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nIf Part Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - - // Add the negation of the if condition as the assume clause - if (negEnsures != null) { - negIfAssertiveCode.addAssume(negEnsures); - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - - // Add any statements inside the else clause - if (stmt.getElseclause() != null) { - negIfAssertiveCode.addStatements(stmt.getElseclause()); - } - - // Modify the confirm details - Exp negIfConfirm = negIfAssertiveCode.getFinalConfirm(); - String negIfDetail = - " , If \"if\" condition at " - + ifCondition.getLocation().toString() + " is false"; - negIfConfirm = appendToLocation(negIfConfirm, negIfDetail); - negIfAssertiveCode.setFinalConfirm(negIfConfirm); - - // Add this new assertive code to our incomplete assertive code stack - myIncAssertiveCodeStack.push(negIfAssertiveCode); - - // Verbose Mode Debug Messages - String newString = "\nNegation of If Part Rule Applied: \n"; - newString += negIfAssertiveCode.assertionToString(); - newString += "\n_____________________ \n"; - myIncAssertiveCodeStackInfo.push(newString); - } - - /** - *

Applies the swap statement rule to the - * Statement.

- * - * @param stmt Our current SwapStmt. - */ - private void applyEBSwapStmtRule(SwapStmt stmt) { - // Obtain the current final confirm clause - Exp conf = myCurrentAssertiveCode.getFinalConfirm(); - - // Create a copy of the left and right hand side - VariableExp stmtLeft = (VariableExp) Exp.copy(stmt.getLeft()); - VariableExp stmtRight = (VariableExp) Exp.copy(stmt.getRight()); - - // New left and right - Exp newLeft = convertExp(stmtLeft); - Exp newRight = convertExp(stmtRight); - - // Use our final confirm to obtain the math types - List lst = conf.getSubExpressions(); - for (int i = 0; i < lst.size(); i++) { - if (lst.get(i) instanceof VarExp) { - VarExp thisExp = (VarExp) lst.get(i); - if (newRight instanceof VarExp) { - if (thisExp.getName().equals( - ((VarExp) newRight).getName().getName())) { - newRight.setMathType(thisExp.getMathType()); - newRight.setMathTypeValue(thisExp.getMathTypeValue()); - } - } - if (newLeft instanceof VarExp) { - if (thisExp.getName().equals( - ((VarExp) newLeft).getName().getName())) { - newLeft.setMathType(thisExp.getMathType()); - newLeft.setMathTypeValue(thisExp.getMathTypeValue()); - } - } - } - } - - // Temp variable - VarExp tmp = new VarExp(); - tmp.setName(createPosSymbol("_" + getVarName(stmtLeft).getName())); - tmp.setMathType(stmtLeft.getMathType()); - tmp.setMathTypeValue(stmtLeft.getMathTypeValue()); - - // Replace according to the swap rule - conf = replace(conf, newRight, tmp); - conf = replace(conf, newLeft, newRight); - conf = replace(conf, tmp, newLeft); - - // Set this new expression as the new final confirm - myCurrentAssertiveCode.setFinalConfirm(conf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nSwap Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the while statement rule.

- * - * @param stmt Our current WhileStmt. - */ - private void applyEBWhileStmtRule(WhileStmt stmt) { - // Obtain the loop invariant - Exp invariant; - if (stmt.getMaintaining() != null) { - invariant = Exp.copy(stmt.getMaintaining()); - invariant.setMathType(stmt.getMaintaining().getMathType()); - } - else { - invariant = myTypeGraph.getTrueVarExp(); - } - - Location loc; - if (invariant.getLocation() != null) { - loc = (Location) invariant.getLocation().clone(); - } - else { - loc = (Location) stmt.getLocation().clone(); - } - loc.setDetails("Base Case of the Invariant of While Statement"); - setLocation(invariant, loc); - - // Confirm the invariant - myCurrentAssertiveCode.addConfirm(invariant); - - // Add the change rule - if (stmt.getChanging() != null) { - myCurrentAssertiveCode.addChange(stmt.getChanging()); - } - - // Assume the invariant and NQV(RP, P_Val) = P_Exp - Location whileLoc = stmt.getLocation(); - Exp assume; - Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); - Exp decreasingExp = stmt.getDecreasing(); - Exp nqv; - - if (decreasingExp != null) { - VarExp pval = createPValExp((Location) whileLoc.clone()); - nqv = createQuestionMarkVariable(finalConfirm, pval); - nqv.setMathType(pval.getMathType()); - Exp equalPExp = - new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv), - 1, Exp.copy(decreasingExp)); - equalPExp.setMathType(BOOLEAN); - assume = myTypeGraph.formConjunct(Exp.copy(invariant), equalPExp); - } - else { - decreasingExp = myTypeGraph.getTrueVarExp(); - nqv = myTypeGraph.getTrueVarExp(); - assume = Exp.copy(invariant); - } - - myCurrentAssertiveCode.addAssume(assume); - - // Create an if statement from the loop - Exp ifConfirm; - if (decreasingExp != null) { - Location decreasingLoc = - (Location) decreasingExp.getLocation().clone(); - if (decreasingLoc != null) { - decreasingLoc.setDetails("Termination of While Statement"); - } - - Exp maintainingInv = Exp.copy(invariant); - Location maintainingLoc = - (Location) invariant.getLocation().clone(); - if (maintainingLoc != null) { - maintainingLoc - .setDetails("Inductive Case of Invariant of While Statement"); - maintainingInv.setLocation(maintainingLoc); - } - - Exp infixExp = - new InfixExp(decreasingLoc, Exp.copy(decreasingExp), - createPosSymbol("<"), Exp.copy(nqv)); - infixExp.setMathType(BOOLEAN); - ifConfirm = myTypeGraph.formConjunct(maintainingInv, infixExp); - } - else { - ifConfirm = myTypeGraph.getTrueVarExp(); - } - - // if statement body - Location ifConfirmLoc = (Location) whileLoc.clone(); - edu.clemson.cs.r2jt.collections.List ifStmtList = - stmt.getStatements(); - ifStmtList.add(new ConfirmStmt(ifConfirmLoc, ifConfirm)); - - // empty elseif pair - edu.clemson.cs.r2jt.collections.List elseIfPairList = - new edu.clemson.cs.r2jt.collections.List(); - - // else body - Location elseConfirmLoc; - if (finalConfirm.getLocation() != null) { - elseConfirmLoc = (Location) finalConfirm.getLocation().clone(); - } - else { - elseConfirmLoc = (Location) whileLoc.clone(); - } - edu.clemson.cs.r2jt.collections.List elseStmtList = - new edu.clemson.cs.r2jt.collections.List(); - elseStmtList - .add(new ConfirmStmt(elseConfirmLoc, Exp.copy(finalConfirm))); - - // condition - ProgramExp condition = (ProgramExp) Exp.copy(stmt.getTest()); - if (condition.getLocation() != null) { - Location condLoc = (Location) condition.getLocation().clone(); - condLoc.setDetails("While Loop Condition"); - setLocation(condition, condLoc); - } - - // add it back to your assertive code - IfStmt newIfStmt = - new IfStmt(condition, ifStmtList, elseIfPairList, elseStmtList); - myCurrentAssertiveCode.addCode(newIfStmt); - - // Change our final confirm to "True" - Exp trueVarExp = myTypeGraph.getTrueVarExp(); - trueVarExp.setLocation((Location) whileLoc.clone()); - myCurrentAssertiveCode.setFinalConfirm(trueVarExp); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nWhile Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the procedure declaration rule.

- * - * @param requires Requires clause - * @param ensures Ensures clause - * @param decreasing Decreasing clause (if any) - * @param variableList List of all variables for this procedure - * @param statementList List of statements for this procedure - */ - private void applyProcedureDeclRule(Exp requires, Exp ensures, - Exp decreasing, List variableList, - List statementList) { - // Add the global requires clause - if (myGlobalRequiresExp != null) { - myCurrentAssertiveCode.addAssume(myGlobalRequiresExp); - } - - // Add the global constraints - if (myGlobalConstraintExp != null) { - myCurrentAssertiveCode.addAssume(myGlobalConstraintExp); - } - - // Add the requires clause - if (requires != null) { - myCurrentAssertiveCode.addAssume(requires); - } - - // Add the remember rule - myCurrentAssertiveCode.addRemember(); - - // Add declared variables into the assertion. Also add - // them to the list of free variables. - myCurrentAssertiveCode.addVariableDecs(variableList); - addVarDecsAsFreeVars(variableList); - - // Check to see if we have a recursive procedure. - // If yes, we will need to create an additional assume clause - // (P_val = (decreasing clause)) in our list of assertions. - if (decreasing != null) { - // Store for future use - myOperationDecreasingExp = decreasing; - - // Add P_val as a free variable - VarExp pVal = createPValExp(decreasing.getLocation()); - myCurrentAssertiveCode.addFreeVar(pVal); - - // Create an equals expression - EqualsExp equalsExp = - new EqualsExp(null, pVal, EqualsExp.EQUAL, Exp - .copy(decreasing)); - equalsExp.setMathType(BOOLEAN); - Location eqLoc = (Location) decreasing.getLocation().clone(); - eqLoc.setDetails("Progress Metric for Recursive Procedure"); - setLocation(equalsExp, eqLoc); - - // Add it to our things to assume - myCurrentAssertiveCode.addAssume(equalsExp); - } - - // Add the list of statements - myCurrentAssertiveCode.addStatements(statementList); - - // Add the final confirms clause - myCurrentAssertiveCode.setFinalConfirm(ensures); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nProcedure Declaration Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the remember rule.

- */ - private void applyRememberRule() { - // Obtain the final confirm and apply the remember method for Exp - Exp conf = myCurrentAssertiveCode.getFinalConfirm(); - conf = conf.remember(); - myCurrentAssertiveCode.setFinalConfirm(conf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nRemember Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the variable declaration rule.

- * - * @param var A declared variable stored as a - * VerificationStatement - */ - private void applyVarDeclRule(VerificationStatement var) { - // Obtain the variable from the verification statement - VarDec varDec = (VarDec) var.getAssertion(); - ProgramTypeEntry typeEntry; - - // Ty is NameTy - if (varDec.getTy() instanceof NameTy) { - NameTy pNameTy = (NameTy) varDec.getTy(); - - // Query for the type entry in the symbol table - typeEntry = - searchProgramType(pNameTy.getLocation(), pNameTy.getName()); - - // Make sure we don't have a generic type - if (typeEntry.getDefiningElement() instanceof TypeDec) { - // Obtain the original dec from the AST - TypeDec type = (TypeDec) typeEntry.getDefiningElement(); - - // Deep copy the original initialization ensures - Exp init = Exp.copy(type.getInitialization().getEnsures()); - - // Make sure we have a constraint - Exp constraint; - if (type.getConstraint() == null) { - constraint = myTypeGraph.getTrueVarExp(); - } - else { - constraint = Exp.copy(type.getConstraint()); - } - - // Set the location for the constraint - Location loc; - if (constraint.getLocation() != null) { - loc = (Location) constraint.getLocation().clone(); - } - else { - loc = (Location) type.getLocation().clone(); - } - loc.setDetails("Constraints on " + varDec.getName().getName()); - setLocation(constraint, loc); - - // Final confirm clause - Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); - - // Check if our initialization ensures clause is - // in simple form. - if (isInitEnsuresSimpleForm(init)) { - // Only deal with initialization ensures of the - // form left = right - if (init instanceof EqualsExp) { - EqualsExp exp = (EqualsExp) init; - VarExp varDecExp = - createVarExp(varDec.getLocation(), varDec - .getName(), typeEntry.getModelType()); - - // Replace all instances of this variable with initialization - // ensures clause of the variable type. - finalConfirm = - replace(finalConfirm, varDecExp, exp.getRight()); - - // Set that as our new final confirm - myCurrentAssertiveCode.setFinalConfirm(finalConfirm); - } - } - // We must have a complex initialization ensures clause - else { - // The variable must be a variable dot expression, - // therefore we will need to extract the name. - String varName = varDec.getName().getName(); - int dotIndex = varName.indexOf("."); - if (dotIndex > 0) - varName = varName.substring(0, dotIndex); - - // Check if our confirm clause uses this variable - if (finalConfirm.containsVar(varName, false)) { - // We don't have any constraints, so the initialization - // clause implies the final confirm statement and - // set this as our new final confirm statement. - if (constraint.equals(myTypeGraph.getTrueVarExp())) { - myCurrentAssertiveCode.setFinalConfirm(myTypeGraph - .formImplies(init, finalConfirm)); - } - // We actually have a constraint, so both the initialization - // and constraint imply the final confirm statement. - // This then becomes our new final confirm statement. - else { - InfixExp exp = - myTypeGraph.formConjunct(constraint, init); - myCurrentAssertiveCode.setFinalConfirm(myTypeGraph - .formImplies(exp, finalConfirm)); - } - } - } - } - // Since the type is generic, we can only use the is_initial predicate - // to ensure that the value is initial value. - else { - // Obtain the original dec from the AST - Location varLoc = varDec.getLocation(); - - // Create an is_initial dot expression - DotExp isInitialExp = createInitExp(varDec); - if (varLoc != null) { - Location loc = (Location) varLoc.clone(); - loc.setDetails("Initial Value for " - + varDec.getName().getName()); - setLocation(isInitialExp, loc); - } - - // Add to our assertive code as an assume - myCurrentAssertiveCode.addAssume(isInitialExp); - } - - // Verbose Mode Debug Messages - myVCBuffer.append("\nVariable Declaration Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - else { - // Ty not handled. - tyNotHandled(varDec.getTy(), varDec.getLocation()); - } - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/old/VCGenerator.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/old/VCGenerator.java deleted file mode 100755 index baf3f94..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/old/VCGenerator.java +++ /dev/null @@ -1,3357 +0,0 @@ -/** - * VCGenerator.java - * --------------------------------- - * Copyright (c) 2014 - * RESOLVE Software Research Group - * School of Computing - * Clemson University - * All rights reserved. - * --------------------------------- - * This file is subject to the terms and conditions defined in - * file 'LICENSE.txt', which is part of this source code package. - */ -package edu.clemson.cs.r2jt.vcgeneration; - -/* - * Libraries - */ -import edu.clemson.cs.r2jt.ResolveCompiler; -import edu.clemson.cs.r2jt.absyn.*; -import edu.clemson.cs.r2jt.data.*; -import edu.clemson.cs.r2jt.init.CompileEnvironment; -import edu.clemson.cs.r2jt.proving2.VC; -import edu.clemson.cs.r2jt.treewalk.TreeWalkerVisitor; -import edu.clemson.cs.r2jt.typeandpopulate.*; -import edu.clemson.cs.r2jt.typeandpopulate.entry.*; -import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.FacilityStrategy; -import edu.clemson.cs.r2jt.typeandpopulate.MathSymbolTable.ImportStrategy; -import edu.clemson.cs.r2jt.typeandpopulate.programtypes.PTType; -import edu.clemson.cs.r2jt.typeandpopulate.query.NameQuery; -import edu.clemson.cs.r2jt.typeandpopulate.query.OperationQuery; -import edu.clemson.cs.r2jt.typeandpopulate.query.UnqualifiedNameQuery; -import edu.clemson.cs.r2jt.typereasoning.TypeGraph; -import edu.clemson.cs.r2jt.utilities.Flag; -import edu.clemson.cs.r2jt.utilities.FlagDependencies; -import edu.clemson.cs.r2jt.utilities.SourceErrorException; - -import java.io.File; -import java.util.*; -import java.util.List; - -/** - * TODO: Write a description of this module - */ -public class VCGenerator extends TreeWalkerVisitor { - - // =========================================================== - // Global Variables - // =========================================================== - - // Symbol table related items - private final MathSymbolTableBuilder mySymbolTable; - private final TypeGraph myTypeGraph; - private final MTType BOOLEAN; - private final MTType MTYPE; - private final MTType Z; - private ModuleScope myCurrentModuleScope; - - // Module level global variables - private Exp myGlobalRequiresExp; - private Exp myGlobalConstraintExp; - - // Operation/Procedure level global variables - private OperationEntry myCurrentOperationEntry; - private Exp myOperationDecreasingExp; - - /** - *

The current assertion we are applying - * VC rules to.

- */ - private AssertiveCode myCurrentAssertiveCode; - - /** - *

The current compile environment used throughout - * the compiler.

- */ - private CompileEnvironment myInstanceEnvironment; - - /** - *

A list that will be built up with AssertiveCode - * objects, each representing a VC or group of VCs that must be - * satisfied to verify a parsed program.

- */ - private Collection myFinalAssertiveCodeList; - - /** - *

This object creates the different VC outputs.

- */ - private OutputVCs myOutputGenerator; - - /** - *

A stack that is used to keep track of the AssertiveCode - * that we still need to apply proof rules to.

- */ - private Stack myIncAssertiveCodeStack; - - /** - *

A stack that is used to keep track of the information that we - * haven't printed for the AssertiveCode - * that we still need to apply proof rules to.

- */ - private Stack myIncAssertiveCodeStackInfo; - - /** - *

This string buffer holds all the steps - * the VC generator takes to generate VCs.

- */ - private StringBuffer myVCBuffer; - - // =========================================================== - // Flag Strings - // =========================================================== - - private static final String FLAG_ALTSECTION_NAME = "GenerateVCs"; - private static final String FLAG_DESC_ATLVERIFY_VC = "Generate VCs."; - private static final String FLAG_DESC_ATTLISTVCS_VC = ""; - - // =========================================================== - // Flags - // =========================================================== - - public static final Flag FLAG_ALTVERIFY_VC = - new Flag(FLAG_ALTSECTION_NAME, "altVCs", FLAG_DESC_ATLVERIFY_VC); - - public static final Flag FLAG_ALTLISTVCS_VC = - new Flag(FLAG_ALTSECTION_NAME, "altListVCs", - FLAG_DESC_ATTLISTVCS_VC, Flag.Type.HIDDEN); - - public static final void setUpFlags() { - FlagDependencies.addImplies(FLAG_ALTVERIFY_VC, FLAG_ALTLISTVCS_VC); - } - - // =========================================================== - // Constructors - // =========================================================== - - public VCGenerator(ScopeRepository table, final CompileEnvironment env) { - // Symbol table items - mySymbolTable = (MathSymbolTableBuilder) table; - myTypeGraph = mySymbolTable.getTypeGraph(); - BOOLEAN = myTypeGraph.BOOLEAN; - MTYPE = myTypeGraph.MTYPE; - Z = myTypeGraph.Z; - - // Current items - myCurrentModuleScope = null; - myCurrentOperationEntry = null; - myGlobalConstraintExp = null; - myGlobalRequiresExp = null; - myOperationDecreasingExp = null; - - // Instance Environment - myInstanceEnvironment = env; - - // VCs + Debugging String - myCurrentAssertiveCode = null; - myFinalAssertiveCodeList = new LinkedList(); - myOutputGenerator = null; - myIncAssertiveCodeStack = new Stack(); - myIncAssertiveCodeStackInfo = new Stack(); - myVCBuffer = new StringBuffer(); - } - - // =========================================================== - // Visitor Methods - // =========================================================== - - // ----------------------------------------------------------- - // ConceptBodyModuleDec - // ----------------------------------------------------------- - - @Override - public void preConceptBodyModuleDec(ConceptBodyModuleDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" VC Generation Details "); - myVCBuffer.append(" =========================\n"); - myVCBuffer.append("\n Concept Realization Name:\t"); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append("\n Concept Name:\t"); - myVCBuffer.append(dec.getConceptName().getName()); - myVCBuffer.append("\n"); - myVCBuffer.append("\n===================================="); - myVCBuffer.append("======================================\n"); - myVCBuffer.append("\n"); - - // Set the current module scope - try { - myCurrentModuleScope = - mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); - - // From the list of imports, obtain the global constraints - // of the imported modules. - myGlobalConstraintExp = - getConstraints(dec.getLocation(), myCurrentModuleScope - .getImports()); - - // Store the global requires clause - myGlobalRequiresExp = getRequiresClause(dec); - } - catch (NoSuchSymbolException e) { - System.err.println("Module " + dec.getName() - + " does not exist or is not in scope."); - noSuchModule(dec.getLocation()); - } - } - - @Override - public void postConceptBodyModuleDec(ConceptBodyModuleDec dec) { - // Set the module level global variables to null - myCurrentModuleScope = null; - myGlobalConstraintExp = null; - myGlobalRequiresExp = null; - } - - // ----------------------------------------------------------- - // EnhancementBodyModuleDec - // ----------------------------------------------------------- - - @Override - public void preEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" VC Generation Details "); - myVCBuffer.append(" =========================\n"); - myVCBuffer.append("\n Enhancement Realization Name:\t"); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append("\n Enhancement Name:\t"); - myVCBuffer.append(dec.getEnhancementName().getName()); - myVCBuffer.append("\n Concept Name:\t"); - myVCBuffer.append(dec.getConceptName().getName()); - myVCBuffer.append("\n"); - myVCBuffer.append("\n===================================="); - myVCBuffer.append("======================================\n"); - myVCBuffer.append("\n"); - - // Set the current module scope - try { - myCurrentModuleScope = - mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); - - // From the list of imports, obtain the global constraints - // of the imported modules. - myGlobalConstraintExp = - getConstraints(dec.getLocation(), myCurrentModuleScope - .getImports()); - - // Store the global requires clause - myGlobalRequiresExp = getRequiresClause(dec); - } - catch (NoSuchSymbolException e) { - System.err.println("Module " + dec.getName() - + " does not exist or is not in scope."); - noSuchModule(dec.getLocation()); - } - } - - @Override - public void postEnhancementBodyModuleDec(EnhancementBodyModuleDec dec) { - // Set the module level global variables to null - myCurrentModuleScope = null; - myGlobalConstraintExp = null; - myGlobalRequiresExp = null; - } - - // ----------------------------------------------------------- - // FacilityModuleDec - // ----------------------------------------------------------- - - @Override - public void preFacilityModuleDec(FacilityModuleDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" VC Generation Details "); - myVCBuffer.append(" =========================\n"); - myVCBuffer.append("\n Facility Name:\t"); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append("\n"); - myVCBuffer.append("\n===================================="); - myVCBuffer.append("======================================\n"); - myVCBuffer.append("\n"); - - // Set the current module scope - try { - myCurrentModuleScope = - mySymbolTable.getModuleScope(new ModuleIdentifier(dec)); - - // From the list of imports, obtain the global constraints - // of the imported modules. - myGlobalConstraintExp = - getConstraints(dec.getLocation(), myCurrentModuleScope - .getImports()); - - // Store the global requires clause - myGlobalRequiresExp = getRequiresClause(dec); - } - catch (NoSuchSymbolException e) { - System.err.println("Module " + dec.getName() - + " does not exist or is not in scope."); - noSuchModule(dec.getLocation()); - } - } - - @Override - public void postFacilityModuleDec(FacilityModuleDec dec) { - // Set the module level global variables to null - myCurrentModuleScope = null; - myGlobalConstraintExp = null; - myGlobalRequiresExp = null; - } - - // ----------------------------------------------------------- - // FacilityOperationDec - // ----------------------------------------------------------- - - @Override - public void preFacilityOperationDec(FacilityOperationDec dec) { - // Keep the current operation dec - List argTypes = new LinkedList(); - for (ParameterVarDec p : dec.getParameters()) { - argTypes.add(p.getTy().getProgramTypeValue()); - } - myCurrentOperationEntry = - searchOperation(dec.getLocation(), null, dec.getName(), - argTypes); - } - - @Override - public void postFacilityOperationDec(FacilityOperationDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" Procedure: "); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append(" =========================\n"); - - // The current assertive code - int curAssertiveCodeNum = 1; - myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment); - - // Obtains items from the current operation - Location loc = dec.getLocation(); - String name = dec.getName().getName(); - Exp requires = modifyRequiresClause(getRequiresClause(dec), loc, name); - Exp ensures = modifyEnsuresClause(getEnsuresClause(dec), loc, name); - List statementList = dec.getStatements(); - List variableList = dec.getAllVariables(); - Exp decreasing = dec.getDecreasing(); - - // Apply the procedure declaration rule - applyProcedureDeclRule(requires, ensures, decreasing, variableList, - statementList); - - // Add this to our stack of to be processed assertive codes. - myIncAssertiveCodeStack.push(myCurrentAssertiveCode); - myIncAssertiveCodeStackInfo.push(""); - - // Set the current assertive code to null - // YS: (We the modify requires and ensures clause needs to have - // and current assertive code to work. Not very clean way to - // solve the problem, but should work.) - myCurrentAssertiveCode = null; - - // Loop until our to process assertive code stack is empty - while (!myIncAssertiveCodeStack.empty()) { - // Set the incoming assertive code as our current assertive - // code we are working on. - myCurrentAssertiveCode = myIncAssertiveCodeStack.pop(); - - myVCBuffer.append("\n***********************"); - myVCBuffer.append(" Begin Path: "); - myVCBuffer.append(curAssertiveCodeNum); - myVCBuffer.append(" ***********************\n"); - - // Append any information that still needs to be added to our - // Debug VC Buffer - myVCBuffer.append(myIncAssertiveCodeStackInfo.pop()); - - // Apply proof rules - applyEBRules(); - - myVCBuffer.append("\n***********************"); - myVCBuffer.append(" End Path: "); - myVCBuffer.append(curAssertiveCodeNum); - myVCBuffer.append(" ***********************\n"); - curAssertiveCodeNum++; - - // Add it to our list of final assertive codes - myFinalAssertiveCodeList.add(myCurrentAssertiveCode); - - // Set the current assertive code to null - myCurrentAssertiveCode = null; - } - - myOperationDecreasingExp = null; - myCurrentOperationEntry = null; - } - - // ----------------------------------------------------------- - // ModuleDec - // ----------------------------------------------------------- - - @Override - public void postModuleDec(ModuleDec dec) { - // Create the output generator and finalize output - myOutputGenerator = - new OutputVCs(myInstanceEnvironment, myFinalAssertiveCodeList, - myVCBuffer); - - // Check if it is generating VCs for WebIDE or not. - if (myInstanceEnvironment.flags.isFlagSet(ResolveCompiler.FLAG_XML_OUT)) { - myOutputGenerator.outputToJSON(); - } - else { - // Print to file if we are in debug mode - // TODO: Add debug flag here - String filename; - if (myInstanceEnvironment.getOutputFilename() != null) { - filename = myInstanceEnvironment.getOutputFilename(); - } - else { - filename = createVCFileName(); - } - myOutputGenerator.outputToFile(filename); - } - } - - // ----------------------------------------------------------- - // ProcedureDec - // ----------------------------------------------------------- - - @Override - public void preProcedureDec(ProcedureDec dec) { - // Keep the current operation dec - List argTypes = new LinkedList(); - for (ParameterVarDec p : dec.getParameters()) { - argTypes.add(p.getTy().getProgramTypeValue()); - } - myCurrentOperationEntry = - searchOperation(dec.getLocation(), null, dec.getName(), - argTypes); - } - - @Override - public void postProcedureDec(ProcedureDec dec) { - // Verbose Mode Debug Messages - myVCBuffer.append("\n========================="); - myVCBuffer.append(" Procedure: "); - myVCBuffer.append(dec.getName().getName()); - myVCBuffer.append(" =========================\n"); - - // The current assertive code - int curAssertiveCodeNum = 1; - myCurrentAssertiveCode = new AssertiveCode(myInstanceEnvironment); - - // Obtains items from the current operation - Location loc = dec.getLocation(); - String name = dec.getName().getName(); - Exp requires = modifyRequiresClause(getRequiresClause(dec), loc, name); - Exp ensures = modifyEnsuresClause(getEnsuresClause(dec), loc, name); - List statementList = dec.getStatements(); - List variableList = dec.getAllVariables(); - Exp decreasing = dec.getDecreasing(); - - // Apply the procedure declaration rule - applyProcedureDeclRule(requires, ensures, decreasing, variableList, - statementList); - - // Add this to our stack of to be processed assertive codes. - myIncAssertiveCodeStack.push(myCurrentAssertiveCode); - myIncAssertiveCodeStackInfo.push(""); - - // Set the current assertive code to null - // YS: (We the modify requires and ensures clause needs to have - // and current assertive code to work. Not very clean way to - // solve the problem, but should work.) - myCurrentAssertiveCode = null; - - // Loop until our to process assertive code stack is empty - while (!myIncAssertiveCodeStack.empty()) { - // Set the incoming assertive code as our current assertive - // code we are working on. - myCurrentAssertiveCode = myIncAssertiveCodeStack.pop(); - - myVCBuffer.append("\n***********************"); - myVCBuffer.append(" Begin Path: "); - myVCBuffer.append(curAssertiveCodeNum); - myVCBuffer.append(" ***********************\n"); - - // Append any information that still needs to be added to our - // Debug VC Buffer - myVCBuffer.append(myIncAssertiveCodeStackInfo.pop()); - - // Apply proof rules - applyEBRules(); - - myVCBuffer.append("\n***********************"); - myVCBuffer.append(" End Path: "); - myVCBuffer.append(curAssertiveCodeNum); - myVCBuffer.append(" ***********************\n"); - curAssertiveCodeNum++; - - // Add it to our list of final assertive codes - myFinalAssertiveCodeList.add(myCurrentAssertiveCode); - - // Set the current assertive code to null - myCurrentAssertiveCode = null; - } - - myOperationDecreasingExp = null; - myCurrentOperationEntry = null; - } - - // =========================================================== - // Public Methods - // =========================================================== - - // ----------------------------------------------------------- - // Error Handling - // ----------------------------------------------------------- - - public void expNotHandled(Exp exp, Location l) { - String message = "Exp not handled: " + exp.toString(); - throw new SourceErrorException(message, l); - } - - public void illegalOperationEnsures(Location l) { - // TODO: Move this to sanity check. - String message = - "Ensures clauses of operations that return a value should be of the form = "; - throw new SourceErrorException(message, l); - } - - public void notAType(SymbolTableEntry entry, Location l) { - throw new SourceErrorException(entry.getSourceModuleIdentifier() - .fullyQualifiedRepresentation(entry.getName()) - + " is not known to be a type.", l); - } - - public void notInFreeVarList(PosSymbol name, Location l) { - String message = - "State variable " + name + " not in free variable list"; - throw new SourceErrorException(message, l); - } - - public void noSuchModule(Location location) { - throw new SourceErrorException( - "Module does not exist or is not in scope.", location); - } - - public void noSuchSymbol(PosSymbol qualifier, String symbolName, Location l) { - - String message; - - if (qualifier == null) { - message = "No such symbol: " + symbolName; - } - else { - message = - "No such symbol in module: " + qualifier.getName() + "." - + symbolName; - } - - throw new SourceErrorException(message, l); - } - - public void tyNotHandled(Ty ty, Location location) { - String message = "Ty not handled: " + ty.toString(); - throw new SourceErrorException(message, location); - } - - // ----------------------------------------------------------- - // Prover Mode - // ----------------------------------------------------------- - - /** - *

The set of immmutable VCs that the in house provers can use.

- * - * @return VCs to be proved. - */ - public List proverOutput() { - return myOutputGenerator.getProverOutput(); - } - - // =========================================================== - // Private Methods - // =========================================================== - - /** - *

Loop through the list of VarDec, search - * for their corresponding ProgramVariableEntry - * and add the result to the list of free variables.

- * - * @param variableList List of the all variables as - * VarDec. - */ - public void addVarDecsAsFreeVars(List variableList) { - // Loop through the variable list - for (VarDec v : variableList) { - myCurrentAssertiveCode.addFreeVar(createVarExp(v.getLocation(), v - .getName(), v.getTy().getMathTypeValue())); - } - } - - /** - *

Append VC Generator step details to the expression's - * location.

- * - * @param exp The current expression we are dealing with. - * @param text VC Generator step details. - * - * @return The modified expression. - */ - private Exp appendToLocation(Exp exp, String text) { - // Check if the expression is empty or not - // and it must have a valid location. - if (exp != null && exp.getLocation() != null) { - // Recursively apply to infix expressions. - if (exp instanceof InfixExp) { - appendToLocation(((InfixExp) exp).getLeft(), text); - appendToLocation(((InfixExp) exp).getRight(), text); - } - else { - Location loc = exp.getLocation(); - if (loc.getDetails() == null) { - loc.setDetails(text); - } - else { - String details = loc.getDetails().concat(text); - loc.setDetails(details); - } - } - } - - return exp; - } - - /** - *

Converts the different types of Exp to the - * ones used by the VC Generator.

- * - * @param oldExp The expression to be converted. - * - * @return An Exp. - */ - private Exp convertExp(Exp oldExp) { - // Case #1: ProgramIntegerExp - if (oldExp instanceof ProgramIntegerExp) { - IntegerExp exp = new IntegerExp(); - exp.setValue(((ProgramIntegerExp) oldExp).getValue()); - exp.setMathType(Z); - return exp; - } - // Case #2: VariableDotExp - else if (oldExp instanceof VariableDotExp) { - DotExp exp = new DotExp(); - List segments = - ((VariableDotExp) oldExp).getSegments(); - edu.clemson.cs.r2jt.collections.List newSegments = - new edu.clemson.cs.r2jt.collections.List(); - - // Need to replace each of the segments in a dot expression - MTType lastMathType = null; - MTType lastMathTypeValue = null; - for (VariableExp v : segments) { - VarExp varExp = new VarExp(); - - // Can only be a VariableNameExp. Anything else - // is a case we have not handled. - if (v instanceof VariableNameExp) { - varExp.setName(((VariableNameExp) v).getName()); - lastMathType = v.getMathType(); - lastMathTypeValue = v.getMathTypeValue(); - newSegments.add(varExp); - } - else { - expNotHandled(v, v.getLocation()); - } - } - - // Set the segments and the type information. - exp.setSegments(newSegments); - exp.setMathType(lastMathType); - exp.setMathTypeValue(lastMathTypeValue); - return exp; - } - // Case #3: VariableNameExp - else if (oldExp instanceof VariableNameExp) { - VarExp exp = new VarExp(); - exp.setName(((VariableNameExp) oldExp).getName()); - exp.setMathType(oldExp.getMathType()); - exp.setMathTypeValue(oldExp.getMathTypeValue()); - return exp; - } - - return oldExp; - } - - /** - *

Returns a newly created PosSymbol - * with the string provided.

- * - * @param name String of the new PosSymbol. - * - * @return The new PosSymbol. - */ - private PosSymbol createPosSymbol(String name) { - // Create the PosSymbol - PosSymbol posSym = new PosSymbol(); - posSym.setSymbol(Symbol.symbol(name)); - return posSym; - } - - /** - *

Returns an DotExp with the VarDec - * and its initialization ensures clause.

- * - * @param var The declared variable. - * - * @return The new DotExp. - */ - private DotExp createInitExp(VarDec var) { - // Convert the declared variable into a VarExp - VarExp varExp = - createVarExp(var.getLocation(), var.getName(), var.getTy() - .getMathTypeValue()); - - // Left hand side of the expression - VarExp left = null; - - // NameTy - if (var.getTy() instanceof NameTy) { - NameTy ty = (NameTy) var.getTy(); - left = createVarExp(ty.getLocation(), ty.getName(), MTYPE); - } - else { - tyNotHandled(var.getTy(), var.getTy().getLocation()); - } - - // Complicated steps to construct the argument list - // YS: No idea why it is so complicated! - edu.clemson.cs.r2jt.collections.List expList = - new edu.clemson.cs.r2jt.collections.List(); - expList.add(varExp); - FunctionArgList argList = new FunctionArgList(); - argList.setArguments(expList); - edu.clemson.cs.r2jt.collections.List functionArgLists = - new edu.clemson.cs.r2jt.collections.List(); - functionArgLists.add(argList); - - // Right hand side of the expression - FunctionExp right = - new FunctionExp(var.getLocation(), null, - createPosSymbol("Is_Initial"), null, functionArgLists); - right.setMathType(BOOLEAN); - - // Create the DotExp - edu.clemson.cs.r2jt.collections.List exps = - new edu.clemson.cs.r2jt.collections.List(); - exps.add(left); - exps.add(right); - DotExp exp = new DotExp(var.getLocation(), exps, null); - exp.setMathType(BOOLEAN); - - return exp; - } - - /** - *

Creates a variable expression with the name - * "P_val" and has type "N".

- * - * @param location Location that wants to create - * this variable. - * - * @return The created VarExp. - */ - private VarExp createPValExp(Location location) { - // Locate "N" (Natural Number) - MathSymbolEntry mse = searchMathSymbol(location, "N"); - try { - // Create a variable with the name P_val - return createVarExp(location, createPosSymbol("P_val"), mse - .getTypeValue()); - } - catch (SymbolNotOfKindTypeException e) { - notAType(mse, location); - } - - return null; - } - - /** - *

Create a question mark variable with the oldVar - * passed in.

- * - * @param exp The full expression clause. - * @param oldVar The old variable expression. - * - * @return A new variable with the question mark in VarExp form. - */ - private VarExp createQuestionMarkVariable(Exp exp, VarExp oldVar) { - // Add an extra question mark to the front of oldVar - VarExp newOldVar = - new VarExp(null, null, createPosSymbol("?" - + oldVar.getName().getName())); - newOldVar.setMathType(oldVar.getMathType()); - newOldVar.setMathTypeValue(oldVar.getMathTypeValue()); - - // Applies the question mark to oldVar if it is our first time visiting. - if (exp.containsVar(oldVar.getName().getName(), false)) { - return createQuestionMarkVariable(exp, newOldVar); - } - // Don't need to apply the question mark here. - else if (exp.containsVar(newOldVar.getName().toString(), false)) { - return createQuestionMarkVariable(exp, newOldVar); - } - else { - // Return the new variable expression with the question mark - if (oldVar.getName().getName().charAt(0) != '?') { - return newOldVar; - } - } - - // Return our old self. - return oldVar; - } - - /** - *

Returns a newly created VarExp - * with the PosSymbol and math type provided.

- * - * @param loc Location of the new VarExp - * @param name PosSymbol of the new VarExp. - * @param type Math type of the new VarExp. - * - * @return The new VarExp. - */ - private VarExp createVarExp(Location loc, PosSymbol name, MTType type) { - // Create the VarExp - VarExp exp = new VarExp(loc, null, name); - exp.setMathType(type); - return exp; - } - - /** - *

Creates the name of the output file.

- * - * @return Name of the file - */ - private String createVCFileName() { - File file = myInstanceEnvironment.getTargetFile(); - ModuleID cid = myInstanceEnvironment.getModuleID(file); - file = myInstanceEnvironment.getFile(cid); - String filename = file.toString(); - int temp = filename.indexOf("."); - String tempfile = filename.substring(0, temp); - String mainFileName; - - mainFileName = tempfile + ".asrt_new"; - - return mainFileName; - } - - /** - *

Returns all the constraint clauses combined together for the - * for the current ModuleDec.

- * - * @param loc The location of the ModuleDec. - * @param imports The list of imported modules. - * - * @return The constraint clause Exp. - */ - private Exp getConstraints(Location loc, List imports) { - Exp retExp = null; - - // Loop - for (ModuleIdentifier mi : imports) { - try { - ModuleDec dec = - mySymbolTable.getModuleScope(mi).getDefiningElement(); - List contraintExpList = null; - - // Handling for facility imports - if (dec instanceof ShortFacilityModuleDec) { - FacilityDec facDec = - ((ShortFacilityModuleDec) dec).getDec(); - dec = - mySymbolTable.getModuleScope( - new ModuleIdentifier(facDec - .getConceptName().getName())) - .getDefiningElement(); - } - - if (dec instanceof ConceptModuleDec) { - contraintExpList = - ((ConceptModuleDec) dec).getConstraints(); - - // Copy all the constraints - for (Exp e : contraintExpList) { - // Deep copy and set the location detail - Exp constraint = Exp.copy(e); - if (constraint.getLocation() != null) { - Location theLoc = constraint.getLocation(); - theLoc.setDetails("Constraint of Module: " - + dec.getName()); - setLocation(constraint, theLoc); - } - - // Form conjunct if needed. - if (retExp == null) { - retExp = Exp.copy(e); - } - else { - retExp = - myTypeGraph.formConjunct(retExp, Exp - .copy(e)); - } - } - } - } - catch (NoSuchSymbolException e) { - System.err.println("Module " + mi.toString() - + " does not exist or is not in scope."); - noSuchModule(loc); - } - } - - return retExp; - } - - /** - *

Returns the ensures clause for the current Dec.

- * - * @param dec The corresponding Dec. - * - * @return The ensures clause Exp. - */ - private Exp getEnsuresClause(Dec dec) { - PosSymbol name = dec.getName(); - Exp ensures = null; - Exp retExp = null; - - // Check for each kind of ModuleDec possible - if (dec instanceof FacilityOperationDec) { - ensures = ((FacilityOperationDec) dec).getEnsures(); - } - else if (dec instanceof OperationDec) { - ensures = ((OperationDec) dec).getEnsures(); - } - - // Deep copy and fill in the details of this location - if (ensures != null) { - retExp = Exp.copy(ensures); - if (retExp.getLocation() != null) { - Location myLoc = retExp.getLocation(); - myLoc.setDetails("Ensures Clause of " + name); - setLocation(retExp, myLoc); - } - } - - return retExp; - } - - /** - *

Locate and return the corresponding operation dec based on the qualifier, - * name, and arguments.

- * - * @param loc Location of the calling statement. - * @param qual Qualifier of the operation - * @param name Name of the operation. - * @param args List of arguments for the operation. - * - * @return The operation corresponding to the calling statement in OperationDec form. - */ - private OperationDec getOperationDec(Location loc, PosSymbol qual, - PosSymbol name, List args) { - // Obtain the corresponding OperationEntry and OperationDec - List argTypes = new LinkedList(); - for (ProgramExp arg : args) { - argTypes.add(arg.getProgramType()); - } - OperationEntry opEntry = searchOperation(loc, qual, name, argTypes); - - // Obtain an OperationDec from the OperationEntry - ResolveConceptualElement element = opEntry.getDefiningElement(); - OperationDec opDec; - if (element instanceof OperationDec) { - opDec = (OperationDec) opEntry.getDefiningElement(); - } - else { - FacilityOperationDec fOpDec = - (FacilityOperationDec) opEntry.getDefiningElement(); - opDec = - new OperationDec(fOpDec.getName(), fOpDec.getParameters(), - fOpDec.getReturnTy(), fOpDec.getStateVars(), fOpDec - .getRequires(), fOpDec.getEnsures()); - } - - return opDec; - } - - /** - *

Returns the requires clause for the current Dec.

- * - * @param dec The corresponding Dec. - * - * @return The requires clause Exp. - */ - private Exp getRequiresClause(Dec dec) { - PosSymbol name = dec.getName(); - Exp requires = null; - Exp retExp = null; - - // Check for each kind of ModuleDec possible - if (dec instanceof FacilityOperationDec) { - requires = ((FacilityOperationDec) dec).getRequires(); - } - else if (dec instanceof OperationDec) { - requires = ((OperationDec) dec).getRequires(); - } - else if (dec instanceof ConceptModuleDec) { - requires = ((ConceptModuleDec) dec).getRequirement(); - } - else if (dec instanceof ConceptBodyModuleDec) { - requires = ((ConceptBodyModuleDec) dec).getRequires(); - } - else if (dec instanceof EnhancementModuleDec) { - requires = ((EnhancementModuleDec) dec).getRequirement(); - } - else if (dec instanceof EnhancementBodyModuleDec) { - requires = ((EnhancementBodyModuleDec) dec).getRequires(); - } - else if (dec instanceof FacilityModuleDec) { - requires = ((FacilityModuleDec) dec).getRequirement(); - } - - // Deep copy and fill in the details of this location - if (requires != null) { - retExp = Exp.copy(requires); - if (retExp.getLocation() != null) { - Location myLoc = retExp.getLocation(); - myLoc.setDetails("Requires Clause for " + name); - setLocation(retExp, myLoc); - } - } - - return retExp; - } - - /** - *

Get the PosSymbol associated with the - * VariableExp left.

- * - * @param left The variable expression. - * - * @return The PosSymbol of left. - */ - private PosSymbol getVarName(VariableExp left) { - // Return value - PosSymbol name; - - // Variable Name Expression - if (left instanceof VariableNameExp) { - name = ((VariableNameExp) left).getName(); - } - // Variable Dot Expression - else if (left instanceof VariableDotExp) { - VariableRecordExp varRecExp = - (VariableRecordExp) ((VariableDotExp) left) - .getSemanticExp(); - name = varRecExp.getName(); - } - // Variable Record Expression - else if (left instanceof VariableRecordExp) { - VariableRecordExp varRecExp = (VariableRecordExp) left; - name = varRecExp.getName(); - } - // - // Creates an expression with "false" as its name - else { - name = createPosSymbol("false"); - } - - return name; - } - - /** - *

Checks to see if the initialization ensures clause - * passed is in the simple form where one side has a - * VarExp.

- * - * @param initEnsures The initialization ensures clause, - * or part of it that we are currently - * checking. - * - * @return True/False - */ - private boolean isInitEnsuresSimpleForm(Exp initEnsures) { - boolean isSimple = false; - - // Case #1: EqualExp in initEnsures - if (initEnsures instanceof EqualsExp) { - EqualsExp exp = (EqualsExp) initEnsures; - // Recursively call this on the left and - // right hand side. Only one of the sides - // needs to be a VarExp. - if (isInitEnsuresSimpleForm(exp.getLeft()) - || isInitEnsuresSimpleForm(exp.getRight())) { - isSimple = true; - } - } - // Case #2: InfixExp in initEnsures - else if (initEnsures instanceof InfixExp) { - InfixExp exp = (InfixExp) initEnsures; - // Only check if we have an "and" expression - if (exp.getOpName().equals("and")) { - // Recursively call this on the left and - // right hand side. Both sides need to be - // a VarExp. - if (isInitEnsuresSimpleForm(exp.getLeft()) - && isInitEnsuresSimpleForm(exp.getRight())) { - isSimple = true; - } - } - } - // Case #3: VarExp = initEnsures - else if (initEnsures instanceof VarExp) { - isSimple = true; - } - - return isSimple; - } - - /** - *

Checks to see if the expression passed in is a - * verification variable or not. A verification variable - * is either "P_val" or starts with "?".

- * - * @param name Expression that we want to check - * - * @return True/False - */ - private boolean isVerificationVar(Exp name) { - // VarExp - if (name instanceof VarExp) { - String strName = ((VarExp) name).getName().getName(); - // Case #1: Question mark variables - if (strName.charAt(0) == '?') { - return true; - } - // Case #2: P_val - else if (strName.equals("P_val")) { - return true; - } - } - // DotExp - else if (name instanceof DotExp) { - // Recursively call this method until we get - // either true or false. - List names = ((DotExp) name).getSegments(); - return isVerificationVar(names.get(0)); - } - - // Definitely not a verification variable. - return false; - } - - /** - *

Modifies the ensures clause based on the parameter mode.

- * - * @param ensures The Exp containing the ensures clause. - * @param opLocation The Location for the operation - * @param opName The name of the operation. - * @param parameterVarDecList The list of parameter variables for the operation. - * - * @return The modified ensures clause Exp. - */ - private Exp modifyEnsuresByParameter(Exp ensures, Location opLocation, - String opName, List parameterVarDecList) { - // Loop through each parameter - for (ParameterVarDec p : parameterVarDecList) { - // Ty is NameTy - if (p.getTy() instanceof NameTy) { - NameTy pNameTy = (NameTy) p.getTy(); - - // Exp form of the parameter variable - VarExp parameterExp = - new VarExp(p.getLocation(), null, p.getName().copy()); - parameterExp.setMathType(pNameTy.getMathTypeValue()); - - // Create an old exp (#parameterExp) - OldExp oldParameterExp = - new OldExp(p.getLocation(), Exp.copy(parameterExp)); - oldParameterExp.setMathType(pNameTy.getMathTypeValue()); - - // Preserves or Restores mode - if (p.getMode() == Mode.PRESERVES - || p.getMode() == Mode.RESTORES) { - // Create an equals expression of the form "#parameterExp = parameterExp" - EqualsExp equalsExp = - new EqualsExp(opLocation, oldParameterExp, - EqualsExp.EQUAL, parameterExp); - equalsExp.setMathType(BOOLEAN); - - // Set the details for the new location - Location equalLoc; - if (ensures != null && ensures.getLocation() != null) { - Location enLoc = ensures.getLocation(); - equalLoc = ((Location) enLoc.clone()); - } - else { - equalLoc = ((Location) opLocation.clone()); - equalLoc.setDetails("Ensures Clause of " + opName); - } - equalLoc.setDetails(equalLoc.getDetails() - + " (Condition from \"" - + p.getMode().getModeName().toUpperCase() - + "\" parameter mode)"); - equalsExp.setLocation(equalLoc); - - // Create an AND infix expression with the ensures clause - if (ensures != null - && !ensures.equals(myTypeGraph.getTrueVarExp())) { - ensures = myTypeGraph.formConjunct(ensures, equalsExp); - } - // Make new expression the ensures clause - else { - ensures = equalsExp; - } - } - // Clears mode - else if (p.getMode() == Mode.CLEARS) { - // Query for the type entry in the symbol table - ProgramTypeEntry typeEntry = - searchProgramType(pNameTy.getLocation(), pNameTy - .getName()); - - Exp init; - if (typeEntry.getDefiningElement() instanceof TypeDec) { - // Obtain the original dec from the AST - TypeDec type = (TypeDec) typeEntry.getDefiningElement(); - - // Obtain the exemplar in VarExp form - VarExp exemplar = - new VarExp(null, null, type.getExemplar()); - exemplar.setMathType(pNameTy.getMathTypeValue()); - - // Deep copy the original initialization ensures and the constraint - init = Exp.copy(type.getInitialization().getEnsures()); - - // Replace the formal with the actual - init = replace(init, exemplar, parameterExp); - - // Set the details for the new location - if (init.getLocation() != null) { - Location initLoc; - if (ensures != null - && ensures.getLocation() != null) { - Location reqLoc = ensures.getLocation(); - initLoc = ((Location) reqLoc.clone()); - } - else { - initLoc = ((Location) opLocation.clone()); - initLoc.setDetails("Ensures Clause of " - + opName); - } - initLoc.setDetails(initLoc.getDetails() - + " (Condition from \"" - + p.getMode().getModeName().toUpperCase() - + "\" parameter mode)"); - init.setLocation(initLoc); - } - } - // Since the type is generic, we can only use the is_initial predicate - // to ensure that the value is initial value. - else { - // Obtain the original dec from the AST - Location varLoc = p.getLocation(); - - // Create an is_initial dot expression - init = - createInitExp(new VarDec(p.getName(), p.getTy())); - if (varLoc != null) { - Location loc = (Location) varLoc.clone(); - loc.setDetails("Initial Value for " - + p.getName().getName()); - setLocation(init, loc); - } - } - - // Create an AND infix expression with the ensures clause - if (ensures != null - && !ensures.equals(myTypeGraph.getTrueVarExp())) { - ensures = myTypeGraph.formConjunct(ensures, init); - } - // Make initialization expression the ensures clause - else { - ensures = init; - } - } - } - else { - // Ty not handled. - tyNotHandled(p.getTy(), p.getLocation()); - } - } - - return ensures; - } - - /** - *

Returns the ensures clause.

- * - * @param ensures The Exp containing the ensures clause. - * @param opLocation The Location for the operation. - * @param opName The name for the operation. - * - * @return The modified ensures clause Exp. - */ - private Exp modifyEnsuresClause(Exp ensures, Location opLocation, - String opName) { - // Obtain the list of parameters for the current operation - List parameterVarDecList; - if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) { - parameterVarDecList = - ((FacilityOperationDec) myCurrentOperationEntry - .getDefiningElement()).getParameters(); - } - else { - parameterVarDecList = - ((OperationDec) myCurrentOperationEntry - .getDefiningElement()).getParameters(); - } - - // Modifies the existing ensures clause based on - // the parameter modes. - ensures = - modifyEnsuresByParameter(ensures, opLocation, opName, - parameterVarDecList); - - return ensures; - } - - /** - *

Modifies the requires clause based on .

- * - * @param requires The Exp containing the requires clause. - * - * @return The modified requires clause Exp. - */ - private Exp modifyRequiresByGlobalMode(Exp requires) { - return requires; - } - - /** - *

Modifies the requires clause based on the parameter mode.

- * - * @param requires The Exp containing the requires clause. - * @param opLocation The Location for the operation. - * @param opName The name for the operation. - * - * @return The modified requires clause Exp. - */ - private Exp modifyRequiresByParameter(Exp requires, Location opLocation, - String opName) { - // Obtain the list of parameters - List parameterVarDecList; - if (myCurrentOperationEntry.getDefiningElement() instanceof FacilityOperationDec) { - parameterVarDecList = - ((FacilityOperationDec) myCurrentOperationEntry - .getDefiningElement()).getParameters(); - } - else { - parameterVarDecList = - ((OperationDec) myCurrentOperationEntry - .getDefiningElement()).getParameters(); - } - - // Loop through each parameter - for (ParameterVarDec p : parameterVarDecList) { - ProgramTypeEntry typeEntry; - - // Ty is NameTy - if (p.getTy() instanceof NameTy) { - NameTy pNameTy = (NameTy) p.getTy(); - - // Query for the type entry in the symbol table - typeEntry = - searchProgramType(pNameTy.getLocation(), pNameTy - .getName()); - - // Obtain the original dec from the AST - TypeDec type = (TypeDec) typeEntry.getDefiningElement(); - - // Convert p to a VarExp - VarExp pExp = new VarExp(null, null, p.getName()); - pExp.setMathType(pNameTy.getMathTypeValue()); - - // Obtain the exemplar in VarExp form - VarExp exemplar = new VarExp(null, null, type.getExemplar()); - exemplar.setMathType(pNameTy.getMathTypeValue()); - - // Deep copy the original initialization ensures and the constraint - Exp init = Exp.copy(type.getInitialization().getEnsures()); - Exp constraint = Exp.copy(type.getConstraint()); - - // Only worry about replaces mode parameters - if (p.getMode() == Mode.REPLACES && init != null) { - // Replace the formal with the actual - init = replace(init, exemplar, pExp); - - // Set the details for the new location - if (init.getLocation() != null) { - Location initLoc; - if (requires != null && requires.getLocation() != null) { - Location reqLoc = requires.getLocation(); - initLoc = ((Location) reqLoc.clone()); - } - else { - // Append the name of the current procedure - String details = ""; - if (myCurrentOperationEntry != null) { - details = - " in Procedure " - + myCurrentOperationEntry - .getName(); - } - - // Set the details of the current location - initLoc = ((Location) opLocation.clone()); - initLoc.setDetails("Requires Clause of " + opName - + details); - } - initLoc.setDetails(initLoc.getDetails() - + " (Assumption from \"" - + p.getMode().getModeName().toUpperCase() - + "\" parameter mode)"); - init.setLocation(initLoc); - } - - // Create an AND infix expression with the requires clause - if (requires != null - && !requires.equals(myTypeGraph.getTrueVarExp())) { - requires = myTypeGraph.formConjunct(requires, init); - } - // Make initialization expression the requires clause - else { - requires = init; - } - } - // Constraints for the other parameter modes needs to be added - // to the requires clause as conjuncts. - else { - if (constraint != null - && !constraint.equals(myTypeGraph.getTrueVarExp())) { - // Replace the formal with the actual - constraint = replace(constraint, exemplar, pExp); - - // Set the details for the new location - if (constraint.getLocation() != null) { - Location constLoc; - if (requires != null - && requires.getLocation() != null) { - Location reqLoc = requires.getLocation(); - constLoc = ((Location) reqLoc.clone()); - } - else { - // Append the name of the current procedure - String details = ""; - if (myCurrentOperationEntry != null) { - details = - " in Procedure " - + myCurrentOperationEntry - .getName(); - } - - constLoc = ((Location) opLocation.clone()); - constLoc.setDetails("Requires Clause of " - + opName + details); - } - constLoc.setDetails(constLoc.getDetails() - + " (Constraint from \"" - + p.getMode().getModeName().toUpperCase() - + "\" parameter mode)"); - constraint.setLocation(constLoc); - } - - // Create an AND infix expression with the requires clause - if (requires != null - && !requires - .equals(myTypeGraph.getTrueVarExp())) { - requires = - myTypeGraph.formConjunct(requires, - constraint); - } - // Make constraint expression the requires clause - else { - requires = constraint; - } - } - } - - // Add the current variable to our list of free variables - myCurrentAssertiveCode.addFreeVar(createVarExp(p.getLocation(), - p.getName(), pNameTy.getMathTypeValue())); - } - else { - // Ty not handled. - tyNotHandled(p.getTy(), p.getLocation()); - } - } - - return requires; - } - - /** - *

Modifies the requires clause.

- * - * @param requires The Exp containing the requires clause. - * @param opLocation The Location for the operation. - * @param opName The name of the operation. - * - * @return The modified requires clause Exp. - */ - private Exp modifyRequiresClause(Exp requires, Location opLocation, - String opName) { - // Modifies the existing requires clause based on - // the parameter modes. - requires = modifyRequiresByParameter(requires, opLocation, opName); - - // Modifies the existing requires clause based on - // the parameter modes. - // TODO: Ask Murali what this means - requires = modifyRequiresByGlobalMode(requires); - - return requires; - } - - /** - *

Negate the incoming expression.

- * - * @param exp Expression to be negated. - * - * @return Negated expression. - */ - private Exp negateExp(Exp exp) { - Exp retExp = Exp.copy(exp); - if (exp instanceof EqualsExp) { - if (((EqualsExp) exp).getOperator() == EqualsExp.EQUAL) - ((EqualsExp) retExp).setOperator(EqualsExp.NOT_EQUAL); - else - ((EqualsExp) retExp).setOperator(EqualsExp.EQUAL); - } - else if (exp instanceof PrefixExp) { - if (((PrefixExp) exp).getSymbol().getName().toString() - .equals("not")) { - retExp = ((PrefixExp) exp).getArgument(); - } - } - else { - PrefixExp tmp = new PrefixExp(); - setLocation(tmp, exp.getLocation()); - tmp.setArgument(exp); - tmp.setSymbol(createPosSymbol("not")); - tmp.setMathType(BOOLEAN); - retExp = tmp; - } - return retExp; - } - - /** - *

Copy and replace the old Exp.

- * - * @param exp The Exp to be replaced. - * @param old The old sub-expression of exp. - * @param repl The new sub-expression of exp. - * - * @return The new Exp. - */ - private Exp replace(Exp exp, Exp old, Exp repl) { - // Clone old and repl and use the Exp replace to do all its work - Exp tmp = Exp.replace(exp, Exp.copy(old), Exp.copy(repl)); - - // Return the corresponding Exp - if (tmp != null) - return tmp; - else - return exp; - } - - /** - *

Replace the formal with the actual variables - * inside the ensures clause.

- * - * @param ensures The ensures clause. - * @param paramList The list of parameter variables. - * @param stateVarList The list of state variables. - * @param argList The list of arguments from the operation call. - * @param isSimple Check if it is a simple replacement. - * - * @return The ensures clause in Exp form. - */ - private Exp replaceFormalWithActualEns(Exp ensures, - List paramList, List stateVarList, - List argList, boolean isSimple) { - // Current final confirm - Exp newConfirm = myCurrentAssertiveCode.getFinalConfirm(); - - // List to hold temp and real values of variables in case - // of duplicate spec and real variables - List undRepList = new ArrayList(); - List replList = new ArrayList(); - - // Replace state variables in the ensures clause - // and create new confirm statements if needed. - for (int i = 0; i < stateVarList.size(); i++) { - newConfirm = myCurrentAssertiveCode.getFinalConfirm(); - AffectsItem stateVar = stateVarList.get(i); - - // Only deal with Alters/Reassigns/Replaces/Updates modes - if (stateVar.getMode() == Mode.ALTERS - || stateVar.getMode() == Mode.REASSIGNS - || stateVar.getMode() == Mode.REPLACES - || stateVar.getMode() == Mode.UPDATES) { - // Obtain the variable from our free variable list - Exp globalFreeVar = - myCurrentAssertiveCode.getFreeVar(stateVar.getName(), - true); - if (globalFreeVar != null) { - VarExp oldNamesVar = new VarExp(); - oldNamesVar.setName(stateVar.getName()); - - // Create a local free variable if it is not there - Exp localFreeVar = - myCurrentAssertiveCode.getFreeVar(stateVar - .getName(), false); - if (localFreeVar == null) { - // TODO: Don't have a type for state variables? - localFreeVar = - new VarExp(null, null, stateVar.getName()); - localFreeVar = - createQuestionMarkVariable(myTypeGraph - .formConjunct(ensures, newConfirm), - (VarExp) localFreeVar); - myCurrentAssertiveCode.addFreeVar(localFreeVar); - } - else { - localFreeVar = - createQuestionMarkVariable(myTypeGraph - .formConjunct(ensures, newConfirm), - (VarExp) localFreeVar); - } - - // Creating "#" expressions and replace these in the - // ensures clause. - OldExp osVar = new OldExp(null, Exp.copy(globalFreeVar)); - OldExp oldNameOSVar = - new OldExp(null, Exp.copy(oldNamesVar)); - ensures = replace(ensures, oldNamesVar, globalFreeVar); - ensures = replace(ensures, oldNameOSVar, osVar); - - // If it is not simple replacement, replace all ensures clauses - // with the appropriate expressions. - if (!isSimple) { - ensures = replace(ensures, globalFreeVar, localFreeVar); - ensures = replace(ensures, osVar, globalFreeVar); - newConfirm = - replace(newConfirm, globalFreeVar, localFreeVar); - } - - // Set newConfirm as our new final confirm statement - myCurrentAssertiveCode.setFinalConfirm(newConfirm); - } - // Error: Why isn't it a free variable. - else { - notInFreeVarList(stateVar.getName(), stateVar.getLocation()); - } - } - } - - // Replace postcondition variables in the ensures clause - for (int i = 0; i < argList.size(); i++) { - ParameterVarDec varDec = paramList.get(i); - ProgramExp pExp = argList.get(i); - PosSymbol VDName = varDec.getName(); - - // VarExp form of the parameter variable - VarExp oldExp = new VarExp(null, null, VDName); - oldExp.setMathType(pExp.getMathType()); - oldExp.setMathTypeValue(pExp.getMathTypeValue()); - - // Convert the pExp into a something we can use - Exp repl = convertExp(pExp); - Exp undqRep = null, quesRep = null; - OldExp oSpecVar, oRealVar; - String replName = null; - - // Case #1: ProgramIntegerExp - if (pExp instanceof ProgramIntegerExp) { - replName = - Integer.toString(((ProgramIntegerExp) repl).getValue()); - - // Create a variable expression of the form "_?[Argument Name]" - undqRep = - new VarExp(null, null, createPosSymbol("_?" + replName)); - undqRep.setMathType(pExp.getMathType()); - undqRep.setMathTypeValue(pExp.getMathTypeValue()); - - // Create a variable expression of the form "?[Argument Name]" - quesRep = - new VarExp(null, null, createPosSymbol("?" + replName)); - quesRep.setMathType(pExp.getMathType()); - quesRep.setMathTypeValue(pExp.getMathTypeValue()); - } - // Case #2: VariableDotExp - else if (pExp instanceof VariableDotExp) { - if (repl instanceof DotExp) { - Exp pE = ((DotExp) repl).getSegments().get(0); - replName = pE.toString(0); - - // Create a variable expression of the form "_?[Argument Name]" - undqRep = Exp.copy(repl); - edu.clemson.cs.r2jt.collections.List segList = - ((DotExp) undqRep).getSegments(); - VariableNameExp undqNameRep = - new VariableNameExp(null, null, - createPosSymbol("_?" + replName)); - undqNameRep.setMathType(pE.getMathType()); - segList.set(0, undqNameRep); - ((DotExp) undqRep).setSegments(segList); - - // Create a variable expression of the form "?[Argument Name]" - quesRep = Exp.copy(repl); - segList = ((DotExp) quesRep).getSegments(); - segList - .set(0, ((VariableDotExp) pExp).getSegments() - .get(0)); - ((DotExp) quesRep).setSegments(segList); - } - else if (repl instanceof VariableDotExp) { - Exp pE = ((VariableDotExp) repl).getSegments().get(0); - replName = pE.toString(0); - - // Create a variable expression of the form "_?[Argument Name]" - undqRep = Exp.copy(repl); - edu.clemson.cs.r2jt.collections.List segList = - ((VariableDotExp) undqRep).getSegments(); - VariableNameExp undqNameRep = - new VariableNameExp(null, null, - createPosSymbol("_?" + replName)); - undqNameRep.setMathType(pE.getMathType()); - segList.set(0, undqNameRep); - ((VariableDotExp) undqRep).setSegments(segList); - - // Create a variable expression of the form "?[Argument Name]" - quesRep = Exp.copy(repl); - segList = ((VariableDotExp) quesRep).getSegments(); - segList - .set(0, ((VariableDotExp) pExp).getSegments() - .get(0)); - ((VariableDotExp) quesRep).setSegments(segList); - } - // Error: Case not handled! - else { - expNotHandled(pExp, pExp.getLocation()); - } - } - // Case #3: VariableNameExp - else if (pExp instanceof VariableNameExp) { - // Name of repl in string form - replName = ((VariableNameExp) pExp).getName().getName(); - - // Create a variable expression of the form "_?[Argument Name]" - undqRep = - new VarExp(null, null, createPosSymbol("_?" + replName)); - undqRep.setMathType(pExp.getMathType()); - undqRep.setMathTypeValue(pExp.getMathTypeValue()); - - // Create a variable expression of the form "?[Argument Name]" - quesRep = - new VarExp(null, null, createPosSymbol("?" + replName)); - quesRep.setMathType(pExp.getMathType()); - quesRep.setMathTypeValue(pExp.getMathTypeValue()); - } - // Error: Case not handled! - else { - expNotHandled(pExp, pExp.getLocation()); - } - - // "#" versions of oldExp and repl - oSpecVar = new OldExp(null, Exp.copy(oldExp)); - oRealVar = new OldExp(null, Exp.copy(repl)); - - // Nothing can be null! - if (oldExp != null && quesRep != null && oSpecVar != null - && repl != null && oRealVar != null) { - // Alters, Clears, Reassigns, Replaces, Updates - if (varDec.getMode() == Mode.ALTERS - || varDec.getMode() == Mode.CLEARS - || varDec.getMode() == Mode.REASSIGNS - || varDec.getMode() == Mode.REPLACES - || varDec.getMode() == Mode.UPDATES) { - Exp quesVar; - - // Obtain the free variable - VarExp freeVar = - (VarExp) myCurrentAssertiveCode.getFreeVar( - createPosSymbol(replName), false); - if (freeVar == null) { - freeVar = - createVarExp(varDec.getLocation(), - createPosSymbol(replName), varDec - .getTy().getMathTypeValue()); - } - - // Apply the question mark to the free variable - freeVar = - createQuestionMarkVariable(myTypeGraph - .formConjunct(ensures, newConfirm), freeVar); - - if (pExp instanceof ProgramDotExp - || pExp instanceof VariableDotExp) { - // Make a copy from repl - quesVar = Exp.copy(repl); - - // Replace the free variable in the question mark variable as the first element - // in the dot expression. - VarExp tmpVar = - new VarExp(null, null, freeVar.getName()); - tmpVar.setMathType(myTypeGraph.BOOLEAN); - edu.clemson.cs.r2jt.collections.List segs = - ((DotExp) quesVar).getSegments(); - segs.set(0, tmpVar); - ((DotExp) quesVar).setSegments(segs); - } - else { - // Create a variable expression from free variable - quesVar = new VarExp(null, null, freeVar.getName()); - quesVar.setMathType(freeVar.getMathType()); - quesVar.setMathTypeValue(freeVar.getMathTypeValue()); - } - - // Add the new free variable to free variable list - myCurrentAssertiveCode.addFreeVar(freeVar); - - // Check if our ensures clause has the parameter variable in it. - if (ensures.containsVar(VDName.getName(), true) - || ensures.containsVar(VDName.getName(), false)) { - // Replace the ensures clause - ensures = replace(ensures, oldExp, undqRep); - ensures = replace(ensures, oSpecVar, repl); - - // Add it to our list of variables to be replaced later - undRepList.add(undqRep); - replList.add(quesVar); - } - else { - // Replace the ensures clause - ensures = replace(ensures, oldExp, quesRep); - ensures = replace(ensures, oSpecVar, repl); - } - - // Update our final confirm with the parameter argument - newConfirm = replace(newConfirm, repl, quesVar); - myCurrentAssertiveCode.setFinalConfirm(newConfirm); - } - // All other modes - else { - // Check if our ensures clause has the parameter variable in it. - if (ensures.containsVar(VDName.getName(), true) - || ensures.containsVar(VDName.getName(), false)) { - // Replace the ensures clause - ensures = replace(ensures, oldExp, undqRep); - ensures = replace(ensures, oSpecVar, undqRep); - - // Add it to our list of variables to be replaced later - undRepList.add(undqRep); - replList.add(repl); - } - else { - // Replace the ensures clause - ensures = replace(ensures, oldExp, repl); - ensures = replace(ensures, oSpecVar, repl); - } - } - } - } - - // Replace the temp values with the actual values - for (int i = 0; i < undRepList.size(); i++) { - ensures = replace(ensures, undRepList.get(i), replList.get(i)); - } - - return ensures; - } - - /** - *

Replace the formal with the actual variables - * inside the requires clause.

- * - * @param requires The requires clause. - * @param paramList The list of parameter variables. - * @param argList The list of arguments from the operation call. - * - * @return The requires clause in Exp form. - */ - private Exp replaceFormalWithActualReq(Exp requires, - List paramList, List argList) { - // List to hold temp and real values of variables in case - // of duplicate spec and real variables - List undRepList = new ArrayList(); - List replList = new ArrayList(); - - // Replace precondition variables in the requires clause - for (int i = 0; i < argList.size(); i++) { - ParameterVarDec varDec = paramList.get(i); - ProgramExp pExp = argList.get(i); - - // Convert the pExp into a something we can use - Exp repl = convertExp(pExp); - - // VarExp form of the parameter variable - VarExp oldExp = new VarExp(null, null, varDec.getName()); - oldExp.setMathType(pExp.getMathType()); - oldExp.setMathTypeValue(pExp.getMathTypeValue()); - - // New VarExp - VarExp newExp = - new VarExp(null, null, createPosSymbol("_" - + varDec.getName().getName())); - newExp.setMathType(repl.getMathType()); - newExp.setMathTypeValue(repl.getMathTypeValue()); - - // Replace the old with the new in the requires clause - requires = replace(requires, oldExp, newExp); - - // Add it to our list - undRepList.add(newExp); - replList.add(repl); - } - - // Replace the temp values with the actual values - for (int i = 0; i < undRepList.size(); i++) { - requires = replace(requires, undRepList.get(i), replList.get(i)); - } - - return requires; - } - - /** - *

Given a math symbol name, locate and return - * the MathSymbolEntry stored in the - * symbol table.

- * - * @param loc The location in the AST that we are - * currently visiting. - * @param name The string name of the math symbol. - * - * @return An MathSymbolEntry from the - * symbol table. - */ - private MathSymbolEntry searchMathSymbol(Location loc, String name) { - // Query for the corresponding math symbol - MathSymbolEntry ms = null; - try { - ms = - myCurrentModuleScope.queryForOne( - new UnqualifiedNameQuery(name, - ImportStrategy.IMPORT_RECURSIVE, - FacilityStrategy.FACILITY_IGNORE, true, - true)).toMathSymbolEntry(loc); - } - catch (NoSuchSymbolException nsse) { - noSuchSymbol(null, name, loc); - } - catch (DuplicateSymbolException dse) { - //This should be caught earlier, when the duplicate symbol is - //created - throw new RuntimeException(dse); - } - - return ms; - } - - /** - *

Given the qualifier, name and the list of argument - * types, locate and return the OperationEntry - * stored in the symbol table.

- * - * @param loc The location in the AST that we are - * currently visiting. - * @param qualifier The qualifier of the operation. - * @param name The name of the operation. - * @param argTypes The list of argument types. - * - * @return An OperationEntry from the - * symbol table. - */ - private OperationEntry searchOperation(Location loc, PosSymbol qualifier, - PosSymbol name, List argTypes) { - // Query for the corresponding operation - OperationEntry op = null; - try { - op = - myCurrentModuleScope.queryForOne(new OperationQuery( - qualifier, name, argTypes)); - } - catch (NoSuchSymbolException nsse) { - noSuchSymbol(null, name.getName(), loc); - } - catch (DuplicateSymbolException dse) { - //This should be caught earlier, when the duplicate operation is - //created - throw new RuntimeException(dse); - } - - return op; - } - - /** - *

Given the name of the type locate and return - * the ProgramTypeEntry stored in the - * symbol table.

- * - * @param loc The location in the AST that we are - * currently visiting. - * @param name The name of the type. - * - * @return An ProgramTypeEntry from the - * symbol table. - */ - private ProgramTypeEntry searchProgramType(Location loc, PosSymbol name) { - // Query for the corresponding operation - ProgramTypeEntry pt = null; - try { - pt = - myCurrentModuleScope.queryForOne( - new NameQuery(null, name, - ImportStrategy.IMPORT_NAMED, - FacilityStrategy.FACILITY_INSTANTIATE, - false)).toProgramTypeEntry(loc); - } - catch (NoSuchSymbolException nsse) { - noSuchSymbol(null, name.getName(), loc); - } - catch (DuplicateSymbolException dse) { - //This should be caught earlier, when the duplicate type is - //created - throw new RuntimeException(dse); - } - - return pt; - } - - /** - *

Changes the Exp with the new - * Location.

- * - * @param exp The Exp that needs to be modified. - * @param loc The new Location. - */ - private void setLocation(Exp exp, Location loc) { - // Special handling for InfixExp - if (exp instanceof InfixExp) { - ((InfixExp) exp).setAllLocations(loc); - } - else { - exp.setLocation(loc); - } - } - - /** - *

Simplify the assume statement where possible.

- * - * @param stmt The assume statement we want to simplify. - * @param exp The current expression we are dealing with. - * - * @return The modified expression in Exp/code> form. - */ - private Exp simplifyAssumeRule(AssumeStmt stmt, Exp exp) { - // Variables - Exp assertion = stmt.getAssertion(); - boolean keepAssumption = false; - - // EqualsExp - if (assertion instanceof EqualsExp) { - EqualsExp equalsExp = (EqualsExp) assertion; - - // Only do simplifications if we have an equals - if (equalsExp.getOperator() == EqualsExp.EQUAL) { - boolean verificationVariable = - isVerificationVar(equalsExp.getLeft()); - - // Create a temp expression where left is replaced with the right - Exp tmp = - replace(exp, equalsExp.getLeft(), equalsExp.getRight()); - if (equalsExp.getLeft() instanceof VarExp) { - // If left is still part of confirm - VarExp left = (VarExp) equalsExp.getLeft(); - if (tmp.containsVar(left.getName().getName(), false)) { - keepAssumption = true; - } - } - - // If tmp is not null, then it means we have to check the right - if (tmp == null) { - // Create a temp expression where right is replaced with the left - verificationVariable = - isVerificationVar(equalsExp.getRight()); - tmp = - replace(exp, equalsExp.getRight(), equalsExp - .getLeft()); - if (equalsExp.getRight() instanceof VarExp) { - // If right is still part of confirm - VarExp right = (VarExp) equalsExp.getRight(); - if (tmp.containsVar(right.getName().getName(), false)) { - keepAssumption = true; - } - } - } - - // We clear our assertion for this assumes if - // we have a verification variable and we don't have to - // keep this assumption. - if (verificationVariable && !keepAssumption) { - assertion = null; - } - - // Update exp - if (!tmp.equals(exp)) { - exp = tmp; - } - } - } - // InfixExp - else if (assertion instanceof InfixExp) { - InfixExp infixExp = (InfixExp) assertion; - - // Only do simplifications if we have an and operator - if (infixExp.getOpName().equals("and")) { - // Recursively call simplify on the left and on the right - AssumeStmt left = new AssumeStmt(Exp.copy(infixExp.getLeft())); - AssumeStmt right = - new AssumeStmt(Exp.copy(infixExp.getRight())); - exp = simplifyAssumeRule(left, exp); - exp = simplifyAssumeRule(right, exp); - - // Case #1: Nothing left - if (left.getAssertion() == null && right.getAssertion() == null) { - assertion = null; - } - // Case #2: Both still have assertions - else if (left.getAssertion() != null - && right.getAssertion() != null) { - assertion = - myTypeGraph.formConjunct(left.getAssertion(), right - .getAssertion()); - } - // Case #3: Left still has assertions - else if (left.getAssertion() != null) { - assertion = left.getAssertion(); - } - // Case #r: Right still has assertions - else { - assertion = right.getAssertion(); - } - } - } - - // Store the new assertion - stmt.setAssertion(assertion); - - return exp; - } - - // ----------------------------------------------------------- - // Proof Rules - // ----------------------------------------------------------- - - /** - *

Applies the assume rule.

- * - * @param assume The assume clause - */ - private void applyAssumeRule(VerificationStatement assume) { - if (assume.getAssertion() instanceof VarExp - && ((VarExp) assume.getAssertion()).equals(Exp - .getTrueVarExp(myTypeGraph))) { - // Verbose Mode Debug Messages - myVCBuffer.append("\nAssume Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - else { - // Obtain the current final confirm clause - Exp conf = myCurrentAssertiveCode.getFinalConfirm(); - - // Create a new implies expression - InfixExp newConf = - myTypeGraph.formImplies((Exp) assume.getAssertion(), conf); - - // Set this new expression as the new final confirm - myCurrentAssertiveCode.setFinalConfirm(newConf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nAssume Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - } - - /** - *

Applies the change rule.

- * - * @param change The change clause - */ - private void applyChangeRule(VerificationStatement change) { - List changeList = - (List) change.getAssertion(); - Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); - - // Loop through each variable - for (VariableExp v : changeList) { - // v is an instance of VariableNameExp - if (v instanceof VariableNameExp) { - VariableNameExp vNameExp = (VariableNameExp) v; - - // Create VarExp for vNameExp - VarExp vExp = - createVarExp(vNameExp.getLocation(), - vNameExp.getName(), vNameExp.getMathType()); - - // Create a new question mark variable - VarExp newV = createQuestionMarkVariable(finalConfirm, vExp); - - // Add this new variable to our list of free variables - myCurrentAssertiveCode.addFreeVar(newV); - - // Replace all instances of vExp with newV - finalConfirm = replace(finalConfirm, vExp, newV); - } - } - - // Set the modified statement as our new final confirm - myCurrentAssertiveCode.setFinalConfirm(finalConfirm); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nChange Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies different rules to code statements.

- * - * @param statement The different statements. - */ - private void applyCodeRules(Statement statement) { - // Apply each statement rule here. - if (statement instanceof AssumeStmt) { - applyEBAssumeStmtRule((AssumeStmt) statement); - } - else if (statement instanceof CallStmt) { - applyEBCallStmtRule((CallStmt) statement); - } - else if (statement instanceof ConfirmStmt) { - applyEBConfirmStmtRule((ConfirmStmt) statement); - } - else if (statement instanceof FuncAssignStmt) { - applyEBFuncAssignStmtRule((FuncAssignStmt) statement); - } - else if (statement instanceof IfStmt) { - applyEBIfStmtRule((IfStmt) statement); - } - else if (statement instanceof SwapStmt) { - applyEBSwapStmtRule((SwapStmt) statement); - } - else if (statement instanceof WhileStmt) { - applyEBWhileStmtRule((WhileStmt) statement); - } - } - - /** - *

Applies the confirm rule.

- * - * @param confirm The confirm clause - */ - private void applyConfirmRule(VerificationStatement confirm) { - if (confirm.getAssertion() instanceof VarExp - && ((VarExp) confirm.getAssertion()).equals(Exp - .getTrueVarExp(myTypeGraph))) { - myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - else { - // Obtain the current final confirm clause - Exp conf = myCurrentAssertiveCode.getFinalConfirm(); - - // Create a new and expression - InfixExp newConf = - myTypeGraph - .formConjunct((Exp) confirm.getAssertion(), conf); - - // Set this new expression as the new final confirm - myCurrentAssertiveCode.setFinalConfirm(newConf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nConfirm Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - } - - /** - *

Applies the assume rule to the - * Statement.

- * - * @param stmt Our current AssumeStmt. - */ - private void applyEBAssumeStmtRule(AssumeStmt stmt) { - // Check to see if our assertion just has "True" - Exp assertion = stmt.getAssertion(); - if (assertion instanceof VarExp - && assertion.equals(myTypeGraph.getTrueVarExp())) { - // Verbose Mode Debug Messages - myVCBuffer.append("\nAssume Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - - return; - } - - // Apply simplification - Exp currentFinalConfirm = - simplifyAssumeRule(stmt, myCurrentAssertiveCode - .getFinalConfirm()); - if (stmt.getAssertion() != null) { - // Create a new implies expression - currentFinalConfirm = - myTypeGraph.formImplies(stmt.getAssertion(), - currentFinalConfirm); - } - - // Set this as our new final confirm - myCurrentAssertiveCode.setFinalConfirm(currentFinalConfirm); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nAssume Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the call statement rule to the - * Statement.

- * - * @param stmt Our current CallStmt. - */ - private void applyEBCallStmtRule(CallStmt stmt) { - // Call a method to locate the operation dec for this call - OperationDec opDec = - getOperationDec(stmt.getLocation(), stmt.getQualifier(), stmt - .getName(), stmt.getArguments()); - - // Get the ensures clause for this operation - // Note: If there isn't an ensures clause, it is set to "True" - Exp ensures; - if (opDec.getEnsures() != null) { - ensures = Exp.copy(opDec.getEnsures()); - } - else { - ensures = myTypeGraph.getTrueVarExp(); - } - - // Get the requires clause for this operation - Exp requires; - if (opDec.getRequires() != null) { - requires = Exp.copy(opDec.getRequires()); - } - else { - requires = myTypeGraph.getTrueVarExp(); - } - - // Check for recursive call of itself - if (myCurrentOperationEntry.getName().equals(opDec.getName()) - && myCurrentOperationEntry.getReturnType() != null) { - // Create a new confirm statement using P_val and the decreasing clause - VarExp pVal = createPValExp(myOperationDecreasingExp.getLocation()); - - // Create a new infix expression - InfixExp exp = - new InfixExp(stmt.getLocation(), Exp - .copy(myOperationDecreasingExp), - createPosSymbol("<"), pVal); - exp.setMathType(BOOLEAN); - - // Create the new confirm statement - Location loc; - if (myOperationDecreasingExp.getLocation() != null) { - loc = (Location) myOperationDecreasingExp.getLocation().clone(); - } - else { - loc = (Location) stmt.getLocation().clone(); - } - loc.setDetails("Show Termination of Recursive Call"); - setLocation(exp, loc); - ConfirmStmt conf = new ConfirmStmt(loc, exp); - - // Add it to our list of assertions - myCurrentAssertiveCode.addCode(conf); - } - - // Modify ensures using the parameter modes - ensures = - modifyEnsuresByParameter(ensures, stmt.getLocation(), opDec - .getName().getName(), opDec.getParameters()); - - // Replace PreCondition variables in the requires clause - requires = - replaceFormalWithActualReq(requires, opDec.getParameters(), - stmt.getArguments()); - - // Replace PostCondition variables in the ensures clause - ensures = - replaceFormalWithActualEns(ensures, opDec.getParameters(), - opDec.getStateVars(), stmt.getArguments(), false); - - // Modify the location of the requires clause and add it to myCurrentAssertiveCode - if (requires != null) { - // Obtain the current location - // Note: If we don't have a location, we create one - Location loc; - if (stmt.getName().getLocation() != null) { - loc = (Location) stmt.getName().getLocation().clone(); - } - else { - loc = new Location(null, null); - } - - // Append the name of the current procedure - String details = ""; - if (myCurrentOperationEntry != null) { - details = " in Procedure " + myCurrentOperationEntry.getName(); - } - - // Set the details of the current location - loc.setDetails("Requires Clause of " + opDec.getName() + details); - setLocation(requires, loc); - - // Add this to our list of things to confirm - myCurrentAssertiveCode.addConfirm(requires); - } - - // Modify the location of the requires clause and add it to myCurrentAssertiveCode - if (ensures != null) { - // Obtain the current location - if (stmt.getName().getLocation() != null) { - // Set the details of the current location - Location loc = (Location) stmt.getName().getLocation().clone(); - loc.setDetails("Ensures Clause of " + opDec.getName()); - setLocation(ensures, loc); - } - - // Add this to our list of things to assume - myCurrentAssertiveCode.addAssume(ensures); - } - - // Verbose Mode Debug Messages - myVCBuffer.append("\nOperation Call Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the confirm rule to the - * Statement.

- * - * @param stmt Our current ConfirmStmt. - */ - private void applyEBConfirmStmtRule(ConfirmStmt stmt) { - // Check to see if our assertion just has "True" - Exp assertion = stmt.getAssertion(); - if (assertion instanceof VarExp - && assertion.equals(myTypeGraph.getTrueVarExp())) { - // Verbose Mode Debug Messages - myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - - return; - } - - // Obtain the current final confirm statement - Exp currentFinalConfirm = myCurrentAssertiveCode.getFinalConfirm(); - - // Check to see if we have a final confirm of "True" - if (currentFinalConfirm instanceof VarExp - && currentFinalConfirm.equals(myTypeGraph.getTrueVarExp())) { - - // Obtain the current location - if (assertion.getLocation() != null) { - // Set the details of the current location - Location loc = (Location) assertion.getLocation().clone(); - setLocation(assertion, loc); - } - - myCurrentAssertiveCode.setFinalConfirm(assertion); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nConfirm Rule Applied and Simplified: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - else { - // Create a new and expression - InfixExp newConf = - myTypeGraph.formConjunct(assertion, currentFinalConfirm); - - // Set this new expression as the new final confirm - myCurrentAssertiveCode.setFinalConfirm(newConf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nConfirm Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - } - - /** - *

Applies each of the proof rules. This AssertiveCode will be - * stored for later use and therefore should be considered immutable after - * a call to this method.

- */ - private void applyEBRules() { - // Apply a proof rule to each of the assertions - while (myCurrentAssertiveCode.hasAnotherAssertion()) { - // Work our way from the last assertion - VerificationStatement curAssertion = - myCurrentAssertiveCode.getLastAssertion(); - - switch (curAssertion.getType()) { - // Assume Assertion - case VerificationStatement.ASSUME: - applyAssumeRule(curAssertion); - break; - // Change Assertion - case VerificationStatement.CHANGE: - applyChangeRule(curAssertion); - break; - // Confirm Assertion - case VerificationStatement.CONFIRM: - applyConfirmRule(curAssertion); - break; - // Code - case VerificationStatement.CODE: - applyCodeRules((Statement) curAssertion.getAssertion()); - break; - // Remember Assertion - case VerificationStatement.REMEMBER: - applyRememberRule(); - break; - // Variable Declaration Assertion - case VerificationStatement.VARIABLE: - applyVarDeclRule(curAssertion); - break; - } - } - } - - /** - *

Applies the function assignment rule to the - * Statement.

- * - * @param stmt Our current FuncAssignStmt. - */ - private void applyEBFuncAssignStmtRule(FuncAssignStmt stmt) { - PosSymbol qualifier = null; - ProgramExp assignExp = stmt.getAssign(); - ProgramParamExp assignParamExp = null; - - // Check to see what kind of expression is on the right hand side - if (assignExp instanceof ProgramParamExp) { - // Cast to a ProgramParamExp - assignParamExp = (ProgramParamExp) assignExp; - } - else if (assignExp instanceof ProgramDotExp) { - // Cast to a ProgramParamExp - ProgramDotExp dotExp = (ProgramDotExp) assignExp; - assignParamExp = (ProgramParamExp) dotExp.getExp(); - qualifier = dotExp.getQualifier(); - } - else { - // TODO: ERROR! - } - - // Call a method to locate the operation dec for this call - OperationDec opDec = - getOperationDec(stmt.getLocation(), qualifier, assignParamExp - .getName(), assignParamExp.getArguments()); - - // Check for recursive call of itself - if (myCurrentOperationEntry.getName().equals(opDec.getName()) - && myCurrentOperationEntry.getReturnType() != null) { - // Create a new confirm statement using P_val and the decreasing clause - VarExp pVal = createPValExp(myOperationDecreasingExp.getLocation()); - - // Create a new infix expression - InfixExp exp = - new InfixExp(stmt.getLocation(), Exp - .copy(myOperationDecreasingExp), - createPosSymbol("<"), pVal); - exp.setMathType(BOOLEAN); - - // Create the new confirm statement - Location loc; - if (myOperationDecreasingExp.getLocation() != null) { - loc = (Location) myOperationDecreasingExp.getLocation().clone(); - } - else { - loc = (Location) stmt.getLocation().clone(); - } - loc.setDetails("Show Termination of Recursive Call"); - setLocation(exp, loc); - ConfirmStmt conf = new ConfirmStmt(loc, exp); - - // Add it to our list of assertions - myCurrentAssertiveCode.addCode(conf); - } - - // Get the requires clause for this operation - Exp requires; - if (opDec.getRequires() != null) { - requires = Exp.copy(opDec.getRequires()); - } - else { - requires = myTypeGraph.getTrueVarExp(); - } - - // Replace PreCondition variables in the requires clause - requires = - replaceFormalWithActualReq(requires, opDec.getParameters(), - assignParamExp.getArguments()); - - // Modify the location of the requires clause and add it to myCurrentAssertiveCode - // Obtain the current location - // Note: If we don't have a location, we create one - Location reqloc; - if (assignParamExp.getName().getLocation() != null) { - reqloc = (Location) assignParamExp.getName().getLocation().clone(); - } - else { - reqloc = new Location(null, null); - } - - // Append the name of the current procedure - String details = ""; - if (myCurrentOperationEntry != null) { - details = " in Procedure " + myCurrentOperationEntry.getName(); - } - - // Set the details of the current location - reqloc.setDetails("Requires Clause of " + opDec.getName() + details); - setLocation(requires, reqloc); - - // Add this to our list of things to confirm - myCurrentAssertiveCode.addConfirm(requires); - - // Get the ensures clause for this operation - // Note: If there isn't an ensures clause, it is set to "True" - Exp ensures, opEnsures; - if (opDec.getEnsures() != null) { - opEnsures = Exp.copy(opDec.getEnsures()); - - // Make sure we have an EqualsExp, else it is an error. - if (opEnsures instanceof EqualsExp) { - // Has to be a VarExp on the left hand side (containing the name - // of the function operation) - if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { - VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); - - // Check if it has the name of the operation - if (leftExp.getName().equals(opDec.getName())) { - ensures = ((EqualsExp) opEnsures).getRight(); - - // Obtain the current location - if (assignParamExp.getName().getLocation() != null) { - // Set the details of the current location - Location loc = - (Location) assignParamExp.getName() - .getLocation().clone(); - loc.setDetails("Ensures Clause of " - + opDec.getName()); - setLocation(ensures, loc); - } - - // Replace all instances of the variable on the left hand side - // in the ensures clause with the expression on the right. - Exp leftVariable; - - // We have a variable inside a record as the variable being assigned. - if (stmt.getVar() instanceof VariableDotExp) { - VariableDotExp v = (VariableDotExp) stmt.getVar(); - List vList = v.getSegments(); - edu.clemson.cs.r2jt.collections.List newSegments = - new edu.clemson.cs.r2jt.collections.List(); - - // Loot through each variable expression and add it to our dot list - for (VariableExp vr : vList) { - VarExp varExp = new VarExp(); - if (vr instanceof VariableNameExp) { - varExp.setName(((VariableNameExp) vr) - .getName()); - varExp.setMathType(vr.getMathType()); - varExp.setMathTypeValue(vr - .getMathTypeValue()); - newSegments.add(varExp); - } - } - - // Expression to be replaced - leftVariable = - new DotExp(v.getLocation(), newSegments, - null); - leftVariable.setMathType(v.getMathType()); - leftVariable.setMathTypeValue(v.getMathTypeValue()); - } - // We have a regular variable being assigned. - else { - // Expression to be replaced - VariableNameExp v = (VariableNameExp) stmt.getVar(); - leftVariable = - new VarExp(v.getLocation(), null, v - .getName()); - leftVariable.setMathType(v.getMathType()); - leftVariable.setMathTypeValue(v.getMathTypeValue()); - } - - // Replace all instances of the left hand side - // variable in the current final confirm statement. - Exp newConf = myCurrentAssertiveCode.getFinalConfirm(); - newConf = replace(newConf, leftVariable, ensures); - - // Replace the formals with the actuals. - newConf = - replaceFormalWithActualEns(newConf, opDec - .getParameters(), opDec.getStateVars(), - assignParamExp.getArguments(), false); - - // Set this as our new final confirm statement. - myCurrentAssertiveCode.setFinalConfirm(newConf); - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - - // Verbose Mode Debug Messages - myVCBuffer.append("\nFunction Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the if statement rule to the - * Statement.

- * - * @param stmt Our current IfStmt. - */ - private void applyEBIfStmtRule(IfStmt stmt) { - // Note: In the If Rule, we will have two instances of the assertive code. - // One for when the if condition is true and one for the else condition. - // The current global assertive code variable is going to be used for the if path, - // and we are going to create a new assertive code for the else path (this includes - // the case when there is no else clause). - ProgramExp ifCondition = stmt.getTest(); - - // Negation of If (Need to make a copy before we start modifying - // the current assertive code for the if part) - AssertiveCode negIfAssertiveCode = - new AssertiveCode(myCurrentAssertiveCode); - - // TODO: Might need to take this out when we figure out the evaluates mode business - // Call a method to locate the operation dec for this call - PosSymbol qualifier = null; - ProgramParamExp testParamExp = null; - - // Check to see what kind of expression is on the right hand side - if (ifCondition instanceof ProgramParamExp) { - // Cast to a ProgramParamExp - testParamExp = (ProgramParamExp) ifCondition; - } - else if (ifCondition instanceof ProgramDotExp) { - // Cast to a ProgramParamExp - ProgramDotExp dotExp = (ProgramDotExp) ifCondition; - testParamExp = (ProgramParamExp) dotExp.getExp(); - qualifier = dotExp.getQualifier(); - } - else { - // TODO: ERROR! - } - OperationDec opDec = - getOperationDec(ifCondition.getLocation(), qualifier, - testParamExp.getName(), testParamExp.getArguments()); - - // Confirm the invoking condition - // Get the requires clause for this operation - Exp requires; - if (opDec.getRequires() != null) { - requires = Exp.copy(opDec.getRequires()); - } - else { - requires = myTypeGraph.getTrueVarExp(); - } - - // Replace PreCondition variables in the requires clause - requires = - replaceFormalWithActualReq(requires, opDec.getParameters(), - testParamExp.getArguments()); - - // Modify the location of the requires clause and add it to myCurrentAssertiveCode - // Obtain the current location - // Note: If we don't have a location, we create one - Location reqloc; - if (testParamExp.getName().getLocation() != null) { - reqloc = (Location) testParamExp.getName().getLocation().clone(); - } - else { - reqloc = new Location(null, null); - } - - // Append the name of the current procedure - String details = " from If Statement Condition"; - - // Set the details of the current location - reqloc.setDetails("Requires Clause of " + opDec.getName() + details); - setLocation(requires, reqloc); - - // Add this to our list of things to confirm - myCurrentAssertiveCode.addConfirm(requires); - - // Add the if condition as the assume clause - // Get the ensures clause for this operation - // Note: If there isn't an ensures clause, it is set to "True" - Exp ensures, negEnsures = null, opEnsures; - if (opDec.getEnsures() != null) { - opEnsures = Exp.copy(opDec.getEnsures()); - - // Make sure we have an EqualsExp, else it is an error. - if (opEnsures instanceof EqualsExp) { - // Has to be a VarExp on the left hand side (containing the name - // of the function operation) - if (((EqualsExp) opEnsures).getLeft() instanceof VarExp) { - VarExp leftExp = (VarExp) ((EqualsExp) opEnsures).getLeft(); - - // Check if it has the name of the operation - if (leftExp.getName().equals(opDec.getName())) { - ensures = ((EqualsExp) opEnsures).getRight(); - - // Obtain the current location - if (testParamExp.getName().getLocation() != null) { - // Set the details of the current location - Location loc = - (Location) testParamExp.getName() - .getLocation().clone(); - loc.setDetails("If Statement Condition"); - setLocation(ensures, loc); - } - - // Replace the formals with the actuals. - ensures = - replaceFormalWithActualEns(ensures, opDec - .getParameters(), opDec.getStateVars(), - testParamExp.getArguments(), false); - myCurrentAssertiveCode.addAssume(ensures); - - // Negation of the condition - negEnsures = negateExp(ensures); - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - } - - // Add any statements inside the then clause - if (stmt.getThenclause() != null) { - myCurrentAssertiveCode.addStatements(stmt.getThenclause()); - } - - // Modify the confirm details - Exp ifConfirm = myCurrentAssertiveCode.getFinalConfirm(); - String ifDetail = - " , If \"if\" condition at " - + ifCondition.getLocation().toString() + " is true"; - ifConfirm = appendToLocation(ifConfirm, ifDetail); - myCurrentAssertiveCode.setFinalConfirm(ifConfirm); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nIf Part Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - - // Add the negation of the if condition as the assume clause - if (negEnsures != null) { - negIfAssertiveCode.addAssume(negEnsures); - } - else { - illegalOperationEnsures(opDec.getLocation()); - } - - // Add any statements inside the else clause - if (stmt.getElseclause() != null) { - negIfAssertiveCode.addStatements(stmt.getElseclause()); - } - - // Modify the confirm details - Exp negIfConfirm = negIfAssertiveCode.getFinalConfirm(); - String negIfDetail = - " , If \"if\" condition at " - + ifCondition.getLocation().toString() + " is false"; - negIfConfirm = appendToLocation(negIfConfirm, negIfDetail); - negIfAssertiveCode.setFinalConfirm(negIfConfirm); - - // Add this new assertive code to our incomplete assertive code stack - myIncAssertiveCodeStack.push(negIfAssertiveCode); - - // Verbose Mode Debug Messages - String newString = "\nNegation of If Part Rule Applied: \n"; - newString += negIfAssertiveCode.assertionToString(); - newString += "\n_____________________ \n"; - myIncAssertiveCodeStackInfo.push(newString); - } - - /** - *

Applies the swap statement rule to the - * Statement.

- * - * @param stmt Our current SwapStmt. - */ - private void applyEBSwapStmtRule(SwapStmt stmt) { - // Obtain the current final confirm clause - Exp conf = myCurrentAssertiveCode.getFinalConfirm(); - - // Create a copy of the left and right hand side - VariableExp stmtLeft = (VariableExp) Exp.copy(stmt.getLeft()); - VariableExp stmtRight = (VariableExp) Exp.copy(stmt.getRight()); - - // New left and right - Exp newLeft = convertExp(stmtLeft); - Exp newRight = convertExp(stmtRight); - - // Use our final confirm to obtain the math types - List lst = conf.getSubExpressions(); - for (int i = 0; i < lst.size(); i++) { - if (lst.get(i) instanceof VarExp) { - VarExp thisExp = (VarExp) lst.get(i); - if (newRight instanceof VarExp) { - if (thisExp.getName().equals( - ((VarExp) newRight).getName().getName())) { - newRight.setMathType(thisExp.getMathType()); - newRight.setMathTypeValue(thisExp.getMathTypeValue()); - } - } - if (newLeft instanceof VarExp) { - if (thisExp.getName().equals( - ((VarExp) newLeft).getName().getName())) { - newLeft.setMathType(thisExp.getMathType()); - newLeft.setMathTypeValue(thisExp.getMathTypeValue()); - } - } - } - } - - // Temp variable - VarExp tmp = new VarExp(); - tmp.setName(createPosSymbol("_" + getVarName(stmtLeft).getName())); - tmp.setMathType(stmtLeft.getMathType()); - tmp.setMathTypeValue(stmtLeft.getMathTypeValue()); - - // Replace according to the swap rule - conf = replace(conf, newRight, tmp); - conf = replace(conf, newLeft, newRight); - conf = replace(conf, tmp, newLeft); - - // Set this new expression as the new final confirm - myCurrentAssertiveCode.setFinalConfirm(conf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nSwap Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the while statement rule.

- * - * @param stmt Our current WhileStmt. - */ - private void applyEBWhileStmtRule(WhileStmt stmt) { - // Obtain the loop invariant - Exp invariant; - if (stmt.getMaintaining() != null) { - invariant = Exp.copy(stmt.getMaintaining()); - invariant.setMathType(stmt.getMaintaining().getMathType()); - } - else { - invariant = myTypeGraph.getTrueVarExp(); - } - - Location loc; - if (invariant.getLocation() != null) { - loc = (Location) invariant.getLocation().clone(); - } - else { - loc = (Location) stmt.getLocation().clone(); - } - loc.setDetails("Base Case of the Invariant of While Statement"); - setLocation(invariant, loc); - - // Confirm the invariant - myCurrentAssertiveCode.addConfirm(invariant); - - // Add the change rule - if (stmt.getChanging() != null) { - myCurrentAssertiveCode.addChange(stmt.getChanging()); - } - - // Assume the invariant and NQV(RP, P_Val) = P_Exp - Location whileLoc = stmt.getLocation(); - Exp assume; - Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); - Exp decreasingExp = stmt.getDecreasing(); - Exp nqv; - - if (decreasingExp != null) { - VarExp pval = createPValExp((Location) whileLoc.clone()); - nqv = createQuestionMarkVariable(finalConfirm, pval); - nqv.setMathType(pval.getMathType()); - Exp equalPExp = - new EqualsExp((Location) whileLoc.clone(), Exp.copy(nqv), - 1, Exp.copy(decreasingExp)); - equalPExp.setMathType(BOOLEAN); - assume = myTypeGraph.formConjunct(Exp.copy(invariant), equalPExp); - } - else { - decreasingExp = myTypeGraph.getTrueVarExp(); - nqv = myTypeGraph.getTrueVarExp(); - assume = Exp.copy(invariant); - } - - myCurrentAssertiveCode.addAssume(assume); - - // Create an if statement from the loop - Exp ifConfirm; - if (decreasingExp != null) { - Location decreasingLoc = - (Location) decreasingExp.getLocation().clone(); - if (decreasingLoc != null) { - decreasingLoc.setDetails("Termination of While Statement"); - } - - Exp maintainingInv = Exp.copy(invariant); - Location maintainingLoc = - (Location) invariant.getLocation().clone(); - if (maintainingLoc != null) { - maintainingLoc - .setDetails("Inductive Case of Invariant of While Statement"); - maintainingInv.setLocation(maintainingLoc); - } - - Exp infixExp = - new InfixExp(decreasingLoc, Exp.copy(decreasingExp), - createPosSymbol("<"), Exp.copy(nqv)); - infixExp.setMathType(BOOLEAN); - ifConfirm = myTypeGraph.formConjunct(maintainingInv, infixExp); - } - else { - ifConfirm = myTypeGraph.getTrueVarExp(); - } - - // if statement body - Location ifConfirmLoc = (Location) whileLoc.clone(); - edu.clemson.cs.r2jt.collections.List ifStmtList = - stmt.getStatements(); - ifStmtList.add(new ConfirmStmt(ifConfirmLoc, ifConfirm)); - - // empty elseif pair - edu.clemson.cs.r2jt.collections.List elseIfPairList = - new edu.clemson.cs.r2jt.collections.List(); - - // else body - Location elseConfirmLoc; - if (finalConfirm.getLocation() != null) { - elseConfirmLoc = (Location) finalConfirm.getLocation().clone(); - } - else { - elseConfirmLoc = (Location) whileLoc.clone(); - } - edu.clemson.cs.r2jt.collections.List elseStmtList = - new edu.clemson.cs.r2jt.collections.List(); - elseStmtList - .add(new ConfirmStmt(elseConfirmLoc, Exp.copy(finalConfirm))); - - // condition - ProgramExp condition = (ProgramExp) Exp.copy(stmt.getTest()); - if (condition.getLocation() != null) { - Location condLoc = (Location) condition.getLocation().clone(); - condLoc.setDetails("While Loop Condition"); - setLocation(condition, condLoc); - } - - // add it back to your assertive code - IfStmt newIfStmt = - new IfStmt(condition, ifStmtList, elseIfPairList, elseStmtList); - myCurrentAssertiveCode.addCode(newIfStmt); - - // Change our final confirm to "True" - Exp trueVarExp = myTypeGraph.getTrueVarExp(); - trueVarExp.setLocation((Location) whileLoc.clone()); - myCurrentAssertiveCode.setFinalConfirm(trueVarExp); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nWhile Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the procedure declaration rule.

- * - * @param requires Requires clause - * @param ensures Ensures clause - * @param decreasing Decreasing clause (if any) - * @param variableList List of all variables for this procedure - * @param statementList List of statements for this procedure - */ - private void applyProcedureDeclRule(Exp requires, Exp ensures, - Exp decreasing, List variableList, - List statementList) { - // Add the global requires clause - if (myGlobalRequiresExp != null) { - myCurrentAssertiveCode.addAssume(myGlobalRequiresExp); - } - - // Add the global constraints - if (myGlobalConstraintExp != null) { - myCurrentAssertiveCode.addAssume(myGlobalConstraintExp); - } - - // Add the requires clause - if (requires != null) { - myCurrentAssertiveCode.addAssume(requires); - } - - // Add the remember rule - myCurrentAssertiveCode.addRemember(); - - // Add declared variables into the assertion. Also add - // them to the list of free variables. - myCurrentAssertiveCode.addVariableDecs(variableList); - addVarDecsAsFreeVars(variableList); - - // Check to see if we have a recursive procedure. - // If yes, we will need to create an additional assume clause - // (P_val = (decreasing clause)) in our list of assertions. - if (decreasing != null) { - // Store for future use - myOperationDecreasingExp = decreasing; - - // Add P_val as a free variable - VarExp pVal = createPValExp(decreasing.getLocation()); - myCurrentAssertiveCode.addFreeVar(pVal); - - // Create an equals expression - EqualsExp equalsExp = - new EqualsExp(null, pVal, EqualsExp.EQUAL, Exp - .copy(decreasing)); - equalsExp.setMathType(BOOLEAN); - Location eqLoc = (Location) decreasing.getLocation().clone(); - eqLoc.setDetails("Progress Metric for Recursive Procedure"); - setLocation(equalsExp, eqLoc); - - // Add it to our things to assume - myCurrentAssertiveCode.addAssume(equalsExp); - } - - // Add the list of statements - myCurrentAssertiveCode.addStatements(statementList); - - // Add the final confirms clause - myCurrentAssertiveCode.setFinalConfirm(ensures); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nProcedure Declaration Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the remember rule.

- */ - private void applyRememberRule() { - // Obtain the final confirm and apply the remember method for Exp - Exp conf = myCurrentAssertiveCode.getFinalConfirm(); - conf = conf.remember(); - myCurrentAssertiveCode.setFinalConfirm(conf); - - // Verbose Mode Debug Messages - myVCBuffer.append("\nRemember Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - - /** - *

Applies the variable declaration rule.

- * - * @param var A declared variable stored as a - * VerificationStatement - */ - private void applyVarDeclRule(VerificationStatement var) { - // Obtain the variable from the verification statement - VarDec varDec = (VarDec) var.getAssertion(); - ProgramTypeEntry typeEntry; - - // Ty is NameTy - if (varDec.getTy() instanceof NameTy) { - NameTy pNameTy = (NameTy) varDec.getTy(); - - // Query for the type entry in the symbol table - typeEntry = - searchProgramType(pNameTy.getLocation(), pNameTy.getName()); - - // Make sure we don't have a generic type - if (typeEntry.getDefiningElement() instanceof TypeDec) { - // Obtain the original dec from the AST - TypeDec type = (TypeDec) typeEntry.getDefiningElement(); - - // Deep copy the original initialization ensures - Exp init = Exp.copy(type.getInitialization().getEnsures()); - - // Make sure we have a constraint - Exp constraint; - if (type.getConstraint() == null) { - constraint = myTypeGraph.getTrueVarExp(); - } - else { - constraint = Exp.copy(type.getConstraint()); - } - - // Set the location for the constraint - Location loc; - if (constraint.getLocation() != null) { - loc = (Location) constraint.getLocation().clone(); - } - else { - loc = (Location) type.getLocation().clone(); - } - loc.setDetails("Constraints on " + varDec.getName().getName()); - setLocation(constraint, loc); - - // Final confirm clause - Exp finalConfirm = myCurrentAssertiveCode.getFinalConfirm(); - - // Check if our initialization ensures clause is - // in simple form. - if (isInitEnsuresSimpleForm(init)) { - // Only deal with initialization ensures of the - // form left = right - if (init instanceof EqualsExp) { - EqualsExp exp = (EqualsExp) init; - VarExp varDecExp = - createVarExp(varDec.getLocation(), varDec - .getName(), typeEntry.getModelType()); - - // Replace all instances of this variable with initialization - // ensures clause of the variable type. - finalConfirm = - replace(finalConfirm, varDecExp, exp.getRight()); - - // Set that as our new final confirm - myCurrentAssertiveCode.setFinalConfirm(finalConfirm); - } - } - // We must have a complex initialization ensures clause - else { - // The variable must be a variable dot expression, - // therefore we will need to extract the name. - String varName = varDec.getName().getName(); - int dotIndex = varName.indexOf("."); - if (dotIndex > 0) - varName = varName.substring(0, dotIndex); - - // Check if our confirm clause uses this variable - if (finalConfirm.containsVar(varName, false)) { - // We don't have any constraints, so the initialization - // clause implies the final confirm statement and - // set this as our new final confirm statement. - if (constraint.equals(myTypeGraph.getTrueVarExp())) { - myCurrentAssertiveCode.setFinalConfirm(myTypeGraph - .formImplies(init, finalConfirm)); - } - // We actually have a constraint, so both the initialization - // and constraint imply the final confirm statement. - // This then becomes our new final confirm statement. - else { - InfixExp exp = - myTypeGraph.formConjunct(constraint, init); - myCurrentAssertiveCode.setFinalConfirm(myTypeGraph - .formImplies(exp, finalConfirm)); - } - } - } - } - // Since the type is generic, we can only use the is_initial predicate - // to ensure that the value is initial value. - else { - // Obtain the original dec from the AST - Location varLoc = varDec.getLocation(); - - // Create an is_initial dot expression - DotExp isInitialExp = createInitExp(varDec); - if (varLoc != null) { - Location loc = (Location) varLoc.clone(); - loc.setDetails("Initial Value for " - + varDec.getName().getName()); - setLocation(isInitialExp, loc); - } - - // Add to our assertive code as an assume - myCurrentAssertiveCode.addAssume(isInitialExp); - } - - // Verbose Mode Debug Messages - myVCBuffer.append("\nVariable Declaration Rule Applied: \n"); - myVCBuffer.append(myCurrentAssertiveCode.assertionToString()); - myVCBuffer.append("\n_____________________ \n"); - } - else { - // Ty not handled. - tyNotHandled(varDec.getTy(), varDec.getLocation()); - } - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/pair.info deleted file mode 100755 index 76f3bde..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#55702/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:55702 -comSha:c7bb6ca7f2cb2e3049306ed02fad3daa9f9ce85b -parentComSha:4a059c613586188aa7787c5eaaf5d850290ddf30 -BuggyFilePath:src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java -FixedFilePath:src/main/java/edu/clemson/cs/r2jt/vcgeneration/VCGenerator.java -StartLineNum:1213 -EndLineNum:1213 -repoName:ClemsonRSRG#RESOLVE \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/comMsg.txt deleted file mode 100755 index bb18407..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Correção do encode do título da mensagem \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/diff.diff deleted file mode 100755 index cf96b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/src/main/java/br/com/dbsoft/mail/DBSEmailSend.java b/src/main/java/br/com/dbsoft/mail/DBSEmailSend.java -index dddd1d0..4e287c2 100644 ---- a/src/main/java/br/com/dbsoft/mail/DBSEmailSend.java -+++ b/src/main/java/br/com/dbsoft/mail/DBSEmailSend.java -@@ -142 +142 @@ public class DBSEmailSend { -- Message xMessage = new MimeMessage(xMailSession); -+ MimeMessage xMessage = new MimeMessage(xMailSession); -@@ -194 +194 @@ public class DBSEmailSend { -- xMessage.setSubject(pMessage.getSubject()); -+ xMessage.setSubject(pMessage.getSubject(), ENCODE.ISO_8859_1); -@@ -196 +196 @@ public class DBSEmailSend { -- xMessageBodyPart.setContent(pMessage.getText(), CONTENT_TYPE.TEXT_HTML + "; charset=" + ENCODE.UTF_8.toLowerCase()); -+ xMessageBodyPart.setContent(pMessage.getText(), CONTENT_TYPE.TEXT_HTML + "; charset=" + ENCODE.UTF_8); -@@ -197,0 +198 @@ public class DBSEmailSend { -+ xMessageBodyPart.setContent(pMessage.getText(), CONTENT_TYPE.TEXT_PLAIN + "; charset=" + ENCODE.UTF_8); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/new/DBSEmailSend.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/new/DBSEmailSend.java deleted file mode 100755 index 4e287c2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/new/DBSEmailSend.java +++ /dev/null @@ -1,268 +0,0 @@ -package br.com.dbsoft.mail; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.mail.Authenticator; -import javax.mail.BodyPart; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.PasswordAuthentication; -import javax.mail.SendFailedException; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; -import javax.mail.Message.RecipientType; - -import org.apache.log4j.Logger; - -import br.com.dbsoft.core.DBSSDK.CONTENT_TYPE; -import br.com.dbsoft.core.DBSSDK.ENCODE; -import br.com.dbsoft.core.DBSSDK.NETWORK.PROTOCOL; -import br.com.dbsoft.util.DBSFile; -import br.com.dbsoft.util.DBSEmail; -import br.com.dbsoft.util.DBSObject; - - -public class DBSEmailSend { - - protected static Logger wLogger = Logger.getLogger(DBSEmailSend.class); - - private String wHostUserName; - private String wHostPassword; - private String wHost; - private String wHostPort = "587"; - private PROTOCOL wProtocol; - private String wProtocolString; - private List wInvalidEmails = new ArrayList(); - - - public DBSEmailSend(){ - setProtocol(null); - } - - //================================================================================================================ - /** - * Conta do usuário no servidor de email - * @return - */ - public String getHostUserName() {return wHostUserName;} - /** - * Conta do usuário no servidor de email - * @return - */ - public void setHostUserName(String pHostUserName) {wHostUserName = pHostUserName;} - - /** - * Senha do usuário no servidor de email - * @return - */ - public String getHostPassword() {return wHostPassword;} - /** - * Senha do usuário no servidor de email - * @return - */ - public void setHostPassword(String pHostPassword) {wHostPassword = pHostPassword;} - - /** - * Servidor SMTP de email - * @return - */ - public String getHost() {return wHost;} - /** - * Servidor SMTP de email - * @return - */ - public void setHost(String pHost) {wHost = pHost;} - - /** - * Porta do servidor de email - * @return - */ - public String getHostPort() {return wHostPort;} - /** - * Porta do servidor de email - * @return - */ - public void setHostPort(String pHostPort) {wHostPort = pHostPort;} - - /** - * Protocolo smtp - * @return - */ - public PROTOCOL getProtocol() {return wProtocol;} - /** - * Protocolo smtp - * @return - */ - public void setProtocol(PROTOCOL pProtocol) { - wProtocol = pProtocol; - if (pProtocol == null){ - wProtocolString = "smtp"; - }else if (pProtocol == PROTOCOL.SSL){ - wProtocolString = "smtps"; - } - } - - public String getProtocolString() {return wProtocolString;} - - /** - * Retorna emails inválidos - * @return - */ - public List getInvalidEmails(){ - return wInvalidEmails; - } - //================================================================================================================ - /** - * Envia o email para os endereço informados.
- * Endereço de email inválidos serão adicionados o atributo invalidEmails. - * @param pMessage - * @return - */ - public boolean send(DBSEmailMessage pMessage){ - wInvalidEmails.clear(); - if (pMessage == null - || DBSObject.isEmpty(pMessage.getFrom()) - || DBSObject.isEmpty(pMessage.getTo()) - || DBSObject.isEmpty(pMessage.getSubject())){ - return false; - } - Properties xProps = new Properties(); - Session xMailSession = Session.getInstance(xProps, new SMTPAuthenticator()); - MimeMessage xMessage = new MimeMessage(xMailSession); - InternetAddress xFromAddress = null; - Transport xTransport; - BodyPart xMessageBodyPart = new MimeBodyPart(); - Multipart xMultipart; - - xProps.put("mail.transport.protocol", wProtocolString); - xProps.put("mail." + wProtocolString + ".host", wHost); - xProps.put("mail." + wProtocolString + ".port", wHostPort); - - if (!DBSObject.isEmpty(wHostUserName) - && !DBSObject.isEmpty(wHostPassword)){ - xProps.put("mail." + wProtocolString + ".auth", "true"); - } - - if (wProtocol != null){ - if (wProtocol == PROTOCOL.SSL){ - xProps.put("mail." + wProtocolString + ".ssl.enable", "true"); - xProps.put("mail." + wProtocolString + ".ssl.required", "true"); - } else if (wProtocol == PROTOCOL.STARTTLS){ - xProps.put("mail.smtp.starttls.enable", "true"); - xProps.put("mail.smtp.socketFactory.port", wHostPort); - xProps.put("mail.smtp.socketFactory.fallback", "false"); - xProps.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); - } else if (wProtocol == PROTOCOL.TLS){ - xProps.put("mail.smtp.starttls.enable", "true"); - } - } - - try { - //FROM - xFromAddress = new InternetAddress(pMessage.getFrom().getAddress()); - xFromAddress.setPersonal(pMessage.getFrom().getName()); - xMessage.setFrom(xFromAddress); - - //TO --------------------- - for (DBSEmailAddress xEmailAddress:DBSEmail.validateEmailAddress(pMessage.getTo())){ //ALBERTO: Adicionada validação de lista de E-mails. Em 26/03/2015. - pvAddRecipient(xMessage, RecipientType.TO, xEmailAddress); - } - //CC --------------------- - for (DBSEmailAddress xEmailAddress:pMessage.getCC()){ - pvAddRecipient(xMessage, RecipientType.CC, xEmailAddress); - } - //BCC --------------------- - for (DBSEmailAddress xEmailAddress:pMessage.getBCC()){ - pvAddRecipient(xMessage, RecipientType.BCC, xEmailAddress); - } - if (xMessage.getAllRecipients() == null){ - return false; - } - - //Texto da mensagem---------- - xMessage.setSubject(pMessage.getSubject(), ENCODE.ISO_8859_1); - if (pMessage.getIsHtmlContent()){ - xMessageBodyPart.setContent(pMessage.getText(), CONTENT_TYPE.TEXT_HTML + "; charset=" + ENCODE.UTF_8); - }else{ - xMessageBodyPart.setContent(pMessage.getText(), CONTENT_TYPE.TEXT_PLAIN + "; charset=" + ENCODE.UTF_8); - xMessageBodyPart.setText(pMessage.getText()); - } - xMultipart = new MimeMultipart(); - xMultipart.addBodyPart(xMessageBodyPart); - - //Anexos--------------------- - for (String xFilename:pMessage.getAttachments()){ - xMessageBodyPart = new MimeBodyPart(); - DataSource source = new FileDataSource(xFilename); - xMessageBodyPart.setDataHandler(new DataHandler(source)); - xMessageBodyPart.setFileName(DBSFile.getFileNameFromPath(xFilename)); - xMultipart.addBodyPart(xMessageBodyPart); - } - - - //Envio----------------------------------- - xMessage.setContent(xMultipart); - - xTransport = xMailSession.getTransport(wProtocolString.toString()); - xTransport.connect(); - xMessage.saveChanges(); - xTransport.sendMessage(xMessage, xMessage.getAllRecipients()); - xTransport.close(); - return true; - } catch (SendFailedException e) { - wLogger.error(e); - } catch (AddressException e) { - wLogger.error(e); - } catch (MessagingException e) { - wLogger.error(e); - } catch (UnsupportedEncodingException e) { - wLogger.error(e); - } - return false; - - } - - private class SMTPAuthenticator extends Authenticator { - @Override - public PasswordAuthentication getPasswordAuthentication() { - String username = wHostUserName; - String password = wHostPassword; - return new PasswordAuthentication(username, password); - } - } - - private void pvAddRecipient(Message pMessage, RecipientType pRecipientType, DBSEmailAddress pEmailAddress) throws MessagingException, UnsupportedEncodingException{ - if (pMessage == null - || pRecipientType == null - || pEmailAddress == null - || DBSObject.isEmpty(pEmailAddress.getAddress())){ - return; - } - - if (!DBSEmail.isValidEmailAddress(pEmailAddress.getAddress())){ - wInvalidEmails.add(pEmailAddress); - } - - InternetAddress xToAddress = new InternetAddress(pEmailAddress.getAddress()); - if (DBSObject.isEmpty(pEmailAddress.getName())){ - xToAddress.setPersonal(pEmailAddress.getAddress()); - }else{ - xToAddress.setPersonal(pEmailAddress.getName()); - } - pMessage.addRecipient(pRecipientType, xToAddress); - } - - - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/old/DBSEmailSend.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/old/DBSEmailSend.java deleted file mode 100755 index dddd1d0..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/old/DBSEmailSend.java +++ /dev/null @@ -1,267 +0,0 @@ -package br.com.dbsoft.mail; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import javax.activation.DataHandler; -import javax.activation.DataSource; -import javax.activation.FileDataSource; -import javax.mail.Authenticator; -import javax.mail.BodyPart; -import javax.mail.Message; -import javax.mail.MessagingException; -import javax.mail.Multipart; -import javax.mail.PasswordAuthentication; -import javax.mail.SendFailedException; -import javax.mail.Session; -import javax.mail.Transport; -import javax.mail.internet.AddressException; -import javax.mail.internet.InternetAddress; -import javax.mail.internet.MimeBodyPart; -import javax.mail.internet.MimeMessage; -import javax.mail.internet.MimeMultipart; -import javax.mail.Message.RecipientType; - -import org.apache.log4j.Logger; - -import br.com.dbsoft.core.DBSSDK.CONTENT_TYPE; -import br.com.dbsoft.core.DBSSDK.ENCODE; -import br.com.dbsoft.core.DBSSDK.NETWORK.PROTOCOL; -import br.com.dbsoft.util.DBSFile; -import br.com.dbsoft.util.DBSEmail; -import br.com.dbsoft.util.DBSObject; - - -public class DBSEmailSend { - - protected static Logger wLogger = Logger.getLogger(DBSEmailSend.class); - - private String wHostUserName; - private String wHostPassword; - private String wHost; - private String wHostPort = "587"; - private PROTOCOL wProtocol; - private String wProtocolString; - private List wInvalidEmails = new ArrayList(); - - - public DBSEmailSend(){ - setProtocol(null); - } - - //================================================================================================================ - /** - * Conta do usuário no servidor de email - * @return - */ - public String getHostUserName() {return wHostUserName;} - /** - * Conta do usuário no servidor de email - * @return - */ - public void setHostUserName(String pHostUserName) {wHostUserName = pHostUserName;} - - /** - * Senha do usuário no servidor de email - * @return - */ - public String getHostPassword() {return wHostPassword;} - /** - * Senha do usuário no servidor de email - * @return - */ - public void setHostPassword(String pHostPassword) {wHostPassword = pHostPassword;} - - /** - * Servidor SMTP de email - * @return - */ - public String getHost() {return wHost;} - /** - * Servidor SMTP de email - * @return - */ - public void setHost(String pHost) {wHost = pHost;} - - /** - * Porta do servidor de email - * @return - */ - public String getHostPort() {return wHostPort;} - /** - * Porta do servidor de email - * @return - */ - public void setHostPort(String pHostPort) {wHostPort = pHostPort;} - - /** - * Protocolo smtp - * @return - */ - public PROTOCOL getProtocol() {return wProtocol;} - /** - * Protocolo smtp - * @return - */ - public void setProtocol(PROTOCOL pProtocol) { - wProtocol = pProtocol; - if (pProtocol == null){ - wProtocolString = "smtp"; - }else if (pProtocol == PROTOCOL.SSL){ - wProtocolString = "smtps"; - } - } - - public String getProtocolString() {return wProtocolString;} - - /** - * Retorna emails inválidos - * @return - */ - public List getInvalidEmails(){ - return wInvalidEmails; - } - //================================================================================================================ - /** - * Envia o email para os endereço informados.
- * Endereço de email inválidos serão adicionados o atributo invalidEmails. - * @param pMessage - * @return - */ - public boolean send(DBSEmailMessage pMessage){ - wInvalidEmails.clear(); - if (pMessage == null - || DBSObject.isEmpty(pMessage.getFrom()) - || DBSObject.isEmpty(pMessage.getTo()) - || DBSObject.isEmpty(pMessage.getSubject())){ - return false; - } - Properties xProps = new Properties(); - Session xMailSession = Session.getInstance(xProps, new SMTPAuthenticator()); - Message xMessage = new MimeMessage(xMailSession); - InternetAddress xFromAddress = null; - Transport xTransport; - BodyPart xMessageBodyPart = new MimeBodyPart(); - Multipart xMultipart; - - xProps.put("mail.transport.protocol", wProtocolString); - xProps.put("mail." + wProtocolString + ".host", wHost); - xProps.put("mail." + wProtocolString + ".port", wHostPort); - - if (!DBSObject.isEmpty(wHostUserName) - && !DBSObject.isEmpty(wHostPassword)){ - xProps.put("mail." + wProtocolString + ".auth", "true"); - } - - if (wProtocol != null){ - if (wProtocol == PROTOCOL.SSL){ - xProps.put("mail." + wProtocolString + ".ssl.enable", "true"); - xProps.put("mail." + wProtocolString + ".ssl.required", "true"); - } else if (wProtocol == PROTOCOL.STARTTLS){ - xProps.put("mail.smtp.starttls.enable", "true"); - xProps.put("mail.smtp.socketFactory.port", wHostPort); - xProps.put("mail.smtp.socketFactory.fallback", "false"); - xProps.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); - } else if (wProtocol == PROTOCOL.TLS){ - xProps.put("mail.smtp.starttls.enable", "true"); - } - } - - try { - //FROM - xFromAddress = new InternetAddress(pMessage.getFrom().getAddress()); - xFromAddress.setPersonal(pMessage.getFrom().getName()); - xMessage.setFrom(xFromAddress); - - //TO --------------------- - for (DBSEmailAddress xEmailAddress:DBSEmail.validateEmailAddress(pMessage.getTo())){ //ALBERTO: Adicionada validação de lista de E-mails. Em 26/03/2015. - pvAddRecipient(xMessage, RecipientType.TO, xEmailAddress); - } - //CC --------------------- - for (DBSEmailAddress xEmailAddress:pMessage.getCC()){ - pvAddRecipient(xMessage, RecipientType.CC, xEmailAddress); - } - //BCC --------------------- - for (DBSEmailAddress xEmailAddress:pMessage.getBCC()){ - pvAddRecipient(xMessage, RecipientType.BCC, xEmailAddress); - } - if (xMessage.getAllRecipients() == null){ - return false; - } - - //Texto da mensagem---------- - xMessage.setSubject(pMessage.getSubject()); - if (pMessage.getIsHtmlContent()){ - xMessageBodyPart.setContent(pMessage.getText(), CONTENT_TYPE.TEXT_HTML + "; charset=" + ENCODE.UTF_8.toLowerCase()); - }else{ - xMessageBodyPart.setText(pMessage.getText()); - } - xMultipart = new MimeMultipart(); - xMultipart.addBodyPart(xMessageBodyPart); - - //Anexos--------------------- - for (String xFilename:pMessage.getAttachments()){ - xMessageBodyPart = new MimeBodyPart(); - DataSource source = new FileDataSource(xFilename); - xMessageBodyPart.setDataHandler(new DataHandler(source)); - xMessageBodyPart.setFileName(DBSFile.getFileNameFromPath(xFilename)); - xMultipart.addBodyPart(xMessageBodyPart); - } - - - //Envio----------------------------------- - xMessage.setContent(xMultipart); - - xTransport = xMailSession.getTransport(wProtocolString.toString()); - xTransport.connect(); - xMessage.saveChanges(); - xTransport.sendMessage(xMessage, xMessage.getAllRecipients()); - xTransport.close(); - return true; - } catch (SendFailedException e) { - wLogger.error(e); - } catch (AddressException e) { - wLogger.error(e); - } catch (MessagingException e) { - wLogger.error(e); - } catch (UnsupportedEncodingException e) { - wLogger.error(e); - } - return false; - - } - - private class SMTPAuthenticator extends Authenticator { - @Override - public PasswordAuthentication getPasswordAuthentication() { - String username = wHostUserName; - String password = wHostPassword; - return new PasswordAuthentication(username, password); - } - } - - private void pvAddRecipient(Message pMessage, RecipientType pRecipientType, DBSEmailAddress pEmailAddress) throws MessagingException, UnsupportedEncodingException{ - if (pMessage == null - || pRecipientType == null - || pEmailAddress == null - || DBSObject.isEmpty(pEmailAddress.getAddress())){ - return; - } - - if (!DBSEmail.isValidEmailAddress(pEmailAddress.getAddress())){ - wInvalidEmails.add(pEmailAddress); - } - - InternetAddress xToAddress = new InternetAddress(pEmailAddress.getAddress()); - if (DBSObject.isEmpty(pEmailAddress.getName())){ - xToAddress.setPersonal(pEmailAddress.getAddress()); - }else{ - xToAddress.setPersonal(pEmailAddress.getName()); - } - pMessage.addRecipient(pRecipientType, xToAddress); - } - - - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/pair.info deleted file mode 100755 index a2d2aa7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#68628/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:68628 -comSha:423e12ec265597bc196635b7b7a4e07570ccae59 -parentComSha:849beb061a04b8f5826c0e039533d4da559a4e80 -BuggyFilePath:src/main/java/br/com/dbsoft/mail/DBSEmailSend.java -FixedFilePath:src/main/java/br/com/dbsoft/mail/DBSEmailSend.java -StartLineNum:196 -EndLineNum:196 -repoName:dbsoftcombr#dbssdk \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/comMsg.txt deleted file mode 100755 index 2f85758..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Minor clean up \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/diff.diff deleted file mode 100755 index 026eb2c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/org/swrlapi/ui/dialog/SWRLRuleEditorDialog.java b/src/main/java/org/swrlapi/ui/dialog/SWRLRuleEditorDialog.java -index 85eef06..5d8751c 100644 ---- a/src/main/java/org/swrlapi/ui/dialog/SWRLRuleEditorDialog.java -+++ b/src/main/java/org/swrlapi/ui/dialog/SWRLRuleEditorDialog.java -@@ -188,3 +188,3 @@ public class SWRLRuleEditorDialog extends JDialog -- ruleName = ruleNameTextField.getText().trim().toUpperCase(); -- ruleText = ruleTextTextArea.getText().trim().toUpperCase(); -- comment = commentTextField.getText().trim().toUpperCase(); -+ ruleName = ruleNameTextField.getText().trim(); -+ ruleText = ruleTextTextArea.getText().trim(); -+ comment = commentTextField.getText().trim(); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/new/SWRLRuleEditorDialog.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/new/SWRLRuleEditorDialog.java deleted file mode 100755 index 5d8751c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/new/SWRLRuleEditorDialog.java +++ /dev/null @@ -1,225 +0,0 @@ -package org.swrlapi.ui.dialog; - -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.text.BadLocationException; -import javax.swing.text.JTextComponent; - -import org.swrlapi.parser.SWRLIncompleteRuleException; -import org.swrlapi.parser.SWRLParseException; -import org.swrlapi.parser.SWRLParser; -import org.swrlapi.ui.controller.SWRLAPIApplicationController; -import org.swrlapi.ui.model.SWRLRulesTableModel; - -public class SWRLRuleEditorDialog extends JDialog -{ - private static final long serialVersionUID = 1L; - - private static final String TITLE = "Edit SWRL Rule"; - private static final String INVALID_RULE_TITLE = "Invalid Rule"; - private static final int BUTTON_PREFERRED_WIDTH = 100; - private static final int BUTTON_PREFERRED_HEIGHT = 30; - - private final SWRLAPIApplicationController applicationController; - - private JTextField ruleNameTextField, commentTextField; - private JTextArea ruleTextTextArea; - - private boolean editMode = false; - - public SWRLRuleEditorDialog(SWRLAPIApplicationController applicationController) - { - this.applicationController = applicationController; - - setTitle(TITLE); - setModal(true); - - createComponents(); - this.ruleTextTextArea.addKeyListener(new SWRLRuleEditorKeyAdapter()); - - setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); - - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent we) - { - } - }); // Thwart user close - } - - public void reset() - { - clearEntryFields(); - } - - public void setEditData(String ruleName, String ruleText, String comment) - { - clearEntryFields(); - - ruleNameTextField.setText(ruleName); - ruleTextTextArea.setText(ruleText); - commentTextField.setText(comment); - - editMode = true; - } - - private void clearEntryFields() - { - ruleNameTextField.setText(""); - ruleNameTextField.setEnabled(true); - ruleTextTextArea.setText(""); - ruleTextTextArea.setEnabled(true); - ruleTextTextArea.setText(""); - commentTextField.setText(""); - - editMode = false; - } - - private void createComponents() - { - Container contentPane = getContentPane(); - - JLabel ruleNameLabel = new JLabel("Name"); - ruleNameTextField = new JTextField(""); - - JLabel ruleTextLabel = new JLabel("Body"); - ruleTextTextArea = new JTextArea("", 20, 60); - ruleTextTextArea.setBorder(BorderFactory.createLoweredBevelBorder()); - - JLabel commentLabel = new JLabel("Comment"); - commentTextField = new JTextField(""); - - JButton cancelButton = new JButton("Cancel"); - cancelButton.setPreferredSize(new Dimension(BUTTON_PREFERRED_WIDTH, BUTTON_PREFERRED_HEIGHT)); - cancelButton.addActionListener(new CancelSWRLRuleEditActionListener()); - - JButton okButton = new JButton("OK"); - okButton.setPreferredSize(new Dimension(BUTTON_PREFERRED_WIDTH, BUTTON_PREFERRED_HEIGHT)); - okButton.addActionListener(new OkSWRLRuleEditActionListener()); - - contentPane.setLayout(new BorderLayout()); - - JPanel surroundPanel = new JPanel(new BorderLayout()); - surroundPanel.setBorder(BorderFactory.createLoweredBevelBorder()); - contentPane.add(surroundPanel, BorderLayout.CENTER); - - JPanel innerPanel = new JPanel(new GridLayout(6, 2)); - - surroundPanel.add(innerPanel, BorderLayout.NORTH); - surroundPanel.add(ruleTextTextArea, BorderLayout.CENTER); - - innerPanel.add(ruleNameLabel); - innerPanel.add(ruleNameTextField); - innerPanel.add(commentLabel); - innerPanel.add(commentTextField); - innerPanel.add(ruleTextLabel); - - JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); - buttonPanel.add(cancelButton); - buttonPanel.add(okButton); - - surroundPanel.add(buttonPanel, BorderLayout.SOUTH); - - pack(); - } - - private class SWRLRuleEditorKeyAdapter extends KeyAdapter - { - @Override - public void keyTyped(KeyEvent event) - { - char ch = event.getKeyChar(); - JTextComponent component = (JTextComponent)event.getSource(); - try { - String ruleText = component.getDocument().getText(0, component.getCaretPosition()).trim(); - ruleText += ch; - // System.out.println("ch: " + ch); - System.out.println("ruleText: " + ruleText); - - if (ruleText.length() != 0) - getSWRLParser().parseSWRLRule(ruleText, true); - } catch (SWRLIncompleteRuleException e) { - System.out.println("Incomplete " + e.getMessage()); - } catch (SWRLParseException e) { - System.err.println("Error " + e.getMessage()); - } catch (BadLocationException e) { - } - } - } - - private class CancelSWRLRuleEditActionListener implements ActionListener - { - @Override - public void actionPerformed(ActionEvent e) - { - clearEntryFields(); - setVisible(false); - } - } - - private class OkSWRLRuleEditActionListener implements ActionListener - { - @Override - public void actionPerformed(ActionEvent e) - { - String ruleName = "", ruleText = "", comment = ""; - boolean errorOccurred = false; - - comment = ruleNameTextField.getText(); - - try { - ruleName = ruleNameTextField.getText().trim(); - ruleText = ruleTextTextArea.getText().trim(); - comment = commentTextField.getText().trim(); - - // TODO Check the rule and name - } catch (Exception ex) { - getApplicationDialogManager().showErrorMessageDialog(ex.getMessage(), INVALID_RULE_TITLE); - errorOccurred = true; - } - - if (!errorOccurred) { - if (editMode) { - getSWRLRulesModel().removeSWRLRule(ruleName); // Remove original - getSWRLRulesModel().addSWRLRule(ruleName, ruleText, comment); - } else { - getSWRLRulesModel().addSWRLRule(ruleName, ruleText, comment); - } - setVisible(false); - clearEntryFields(); - } - } - } - - private SWRLParser getSWRLParser() - { - return applicationController.getApplicationModel().getSWRLParser(); - } - - private SWRLRulesTableModel getSWRLRulesModel() - { - return applicationController.getApplicationModel().getSWRLRulesTableModel(); - } - - private SWRLAPIApplicationDialogManager getApplicationDialogManager() - { - return applicationController.getApplicationDialogManager(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/old/SWRLRuleEditorDialog.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/old/SWRLRuleEditorDialog.java deleted file mode 100755 index 85eef06..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/old/SWRLRuleEditorDialog.java +++ /dev/null @@ -1,225 +0,0 @@ -package org.swrlapi.ui.dialog; - -import java.awt.BorderLayout; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import javax.swing.BorderFactory; -import javax.swing.JButton; -import javax.swing.JDialog; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.text.BadLocationException; -import javax.swing.text.JTextComponent; - -import org.swrlapi.parser.SWRLIncompleteRuleException; -import org.swrlapi.parser.SWRLParseException; -import org.swrlapi.parser.SWRLParser; -import org.swrlapi.ui.controller.SWRLAPIApplicationController; -import org.swrlapi.ui.model.SWRLRulesTableModel; - -public class SWRLRuleEditorDialog extends JDialog -{ - private static final long serialVersionUID = 1L; - - private static final String TITLE = "Edit SWRL Rule"; - private static final String INVALID_RULE_TITLE = "Invalid Rule"; - private static final int BUTTON_PREFERRED_WIDTH = 100; - private static final int BUTTON_PREFERRED_HEIGHT = 30; - - private final SWRLAPIApplicationController applicationController; - - private JTextField ruleNameTextField, commentTextField; - private JTextArea ruleTextTextArea; - - private boolean editMode = false; - - public SWRLRuleEditorDialog(SWRLAPIApplicationController applicationController) - { - this.applicationController = applicationController; - - setTitle(TITLE); - setModal(true); - - createComponents(); - this.ruleTextTextArea.addKeyListener(new SWRLRuleEditorKeyAdapter()); - - setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); - - addWindowListener(new WindowAdapter() { - @Override - public void windowClosing(WindowEvent we) - { - } - }); // Thwart user close - } - - public void reset() - { - clearEntryFields(); - } - - public void setEditData(String ruleName, String ruleText, String comment) - { - clearEntryFields(); - - ruleNameTextField.setText(ruleName); - ruleTextTextArea.setText(ruleText); - commentTextField.setText(comment); - - editMode = true; - } - - private void clearEntryFields() - { - ruleNameTextField.setText(""); - ruleNameTextField.setEnabled(true); - ruleTextTextArea.setText(""); - ruleTextTextArea.setEnabled(true); - ruleTextTextArea.setText(""); - commentTextField.setText(""); - - editMode = false; - } - - private void createComponents() - { - Container contentPane = getContentPane(); - - JLabel ruleNameLabel = new JLabel("Name"); - ruleNameTextField = new JTextField(""); - - JLabel ruleTextLabel = new JLabel("Body"); - ruleTextTextArea = new JTextArea("", 20, 60); - ruleTextTextArea.setBorder(BorderFactory.createLoweredBevelBorder()); - - JLabel commentLabel = new JLabel("Comment"); - commentTextField = new JTextField(""); - - JButton cancelButton = new JButton("Cancel"); - cancelButton.setPreferredSize(new Dimension(BUTTON_PREFERRED_WIDTH, BUTTON_PREFERRED_HEIGHT)); - cancelButton.addActionListener(new CancelSWRLRuleEditActionListener()); - - JButton okButton = new JButton("OK"); - okButton.setPreferredSize(new Dimension(BUTTON_PREFERRED_WIDTH, BUTTON_PREFERRED_HEIGHT)); - okButton.addActionListener(new OkSWRLRuleEditActionListener()); - - contentPane.setLayout(new BorderLayout()); - - JPanel surroundPanel = new JPanel(new BorderLayout()); - surroundPanel.setBorder(BorderFactory.createLoweredBevelBorder()); - contentPane.add(surroundPanel, BorderLayout.CENTER); - - JPanel innerPanel = new JPanel(new GridLayout(6, 2)); - - surroundPanel.add(innerPanel, BorderLayout.NORTH); - surroundPanel.add(ruleTextTextArea, BorderLayout.CENTER); - - innerPanel.add(ruleNameLabel); - innerPanel.add(ruleNameTextField); - innerPanel.add(commentLabel); - innerPanel.add(commentTextField); - innerPanel.add(ruleTextLabel); - - JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER)); - buttonPanel.add(cancelButton); - buttonPanel.add(okButton); - - surroundPanel.add(buttonPanel, BorderLayout.SOUTH); - - pack(); - } - - private class SWRLRuleEditorKeyAdapter extends KeyAdapter - { - @Override - public void keyTyped(KeyEvent event) - { - char ch = event.getKeyChar(); - JTextComponent component = (JTextComponent)event.getSource(); - try { - String ruleText = component.getDocument().getText(0, component.getCaretPosition()).trim(); - ruleText += ch; - // System.out.println("ch: " + ch); - System.out.println("ruleText: " + ruleText); - - if (ruleText.length() != 0) - getSWRLParser().parseSWRLRule(ruleText, true); - } catch (SWRLIncompleteRuleException e) { - System.out.println("Incomplete " + e.getMessage()); - } catch (SWRLParseException e) { - System.err.println("Error " + e.getMessage()); - } catch (BadLocationException e) { - } - } - } - - private class CancelSWRLRuleEditActionListener implements ActionListener - { - @Override - public void actionPerformed(ActionEvent e) - { - clearEntryFields(); - setVisible(false); - } - } - - private class OkSWRLRuleEditActionListener implements ActionListener - { - @Override - public void actionPerformed(ActionEvent e) - { - String ruleName = "", ruleText = "", comment = ""; - boolean errorOccurred = false; - - comment = ruleNameTextField.getText(); - - try { - ruleName = ruleNameTextField.getText().trim().toUpperCase(); - ruleText = ruleTextTextArea.getText().trim().toUpperCase(); - comment = commentTextField.getText().trim().toUpperCase(); - - // TODO Check the rule and name - } catch (Exception ex) { - getApplicationDialogManager().showErrorMessageDialog(ex.getMessage(), INVALID_RULE_TITLE); - errorOccurred = true; - } - - if (!errorOccurred) { - if (editMode) { - getSWRLRulesModel().removeSWRLRule(ruleName); // Remove original - getSWRLRulesModel().addSWRLRule(ruleName, ruleText, comment); - } else { - getSWRLRulesModel().addSWRLRule(ruleName, ruleText, comment); - } - setVisible(false); - clearEntryFields(); - } - } - } - - private SWRLParser getSWRLParser() - { - return applicationController.getApplicationModel().getSWRLParser(); - } - - private SWRLRulesTableModel getSWRLRulesModel() - { - return applicationController.getApplicationModel().getSWRLRulesTableModel(); - } - - private SWRLAPIApplicationDialogManager getApplicationDialogManager() - { - return applicationController.getApplicationDialogManager(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/pair.info deleted file mode 100755 index a2a7110..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#73453/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:73453 -comSha:73840d406456a8549723935f3d17312f749c5ac2 -parentComSha:94072747d56a534926a1960e7374e751d941a3a9 -BuggyFilePath:src/main/java/org/swrlapi/ui/dialog/SWRLRuleEditorDialog.java -FixedFilePath:src/main/java/org/swrlapi/ui/dialog/SWRLRuleEditorDialog.java -StartLineNum:188 -EndLineNum:188 -repoName:protegeproject#swrlapi \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/diff.diff deleted file mode 100755 index a691fa9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/math/statistics/ranking/RankingStrategy.java b/src/main/java/org/optimizationBenchmarking/utils/math/statistics/ranking/RankingStrategy.java -index 8b736c17..43e7ba41 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/math/statistics/ranking/RankingStrategy.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/math/statistics/ranking/RankingStrategy.java -@@ -8,0 +9 @@ import org.optimizationBenchmarking.utils.text.ETextCase; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -214 +215 @@ public final class RankingStrategy implements ISemanticComponent { -- mto.append(this.m_nan.name().toLowerCase()); -+ mto.append(TextUtils.toLowerCase(this.m_nan.name())); -@@ -218 +219 @@ public final class RankingStrategy implements ISemanticComponent { -- mto.append(this.m_ties.name().toLowerCase()); -+ mto.append(TextUtils.toLowerCase(this.m_ties.name())); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/new/RankingStrategy.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/new/RankingStrategy.java deleted file mode 100755 index 43e7ba4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/new/RankingStrategy.java +++ /dev/null @@ -1,224 +0,0 @@ -package org.optimizationBenchmarking.utils.math.statistics.ranking; - -import java.util.Arrays; - -import org.optimizationBenchmarking.utils.config.Configuration; -import org.optimizationBenchmarking.utils.document.spec.ISemanticComponent; -import org.optimizationBenchmarking.utils.math.matrix.IMatrix; -import org.optimizationBenchmarking.utils.text.ETextCase; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; -import org.optimizationBenchmarking.utils.text.textOutput.MemoryTextOutput; - -/** This class lets us rank elements */ -public final class RankingStrategy implements ISemanticComponent { - - /** the NaN strategy for the ranking */ - public static final String NAN_STRATEGY_PARAMETER = "rankingNaNStrategy"; //$NON-NLS-1$ - - /** the tie strategy for the ranking */ - public static final String TIE_STRATEGY_PARAMETER = "rankingTieStrategy"; //$NON-NLS-1$ - - /** the short name for the ranking */ - private static final char[] SHORT_NAME = { 'r', 'a', 'n', 'k' }; - - /** the nan strategy */ - private final ENaNStrategy m_nan; - - /** the tie strategy */ - private final ETieStrategy m_ties; - - /** - * Create the ranking - * - * @param nan - * the {@linkplain ENaNStrategy NaN strategy}, or {@code null} - * for {@linkplain ENaNStrategy#DEFAULT default} - * @param ties - * the {@linkplain ETieStrategy tie strategy}, or {@code null} - * for {@linkplain ETieStrategy#DEFAULT default} - */ - public RankingStrategy(final ENaNStrategy nan, final ETieStrategy ties) { - super(); - - this.m_nan = ((nan != null) ? nan : ENaNStrategy.DEFAULT); - this.m_ties = ((ties != null) ? ties : ETieStrategy.DEFAULT); - } - - /** - * Obtain the {@linkplain ENaNStrategy NaN strategy}, i.e., the way in - * which {@value java.lang.Double#NaN}s are handled - * - * @return the {@linkplain ENaNStrategy NaN strategy}, i.e., the way in - * which {@value java.lang.Double#NaN}s are handled - */ - public final ENaNStrategy getNaNStrategy() { - return this.m_nan; - } - - /** - * Obtain the {@linkplain ETieStrategy tie strategy}, i.e., the way in - * which ties handled, meaning how equal values are ranked - * - * @return the {@linkplain ETieStrategy tie strategy}, i.e., the way in - * which ties handled, meaning how equal values are ranked - */ - public final ETieStrategy getTieStrategy() { - return this.m_ties; - } - - /** - * Rank all elements in the {@code data} array and store the resulting - * ranks in the destination array. - * - * @param data - * the data array, containing the elements to be ranked - * @param dest - * the destination array - */ - public final void rank(final double[] data, final double[] dest) { - final _RankedElement[] elements; - int i; - - elements = new _RankedElement[data.length]; - i = 0; - for (final double d : data) { - elements[i] = this.m_nan._element(i, 0, d); - ++i; - } - Arrays.sort(elements); - this.m_ties._rank(elements); - this.m_nan._refine(elements); - for (final _RankedElement e : elements) { - dest[e.m_index1] = e.m_rank; - } - } - - /** - * Rank all elements in the {@code data} array and store the resulting - * ranks in the destination array. - * - * @param data - * the data array, containing the elements to be ranked - * @param dest - * the destination array - */ - public final void rank(final long[] data, final double[] dest) { - final _RankedElement[] elements; - int i; - - elements = new _RankedElement[data.length]; - i = 0; - for (final double d : data) { - elements[i] = this.m_nan._element(i, 0, d); - ++i; - } - Arrays.sort(elements); - this.m_ties._rank(elements); - this.m_nan._refine(elements); - for (final _RankedElement e : elements) { - dest[e.m_index1] = e.m_rank; - } - } - - /** - * Rank the elements in row {@code row} of a given {@code matrix} store - * the resulting ranks in the destination array. - * - * @param matrix - * the matrix, containing the row with the elements to be ranked - * @param row - * the index of the row to rank - * @param dest - * the destination array - */ - public final void rankRow(final IMatrix matrix, final int row, - final double[] dest) { - final _RankedElement[] elements; - int i; - - elements = new _RankedElement[matrix.n()]; - for (i = elements.length; (--i) >= 0;) { - elements[i] = this.m_nan._element(i, 0, matrix.getDouble(row, i)); - } - Arrays.sort(elements); - this.m_ties._rank(elements); - this.m_nan._refine(elements); - for (final _RankedElement e : elements) { - dest[e.m_index1] = e.m_rank; - } - } - - /** - * Load a ranking strategy from a configuration - * - * @param config - * the configuration - * @return the ranking strategy - */ - public static final RankingStrategy create(final Configuration config) { - final ENaNStrategy nan; - final ETieStrategy tie; - - nan = config.get(RankingStrategy.NAN_STRATEGY_PARAMETER, - NaNStrategyParser.INSTANCE, ENaNStrategy.DEFAULT); - tie = config.get(RankingStrategy.TIE_STRATEGY_PARAMETER, - TieStrategyParser.INSTANCE, ETieStrategy.DEFAULT); - - return new RankingStrategy(nan, tie); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printShortName(final ITextOutput textOut, - final ETextCase textCase) { - return textCase.appendWord(RankingStrategy.SHORT_NAME, textOut); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printLongName(final ITextOutput textOut, - final ETextCase textCase) { - return textCase.appendWord("ranking", textOut); //$NON-NLS-1$ - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printDescription(final ITextOutput textOut, - final ETextCase textCase) { - ETextCase next; - - next = textCase.appendWords("during the ranking", textOut);//$NON-NLS-1$ - textOut.append(','); - textOut.append(' '); - - if (this.m_nan != ENaNStrategy.ERROR) { - next = this.m_nan._printDescription(textOut, next); - textOut.append(','); - textOut.append(' '); - next = next.appendWord("while", textOut);//$NON-NLS-1$ - textOut.append(' '); - } - - return this.m_ties._printDescription(textOut, next); - } - - /** {@inheritDoc} */ - @Override - public final String getPathComponentSuggestion() { - MemoryTextOutput mto; - - mto = new MemoryTextOutput(); - mto.append(RankingStrategy.SHORT_NAME); - if (this.m_nan != ENaNStrategy.DEFAULT) { - mto.append('_'); - mto.append(TextUtils.toLowerCase(this.m_nan.name())); - } - if (this.m_ties != ETieStrategy.DEFAULT) { - mto.append('_'); - mto.append(TextUtils.toLowerCase(this.m_ties.name())); - } - - return mto.toString(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/old/RankingStrategy.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/old/RankingStrategy.java deleted file mode 100755 index 8b736c1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/old/RankingStrategy.java +++ /dev/null @@ -1,223 +0,0 @@ -package org.optimizationBenchmarking.utils.math.statistics.ranking; - -import java.util.Arrays; - -import org.optimizationBenchmarking.utils.config.Configuration; -import org.optimizationBenchmarking.utils.document.spec.ISemanticComponent; -import org.optimizationBenchmarking.utils.math.matrix.IMatrix; -import org.optimizationBenchmarking.utils.text.ETextCase; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; -import org.optimizationBenchmarking.utils.text.textOutput.MemoryTextOutput; - -/** This class lets us rank elements */ -public final class RankingStrategy implements ISemanticComponent { - - /** the NaN strategy for the ranking */ - public static final String NAN_STRATEGY_PARAMETER = "rankingNaNStrategy"; //$NON-NLS-1$ - - /** the tie strategy for the ranking */ - public static final String TIE_STRATEGY_PARAMETER = "rankingTieStrategy"; //$NON-NLS-1$ - - /** the short name for the ranking */ - private static final char[] SHORT_NAME = { 'r', 'a', 'n', 'k' }; - - /** the nan strategy */ - private final ENaNStrategy m_nan; - - /** the tie strategy */ - private final ETieStrategy m_ties; - - /** - * Create the ranking - * - * @param nan - * the {@linkplain ENaNStrategy NaN strategy}, or {@code null} - * for {@linkplain ENaNStrategy#DEFAULT default} - * @param ties - * the {@linkplain ETieStrategy tie strategy}, or {@code null} - * for {@linkplain ETieStrategy#DEFAULT default} - */ - public RankingStrategy(final ENaNStrategy nan, final ETieStrategy ties) { - super(); - - this.m_nan = ((nan != null) ? nan : ENaNStrategy.DEFAULT); - this.m_ties = ((ties != null) ? ties : ETieStrategy.DEFAULT); - } - - /** - * Obtain the {@linkplain ENaNStrategy NaN strategy}, i.e., the way in - * which {@value java.lang.Double#NaN}s are handled - * - * @return the {@linkplain ENaNStrategy NaN strategy}, i.e., the way in - * which {@value java.lang.Double#NaN}s are handled - */ - public final ENaNStrategy getNaNStrategy() { - return this.m_nan; - } - - /** - * Obtain the {@linkplain ETieStrategy tie strategy}, i.e., the way in - * which ties handled, meaning how equal values are ranked - * - * @return the {@linkplain ETieStrategy tie strategy}, i.e., the way in - * which ties handled, meaning how equal values are ranked - */ - public final ETieStrategy getTieStrategy() { - return this.m_ties; - } - - /** - * Rank all elements in the {@code data} array and store the resulting - * ranks in the destination array. - * - * @param data - * the data array, containing the elements to be ranked - * @param dest - * the destination array - */ - public final void rank(final double[] data, final double[] dest) { - final _RankedElement[] elements; - int i; - - elements = new _RankedElement[data.length]; - i = 0; - for (final double d : data) { - elements[i] = this.m_nan._element(i, 0, d); - ++i; - } - Arrays.sort(elements); - this.m_ties._rank(elements); - this.m_nan._refine(elements); - for (final _RankedElement e : elements) { - dest[e.m_index1] = e.m_rank; - } - } - - /** - * Rank all elements in the {@code data} array and store the resulting - * ranks in the destination array. - * - * @param data - * the data array, containing the elements to be ranked - * @param dest - * the destination array - */ - public final void rank(final long[] data, final double[] dest) { - final _RankedElement[] elements; - int i; - - elements = new _RankedElement[data.length]; - i = 0; - for (final double d : data) { - elements[i] = this.m_nan._element(i, 0, d); - ++i; - } - Arrays.sort(elements); - this.m_ties._rank(elements); - this.m_nan._refine(elements); - for (final _RankedElement e : elements) { - dest[e.m_index1] = e.m_rank; - } - } - - /** - * Rank the elements in row {@code row} of a given {@code matrix} store - * the resulting ranks in the destination array. - * - * @param matrix - * the matrix, containing the row with the elements to be ranked - * @param row - * the index of the row to rank - * @param dest - * the destination array - */ - public final void rankRow(final IMatrix matrix, final int row, - final double[] dest) { - final _RankedElement[] elements; - int i; - - elements = new _RankedElement[matrix.n()]; - for (i = elements.length; (--i) >= 0;) { - elements[i] = this.m_nan._element(i, 0, matrix.getDouble(row, i)); - } - Arrays.sort(elements); - this.m_ties._rank(elements); - this.m_nan._refine(elements); - for (final _RankedElement e : elements) { - dest[e.m_index1] = e.m_rank; - } - } - - /** - * Load a ranking strategy from a configuration - * - * @param config - * the configuration - * @return the ranking strategy - */ - public static final RankingStrategy create(final Configuration config) { - final ENaNStrategy nan; - final ETieStrategy tie; - - nan = config.get(RankingStrategy.NAN_STRATEGY_PARAMETER, - NaNStrategyParser.INSTANCE, ENaNStrategy.DEFAULT); - tie = config.get(RankingStrategy.TIE_STRATEGY_PARAMETER, - TieStrategyParser.INSTANCE, ETieStrategy.DEFAULT); - - return new RankingStrategy(nan, tie); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printShortName(final ITextOutput textOut, - final ETextCase textCase) { - return textCase.appendWord(RankingStrategy.SHORT_NAME, textOut); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printLongName(final ITextOutput textOut, - final ETextCase textCase) { - return textCase.appendWord("ranking", textOut); //$NON-NLS-1$ - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printDescription(final ITextOutput textOut, - final ETextCase textCase) { - ETextCase next; - - next = textCase.appendWords("during the ranking", textOut);//$NON-NLS-1$ - textOut.append(','); - textOut.append(' '); - - if (this.m_nan != ENaNStrategy.ERROR) { - next = this.m_nan._printDescription(textOut, next); - textOut.append(','); - textOut.append(' '); - next = next.appendWord("while", textOut);//$NON-NLS-1$ - textOut.append(' '); - } - - return this.m_ties._printDescription(textOut, next); - } - - /** {@inheritDoc} */ - @Override - public final String getPathComponentSuggestion() { - MemoryTextOutput mto; - - mto = new MemoryTextOutput(); - mto.append(RankingStrategy.SHORT_NAME); - if (this.m_nan != ENaNStrategy.DEFAULT) { - mto.append('_'); - mto.append(this.m_nan.name().toLowerCase()); - } - if (this.m_ties != ETieStrategy.DEFAULT) { - mto.append('_'); - mto.append(this.m_ties.name().toLowerCase()); - } - - return mto.toString(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/pair.info deleted file mode 100755 index f88e337..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75223/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75223 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/math/statistics/ranking/RankingStrategy.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/math/statistics/ranking/RankingStrategy.java -StartLineNum:214 -EndLineNum:214 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/diff.diff deleted file mode 100755 index 541aa9f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/document/impl/export/_ExportMathCompare.java b/src/main/java/org/optimizationBenchmarking/utils/document/impl/export/_ExportMathCompare.java -index fa48edc8..2b59126d 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/document/impl/export/_ExportMathCompare.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/document/impl/export/_ExportMathCompare.java -@@ -5,0 +6 @@ import org.optimizationBenchmarking.utils.document.spec.EMathComparison; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -33 +34 @@ final class _ExportMathCompare extends MathCompare { -- out.append(this.getComparison().toString().toLowerCase()); -+ out.append(TextUtils.toLowerCase(this.getComparison().toString())); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/new/_ExportMathCompare.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/new/_ExportMathCompare.java deleted file mode 100755 index 2b59126..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/new/_ExportMathCompare.java +++ /dev/null @@ -1,40 +0,0 @@ -package org.optimizationBenchmarking.utils.document.impl.export; - -import org.optimizationBenchmarking.utils.document.impl.abstr.BasicMath; -import org.optimizationBenchmarking.utils.document.impl.abstr.MathCompare; -import org.optimizationBenchmarking.utils.document.spec.EMathComparison; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; - -/** an mathematical compare function in an export document */ -final class _ExportMathCompare extends MathCompare { - - /** - * Create a new mathematical function - * - * @param owner - * the owning text - * @param cmp - * the comparator - */ - _ExportMathCompare(final BasicMath owner, final EMathComparison cmp) { - super(owner, cmp); - this.open(); - } - - /** {@inheritDoc} */ - @Override - protected final void render(final ITextOutput out, final char[][] data, - final int size) { - - out.append('('); - out.append(data[0]); - out.append(')'); - - out.append(TextUtils.toLowerCase(this.getComparison().toString())); - - out.append('('); - out.append(data[1]); - out.append(')'); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/old/_ExportMathCompare.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/old/_ExportMathCompare.java deleted file mode 100755 index fa48edc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/old/_ExportMathCompare.java +++ /dev/null @@ -1,39 +0,0 @@ -package org.optimizationBenchmarking.utils.document.impl.export; - -import org.optimizationBenchmarking.utils.document.impl.abstr.BasicMath; -import org.optimizationBenchmarking.utils.document.impl.abstr.MathCompare; -import org.optimizationBenchmarking.utils.document.spec.EMathComparison; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; - -/** an mathematical compare function in an export document */ -final class _ExportMathCompare extends MathCompare { - - /** - * Create a new mathematical function - * - * @param owner - * the owning text - * @param cmp - * the comparator - */ - _ExportMathCompare(final BasicMath owner, final EMathComparison cmp) { - super(owner, cmp); - this.open(); - } - - /** {@inheritDoc} */ - @Override - protected final void render(final ITextOutput out, final char[][] data, - final int size) { - - out.append('('); - out.append(data[0]); - out.append(')'); - - out.append(this.getComparison().toString().toLowerCase()); - - out.append('('); - out.append(data[1]); - out.append(')'); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/pair.info deleted file mode 100755 index b0d5ff6..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75227/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75227 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/document/impl/export/_ExportMathCompare.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/document/impl/export/_ExportMathCompare.java -StartLineNum:33 -EndLineNum:33 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/diff.diff deleted file mode 100755 index f529ebb..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/comparison/ComparisonParser.java b/src/main/java/org/optimizationBenchmarking/utils/comparison/ComparisonParser.java -index e04bd08b..b285160d 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/comparison/ComparisonParser.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/comparison/ComparisonParser.java -@@ -4,0 +5 @@ import org.optimizationBenchmarking.utils.reflection.ReflectionUtils; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -22 +23 @@ public class ComparisonParser extends InstanceParser { -- switch (string.toLowerCase()) { -+ switch (TextUtils.toLowerCase(string)) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/new/ComparisonParser.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/new/ComparisonParser.java deleted file mode 100755 index b285160..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/new/ComparisonParser.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.optimizationBenchmarking.utils.comparison; - -import org.optimizationBenchmarking.utils.parsers.InstanceParser; -import org.optimizationBenchmarking.utils.reflection.ReflectionUtils; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** A parser for comparisons */ -public class ComparisonParser extends InstanceParser { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** create the comparison parser */ - ComparisonParser() { - super(EComparison.class, new String[] { ReflectionUtils - .getPackagePrefix(EComparison.class) }); - } - - /** {@inheritDoc} */ - @Override - public final EComparison parseString(final String string) - throws Exception { - switch (TextUtils.toLowerCase(string)) { - - case "less than": //$NON-NLS-1$ - case "less": //$NON-NLS-1$ - case "l"://$NON-NLS-1$ - case "<": {//$NON-NLS-1$ - return EComparison.LESS; - } - - case "less or equal": //$NON-NLS-1$ - case "less than or equal to": //$NON-NLS-1$ - case "le"://$NON-NLS-1$ - case "leq"://$NON-NLS-1$ - case "\u2264"://$NON-NLS-1$ - case "<=": {//$NON-NLS-1$ - return EComparison.LESS_OR_EQUAL; - } - - case "equal to": //$NON-NLS-1$ - case "equal": //$NON-NLS-1$ - case "eq"://$NON-NLS-1$ - case "e"://$NON-NLS-1$ - case "="://$NON-NLS-1$ - case "==": {//$NON-NLS-1$ - return EComparison.EQUAL; - } - - case "greater or equal": //$NON-NLS-1$ - case "greater than or equal to": //$NON-NLS-1$ - case "ge"://$NON-NLS-1$ - case "geq"://$NON-NLS-1$ - case "\u2265"://$NON-NLS-1$ - case ">=": {//$NON-NLS-1$ - return EComparison.GREATER_OR_EQUAL; - } - - case "greater than": //$NON-NLS-1$ - case "greater": //$NON-NLS-1$ - case "g"://$NON-NLS-1$ - case ">": {//$NON-NLS-1$ - return EComparison.GREATER; - } - - case "not equal to": //$NON-NLS-1$ - case "not equal": //$NON-NLS-1$ - case "neq"://$NON-NLS-1$ - case "ne"://$NON-NLS-1$ - case "!="://$NON-NLS-1$ - case "\u2260": {//$NON-NLS-1$ - return EComparison.NOT_EQUAL; - } - default: { - return super.parseObject(string); - } - } - } - - /** - * Get the singleton instance of this parser - * - * @return the document driver parser - */ - public static final ComparisonParser getInstance() { - return __ComparisonParserLoader.INSTANCE; - } - - /** the instance loader */ - private static final class __ComparisonParserLoader { - /** the instance */ - static final ComparisonParser INSTANCE = new ComparisonParser(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/old/ComparisonParser.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/old/ComparisonParser.java deleted file mode 100755 index e04bd08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/old/ComparisonParser.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.optimizationBenchmarking.utils.comparison; - -import org.optimizationBenchmarking.utils.parsers.InstanceParser; -import org.optimizationBenchmarking.utils.reflection.ReflectionUtils; - -/** A parser for comparisons */ -public class ComparisonParser extends InstanceParser { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** create the comparison parser */ - ComparisonParser() { - super(EComparison.class, new String[] { ReflectionUtils - .getPackagePrefix(EComparison.class) }); - } - - /** {@inheritDoc} */ - @Override - public final EComparison parseString(final String string) - throws Exception { - switch (string.toLowerCase()) { - - case "less than": //$NON-NLS-1$ - case "less": //$NON-NLS-1$ - case "l"://$NON-NLS-1$ - case "<": {//$NON-NLS-1$ - return EComparison.LESS; - } - - case "less or equal": //$NON-NLS-1$ - case "less than or equal to": //$NON-NLS-1$ - case "le"://$NON-NLS-1$ - case "leq"://$NON-NLS-1$ - case "\u2264"://$NON-NLS-1$ - case "<=": {//$NON-NLS-1$ - return EComparison.LESS_OR_EQUAL; - } - - case "equal to": //$NON-NLS-1$ - case "equal": //$NON-NLS-1$ - case "eq"://$NON-NLS-1$ - case "e"://$NON-NLS-1$ - case "="://$NON-NLS-1$ - case "==": {//$NON-NLS-1$ - return EComparison.EQUAL; - } - - case "greater or equal": //$NON-NLS-1$ - case "greater than or equal to": //$NON-NLS-1$ - case "ge"://$NON-NLS-1$ - case "geq"://$NON-NLS-1$ - case "\u2265"://$NON-NLS-1$ - case ">=": {//$NON-NLS-1$ - return EComparison.GREATER_OR_EQUAL; - } - - case "greater than": //$NON-NLS-1$ - case "greater": //$NON-NLS-1$ - case "g"://$NON-NLS-1$ - case ">": {//$NON-NLS-1$ - return EComparison.GREATER; - } - - case "not equal to": //$NON-NLS-1$ - case "not equal": //$NON-NLS-1$ - case "neq"://$NON-NLS-1$ - case "ne"://$NON-NLS-1$ - case "!="://$NON-NLS-1$ - case "\u2260": {//$NON-NLS-1$ - return EComparison.NOT_EQUAL; - } - default: { - return super.parseObject(string); - } - } - } - - /** - * Get the singleton instance of this parser - * - * @return the document driver parser - */ - public static final ComparisonParser getInstance() { - return __ComparisonParserLoader.INSTANCE; - } - - /** the instance loader */ - private static final class __ComparisonParserLoader { - /** the instance */ - static final ComparisonParser INSTANCE = new ComparisonParser(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/pair.info deleted file mode 100755 index 28d3a5d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75263/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75263 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/comparison/ComparisonParser.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/comparison/ComparisonParser.java -StartLineNum:22 -EndLineNum:22 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/diff.diff deleted file mode 100755 index 6f8b3aa..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/tools/impl/latex/_LaTeXUsedAsToolBase.java b/src/main/java/org/optimizationBenchmarking/utils/tools/impl/latex/_LaTeXUsedAsToolBase.java -index 7557e5a6..1e9a0507 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/tools/impl/latex/_LaTeXUsedAsToolBase.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/tools/impl/latex/_LaTeXUsedAsToolBase.java -@@ -8,0 +9 @@ import org.optimizationBenchmarking.utils.config.Configuration; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -127 +128 @@ abstract class _LaTeXUsedAsToolBase extends _LaTeXToolChainComponent { -- this._produces().getDefaultSuffix().toLowerCase()) -+ TextUtils.toLowerCase(this._produces().getDefaultSuffix())) \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/new/_LaTeXUsedAsToolBase.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/new/_LaTeXUsedAsToolBase.java deleted file mode 100755 index 1e9a050..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/new/_LaTeXUsedAsToolBase.java +++ /dev/null @@ -1,311 +0,0 @@ -package org.optimizationBenchmarking.utils.tools.impl.latex; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.optimizationBenchmarking.utils.config.Configuration; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; -import org.optimizationBenchmarking.utils.tools.impl.process.EProcessStream; -import org.optimizationBenchmarking.utils.tools.impl.process.ExternalProcess; -import org.optimizationBenchmarking.utils.tools.impl.process.ExternalProcessBuilder; -import org.optimizationBenchmarking.utils.tools.impl.process.ProcessExecutor; - -/** a tool using which is used as another tool */ -abstract class _LaTeXUsedAsToolBase extends _LaTeXToolChainComponent { - - /** the executable */ - private final Path m_executable; - - /** can we halt on error? */ - private final String m_haltArg; - /** the format argument */ - private final String m_formatArg; - /** the program name command line argument */ - private final String m_progNameArg; - - /** the error */ - private final Throwable m_error; - - /** the tool name */ - private final String m_toolName; - /** the tool 1 name */ - private final String m_tool1Name; - /** the tool 2 name */ - private final String m_tool2Name; - - /** create */ - _LaTeXUsedAsToolBase() { - super(); - - final Logger logger; - final boolean needsOutput; - Path exec; - String[] args; - String progname, name, arg1, arg2, arg3; - Throwable error; - int index; - - name = this.getClass().getSimpleName(); - index = name.indexOf("As"); //$NON-NLS-1$ - if (index > 0) { - this.m_tool1Name = name.substring(1, index); - this.m_tool2Name = name.substring(index + 2); - this.m_toolName = (this.m_tool1Name + " used as " + this.m_tool2Name);//$NON-NLS-1$ - } else { - this.m_toolName = this.m_tool2Name = this.m_tool1Name = // - name.substring(1); - } - - error = null; - arg1 = arg2 = arg3 = null; - - logger = Configuration.getGlobalLogger(); - if ((logger != null) && (logger.isLoggable(Level.CONFIG))) { - logger.config(// - "Now trying to find " + this.m_tool1Name + //$NON-NLS-1$ - " executable which can be used as " + this.m_tool2Name);//$NON-NLS-1$ - } - - exec = this._getExecutable(); - - if (exec != null) { - progname = this._getProcName(); - - index = 1; - needsOutput = this._needsOutputFormat(); - if (needsOutput) { - index++; - } - if (progname != null) { - index++; - } - args = new String[index]; - args[0] = "halt-on-error"; //$NON-NLS-1$ - index = 1; - if (needsOutput) { - args[index++] = "output-format="; //$NON-NLS-1$ - } - if (progname != null) { - args[index] = "progname="; //$NON-NLS-1$ - } - - try { - args = _LaTeXToolChainComponent._getArgs(exec, "-help", args);//$NON-NLS-1$ - - arg2 = args[0]; - - index = 1; - if (needsOutput) { - if ((arg1 = args[index++]) == null) { - throw new IllegalStateException( - this.m_tool1Name + " binary '" + exec//$NON-NLS-1$ - + "' does not offer option 'output-format' when asked via '-help'.");//$NON-NLS-1$ - } - } - - if (progname != null) { - if ((arg3 = args[index]) == null) { - throw new IllegalStateException(// - this.m_tool1Name + " binary '" + exec + //$NON-NLS-1$ - "' does not offer option 'progname' when asked via '-help'.");//$NON-NLS-1$ - } - } - - } catch (final Throwable err) { - error = err; - arg1 = arg2 = arg3 = null; - exec = null; - } - } else { - progname = null; - } - - this.m_executable = exec; - this.m_formatArg = ((arg1 != null) ? (arg1 + // - TextUtils.toLowerCase(this._produces().getDefaultSuffix())) - : null); - this.m_haltArg = arg2; - this.m_progNameArg = ((arg3 != null) ? (arg3 + progname) : null); - this.m_error = error; - - if ((logger != null) && (logger.isLoggable(Level.CONFIG))) { - logger.config(((this.m_executable != null) ? "" : "No ") + //$NON-NLS-1$ //$NON-NLS-2$ - (this.m_tool1Name + " executable '" + this.m_executable + //$NON-NLS-1$ - "' which can be used as " + //$NON-NLS-1$ - this.m_tool2Name + " found.")); //$NON-NLS-1$ - } - } - - /** - * get the program name to use, or {@code null} if none is necessary - * - * @return the program name to use, or {@code null} if none is necessary - */ - String _getProcName() { - return null; - } - - /** - * Do we need a parameter for the output format? - * - * @return {@code true} if we need such a parameter, {@code false} - * otherwise - */ - boolean _needsOutputFormat() { - return true; - } - - /** - * Obtain the path to the executable - * - * @return the path to the executable, or {@code null} if none was found - */ - abstract Path _getExecutable(); - - /** {@inheritDoc} */ - @Override - final boolean _canUse() { - return ((this.m_executable != null) && // - ((this.m_formatArg != null) || (!(this._needsOutputFormat()))) && // - (this.m_error == null) && // - ((this.m_progNameArg != null) || (this._getProcName() == null))); - } - - /** {@inheritDoc} */ - @Override - final void _use(final _LaTeXMainJob job) throws IOException { - final Logger logger; - final Path exec, tex; - final ExternalProcessBuilder builder; - final ELaTeXFileType type; - final int ret; - final boolean needsOutput; - boolean ok; - - if (this.m_error != null) { - throw new UnsupportedOperationException(// - this.m_tool1Name - + " cannot be used as "//$NON-NLS-1$ - + this.m_tool2Name - + " compiler because... (see causing error).",//$NON-NLS-1$ - this.m_error); - } - needsOutput = this._needsOutputFormat(); - if (needsOutput) { - if (this.m_formatArg == null) { - throw new UnsupportedOperationException(// - this.m_tool1Name + " cannot be used as " + //$NON-NLS-1$ - this.m_tool2Name + // - " compiler because no corresponding option was detected.");//$NON-NLS-1$ - } - } - if (this.m_progNameArg == null) { - if (this._getProcName() != null) { - throw new UnsupportedOperationException(// - this.m_tool1Name + " cannot be used as " + //$NON-NLS-1$ - this.m_tool2Name + // - " compiler because no corresponding 'progname' option was detected.");//$NON-NLS-1$ - } - } - if ((exec = this.m_executable) == null) { - throw new UnsupportedOperationException("No " + this.m_tool1Name + //$NON-NLS-1$ - " binary that can be used as " + //$NON-NLS-1$ - this.m_tool2Name + " detected."); //$NON-NLS-1$ - } - - if ((tex = this._getFile(job, ELaTeXFileType.TEX, true, null)) == null) { - return; - } - if (this._getFile(job, ELaTeXFileType.AUX, false, null) == null) { - return; - } - - type = this._produces(); - if (this._getFile(job, type, false, null) == null) { - return; - } - - logger = job._getLogger(); - if ((logger != null) && (logger.isLoggable(Level.INFO))) { - logger.info(// - (("Applying " + this.m_toolName + //$NON-NLS-1$ - " to '" + tex) + '\'') + '.'); //$NON-NLS-1$ - } - - builder = ProcessExecutor.getInstance().use(); - builder.setDirectory(job._getDirectory()); - builder.setExecutable(exec); - if (this.m_formatArg != null) { - builder.addStringArgument(this.m_formatArg); - } - if (this.m_progNameArg != null) { - builder.addStringArgument(this.m_progNameArg); - } - if (this.m_haltArg != null) { - builder.addStringArgument(this.m_haltArg); - } - builder.addPathArgument(tex); - builder.setLogger(logger); - builder.setStdErr(EProcessStream.REDIRECT_TO_LOGGER); - builder.setStdOut(EProcessStream.REDIRECT_TO_LOGGER); - builder.setStdIn(EProcessStream.IGNORE); - - try (ExternalProcess proc = builder.create()) { - if ((ret = proc.waitFor()) != 0) { - throw new IOException(((((((this.m_tool1Name + " executable '" //$NON-NLS-1$ - + exec) + "' (used as " + this.m_tool2Name + //$NON-NLS-1$ - ") returned value ") + ret) + //$NON-NLS-1$ - ", which indicates an error, for tex file '") + //$NON-NLS-1$ - tex) + '\'') + '.'); - } - } - - ok = true; - if (this - ._getFile( - job, - ELaTeXFileType.AUX, - true, - " This could mean that the latex document does not contain any label, citation, or section."//$NON-NLS-1$ - ) == null) { - ok = false; - } - if (this._getFile(job, type, true, - " This could mean that the latex document does not produce any output."//$NON-NLS-1$ - ) == null) { - ok = false; - } - - if (ok) { - if ((logger != null) && (logger.isLoggable(Level.FINE))) { - logger.fine(// - (("Finished applying " + this.m_toolName + //$NON-NLS-1$ - " to '" + tex) + '\'') + '.'); //$NON-NLS-1$ - } - } - } - - /** {@inheritDoc} */ - @Override - public final void toText(final ITextOutput textOut) { - textOut.append(this.m_toolName); - textOut.append('('); - textOut.append(this.m_executable); - if (this.m_formatArg != null) { - textOut.append(' '); - textOut.append(this.m_formatArg); - } - if (this.m_progNameArg != null) { - textOut.append(' '); - textOut.append(this.m_progNameArg); - } - if (this.m_haltArg != null) { - textOut.append(' '); - textOut.append(this.m_haltArg); - } - textOut.append(')'); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/old/_LaTeXUsedAsToolBase.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/old/_LaTeXUsedAsToolBase.java deleted file mode 100755 index 7557e5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/old/_LaTeXUsedAsToolBase.java +++ /dev/null @@ -1,310 +0,0 @@ -package org.optimizationBenchmarking.utils.tools.impl.latex; - -import java.io.IOException; -import java.nio.file.Path; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.optimizationBenchmarking.utils.config.Configuration; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; -import org.optimizationBenchmarking.utils.tools.impl.process.EProcessStream; -import org.optimizationBenchmarking.utils.tools.impl.process.ExternalProcess; -import org.optimizationBenchmarking.utils.tools.impl.process.ExternalProcessBuilder; -import org.optimizationBenchmarking.utils.tools.impl.process.ProcessExecutor; - -/** a tool using which is used as another tool */ -abstract class _LaTeXUsedAsToolBase extends _LaTeXToolChainComponent { - - /** the executable */ - private final Path m_executable; - - /** can we halt on error? */ - private final String m_haltArg; - /** the format argument */ - private final String m_formatArg; - /** the program name command line argument */ - private final String m_progNameArg; - - /** the error */ - private final Throwable m_error; - - /** the tool name */ - private final String m_toolName; - /** the tool 1 name */ - private final String m_tool1Name; - /** the tool 2 name */ - private final String m_tool2Name; - - /** create */ - _LaTeXUsedAsToolBase() { - super(); - - final Logger logger; - final boolean needsOutput; - Path exec; - String[] args; - String progname, name, arg1, arg2, arg3; - Throwable error; - int index; - - name = this.getClass().getSimpleName(); - index = name.indexOf("As"); //$NON-NLS-1$ - if (index > 0) { - this.m_tool1Name = name.substring(1, index); - this.m_tool2Name = name.substring(index + 2); - this.m_toolName = (this.m_tool1Name + " used as " + this.m_tool2Name);//$NON-NLS-1$ - } else { - this.m_toolName = this.m_tool2Name = this.m_tool1Name = // - name.substring(1); - } - - error = null; - arg1 = arg2 = arg3 = null; - - logger = Configuration.getGlobalLogger(); - if ((logger != null) && (logger.isLoggable(Level.CONFIG))) { - logger.config(// - "Now trying to find " + this.m_tool1Name + //$NON-NLS-1$ - " executable which can be used as " + this.m_tool2Name);//$NON-NLS-1$ - } - - exec = this._getExecutable(); - - if (exec != null) { - progname = this._getProcName(); - - index = 1; - needsOutput = this._needsOutputFormat(); - if (needsOutput) { - index++; - } - if (progname != null) { - index++; - } - args = new String[index]; - args[0] = "halt-on-error"; //$NON-NLS-1$ - index = 1; - if (needsOutput) { - args[index++] = "output-format="; //$NON-NLS-1$ - } - if (progname != null) { - args[index] = "progname="; //$NON-NLS-1$ - } - - try { - args = _LaTeXToolChainComponent._getArgs(exec, "-help", args);//$NON-NLS-1$ - - arg2 = args[0]; - - index = 1; - if (needsOutput) { - if ((arg1 = args[index++]) == null) { - throw new IllegalStateException( - this.m_tool1Name + " binary '" + exec//$NON-NLS-1$ - + "' does not offer option 'output-format' when asked via '-help'.");//$NON-NLS-1$ - } - } - - if (progname != null) { - if ((arg3 = args[index]) == null) { - throw new IllegalStateException(// - this.m_tool1Name + " binary '" + exec + //$NON-NLS-1$ - "' does not offer option 'progname' when asked via '-help'.");//$NON-NLS-1$ - } - } - - } catch (final Throwable err) { - error = err; - arg1 = arg2 = arg3 = null; - exec = null; - } - } else { - progname = null; - } - - this.m_executable = exec; - this.m_formatArg = ((arg1 != null) ? (arg1 + // - this._produces().getDefaultSuffix().toLowerCase()) - : null); - this.m_haltArg = arg2; - this.m_progNameArg = ((arg3 != null) ? (arg3 + progname) : null); - this.m_error = error; - - if ((logger != null) && (logger.isLoggable(Level.CONFIG))) { - logger.config(((this.m_executable != null) ? "" : "No ") + //$NON-NLS-1$ //$NON-NLS-2$ - (this.m_tool1Name + " executable '" + this.m_executable + //$NON-NLS-1$ - "' which can be used as " + //$NON-NLS-1$ - this.m_tool2Name + " found.")); //$NON-NLS-1$ - } - } - - /** - * get the program name to use, or {@code null} if none is necessary - * - * @return the program name to use, or {@code null} if none is necessary - */ - String _getProcName() { - return null; - } - - /** - * Do we need a parameter for the output format? - * - * @return {@code true} if we need such a parameter, {@code false} - * otherwise - */ - boolean _needsOutputFormat() { - return true; - } - - /** - * Obtain the path to the executable - * - * @return the path to the executable, or {@code null} if none was found - */ - abstract Path _getExecutable(); - - /** {@inheritDoc} */ - @Override - final boolean _canUse() { - return ((this.m_executable != null) && // - ((this.m_formatArg != null) || (!(this._needsOutputFormat()))) && // - (this.m_error == null) && // - ((this.m_progNameArg != null) || (this._getProcName() == null))); - } - - /** {@inheritDoc} */ - @Override - final void _use(final _LaTeXMainJob job) throws IOException { - final Logger logger; - final Path exec, tex; - final ExternalProcessBuilder builder; - final ELaTeXFileType type; - final int ret; - final boolean needsOutput; - boolean ok; - - if (this.m_error != null) { - throw new UnsupportedOperationException(// - this.m_tool1Name - + " cannot be used as "//$NON-NLS-1$ - + this.m_tool2Name - + " compiler because... (see causing error).",//$NON-NLS-1$ - this.m_error); - } - needsOutput = this._needsOutputFormat(); - if (needsOutput) { - if (this.m_formatArg == null) { - throw new UnsupportedOperationException(// - this.m_tool1Name + " cannot be used as " + //$NON-NLS-1$ - this.m_tool2Name + // - " compiler because no corresponding option was detected.");//$NON-NLS-1$ - } - } - if (this.m_progNameArg == null) { - if (this._getProcName() != null) { - throw new UnsupportedOperationException(// - this.m_tool1Name + " cannot be used as " + //$NON-NLS-1$ - this.m_tool2Name + // - " compiler because no corresponding 'progname' option was detected.");//$NON-NLS-1$ - } - } - if ((exec = this.m_executable) == null) { - throw new UnsupportedOperationException("No " + this.m_tool1Name + //$NON-NLS-1$ - " binary that can be used as " + //$NON-NLS-1$ - this.m_tool2Name + " detected."); //$NON-NLS-1$ - } - - if ((tex = this._getFile(job, ELaTeXFileType.TEX, true, null)) == null) { - return; - } - if (this._getFile(job, ELaTeXFileType.AUX, false, null) == null) { - return; - } - - type = this._produces(); - if (this._getFile(job, type, false, null) == null) { - return; - } - - logger = job._getLogger(); - if ((logger != null) && (logger.isLoggable(Level.INFO))) { - logger.info(// - (("Applying " + this.m_toolName + //$NON-NLS-1$ - " to '" + tex) + '\'') + '.'); //$NON-NLS-1$ - } - - builder = ProcessExecutor.getInstance().use(); - builder.setDirectory(job._getDirectory()); - builder.setExecutable(exec); - if (this.m_formatArg != null) { - builder.addStringArgument(this.m_formatArg); - } - if (this.m_progNameArg != null) { - builder.addStringArgument(this.m_progNameArg); - } - if (this.m_haltArg != null) { - builder.addStringArgument(this.m_haltArg); - } - builder.addPathArgument(tex); - builder.setLogger(logger); - builder.setStdErr(EProcessStream.REDIRECT_TO_LOGGER); - builder.setStdOut(EProcessStream.REDIRECT_TO_LOGGER); - builder.setStdIn(EProcessStream.IGNORE); - - try (ExternalProcess proc = builder.create()) { - if ((ret = proc.waitFor()) != 0) { - throw new IOException(((((((this.m_tool1Name + " executable '" //$NON-NLS-1$ - + exec) + "' (used as " + this.m_tool2Name + //$NON-NLS-1$ - ") returned value ") + ret) + //$NON-NLS-1$ - ", which indicates an error, for tex file '") + //$NON-NLS-1$ - tex) + '\'') + '.'); - } - } - - ok = true; - if (this - ._getFile( - job, - ELaTeXFileType.AUX, - true, - " This could mean that the latex document does not contain any label, citation, or section."//$NON-NLS-1$ - ) == null) { - ok = false; - } - if (this._getFile(job, type, true, - " This could mean that the latex document does not produce any output."//$NON-NLS-1$ - ) == null) { - ok = false; - } - - if (ok) { - if ((logger != null) && (logger.isLoggable(Level.FINE))) { - logger.fine(// - (("Finished applying " + this.m_toolName + //$NON-NLS-1$ - " to '" + tex) + '\'') + '.'); //$NON-NLS-1$ - } - } - } - - /** {@inheritDoc} */ - @Override - public final void toText(final ITextOutput textOut) { - textOut.append(this.m_toolName); - textOut.append('('); - textOut.append(this.m_executable); - if (this.m_formatArg != null) { - textOut.append(' '); - textOut.append(this.m_formatArg); - } - if (this.m_progNameArg != null) { - textOut.append(' '); - textOut.append(this.m_progNameArg); - } - if (this.m_haltArg != null) { - textOut.append(' '); - textOut.append(this.m_haltArg); - } - textOut.append(')'); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/pair.info deleted file mode 100755 index 27c333f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75268/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75268 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/tools/impl/latex/_LaTeXUsedAsToolBase.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/tools/impl/latex/_LaTeXUsedAsToolBase.java -StartLineNum:126 -EndLineNum:126 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/diff.diff deleted file mode 100755 index a61127e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/collections/maps/StringMapCI.java b/src/main/java/org/optimizationBenchmarking/utils/collections/maps/StringMapCI.java -index fd367438..814d2284 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/collections/maps/StringMapCI.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/collections/maps/StringMapCI.java -@@ -2,0 +3,2 @@ package org.optimizationBenchmarking.utils.collections.maps; -+import org.optimizationBenchmarking.utils.text.TextUtils; -+ -@@ -30 +32 @@ public class StringMapCI extends StringMap { -- return t.toLowerCase(); -+ return TextUtils.toLowerCase(t); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/new/StringMapCI.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/new/StringMapCI.java deleted file mode 100755 index 814d228..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/new/StringMapCI.java +++ /dev/null @@ -1,36 +0,0 @@ -package org.optimizationBenchmarking.utils.collections.maps; - -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - * A case-insensitive hash map that uses {@link java.lang.String}s as keys. - * All keys will be converted to lower case. Since the case of key strings - * is ignored, this implementation breaks with some of the contracts of - * {@link java.util.Map}. For instance, this map may return {@code true} - * when queried whether it {@link java.util.Map#equals(Object) equals} - * another map, although it may have a different - * {@link java.util.Map#hashCode() hash code}. - * - * @param - * the element type - */ -public class StringMapCI extends StringMap { - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** create the hash map */ - public StringMapCI() { - super(); - } - - /** {@inheritDoc} */ - @Override - final String _prepare(final String s) { - final String t; - t = super._prepare(s); - if (t != null) { - return TextUtils.toLowerCase(t); - } - return null; - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/old/StringMapCI.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/old/StringMapCI.java deleted file mode 100755 index fd36743..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/old/StringMapCI.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.optimizationBenchmarking.utils.collections.maps; - -/** - * A case-insensitive hash map that uses {@link java.lang.String}s as keys. - * All keys will be converted to lower case. Since the case of key strings - * is ignored, this implementation breaks with some of the contracts of - * {@link java.util.Map}. For instance, this map may return {@code true} - * when queried whether it {@link java.util.Map#equals(Object) equals} - * another map, although it may have a different - * {@link java.util.Map#hashCode() hash code}. - * - * @param - * the element type - */ -public class StringMapCI extends StringMap { - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** create the hash map */ - public StringMapCI() { - super(); - } - - /** {@inheritDoc} */ - @Override - final String _prepare(final String s) { - final String t; - t = super._prepare(s); - if (t != null) { - return t.toLowerCase(); - } - return null; - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/pair.info deleted file mode 100755 index b9354ac..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75294/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75294 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/collections/maps/StringMapCI.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/collections/maps/StringMapCI.java -StartLineNum:30 -EndLineNum:30 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/diff.diff deleted file mode 100755 index 27a4445..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/math/functions/MathematicalFunction.java b/src/main/java/org/optimizationBenchmarking/utils/math/functions/MathematicalFunction.java -index 97cdcd74..b5249cbf 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/math/functions/MathematicalFunction.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/math/functions/MathematicalFunction.java -@@ -7,0 +8 @@ import org.optimizationBenchmarking.utils.math.text.IParameterRenderer; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -519 +520 @@ public abstract class MathematicalFunction implements Serializable, -- return this.getClass().getSimpleName().toLowerCase(); -+ return TextUtils.toLowerCase(this.getClass().getSimpleName()); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/new/MathematicalFunction.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/new/MathematicalFunction.java deleted file mode 100755 index b5249cb..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/new/MathematicalFunction.java +++ /dev/null @@ -1,522 +0,0 @@ -package org.optimizationBenchmarking.utils.math.functions; - -import java.io.Serializable; - -import org.optimizationBenchmarking.utils.document.spec.IMath; -import org.optimizationBenchmarking.utils.math.text.IMathRenderable; -import org.optimizationBenchmarking.utils.math.text.IParameterRenderer; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; - -/** - *

- * The base class for mathematical functions. It is our goal to implement - * many mathematical functions in a way that can - *

- *
    - *
  1. make use of inheritance and overriding in order to allow for a great - * versatility and provide the chance to construct more complex functions - * and operations
  2. - *
  3. is very fast and efficient to access, i.e., has routines that can - * efficiently inlined by a compiler
  4. - *
- */ -public abstract class MathematicalFunction implements Serializable, - IMathRenderable { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** - * The default precedence priority: it should be somewhere between an - * addition and a multiplication. - */ - protected static final int DEFAULT_PRECEDENCE_PRIORITY = 0; - - /** - * Instantiate the basic function class. - */ - protected MathematicalFunction() { - super(); - } - - /** - * Get the minimum arity of this function, i.e., the number of arguments - * it requires at least. - * - * @return the number of arguments that this function needs at least - * @see #getMaxArity() - */ - public abstract int getMinArity(); - - /** - * Get the maximum arity of this function, i.e., the number of arguments - * it permits at most. - * - * @return the number of arguments that this function needs accepts at - * most - * @see #getMinArity() - */ - public abstract int getMaxArity(); - - /** - * throws the illegal argument exception caused by a NaN return value for - * an integer function. - * - * @throws IllegalArgumentException - * always - */ - final void _throwIllegalNaN() { - throw new IllegalArgumentException(// - "The integer-based '" + this.toString() + //$NON-NLS-1$ - "' delegate to a real-valued calculation has returned NaN."); //$NON-NLS-1$ - } - - /** - * throws the illegal argument exception caused by an illegal arity for - * an integer function. - * - * @param length - * the dimension of the argument - * @throws IllegalArgumentException - * always - */ - final void _checkArity(final int length) { - int x; - - x = this.getMinArity(); - if (length < x) { - throw new IllegalArgumentException(// - "The function '" + this.toString() + //$NON-NLS-1$ - "' requires at least " + x + //$NON-NLS-1$ - " parameters, but was invoked with " + length + //$NON-NLS-1$ - " arguments."); //$NON-NLS-1$ - } - x = this.getMaxArity(); - if (length < x) { - throw new IllegalArgumentException(// - "The function '" + this.toString() + //$NON-NLS-1$ - "' allows at most " + x + //$NON-NLS-1$ - " parameters, but was invoked with " + length + //$NON-NLS-1$ - " arguments."); //$NON-NLS-1$ - } - } - - /** - * Compute the result of this function when all parameters are - * {@code double} valued. - * - * @param x - * the vector of parameters, which must contain (at least) - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code double} values - * @return the result of this function, computed in {@code double} - * precision - */ - public double computeAsDouble(final double... x) { - throw new UnsupportedOperationException(); - } - - /** - * Compute the result of this function as {@code double} when all - * parameters are {@code long} valued. - * - * @param x - * the vector of parameters, which must contain (at least) - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code long} values - * @return the result of this function, computed in {@code double} - * precision - */ - public double computeAsDouble(final long... x) { - final double[] a; - int i; - - i = x.length; - this._checkArity(i); - - a = new double[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - return this.computeAsDouble(a); - } - - /** - * Compute the result of this function as {@code double} when all - * parameters are {@code int} valued. - * - * @param x - * the vector of parameters, which must contain (at least) - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code int} values - * @return the result of this function, computed in {@code double} - * precision - */ - public double computeAsDouble(final int... x) { - final long[] a; - int i; - - i = x.length; - this._checkArity(i); - - a = new long[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - return this.computeAsDouble(a); - } - - /** - * Compute the function value in the {@code byte} domain. This basic - * function template delegates the computation to the {@code int} variant - * of this function. The {@code int} result of that function is then - * casted to {@code byte}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code byte} values - * @return the return value of this function, a byte - * @throws IllegalArgumentException - * if a floating point delegate in the delegation chain returns - * {@code Double.NaN}. - */ - public byte computeAsByte(final byte... x) { - final int[] a; - int i; - final int r; - - i = x.length; - this._checkArity(i); - - a = new int[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = Math.min(Byte.MAX_VALUE, - Math.max(Byte.MIN_VALUE, this.computeAsInt(a))); - return ((byte) (r)); - } - - /** - * Compute the function value in the {@code short} domain. This basic - * function template delegates the computation to the {@code int} variant - * of this function. The {@code int} result of that function is then - * casted to {@code short}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code short} values - * @return the return value of this function, a short - * @throws IllegalArgumentException - * if a floating point delegate in the delegation chain returns - * {@code Double.NaN}. - */ - public short computeAsShort(final short... x) { - final int[] a; - int i; - final int r; - - i = x.length; - this._checkArity(i); - - a = new int[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = Math.min(Short.MAX_VALUE, - Math.max(Short.MIN_VALUE, this.computeAsInt(a))); - return ((short) (r)); - } - - /** - * Compute the function value in the {@code int} domain. This basic - * function template delegates the computation to the {@code long} - * variant of this function. The {@code long} result of that function is - * then casted to {@code int}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code int} values - * @return the return value of this function, a int - * @throws IllegalArgumentException - * if a floating point delegate in the delegation chain returns - * {@code Double.NaN}. - */ - public int computeAsInt(final int... x) { - final long[] a; - int i; - final long r; - - i = x.length; - this._checkArity(i); - - a = new long[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = Math.min(Integer.MAX_VALUE, - Math.max(Integer.MIN_VALUE, this.computeAsLong(a))); - return ((int) (r)); - } - - /** - * Compute the function value in the {@code long} domain. This basic - * function template delegates the computation to the {@code double} - * variant of this function. The {@code double} result of that function - * is then casted to {@code long}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code long} values - * @return the return value of this function, a long - * @throws IllegalArgumentException - * if a floating point delegate in the delegation chain returns - * {@code Double.NaN}. - */ - public long computeAsLong(final long... x) { - final double[] a; - int i; - final double r; - - i = x.length; - this._checkArity(i); - - a = new double[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = this.computeAsDouble(a); - if (r <= (java.lang.Double.NEGATIVE_INFINITY)) { - return (java.lang.Long.MIN_VALUE); - } - if (r >= (java.lang.Double.POSITIVE_INFINITY)) { - return (java.lang.Long.MAX_VALUE); - } - if (java.lang.Double.isNaN(r)) { - this._throwIllegalNaN(); - } - return ((long) ((r))); - } - - /** - * Compute the function value in the {@code float} domain. This basic - * function template delegates the computation to the {@code double} - * variant of this function. The {@code double} result of that function - * is then casted to {@code float}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code float} values - * @return the return value of this function, a float - */ - public float computeAsFloat(final float... x) { - final double[] a; - int i; - final double r; - - i = x.length; - this._checkArity(i); - - a = new double[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = this.computeAsDouble(a); - return ((float) (r)); - } - - /** - *

- * Invert the function for the parameter at index {@code index}. If an - * inverse function exists for the parameter at index {@code index}, the - * result will a pointer to the object implementing said inverse - * (otherwise it will be {@code null}). - *

- *

- * If this function here is a n-ary function like - * {@code f(x0, x1, x2, ...) = r}, then {@code f.invertFor(1)} should - * return a function {@code g} such that - * {@code g(x0, f(x0, x1, x2, ...), x1, x2, ...) = x1}, i.e., the result - * of the original function takes the place of the {@code (index+1)} - * th argument. - *

- *

- * Notice that the existence of an inverse function for a given parameter - * {@code index} does not mean that it is defined for all parameters. For - * example, multiplication is an inverse for division, but a division by - * zero may not be invertible. - *

- * - * @param index - * the index of the parameter with - * 0≤index<{@link #getMaxArity()} - * @return the inverse function, if it exists, {@code null} otherwise - */ - public MathematicalFunction invertFor(final int index) { - return null; - } - - /** - *

- * Get the derivative of the function for the parameter at index - * {@code index}. If a derivative function exists for the parameter at - * index {@code index}, the result will a pointer to the object - * implementing said derivative (otherwise it will be {@code null}). - *

- *

- * If this function here is an {@code n}-ary function, then the - * derivative will either also be an {@code n}-ary function with the same - * parameters as the original function, or it will be an {@code n-1}-ary - * function where the parameter at index {@code index} is left out (if it - * disappeared during the differentiation procedure). - *

- * - * @param index - * the index of the parameter with - * 0≤index<{@link #getMaxArity()} - * @return the derivative function, if it exists, {@code null} otherwise - */ - public MathematicalFunction derivativeFor(final int index) { - return null; - } - - /** - *

- * Get the integral of the function for the parameter at index - * {@code index}. If an integral function exists for the parameter at - * index {@code index}, the result will a pointer to the object - * implementing said integral (otherwise it will be {@code null}). Of - * course, all integrals could have an added constant {@code c}. We - * assume that {@code c=0} here. - *

- * - * @param index - * the index of the parameter with - * 0≤index<{@link #getMaxArity()} - * @return the integral function, if it exists, {@code null} otherwise - */ - public MathematicalFunction integrateFor(final int index) { - return null; - } - - /** - * This instance equals to any object of the same class. The reason is - * that mathematical functions are usually singletons. - * - * @param o - * the object - * @return {@code true} if {@code o} is an instance of the same class, - * {@code false} otherwise - */ - @Override - public boolean equals(final Object o) { - return ((o == this) || // - ((o != null) && (this.getClass() == o.getClass()))); - } - - /** - * The hash code here is set to the hash code of the class, since - * mathematical functions are usually singletons. - * - * @return the hash code - */ - @Override - public int hashCode() { - return this.getClass().hashCode(); - } - - /** - * Is a calculation in {@code long} arithmetic accurate? Some - * mathematical functions will always return the correct result for - * {@link #computeAsLong(long...)}, for example min, max, round, etc. - * Others will not (such as {@code +} (due to possible overflows) and - * {@code sin}). - * - * @return {@code true} if calculating values in {@code long} arithmetic - * will always return accurate results, {@code false} otherwise - */ - public boolean isLongArithmeticAccurate() { - return false; - } - - /** - * Render this mathematical function to the given text output device - * - * @param out - * the text output device - * @param renderer - * the parameter renderer - */ - @Override - public void mathRender(final ITextOutput out, - final IParameterRenderer renderer) { - final int arity; - char separator; - int index; - - out.append(this.toString()); - separator = '('; - arity = this.getMinArity(); - - for (index = 0; index < arity; index++) { - out.append(separator); - separator = ','; - renderer.renderParameter(index, out); - } - - out.append(')'); - } - - /** - * Render this mathematical function to the given math output device - * - * @param out - * the math output device - * @param renderer - * the parameter renderer - */ - @Override - public void mathRender(final IMath out, final IParameterRenderer renderer) { - final int arity; - int index; - - arity = this.getMinArity(); - try (final IMath math = out.nAryFunction(// - this.toString(), arity, arity)) { - for (index = 0; index < arity; index++) { - renderer.renderParameter(index, math); - } - } - } - - /** - * Obtain the precedence - * priority of this operator. The higher the returned value is, the - * more "binding" it is to its arguments. - * - * @return the precedence priority - */ - public int getPrecedencePriority() { - return MathematicalFunction.DEFAULT_PRECEDENCE_PRIORITY; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return TextUtils.toLowerCase(this.getClass().getSimpleName()); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/old/MathematicalFunction.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/old/MathematicalFunction.java deleted file mode 100755 index 97cdcd7..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/old/MathematicalFunction.java +++ /dev/null @@ -1,521 +0,0 @@ -package org.optimizationBenchmarking.utils.math.functions; - -import java.io.Serializable; - -import org.optimizationBenchmarking.utils.document.spec.IMath; -import org.optimizationBenchmarking.utils.math.text.IMathRenderable; -import org.optimizationBenchmarking.utils.math.text.IParameterRenderer; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; - -/** - *

- * The base class for mathematical functions. It is our goal to implement - * many mathematical functions in a way that can - *

- *
    - *
  1. make use of inheritance and overriding in order to allow for a great - * versatility and provide the chance to construct more complex functions - * and operations
  2. - *
  3. is very fast and efficient to access, i.e., has routines that can - * efficiently inlined by a compiler
  4. - *
- */ -public abstract class MathematicalFunction implements Serializable, - IMathRenderable { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** - * The default precedence priority: it should be somewhere between an - * addition and a multiplication. - */ - protected static final int DEFAULT_PRECEDENCE_PRIORITY = 0; - - /** - * Instantiate the basic function class. - */ - protected MathematicalFunction() { - super(); - } - - /** - * Get the minimum arity of this function, i.e., the number of arguments - * it requires at least. - * - * @return the number of arguments that this function needs at least - * @see #getMaxArity() - */ - public abstract int getMinArity(); - - /** - * Get the maximum arity of this function, i.e., the number of arguments - * it permits at most. - * - * @return the number of arguments that this function needs accepts at - * most - * @see #getMinArity() - */ - public abstract int getMaxArity(); - - /** - * throws the illegal argument exception caused by a NaN return value for - * an integer function. - * - * @throws IllegalArgumentException - * always - */ - final void _throwIllegalNaN() { - throw new IllegalArgumentException(// - "The integer-based '" + this.toString() + //$NON-NLS-1$ - "' delegate to a real-valued calculation has returned NaN."); //$NON-NLS-1$ - } - - /** - * throws the illegal argument exception caused by an illegal arity for - * an integer function. - * - * @param length - * the dimension of the argument - * @throws IllegalArgumentException - * always - */ - final void _checkArity(final int length) { - int x; - - x = this.getMinArity(); - if (length < x) { - throw new IllegalArgumentException(// - "The function '" + this.toString() + //$NON-NLS-1$ - "' requires at least " + x + //$NON-NLS-1$ - " parameters, but was invoked with " + length + //$NON-NLS-1$ - " arguments."); //$NON-NLS-1$ - } - x = this.getMaxArity(); - if (length < x) { - throw new IllegalArgumentException(// - "The function '" + this.toString() + //$NON-NLS-1$ - "' allows at most " + x + //$NON-NLS-1$ - " parameters, but was invoked with " + length + //$NON-NLS-1$ - " arguments."); //$NON-NLS-1$ - } - } - - /** - * Compute the result of this function when all parameters are - * {@code double} valued. - * - * @param x - * the vector of parameters, which must contain (at least) - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code double} values - * @return the result of this function, computed in {@code double} - * precision - */ - public double computeAsDouble(final double... x) { - throw new UnsupportedOperationException(); - } - - /** - * Compute the result of this function as {@code double} when all - * parameters are {@code long} valued. - * - * @param x - * the vector of parameters, which must contain (at least) - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code long} values - * @return the result of this function, computed in {@code double} - * precision - */ - public double computeAsDouble(final long... x) { - final double[] a; - int i; - - i = x.length; - this._checkArity(i); - - a = new double[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - return this.computeAsDouble(a); - } - - /** - * Compute the result of this function as {@code double} when all - * parameters are {@code int} valued. - * - * @param x - * the vector of parameters, which must contain (at least) - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code int} values - * @return the result of this function, computed in {@code double} - * precision - */ - public double computeAsDouble(final int... x) { - final long[] a; - int i; - - i = x.length; - this._checkArity(i); - - a = new long[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - return this.computeAsDouble(a); - } - - /** - * Compute the function value in the {@code byte} domain. This basic - * function template delegates the computation to the {@code int} variant - * of this function. The {@code int} result of that function is then - * casted to {@code byte}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code byte} values - * @return the return value of this function, a byte - * @throws IllegalArgumentException - * if a floating point delegate in the delegation chain returns - * {@code Double.NaN}. - */ - public byte computeAsByte(final byte... x) { - final int[] a; - int i; - final int r; - - i = x.length; - this._checkArity(i); - - a = new int[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = Math.min(Byte.MAX_VALUE, - Math.max(Byte.MIN_VALUE, this.computeAsInt(a))); - return ((byte) (r)); - } - - /** - * Compute the function value in the {@code short} domain. This basic - * function template delegates the computation to the {@code int} variant - * of this function. The {@code int} result of that function is then - * casted to {@code short}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code short} values - * @return the return value of this function, a short - * @throws IllegalArgumentException - * if a floating point delegate in the delegation chain returns - * {@code Double.NaN}. - */ - public short computeAsShort(final short... x) { - final int[] a; - int i; - final int r; - - i = x.length; - this._checkArity(i); - - a = new int[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = Math.min(Short.MAX_VALUE, - Math.max(Short.MIN_VALUE, this.computeAsInt(a))); - return ((short) (r)); - } - - /** - * Compute the function value in the {@code int} domain. This basic - * function template delegates the computation to the {@code long} - * variant of this function. The {@code long} result of that function is - * then casted to {@code int}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code int} values - * @return the return value of this function, a int - * @throws IllegalArgumentException - * if a floating point delegate in the delegation chain returns - * {@code Double.NaN}. - */ - public int computeAsInt(final int... x) { - final long[] a; - int i; - final long r; - - i = x.length; - this._checkArity(i); - - a = new long[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = Math.min(Integer.MAX_VALUE, - Math.max(Integer.MIN_VALUE, this.computeAsLong(a))); - return ((int) (r)); - } - - /** - * Compute the function value in the {@code long} domain. This basic - * function template delegates the computation to the {@code double} - * variant of this function. The {@code double} result of that function - * is then casted to {@code long}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code long} values - * @return the return value of this function, a long - * @throws IllegalArgumentException - * if a floating point delegate in the delegation chain returns - * {@code Double.NaN}. - */ - public long computeAsLong(final long... x) { - final double[] a; - int i; - final double r; - - i = x.length; - this._checkArity(i); - - a = new double[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = this.computeAsDouble(a); - if (r <= (java.lang.Double.NEGATIVE_INFINITY)) { - return (java.lang.Long.MIN_VALUE); - } - if (r >= (java.lang.Double.POSITIVE_INFINITY)) { - return (java.lang.Long.MAX_VALUE); - } - if (java.lang.Double.isNaN(r)) { - this._throwIllegalNaN(); - } - return ((long) ((r))); - } - - /** - * Compute the function value in the {@code float} domain. This basic - * function template delegates the computation to the {@code double} - * variant of this function. The {@code double} result of that function - * is then casted to {@code float}. - * - * @param x - * the vector of parameters, which must contain at least - * {@link #getMinArity()} and at most {@link #getMaxArity()} - * {@code float} values - * @return the return value of this function, a float - */ - public float computeAsFloat(final float... x) { - final double[] a; - int i; - final double r; - - i = x.length; - this._checkArity(i); - - a = new double[i]; - for (; (--i) >= 0;) { - a[i] = (x[i]); - } - - r = this.computeAsDouble(a); - return ((float) (r)); - } - - /** - *

- * Invert the function for the parameter at index {@code index}. If an - * inverse function exists for the parameter at index {@code index}, the - * result will a pointer to the object implementing said inverse - * (otherwise it will be {@code null}). - *

- *

- * If this function here is a n-ary function like - * {@code f(x0, x1, x2, ...) = r}, then {@code f.invertFor(1)} should - * return a function {@code g} such that - * {@code g(x0, f(x0, x1, x2, ...), x1, x2, ...) = x1}, i.e., the result - * of the original function takes the place of the {@code (index+1)} - * th argument. - *

- *

- * Notice that the existence of an inverse function for a given parameter - * {@code index} does not mean that it is defined for all parameters. For - * example, multiplication is an inverse for division, but a division by - * zero may not be invertible. - *

- * - * @param index - * the index of the parameter with - * 0≤index<{@link #getMaxArity()} - * @return the inverse function, if it exists, {@code null} otherwise - */ - public MathematicalFunction invertFor(final int index) { - return null; - } - - /** - *

- * Get the derivative of the function for the parameter at index - * {@code index}. If a derivative function exists for the parameter at - * index {@code index}, the result will a pointer to the object - * implementing said derivative (otherwise it will be {@code null}). - *

- *

- * If this function here is an {@code n}-ary function, then the - * derivative will either also be an {@code n}-ary function with the same - * parameters as the original function, or it will be an {@code n-1}-ary - * function where the parameter at index {@code index} is left out (if it - * disappeared during the differentiation procedure). - *

- * - * @param index - * the index of the parameter with - * 0≤index<{@link #getMaxArity()} - * @return the derivative function, if it exists, {@code null} otherwise - */ - public MathematicalFunction derivativeFor(final int index) { - return null; - } - - /** - *

- * Get the integral of the function for the parameter at index - * {@code index}. If an integral function exists for the parameter at - * index {@code index}, the result will a pointer to the object - * implementing said integral (otherwise it will be {@code null}). Of - * course, all integrals could have an added constant {@code c}. We - * assume that {@code c=0} here. - *

- * - * @param index - * the index of the parameter with - * 0≤index<{@link #getMaxArity()} - * @return the integral function, if it exists, {@code null} otherwise - */ - public MathematicalFunction integrateFor(final int index) { - return null; - } - - /** - * This instance equals to any object of the same class. The reason is - * that mathematical functions are usually singletons. - * - * @param o - * the object - * @return {@code true} if {@code o} is an instance of the same class, - * {@code false} otherwise - */ - @Override - public boolean equals(final Object o) { - return ((o == this) || // - ((o != null) && (this.getClass() == o.getClass()))); - } - - /** - * The hash code here is set to the hash code of the class, since - * mathematical functions are usually singletons. - * - * @return the hash code - */ - @Override - public int hashCode() { - return this.getClass().hashCode(); - } - - /** - * Is a calculation in {@code long} arithmetic accurate? Some - * mathematical functions will always return the correct result for - * {@link #computeAsLong(long...)}, for example min, max, round, etc. - * Others will not (such as {@code +} (due to possible overflows) and - * {@code sin}). - * - * @return {@code true} if calculating values in {@code long} arithmetic - * will always return accurate results, {@code false} otherwise - */ - public boolean isLongArithmeticAccurate() { - return false; - } - - /** - * Render this mathematical function to the given text output device - * - * @param out - * the text output device - * @param renderer - * the parameter renderer - */ - @Override - public void mathRender(final ITextOutput out, - final IParameterRenderer renderer) { - final int arity; - char separator; - int index; - - out.append(this.toString()); - separator = '('; - arity = this.getMinArity(); - - for (index = 0; index < arity; index++) { - out.append(separator); - separator = ','; - renderer.renderParameter(index, out); - } - - out.append(')'); - } - - /** - * Render this mathematical function to the given math output device - * - * @param out - * the math output device - * @param renderer - * the parameter renderer - */ - @Override - public void mathRender(final IMath out, final IParameterRenderer renderer) { - final int arity; - int index; - - arity = this.getMinArity(); - try (final IMath math = out.nAryFunction(// - this.toString(), arity, arity)) { - for (index = 0; index < arity; index++) { - renderer.renderParameter(index, math); - } - } - } - - /** - * Obtain the precedence - * priority of this operator. The higher the returned value is, the - * more "binding" it is to its arguments. - * - * @return the precedence priority - */ - public int getPrecedencePriority() { - return MathematicalFunction.DEFAULT_PRECEDENCE_PRIORITY; - } - - /** {@inheritDoc} */ - @Override - public String toString() { - return this.getClass().getSimpleName().toLowerCase(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/pair.info deleted file mode 100755 index f3428a5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75308/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75308 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/math/functions/MathematicalFunction.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/math/functions/MathematicalFunction.java -StartLineNum:519 -EndLineNum:519 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/diff.diff deleted file mode 100755 index f853867..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/math/text/MathematicalFunctionParser.java b/src/main/java/org/optimizationBenchmarking/utils/math/text/MathematicalFunctionParser.java -index 6d8ffaa5..b26ec02a 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/math/text/MathematicalFunctionParser.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/math/text/MathematicalFunctionParser.java -@@ -133 +133 @@ public final class MathematicalFunctionParser extends -- lowerCase = preProcessed.toLowerCase(); -+ lowerCase = TextUtils.toLowerCase(preProcessed); -@@ -184 +184 @@ public final class MathematicalFunctionParser extends -- func = super.parseString(Character.toUpperCase(first) -+ func = super.parseString(TextUtils.toUpperCase(first) -@@ -197 +197 @@ public final class MathematicalFunctionParser extends -- func = super.parseString(Character.toUpperCase(first) -+ func = super.parseString(TextUtils.toUpperCase(first) \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/new/MathematicalFunctionParser.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/new/MathematicalFunctionParser.java deleted file mode 100755 index b26ec02..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/new/MathematicalFunctionParser.java +++ /dev/null @@ -1,346 +0,0 @@ -package org.optimizationBenchmarking.utils.math.text; - -import java.util.LinkedHashSet; - -import org.optimizationBenchmarking.utils.math.functions.MathematicalFunction; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.Absolute; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.Add; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.ModuloDivisorSign; -import org.optimizationBenchmarking.utils.math.functions.binary.BAnd; -import org.optimizationBenchmarking.utils.math.functions.combinatoric.Factorial; -import org.optimizationBenchmarking.utils.math.functions.hyperbolic.ACosh; -import org.optimizationBenchmarking.utils.math.functions.hyperbolic.ASinh; -import org.optimizationBenchmarking.utils.math.functions.hyperbolic.ATanh; -import org.optimizationBenchmarking.utils.math.functions.logic.LAnd; -import org.optimizationBenchmarking.utils.math.functions.numeric.Ceil; -import org.optimizationBenchmarking.utils.math.functions.power.Ld; -import org.optimizationBenchmarking.utils.math.functions.power.Lg; -import org.optimizationBenchmarking.utils.math.functions.power.Log; -import org.optimizationBenchmarking.utils.math.functions.power.Pow; -import org.optimizationBenchmarking.utils.math.functions.power.Sqrt; -import org.optimizationBenchmarking.utils.math.functions.special.Beta; -import org.optimizationBenchmarking.utils.math.functions.special.ErrorFunction; -import org.optimizationBenchmarking.utils.math.functions.stochastic.NormalCDF; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.ACos; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.ASin; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.ATan; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.Cos; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.Sin; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.Tan; -import org.optimizationBenchmarking.utils.parsers.InstanceParser; -import org.optimizationBenchmarking.utils.reflection.ReflectionUtils; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - * A parser for singular instances of - * {@link org.optimizationBenchmarking.utils.math.functions.MathematicalFunction} - * , such as simple addition or subtraction. If you are looking for - * compound functions such as {@code 4+5*7*x}, use - * {@link org.optimizationBenchmarking.utils.math.text.CompoundFunctionParser} - * . - */ -public final class MathematicalFunctionParser extends - InstanceParser { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** create */ - MathematicalFunctionParser() { - super(MathematicalFunction.class, MathematicalFunctionParser - .__prefixes()); - } - - /** - * get the prefixes - * - * @return the path prefixes - */ - private static final String[] __prefixes() { - final LinkedHashSet paths; - - paths = new LinkedHashSet<>(); - ReflectionUtils.addPackageOfClassToPrefixList( - MathematicalFunctionParser.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Add.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - BAnd.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Factorial.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - ACosh.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - LAnd.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Ceil.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Sqrt.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Beta.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - NormalCDF.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Sin.class, paths); - return paths.toArray(new String[paths.size()]); - } - - /** {@inheritDoc} */ - @Override - public final MathematicalFunction parseString(final String string) - throws Exception { - _ParsedFunction func; - - func = this._parseString(string); - if (func != null) { - return func.m_func; - } - throw new IllegalStateException("No function parsed from '" //$NON-NLS-1$ - + string + '\''); - } - - /** - * Parse a mathematical function string - * - * @param string - * the string - * @return the function - */ - @SuppressWarnings("incomplete-switch") - final _ParsedFunction _parseString(final String string) { - final String preProcessed, lowerCase; - final char first; - _ParsedFunction parsed; - MathematicalFunction func; - Throwable error; - - preProcessed = TextUtils.prepare(string); - if (string == null) { - throw new IllegalArgumentException(((// - "String to be parsed to a mathematical function cannot be empty, null, or just consist of white spaces, but you supplied '"//$NON-NLS-1$ - + string) + '\'') + '.'); - } - - first = preProcessed.charAt(0); - if (preProcessed.length() == 1) { - parsed = MathematicalFunctionParser._parseChar(preProcessed - .charAt(0)); - if (parsed != null) { - return parsed; - } - } - - lowerCase = TextUtils.toLowerCase(preProcessed); - func = null; - error = null; - findFunc: { - switch (lowerCase) { - case "^2": {return _ParsedFunction.SQR_POSTFIX;} //$NON-NLS-1$ - case "^3": {return _ParsedFunction.CUBE_POSTFIX;} //$NON-NLS-1$ - case "**": {return _ParsedFunction.POW_INFIX;} //$NON-NLS-1$ - case "10**": {return _ParsedFunction.POW10_PREFIX;} //$NON-NLS-1$ - case "2**": {return _ParsedFunction.POW2_PREFIX;} //$NON-NLS-1$ - case "10^": {return _ParsedFunction.POW10_PREFIX;} //$NON-NLS-1$ - case "2^": {return _ParsedFunction.POW2_PREFIX;} //$NON-NLS-1$ - case "abs"://$NON-NLS-1$ - case "absolute": {func = Absolute.INSTANCE;break findFunc;}//$NON-NLS-1$ - case "acos": {func = ACos.INSTANCE;break findFunc;}//$NON-NLS-1$ - case "acosh": {func = ACosh.INSTANCE;break findFunc;}//$NON-NLS-1$ - case "asin": {func = ASin.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "asinh": {func = ASinh.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "atan": {func = ATan.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "atanh": {func = ATanh.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "cosine": {func = Cos.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "e^": {return _ParsedFunction.EXP_PREFIX;} //$NON-NLS-1$ - case "erf": {func = ErrorFunction.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "log10": {func = Lg.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "log2": {func = Ld.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "log_10": {func = Lg.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "log_2": {func = Ld.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "logarithm": {func = Log.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "mod": {func = ModuloDivisorSign.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "modulo": {func = ModuloDivisorSign.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "power": //$NON-NLS-1$ - case "pwr": //$NON-NLS-1$ - case "pow": {func = Pow.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "sine": {func = Sin.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "tangent": {func = Tan.INSTANCE;break findFunc;} //$NON-NLS-1$ - } - - try { - func = super.parseString(preProcessed); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - error = t; - func = null; - } - - if (preProcessed.lastIndexOf('.') < 0) { - // if no '.' is contained in the function name, we can try - // different cases - try { - func = super.parseString(TextUtils.toUpperCase(first) - + preProcessed.substring(1)); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - if (error == null) { - error = t; - } - func = null; - } - - try { - func = super.parseString(TextUtils.toUpperCase(first) - + lowerCase.substring(1)); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - if (error == null) { - error = t; - } - func = null; - } - - try { - func = super.parseString(lowerCase); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - if (error == null) { - error = t; - } - func = null; - } - - try { - func = super.parseString(preProcessed.toUpperCase()); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - if (error == null) { - error = t; - } - func = null; - } - } - } - - if (func != null) { - return new _ParsedFunction(func, _ParsedFunction.MODE_CALL); - } - - throw new IllegalArgumentException(("The string '" //$NON-NLS-1$ - + string + // - "' cannot be parsed to a mathematical function."),//$NON-NLS-1$ - error); - } - - /** - * Parse the given character to a function - * - * @param currentChar - * the current character - * @return the function representing the character, or {@code null} if - * none was found - */ - static final _ParsedFunction _parseChar(final char currentChar) { - switch (currentChar) { - case 0x21: { // '!' - return _ParsedFunction.FACTORIAL_POSTFIX; - } - case 0x25: { // ':' - return _ParsedFunction.MOD_INFIX; - } - case 0x26: { // '&' - return _ParsedFunction.BAND_INFIX; - } - case 0x2a: { // '*' - return _ParsedFunction.MUL_INFIX; - } - case 0x2b: { // '+' - return _ParsedFunction.ADD_INFIX; - } - case 0x2d: { // '-' - return _ParsedFunction.SUB_INFIX; - } - case 0x2f: // '/' - case 0x3a: {// ':' - return _ParsedFunction.DIV_INFIX; - } - case 0x5e: { // '^' - return _ParsedFunction.POW_INFIX; - } - case 0x7e: {// '~' - return _ParsedFunction.BNOT_PREFIX; - } - case 0xac: { // logical not character - return _ParsedFunction.LNOT_PREFIX; - } - case 0xb2: { // '^2' - return _ParsedFunction.SQR_POSTFIX; - } - case 0xb3: { // '^3' - return _ParsedFunction.CUBE_POSTFIX; - } - case 0x221a: { // sqrt character - return _ParsedFunction.SQRT_PREFIX; - } - case 0x221b: { // cubic root character - return _ParsedFunction.CBRT_PREFIX; - } - default: { - return null; - } - } - } - - // default, automatic serialization replacement and resolve routines for - // singletons - // - /** - * Write replace: the instance this method is invoked on will be replaced - * with the singleton instance {@link #getInstance()} for serialization, - * i.e., when the instance is written with - * {@link java.io.ObjectOutputStream#writeObject(Object)}. - * - * @return the replacement instance (always {@link #getInstance()}) - */ - private final Object writeReplace() { - return MathematicalFunctionParser.getInstance(); - } - - /** - * Read resolve: The instance this method is invoked on will be replaced - * with the singleton instance {@link #getInstance()} after - * serialization, i.e., when the instance is read with - * {@link java.io.ObjectInputStream#readObject()}. - * - * @return the replacement instance (always {@link #getInstance()}) - */ - private final Object readResolve() { - return MathematicalFunctionParser.getInstance(); - } - - /** - * Get the singleton instance of this parser - * - * @return the document driver parser - */ - public static final MathematicalFunctionParser getInstance() { - return __MathematicalFunctionParserLoader.INSTANCE; - } - - /** the instance loader */ - private static final class __MathematicalFunctionParserLoader { - /** the instance */ - static final MathematicalFunctionParser INSTANCE = new MathematicalFunctionParser(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/old/MathematicalFunctionParser.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/old/MathematicalFunctionParser.java deleted file mode 100755 index 6d8ffaa..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/old/MathematicalFunctionParser.java +++ /dev/null @@ -1,346 +0,0 @@ -package org.optimizationBenchmarking.utils.math.text; - -import java.util.LinkedHashSet; - -import org.optimizationBenchmarking.utils.math.functions.MathematicalFunction; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.Absolute; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.Add; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.ModuloDivisorSign; -import org.optimizationBenchmarking.utils.math.functions.binary.BAnd; -import org.optimizationBenchmarking.utils.math.functions.combinatoric.Factorial; -import org.optimizationBenchmarking.utils.math.functions.hyperbolic.ACosh; -import org.optimizationBenchmarking.utils.math.functions.hyperbolic.ASinh; -import org.optimizationBenchmarking.utils.math.functions.hyperbolic.ATanh; -import org.optimizationBenchmarking.utils.math.functions.logic.LAnd; -import org.optimizationBenchmarking.utils.math.functions.numeric.Ceil; -import org.optimizationBenchmarking.utils.math.functions.power.Ld; -import org.optimizationBenchmarking.utils.math.functions.power.Lg; -import org.optimizationBenchmarking.utils.math.functions.power.Log; -import org.optimizationBenchmarking.utils.math.functions.power.Pow; -import org.optimizationBenchmarking.utils.math.functions.power.Sqrt; -import org.optimizationBenchmarking.utils.math.functions.special.Beta; -import org.optimizationBenchmarking.utils.math.functions.special.ErrorFunction; -import org.optimizationBenchmarking.utils.math.functions.stochastic.NormalCDF; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.ACos; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.ASin; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.ATan; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.Cos; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.Sin; -import org.optimizationBenchmarking.utils.math.functions.trigonometric.Tan; -import org.optimizationBenchmarking.utils.parsers.InstanceParser; -import org.optimizationBenchmarking.utils.reflection.ReflectionUtils; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - * A parser for singular instances of - * {@link org.optimizationBenchmarking.utils.math.functions.MathematicalFunction} - * , such as simple addition or subtraction. If you are looking for - * compound functions such as {@code 4+5*7*x}, use - * {@link org.optimizationBenchmarking.utils.math.text.CompoundFunctionParser} - * . - */ -public final class MathematicalFunctionParser extends - InstanceParser { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** create */ - MathematicalFunctionParser() { - super(MathematicalFunction.class, MathematicalFunctionParser - .__prefixes()); - } - - /** - * get the prefixes - * - * @return the path prefixes - */ - private static final String[] __prefixes() { - final LinkedHashSet paths; - - paths = new LinkedHashSet<>(); - ReflectionUtils.addPackageOfClassToPrefixList( - MathematicalFunctionParser.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Add.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - BAnd.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Factorial.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - ACosh.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - LAnd.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Ceil.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Sqrt.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Beta.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - NormalCDF.class, paths); - ReflectionUtils.addPackageOfClassToPrefixList(// - Sin.class, paths); - return paths.toArray(new String[paths.size()]); - } - - /** {@inheritDoc} */ - @Override - public final MathematicalFunction parseString(final String string) - throws Exception { - _ParsedFunction func; - - func = this._parseString(string); - if (func != null) { - return func.m_func; - } - throw new IllegalStateException("No function parsed from '" //$NON-NLS-1$ - + string + '\''); - } - - /** - * Parse a mathematical function string - * - * @param string - * the string - * @return the function - */ - @SuppressWarnings("incomplete-switch") - final _ParsedFunction _parseString(final String string) { - final String preProcessed, lowerCase; - final char first; - _ParsedFunction parsed; - MathematicalFunction func; - Throwable error; - - preProcessed = TextUtils.prepare(string); - if (string == null) { - throw new IllegalArgumentException(((// - "String to be parsed to a mathematical function cannot be empty, null, or just consist of white spaces, but you supplied '"//$NON-NLS-1$ - + string) + '\'') + '.'); - } - - first = preProcessed.charAt(0); - if (preProcessed.length() == 1) { - parsed = MathematicalFunctionParser._parseChar(preProcessed - .charAt(0)); - if (parsed != null) { - return parsed; - } - } - - lowerCase = preProcessed.toLowerCase(); - func = null; - error = null; - findFunc: { - switch (lowerCase) { - case "^2": {return _ParsedFunction.SQR_POSTFIX;} //$NON-NLS-1$ - case "^3": {return _ParsedFunction.CUBE_POSTFIX;} //$NON-NLS-1$ - case "**": {return _ParsedFunction.POW_INFIX;} //$NON-NLS-1$ - case "10**": {return _ParsedFunction.POW10_PREFIX;} //$NON-NLS-1$ - case "2**": {return _ParsedFunction.POW2_PREFIX;} //$NON-NLS-1$ - case "10^": {return _ParsedFunction.POW10_PREFIX;} //$NON-NLS-1$ - case "2^": {return _ParsedFunction.POW2_PREFIX;} //$NON-NLS-1$ - case "abs"://$NON-NLS-1$ - case "absolute": {func = Absolute.INSTANCE;break findFunc;}//$NON-NLS-1$ - case "acos": {func = ACos.INSTANCE;break findFunc;}//$NON-NLS-1$ - case "acosh": {func = ACosh.INSTANCE;break findFunc;}//$NON-NLS-1$ - case "asin": {func = ASin.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "asinh": {func = ASinh.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "atan": {func = ATan.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "atanh": {func = ATanh.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "cosine": {func = Cos.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "e^": {return _ParsedFunction.EXP_PREFIX;} //$NON-NLS-1$ - case "erf": {func = ErrorFunction.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "log10": {func = Lg.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "log2": {func = Ld.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "log_10": {func = Lg.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "log_2": {func = Ld.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "logarithm": {func = Log.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "mod": {func = ModuloDivisorSign.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "modulo": {func = ModuloDivisorSign.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "power": //$NON-NLS-1$ - case "pwr": //$NON-NLS-1$ - case "pow": {func = Pow.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "sine": {func = Sin.INSTANCE;break findFunc;} //$NON-NLS-1$ - case "tangent": {func = Tan.INSTANCE;break findFunc;} //$NON-NLS-1$ - } - - try { - func = super.parseString(preProcessed); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - error = t; - func = null; - } - - if (preProcessed.lastIndexOf('.') < 0) { - // if no '.' is contained in the function name, we can try - // different cases - try { - func = super.parseString(Character.toUpperCase(first) - + preProcessed.substring(1)); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - if (error == null) { - error = t; - } - func = null; - } - - try { - func = super.parseString(Character.toUpperCase(first) - + lowerCase.substring(1)); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - if (error == null) { - error = t; - } - func = null; - } - - try { - func = super.parseString(lowerCase); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - if (error == null) { - error = t; - } - func = null; - } - - try { - func = super.parseString(preProcessed.toUpperCase()); - if (func != null) { - break findFunc; - } - } catch (final Throwable t) { - if (error == null) { - error = t; - } - func = null; - } - } - } - - if (func != null) { - return new _ParsedFunction(func, _ParsedFunction.MODE_CALL); - } - - throw new IllegalArgumentException(("The string '" //$NON-NLS-1$ - + string + // - "' cannot be parsed to a mathematical function."),//$NON-NLS-1$ - error); - } - - /** - * Parse the given character to a function - * - * @param currentChar - * the current character - * @return the function representing the character, or {@code null} if - * none was found - */ - static final _ParsedFunction _parseChar(final char currentChar) { - switch (currentChar) { - case 0x21: { // '!' - return _ParsedFunction.FACTORIAL_POSTFIX; - } - case 0x25: { // ':' - return _ParsedFunction.MOD_INFIX; - } - case 0x26: { // '&' - return _ParsedFunction.BAND_INFIX; - } - case 0x2a: { // '*' - return _ParsedFunction.MUL_INFIX; - } - case 0x2b: { // '+' - return _ParsedFunction.ADD_INFIX; - } - case 0x2d: { // '-' - return _ParsedFunction.SUB_INFIX; - } - case 0x2f: // '/' - case 0x3a: {// ':' - return _ParsedFunction.DIV_INFIX; - } - case 0x5e: { // '^' - return _ParsedFunction.POW_INFIX; - } - case 0x7e: {// '~' - return _ParsedFunction.BNOT_PREFIX; - } - case 0xac: { // logical not character - return _ParsedFunction.LNOT_PREFIX; - } - case 0xb2: { // '^2' - return _ParsedFunction.SQR_POSTFIX; - } - case 0xb3: { // '^3' - return _ParsedFunction.CUBE_POSTFIX; - } - case 0x221a: { // sqrt character - return _ParsedFunction.SQRT_PREFIX; - } - case 0x221b: { // cubic root character - return _ParsedFunction.CBRT_PREFIX; - } - default: { - return null; - } - } - } - - // default, automatic serialization replacement and resolve routines for - // singletons - // - /** - * Write replace: the instance this method is invoked on will be replaced - * with the singleton instance {@link #getInstance()} for serialization, - * i.e., when the instance is written with - * {@link java.io.ObjectOutputStream#writeObject(Object)}. - * - * @return the replacement instance (always {@link #getInstance()}) - */ - private final Object writeReplace() { - return MathematicalFunctionParser.getInstance(); - } - - /** - * Read resolve: The instance this method is invoked on will be replaced - * with the singleton instance {@link #getInstance()} after - * serialization, i.e., when the instance is read with - * {@link java.io.ObjectInputStream#readObject()}. - * - * @return the replacement instance (always {@link #getInstance()}) - */ - private final Object readResolve() { - return MathematicalFunctionParser.getInstance(); - } - - /** - * Get the singleton instance of this parser - * - * @return the document driver parser - */ - public static final MathematicalFunctionParser getInstance() { - return __MathematicalFunctionParserLoader.INSTANCE; - } - - /** the instance loader */ - private static final class __MathematicalFunctionParserLoader { - /** the instance */ - static final MathematicalFunctionParser INSTANCE = new MathematicalFunctionParser(); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/pair.info deleted file mode 100755 index d3e65f4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75311/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75311 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/math/text/MathematicalFunctionParser.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/math/text/MathematicalFunctionParser.java -StartLineNum:133 -EndLineNum:133 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/diff.diff deleted file mode 100755 index d4cfd85..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/chart/impl/abstr/ChartDriver.java b/src/main/java/org/optimizationBenchmarking/utils/chart/impl/abstr/ChartDriver.java -index 8c9c1eae..15ea7c20 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/chart/impl/abstr/ChartDriver.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/chart/impl/abstr/ChartDriver.java -@@ -16,0 +17 @@ import org.optimizationBenchmarking.utils.hash.HashUtils; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -557 +558 @@ public abstract class ChartDriver extends Tool implements IChartDriver { -- this.m_fontName = font.getFontName().toLowerCase(); -+ this.m_fontName = TextUtils.toLowerCase(font.getFontName()); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/new/ChartDriver.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/new/ChartDriver.java deleted file mode 100755 index 15ea7c2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/new/ChartDriver.java +++ /dev/null @@ -1,599 +0,0 @@ -package org.optimizationBenchmarking.utils.chart.impl.abstr; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Font; -import java.awt.Stroke; -import java.util.HashMap; -import java.util.WeakHashMap; -import java.util.logging.Logger; - -import org.optimizationBenchmarking.utils.chart.spec.IChartDriver; -import org.optimizationBenchmarking.utils.graphics.FontProperties; -import org.optimizationBenchmarking.utils.graphics.graphic.spec.Graphic; -import org.optimizationBenchmarking.utils.graphics.style.StyleSet; -import org.optimizationBenchmarking.utils.graphics.style.stroke.StrokeStyle; -import org.optimizationBenchmarking.utils.hash.HashUtils; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.tools.impl.abstr.Tool; - -/** the chart driver base class */ -public abstract class ChartDriver extends Tool implements IChartDriver { - - /** the font scale for the chart title: {@value} */ - protected static final float FONT_SCALE_CHART_TITLE = 1f; - /** the font scale for the axis title: {@value} */ - protected static final float FONT_SCALE_AXIS_TITLE = 0.9f; - /** the font scale for the data title: {@value} */ - protected static final float FONT_SCALE_DATA_TITLE = ChartDriver.FONT_SCALE_AXIS_TITLE; - /** the font scale for the axis ticks: {@value} */ - protected static final float FONT_SCALE_AXIS_TICKS = (0.1f * (int) (10 * (ChartDriver.FONT_SCALE_AXIS_TITLE * ChartDriver.FONT_SCALE_AXIS_TITLE))); - - /** the hash map of scaled fonts */ - private final HashMap<__FontKey, Font> m_scaled; - - /** the defaults */ - private final WeakHashMap m_defaults; - - /** - * the chart driver - */ - protected ChartDriver() { - super(); - this.m_scaled = new HashMap<>(); - this.m_defaults = new WeakHashMap<>(); - } - - /** {@inheritDoc} */ - @Override - public ChartBuilder use() { - this.checkCanUse(); - return new ChartBuilder(this); - } - - /** - * render a compiled 2D line chart - * - * @param chart - * the chart to be rendered. - * @param graphic - * the graphic output interface - * @param logger - * a logger for logging info, or {@code null} if none is needed - */ - protected abstract void renderLineChart2D( - final CompiledLineChart2D chart, final Graphic graphic, - final Logger logger); - - /** - * render a compiled pie chart - * - * @param chart - * the chart to be rendered. - * @param graphic - * the graphic output interface - * @param logger - * a logger for logging info, or {@code null} if none is needed - */ - protected abstract void renderPieChart(final CompiledPieChart chart, - final Graphic graphic, final Logger logger); - - /** - * Scale a font with the base font scale - * - * @param font - * the font - * @param scale - * the scale - * @return the scaled font - */ - public synchronized final Font scaleFont(final Font font, - final float scale) { - final float oldSize, newSize; - final int size; - final __FontKey goalKey, goalKey2; - Font found, derived; - int goalSize; - - if (scale == 1f) { - return font; - } - - oldSize = font.getSize2D(); - if (scale < 1f) { - goalSize = (int) (Math.floor(oldSize * scale)); - } else { - goalSize = (int) (Math.ceil(oldSize * scale)); - } - goalSize = Math.max(5, Math.min(100, goalSize)); - if (goalSize == oldSize) { - return font; - } - - goalKey = new __FontKey(font, goalSize); - found = this.m_scaled.get(goalKey); - if (found != null) { - return found; - } - - derived = font.deriveFont((float) goalSize); - if (derived == null) { - return font; - } - - newSize = derived.getSize2D(); - if (newSize == oldSize) { - derived = font; - } else { - if (Math.abs(newSize - goalSize) > Math.abs(oldSize - goalSize)) { - derived = font; - } - } - - size = derived.getSize(); - if (size != goalSize) { - goalKey2 = new __FontKey(font, size); - found = this.m_scaled.get(goalKey2); - if (found != null) { - this.m_scaled.put(goalKey, found); - return found; - } - } - - this.m_scaled.put(goalKey, derived); - - return derived; - } - - /** - * Get the defaults for a given style set - * - * @param styles - * the style set - * @return the defaults for a given style set - */ - private synchronized final Object[] __getDefaults(final StyleSet styles) { - Object[] result; - - result = this.m_defaults.get(styles); - if (result == null) { - result = new Object[_EDefaults.DEFAULT_COUNT]; - this.m_defaults.put(styles, result); - this.m_scaled.clear(); - } - - return result; - } - - /** - * Scale the title font of the chart - * - * @param font - * the title font - * @return the scaled font - */ - public synchronized Font scaleTitleFont(final Font font) { - return this.scaleFont(font, ChartDriver.FONT_SCALE_CHART_TITLE); - } - - /** - * Create the default font to be used for the chart title - * - * @param styles - * the available style set - * @return the default font to be used for the chart title - */ - protected synchronized Font createDefaultChartTitleFont( - final StyleSet styles) { - return this.scaleTitleFont(styles.getDefaultFont().getFont()); - } - - /** - * Get the default font to be used for the chart title - * - * @param styles - * the available style set - * @return the default font to be used for the chart title - */ - public synchronized final Font getDefaultChartTitleFont( - final StyleSet styles) { - final int key; - final Object[] defaults; - Font result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.CHART_TITLE_FONT.ordinal(); - result = ((Font) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultChartTitleFont(styles); - } - return result; - } - - /** - * Scale the data title font of a data element - * - * @param font - * the data title font - * @return the scaled font - */ - public synchronized Font scaleDataTitleFont(final Font font) { - return this.scaleFont(font, ChartDriver.FONT_SCALE_DATA_TITLE); - } - - /** - * Create the default font to be used for a data element titles - * - * @param styles - * the available style set - * @return the default font to be used for a data element titles - */ - protected synchronized Font createDefaultDataTitleFont( - final StyleSet styles) { - return this.scaleDataTitleFont(styles.getDefaultFont().getFont()); - } - - /** - * Get the default font to be used for a data element title - * - * @param styles - * the available style set - * @return the default font to be used for a data element title - */ - public synchronized final Font getDefaultDataTitleFont( - final StyleSet styles) { - final int key; - final Object[] defaults; - Font result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.DATA_TITLE_FONT.ordinal(); - result = ((Font) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultDataTitleFont(styles); - } - return result; - } - - /** - * Create the default data stroke - * - * @param styles - * the styles - * @return the default data stroke - */ - protected synchronized Stroke createDefaultDataStroke( - final StyleSet styles) { - return styles.getDefaultStroke(); - } - - /** - * Get the default data stroke - * - * @param styles - * the available style set - * @return the default stroke to be used for a data - */ - public synchronized final Stroke getDefaultDataStroke( - final StyleSet styles) { - final int key; - final Object[] defaults; - Stroke result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.DATA_STROKE.ordinal(); - result = ((Stroke) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultDataStroke(styles); - } - return result; - } - - /** - * Scale the axis title font of the chart - * - * @param font - * the axis title font - * @return the scaled font - */ - public synchronized Font scaleAxisTitleFont(final Font font) { - return this.scaleFont(font, ChartDriver.FONT_SCALE_AXIS_TITLE); - } - - /** - * Create the default font to be used for axis titles - * - * @param styles - * the available style set - * @return the default font to be used for axis titles - */ - protected synchronized Font createDefaultAxisTitleFont( - final StyleSet styles) { - return this.scaleFont(styles.getDefaultFont().getFont(), - ChartDriver.FONT_SCALE_AXIS_TITLE); - } - - /** - * Get the default font to be used for an axis title - * - * @param styles - * the available style set - * @return the default font to be used for an axis title - */ - public synchronized final Font getDefaultAxisTitleFont( - final StyleSet styles) { - final int key; - final Object[] defaults; - Font result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.AXIS_TITLE_FONT.ordinal(); - result = ((Font) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultAxisTitleFont(styles); - } - return result; - } - - /** - * Scale the axis tick font of the chart - * - * @param font - * the axis title font - * @return the scaled font - */ - public synchronized Font scaleAxisTickFont(final Font font) { - return this.scaleFont(font, ChartDriver.FONT_SCALE_AXIS_TICKS); - } - - /** - * Create the default font to be used for axis ticks - * - * @param styles - * the available style set - * @return the default font to be used for axis ticks - */ - protected synchronized Font createDefaultAxisTickFont( - final StyleSet styles) { - return this.scaleFont(styles.getDefaultFont().getFont(), - ChartDriver.FONT_SCALE_AXIS_TICKS); - } - - /** - * Get the default font to be used for an axis ticks - * - * @param styles - * the available style set - * @return the default font to be used for an axis ticks - */ - public synchronized final Font getDefaultAxisTickFont( - final StyleSet styles) { - final int key; - final Object[] defaults; - Font result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.AXIS_TICK_FONT.ordinal(); - result = ((Font) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultAxisTickFont(styles); - } - return result; - } - - /** - * Get the stroke to be used for axes - * - * @param styles - * the styles - * @return the axes stroke - */ - protected synchronized Stroke createDefaultAxisStroke( - final StyleSet styles) { - final BasicStroke defaultStroke; - final float defaultWidth, thickWidth, goalWidth; - - defaultStroke = styles.getDefaultStroke(); - defaultWidth = defaultStroke.getLineWidth(); - thickWidth = styles.getThickStroke().getLineWidth(); - goalWidth = Math.max(defaultWidth,// - Math.min(thickWidth,// - ((float) (0.01d * Math.round(100d * // - ((0.65d * defaultWidth) + // - (0.35d * thickWidth))))))); - - return new BasicStroke(goalWidth, defaultStroke.getEndCap(), - defaultStroke.getLineJoin(), defaultStroke.getMiterLimit()); - } - - /** - * Get the default axis stroke - * - * @param styles - * the available style set - * @return the default stroke to be used for an axis - */ - public synchronized final Stroke getDefaultAxisStroke( - final StyleSet styles) { - final int key; - final Object[] defaults; - Stroke result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.AXIS_STROKE.ordinal(); - result = ((Stroke) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultAxisStroke(styles); - } - return result; - } - - /** - * Create the color to be used for axes - * - * @param styles - * the styles - * @return the axis color - */ - protected synchronized Color createDefaultAxisColor(final StyleSet styles) { - return styles.getBlack(); - } - - /** - * Get the default axis color - * - * @param styles - * the available style set - * @return the default color to be used for an axis - */ - public synchronized final Color getDefaultAxisColor(final StyleSet styles) { - final int key; - final Object[] defaults; - Color result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.AXIS_COLOR.ordinal(); - result = ((Color) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultAxisColor(styles); - } - return result; - } - - /** - * Get the stroke to be used for grid lines - * - * @param styles - * the styles - * @return the grid line stroke - */ - protected synchronized Stroke createDefaultGridLineStroke( - final StyleSet styles) { - final StrokeStyle thin; - - thin = styles.getThinStroke(); - return new BasicStroke(thin.getLineWidth(), thin.getEndCap(), - thin.getLineJoin(), thin.getMiterLimit(), - new float[] { 0.5f, 2.5f }, 0f); - } - - /** - * Get the default grid line stroke - * - * @param styles - * the available style set - * @return the default stroke to be used for a grid line - */ - public synchronized final Stroke getDefaultGridLineStroke( - final StyleSet styles) { - final int key; - final Object[] defaults; - Stroke result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.GRID_STROKE.ordinal(); - result = ((Stroke) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultGridLineStroke(styles); - } - return result; - } - - /** - * Get the color to be used for grid lines - * - * @param styles - * the styles - * @return the grid line color - */ - protected synchronized Color createDefaultGridLineColor( - final StyleSet styles) { - return this.getDefaultAxisColor(styles); - } - - /** - * Get the default grid line color - * - * @param styles - * the available style set - * @return the default color to be used for an grid lines - */ - public synchronized final Color getDefaultGridLineColor( - final StyleSet styles) { - final int key; - final Object[] defaults; - Color result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.GRID_COLOR.ordinal(); - result = ((Color) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultGridLineColor(styles); - } - return result; - } - - /** the font key */ - private static final class __FontKey { - - /** the font name */ - final String m_fontName; - - /** the hash code */ - final int m_hash; - - /** - * Create a font key - * - * @param font - * the font - * @param size - * the size - */ - __FontKey(final Font font, final int size) { - super(); - - int style; - - this.m_fontName = TextUtils.toLowerCase(font.getFontName()); - - style = 0; - if (!(font.isBold())) { - style |= 1; - } - if (!(font.isItalic())) { - style |= 2; - } - if (!(FontProperties.isFontUnderlined(font))) { - style |= 4; - } - style |= (font.getSize() << 3); - - this.m_hash = HashUtils.combineHashes(HashUtils.hashCode(// - (style ^ (style << 12) ^ (style << 24))), - HashUtils.hashCode(this.m_fontName)); - } - - /** {@inheritDoc} */ - @Override - public final int hashCode() { - return this.m_hash; - } - - /** {@inheritDoc} */ - @Override - public final boolean equals(final Object o) { - final __FontKey fk; - if (o == this) { - return true; - } - if (o instanceof __FontKey) { - fk = ((__FontKey) o); - return ((fk.m_hash == this.m_hash) && // - (this.m_fontName.equals(fk.m_fontName))); - } - - return false; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/old/ChartDriver.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/old/ChartDriver.java deleted file mode 100755 index 8c9c1ea..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/old/ChartDriver.java +++ /dev/null @@ -1,598 +0,0 @@ -package org.optimizationBenchmarking.utils.chart.impl.abstr; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Font; -import java.awt.Stroke; -import java.util.HashMap; -import java.util.WeakHashMap; -import java.util.logging.Logger; - -import org.optimizationBenchmarking.utils.chart.spec.IChartDriver; -import org.optimizationBenchmarking.utils.graphics.FontProperties; -import org.optimizationBenchmarking.utils.graphics.graphic.spec.Graphic; -import org.optimizationBenchmarking.utils.graphics.style.StyleSet; -import org.optimizationBenchmarking.utils.graphics.style.stroke.StrokeStyle; -import org.optimizationBenchmarking.utils.hash.HashUtils; -import org.optimizationBenchmarking.utils.tools.impl.abstr.Tool; - -/** the chart driver base class */ -public abstract class ChartDriver extends Tool implements IChartDriver { - - /** the font scale for the chart title: {@value} */ - protected static final float FONT_SCALE_CHART_TITLE = 1f; - /** the font scale for the axis title: {@value} */ - protected static final float FONT_SCALE_AXIS_TITLE = 0.9f; - /** the font scale for the data title: {@value} */ - protected static final float FONT_SCALE_DATA_TITLE = ChartDriver.FONT_SCALE_AXIS_TITLE; - /** the font scale for the axis ticks: {@value} */ - protected static final float FONT_SCALE_AXIS_TICKS = (0.1f * (int) (10 * (ChartDriver.FONT_SCALE_AXIS_TITLE * ChartDriver.FONT_SCALE_AXIS_TITLE))); - - /** the hash map of scaled fonts */ - private final HashMap<__FontKey, Font> m_scaled; - - /** the defaults */ - private final WeakHashMap m_defaults; - - /** - * the chart driver - */ - protected ChartDriver() { - super(); - this.m_scaled = new HashMap<>(); - this.m_defaults = new WeakHashMap<>(); - } - - /** {@inheritDoc} */ - @Override - public ChartBuilder use() { - this.checkCanUse(); - return new ChartBuilder(this); - } - - /** - * render a compiled 2D line chart - * - * @param chart - * the chart to be rendered. - * @param graphic - * the graphic output interface - * @param logger - * a logger for logging info, or {@code null} if none is needed - */ - protected abstract void renderLineChart2D( - final CompiledLineChart2D chart, final Graphic graphic, - final Logger logger); - - /** - * render a compiled pie chart - * - * @param chart - * the chart to be rendered. - * @param graphic - * the graphic output interface - * @param logger - * a logger for logging info, or {@code null} if none is needed - */ - protected abstract void renderPieChart(final CompiledPieChart chart, - final Graphic graphic, final Logger logger); - - /** - * Scale a font with the base font scale - * - * @param font - * the font - * @param scale - * the scale - * @return the scaled font - */ - public synchronized final Font scaleFont(final Font font, - final float scale) { - final float oldSize, newSize; - final int size; - final __FontKey goalKey, goalKey2; - Font found, derived; - int goalSize; - - if (scale == 1f) { - return font; - } - - oldSize = font.getSize2D(); - if (scale < 1f) { - goalSize = (int) (Math.floor(oldSize * scale)); - } else { - goalSize = (int) (Math.ceil(oldSize * scale)); - } - goalSize = Math.max(5, Math.min(100, goalSize)); - if (goalSize == oldSize) { - return font; - } - - goalKey = new __FontKey(font, goalSize); - found = this.m_scaled.get(goalKey); - if (found != null) { - return found; - } - - derived = font.deriveFont((float) goalSize); - if (derived == null) { - return font; - } - - newSize = derived.getSize2D(); - if (newSize == oldSize) { - derived = font; - } else { - if (Math.abs(newSize - goalSize) > Math.abs(oldSize - goalSize)) { - derived = font; - } - } - - size = derived.getSize(); - if (size != goalSize) { - goalKey2 = new __FontKey(font, size); - found = this.m_scaled.get(goalKey2); - if (found != null) { - this.m_scaled.put(goalKey, found); - return found; - } - } - - this.m_scaled.put(goalKey, derived); - - return derived; - } - - /** - * Get the defaults for a given style set - * - * @param styles - * the style set - * @return the defaults for a given style set - */ - private synchronized final Object[] __getDefaults(final StyleSet styles) { - Object[] result; - - result = this.m_defaults.get(styles); - if (result == null) { - result = new Object[_EDefaults.DEFAULT_COUNT]; - this.m_defaults.put(styles, result); - this.m_scaled.clear(); - } - - return result; - } - - /** - * Scale the title font of the chart - * - * @param font - * the title font - * @return the scaled font - */ - public synchronized Font scaleTitleFont(final Font font) { - return this.scaleFont(font, ChartDriver.FONT_SCALE_CHART_TITLE); - } - - /** - * Create the default font to be used for the chart title - * - * @param styles - * the available style set - * @return the default font to be used for the chart title - */ - protected synchronized Font createDefaultChartTitleFont( - final StyleSet styles) { - return this.scaleTitleFont(styles.getDefaultFont().getFont()); - } - - /** - * Get the default font to be used for the chart title - * - * @param styles - * the available style set - * @return the default font to be used for the chart title - */ - public synchronized final Font getDefaultChartTitleFont( - final StyleSet styles) { - final int key; - final Object[] defaults; - Font result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.CHART_TITLE_FONT.ordinal(); - result = ((Font) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultChartTitleFont(styles); - } - return result; - } - - /** - * Scale the data title font of a data element - * - * @param font - * the data title font - * @return the scaled font - */ - public synchronized Font scaleDataTitleFont(final Font font) { - return this.scaleFont(font, ChartDriver.FONT_SCALE_DATA_TITLE); - } - - /** - * Create the default font to be used for a data element titles - * - * @param styles - * the available style set - * @return the default font to be used for a data element titles - */ - protected synchronized Font createDefaultDataTitleFont( - final StyleSet styles) { - return this.scaleDataTitleFont(styles.getDefaultFont().getFont()); - } - - /** - * Get the default font to be used for a data element title - * - * @param styles - * the available style set - * @return the default font to be used for a data element title - */ - public synchronized final Font getDefaultDataTitleFont( - final StyleSet styles) { - final int key; - final Object[] defaults; - Font result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.DATA_TITLE_FONT.ordinal(); - result = ((Font) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultDataTitleFont(styles); - } - return result; - } - - /** - * Create the default data stroke - * - * @param styles - * the styles - * @return the default data stroke - */ - protected synchronized Stroke createDefaultDataStroke( - final StyleSet styles) { - return styles.getDefaultStroke(); - } - - /** - * Get the default data stroke - * - * @param styles - * the available style set - * @return the default stroke to be used for a data - */ - public synchronized final Stroke getDefaultDataStroke( - final StyleSet styles) { - final int key; - final Object[] defaults; - Stroke result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.DATA_STROKE.ordinal(); - result = ((Stroke) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultDataStroke(styles); - } - return result; - } - - /** - * Scale the axis title font of the chart - * - * @param font - * the axis title font - * @return the scaled font - */ - public synchronized Font scaleAxisTitleFont(final Font font) { - return this.scaleFont(font, ChartDriver.FONT_SCALE_AXIS_TITLE); - } - - /** - * Create the default font to be used for axis titles - * - * @param styles - * the available style set - * @return the default font to be used for axis titles - */ - protected synchronized Font createDefaultAxisTitleFont( - final StyleSet styles) { - return this.scaleFont(styles.getDefaultFont().getFont(), - ChartDriver.FONT_SCALE_AXIS_TITLE); - } - - /** - * Get the default font to be used for an axis title - * - * @param styles - * the available style set - * @return the default font to be used for an axis title - */ - public synchronized final Font getDefaultAxisTitleFont( - final StyleSet styles) { - final int key; - final Object[] defaults; - Font result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.AXIS_TITLE_FONT.ordinal(); - result = ((Font) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultAxisTitleFont(styles); - } - return result; - } - - /** - * Scale the axis tick font of the chart - * - * @param font - * the axis title font - * @return the scaled font - */ - public synchronized Font scaleAxisTickFont(final Font font) { - return this.scaleFont(font, ChartDriver.FONT_SCALE_AXIS_TICKS); - } - - /** - * Create the default font to be used for axis ticks - * - * @param styles - * the available style set - * @return the default font to be used for axis ticks - */ - protected synchronized Font createDefaultAxisTickFont( - final StyleSet styles) { - return this.scaleFont(styles.getDefaultFont().getFont(), - ChartDriver.FONT_SCALE_AXIS_TICKS); - } - - /** - * Get the default font to be used for an axis ticks - * - * @param styles - * the available style set - * @return the default font to be used for an axis ticks - */ - public synchronized final Font getDefaultAxisTickFont( - final StyleSet styles) { - final int key; - final Object[] defaults; - Font result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.AXIS_TICK_FONT.ordinal(); - result = ((Font) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultAxisTickFont(styles); - } - return result; - } - - /** - * Get the stroke to be used for axes - * - * @param styles - * the styles - * @return the axes stroke - */ - protected synchronized Stroke createDefaultAxisStroke( - final StyleSet styles) { - final BasicStroke defaultStroke; - final float defaultWidth, thickWidth, goalWidth; - - defaultStroke = styles.getDefaultStroke(); - defaultWidth = defaultStroke.getLineWidth(); - thickWidth = styles.getThickStroke().getLineWidth(); - goalWidth = Math.max(defaultWidth,// - Math.min(thickWidth,// - ((float) (0.01d * Math.round(100d * // - ((0.65d * defaultWidth) + // - (0.35d * thickWidth))))))); - - return new BasicStroke(goalWidth, defaultStroke.getEndCap(), - defaultStroke.getLineJoin(), defaultStroke.getMiterLimit()); - } - - /** - * Get the default axis stroke - * - * @param styles - * the available style set - * @return the default stroke to be used for an axis - */ - public synchronized final Stroke getDefaultAxisStroke( - final StyleSet styles) { - final int key; - final Object[] defaults; - Stroke result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.AXIS_STROKE.ordinal(); - result = ((Stroke) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultAxisStroke(styles); - } - return result; - } - - /** - * Create the color to be used for axes - * - * @param styles - * the styles - * @return the axis color - */ - protected synchronized Color createDefaultAxisColor(final StyleSet styles) { - return styles.getBlack(); - } - - /** - * Get the default axis color - * - * @param styles - * the available style set - * @return the default color to be used for an axis - */ - public synchronized final Color getDefaultAxisColor(final StyleSet styles) { - final int key; - final Object[] defaults; - Color result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.AXIS_COLOR.ordinal(); - result = ((Color) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultAxisColor(styles); - } - return result; - } - - /** - * Get the stroke to be used for grid lines - * - * @param styles - * the styles - * @return the grid line stroke - */ - protected synchronized Stroke createDefaultGridLineStroke( - final StyleSet styles) { - final StrokeStyle thin; - - thin = styles.getThinStroke(); - return new BasicStroke(thin.getLineWidth(), thin.getEndCap(), - thin.getLineJoin(), thin.getMiterLimit(), - new float[] { 0.5f, 2.5f }, 0f); - } - - /** - * Get the default grid line stroke - * - * @param styles - * the available style set - * @return the default stroke to be used for a grid line - */ - public synchronized final Stroke getDefaultGridLineStroke( - final StyleSet styles) { - final int key; - final Object[] defaults; - Stroke result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.GRID_STROKE.ordinal(); - result = ((Stroke) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultGridLineStroke(styles); - } - return result; - } - - /** - * Get the color to be used for grid lines - * - * @param styles - * the styles - * @return the grid line color - */ - protected synchronized Color createDefaultGridLineColor( - final StyleSet styles) { - return this.getDefaultAxisColor(styles); - } - - /** - * Get the default grid line color - * - * @param styles - * the available style set - * @return the default color to be used for an grid lines - */ - public synchronized final Color getDefaultGridLineColor( - final StyleSet styles) { - final int key; - final Object[] defaults; - Color result; - - defaults = this.__getDefaults(styles); - key = _EDefaults.GRID_COLOR.ordinal(); - result = ((Color) (defaults[key])); - if (result == null) { - defaults[key] = result = this.createDefaultGridLineColor(styles); - } - return result; - } - - /** the font key */ - private static final class __FontKey { - - /** the font name */ - final String m_fontName; - - /** the hash code */ - final int m_hash; - - /** - * Create a font key - * - * @param font - * the font - * @param size - * the size - */ - __FontKey(final Font font, final int size) { - super(); - - int style; - - this.m_fontName = font.getFontName().toLowerCase(); - - style = 0; - if (!(font.isBold())) { - style |= 1; - } - if (!(font.isItalic())) { - style |= 2; - } - if (!(FontProperties.isFontUnderlined(font))) { - style |= 4; - } - style |= (font.getSize() << 3); - - this.m_hash = HashUtils.combineHashes(HashUtils.hashCode(// - (style ^ (style << 12) ^ (style << 24))), - HashUtils.hashCode(this.m_fontName)); - } - - /** {@inheritDoc} */ - @Override - public final int hashCode() { - return this.m_hash; - } - - /** {@inheritDoc} */ - @Override - public final boolean equals(final Object o) { - final __FontKey fk; - if (o == this) { - return true; - } - if (o instanceof __FontKey) { - fk = ((__FontKey) o); - return ((fk.m_hash == this.m_hash) && // - (this.m_fontName.equals(fk.m_fontName))); - } - - return false; - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/pair.info deleted file mode 100755 index f7cfe4a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75318/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75318 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/chart/impl/abstr/ChartDriver.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/chart/impl/abstr/ChartDriver.java -StartLineNum:557 -EndLineNum:557 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/diff.diff deleted file mode 100755 index 02ed0a5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/ValueRangeGroups.java b/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/ValueRangeGroups.java -index 1272c14f..f42ad8f9 100644 ---- a/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/ValueRangeGroups.java -+++ b/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/ValueRangeGroups.java -@@ -9,0 +10 @@ import org.optimizationBenchmarking.utils.text.ETextCase; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -71 +72 @@ public class ValueRangeGroups extends PropertyValueGroups { -- this.getGroupingMode().toString().toLowerCase() + // -+ TextUtils.toLowerCase(this.getGroupingMode().toString()) + // \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/new/ValueRangeGroups.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/new/ValueRangeGroups.java deleted file mode 100755 index f42ad8f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/new/ValueRangeGroups.java +++ /dev/null @@ -1,161 +0,0 @@ -package org.optimizationBenchmarking.experimentation.attributes.clusters.propertyValueGroups; - -import org.optimizationBenchmarking.experimentation.data.impl.shadow.DataSelection; -import org.optimizationBenchmarking.experimentation.data.spec.IFeature; -import org.optimizationBenchmarking.experimentation.data.spec.IParameter; -import org.optimizationBenchmarking.experimentation.data.spec.IProperty; -import org.optimizationBenchmarking.utils.collections.lists.ArrayListView; -import org.optimizationBenchmarking.utils.document.impl.SemanticComponentUtils; -import org.optimizationBenchmarking.utils.text.ETextCase; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; - -/** A set of property value range groups. */ -public class ValueRangeGroups extends PropertyValueGroups { - - /** the grouping parameterrmation */ - private final Number m_parameter; - - /** - * create the value range groups - * - * @param groups - * the groups - * @param property - * the property - * @param unspecified - * a group holding all elements for which the property value was - * unspecified, or {@code null} if no such elements exist - * @param unspecifiedValue - * the unspecified value - */ - ValueRangeGroups(final IProperty property, final _Groups groups, - final DataSelection unspecified, final Object unspecifiedValue) { - super(property, groups, unspecified, unspecifiedValue); - - if (groups.m_groupingParameter == null) { - throw new IllegalArgumentException(// - "Grouping parameter cannot be null."); //$NON-NLS-1$ - } - this.m_parameter = groups.m_groupingParameter; - } - - /** {@inheritDoc} */ - @Override - final ValueRangeGroup _group(final _Group group) { - return new ValueRangeGroup(this, group.m_selection, - ((Number) (group.m_lower)), ((Number) (group.m_upper)), - group.m_isUpperExclusive); - } - - /** {@inheritDoc} */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public final ArrayListView getData() { - return ((ArrayListView) (this.m_data)); - } - - /** - * Get the grouping parameter. - * - * @return the grouping parameter. - */ - public final Number getInfo() { - return this.m_parameter; - } - - /** {@inheritDoc} */ - @Override - public final String getPathComponentSuggestion() { - return (this.m_property.getName() + // - "_grouped_by_" + //$NON-NLS-1$ - TextUtils.toLowerCase(this.getGroupingMode().toString()) + // - "_of_" + //$NON-NLS-1$ - this.m_parameter.toString()); - } - - /** - * Print the rest of the name - * - * @param textOut - * the destination - * @param textCase - * the text case - * @return the next case - */ - private final ETextCase __printNameRest(final ITextOutput textOut, - final ETextCase textCase) { - ETextCase next; - - textOut.append(' '); - next = ETextCase.IN_SENTENCE.appendWords("grouped by", textOut); //$NON-NLS-1$ - textOut.append(' '); - next = next.appendWord(this.getGroupingMode().toString(), textOut); - textOut.append(' '); - next = next.appendWord("of", textOut); //$NON-NLS-1$ - textOut.append(' '); - PropertyValueGroup._appendNumber(this.m_parameter, textOut); - return next.nextCase(); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printLongName(final ITextOutput textOut, - final ETextCase textCase) { - return this.__printNameRest(textOut, - this.m_property.printLongName(textOut, textCase)); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printShortName(final ITextOutput textOut, - final ETextCase textCase) { - return this.__printNameRest(textOut, - this.m_property.printShortName(textOut, textCase)); - } - - /** {@inheritDoc} */ - @Override - public ETextCase printDescription(final ITextOutput textOut, - final ETextCase textCase) { - ETextCase next; - - next = textCase; - - if (this.m_property instanceof IParameter) { - textOut.append(' '); - next = next.appendWords(// - "all experiments whose value of parameter",//$NON-NLS-1$ - textOut); - } else { - if (this.m_property instanceof IFeature) { - textOut.append(' '); - next = next - .appendWords(// - "all instance run sets belonging to an instance whose value of feature",//$NON-NLS-1$ - textOut); - } else { - next = textCase.appendWords(// - "the data whose", textOut); //$NON-NLS-1$ - } - } - textOut.append(' '); - next = SemanticComponentUtils.printLongAndShortNameIfDifferent( - this.m_property, textOut, next); - textOut.append(' '); - if (next == null) { - next = ETextCase.IN_SENTENCE; - } - next = next.appendWords("fall into the range of the same", textOut); //$NON-NLS-1$ - textOut.append(' '); - next = next.appendWord(this.getGroupingMode().toString(), textOut); - textOut.append(' '); - next = next.appendWord("of", textOut); //$NON-NLS-1$ - textOut.append(' '); - PropertyValueGroup._appendNumber(this.m_parameter, textOut); - textOut.append(' '); - next = next.appendWords("are grouped together.", textOut); //$NON-NLS-1$ - - return next.nextAfterSentenceEnd(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/old/ValueRangeGroups.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/old/ValueRangeGroups.java deleted file mode 100755 index 1272c14..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/old/ValueRangeGroups.java +++ /dev/null @@ -1,160 +0,0 @@ -package org.optimizationBenchmarking.experimentation.attributes.clusters.propertyValueGroups; - -import org.optimizationBenchmarking.experimentation.data.impl.shadow.DataSelection; -import org.optimizationBenchmarking.experimentation.data.spec.IFeature; -import org.optimizationBenchmarking.experimentation.data.spec.IParameter; -import org.optimizationBenchmarking.experimentation.data.spec.IProperty; -import org.optimizationBenchmarking.utils.collections.lists.ArrayListView; -import org.optimizationBenchmarking.utils.document.impl.SemanticComponentUtils; -import org.optimizationBenchmarking.utils.text.ETextCase; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; - -/** A set of property value range groups. */ -public class ValueRangeGroups extends PropertyValueGroups { - - /** the grouping parameterrmation */ - private final Number m_parameter; - - /** - * create the value range groups - * - * @param groups - * the groups - * @param property - * the property - * @param unspecified - * a group holding all elements for which the property value was - * unspecified, or {@code null} if no such elements exist - * @param unspecifiedValue - * the unspecified value - */ - ValueRangeGroups(final IProperty property, final _Groups groups, - final DataSelection unspecified, final Object unspecifiedValue) { - super(property, groups, unspecified, unspecifiedValue); - - if (groups.m_groupingParameter == null) { - throw new IllegalArgumentException(// - "Grouping parameter cannot be null."); //$NON-NLS-1$ - } - this.m_parameter = groups.m_groupingParameter; - } - - /** {@inheritDoc} */ - @Override - final ValueRangeGroup _group(final _Group group) { - return new ValueRangeGroup(this, group.m_selection, - ((Number) (group.m_lower)), ((Number) (group.m_upper)), - group.m_isUpperExclusive); - } - - /** {@inheritDoc} */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - @Override - public final ArrayListView getData() { - return ((ArrayListView) (this.m_data)); - } - - /** - * Get the grouping parameter. - * - * @return the grouping parameter. - */ - public final Number getInfo() { - return this.m_parameter; - } - - /** {@inheritDoc} */ - @Override - public final String getPathComponentSuggestion() { - return (this.m_property.getName() + // - "_grouped_by_" + //$NON-NLS-1$ - this.getGroupingMode().toString().toLowerCase() + // - "_of_" + //$NON-NLS-1$ - this.m_parameter.toString()); - } - - /** - * Print the rest of the name - * - * @param textOut - * the destination - * @param textCase - * the text case - * @return the next case - */ - private final ETextCase __printNameRest(final ITextOutput textOut, - final ETextCase textCase) { - ETextCase next; - - textOut.append(' '); - next = ETextCase.IN_SENTENCE.appendWords("grouped by", textOut); //$NON-NLS-1$ - textOut.append(' '); - next = next.appendWord(this.getGroupingMode().toString(), textOut); - textOut.append(' '); - next = next.appendWord("of", textOut); //$NON-NLS-1$ - textOut.append(' '); - PropertyValueGroup._appendNumber(this.m_parameter, textOut); - return next.nextCase(); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printLongName(final ITextOutput textOut, - final ETextCase textCase) { - return this.__printNameRest(textOut, - this.m_property.printLongName(textOut, textCase)); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printShortName(final ITextOutput textOut, - final ETextCase textCase) { - return this.__printNameRest(textOut, - this.m_property.printShortName(textOut, textCase)); - } - - /** {@inheritDoc} */ - @Override - public ETextCase printDescription(final ITextOutput textOut, - final ETextCase textCase) { - ETextCase next; - - next = textCase; - - if (this.m_property instanceof IParameter) { - textOut.append(' '); - next = next.appendWords(// - "all experiments whose value of parameter",//$NON-NLS-1$ - textOut); - } else { - if (this.m_property instanceof IFeature) { - textOut.append(' '); - next = next - .appendWords(// - "all instance run sets belonging to an instance whose value of feature",//$NON-NLS-1$ - textOut); - } else { - next = textCase.appendWords(// - "the data whose", textOut); //$NON-NLS-1$ - } - } - textOut.append(' '); - next = SemanticComponentUtils.printLongAndShortNameIfDifferent( - this.m_property, textOut, next); - textOut.append(' '); - if (next == null) { - next = ETextCase.IN_SENTENCE; - } - next = next.appendWords("fall into the range of the same", textOut); //$NON-NLS-1$ - textOut.append(' '); - next = next.appendWord(this.getGroupingMode().toString(), textOut); - textOut.append(' '); - next = next.appendWord("of", textOut); //$NON-NLS-1$ - textOut.append(' '); - PropertyValueGroup._appendNumber(this.m_parameter, textOut); - textOut.append(' '); - next = next.appendWords("are grouped together.", textOut); //$NON-NLS-1$ - - return next.nextAfterSentenceEnd(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/pair.info deleted file mode 100755 index 8e5a616..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75371/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75371 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/ValueRangeGroups.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/ValueRangeGroups.java -StartLineNum:69 -EndLineNum:69 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/diff.diff deleted file mode 100755 index a00bc2c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/EGroupingMode.java b/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/EGroupingMode.java -index 48bf5c39..264ab806 100644 ---- a/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/EGroupingMode.java -+++ b/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/EGroupingMode.java -@@ -9,0 +10 @@ import org.optimizationBenchmarking.utils.math.functions.power.Pow; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -830 +831 @@ public enum EGroupingMode { -- this.m_name = super.toString().toLowerCase(); -+ this.m_name = TextUtils.toLowerCase(super.toString()); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/new/EGroupingMode.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/new/EGroupingMode.java deleted file mode 100755 index 264ab80..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/new/EGroupingMode.java +++ /dev/null @@ -1,839 +0,0 @@ -package org.optimizationBenchmarking.experimentation.attributes.clusters.propertyValueGroups; - -import org.optimizationBenchmarking.utils.math.NumericalTypes; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.Div; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.Mul; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.SaturatingAdd; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.SaturatingSub; -import org.optimizationBenchmarking.utils.math.functions.power.Log; -import org.optimizationBenchmarking.utils.math.functions.power.Pow; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - * A set of different modi for grouping elements. - */ -public enum EGroupingMode { - - /** Group distinct values, i.e., each value becomes an own group */ - DISTINCT { - /** {@inheritDoc} */ - @Override - _Groups _groupObjects(final Number param, final Object[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - int count; - - count = 0; - for (final _Group group : buffer) { - group.m_size = 1; - group.m_isUpperExclusive = false; - group.m_lower = group.m_upper = data[count++]; - } - - return new _Groups(buffer, minGroups, maxGroups, this, null); - } - - /** {@inheritDoc} */ - @Override - _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - return this._groupObjects(param, data, minGroups, maxGroups, buffer); - } - - /** {@inheritDoc} */ - @Override - _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - return this._groupObjects(param, data, minGroups, maxGroups, buffer); - } - }, - - /** - * Group elements in terms of reasonable powers, including powers of - * {@code 2}, {@code 10}, etc. - */ - POWERS { - - /** {@inheritDoc} */ - @Override - final _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - final long pl; - _Groups best, current; - - if (param != null) { - pl = param.longValue(); - best = EGroupingMode._groupLongsByPowerRange(pl, data, minGroups, - maxGroups, buffer); - if ((param instanceof Float) || (param instanceof Double)) { - if ((pl < Long.MAX_VALUE) && (pl != param.doubleValue())) { - current = EGroupingMode._groupLongsByPowerRange((pl + 1L), - data, minGroups, maxGroups, buffer); - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - if (best != null) { - return best; - } - } else { - best = null; - } - - for (final long power : EGroupingMode.POWER_CHOICES) { - current = EGroupingMode._groupLongsByPowerRange(power, data, - minGroups, maxGroups, buffer); - if (current != null) { - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - - if (best == null) { - return DISTINCT._groupLongs(param, data, minGroups, maxGroups, - buffer); - } - return best; - } - - /** {@inheritDoc} */ - @Override - final _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - final double dl; - _Groups best, current; - - if (param != null) { - dl = param.doubleValue(); - best = EGroupingMode._groupDoublesByPowerRange(dl, data, - minGroups, maxGroups, buffer); - if (best != null) { - return best; - } - } else { - best = null; - } - - for (final long power : EGroupingMode.POWER_CHOICES) { - current = EGroupingMode._groupDoublesByPowerRange(power, data, - minGroups, maxGroups, buffer); - if (current != null) { - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - - if (best == null) { - return DISTINCT._groupDoubles(param, data, minGroups, maxGroups, - buffer); - } - return best; - } - }, - - /** - * Group elements in terms of reasonable multiples, including multipes of - * {@code 1}, {@code 2}, {@code 10}, etc. - */ - MULTIPLES { - - /** {@inheritDoc} */ - @Override - final _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - final long pl; - _Groups best, current; - - if (param != null) { - pl = param.longValue(); - best = EGroupingMode._groupLongsByMultipleRange(pl, data, - minGroups, maxGroups, buffer); - if ((param instanceof Float) || (param instanceof Double)) { - if ((pl < Long.MAX_VALUE) && (pl != param.doubleValue())) { - current = EGroupingMode._groupLongsByMultipleRange((pl + 1L), - data, minGroups, maxGroups, buffer); - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - if (best != null) { - return best; - } - } else { - best = null; - } - - for (final long range : EGroupingMode.MULTIPLE_CHOICES_L) { - current = EGroupingMode._groupLongsByMultipleRange(range, data, - minGroups, maxGroups, buffer); - if (current != null) { - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - - if (best == null) { - return DISTINCT._groupLongs(param, data, minGroups, maxGroups, - buffer); - } - return best; - } - - /** {@inheritDoc} */ - @Override - final _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - final double dl; - _Groups best, current; - - if (param != null) { - dl = param.doubleValue(); - best = EGroupingMode._groupDoublesByMultipleRange(dl, data, - minGroups, maxGroups, buffer); - if (best != null) { - return best; - } - } else { - best = null; - } - - for (final double range : EGroupingMode.MULTIPLE_CHOICES_D) { - current = EGroupingMode._groupDoublesByMultipleRange(range, data, - minGroups, maxGroups, buffer); - if (current != null) { - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - - if (best == null) { - return DISTINCT._groupDoubles(param, data, minGroups, maxGroups, - buffer); - } - return best; - } - }, - - /** Group according to any possible choice */ - ANY { - - /** {@inheritDoc} */ - @Override - final _Groups _groupObjects(final Number param, final Object[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - return DISTINCT._groupObjects(param, data, minGroups, maxGroups, - buffer); - } - - /** {@inheritDoc} */ - @Override - _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - _Groups best, current; - - best = DISTINCT._groupLongs(param, data, minGroups, maxGroups, - buffer); - current = POWERS._groupLongs(param, data, minGroups, maxGroups, - buffer); - if (current.compareTo(best) < 0) { - best = current; - } - current = MULTIPLES._groupLongs(param, data, minGroups, maxGroups, - buffer); - if ((current != null) && (current.compareTo(best) < 0)) { - best = current; - } - return best; - } - - /** {@inheritDoc} */ - @Override - _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - _Groups best, current; - - best = DISTINCT._groupDoubles(param, data, minGroups, maxGroups, - buffer); - current = POWERS._groupDoubles(param, data, minGroups, maxGroups, - buffer); - if (current.compareTo(best) < 0) { - best = current; - } - current = MULTIPLES._groupDoubles(param, data, minGroups, maxGroups, - buffer); - if ((current != null) && (current.compareTo(best) < 0)) { - best = current; - } - return best; - } - - } - - ; - - /** the power choices */ - static final long[] POWER_CHOICES = { 10L, 2L, 100L, 4L, 1000L, 8L, 16L, - 10000L, 1024L, 32L, 64L, 256L, 512L, }; - - /** the choices for the {@code long} multiples */ - static final long[] MULTIPLE_CHOICES_L = { 2L, 3L, 4L, 5L, 10L, 15L, - 20L, 25L, 30L, 40L, 50L, 75L, 100L, 200L, 250L, 500L, 750L, 1_000L, - 1_500L, 2_000L, 2_500L, 5_000L, 10_000L, 100_000L, 1_000_000L, - 10_000_000L, 100_000_000L, 1_000_000_000L, 10_000_000_000L, - 100_000_000_000L, 1_000_000_000_000L }; - - /** the choices for the {@code double} multiples */ - static final double[] MULTIPLE_CHOICES_D = { 1e-30d, 1e-24d, 1e-21d, - 1e-18d, 1e-15d, 1e-12d, 1e-9d, 1e-6, 1e-5, 1e-4d, 1E-3d, 1E-2d, - 1E-1d, 0.125d, 0.2d, 0.25d, 0.3d, (1d / 3d), 0.4d, 0.5d, 0.75d, 1d, - 1.5d, 2d, 2.5d, 3d, 4d, 5d, 7.5d, 10d, 15d, 20d, 25d, 30d, 40d, 50d, - 75d, 100d, 200d, 250d, 500d, 750d, 1_000d, 1_500d, 2_000d, 2_500d, - 5_000d, 1e4d, 1e5d, 1e6d, 1e7d, 1e8d, 1e9d, 1e10d, 1e12d, 1e15d, - 1e18d, 1e20d, 1e21d, 1e24d, 1e27d, 1e30d, 1e35d, 1e40d, 1e50d, - 1e60d, 1e70d, 1e100d, 1e200d, 1e300d }; - - /** the name */ - private final String m_name; - - /** - * Create a grouping - * - * @param param - * the parameter - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - _Groups _groupObjects(final Number param, final Object[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - throw new UnsupportedOperationException("Mode " + this + //$NON-NLS-1$ - " can only apply to numbers."); //$NON-NLS-1$ - } - - /** - * Create a grouping - * - * @param param - * the parameter - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - abstract _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer); - - /** - * Create a grouping - * - * @param param - * the parameter - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - abstract _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer); - - /** - * @param power - * the power to group by - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - static _Groups _groupLongsByPowerRange(final long power, - final Number[] data, final int minGroups, final int maxGroups, - final _Group[] buffer) { - - long prev, next, cur; - int minIndex, exclusiveMaxIndex, groupIndex; - _Group group; - boolean exclusive; - - if (power <= 1L) { - return null; - } - - next = power; - do { - prev = next; - next *= power; - } while (next > prev); - - next = (-prev); - prev = Long.MIN_VALUE; - - exclusiveMaxIndex = 0; - groupIndex = 0; - exclusive = true; - - // First, we want to find all the negative powers, then the positive - // ones. - outer: for (;;) { - if (exclusiveMaxIndex >= data.length) { - break outer; - } - minIndex = exclusiveMaxIndex; - - inner: for (;;) { - cur = data[exclusiveMaxIndex].longValue(); - if (cur < prev) { - break inner; - } - if (exclusive) { - if (cur >= next) { - break inner; - } - } else { - if (cur > next) { - break inner; - } - } - exclusiveMaxIndex++; - if (exclusiveMaxIndex >= data.length) { - break inner; - } - } - - if (exclusiveMaxIndex > minIndex) { - group = buffer[groupIndex++]; - group.m_lower = NumericalTypes.valueOf(prev); - group.m_upper = NumericalTypes.valueOf(next); - group.m_isUpperExclusive = exclusive; - group.m_size = (exclusiveMaxIndex - minIndex); - if ((exclusiveMaxIndex >= data.length) || // - (groupIndex >= buffer.length)) { - break outer; - } - } - - prev = next; - if (prev > 0L) { - if (next >= Long.MAX_VALUE) { - throw new IllegalStateException(// - "There are long values bigger than MAX_LONG??"); //$NON-NLS-1$ - } - next *= power; - if (next <= prev) { - next = Long.MAX_VALUE; - exclusive = false; - } - } else { - if (prev == 0L) { - next = power; - } else { - next /= power; - } - } - } - - if (groupIndex < buffer.length) { - buffer[groupIndex].m_size = (-1); - } - - return new _Groups(buffer, minGroups, maxGroups, POWERS,// - NumericalTypes.valueOf(power)); - } - - /** - * @param power - * the power to group by - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - static _Groups _groupDoublesByPowerRange(final double power, - final Number[] data, final int minGroups, final int maxGroups, - final _Group[] buffer) { - double prev, next, cur; - long pwr; - int minIndex, exclusiveMaxIndex, groupIndex; - _Group group; - boolean exclusive; - - if ((power <= 1d) || (power != power) - || (power >= Double.POSITIVE_INFINITY)) { - return null; - } - - pwr = (((long) (Log.INSTANCE.computeAsDouble(power, Double.MAX_VALUE))) + 1L); - prev = Double.NEGATIVE_INFINITY; - while ((next = (-Pow.INSTANCE.computeAsDouble(power, pwr))) <= prev) { - pwr--; - } - - if ((prev != prev) || (next != next)) { - return null; // not possible. - } - - exclusiveMaxIndex = 0; - groupIndex = 0; - exclusive = true; - - // First, we want to find all the negative powers, then the positive - // ones. - outer: for (;;) { - if (exclusiveMaxIndex >= data.length) { - break outer; - } - minIndex = exclusiveMaxIndex; - - inner: for (;;) { - cur = data[exclusiveMaxIndex].doubleValue(); - if (cur < prev) { - break inner; - } - if (exclusive) { - if (cur >= next) { - break inner; - } - } else { - if (cur > next) { - break inner; - } - } - exclusiveMaxIndex++; - if (exclusiveMaxIndex >= data.length) { - break inner; - } - } - - if (exclusiveMaxIndex > minIndex) { - group = buffer[groupIndex++]; - group.m_lower = NumericalTypes.valueOf(prev); - group.m_upper = NumericalTypes.valueOf(next); - group.m_isUpperExclusive = exclusive; - group.m_size = (exclusiveMaxIndex - minIndex); - if ((exclusiveMaxIndex >= data.length) || // - (groupIndex >= buffer.length)) { - break outer; - } - } - - prev = next; - if (next > 0d) { - if (next >= Double.POSITIVE_INFINITY) { - throw new IllegalStateException(// - "There are double values bigger than POSITIVE_INFINITY??"); //$NON-NLS-1$ - } - next = Pow.INSTANCE.computeAsDouble(power, (++pwr)); - if (next >= Double.POSITIVE_INFINITY) { - exclusive = false; - } else { - if (next != next) { - return null; - } - } - } else { - if (prev == 0d) { - pwr = (((long) (Log.INSTANCE.computeAsDouble(power, - Double.MIN_VALUE))) - 1L); - - while ((next = Pow.INSTANCE.computeAsDouble(power, pwr)) <= 0d) { - pwr++; - } - } else { - next = (-(Pow.INSTANCE.computeAsDouble(power, (--pwr)))); - if (next == 0d) { - next = 0d; // deal with -0d -> 0d - } else { - if (next != next) { - return null; - } - } - } - } - } - if (groupIndex < buffer.length) { - buffer[groupIndex].m_size = (-1); - } - - return new _Groups(buffer, minGroups, maxGroups, POWERS,// - NumericalTypes.valueOf(pwr)); - } - - /** - * Group longs by range - * - * @param range - * the range to group by - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - static _Groups _groupLongsByMultipleRange(final long range, - final Number[] data, final int minGroups, final int maxGroups, - final _Group[] buffer) { - - long prev, next, cur; - int minIndex, exclusiveMaxIndex, groupIndex; - _Group group; - boolean exclusive; - - if (range <= 0L) { - return null; - } - - cur = data[0].longValue(); - next = (cur / range); - prev = (data[data.length - 1].longValue() / range); - - if (SaturatingAdd.INSTANCE.computeAsLong(// - ((next > Long.MIN_VALUE) ? Math.abs(next) : Long.MAX_VALUE),// - ((prev > Long.MIN_VALUE) ? Math.abs(prev) : Long.MAX_VALUE)) >= 1000L) { - return null; // too many steps! - } - - if (next >= prev) { - return null;// range to big - } - - next *= range; - prev = next; - if (prev <= 0L) { - while (prev > cur) { - prev = SaturatingSub.INSTANCE.computeAsLong(prev, range); - } - } - next = SaturatingAdd.INSTANCE.computeAsLong(prev, range); - - exclusiveMaxIndex = 0; - groupIndex = 0; - exclusive = true; - - // First, we want to find all the negative powers, then the positive - // ones. - outer: for (;;) { - if (exclusiveMaxIndex >= data.length) { - break outer; - } - minIndex = exclusiveMaxIndex; - - inner: for (;;) { - cur = data[exclusiveMaxIndex].longValue(); - if (cur < prev) { - break inner; - } - if (exclusive) { - if (cur >= next) { - break inner; - } - } else { - if (cur > next) { - break inner; - } - } - exclusiveMaxIndex++; - if (exclusiveMaxIndex >= data.length) { - break inner; - } - } - - if (exclusiveMaxIndex > minIndex) { - group = buffer[groupIndex++]; - group.m_lower = Long.valueOf(prev); - group.m_upper = Long.valueOf(next); - group.m_isUpperExclusive = exclusive; - group.m_size = (exclusiveMaxIndex - minIndex); - if ((exclusiveMaxIndex >= data.length) || // - (groupIndex >= buffer.length)) { - break outer; - } - } - - prev = next; - if (next >= Long.MAX_VALUE) { - throw new IllegalStateException(// - "There are long values bigger than MAX_LONG??"); //$NON-NLS-1$ - } - next = SaturatingAdd.INSTANCE.computeAsLong(next, range); - if (next >= Long.MAX_VALUE) { - exclusive = false; - } - } - - if (groupIndex < buffer.length) { - buffer[groupIndex].m_size = (-1); - } - - return new _Groups(buffer, minGroups, maxGroups, MULTIPLES, - NumericalTypes.valueOf(range)); - } - - /** - * Group longs by range - * - * @param range - * the range to group by - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - static _Groups _groupDoublesByMultipleRange(final double range, - final Number[] data, final int minGroups, final int maxGroups, - final _Group[] buffer) { - double prev, next, cur, span; - long prevMul; - int minIndex, exclusiveMaxIndex, groupIndex; - _Group group; - - if ((range <= 0d) || (range != range) - || (range >= Double.POSITIVE_INFINITY)) { - return null; - } - - cur = data[0].doubleValue(); - prev = Div.INSTANCE.computeAsDouble(cur, range); - next = Div.INSTANCE.computeAsDouble( - data[data.length - 1].doubleValue(), range); - - if ((prev != prev) || // - (next != next) || // - ((span = (Math.abs(next) + Math.abs(prev))) >= 1000d) || // - (span != span) || // - (Math.ceil(prev) >= Math.floor(next))) { - return null; // too many steps! - } - - prevMul = ((long) (prev)); - if (prevMul != prev) { - return null; // cannot use the range due to imprecision - } - - next = prev = Mul.INSTANCE.computeAsDouble(prevMul, range); - if ((prev + range) <= prev) { - return null; - } - - if (prev <= 0d) { - while (prev > cur) { - if (prevMul <= Long.MIN_VALUE) { - return null; - } - prevMul--; - prev = Mul.INSTANCE.computeAsDouble(prevMul, range); - if ((prev + range) <= prev) { - return null; - } - } - } - - if (prevMul >= Long.MAX_VALUE) { - return null; - } - next = Mul.INSTANCE.computeAsDouble((++prevMul), range); - if (next <= prev) { - return null; - } - - exclusiveMaxIndex = 0; - groupIndex = 0; - - // First, we want to find all the negative powers, then the positive - // ones. - outer: for (;;) { - if (exclusiveMaxIndex >= data.length) { - break outer; - } - minIndex = exclusiveMaxIndex; - - inner: for (;;) { - cur = data[exclusiveMaxIndex].longValue(); - if ((cur < prev) || (cur >= next)) { - break inner; - } - exclusiveMaxIndex++; - if (exclusiveMaxIndex >= data.length) { - break inner; - } - } - - if (exclusiveMaxIndex > minIndex) { - group = buffer[groupIndex++]; - group.m_lower = Double.valueOf(prev); - group.m_upper = Double.valueOf(next); - group.m_isUpperExclusive = true; - group.m_size = (exclusiveMaxIndex - minIndex); - if ((exclusiveMaxIndex >= data.length) || // - (groupIndex >= buffer.length)) { - break outer; - } - } - - prev = next; - if (prevMul >= Long.MAX_VALUE) { - return null; - } - prevMul++; - next = Mul.INSTANCE.computeAsDouble(prevMul, range); - if (next <= prev) { - return null; - } - } - - if (groupIndex < buffer.length) { - buffer[groupIndex].m_size = (-1); - } - - return new _Groups(buffer, minGroups, maxGroups, MULTIPLES, - NumericalTypes.valueOf(range)); - } - - /** create the grouping mode */ - EGroupingMode() { - this.m_name = TextUtils.toLowerCase(super.toString()); - } - - /** {@inheritDoc} */ - @Override - public final String toString() { - return this.m_name; - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/old/EGroupingMode.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/old/EGroupingMode.java deleted file mode 100755 index 48bf5c3..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/old/EGroupingMode.java +++ /dev/null @@ -1,838 +0,0 @@ -package org.optimizationBenchmarking.experimentation.attributes.clusters.propertyValueGroups; - -import org.optimizationBenchmarking.utils.math.NumericalTypes; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.Div; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.Mul; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.SaturatingAdd; -import org.optimizationBenchmarking.utils.math.functions.arithmetic.SaturatingSub; -import org.optimizationBenchmarking.utils.math.functions.power.Log; -import org.optimizationBenchmarking.utils.math.functions.power.Pow; - -/** - * A set of different modi for grouping elements. - */ -public enum EGroupingMode { - - /** Group distinct values, i.e., each value becomes an own group */ - DISTINCT { - /** {@inheritDoc} */ - @Override - _Groups _groupObjects(final Number param, final Object[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - int count; - - count = 0; - for (final _Group group : buffer) { - group.m_size = 1; - group.m_isUpperExclusive = false; - group.m_lower = group.m_upper = data[count++]; - } - - return new _Groups(buffer, minGroups, maxGroups, this, null); - } - - /** {@inheritDoc} */ - @Override - _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - return this._groupObjects(param, data, minGroups, maxGroups, buffer); - } - - /** {@inheritDoc} */ - @Override - _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - return this._groupObjects(param, data, minGroups, maxGroups, buffer); - } - }, - - /** - * Group elements in terms of reasonable powers, including powers of - * {@code 2}, {@code 10}, etc. - */ - POWERS { - - /** {@inheritDoc} */ - @Override - final _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - final long pl; - _Groups best, current; - - if (param != null) { - pl = param.longValue(); - best = EGroupingMode._groupLongsByPowerRange(pl, data, minGroups, - maxGroups, buffer); - if ((param instanceof Float) || (param instanceof Double)) { - if ((pl < Long.MAX_VALUE) && (pl != param.doubleValue())) { - current = EGroupingMode._groupLongsByPowerRange((pl + 1L), - data, minGroups, maxGroups, buffer); - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - if (best != null) { - return best; - } - } else { - best = null; - } - - for (final long power : EGroupingMode.POWER_CHOICES) { - current = EGroupingMode._groupLongsByPowerRange(power, data, - minGroups, maxGroups, buffer); - if (current != null) { - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - - if (best == null) { - return DISTINCT._groupLongs(param, data, minGroups, maxGroups, - buffer); - } - return best; - } - - /** {@inheritDoc} */ - @Override - final _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - final double dl; - _Groups best, current; - - if (param != null) { - dl = param.doubleValue(); - best = EGroupingMode._groupDoublesByPowerRange(dl, data, - minGroups, maxGroups, buffer); - if (best != null) { - return best; - } - } else { - best = null; - } - - for (final long power : EGroupingMode.POWER_CHOICES) { - current = EGroupingMode._groupDoublesByPowerRange(power, data, - minGroups, maxGroups, buffer); - if (current != null) { - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - - if (best == null) { - return DISTINCT._groupDoubles(param, data, minGroups, maxGroups, - buffer); - } - return best; - } - }, - - /** - * Group elements in terms of reasonable multiples, including multipes of - * {@code 1}, {@code 2}, {@code 10}, etc. - */ - MULTIPLES { - - /** {@inheritDoc} */ - @Override - final _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - final long pl; - _Groups best, current; - - if (param != null) { - pl = param.longValue(); - best = EGroupingMode._groupLongsByMultipleRange(pl, data, - minGroups, maxGroups, buffer); - if ((param instanceof Float) || (param instanceof Double)) { - if ((pl < Long.MAX_VALUE) && (pl != param.doubleValue())) { - current = EGroupingMode._groupLongsByMultipleRange((pl + 1L), - data, minGroups, maxGroups, buffer); - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - if (best != null) { - return best; - } - } else { - best = null; - } - - for (final long range : EGroupingMode.MULTIPLE_CHOICES_L) { - current = EGroupingMode._groupLongsByMultipleRange(range, data, - minGroups, maxGroups, buffer); - if (current != null) { - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - - if (best == null) { - return DISTINCT._groupLongs(param, data, minGroups, maxGroups, - buffer); - } - return best; - } - - /** {@inheritDoc} */ - @Override - final _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - final double dl; - _Groups best, current; - - if (param != null) { - dl = param.doubleValue(); - best = EGroupingMode._groupDoublesByMultipleRange(dl, data, - minGroups, maxGroups, buffer); - if (best != null) { - return best; - } - } else { - best = null; - } - - for (final double range : EGroupingMode.MULTIPLE_CHOICES_D) { - current = EGroupingMode._groupDoublesByMultipleRange(range, data, - minGroups, maxGroups, buffer); - if (current != null) { - if ((best == null) || (current.compareTo(best) < 0)) { - best = current; - } - } - } - - if (best == null) { - return DISTINCT._groupDoubles(param, data, minGroups, maxGroups, - buffer); - } - return best; - } - }, - - /** Group according to any possible choice */ - ANY { - - /** {@inheritDoc} */ - @Override - final _Groups _groupObjects(final Number param, final Object[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - return DISTINCT._groupObjects(param, data, minGroups, maxGroups, - buffer); - } - - /** {@inheritDoc} */ - @Override - _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - _Groups best, current; - - best = DISTINCT._groupLongs(param, data, minGroups, maxGroups, - buffer); - current = POWERS._groupLongs(param, data, minGroups, maxGroups, - buffer); - if (current.compareTo(best) < 0) { - best = current; - } - current = MULTIPLES._groupLongs(param, data, minGroups, maxGroups, - buffer); - if ((current != null) && (current.compareTo(best) < 0)) { - best = current; - } - return best; - } - - /** {@inheritDoc} */ - @Override - _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - _Groups best, current; - - best = DISTINCT._groupDoubles(param, data, minGroups, maxGroups, - buffer); - current = POWERS._groupDoubles(param, data, minGroups, maxGroups, - buffer); - if (current.compareTo(best) < 0) { - best = current; - } - current = MULTIPLES._groupDoubles(param, data, minGroups, maxGroups, - buffer); - if ((current != null) && (current.compareTo(best) < 0)) { - best = current; - } - return best; - } - - } - - ; - - /** the power choices */ - static final long[] POWER_CHOICES = { 10L, 2L, 100L, 4L, 1000L, 8L, 16L, - 10000L, 1024L, 32L, 64L, 256L, 512L, }; - - /** the choices for the {@code long} multiples */ - static final long[] MULTIPLE_CHOICES_L = { 2L, 3L, 4L, 5L, 10L, 15L, - 20L, 25L, 30L, 40L, 50L, 75L, 100L, 200L, 250L, 500L, 750L, 1_000L, - 1_500L, 2_000L, 2_500L, 5_000L, 10_000L, 100_000L, 1_000_000L, - 10_000_000L, 100_000_000L, 1_000_000_000L, 10_000_000_000L, - 100_000_000_000L, 1_000_000_000_000L }; - - /** the choices for the {@code double} multiples */ - static final double[] MULTIPLE_CHOICES_D = { 1e-30d, 1e-24d, 1e-21d, - 1e-18d, 1e-15d, 1e-12d, 1e-9d, 1e-6, 1e-5, 1e-4d, 1E-3d, 1E-2d, - 1E-1d, 0.125d, 0.2d, 0.25d, 0.3d, (1d / 3d), 0.4d, 0.5d, 0.75d, 1d, - 1.5d, 2d, 2.5d, 3d, 4d, 5d, 7.5d, 10d, 15d, 20d, 25d, 30d, 40d, 50d, - 75d, 100d, 200d, 250d, 500d, 750d, 1_000d, 1_500d, 2_000d, 2_500d, - 5_000d, 1e4d, 1e5d, 1e6d, 1e7d, 1e8d, 1e9d, 1e10d, 1e12d, 1e15d, - 1e18d, 1e20d, 1e21d, 1e24d, 1e27d, 1e30d, 1e35d, 1e40d, 1e50d, - 1e60d, 1e70d, 1e100d, 1e200d, 1e300d }; - - /** the name */ - private final String m_name; - - /** - * Create a grouping - * - * @param param - * the parameter - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - _Groups _groupObjects(final Number param, final Object[] data, - final int minGroups, final int maxGroups, final _Group[] buffer) { - throw new UnsupportedOperationException("Mode " + this + //$NON-NLS-1$ - " can only apply to numbers."); //$NON-NLS-1$ - } - - /** - * Create a grouping - * - * @param param - * the parameter - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - abstract _Groups _groupLongs(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer); - - /** - * Create a grouping - * - * @param param - * the parameter - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - abstract _Groups _groupDoubles(final Number param, final Number[] data, - final int minGroups, final int maxGroups, final _Group[] buffer); - - /** - * @param power - * the power to group by - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - static _Groups _groupLongsByPowerRange(final long power, - final Number[] data, final int minGroups, final int maxGroups, - final _Group[] buffer) { - - long prev, next, cur; - int minIndex, exclusiveMaxIndex, groupIndex; - _Group group; - boolean exclusive; - - if (power <= 1L) { - return null; - } - - next = power; - do { - prev = next; - next *= power; - } while (next > prev); - - next = (-prev); - prev = Long.MIN_VALUE; - - exclusiveMaxIndex = 0; - groupIndex = 0; - exclusive = true; - - // First, we want to find all the negative powers, then the positive - // ones. - outer: for (;;) { - if (exclusiveMaxIndex >= data.length) { - break outer; - } - minIndex = exclusiveMaxIndex; - - inner: for (;;) { - cur = data[exclusiveMaxIndex].longValue(); - if (cur < prev) { - break inner; - } - if (exclusive) { - if (cur >= next) { - break inner; - } - } else { - if (cur > next) { - break inner; - } - } - exclusiveMaxIndex++; - if (exclusiveMaxIndex >= data.length) { - break inner; - } - } - - if (exclusiveMaxIndex > minIndex) { - group = buffer[groupIndex++]; - group.m_lower = NumericalTypes.valueOf(prev); - group.m_upper = NumericalTypes.valueOf(next); - group.m_isUpperExclusive = exclusive; - group.m_size = (exclusiveMaxIndex - minIndex); - if ((exclusiveMaxIndex >= data.length) || // - (groupIndex >= buffer.length)) { - break outer; - } - } - - prev = next; - if (prev > 0L) { - if (next >= Long.MAX_VALUE) { - throw new IllegalStateException(// - "There are long values bigger than MAX_LONG??"); //$NON-NLS-1$ - } - next *= power; - if (next <= prev) { - next = Long.MAX_VALUE; - exclusive = false; - } - } else { - if (prev == 0L) { - next = power; - } else { - next /= power; - } - } - } - - if (groupIndex < buffer.length) { - buffer[groupIndex].m_size = (-1); - } - - return new _Groups(buffer, minGroups, maxGroups, POWERS,// - NumericalTypes.valueOf(power)); - } - - /** - * @param power - * the power to group by - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - static _Groups _groupDoublesByPowerRange(final double power, - final Number[] data, final int minGroups, final int maxGroups, - final _Group[] buffer) { - double prev, next, cur; - long pwr; - int minIndex, exclusiveMaxIndex, groupIndex; - _Group group; - boolean exclusive; - - if ((power <= 1d) || (power != power) - || (power >= Double.POSITIVE_INFINITY)) { - return null; - } - - pwr = (((long) (Log.INSTANCE.computeAsDouble(power, Double.MAX_VALUE))) + 1L); - prev = Double.NEGATIVE_INFINITY; - while ((next = (-Pow.INSTANCE.computeAsDouble(power, pwr))) <= prev) { - pwr--; - } - - if ((prev != prev) || (next != next)) { - return null; // not possible. - } - - exclusiveMaxIndex = 0; - groupIndex = 0; - exclusive = true; - - // First, we want to find all the negative powers, then the positive - // ones. - outer: for (;;) { - if (exclusiveMaxIndex >= data.length) { - break outer; - } - minIndex = exclusiveMaxIndex; - - inner: for (;;) { - cur = data[exclusiveMaxIndex].doubleValue(); - if (cur < prev) { - break inner; - } - if (exclusive) { - if (cur >= next) { - break inner; - } - } else { - if (cur > next) { - break inner; - } - } - exclusiveMaxIndex++; - if (exclusiveMaxIndex >= data.length) { - break inner; - } - } - - if (exclusiveMaxIndex > minIndex) { - group = buffer[groupIndex++]; - group.m_lower = NumericalTypes.valueOf(prev); - group.m_upper = NumericalTypes.valueOf(next); - group.m_isUpperExclusive = exclusive; - group.m_size = (exclusiveMaxIndex - minIndex); - if ((exclusiveMaxIndex >= data.length) || // - (groupIndex >= buffer.length)) { - break outer; - } - } - - prev = next; - if (next > 0d) { - if (next >= Double.POSITIVE_INFINITY) { - throw new IllegalStateException(// - "There are double values bigger than POSITIVE_INFINITY??"); //$NON-NLS-1$ - } - next = Pow.INSTANCE.computeAsDouble(power, (++pwr)); - if (next >= Double.POSITIVE_INFINITY) { - exclusive = false; - } else { - if (next != next) { - return null; - } - } - } else { - if (prev == 0d) { - pwr = (((long) (Log.INSTANCE.computeAsDouble(power, - Double.MIN_VALUE))) - 1L); - - while ((next = Pow.INSTANCE.computeAsDouble(power, pwr)) <= 0d) { - pwr++; - } - } else { - next = (-(Pow.INSTANCE.computeAsDouble(power, (--pwr)))); - if (next == 0d) { - next = 0d; // deal with -0d -> 0d - } else { - if (next != next) { - return null; - } - } - } - } - } - if (groupIndex < buffer.length) { - buffer[groupIndex].m_size = (-1); - } - - return new _Groups(buffer, minGroups, maxGroups, POWERS,// - NumericalTypes.valueOf(pwr)); - } - - /** - * Group longs by range - * - * @param range - * the range to group by - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - static _Groups _groupLongsByMultipleRange(final long range, - final Number[] data, final int minGroups, final int maxGroups, - final _Group[] buffer) { - - long prev, next, cur; - int minIndex, exclusiveMaxIndex, groupIndex; - _Group group; - boolean exclusive; - - if (range <= 0L) { - return null; - } - - cur = data[0].longValue(); - next = (cur / range); - prev = (data[data.length - 1].longValue() / range); - - if (SaturatingAdd.INSTANCE.computeAsLong(// - ((next > Long.MIN_VALUE) ? Math.abs(next) : Long.MAX_VALUE),// - ((prev > Long.MIN_VALUE) ? Math.abs(prev) : Long.MAX_VALUE)) >= 1000L) { - return null; // too many steps! - } - - if (next >= prev) { - return null;// range to big - } - - next *= range; - prev = next; - if (prev <= 0L) { - while (prev > cur) { - prev = SaturatingSub.INSTANCE.computeAsLong(prev, range); - } - } - next = SaturatingAdd.INSTANCE.computeAsLong(prev, range); - - exclusiveMaxIndex = 0; - groupIndex = 0; - exclusive = true; - - // First, we want to find all the negative powers, then the positive - // ones. - outer: for (;;) { - if (exclusiveMaxIndex >= data.length) { - break outer; - } - minIndex = exclusiveMaxIndex; - - inner: for (;;) { - cur = data[exclusiveMaxIndex].longValue(); - if (cur < prev) { - break inner; - } - if (exclusive) { - if (cur >= next) { - break inner; - } - } else { - if (cur > next) { - break inner; - } - } - exclusiveMaxIndex++; - if (exclusiveMaxIndex >= data.length) { - break inner; - } - } - - if (exclusiveMaxIndex > minIndex) { - group = buffer[groupIndex++]; - group.m_lower = Long.valueOf(prev); - group.m_upper = Long.valueOf(next); - group.m_isUpperExclusive = exclusive; - group.m_size = (exclusiveMaxIndex - minIndex); - if ((exclusiveMaxIndex >= data.length) || // - (groupIndex >= buffer.length)) { - break outer; - } - } - - prev = next; - if (next >= Long.MAX_VALUE) { - throw new IllegalStateException(// - "There are long values bigger than MAX_LONG??"); //$NON-NLS-1$ - } - next = SaturatingAdd.INSTANCE.computeAsLong(next, range); - if (next >= Long.MAX_VALUE) { - exclusive = false; - } - } - - if (groupIndex < buffer.length) { - buffer[groupIndex].m_size = (-1); - } - - return new _Groups(buffer, minGroups, maxGroups, MULTIPLES, - NumericalTypes.valueOf(range)); - } - - /** - * Group longs by range - * - * @param range - * the range to group by - * @param data - * the data - * @param minGroups - * the anticipated minimum number of groups - * @param maxGroups - * the anticipated maximum number of groups - * @param buffer - * a multi-purpose buffer - * @return the objects to group - */ - static _Groups _groupDoublesByMultipleRange(final double range, - final Number[] data, final int minGroups, final int maxGroups, - final _Group[] buffer) { - double prev, next, cur, span; - long prevMul; - int minIndex, exclusiveMaxIndex, groupIndex; - _Group group; - - if ((range <= 0d) || (range != range) - || (range >= Double.POSITIVE_INFINITY)) { - return null; - } - - cur = data[0].doubleValue(); - prev = Div.INSTANCE.computeAsDouble(cur, range); - next = Div.INSTANCE.computeAsDouble( - data[data.length - 1].doubleValue(), range); - - if ((prev != prev) || // - (next != next) || // - ((span = (Math.abs(next) + Math.abs(prev))) >= 1000d) || // - (span != span) || // - (Math.ceil(prev) >= Math.floor(next))) { - return null; // too many steps! - } - - prevMul = ((long) (prev)); - if (prevMul != prev) { - return null; // cannot use the range due to imprecision - } - - next = prev = Mul.INSTANCE.computeAsDouble(prevMul, range); - if ((prev + range) <= prev) { - return null; - } - - if (prev <= 0d) { - while (prev > cur) { - if (prevMul <= Long.MIN_VALUE) { - return null; - } - prevMul--; - prev = Mul.INSTANCE.computeAsDouble(prevMul, range); - if ((prev + range) <= prev) { - return null; - } - } - } - - if (prevMul >= Long.MAX_VALUE) { - return null; - } - next = Mul.INSTANCE.computeAsDouble((++prevMul), range); - if (next <= prev) { - return null; - } - - exclusiveMaxIndex = 0; - groupIndex = 0; - - // First, we want to find all the negative powers, then the positive - // ones. - outer: for (;;) { - if (exclusiveMaxIndex >= data.length) { - break outer; - } - minIndex = exclusiveMaxIndex; - - inner: for (;;) { - cur = data[exclusiveMaxIndex].longValue(); - if ((cur < prev) || (cur >= next)) { - break inner; - } - exclusiveMaxIndex++; - if (exclusiveMaxIndex >= data.length) { - break inner; - } - } - - if (exclusiveMaxIndex > minIndex) { - group = buffer[groupIndex++]; - group.m_lower = Double.valueOf(prev); - group.m_upper = Double.valueOf(next); - group.m_isUpperExclusive = true; - group.m_size = (exclusiveMaxIndex - minIndex); - if ((exclusiveMaxIndex >= data.length) || // - (groupIndex >= buffer.length)) { - break outer; - } - } - - prev = next; - if (prevMul >= Long.MAX_VALUE) { - return null; - } - prevMul++; - next = Mul.INSTANCE.computeAsDouble(prevMul, range); - if (next <= prev) { - return null; - } - } - - if (groupIndex < buffer.length) { - buffer[groupIndex].m_size = (-1); - } - - return new _Groups(buffer, minGroups, maxGroups, MULTIPLES, - NumericalTypes.valueOf(range)); - } - - /** create the grouping mode */ - EGroupingMode() { - this.m_name = super.toString().toLowerCase(); - } - - /** {@inheritDoc} */ - @Override - public final String toString() { - return this.m_name; - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/pair.info deleted file mode 100755 index 872c4a1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75374/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75374 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/EGroupingMode.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/EGroupingMode.java -StartLineNum:830 -EndLineNum:830 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/diff.diff deleted file mode 100755 index d1f6827..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/document/impl/abstr/ComplexObject.java b/src/main/java/org/optimizationBenchmarking/utils/document/impl/abstr/ComplexObject.java -index deee8d28..dd8092f2 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/document/impl/abstr/ComplexObject.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/document/impl/abstr/ComplexObject.java -@@ -191 +191 @@ public abstract class ComplexObject extends DocumentPart implements -- s = s.toLowerCase(); -+ s = TextUtils.toLowerCase(s); -@@ -201 +201 @@ public abstract class ComplexObject extends DocumentPart implements -- s = s.substring(i + 1).toLowerCase(); -+ s = TextUtils.toLowerCase(s.substring(i + 1)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/new/ComplexObject.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/new/ComplexObject.java deleted file mode 100755 index dd8092f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/new/ComplexObject.java +++ /dev/null @@ -1,244 +0,0 @@ -package org.optimizationBenchmarking.utils.document.impl.abstr; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.optimizationBenchmarking.utils.comparison.EComparison; -import org.optimizationBenchmarking.utils.document.spec.ELabelType; -import org.optimizationBenchmarking.utils.document.spec.ILabel; -import org.optimizationBenchmarking.utils.document.spec.ILabeledObject; -import org.optimizationBenchmarking.utils.hierarchy.HierarchicalFSM; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - * The base class for sections, tables, and figures - */ -public abstract class ComplexObject extends DocumentPart implements - ILabeledObject { - - /** the package */ - private static final Package LOG_PACKAGE = ComplexObject.class - .getPackage(); - - /** the index in the owning context */ - final int m_index; - - /** the full id of the object, globally identifying it */ - final String m_globalID; - - /** the short id of the object, only identifying it in the owning context */ - final String m_localID; - - /** the label of the object */ - final Label m_label; - - /** - * Create a complex object - * - * @param owner - * the owning section body - * @param index - * the table index in the owning section - * @param useLabel - * the label to use - */ - ComplexObject(final DocumentPart owner, final ILabel useLabel, - final int index) { - super(owner); - - final String oid; - - if (index <= 0) { - throw new IllegalArgumentException(// - "Object index must be greater than 0, but is " //$NON-NLS-1$ - + index); - } - - this._constructorHook(owner); - this.m_index = index; - this.m_localID = this.renderIndex(index); - - oid = ComplexObject._getOwnerID(owner); - if (oid != null) { - this.m_globalID = (oid + this.m_localID); - } else { - this.m_globalID = this.m_localID; - } - - if (useLabel != null) { - this.m_label = this.m_doc._getLabel(this._labelType(), useLabel, - this.m_globalID); - } else { - this.m_label = null; - } - } - - /** - * An internal hook used in the constructor, needed to implement the - * behavior of sections correctly. This method is called before - * initializing the members of this class - * - * @param owner - * the owning object - */ - void _constructorHook(final DocumentPart owner) { - // - } - - /** - * Get the label type - * - * @return the label type - */ - abstract ELabelType _labelType(); - - /** - * Get the owner id - * - * @param owner - * the owner - * @return the id of the owner - */ - @SuppressWarnings("resource") - static final String _getOwnerID(final DocumentElement owner) { - HierarchicalFSM h; - - h = owner; - while (h != null) { - if (h instanceof DocumentElement) { - if (h instanceof ComplexObject) { - return ((ComplexObject) h).m_globalID; - } - h = ((DocumentElement) h)._owner(); - } else { - break; - } - } - - return null; - } - - /** - * Render a string to an index - * - * @param index - * the index to render - * @return a string - */ - protected String renderIndex(final int index) { - return (Integer.toString(index) + '.'); - } - - /** - * Get the label of this object - * - * @return the label of this object, or {@code null} if it has none - */ - @Override - public final Label getLabel() { - return this.m_label; - } - - /** - * Get the index of the object within the owning context (starts at - * {@code 1}) - * - * @return the index of the object within the owning section - */ - public final int getIndex() { - return this.m_index; - } - - /** - * Get the global id, which identifies this object globally unique in the - * document. This id is composed of the rendered indexes through the - * complete element hierarchy. - * - * @return the globally unique id of this object - */ - public final String getGlobalID() { - return this.m_globalID; - } - - /** - * Get the local id, which identifies this object within its owning - * context. It corresponds to a {@link #renderIndex(int) rendered} - * version of {@link #getIndex()}. - * - * @return the locally unique id of this object within the owning context - */ - public final String getLocalID() { - return this.m_localID; - } - - /** - * get the object type - * - * @return the type - */ - final String _getType() { - Class clazz; - String s, n; - int i; - - findName: { - for (clazz = this.getClass(); clazz != null; clazz = clazz - .getSuperclass()) { - if (EComparison.equals(clazz.getPackage(), - ComplexObject.LOG_PACKAGE)) { - s = clazz.getSimpleName(); - if (s != null) { - s = TextUtils.toLowerCase(s); - break findName; - } - } - } - - s = TextUtils.className(this.getClass()); - if (s != null) { - i = s.lastIndexOf('.'); - if (i > 0) { - s = TextUtils.toLowerCase(s.substring(i + 1)); - break findName; - } - } - } - - n = this.m_globalID; - i = n.length(); - if (i <= 0) { - return s; - } - if (n.charAt(--i) == '.') { - n = n.substring(0, i); - } - - return (s + ' ' + n + " for" + this.m_doc.__name());//$NON-NLS-1$ - } - - /** {@inheritDoc} */ - @Override - protected synchronized void onOpen() { - final Logger log; - - super.onOpen(); - - log = this.m_doc.m_logger; - if ((log != null) && (log.isLoggable(Level.FINEST))) { - log.finest("Begin creating " + this._getType());//$NON-NLS-1$ - } - } - - /** {@inheritDoc} */ - @Override - protected synchronized void onClose() { - final Logger log; - - super.onClose(); - - log = this.m_doc.m_logger; - if ((log != null) && (log.isLoggable(Level.FINEST))) { - log.finest("Finished creating " + this._getType());//$NON-NLS-1$ - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/old/ComplexObject.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/old/ComplexObject.java deleted file mode 100755 index deee8d2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/old/ComplexObject.java +++ /dev/null @@ -1,244 +0,0 @@ -package org.optimizationBenchmarking.utils.document.impl.abstr; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.optimizationBenchmarking.utils.comparison.EComparison; -import org.optimizationBenchmarking.utils.document.spec.ELabelType; -import org.optimizationBenchmarking.utils.document.spec.ILabel; -import org.optimizationBenchmarking.utils.document.spec.ILabeledObject; -import org.optimizationBenchmarking.utils.hierarchy.HierarchicalFSM; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - * The base class for sections, tables, and figures - */ -public abstract class ComplexObject extends DocumentPart implements - ILabeledObject { - - /** the package */ - private static final Package LOG_PACKAGE = ComplexObject.class - .getPackage(); - - /** the index in the owning context */ - final int m_index; - - /** the full id of the object, globally identifying it */ - final String m_globalID; - - /** the short id of the object, only identifying it in the owning context */ - final String m_localID; - - /** the label of the object */ - final Label m_label; - - /** - * Create a complex object - * - * @param owner - * the owning section body - * @param index - * the table index in the owning section - * @param useLabel - * the label to use - */ - ComplexObject(final DocumentPart owner, final ILabel useLabel, - final int index) { - super(owner); - - final String oid; - - if (index <= 0) { - throw new IllegalArgumentException(// - "Object index must be greater than 0, but is " //$NON-NLS-1$ - + index); - } - - this._constructorHook(owner); - this.m_index = index; - this.m_localID = this.renderIndex(index); - - oid = ComplexObject._getOwnerID(owner); - if (oid != null) { - this.m_globalID = (oid + this.m_localID); - } else { - this.m_globalID = this.m_localID; - } - - if (useLabel != null) { - this.m_label = this.m_doc._getLabel(this._labelType(), useLabel, - this.m_globalID); - } else { - this.m_label = null; - } - } - - /** - * An internal hook used in the constructor, needed to implement the - * behavior of sections correctly. This method is called before - * initializing the members of this class - * - * @param owner - * the owning object - */ - void _constructorHook(final DocumentPart owner) { - // - } - - /** - * Get the label type - * - * @return the label type - */ - abstract ELabelType _labelType(); - - /** - * Get the owner id - * - * @param owner - * the owner - * @return the id of the owner - */ - @SuppressWarnings("resource") - static final String _getOwnerID(final DocumentElement owner) { - HierarchicalFSM h; - - h = owner; - while (h != null) { - if (h instanceof DocumentElement) { - if (h instanceof ComplexObject) { - return ((ComplexObject) h).m_globalID; - } - h = ((DocumentElement) h)._owner(); - } else { - break; - } - } - - return null; - } - - /** - * Render a string to an index - * - * @param index - * the index to render - * @return a string - */ - protected String renderIndex(final int index) { - return (Integer.toString(index) + '.'); - } - - /** - * Get the label of this object - * - * @return the label of this object, or {@code null} if it has none - */ - @Override - public final Label getLabel() { - return this.m_label; - } - - /** - * Get the index of the object within the owning context (starts at - * {@code 1}) - * - * @return the index of the object within the owning section - */ - public final int getIndex() { - return this.m_index; - } - - /** - * Get the global id, which identifies this object globally unique in the - * document. This id is composed of the rendered indexes through the - * complete element hierarchy. - * - * @return the globally unique id of this object - */ - public final String getGlobalID() { - return this.m_globalID; - } - - /** - * Get the local id, which identifies this object within its owning - * context. It corresponds to a {@link #renderIndex(int) rendered} - * version of {@link #getIndex()}. - * - * @return the locally unique id of this object within the owning context - */ - public final String getLocalID() { - return this.m_localID; - } - - /** - * get the object type - * - * @return the type - */ - final String _getType() { - Class clazz; - String s, n; - int i; - - findName: { - for (clazz = this.getClass(); clazz != null; clazz = clazz - .getSuperclass()) { - if (EComparison.equals(clazz.getPackage(), - ComplexObject.LOG_PACKAGE)) { - s = clazz.getSimpleName(); - if (s != null) { - s = s.toLowerCase(); - break findName; - } - } - } - - s = TextUtils.className(this.getClass()); - if (s != null) { - i = s.lastIndexOf('.'); - if (i > 0) { - s = s.substring(i + 1).toLowerCase(); - break findName; - } - } - } - - n = this.m_globalID; - i = n.length(); - if (i <= 0) { - return s; - } - if (n.charAt(--i) == '.') { - n = n.substring(0, i); - } - - return (s + ' ' + n + " for" + this.m_doc.__name());//$NON-NLS-1$ - } - - /** {@inheritDoc} */ - @Override - protected synchronized void onOpen() { - final Logger log; - - super.onOpen(); - - log = this.m_doc.m_logger; - if ((log != null) && (log.isLoggable(Level.FINEST))) { - log.finest("Begin creating " + this._getType());//$NON-NLS-1$ - } - } - - /** {@inheritDoc} */ - @Override - protected synchronized void onClose() { - final Logger log; - - super.onClose(); - - log = this.m_doc.m_logger; - if ((log != null) && (log.isLoggable(Level.FINEST))) { - log.finest("Finished creating " + this._getType());//$NON-NLS-1$ - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/pair.info deleted file mode 100755 index 78abfd9..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75380/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75380 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/document/impl/abstr/ComplexObject.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/document/impl/abstr/ComplexObject.java -StartLineNum:191 -EndLineNum:191 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/diff.diff deleted file mode 100755 index 5c93517..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/io/paths/predicates/FileNamePredicate.java b/src/main/java/org/optimizationBenchmarking/utils/io/paths/predicates/FileNamePredicate.java -index e418c625..a618a19f 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/io/paths/predicates/FileNamePredicate.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/io/paths/predicates/FileNamePredicate.java -@@ -6,0 +7 @@ import org.optimizationBenchmarking.utils.io.paths.PathUtils; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -60 +61 @@ public final class FileNamePredicate extends StringInListIgnoreCase { -- return ((s != null) ? s.toLowerCase() : null); -+ return ((s != null) ? TextUtils.toLowerCase(s) : null); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/new/FileNamePredicate.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/new/FileNamePredicate.java deleted file mode 100755 index a618a19..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/new/FileNamePredicate.java +++ /dev/null @@ -1,63 +0,0 @@ -package org.optimizationBenchmarking.utils.io.paths.predicates; - -import java.nio.file.Path; -import java.util.Collection; - -import org.optimizationBenchmarking.utils.io.paths.PathUtils; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.text.predicates.StringInListIgnoreCase; - -/** - * This predicate is {@code true} if the file name matches a given - * template. - */ -public final class FileNamePredicate extends StringInListIgnoreCase { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** - * ignore (remove) the file extension (if any) before the name comparison - */ - private final boolean m_ignoreExtension; - - /** - * Create the file name comparison predicate - * - * @param ignoreExtension - * ignore (remove) the file extension (if any) before the name - * comparison - * @param list - * the string list - */ - public FileNamePredicate(final boolean ignoreExtension, - final String... list) { - super(list); - this.m_ignoreExtension = ignoreExtension; - } - - /** - * Create the file name comparison predicate - * - * @param ignoreExtension - * ignore (remove) the file extension (if any) before the name - * comparison - * @param list - * the string list - */ - public FileNamePredicate(final boolean ignoreExtension, - final Collection list) { - super(list); - this.m_ignoreExtension = ignoreExtension; - } - - /** {@inheritDoc} */ - @Override - protected final String getString(final Path file) { - final String s; - - s = (this.m_ignoreExtension ? PathUtils - .getFileNameWithoutExtension(file) : PathUtils.getName(file)); - return ((s != null) ? TextUtils.toLowerCase(s) : null); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/old/FileNamePredicate.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/old/FileNamePredicate.java deleted file mode 100755 index e418c62..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/old/FileNamePredicate.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.optimizationBenchmarking.utils.io.paths.predicates; - -import java.nio.file.Path; -import java.util.Collection; - -import org.optimizationBenchmarking.utils.io.paths.PathUtils; -import org.optimizationBenchmarking.utils.text.predicates.StringInListIgnoreCase; - -/** - * This predicate is {@code true} if the file name matches a given - * template. - */ -public final class FileNamePredicate extends StringInListIgnoreCase { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** - * ignore (remove) the file extension (if any) before the name comparison - */ - private final boolean m_ignoreExtension; - - /** - * Create the file name comparison predicate - * - * @param ignoreExtension - * ignore (remove) the file extension (if any) before the name - * comparison - * @param list - * the string list - */ - public FileNamePredicate(final boolean ignoreExtension, - final String... list) { - super(list); - this.m_ignoreExtension = ignoreExtension; - } - - /** - * Create the file name comparison predicate - * - * @param ignoreExtension - * ignore (remove) the file extension (if any) before the name - * comparison - * @param list - * the string list - */ - public FileNamePredicate(final boolean ignoreExtension, - final Collection list) { - super(list); - this.m_ignoreExtension = ignoreExtension; - } - - /** {@inheritDoc} */ - @Override - protected final String getString(final Path file) { - final String s; - - s = (this.m_ignoreExtension ? PathUtils - .getFileNameWithoutExtension(file) : PathUtils.getName(file)); - return ((s != null) ? s.toLowerCase() : null); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/pair.info deleted file mode 100755 index 46fed28..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75417/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75417 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/io/paths/predicates/FileNamePredicate.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/io/paths/predicates/FileNamePredicate.java -StartLineNum:60 -EndLineNum:60 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/diff.diff deleted file mode 100755 index 5983778..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/graphics/FontProperties.java b/src/main/java/org/optimizationBenchmarking/utils/graphics/FontProperties.java -index d69743d3..7e4fd6ec 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/graphics/FontProperties.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/graphics/FontProperties.java -@@ -214 +214 @@ public class FontProperties extends HashObject { -- beginner = beginner.toLowerCase(); -+ beginner = TextUtils.toLowerCase(beginner); -@@ -504,2 +504,2 @@ public class FontProperties extends HashObject { -- this.m_name = TextUtils.prepare(data.substring(idx + 1)) -- .toLowerCase(); -+ this.m_name = TextUtils.toLowerCase(TextUtils.prepare(// -+ data.substring(idx + 1))); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/new/FontProperties.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/new/FontProperties.java deleted file mode 100755 index 7e4fd6e..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/new/FontProperties.java +++ /dev/null @@ -1,540 +0,0 @@ -package org.optimizationBenchmarking.utils.graphics; - -import java.awt.Font; -import java.awt.font.TextAttribute; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Locale; - -import org.optimizationBenchmarking.utils.config.Configuration; -import org.optimizationBenchmarking.utils.error.ErrorUtils; -import org.optimizationBenchmarking.utils.error.RethrowMode; -import org.optimizationBenchmarking.utils.hash.HashObject; -import org.optimizationBenchmarking.utils.hash.HashUtils; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** A class managing font properties */ -public class FontProperties extends HashObject { - - /** the bold font flag */ - protected static final int FONT_FLAG_BOLD = 1; - /** the italic font flag */ - protected static final int FONT_FLAG_ITALIC = (FontProperties.FONT_FLAG_BOLD << 1); - /** the underlined font flag */ - protected static final int FONT_FLAG_UNDERLINED = (FontProperties.FONT_FLAG_ITALIC << 1); - /** the monospace font flag */ - protected static final int FONT_FLAG_MONOSPACE = (FontProperties.FONT_FLAG_UNDERLINED << 1); - /** the serif font flag */ - protected static final int FONT_FLAG_SERIF = (FontProperties.FONT_FLAG_MONOSPACE << 1); - /** the sans-serif font flag */ - protected static final int FONT_FLAG_SANS_SERIF = (FontProperties.FONT_FLAG_SERIF << 1); - /** the dialog font flag */ - protected static final int FONT_FLAG_DIALOG = (FontProperties.FONT_FLAG_SANS_SERIF << 1); - /** the dialog input font flag */ - protected static final int FONT_FLAG_DIALOG_INPUT = (FontProperties.FONT_FLAG_DIALOG << 1); - - /** the font family flags */ - private static final int FONT_FLAG_FAMILY = (FontProperties.FONT_FLAG_MONOSPACE - | FontProperties.FONT_FLAG_SERIF - | FontProperties.FONT_FLAG_SANS_SERIF - | FontProperties.FONT_FLAG_DIALOG | FontProperties.FONT_FLAG_DIALOG_INPUT); - - /** all the font flags */ - private static final int FONT_FLAG_ALL = (FontProperties.FONT_FLAG_BOLD - | FontProperties.FONT_FLAG_ITALIC - | FontProperties.FONT_FLAG_UNDERLINED - | FontProperties.FONT_FLAG_MONOSPACE - | FontProperties.FONT_FLAG_SERIF - | FontProperties.FONT_FLAG_SANS_SERIF - | FontProperties.FONT_FLAG_DIALOG | FontProperties.FONT_FLAG_DIALOG_INPUT); - - /** the flags */ - protected final int m_flags; - - /** - * Create the font properties object - * - * @param flags - * the flags - */ - protected FontProperties(final int flags) { - super(); - this.m_flags = (flags & FontProperties.FONT_FLAG_ALL); - } - - /** {@inheritDoc} */ - @Override - protected int calcHashCode() { - return HashUtils.hashCode(this.m_flags); - } - - /** {@inheritDoc} */ - @Override - public boolean equals(final Object o) { - if (o == this) { - return true; - } - if (o instanceof FontProperties) { - return (((FontProperties) o).m_flags == this.m_flags); - } - return false; - } - - /** - * Get the font family - * - * @return the font family, or {@code null} if no family is defined - */ - public final EFontFamily getFamily() { - switch (this.m_flags & FontProperties.FONT_FLAG_FAMILY) { - case FONT_FLAG_SERIF: { - return EFontFamily.SERIF; - } - case FONT_FLAG_SANS_SERIF: { - return EFontFamily.SANS_SERIF; - } - case FONT_FLAG_MONOSPACE: { - return EFontFamily.MONOSPACED; - } - case FONT_FLAG_DIALOG: { - return EFontFamily.DIALOG; - } - case FONT_FLAG_DIALOG_INPUT: { - return EFontFamily.DIALOG_INPUT; - } - default: { - return null; - } - } - } - - /** - * Is this font italic? - * - * @return {@code true} for italic fonts, {@code false} for normal ones - */ - public final boolean isItalic() { - return ((this.m_flags & FontProperties.FONT_FLAG_ITALIC) != 0); - } - - /** - * Is this font bold? - * - * @return {@code true} for bold fonts, {@code false} for normal ones - */ - public final boolean isBold() { - return ((this.m_flags & FontProperties.FONT_FLAG_BOLD) != 0); - } - - /** - * Is this font underlined? - * - * @return {@code true} for underlined fonts, {@code false} for normal - * ones - */ - public final boolean isUnderlined() { - return ((this.m_flags & FontProperties.FONT_FLAG_UNDERLINED) != 0); - } - - /** - *

- * Get the {@link java.awt.Font#getStyle() style flags} of this font - * property set. If the font properties is obtained via - * {@link #getFontProperties(Font,boolean)} or - * {@link #getFontProperties(String)} , then this method's result is - * based on a heuristic detection whether a font is - * {@link java.awt.Font#BOLD bold} or {@link java.awt.Font#ITALIC} based - * on the font name. - *

- *

- * Some fonts have particular name parts which already enforce certain - * style features. Examples for this are the LaTeX fonts such as - * {@code cmbx}, {@code cmti}, etc. Although the documentation of - * {@link java.awt.Font} states that - * The style argument is merged with the specified face's style, not - * added or subtracted., this may not work: The fonts may not be - * annotated as bold while being bold, for instance, resulting in - * super-bold fonts if loaded in the "bold" way. Other fonts - * may already be italic, slanted, or oblique, but get italic-ized - * additionally by the rendering engine, leading to odd results. - *

- *

- * Thus, the information returned by this method may be quite helpful - * when loading fonts. Let's say it returns {@code mask} for a given - * font. Then, the "goal" style constant based to the - * {@link java.awt.Font#Font(String, int, int) font constructor} may be - * {@code and-not}-ed ({@code style & (~mask)}) with this return value. - * The output of {@link java.awt.Font#getStyle()}, on the other hand, may - * be {@code or}-ed ({@code | mask}) with the result of this method. - *

- * - * @return the style flags, a combination of {@link java.awt.Font#PLAIN}, - * {@link java.awt.Font#ITALIC}, and {@link java.awt.Font#BOLD} - */ - public final int getStyle() { - int f; - - f = 0; - if ((this.m_flags & FontProperties.FONT_FLAG_ITALIC) != 0) { - f |= Font.ITALIC; - } - - if ((this.m_flags & FontProperties.FONT_FLAG_BOLD) != 0) { - f |= Font.BOLD; - } - - if (f != 0) { - return f; - } - return Font.PLAIN; - } - - /** - * Get the font properties for a font name in a heuristic way - * - * @param name - * the font name - * @return the font family - */ - public static final FontProperties getFontProperties(final String name) { - String str, beginner; - int cmpMode, j, i; - char ch; - - if (name == null) { - return null; - } - beginner = TextUtils.normalize(name); - if (beginner == null) { - return null; - } - beginner = TextUtils.toLowerCase(beginner); - - for (cmpMode = 0; cmpMode <= 3; cmpMode++) { - str = beginner; - - inner: for (;;) { - // test all flags - for (final __FontFlags f : __FontFlags.FLAGS) { - switch (cmpMode) { - case 0: { - if (f.m_name.equals(str)) { - return f; - } - break; - } - case 1: { - if (f.m_name.startsWith(str)) { - return f; - } - break; - } - case 2: { - if (f.m_name.endsWith(str)) { - return f; - } - break; - } - default: { - if (f.m_name.contains(str)) { - return f; - } - break; - } - } - } - - // no match: try to make string shorter - - // first: try to remove font size suffixes - j = str.length(); - numberSuffix: for (i = j; (--i) >= 0;) { - ch = str.charAt(i); - if ((ch < '0') || (ch > '9')) { - break numberSuffix; - } - } - i++; - if ((i < j) && (i > 0)) { - str = TextUtils.prepare(str.substring(0, i)); - if (str != null) { - continue inner; - } - } - - // try to divide the name by removing suffixes - i = str.lastIndexOf(' '); - j = str.lastIndexOf('-'); - if (j > i) { - i = j; - } - if (i > 0) { - str = TextUtils.prepare(str.substring(0, i)); - if (str != null) { - continue inner; - } - } - - break inner; - } - } - - return null; - } - - /** - * Get the font properties for a given font - * - * @param font - * the font object - * @param useOnlyName - * only use the font name to get the properties - * @return the font properties - */ - @SuppressWarnings("incomplete-switch") - public static final FontProperties getFontProperties(final Font font, - final boolean useOnlyName) { - FontProperties fp; - int style, fam1, fam2; - - if (font == null) { - return null; - } - fp = FontProperties.getFontProperties(font.getFontName()); - if (fp == null) { - fp = FontProperties.getFontProperties(font.getFontName(Locale.US)); - if (fp == null) { - fp = FontProperties.getFontProperties(font.getPSName()); - if (fp == null) { - fp = FontProperties.getFontProperties(font.getName()); - if (fp == null) { - fp = FontProperties.getFontProperties(font.getFamily()); - if (fp == null) { - fp = FontProperties.getFontProperties(// - font.getFamily(Locale.US)); - } - } - } - } - } - - if (useOnlyName) { - return fp; - } - - style = 0; - if (font.isBold()) { - style |= FontProperties.FONT_FLAG_BOLD; - } - if (font.isItalic()) { - style |= FontProperties.FONT_FLAG_ITALIC; - } - - if (FontProperties.isFontUnderlined(font)) { - style |= FontProperties.FONT_FLAG_UNDERLINED; - } - - switch (font.getFamily()) { - case Font.SANS_SERIF: { - style |= FontProperties.FONT_FLAG_SANS_SERIF; - break; - } - case Font.SERIF: { - style |= FontProperties.FONT_FLAG_SERIF; - break; - } - case Font.MONOSPACED: { - style |= FontProperties.FONT_FLAG_MONOSPACE; - break; - } - case Font.DIALOG: { - style |= FontProperties.FONT_FLAG_DIALOG; - break; - } - case Font.DIALOG_INPUT: { - style |= FontProperties.FONT_FLAG_DIALOG_INPUT; - break; - } - } - - if (fp != null) { - fam1 = (style & FontProperties.FONT_FLAG_FAMILY); - fam2 = (style & FontProperties.FONT_FLAG_FAMILY); - style |= (fp.m_flags & (~FontProperties.FONT_FLAG_FAMILY)); - if (((fam1 == 0) || (fam1 == FontProperties.FONT_FLAG_DIALOG) || (fam1 == FontProperties.FONT_FLAG_DIALOG_INPUT)) - && (((fam2 != 0) && (fam2 != FontProperties.FONT_FLAG_DIALOG) && (fam2 != FontProperties.FONT_FLAG_DIALOG_INPUT)))) { - style = ((style & (~FontProperties.FONT_FLAG_FAMILY)) | fam2); - } - if (style == fp.m_flags) { - return fp; - } - } - - return new FontProperties(style); - } - - /** - * Check whether a font is underlined or not. This method bases its - * result solely on the properties of the font, it does not perform a - * resource-based lookup. If you want this, use - * {@link #getFontProperties(Font, boolean) getFontProperties(Font, false)}.{@link #isUnderlined()} - * instead. - * - * @param font - * the font - * @return {@code true} if the font is underlined, {@code false} - * otherwise - */ - public static final boolean isFontUnderlined(final Font font) { - final Number underlineAtt; - - underlineAtt = ((Number) (font.getAttributes() - .get(TextAttribute.UNDERLINE))); - return ((underlineAtt != null) && (underlineAtt.intValue() >= 0)); - } - - /** - * get the flags - * - * @param data - * the data string - * @param idx - * the start index - * @return the flags - */ - static final int _flags(final String data, final int idx) { - int i, f; - - i = idx; - - f = 0; - for (; (--i) >= 0;) { - switch (data.charAt(i)) { - case 'b': - case 'B': { - f |= FontProperties.FONT_FLAG_BOLD; - break; - } - case 'i': - case 'I': { - f |= FontProperties.FONT_FLAG_ITALIC; - break; - } - case 'm': - case 'M': { - f |= FontProperties.FONT_FLAG_MONOSPACE; - break; - } - case 's': - case 'S': { - f |= FontProperties.FONT_FLAG_SANS_SERIF; - break; - } - case 'r': - case 'R': { - f |= FontProperties.FONT_FLAG_SERIF; - break; - } - case 'u': - case 'U': { - f |= FontProperties.FONT_FLAG_UNDERLINED; - break; - } - default: { - throw new IllegalArgumentException("Illegal flag: " //$NON-NLS-1$ - + data.charAt(i)); - } - } - } - - return f; - } - - /** the internal font flag class */ - private static final class __FontFlags extends FontProperties implements - Comparable<__FontFlags> { - - /** the array with the font flags */ - static final __FontFlags[] FLAGS; - - // load the flags of the known fonts - static { - ArrayList<__FontFlags> al; - String s; - - al = new ArrayList<>(); - try (final InputStream is = // - FontProperties.class.getResourceAsStream("knownFonts.txt")) { //$NON-NLS-1$ - try (final InputStreamReader isr = new InputStreamReader(is)) { - try (final BufferedReader br = new BufferedReader(isr)) { - while ((s = br.readLine()) != null) { - s = TextUtils.normalize(s); - if ((s != null) && (s.charAt(0) != '#')) { - al.add(new __FontFlags(s)); - } - } - } - } - } catch (final Throwable ioe) { - ErrorUtils.logError(Configuration.getGlobalLogger(),// - "Error when reading list of known fonts.", //$NON-NLS-1$ - ioe, true, RethrowMode.AS_RUNTIME_EXCEPTION); - } - - FLAGS = al.toArray(new __FontFlags[al.size()]); - Arrays.sort(__FontFlags.FLAGS); - } - - /** the font name */ - final String m_name; - - /** - * create - * - * @param data - * the data string - * @param idx - * the index - */ - private __FontFlags(final String data, final int idx) { - super(FontProperties._flags(data, idx)); - this.m_name = TextUtils.toLowerCase(TextUtils.prepare(// - data.substring(idx + 1))); - } - - /** - * create - * - * @param data - * the data string - */ - __FontFlags(final String data) { - this(data, data.indexOf(' ')); - } - - /** {@inheritDoc} */ - @Override - public final int compareTo(final __FontFlags o) { - String a, b; - int r; - - if (this == o) { - return 0; - } - if (o == null) { - return (-1); - } - a = this.m_name; - b = o.m_name; - r = Integer.compare(b.length(), a.length()); - if (r != 0) { - return r; - } - return a.compareTo(b); - } - - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/old/FontProperties.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/old/FontProperties.java deleted file mode 100755 index d69743d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/old/FontProperties.java +++ /dev/null @@ -1,540 +0,0 @@ -package org.optimizationBenchmarking.utils.graphics; - -import java.awt.Font; -import java.awt.font.TextAttribute; -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Locale; - -import org.optimizationBenchmarking.utils.config.Configuration; -import org.optimizationBenchmarking.utils.error.ErrorUtils; -import org.optimizationBenchmarking.utils.error.RethrowMode; -import org.optimizationBenchmarking.utils.hash.HashObject; -import org.optimizationBenchmarking.utils.hash.HashUtils; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** A class managing font properties */ -public class FontProperties extends HashObject { - - /** the bold font flag */ - protected static final int FONT_FLAG_BOLD = 1; - /** the italic font flag */ - protected static final int FONT_FLAG_ITALIC = (FontProperties.FONT_FLAG_BOLD << 1); - /** the underlined font flag */ - protected static final int FONT_FLAG_UNDERLINED = (FontProperties.FONT_FLAG_ITALIC << 1); - /** the monospace font flag */ - protected static final int FONT_FLAG_MONOSPACE = (FontProperties.FONT_FLAG_UNDERLINED << 1); - /** the serif font flag */ - protected static final int FONT_FLAG_SERIF = (FontProperties.FONT_FLAG_MONOSPACE << 1); - /** the sans-serif font flag */ - protected static final int FONT_FLAG_SANS_SERIF = (FontProperties.FONT_FLAG_SERIF << 1); - /** the dialog font flag */ - protected static final int FONT_FLAG_DIALOG = (FontProperties.FONT_FLAG_SANS_SERIF << 1); - /** the dialog input font flag */ - protected static final int FONT_FLAG_DIALOG_INPUT = (FontProperties.FONT_FLAG_DIALOG << 1); - - /** the font family flags */ - private static final int FONT_FLAG_FAMILY = (FontProperties.FONT_FLAG_MONOSPACE - | FontProperties.FONT_FLAG_SERIF - | FontProperties.FONT_FLAG_SANS_SERIF - | FontProperties.FONT_FLAG_DIALOG | FontProperties.FONT_FLAG_DIALOG_INPUT); - - /** all the font flags */ - private static final int FONT_FLAG_ALL = (FontProperties.FONT_FLAG_BOLD - | FontProperties.FONT_FLAG_ITALIC - | FontProperties.FONT_FLAG_UNDERLINED - | FontProperties.FONT_FLAG_MONOSPACE - | FontProperties.FONT_FLAG_SERIF - | FontProperties.FONT_FLAG_SANS_SERIF - | FontProperties.FONT_FLAG_DIALOG | FontProperties.FONT_FLAG_DIALOG_INPUT); - - /** the flags */ - protected final int m_flags; - - /** - * Create the font properties object - * - * @param flags - * the flags - */ - protected FontProperties(final int flags) { - super(); - this.m_flags = (flags & FontProperties.FONT_FLAG_ALL); - } - - /** {@inheritDoc} */ - @Override - protected int calcHashCode() { - return HashUtils.hashCode(this.m_flags); - } - - /** {@inheritDoc} */ - @Override - public boolean equals(final Object o) { - if (o == this) { - return true; - } - if (o instanceof FontProperties) { - return (((FontProperties) o).m_flags == this.m_flags); - } - return false; - } - - /** - * Get the font family - * - * @return the font family, or {@code null} if no family is defined - */ - public final EFontFamily getFamily() { - switch (this.m_flags & FontProperties.FONT_FLAG_FAMILY) { - case FONT_FLAG_SERIF: { - return EFontFamily.SERIF; - } - case FONT_FLAG_SANS_SERIF: { - return EFontFamily.SANS_SERIF; - } - case FONT_FLAG_MONOSPACE: { - return EFontFamily.MONOSPACED; - } - case FONT_FLAG_DIALOG: { - return EFontFamily.DIALOG; - } - case FONT_FLAG_DIALOG_INPUT: { - return EFontFamily.DIALOG_INPUT; - } - default: { - return null; - } - } - } - - /** - * Is this font italic? - * - * @return {@code true} for italic fonts, {@code false} for normal ones - */ - public final boolean isItalic() { - return ((this.m_flags & FontProperties.FONT_FLAG_ITALIC) != 0); - } - - /** - * Is this font bold? - * - * @return {@code true} for bold fonts, {@code false} for normal ones - */ - public final boolean isBold() { - return ((this.m_flags & FontProperties.FONT_FLAG_BOLD) != 0); - } - - /** - * Is this font underlined? - * - * @return {@code true} for underlined fonts, {@code false} for normal - * ones - */ - public final boolean isUnderlined() { - return ((this.m_flags & FontProperties.FONT_FLAG_UNDERLINED) != 0); - } - - /** - *

- * Get the {@link java.awt.Font#getStyle() style flags} of this font - * property set. If the font properties is obtained via - * {@link #getFontProperties(Font,boolean)} or - * {@link #getFontProperties(String)} , then this method's result is - * based on a heuristic detection whether a font is - * {@link java.awt.Font#BOLD bold} or {@link java.awt.Font#ITALIC} based - * on the font name. - *

- *

- * Some fonts have particular name parts which already enforce certain - * style features. Examples for this are the LaTeX fonts such as - * {@code cmbx}, {@code cmti}, etc. Although the documentation of - * {@link java.awt.Font} states that - * The style argument is merged with the specified face's style, not - * added or subtracted., this may not work: The fonts may not be - * annotated as bold while being bold, for instance, resulting in - * super-bold fonts if loaded in the "bold" way. Other fonts - * may already be italic, slanted, or oblique, but get italic-ized - * additionally by the rendering engine, leading to odd results. - *

- *

- * Thus, the information returned by this method may be quite helpful - * when loading fonts. Let's say it returns {@code mask} for a given - * font. Then, the "goal" style constant based to the - * {@link java.awt.Font#Font(String, int, int) font constructor} may be - * {@code and-not}-ed ({@code style & (~mask)}) with this return value. - * The output of {@link java.awt.Font#getStyle()}, on the other hand, may - * be {@code or}-ed ({@code | mask}) with the result of this method. - *

- * - * @return the style flags, a combination of {@link java.awt.Font#PLAIN}, - * {@link java.awt.Font#ITALIC}, and {@link java.awt.Font#BOLD} - */ - public final int getStyle() { - int f; - - f = 0; - if ((this.m_flags & FontProperties.FONT_FLAG_ITALIC) != 0) { - f |= Font.ITALIC; - } - - if ((this.m_flags & FontProperties.FONT_FLAG_BOLD) != 0) { - f |= Font.BOLD; - } - - if (f != 0) { - return f; - } - return Font.PLAIN; - } - - /** - * Get the font properties for a font name in a heuristic way - * - * @param name - * the font name - * @return the font family - */ - public static final FontProperties getFontProperties(final String name) { - String str, beginner; - int cmpMode, j, i; - char ch; - - if (name == null) { - return null; - } - beginner = TextUtils.normalize(name); - if (beginner == null) { - return null; - } - beginner = beginner.toLowerCase(); - - for (cmpMode = 0; cmpMode <= 3; cmpMode++) { - str = beginner; - - inner: for (;;) { - // test all flags - for (final __FontFlags f : __FontFlags.FLAGS) { - switch (cmpMode) { - case 0: { - if (f.m_name.equals(str)) { - return f; - } - break; - } - case 1: { - if (f.m_name.startsWith(str)) { - return f; - } - break; - } - case 2: { - if (f.m_name.endsWith(str)) { - return f; - } - break; - } - default: { - if (f.m_name.contains(str)) { - return f; - } - break; - } - } - } - - // no match: try to make string shorter - - // first: try to remove font size suffixes - j = str.length(); - numberSuffix: for (i = j; (--i) >= 0;) { - ch = str.charAt(i); - if ((ch < '0') || (ch > '9')) { - break numberSuffix; - } - } - i++; - if ((i < j) && (i > 0)) { - str = TextUtils.prepare(str.substring(0, i)); - if (str != null) { - continue inner; - } - } - - // try to divide the name by removing suffixes - i = str.lastIndexOf(' '); - j = str.lastIndexOf('-'); - if (j > i) { - i = j; - } - if (i > 0) { - str = TextUtils.prepare(str.substring(0, i)); - if (str != null) { - continue inner; - } - } - - break inner; - } - } - - return null; - } - - /** - * Get the font properties for a given font - * - * @param font - * the font object - * @param useOnlyName - * only use the font name to get the properties - * @return the font properties - */ - @SuppressWarnings("incomplete-switch") - public static final FontProperties getFontProperties(final Font font, - final boolean useOnlyName) { - FontProperties fp; - int style, fam1, fam2; - - if (font == null) { - return null; - } - fp = FontProperties.getFontProperties(font.getFontName()); - if (fp == null) { - fp = FontProperties.getFontProperties(font.getFontName(Locale.US)); - if (fp == null) { - fp = FontProperties.getFontProperties(font.getPSName()); - if (fp == null) { - fp = FontProperties.getFontProperties(font.getName()); - if (fp == null) { - fp = FontProperties.getFontProperties(font.getFamily()); - if (fp == null) { - fp = FontProperties.getFontProperties(// - font.getFamily(Locale.US)); - } - } - } - } - } - - if (useOnlyName) { - return fp; - } - - style = 0; - if (font.isBold()) { - style |= FontProperties.FONT_FLAG_BOLD; - } - if (font.isItalic()) { - style |= FontProperties.FONT_FLAG_ITALIC; - } - - if (FontProperties.isFontUnderlined(font)) { - style |= FontProperties.FONT_FLAG_UNDERLINED; - } - - switch (font.getFamily()) { - case Font.SANS_SERIF: { - style |= FontProperties.FONT_FLAG_SANS_SERIF; - break; - } - case Font.SERIF: { - style |= FontProperties.FONT_FLAG_SERIF; - break; - } - case Font.MONOSPACED: { - style |= FontProperties.FONT_FLAG_MONOSPACE; - break; - } - case Font.DIALOG: { - style |= FontProperties.FONT_FLAG_DIALOG; - break; - } - case Font.DIALOG_INPUT: { - style |= FontProperties.FONT_FLAG_DIALOG_INPUT; - break; - } - } - - if (fp != null) { - fam1 = (style & FontProperties.FONT_FLAG_FAMILY); - fam2 = (style & FontProperties.FONT_FLAG_FAMILY); - style |= (fp.m_flags & (~FontProperties.FONT_FLAG_FAMILY)); - if (((fam1 == 0) || (fam1 == FontProperties.FONT_FLAG_DIALOG) || (fam1 == FontProperties.FONT_FLAG_DIALOG_INPUT)) - && (((fam2 != 0) && (fam2 != FontProperties.FONT_FLAG_DIALOG) && (fam2 != FontProperties.FONT_FLAG_DIALOG_INPUT)))) { - style = ((style & (~FontProperties.FONT_FLAG_FAMILY)) | fam2); - } - if (style == fp.m_flags) { - return fp; - } - } - - return new FontProperties(style); - } - - /** - * Check whether a font is underlined or not. This method bases its - * result solely on the properties of the font, it does not perform a - * resource-based lookup. If you want this, use - * {@link #getFontProperties(Font, boolean) getFontProperties(Font, false)}.{@link #isUnderlined()} - * instead. - * - * @param font - * the font - * @return {@code true} if the font is underlined, {@code false} - * otherwise - */ - public static final boolean isFontUnderlined(final Font font) { - final Number underlineAtt; - - underlineAtt = ((Number) (font.getAttributes() - .get(TextAttribute.UNDERLINE))); - return ((underlineAtt != null) && (underlineAtt.intValue() >= 0)); - } - - /** - * get the flags - * - * @param data - * the data string - * @param idx - * the start index - * @return the flags - */ - static final int _flags(final String data, final int idx) { - int i, f; - - i = idx; - - f = 0; - for (; (--i) >= 0;) { - switch (data.charAt(i)) { - case 'b': - case 'B': { - f |= FontProperties.FONT_FLAG_BOLD; - break; - } - case 'i': - case 'I': { - f |= FontProperties.FONT_FLAG_ITALIC; - break; - } - case 'm': - case 'M': { - f |= FontProperties.FONT_FLAG_MONOSPACE; - break; - } - case 's': - case 'S': { - f |= FontProperties.FONT_FLAG_SANS_SERIF; - break; - } - case 'r': - case 'R': { - f |= FontProperties.FONT_FLAG_SERIF; - break; - } - case 'u': - case 'U': { - f |= FontProperties.FONT_FLAG_UNDERLINED; - break; - } - default: { - throw new IllegalArgumentException("Illegal flag: " //$NON-NLS-1$ - + data.charAt(i)); - } - } - } - - return f; - } - - /** the internal font flag class */ - private static final class __FontFlags extends FontProperties implements - Comparable<__FontFlags> { - - /** the array with the font flags */ - static final __FontFlags[] FLAGS; - - // load the flags of the known fonts - static { - ArrayList<__FontFlags> al; - String s; - - al = new ArrayList<>(); - try (final InputStream is = // - FontProperties.class.getResourceAsStream("knownFonts.txt")) { //$NON-NLS-1$ - try (final InputStreamReader isr = new InputStreamReader(is)) { - try (final BufferedReader br = new BufferedReader(isr)) { - while ((s = br.readLine()) != null) { - s = TextUtils.normalize(s); - if ((s != null) && (s.charAt(0) != '#')) { - al.add(new __FontFlags(s)); - } - } - } - } - } catch (final Throwable ioe) { - ErrorUtils.logError(Configuration.getGlobalLogger(),// - "Error when reading list of known fonts.", //$NON-NLS-1$ - ioe, true, RethrowMode.AS_RUNTIME_EXCEPTION); - } - - FLAGS = al.toArray(new __FontFlags[al.size()]); - Arrays.sort(__FontFlags.FLAGS); - } - - /** the font name */ - final String m_name; - - /** - * create - * - * @param data - * the data string - * @param idx - * the index - */ - private __FontFlags(final String data, final int idx) { - super(FontProperties._flags(data, idx)); - this.m_name = TextUtils.prepare(data.substring(idx + 1)) - .toLowerCase(); - } - - /** - * create - * - * @param data - * the data string - */ - __FontFlags(final String data) { - this(data, data.indexOf(' ')); - } - - /** {@inheritDoc} */ - @Override - public final int compareTo(final __FontFlags o) { - String a, b; - int r; - - if (this == o) { - return 0; - } - if (o == null) { - return (-1); - } - a = this.m_name; - b = o.m_name; - r = Integer.compare(b.length(), a.length()); - if (r != 0) { - return r; - } - return a.compareTo(b); - } - - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/pair.info deleted file mode 100755 index fb947c1..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75421/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75421 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/graphics/FontProperties.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/graphics/FontProperties.java -StartLineNum:504 -EndLineNum:504 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/diff.diff deleted file mode 100755 index 2078fb2..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/_PropertyValueGrouperParser.java b/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/_PropertyValueGrouperParser.java -index c856695a..a8c3c9c2 100644 ---- a/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/_PropertyValueGrouperParser.java -+++ b/src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/_PropertyValueGrouperParser.java -@@ -113 +113 @@ final class _PropertyValueGrouperParser extends -- currentLC = current.toLowerCase(); -+ currentLC = TextUtils.toLowerCase(current); -@@ -168 +168 @@ final class _PropertyValueGrouperParser extends -- switch (current.toLowerCase()) { -+ switch (TextUtils.toLowerCase(current)) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/new/_PropertyValueGrouperParser.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/new/_PropertyValueGrouperParser.java deleted file mode 100755 index a8c3c9c..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/new/_PropertyValueGrouperParser.java +++ /dev/null @@ -1,225 +0,0 @@ -package org.optimizationBenchmarking.experimentation.attributes.clusters.propertyValueGroups; - -import org.optimizationBenchmarking.utils.comparison.EComparison; -import org.optimizationBenchmarking.utils.parsers.AnyNumberParser; -import org.optimizationBenchmarking.utils.parsers.IntParser; -import org.optimizationBenchmarking.utils.parsers.Parser; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.text.tokenizers.WordBasedStringIterator; - -/** - * A parser which can transform a string to a property value grouper. The - * following syntax is supported (where | indicates an - * exclusive or choice of strings): - *
- *
m|? to n|?
- *
Try to find between m to n groups. A - * question mark (?) can be specified instead of either - * m or n and indicates don't care, in - * which case a reasonable default is used. The resulting groups may be - * generated based on any grouping mode.
- *
- * m|? to n|? multiples|powers|any
- *
Try to find a grouping where the ranges are multiples or powers (or - * anything) such that there are m to n groups. A - * question mark (? ) can be specified instead of either - * m or n and indicates don't care, in - * which case a reasonable default is used.
- *
- * multiples|powers of p
- *
The grouping is to be based on powers or multiples of the number - * p. The group number results automatically and cannot be - * specified.
- *
- * multiples|powers|distinct|any
- *
Groupings are to be found which are either multiples, powers, - * correspond to distinct values, or are any of the above. The group number - * is don't care in the multiple, power, or any case and results - * automatically in the distinct case.
- *
- */ -final class _PropertyValueGrouperParser extends - Parser { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** The default value grouper parser */ - public static final _PropertyValueGrouperParser DEFAULT_GROUPER_PARSER// - = new _PropertyValueGrouperParser(); - - /** the don't care string */ - private static final String DONT_CARE = "?";//$NON-NLS-1$ - - /** the constant for the multiples mode */ - private static final String MULTIPLES = "multiples";//$NON-NLS-1$ - /** the constant for the powers mode */ - private static final String POWERS = "powers";//$NON-NLS-1$ - /** the constant for the distinct mode */ - private static final String DISTINCT = "distinct";//$NON-NLS-1$ - /** the constant for the any mode */ - private static final String ANY = "any";//$NON-NLS-1$ - /** the constant for "of" */ - private static final String OF = "of";//$NON-NLS-1$ - /** the constant for "to" */ - private static final String TO = "to";//$NON-NLS-1$ - - /** create the parser */ - private _PropertyValueGrouperParser() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final Class getOutputClass() { - return PropertyValueGrouper.class; - } - - /** {@inheritDoc} */ - @Override - public final PropertyValueGrouper parseString(final String string) - throws Exception { - final String use; - final EGroupingMode defMode; - final int defMinGroups, defMaxGroups; - final Number defParam; - final WordBasedStringIterator iterator; - boolean minMaxMode; // true=min/maxGroups, false=param defined? - EGroupingMode mode; - int minGroups, maxGroups; - String current, currentLC; - Number param; - - use = TextUtils.prepare(string); - if (use == null) { - throw new IllegalArgumentException(((// - "PropertyValueGrouper definition string cannot be null, empty, or just contain white space, but is '" //$NON-NLS-1$ - + string) + '\'') + '.'); - } - - mode = defMode = // - PropertyValueGrouper.DEFAULT_GROUPER.getGroupingMode(); - minGroups = defMinGroups = // - PropertyValueGrouper.DEFAULT_GROUPER.getMinGroups(); - maxGroups = defMaxGroups = // - PropertyValueGrouper.DEFAULT_GROUPER.getMaxGroups(); - param = defParam = // - PropertyValueGrouper.DEFAULT_GROUPER.getGroupingParameter(); - - try { - iterator = new WordBasedStringIterator(use); - - current = iterator.next(); - currentLC = TextUtils.toLowerCase(current); - - define: { - switch (currentLC) { - case MULTIPLES: { - mode = EGroupingMode.MULTIPLES; - minMaxMode = false; - break; - } - case POWERS: { - mode = EGroupingMode.POWERS; - minMaxMode = false; - break; - } - case DISTINCT: { - mode = EGroupingMode.DISTINCT; - break define; - } - case ANY: { - mode = EGroupingMode.ANY; - break define; - } - case DONT_CARE: { - minMaxMode = true; - break; - } - default: { - minGroups = IntParser.INSTANCE.parseInt(current); - minMaxMode = true; - } - } - - if (minMaxMode) { - current = iterator.next(); - if (!(_PropertyValueGrouperParser.TO.equalsIgnoreCase(current))) { - throw new IllegalArgumentException( - (((// - '\'' + _PropertyValueGrouperParser.TO) + "' expected, but '")//$NON-NLS-1$ - + current) - + "' found.");//$NON-NLS-1$ - } - - current = iterator.next(); - if (!(_PropertyValueGrouperParser.DONT_CARE.equals(current))) { - maxGroups = IntParser.INSTANCE.parseInt(current); - } - - if (maxGroups < minGroups) { - throw new IllegalArgumentException(// - "The maximum number of groups cannot be less than the minimum number of groups, but you specified "//$NON-NLS-1$ - + maxGroups + " and " + minGroups + ", respectively.");//$NON-NLS-1$//$NON-NLS-2$ - } - - if (iterator.hasNext()) { - current = iterator.next(); - switch (TextUtils.toLowerCase(current)) { - case MULTIPLES: { - mode = EGroupingMode.MULTIPLES; - break; - } - case POWERS: { - mode = EGroupingMode.POWERS; - break; - } - case ANY: { - mode = EGroupingMode.ANY; - break; - } - default: { - throw new IllegalArgumentException( - (((((((// - "Found '" + current) + //$NON-NLS-1$ - "' but expected ")//$NON-NLS-1$ - + _PropertyValueGrouperParser.MULTIPLES) + ',') + ' ') + _PropertyValueGrouperParser.POWERS)// - + ", or ") + //$NON-NLS-1$ - _PropertyValueGrouperParser.ANY); - } - } - } - } else { - // the grouping parameter (may) follow - - if (iterator.hasNext()) { - - current = iterator.next(); - if (!(_PropertyValueGrouperParser.OF.equalsIgnoreCase(current))) { - throw new IllegalArgumentException( - (((// - '\'' + _PropertyValueGrouperParser.OF) + "' expected, but '")//$NON-NLS-1$ - + current) - + "' found.");//$NON-NLS-1$ - } - - param = AnyNumberParser.INSTANCE.parseObject(iterator.next()); - } - } - } - - if (EComparison.equals(mode, defMode) && // - (minGroups == defMinGroups) && // - (maxGroups == defMaxGroups) && // - EComparison.equals(param, defParam)) { - return PropertyValueGrouper.DEFAULT_GROUPER; - } - - return new PropertyValueGrouper(mode, param, minGroups, maxGroups); - } catch (final Throwable cause) { - throw new IllegalArgumentException((("The string '" + string) + //$NON-NLS-1$ - "' is not a valid grouping definition."),//$NON-NLS-1$ - cause); - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/old/_PropertyValueGrouperParser.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/old/_PropertyValueGrouperParser.java deleted file mode 100755 index c856695..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/old/_PropertyValueGrouperParser.java +++ /dev/null @@ -1,225 +0,0 @@ -package org.optimizationBenchmarking.experimentation.attributes.clusters.propertyValueGroups; - -import org.optimizationBenchmarking.utils.comparison.EComparison; -import org.optimizationBenchmarking.utils.parsers.AnyNumberParser; -import org.optimizationBenchmarking.utils.parsers.IntParser; -import org.optimizationBenchmarking.utils.parsers.Parser; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.text.tokenizers.WordBasedStringIterator; - -/** - * A parser which can transform a string to a property value grouper. The - * following syntax is supported (where | indicates an - * exclusive or choice of strings): - *
- *
m|? to n|?
- *
Try to find between m to n groups. A - * question mark (?) can be specified instead of either - * m or n and indicates don't care, in - * which case a reasonable default is used. The resulting groups may be - * generated based on any grouping mode.
- *
- * m|? to n|? multiples|powers|any
- *
Try to find a grouping where the ranges are multiples or powers (or - * anything) such that there are m to n groups. A - * question mark (? ) can be specified instead of either - * m or n and indicates don't care, in - * which case a reasonable default is used.
- *
- * multiples|powers of p
- *
The grouping is to be based on powers or multiples of the number - * p. The group number results automatically and cannot be - * specified.
- *
- * multiples|powers|distinct|any
- *
Groupings are to be found which are either multiples, powers, - * correspond to distinct values, or are any of the above. The group number - * is don't care in the multiple, power, or any case and results - * automatically in the distinct case.
- *
- */ -final class _PropertyValueGrouperParser extends - Parser { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** The default value grouper parser */ - public static final _PropertyValueGrouperParser DEFAULT_GROUPER_PARSER// - = new _PropertyValueGrouperParser(); - - /** the don't care string */ - private static final String DONT_CARE = "?";//$NON-NLS-1$ - - /** the constant for the multiples mode */ - private static final String MULTIPLES = "multiples";//$NON-NLS-1$ - /** the constant for the powers mode */ - private static final String POWERS = "powers";//$NON-NLS-1$ - /** the constant for the distinct mode */ - private static final String DISTINCT = "distinct";//$NON-NLS-1$ - /** the constant for the any mode */ - private static final String ANY = "any";//$NON-NLS-1$ - /** the constant for "of" */ - private static final String OF = "of";//$NON-NLS-1$ - /** the constant for "to" */ - private static final String TO = "to";//$NON-NLS-1$ - - /** create the parser */ - private _PropertyValueGrouperParser() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final Class getOutputClass() { - return PropertyValueGrouper.class; - } - - /** {@inheritDoc} */ - @Override - public final PropertyValueGrouper parseString(final String string) - throws Exception { - final String use; - final EGroupingMode defMode; - final int defMinGroups, defMaxGroups; - final Number defParam; - final WordBasedStringIterator iterator; - boolean minMaxMode; // true=min/maxGroups, false=param defined? - EGroupingMode mode; - int minGroups, maxGroups; - String current, currentLC; - Number param; - - use = TextUtils.prepare(string); - if (use == null) { - throw new IllegalArgumentException(((// - "PropertyValueGrouper definition string cannot be null, empty, or just contain white space, but is '" //$NON-NLS-1$ - + string) + '\'') + '.'); - } - - mode = defMode = // - PropertyValueGrouper.DEFAULT_GROUPER.getGroupingMode(); - minGroups = defMinGroups = // - PropertyValueGrouper.DEFAULT_GROUPER.getMinGroups(); - maxGroups = defMaxGroups = // - PropertyValueGrouper.DEFAULT_GROUPER.getMaxGroups(); - param = defParam = // - PropertyValueGrouper.DEFAULT_GROUPER.getGroupingParameter(); - - try { - iterator = new WordBasedStringIterator(use); - - current = iterator.next(); - currentLC = current.toLowerCase(); - - define: { - switch (currentLC) { - case MULTIPLES: { - mode = EGroupingMode.MULTIPLES; - minMaxMode = false; - break; - } - case POWERS: { - mode = EGroupingMode.POWERS; - minMaxMode = false; - break; - } - case DISTINCT: { - mode = EGroupingMode.DISTINCT; - break define; - } - case ANY: { - mode = EGroupingMode.ANY; - break define; - } - case DONT_CARE: { - minMaxMode = true; - break; - } - default: { - minGroups = IntParser.INSTANCE.parseInt(current); - minMaxMode = true; - } - } - - if (minMaxMode) { - current = iterator.next(); - if (!(_PropertyValueGrouperParser.TO.equalsIgnoreCase(current))) { - throw new IllegalArgumentException( - (((// - '\'' + _PropertyValueGrouperParser.TO) + "' expected, but '")//$NON-NLS-1$ - + current) - + "' found.");//$NON-NLS-1$ - } - - current = iterator.next(); - if (!(_PropertyValueGrouperParser.DONT_CARE.equals(current))) { - maxGroups = IntParser.INSTANCE.parseInt(current); - } - - if (maxGroups < minGroups) { - throw new IllegalArgumentException(// - "The maximum number of groups cannot be less than the minimum number of groups, but you specified "//$NON-NLS-1$ - + maxGroups + " and " + minGroups + ", respectively.");//$NON-NLS-1$//$NON-NLS-2$ - } - - if (iterator.hasNext()) { - current = iterator.next(); - switch (current.toLowerCase()) { - case MULTIPLES: { - mode = EGroupingMode.MULTIPLES; - break; - } - case POWERS: { - mode = EGroupingMode.POWERS; - break; - } - case ANY: { - mode = EGroupingMode.ANY; - break; - } - default: { - throw new IllegalArgumentException( - (((((((// - "Found '" + current) + //$NON-NLS-1$ - "' but expected ")//$NON-NLS-1$ - + _PropertyValueGrouperParser.MULTIPLES) + ',') + ' ') + _PropertyValueGrouperParser.POWERS)// - + ", or ") + //$NON-NLS-1$ - _PropertyValueGrouperParser.ANY); - } - } - } - } else { - // the grouping parameter (may) follow - - if (iterator.hasNext()) { - - current = iterator.next(); - if (!(_PropertyValueGrouperParser.OF.equalsIgnoreCase(current))) { - throw new IllegalArgumentException( - (((// - '\'' + _PropertyValueGrouperParser.OF) + "' expected, but '")//$NON-NLS-1$ - + current) - + "' found.");//$NON-NLS-1$ - } - - param = AnyNumberParser.INSTANCE.parseObject(iterator.next()); - } - } - } - - if (EComparison.equals(mode, defMode) && // - (minGroups == defMinGroups) && // - (maxGroups == defMaxGroups) && // - EComparison.equals(param, defParam)) { - return PropertyValueGrouper.DEFAULT_GROUPER; - } - - return new PropertyValueGrouper(mode, param, minGroups, maxGroups); - } catch (final Throwable cause) { - throw new IllegalArgumentException((("The string '" + string) + //$NON-NLS-1$ - "' is not a valid grouping definition."),//$NON-NLS-1$ - cause); - } - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/pair.info deleted file mode 100755 index 247ce07..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75422/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75422 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/_PropertyValueGrouperParser.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/experimentation/attributes/clusters/propertyValueGroups/_PropertyValueGrouperParser.java -StartLineNum:113 -EndLineNum:113 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/diff.diff deleted file mode 100755 index eee3efc..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/document/impl/FigureSizeParser.java b/src/main/java/org/optimizationBenchmarking/utils/document/impl/FigureSizeParser.java -index 352d14db..8c77ead3 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/document/impl/FigureSizeParser.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/document/impl/FigureSizeParser.java -@@ -6,0 +7 @@ import org.optimizationBenchmarking.utils.reflection.ReflectionUtils; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -66 +67 @@ public class FigureSizeParser extends Parser { -- name = name.toLowerCase(); -+ name = TextUtils.toLowerCase(name); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/new/FigureSizeParser.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/new/FigureSizeParser.java deleted file mode 100755 index 8c77ead..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/new/FigureSizeParser.java +++ /dev/null @@ -1,134 +0,0 @@ -package org.optimizationBenchmarking.utils.document.impl; - -import org.optimizationBenchmarking.utils.collections.maps.StringMapCI; -import org.optimizationBenchmarking.utils.document.spec.EFigureSize; -import org.optimizationBenchmarking.utils.parsers.Parser; -import org.optimizationBenchmarking.utils.reflection.ReflectionUtils; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - * A parser for instances of - * {@link org.optimizationBenchmarking.utils.document.spec.EFigureSize}. - */ -public class FigureSizeParser extends Parser { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** the figure size parameter */ - public static final String PARAM_FIGURE_SIZE = "figureSize"; //$NON-NLS-1$ - - /** the internal loopkup */ - private static final StringMapCI LOOKUP = FigureSizeParser - .__makeMap(); - - /** the globally shared instance of the figure size parser */ - public static final FigureSizeParser INSTANCE = new FigureSizeParser(); - - /** create the figure size parser */ - private FigureSizeParser() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final Class getOutputClass() { - return EFigureSize.class; - } - - /** {@inheritDoc} */ - @Override - public final EFigureSize parseString(final String string) - throws Exception { - EFigureSize res; - - res = FigureSizeParser.LOOKUP.get(string); - if (res != null) { - return res; - } - - return ReflectionUtils.getInstanceByName(EFigureSize.class, string); - } - - /** - * Make the map for lookups - * - * @return the map - */ - private static final StringMapCI __makeMap() { - final StringMapCI map; - String name, name2; - - map = new StringMapCI<>(); - - for (final EFigureSize size : EFigureSize.INSTANCES) { - name = size.name(); - map.put(name, size); - name = TextUtils.toLowerCase(name); - - for (int i = 0; i < 16; i++) { - name2 = name; - - if ((i & 1) != 0) { - name2 = name2.replace('_', ' '); - map.put(name2.trim(), size); - } - - if ((i & 2) != 0) { - name2 = name2.replace("page ", "")//$NON-NLS-1$//$NON-NLS-2$ - .replace("column ", "col ");//$NON-NLS-1$//$NON-NLS-2$ - map.put(name2.trim(), size); - } - - if ((i & 4) != 0) { - name2 = name2.replace(" by ", "x")//$NON-NLS-1$//$NON-NLS-2$ - .replace("_by_", "x")//$NON-NLS-1$//$NON-NLS-2$ - .replace(" per ", "/")//$NON-NLS-1$//$NON-NLS-2$ - .replace("_per_", "/");//$NON-NLS-1$//$NON-NLS-2$ - map.put(name2.trim(), size); - } - - if ((i & 8) != 0) { - name2 = name2.replace(" by ", "*")//$NON-NLS-1$//$NON-NLS-2$ - .replace("_by_", "*");//$NON-NLS-1$//$NON-NLS-2$ - map.put(name2.trim(), size); - } - } - - name = size.toString(); - map.put(name, size); - } - - map.put("page", EFigureSize.PAGE_FULL);//$NON-NLS-1$ - map.put("column", EFigureSize.COLUMN_FULL); //$NON-NLS-1$ - - return map; - } - - // default, automatic serialization replacement and resolve routines for - // singletons - // - /** - * Write replace: the instance this method is invoked on will be replaced - * with the singleton instance {@link #INSTANCE} for serialization, i.e., - * when the instance is written with - * {@link java.io.ObjectOutputStream#writeObject(Object)}. - * - * @return the replacement instance (always {@link #INSTANCE}) - */ - private final Object writeReplace() { - return FigureSizeParser.INSTANCE; - } - - /** - * Read resolve: The instance this method is invoked on will be replaced - * with the singleton instance {@link #INSTANCE} after serialization, - * i.e., when the instance is read with - * {@link java.io.ObjectInputStream#readObject()}. - * - * @return the replacement instance (always {@link #INSTANCE}) - */ - private final Object readResolve() { - return FigureSizeParser.INSTANCE; - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/old/FigureSizeParser.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/old/FigureSizeParser.java deleted file mode 100755 index 352d14d..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/old/FigureSizeParser.java +++ /dev/null @@ -1,133 +0,0 @@ -package org.optimizationBenchmarking.utils.document.impl; - -import org.optimizationBenchmarking.utils.collections.maps.StringMapCI; -import org.optimizationBenchmarking.utils.document.spec.EFigureSize; -import org.optimizationBenchmarking.utils.parsers.Parser; -import org.optimizationBenchmarking.utils.reflection.ReflectionUtils; - -/** - * A parser for instances of - * {@link org.optimizationBenchmarking.utils.document.spec.EFigureSize}. - */ -public class FigureSizeParser extends Parser { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** the figure size parameter */ - public static final String PARAM_FIGURE_SIZE = "figureSize"; //$NON-NLS-1$ - - /** the internal loopkup */ - private static final StringMapCI LOOKUP = FigureSizeParser - .__makeMap(); - - /** the globally shared instance of the figure size parser */ - public static final FigureSizeParser INSTANCE = new FigureSizeParser(); - - /** create the figure size parser */ - private FigureSizeParser() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final Class getOutputClass() { - return EFigureSize.class; - } - - /** {@inheritDoc} */ - @Override - public final EFigureSize parseString(final String string) - throws Exception { - EFigureSize res; - - res = FigureSizeParser.LOOKUP.get(string); - if (res != null) { - return res; - } - - return ReflectionUtils.getInstanceByName(EFigureSize.class, string); - } - - /** - * Make the map for lookups - * - * @return the map - */ - private static final StringMapCI __makeMap() { - final StringMapCI map; - String name, name2; - - map = new StringMapCI<>(); - - for (final EFigureSize size : EFigureSize.INSTANCES) { - name = size.name(); - map.put(name, size); - name = name.toLowerCase(); - - for (int i = 0; i < 16; i++) { - name2 = name; - - if ((i & 1) != 0) { - name2 = name2.replace('_', ' '); - map.put(name2.trim(), size); - } - - if ((i & 2) != 0) { - name2 = name2.replace("page ", "")//$NON-NLS-1$//$NON-NLS-2$ - .replace("column ", "col ");//$NON-NLS-1$//$NON-NLS-2$ - map.put(name2.trim(), size); - } - - if ((i & 4) != 0) { - name2 = name2.replace(" by ", "x")//$NON-NLS-1$//$NON-NLS-2$ - .replace("_by_", "x")//$NON-NLS-1$//$NON-NLS-2$ - .replace(" per ", "/")//$NON-NLS-1$//$NON-NLS-2$ - .replace("_per_", "/");//$NON-NLS-1$//$NON-NLS-2$ - map.put(name2.trim(), size); - } - - if ((i & 8) != 0) { - name2 = name2.replace(" by ", "*")//$NON-NLS-1$//$NON-NLS-2$ - .replace("_by_", "*");//$NON-NLS-1$//$NON-NLS-2$ - map.put(name2.trim(), size); - } - } - - name = size.toString(); - map.put(name, size); - } - - map.put("page", EFigureSize.PAGE_FULL);//$NON-NLS-1$ - map.put("column", EFigureSize.COLUMN_FULL); //$NON-NLS-1$ - - return map; - } - - // default, automatic serialization replacement and resolve routines for - // singletons - // - /** - * Write replace: the instance this method is invoked on will be replaced - * with the singleton instance {@link #INSTANCE} for serialization, i.e., - * when the instance is written with - * {@link java.io.ObjectOutputStream#writeObject(Object)}. - * - * @return the replacement instance (always {@link #INSTANCE}) - */ - private final Object writeReplace() { - return FigureSizeParser.INSTANCE; - } - - /** - * Read resolve: The instance this method is invoked on will be replaced - * with the singleton instance {@link #INSTANCE} after serialization, - * i.e., when the instance is read with - * {@link java.io.ObjectInputStream#readObject()}. - * - * @return the replacement instance (always {@link #INSTANCE}) - */ - private final Object readResolve() { - return FigureSizeParser.INSTANCE; - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/pair.info deleted file mode 100755 index 82b2798..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75429/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75429 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/document/impl/FigureSizeParser.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/document/impl/FigureSizeParser.java -StartLineNum:66 -EndLineNum:66 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/diff.diff deleted file mode 100755 index 7893dd6..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/experimentation/attributes/functions/FunctionAttribute.java b/src/main/java/org/optimizationBenchmarking/experimentation/attributes/functions/FunctionAttribute.java -index 71b91690..f266988d 100644 ---- a/src/main/java/org/optimizationBenchmarking/experimentation/attributes/functions/FunctionAttribute.java -+++ b/src/main/java/org/optimizationBenchmarking/experimentation/attributes/functions/FunctionAttribute.java -@@ -19,0 +20 @@ import org.optimizationBenchmarking.utils.text.ETextCase; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -190 +191 @@ public abstract class FunctionAttribute
extends -- return this.getClass().getSimpleName().toLowerCase(); -+ return TextUtils.toLowerCase(this.getClass().getSimpleName()); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/new/FunctionAttribute.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/new/FunctionAttribute.java deleted file mode 100755 index f266988..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/new/FunctionAttribute.java +++ /dev/null @@ -1,780 +0,0 @@ -package org.optimizationBenchmarking.experimentation.attributes.functions; - -import org.optimizationBenchmarking.experimentation.data.spec.Attribute; -import org.optimizationBenchmarking.experimentation.data.spec.EAttributeType; -import org.optimizationBenchmarking.experimentation.data.spec.IElementSet; -import org.optimizationBenchmarking.utils.comparison.EComparison; -import org.optimizationBenchmarking.utils.document.impl.SemanticComponentUtils; -import org.optimizationBenchmarking.utils.document.spec.IComplexText; -import org.optimizationBenchmarking.utils.document.spec.IMath; -import org.optimizationBenchmarking.utils.document.spec.ISemanticComponent; -import org.optimizationBenchmarking.utils.document.spec.ISemanticMathComponent; -import org.optimizationBenchmarking.utils.document.spec.IText; -import org.optimizationBenchmarking.utils.hash.HashUtils; -import org.optimizationBenchmarking.utils.io.paths.PathUtils; -import org.optimizationBenchmarking.utils.math.matrix.IMatrix; -import org.optimizationBenchmarking.utils.math.text.AbstractParameterRenderer; -import org.optimizationBenchmarking.utils.math.text.DefaultParameterRenderer; -import org.optimizationBenchmarking.utils.math.text.IParameterRenderer; -import org.optimizationBenchmarking.utils.text.ETextCase; -import org.optimizationBenchmarking.utils.text.TextUtils; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; -import org.optimizationBenchmarking.utils.text.textOutput.MemoryTextOutput; - -/** - * An attribute which computes a function over a given data set. - * - * @param
- * the data type - */ -public abstract class FunctionAttribute
extends - Attribute implements ISemanticComponent { - - /** - * The default parameter for the {@code x}-axis (see - * {@link #getYAxisOutputTransformation()}: This is intended for use in - * conjunction with a - * {@link org.optimizationBenchmarking.utils.config.Configuration}. - */ - public static final String X_AXIS_PARAM = "xAxis"; //$NON-NLS-1$ - - /** - * The default parameter for the {@code y}-axis input transformation (see - * {@link #getYAxisInputTransformation()}): This is intended for use in - * conjunction with a - * {@link org.optimizationBenchmarking.utils.config.Configuration}. - */ - public static final String Y_INPUT_AXIS_PARAM = "yAxis"; //$NON-NLS-1$ - - /** - * The default parameter for the {@code y}-axis result transformation - * (see {@link #getYAxisOutputTransformation()}): This is intended for - * use in conjunction with a - * {@link org.optimizationBenchmarking.utils.config.Configuration}. - */ - public static final String Y_AXIS_OUTPUT_PARAM = "yAxisTransformation"; //$NON-NLS-1$ - - /** the transformation of the {@code x}-axis */ - final DimensionTransformation m_xAxisTransformation; - - /** - * the transformation to be applied to the data of the {@code y}-axis - * before being fed to the actual computation - */ - final DimensionTransformation m_yAxisInputTransformation; - - /** - * the transformation of the result of the function applied to the data - * on the {@code y}-axis - */ - final Transformation m_yAxisOutputTransformation; - - /** - * the - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticMathComponent - * semantic math component} representing the {@code y}-axis - */ - private transient ISemanticMathComponent m_yAxisSemanticComponent; - - /** - * the - * {@link org.optimizationBenchmarking.utils.math.text.IParameterRenderer - * parameter renderer} for the {@code y}-axis function - */ - private transient IParameterRenderer m_yAxisFunctionRenderer; - /** - * the - * {@link org.optimizationBenchmarking.utils.math.text.IParameterRenderer - * parameter renderer} for the {@code y}-axis function in path component - * suggestions - */ - private transient IParameterRenderer m_yAxisPathComponentRenderer; - - /** - * Create the function attribute - * - * @param type - * the attribute type - * @param xAxisTransformation - * the transformation to be applied to the {@code x}-axis - * @param yAxisInputTransformation - * the transformation to be applied to the data of the {@code y} - * -axis before being fed to the actual computation - * @param yAxisOutputTransformation - * the transformation of the result of the function applied to - * the data on the {@code y}-axis. - */ - protected FunctionAttribute(final EAttributeType type, - final DimensionTransformation xAxisTransformation, - final DimensionTransformation yAxisInputTransformation, - final Transformation yAxisOutputTransformation) { - super(type); - - if (xAxisTransformation == null) { - throw new IllegalArgumentException(// - "The transformation to be applied to the x-axis cannot be null when creating an instance of " + //$NON-NLS-1$ - this.getClass().getSimpleName()); - } - - if (yAxisInputTransformation == null) { - throw new IllegalArgumentException(// - "The transformation to be applied to the data of the y-axis before being fed to the actual computation cannot be null when creating an instance of " + //$NON-NLS-1$ - this.getClass().getSimpleName()); - } - - if (yAxisOutputTransformation == null) { - throw new IllegalArgumentException(// - "The transformation of the result of the function applied to the data on the y-axis cannot be null when creating an instance of " + //$NON-NLS-1$ - this.getClass().getSimpleName()); - } - - this.m_xAxisTransformation = xAxisTransformation; - this.m_yAxisInputTransformation = yAxisInputTransformation; - this.m_yAxisOutputTransformation = yAxisOutputTransformation; - } - - /** - * Obtain the transformation to be applied to the {@code x}-axis. - * - * @return the transformation to be applied to the {@code x}-axis - */ - public final DimensionTransformation getXAxisTransformation() { - return this.m_xAxisTransformation; - } - - /** - * Obtain the transformation to be applied to the data of the {@code y} - * -axis before being fed to the actual computation - * - * @return the transformation to be applied to the data of the {@code y} - * -axis before being fed to the actual computation - */ - public final DimensionTransformation getYAxisInputTransformation() { - return this.m_yAxisInputTransformation; - } - - /** - * Obtain the transformation of the result of the function applied to the - * data on the {@code y}-axis. - * - * @return the transformation of the result of the function applied to - * the data on the {@code y}-axis - */ - public final Transformation getYAxisOutputTransformation() { - return this.m_yAxisOutputTransformation; - } - - /** - * Get the - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticMathComponent - * semantic math component} representing the {@code y}-axis - * - * @return the - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticMathComponent - * semantic math component} representing the {@code y}-axis - */ - public final ISemanticMathComponent getYAxisSemanticComponent() { - if (this.m_yAxisSemanticComponent == null) { - this.m_yAxisSemanticComponent = new __FunctionYAxis(); - } - return this.m_yAxisSemanticComponent; - } - - /** - * Obtain the short name of the function to be computed (which is plotted - * along the {@code y}-axis, of course). This might be something like - * {@code "ECDF"}. - * - * @return the name of the function to be computed - */ - protected String getShortName() { - return TextUtils.toLowerCase(this.getClass().getSimpleName()); - } - - /** - * Obtain the name of the function to be computed (which is plotted along - * the {@code y}-axis, of course). This might be something like - * {@code "Empirical Cumulative Distribution Function"}. - * - * @return the name of the function to be computed - */ - protected String getLongName() { - return this.getShortName(); - } - - /** {@inheritDoc} */ - @Override - public ETextCase printShortName(final ITextOutput textOut, - final ETextCase textCase) { - if (textOut instanceof IComplexText) { - try (final IMath math = ((IComplexText) textOut).inlineMath()) { - try (final IText name = math.name()) { - name.append(this.getShortName()); - } - } - } else { - textOut.append(this.getShortName()); - } - return textCase.nextCase(); - } - - /** {@inheritDoc} */ - @Override - public ETextCase printLongName(final ITextOutput textOut, - final ETextCase textCase) { - return textCase.appendWords(this.getLongName(), textOut); - } - - /** {@inheritDoc} */ - @Override - public ETextCase printDescription(final ITextOutput textOut, - final ETextCase textCase) { - return this.__printDescription(textOut, textCase, false); - } - - /** {@inheritDoc} */ - @Override - public String getPathComponentSuggestion() { - return this.yAxisGetPathComponentSuggestion(); - } - - /** {@inheritDoc} */ - @Override - protected int calcHashCode() { - return HashUtils.combineHashes(// - HashUtils.combineHashes(// - HashUtils.hashCode(this.getClass()),// - HashUtils.hashCode(this.m_xAxisTransformation)),// - HashUtils.combineHashes(// - HashUtils.hashCode(this.m_yAxisInputTransformation),// - HashUtils.hashCode(this.m_yAxisOutputTransformation))); - } - - /** - * Check whether the other object is equal to this one. - * - * @param other - * the other object, will be an instance of the same class as - * this object - * @return {@code true} if {@code other} is equal to {@code this}. - */ - protected abstract boolean isEqual(final FunctionAttribute
other); - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override - public final boolean equals(final Object o) { - final FunctionAttribute
other; - if (o == this) { - return true; - } - if (o == null) { - return false; - } - if (EComparison.equals(o.getClass(), this.getClass())) { - other = ((FunctionAttribute
) o); - return ((this.m_xAxisTransformation.equals(// - other.m_xAxisTransformation)) && // - (this.m_yAxisInputTransformation.equals(// - other.m_yAxisInputTransformation)) && // - (this.m_yAxisOutputTransformation.equals(// - other.m_yAxisOutputTransformation)) && // - this.isEqual(other)); - } - return false; - } - - /** - * get the internal function renderer for the {@code y}-axis - * - * @return the internal function renderer for the {@code y}-axis - */ - private final IParameterRenderer __getYAxisFunctionRenderer() { - if (this.m_yAxisFunctionRenderer == null) { - this.m_yAxisFunctionRenderer = new __YAxisFunctionRenderer(); - } - return this.m_yAxisFunctionRenderer; - } - - /** - * get the internal function renderer for the {@code y}-axis for - * {@link #yAxisGetPathComponentSuggestion()} - * - * @return the internal function renderer for the {@code y}-axis for - * {@link #yAxisGetPathComponentSuggestion()} - */ - private final IParameterRenderer __getYAxisPathComponentRenderer() { - if (this.m_yAxisPathComponentRenderer == null) { - this.m_yAxisPathComponentRenderer = new __YAxisPathComponentRenderer(); - } - return this.m_yAxisPathComponentRenderer; - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#printShortName(ITextOutput, ETextCase)} - * for the {@code y}-axis - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @return the next text case - */ - protected ETextCase yAxisPrintShortName(final ITextOutput textOut, - final ETextCase textCase) { - this.yAxisMathRender(textOut, this.__getYAxisFunctionRenderer()); - return textCase.nextCase(); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#printLongName(ITextOutput, ETextCase)} - * for the {@code y}-axis - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @return the next text case - */ - protected ETextCase yAxisPrintLongName(final ITextOutput textOut, - final ETextCase textCase) { - return this.yAxisPrintShortName(textOut, textCase); - } - - /** - * Print the name of this function inside a description. - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @param fromYAxisSemanticComponent - * is this method called from - * {@link #yAxisPrintDescription(ITextOutput, ETextCase)} ( - * {@code true}) or - * {@link #printDescription(ITextOutput, ETextCase)} ( - * {@code false}) - * @return the next text case - */ - protected ETextCase printNameInDescription(final ITextOutput textOut, - final ETextCase textCase, final boolean fromYAxisSemanticComponent) { - return SemanticComponentUtils.printLongAndShortNameIfDifferent(this, - textOut, textCase); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#printDescription(ITextOutput, ETextCase)} - * for the {@code y}-axis - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @param fromYAxisSemanticComponent - * is this method called from - * {@link #yAxisPrintDescription(ITextOutput, ETextCase)} ( - * {@code true}) or - * {@link #printDescription(ITextOutput, ETextCase)} ( - * {@code false}) - * @return the next text case - */ - private final ETextCase __printDescription(final ITextOutput textOut, - final ETextCase textCase, final boolean fromYAxisSemanticComponent) { - ETextCase use; - - use = textCase.appendWord("the", textOut); //$NON-NLS-1$ - textOut.append(' '); - use = this.printNameInDescription(textOut, use, - fromYAxisSemanticComponent); - textOut.append(' '); - - if (!(this.m_yAxisOutputTransformation.isIdentityTransformation())) { - use = use.appendWords("transformed according to", textOut);//$NON-NLS-1$ - textOut.append(' '); - if (textOut instanceof IComplexText) { - try (final IMath math = ((IComplexText) textOut).inlineMath()) { - this.m_yAxisOutputTransformation.m_func.mathRender(math, - this.__getYAxisFunctionRenderer()); - } - } else { - this.m_yAxisOutputTransformation.m_func.mathRender(textOut, - this.__getYAxisFunctionRenderer()); - } - use = use.nextCase(); - textOut.append(' '); - } - - if (this.m_yAxisInputTransformation.isIdentityTransformation()) { - use = use.appendWords("of", textOut);//$NON-NLS-1$ - textOut.append(' '); - use = this.m_yAxisInputTransformation.m_dimension.printShortName( - textOut, use); - } else { - use = use.appendWords("computed based on", textOut);//$NON-NLS-1$ - textOut.append(' '); - if (textOut instanceof IComplexText) { - try (final IMath math = ((IComplexText) textOut).inlineMath()) { - this.m_yAxisInputTransformation.mathRender(math, - DefaultParameterRenderer.INSTANCE); - } - } else { - this.m_yAxisInputTransformation.mathRender(textOut, - DefaultParameterRenderer.INSTANCE); - } - use = use.nextCase(); - } - - textOut.append(' '); - use = use.appendWord("over", textOut);//$NON-NLS-1$ - textOut.append(' '); - use = this.m_xAxisTransformation.printShortName(textOut, use); - textOut.append('.'); - return use.nextAfterSentenceEnd(); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#printDescription(ITextOutput, ETextCase)} - * for the {@code y}-axis - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @return the next text case - */ - protected ETextCase yAxisPrintDescription(final ITextOutput textOut, - final ETextCase textCase) { - return this.__printDescription(textOut, textCase, true); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#getPathComponentSuggestion()} - * for the {@code y}-axis - * - * @return the path component suggestion - */ - protected String yAxisGetPathComponentSuggestion() { - final MemoryTextOutput mto; - mto = new MemoryTextOutput(); - this.m_yAxisOutputTransformation.m_func.mathRender(mto, - this.__getYAxisPathComponentRenderer()); - return PathUtils.sanitizePathComponent(mto.toString()); - } - - /** - * The method {@link java.lang.Object#toString()} for the {@code y}-axis - * - * @return the string - */ - protected String yAxisToString() { - final MemoryTextOutput mto; - mto = new MemoryTextOutput(); - this.yAxisMathRender(mto, this.__getYAxisFunctionRenderer()); - return mto.toString(); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.math.text.IMathRenderable#mathRender(ITextOutput, IParameterRenderer)} - * for the {@code y}-axis - * - * @param out - * the text output device - * @param renderer - * the renderer - */ - protected void yAxisMathRender(final ITextOutput out, - final IParameterRenderer renderer) { - this.m_yAxisOutputTransformation.m_func.mathRender(out, - this.__getYAxisFunctionRenderer()); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.math.text.IMathRenderable#mathRender(IMath, IParameterRenderer)} - * for the {@code y}-axis - * - * @param out - * the math output device - * @param renderer - * the renderer - */ - protected void yAxisMathRender(final IMath out, - final IParameterRenderer renderer) { - this.m_yAxisOutputTransformation.m_func.mathRender(out, - this.__getYAxisFunctionRenderer()); - } - - /** - * Render the name of {@code x}-axis, as used in the first parameter of - * the function computed as {@code y}-axis - * - * @param out - * the output destination - */ - protected void yAxisRenderXAxisAsParameter(final IMath out) { - this.m_xAxisTransformation.getDimension().mathRender(out, - DefaultParameterRenderer.INSTANCE); - } - - /** - * Render the name of {@code x}-axis, as used in the first parameter of - * the function computed as {@code y}-axis - * - * @param out - * the output destination - */ - protected void yAxisRenderXAxisAsParameter(final ITextOutput out) { - out.append(this.m_xAxisTransformation.getDimension().getName()); - } - - /** - * Render the name of {@code y}-axis source, as used in the second - * parameter of the function computed as {@code y}-axis - * - * @param out - * the output destination - */ - protected void yAxisRenderYAxisSourceAsParameter(final IMath out) { - this.m_yAxisInputTransformation.mathRender(out, - DefaultParameterRenderer.INSTANCE); - } - - /** - * Render the name of {@code y}-axis source, as used in the second - * parameter of the function computed as {@code y}-axis - * - * @param out - * the output destination - */ - protected void yAxisRenderYAxisSourceAsParameter(final ITextOutput out) { - this.m_yAxisInputTransformation.mathRender(out, - DefaultParameterRenderer.INSTANCE); - } - - /** The internal class representing the y-axis of a function */ - private final class __FunctionYAxis implements ISemanticMathComponent { - - /** create */ - __FunctionYAxis() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printShortName(final ITextOutput textOut, - final ETextCase textCase) { - return FunctionAttribute.this.yAxisPrintShortName(textOut, textCase); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printLongName(final ITextOutput textOut, - final ETextCase textCase) { - return FunctionAttribute.this.yAxisPrintLongName(textOut, textCase); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printDescription(final ITextOutput textOut, - final ETextCase textCase) { - return FunctionAttribute.this.yAxisPrintDescription(textOut, - textCase); - } - - /** {@inheritDoc} */ - @Override - public final String getPathComponentSuggestion() { - return FunctionAttribute.this.yAxisGetPathComponentSuggestion(); - } - - /** {@inheritDoc} */ - @Override - public final void mathRender(final ITextOutput out, - final IParameterRenderer renderer) { - FunctionAttribute.this.yAxisMathRender(out, renderer); - } - - /** {@inheritDoc} */ - @Override - public final void mathRender(final IMath out, - final IParameterRenderer renderer) { - FunctionAttribute.this.yAxisMathRender(out, renderer); - } - - /** {@inheritDoc} */ - @Override - public final int hashCode() { - return (5434243 ^ FunctionAttribute.this.hashCode()); - } - - /** - * get the owning function attribute - * - * @return the owning function attribute - */ - private final FunctionAttribute __getOwner() { - return FunctionAttribute.this; - } - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override - public final boolean equals(final Object o) { - return ((o == this) || // - ((o instanceof FunctionAttribute.__FunctionYAxis) && // - (FunctionAttribute.this.equals(((__FunctionYAxis) o).__getOwner())))); - } - - /** {@inheritDoc} */ - @Override - public final String toString() { - return FunctionAttribute.this.yAxisToString(); - } - } - - /** The renderer for the {@code y}-axis function */ - private final class __YAxisFunctionRenderer extends - AbstractParameterRenderer { - - /** create */ - __YAxisFunctionRenderer() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final void renderParameter(final int index, - final ITextOutput out) { - if (index == 0) { - out.append(FunctionAttribute.this.getShortName()); - out.append('('); - FunctionAttribute.this.yAxisRenderXAxisAsParameter(out); - out.append(','); - FunctionAttribute.this.yAxisRenderYAxisSourceAsParameter(out); - out.append(')'); - } else { - AbstractParameterRenderer.throwInvalidParameterIndex(index, 0); - } - } - - /** {@inheritDoc} */ - @Override - public final void renderParameter(final int index, final IMath out) { - - if (index == 0) { - try (final IMath function = out.nAryFunction( - FunctionAttribute.this.getShortName(), 2, 2)) { - FunctionAttribute.this.yAxisRenderXAxisAsParameter(function); - FunctionAttribute.this - .yAxisRenderYAxisSourceAsParameter(function); - } - } else { - AbstractParameterRenderer.throwInvalidParameterIndex(index, 0); - } - } - - /** {@inheritDoc} */ - @Override - public final int hashCode() { - return (9739559 ^ FunctionAttribute.this.hashCode()); - } - - /** - * get the owning function attribute - * - * @return the owning function attribute - */ - private final FunctionAttribute __getOwner() { - return FunctionAttribute.this; - } - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override - public final boolean equals(final Object o) { - return ((o == this) || // - ((o instanceof FunctionAttribute.__YAxisFunctionRenderer) && // - (FunctionAttribute.this.equals(((__YAxisFunctionRenderer) o) - .__getOwner())))); - } - } - - /** - * The renderer for the {@code y}-axis function for making the path - * component - */ - private final class __YAxisPathComponentRenderer extends - AbstractParameterRenderer { - - /** create */ - __YAxisPathComponentRenderer() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final void renderParameter(final int index, - final ITextOutput out) { - if (index == 0) { - out.append(FunctionAttribute.this.getShortName()); - out.append('('); - FunctionAttribute.this.m_xAxisTransformation.mathRender(out, - DefaultParameterRenderer.INSTANCE); - out.append(','); - FunctionAttribute.this.yAxisRenderYAxisSourceAsParameter(out); - out.append(')'); - } else { - AbstractParameterRenderer.throwInvalidParameterIndex(index, 0); - } - } - - /** {@inheritDoc} */ - @Override - public final void renderParameter(final int index, final IMath out) { - - if (index == 0) { - try (final IMath function = out.nAryFunction( - FunctionAttribute.this.getShortName(), 2, 2)) { - FunctionAttribute.this.m_xAxisTransformation.mathRender(out, - DefaultParameterRenderer.INSTANCE); - FunctionAttribute.this - .yAxisRenderYAxisSourceAsParameter(function); - } - } else { - AbstractParameterRenderer.throwInvalidParameterIndex(index, 0); - } - } - - /** {@inheritDoc} */ - @Override - public final int hashCode() { - return (7764707 ^ FunctionAttribute.this.hashCode()); - } - - /** - * get the owning function attribute - * - * @return the owning function attribute - */ - private final FunctionAttribute __getOwner() { - return FunctionAttribute.this; - } - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override - public final boolean equals(final Object o) { - return ((o == this) || // - ((o instanceof FunctionAttribute.__YAxisPathComponentRenderer) && // - (FunctionAttribute.this.equals(((__YAxisPathComponentRenderer) o) - .__getOwner())))); - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/old/FunctionAttribute.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/old/FunctionAttribute.java deleted file mode 100755 index 71b9169..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/old/FunctionAttribute.java +++ /dev/null @@ -1,779 +0,0 @@ -package org.optimizationBenchmarking.experimentation.attributes.functions; - -import org.optimizationBenchmarking.experimentation.data.spec.Attribute; -import org.optimizationBenchmarking.experimentation.data.spec.EAttributeType; -import org.optimizationBenchmarking.experimentation.data.spec.IElementSet; -import org.optimizationBenchmarking.utils.comparison.EComparison; -import org.optimizationBenchmarking.utils.document.impl.SemanticComponentUtils; -import org.optimizationBenchmarking.utils.document.spec.IComplexText; -import org.optimizationBenchmarking.utils.document.spec.IMath; -import org.optimizationBenchmarking.utils.document.spec.ISemanticComponent; -import org.optimizationBenchmarking.utils.document.spec.ISemanticMathComponent; -import org.optimizationBenchmarking.utils.document.spec.IText; -import org.optimizationBenchmarking.utils.hash.HashUtils; -import org.optimizationBenchmarking.utils.io.paths.PathUtils; -import org.optimizationBenchmarking.utils.math.matrix.IMatrix; -import org.optimizationBenchmarking.utils.math.text.AbstractParameterRenderer; -import org.optimizationBenchmarking.utils.math.text.DefaultParameterRenderer; -import org.optimizationBenchmarking.utils.math.text.IParameterRenderer; -import org.optimizationBenchmarking.utils.text.ETextCase; -import org.optimizationBenchmarking.utils.text.textOutput.ITextOutput; -import org.optimizationBenchmarking.utils.text.textOutput.MemoryTextOutput; - -/** - * An attribute which computes a function over a given data set. - * - * @param
- * the data type - */ -public abstract class FunctionAttribute
extends - Attribute implements ISemanticComponent { - - /** - * The default parameter for the {@code x}-axis (see - * {@link #getYAxisOutputTransformation()}: This is intended for use in - * conjunction with a - * {@link org.optimizationBenchmarking.utils.config.Configuration}. - */ - public static final String X_AXIS_PARAM = "xAxis"; //$NON-NLS-1$ - - /** - * The default parameter for the {@code y}-axis input transformation (see - * {@link #getYAxisInputTransformation()}): This is intended for use in - * conjunction with a - * {@link org.optimizationBenchmarking.utils.config.Configuration}. - */ - public static final String Y_INPUT_AXIS_PARAM = "yAxis"; //$NON-NLS-1$ - - /** - * The default parameter for the {@code y}-axis result transformation - * (see {@link #getYAxisOutputTransformation()}): This is intended for - * use in conjunction with a - * {@link org.optimizationBenchmarking.utils.config.Configuration}. - */ - public static final String Y_AXIS_OUTPUT_PARAM = "yAxisTransformation"; //$NON-NLS-1$ - - /** the transformation of the {@code x}-axis */ - final DimensionTransformation m_xAxisTransformation; - - /** - * the transformation to be applied to the data of the {@code y}-axis - * before being fed to the actual computation - */ - final DimensionTransformation m_yAxisInputTransformation; - - /** - * the transformation of the result of the function applied to the data - * on the {@code y}-axis - */ - final Transformation m_yAxisOutputTransformation; - - /** - * the - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticMathComponent - * semantic math component} representing the {@code y}-axis - */ - private transient ISemanticMathComponent m_yAxisSemanticComponent; - - /** - * the - * {@link org.optimizationBenchmarking.utils.math.text.IParameterRenderer - * parameter renderer} for the {@code y}-axis function - */ - private transient IParameterRenderer m_yAxisFunctionRenderer; - /** - * the - * {@link org.optimizationBenchmarking.utils.math.text.IParameterRenderer - * parameter renderer} for the {@code y}-axis function in path component - * suggestions - */ - private transient IParameterRenderer m_yAxisPathComponentRenderer; - - /** - * Create the function attribute - * - * @param type - * the attribute type - * @param xAxisTransformation - * the transformation to be applied to the {@code x}-axis - * @param yAxisInputTransformation - * the transformation to be applied to the data of the {@code y} - * -axis before being fed to the actual computation - * @param yAxisOutputTransformation - * the transformation of the result of the function applied to - * the data on the {@code y}-axis. - */ - protected FunctionAttribute(final EAttributeType type, - final DimensionTransformation xAxisTransformation, - final DimensionTransformation yAxisInputTransformation, - final Transformation yAxisOutputTransformation) { - super(type); - - if (xAxisTransformation == null) { - throw new IllegalArgumentException(// - "The transformation to be applied to the x-axis cannot be null when creating an instance of " + //$NON-NLS-1$ - this.getClass().getSimpleName()); - } - - if (yAxisInputTransformation == null) { - throw new IllegalArgumentException(// - "The transformation to be applied to the data of the y-axis before being fed to the actual computation cannot be null when creating an instance of " + //$NON-NLS-1$ - this.getClass().getSimpleName()); - } - - if (yAxisOutputTransformation == null) { - throw new IllegalArgumentException(// - "The transformation of the result of the function applied to the data on the y-axis cannot be null when creating an instance of " + //$NON-NLS-1$ - this.getClass().getSimpleName()); - } - - this.m_xAxisTransformation = xAxisTransformation; - this.m_yAxisInputTransformation = yAxisInputTransformation; - this.m_yAxisOutputTransformation = yAxisOutputTransformation; - } - - /** - * Obtain the transformation to be applied to the {@code x}-axis. - * - * @return the transformation to be applied to the {@code x}-axis - */ - public final DimensionTransformation getXAxisTransformation() { - return this.m_xAxisTransformation; - } - - /** - * Obtain the transformation to be applied to the data of the {@code y} - * -axis before being fed to the actual computation - * - * @return the transformation to be applied to the data of the {@code y} - * -axis before being fed to the actual computation - */ - public final DimensionTransformation getYAxisInputTransformation() { - return this.m_yAxisInputTransformation; - } - - /** - * Obtain the transformation of the result of the function applied to the - * data on the {@code y}-axis. - * - * @return the transformation of the result of the function applied to - * the data on the {@code y}-axis - */ - public final Transformation getYAxisOutputTransformation() { - return this.m_yAxisOutputTransformation; - } - - /** - * Get the - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticMathComponent - * semantic math component} representing the {@code y}-axis - * - * @return the - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticMathComponent - * semantic math component} representing the {@code y}-axis - */ - public final ISemanticMathComponent getYAxisSemanticComponent() { - if (this.m_yAxisSemanticComponent == null) { - this.m_yAxisSemanticComponent = new __FunctionYAxis(); - } - return this.m_yAxisSemanticComponent; - } - - /** - * Obtain the short name of the function to be computed (which is plotted - * along the {@code y}-axis, of course). This might be something like - * {@code "ECDF"}. - * - * @return the name of the function to be computed - */ - protected String getShortName() { - return this.getClass().getSimpleName().toLowerCase(); - } - - /** - * Obtain the name of the function to be computed (which is plotted along - * the {@code y}-axis, of course). This might be something like - * {@code "Empirical Cumulative Distribution Function"}. - * - * @return the name of the function to be computed - */ - protected String getLongName() { - return this.getShortName(); - } - - /** {@inheritDoc} */ - @Override - public ETextCase printShortName(final ITextOutput textOut, - final ETextCase textCase) { - if (textOut instanceof IComplexText) { - try (final IMath math = ((IComplexText) textOut).inlineMath()) { - try (final IText name = math.name()) { - name.append(this.getShortName()); - } - } - } else { - textOut.append(this.getShortName()); - } - return textCase.nextCase(); - } - - /** {@inheritDoc} */ - @Override - public ETextCase printLongName(final ITextOutput textOut, - final ETextCase textCase) { - return textCase.appendWords(this.getLongName(), textOut); - } - - /** {@inheritDoc} */ - @Override - public ETextCase printDescription(final ITextOutput textOut, - final ETextCase textCase) { - return this.__printDescription(textOut, textCase, false); - } - - /** {@inheritDoc} */ - @Override - public String getPathComponentSuggestion() { - return this.yAxisGetPathComponentSuggestion(); - } - - /** {@inheritDoc} */ - @Override - protected int calcHashCode() { - return HashUtils.combineHashes(// - HashUtils.combineHashes(// - HashUtils.hashCode(this.getClass()),// - HashUtils.hashCode(this.m_xAxisTransformation)),// - HashUtils.combineHashes(// - HashUtils.hashCode(this.m_yAxisInputTransformation),// - HashUtils.hashCode(this.m_yAxisOutputTransformation))); - } - - /** - * Check whether the other object is equal to this one. - * - * @param other - * the other object, will be an instance of the same class as - * this object - * @return {@code true} if {@code other} is equal to {@code this}. - */ - protected abstract boolean isEqual(final FunctionAttribute
other); - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override - public final boolean equals(final Object o) { - final FunctionAttribute
other; - if (o == this) { - return true; - } - if (o == null) { - return false; - } - if (EComparison.equals(o.getClass(), this.getClass())) { - other = ((FunctionAttribute
) o); - return ((this.m_xAxisTransformation.equals(// - other.m_xAxisTransformation)) && // - (this.m_yAxisInputTransformation.equals(// - other.m_yAxisInputTransformation)) && // - (this.m_yAxisOutputTransformation.equals(// - other.m_yAxisOutputTransformation)) && // - this.isEqual(other)); - } - return false; - } - - /** - * get the internal function renderer for the {@code y}-axis - * - * @return the internal function renderer for the {@code y}-axis - */ - private final IParameterRenderer __getYAxisFunctionRenderer() { - if (this.m_yAxisFunctionRenderer == null) { - this.m_yAxisFunctionRenderer = new __YAxisFunctionRenderer(); - } - return this.m_yAxisFunctionRenderer; - } - - /** - * get the internal function renderer for the {@code y}-axis for - * {@link #yAxisGetPathComponentSuggestion()} - * - * @return the internal function renderer for the {@code y}-axis for - * {@link #yAxisGetPathComponentSuggestion()} - */ - private final IParameterRenderer __getYAxisPathComponentRenderer() { - if (this.m_yAxisPathComponentRenderer == null) { - this.m_yAxisPathComponentRenderer = new __YAxisPathComponentRenderer(); - } - return this.m_yAxisPathComponentRenderer; - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#printShortName(ITextOutput, ETextCase)} - * for the {@code y}-axis - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @return the next text case - */ - protected ETextCase yAxisPrintShortName(final ITextOutput textOut, - final ETextCase textCase) { - this.yAxisMathRender(textOut, this.__getYAxisFunctionRenderer()); - return textCase.nextCase(); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#printLongName(ITextOutput, ETextCase)} - * for the {@code y}-axis - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @return the next text case - */ - protected ETextCase yAxisPrintLongName(final ITextOutput textOut, - final ETextCase textCase) { - return this.yAxisPrintShortName(textOut, textCase); - } - - /** - * Print the name of this function inside a description. - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @param fromYAxisSemanticComponent - * is this method called from - * {@link #yAxisPrintDescription(ITextOutput, ETextCase)} ( - * {@code true}) or - * {@link #printDescription(ITextOutput, ETextCase)} ( - * {@code false}) - * @return the next text case - */ - protected ETextCase printNameInDescription(final ITextOutput textOut, - final ETextCase textCase, final boolean fromYAxisSemanticComponent) { - return SemanticComponentUtils.printLongAndShortNameIfDifferent(this, - textOut, textCase); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#printDescription(ITextOutput, ETextCase)} - * for the {@code y}-axis - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @param fromYAxisSemanticComponent - * is this method called from - * {@link #yAxisPrintDescription(ITextOutput, ETextCase)} ( - * {@code true}) or - * {@link #printDescription(ITextOutput, ETextCase)} ( - * {@code false}) - * @return the next text case - */ - private final ETextCase __printDescription(final ITextOutput textOut, - final ETextCase textCase, final boolean fromYAxisSemanticComponent) { - ETextCase use; - - use = textCase.appendWord("the", textOut); //$NON-NLS-1$ - textOut.append(' '); - use = this.printNameInDescription(textOut, use, - fromYAxisSemanticComponent); - textOut.append(' '); - - if (!(this.m_yAxisOutputTransformation.isIdentityTransformation())) { - use = use.appendWords("transformed according to", textOut);//$NON-NLS-1$ - textOut.append(' '); - if (textOut instanceof IComplexText) { - try (final IMath math = ((IComplexText) textOut).inlineMath()) { - this.m_yAxisOutputTransformation.m_func.mathRender(math, - this.__getYAxisFunctionRenderer()); - } - } else { - this.m_yAxisOutputTransformation.m_func.mathRender(textOut, - this.__getYAxisFunctionRenderer()); - } - use = use.nextCase(); - textOut.append(' '); - } - - if (this.m_yAxisInputTransformation.isIdentityTransformation()) { - use = use.appendWords("of", textOut);//$NON-NLS-1$ - textOut.append(' '); - use = this.m_yAxisInputTransformation.m_dimension.printShortName( - textOut, use); - } else { - use = use.appendWords("computed based on", textOut);//$NON-NLS-1$ - textOut.append(' '); - if (textOut instanceof IComplexText) { - try (final IMath math = ((IComplexText) textOut).inlineMath()) { - this.m_yAxisInputTransformation.mathRender(math, - DefaultParameterRenderer.INSTANCE); - } - } else { - this.m_yAxisInputTransformation.mathRender(textOut, - DefaultParameterRenderer.INSTANCE); - } - use = use.nextCase(); - } - - textOut.append(' '); - use = use.appendWord("over", textOut);//$NON-NLS-1$ - textOut.append(' '); - use = this.m_xAxisTransformation.printShortName(textOut, use); - textOut.append('.'); - return use.nextAfterSentenceEnd(); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#printDescription(ITextOutput, ETextCase)} - * for the {@code y}-axis - * - * @param textOut - * the text output device - * @param textCase - * the text case - * @return the next text case - */ - protected ETextCase yAxisPrintDescription(final ITextOutput textOut, - final ETextCase textCase) { - return this.__printDescription(textOut, textCase, true); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.document.spec.ISemanticComponent#getPathComponentSuggestion()} - * for the {@code y}-axis - * - * @return the path component suggestion - */ - protected String yAxisGetPathComponentSuggestion() { - final MemoryTextOutput mto; - mto = new MemoryTextOutput(); - this.m_yAxisOutputTransformation.m_func.mathRender(mto, - this.__getYAxisPathComponentRenderer()); - return PathUtils.sanitizePathComponent(mto.toString()); - } - - /** - * The method {@link java.lang.Object#toString()} for the {@code y}-axis - * - * @return the string - */ - protected String yAxisToString() { - final MemoryTextOutput mto; - mto = new MemoryTextOutput(); - this.yAxisMathRender(mto, this.__getYAxisFunctionRenderer()); - return mto.toString(); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.math.text.IMathRenderable#mathRender(ITextOutput, IParameterRenderer)} - * for the {@code y}-axis - * - * @param out - * the text output device - * @param renderer - * the renderer - */ - protected void yAxisMathRender(final ITextOutput out, - final IParameterRenderer renderer) { - this.m_yAxisOutputTransformation.m_func.mathRender(out, - this.__getYAxisFunctionRenderer()); - } - - /** - * The method - * {@link org.optimizationBenchmarking.utils.math.text.IMathRenderable#mathRender(IMath, IParameterRenderer)} - * for the {@code y}-axis - * - * @param out - * the math output device - * @param renderer - * the renderer - */ - protected void yAxisMathRender(final IMath out, - final IParameterRenderer renderer) { - this.m_yAxisOutputTransformation.m_func.mathRender(out, - this.__getYAxisFunctionRenderer()); - } - - /** - * Render the name of {@code x}-axis, as used in the first parameter of - * the function computed as {@code y}-axis - * - * @param out - * the output destination - */ - protected void yAxisRenderXAxisAsParameter(final IMath out) { - this.m_xAxisTransformation.getDimension().mathRender(out, - DefaultParameterRenderer.INSTANCE); - } - - /** - * Render the name of {@code x}-axis, as used in the first parameter of - * the function computed as {@code y}-axis - * - * @param out - * the output destination - */ - protected void yAxisRenderXAxisAsParameter(final ITextOutput out) { - out.append(this.m_xAxisTransformation.getDimension().getName()); - } - - /** - * Render the name of {@code y}-axis source, as used in the second - * parameter of the function computed as {@code y}-axis - * - * @param out - * the output destination - */ - protected void yAxisRenderYAxisSourceAsParameter(final IMath out) { - this.m_yAxisInputTransformation.mathRender(out, - DefaultParameterRenderer.INSTANCE); - } - - /** - * Render the name of {@code y}-axis source, as used in the second - * parameter of the function computed as {@code y}-axis - * - * @param out - * the output destination - */ - protected void yAxisRenderYAxisSourceAsParameter(final ITextOutput out) { - this.m_yAxisInputTransformation.mathRender(out, - DefaultParameterRenderer.INSTANCE); - } - - /** The internal class representing the y-axis of a function */ - private final class __FunctionYAxis implements ISemanticMathComponent { - - /** create */ - __FunctionYAxis() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printShortName(final ITextOutput textOut, - final ETextCase textCase) { - return FunctionAttribute.this.yAxisPrintShortName(textOut, textCase); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printLongName(final ITextOutput textOut, - final ETextCase textCase) { - return FunctionAttribute.this.yAxisPrintLongName(textOut, textCase); - } - - /** {@inheritDoc} */ - @Override - public final ETextCase printDescription(final ITextOutput textOut, - final ETextCase textCase) { - return FunctionAttribute.this.yAxisPrintDescription(textOut, - textCase); - } - - /** {@inheritDoc} */ - @Override - public final String getPathComponentSuggestion() { - return FunctionAttribute.this.yAxisGetPathComponentSuggestion(); - } - - /** {@inheritDoc} */ - @Override - public final void mathRender(final ITextOutput out, - final IParameterRenderer renderer) { - FunctionAttribute.this.yAxisMathRender(out, renderer); - } - - /** {@inheritDoc} */ - @Override - public final void mathRender(final IMath out, - final IParameterRenderer renderer) { - FunctionAttribute.this.yAxisMathRender(out, renderer); - } - - /** {@inheritDoc} */ - @Override - public final int hashCode() { - return (5434243 ^ FunctionAttribute.this.hashCode()); - } - - /** - * get the owning function attribute - * - * @return the owning function attribute - */ - private final FunctionAttribute __getOwner() { - return FunctionAttribute.this; - } - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override - public final boolean equals(final Object o) { - return ((o == this) || // - ((o instanceof FunctionAttribute.__FunctionYAxis) && // - (FunctionAttribute.this.equals(((__FunctionYAxis) o).__getOwner())))); - } - - /** {@inheritDoc} */ - @Override - public final String toString() { - return FunctionAttribute.this.yAxisToString(); - } - } - - /** The renderer for the {@code y}-axis function */ - private final class __YAxisFunctionRenderer extends - AbstractParameterRenderer { - - /** create */ - __YAxisFunctionRenderer() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final void renderParameter(final int index, - final ITextOutput out) { - if (index == 0) { - out.append(FunctionAttribute.this.getShortName()); - out.append('('); - FunctionAttribute.this.yAxisRenderXAxisAsParameter(out); - out.append(','); - FunctionAttribute.this.yAxisRenderYAxisSourceAsParameter(out); - out.append(')'); - } else { - AbstractParameterRenderer.throwInvalidParameterIndex(index, 0); - } - } - - /** {@inheritDoc} */ - @Override - public final void renderParameter(final int index, final IMath out) { - - if (index == 0) { - try (final IMath function = out.nAryFunction( - FunctionAttribute.this.getShortName(), 2, 2)) { - FunctionAttribute.this.yAxisRenderXAxisAsParameter(function); - FunctionAttribute.this - .yAxisRenderYAxisSourceAsParameter(function); - } - } else { - AbstractParameterRenderer.throwInvalidParameterIndex(index, 0); - } - } - - /** {@inheritDoc} */ - @Override - public final int hashCode() { - return (9739559 ^ FunctionAttribute.this.hashCode()); - } - - /** - * get the owning function attribute - * - * @return the owning function attribute - */ - private final FunctionAttribute __getOwner() { - return FunctionAttribute.this; - } - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override - public final boolean equals(final Object o) { - return ((o == this) || // - ((o instanceof FunctionAttribute.__YAxisFunctionRenderer) && // - (FunctionAttribute.this.equals(((__YAxisFunctionRenderer) o) - .__getOwner())))); - } - } - - /** - * The renderer for the {@code y}-axis function for making the path - * component - */ - private final class __YAxisPathComponentRenderer extends - AbstractParameterRenderer { - - /** create */ - __YAxisPathComponentRenderer() { - super(); - } - - /** {@inheritDoc} */ - @Override - public final void renderParameter(final int index, - final ITextOutput out) { - if (index == 0) { - out.append(FunctionAttribute.this.getShortName()); - out.append('('); - FunctionAttribute.this.m_xAxisTransformation.mathRender(out, - DefaultParameterRenderer.INSTANCE); - out.append(','); - FunctionAttribute.this.yAxisRenderYAxisSourceAsParameter(out); - out.append(')'); - } else { - AbstractParameterRenderer.throwInvalidParameterIndex(index, 0); - } - } - - /** {@inheritDoc} */ - @Override - public final void renderParameter(final int index, final IMath out) { - - if (index == 0) { - try (final IMath function = out.nAryFunction( - FunctionAttribute.this.getShortName(), 2, 2)) { - FunctionAttribute.this.m_xAxisTransformation.mathRender(out, - DefaultParameterRenderer.INSTANCE); - FunctionAttribute.this - .yAxisRenderYAxisSourceAsParameter(function); - } - } else { - AbstractParameterRenderer.throwInvalidParameterIndex(index, 0); - } - } - - /** {@inheritDoc} */ - @Override - public final int hashCode() { - return (7764707 ^ FunctionAttribute.this.hashCode()); - } - - /** - * get the owning function attribute - * - * @return the owning function attribute - */ - private final FunctionAttribute __getOwner() { - return FunctionAttribute.this; - } - - /** {@inheritDoc} */ - @SuppressWarnings("unchecked") - @Override - public final boolean equals(final Object o) { - return ((o == this) || // - ((o instanceof FunctionAttribute.__YAxisPathComponentRenderer) && // - (FunctionAttribute.this.equals(((__YAxisPathComponentRenderer) o) - .__getOwner())))); - } - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/pair.info deleted file mode 100755 index 4df1978..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75449/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75449 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/experimentation/attributes/functions/FunctionAttribute.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/experimentation/attributes/functions/FunctionAttribute.java -StartLineNum:190 -EndLineNum:190 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/diff.diff deleted file mode 100755 index 946f3fd..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/experimentation/io/impl/csvedi/CSVEDIInput.java b/src/main/java/org/optimizationBenchmarking/experimentation/io/impl/csvedi/CSVEDIInput.java -index dd1cd935..b90d2388 100644 ---- a/src/main/java/org/optimizationBenchmarking/experimentation/io/impl/csvedi/CSVEDIInput.java -+++ b/src/main/java/org/optimizationBenchmarking/experimentation/io/impl/csvedi/CSVEDIInput.java -@@ -164 +164,2 @@ public final class CSVEDIInput extends EDIInputToolBase { -- for (final String str1 : new String[] { base, base.toUpperCase() }) { -+ for (final String str1 : new String[] { base, -+ TextUtils.toUpperCase(base) }) { -@@ -170 +171,2 @@ public final class CSVEDIInput extends EDIInputToolBase { -- for (final String str3 : new String[] { str2, str2.toUpperCase() }) { -+ for (final String str3 : new String[] { str2, -+ TextUtils.toUpperCase(str2) }) { \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/new/CSVEDIInput.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/new/CSVEDIInput.java deleted file mode 100755 index b90d238..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/new/CSVEDIInput.java +++ /dev/null @@ -1,482 +0,0 @@ -package org.optimizationBenchmarking.experimentation.io.impl.csvedi; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.LinkedHashSet; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.optimizationBenchmarking.experimentation.data.impl.ref.ExperimentSetContext; -import org.optimizationBenchmarking.experimentation.data.impl.ref.Instance; -import org.optimizationBenchmarking.experimentation.io.impl.edi.EDI; -import org.optimizationBenchmarking.experimentation.io.impl.edi.EDIInputToolBase; -import org.optimizationBenchmarking.utils.io.encoding.StreamEncoding; -import org.optimizationBenchmarking.utils.io.paths.PathUtils; -import org.optimizationBenchmarking.utils.io.structured.impl.abstr.IOJob; -import org.optimizationBenchmarking.utils.io.xml.XMLFileType; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - *

- * A driver for mixing Comma-Separated Values (CSV) with Experiment Data - * Interchange (EDI) input. EDI is our default, canonical format for - * storing and exchanging - * {@link org.optimizationBenchmarking.experimentation.data experiment data - * structures}. - *

- *

- * This driver looks for the following files: - *

- *
    - *
  1. {@code dimensions.edi} or {@code dimensions.xml} to load the - * definition of the measurement dimensions.
  2. - *
  3. {@code instances.edi} or {@code instances.xml} to load the - * definition of the benchmark instance dimensions.
  4. - *
  5. {@code experiment.edi} or {@code experiment.xml} to load the - * parameter values of an experiment.
  6. - *
- *

- * The overall folder structure this loader can deal with looks as follows: - *

- *
    - *
  1. Root Folder - *
      - *
    1. dimensions.edi or dimensions.xml defining - * the dimensions
    2. - *
    3. instances.edi or instances.xml defining - * the instances
    4. - *
    5. experimentA the folder for the first experiment - *
        - *
      1. experiment.edi or experiment.xml to define - * the parameters of the first experiment
      2. - *
      3. instanceA the folder with the log files for - * "experimentA" on benchmark instance name "instanceA" - *
          - *
        1. run1.csv the first run log file for - * "experimentA" on "instanceA"
        2. - *
        3. run2.txt the second run log file for - * "experimentA" on "instanceA"
        4. - *
        5. - *
        - *
      4. - *
      5. instanceB the folder with the log files for - * "experimentA" on benchmark instance name "instanceB" - *
          - *
        1. run1.csv the first run log file for - * "experimentA" on "instanceB"
        2. - *
        3. run2.txt the second run log file for - * "experimentA" on "instanceB"
        4. - *
        5. - *
        - *
      6. - *
      7. - *
      - *
    6. - *
    7. experimentB the folder for the first experiment - *
        - *
      1. experiment.edi or experiment.xml to define - * the parameters of the second experiment
      2. - *
      3. instanceA the folder with the log files for - * "experimentB" on benchmark instance name "instanceA" - *
          - *
        1. run1.csv the first run log file for - * "experimentB" on "instanceA"
        2. - *
        3. run2.txt the second run log file for - * "experimentB" on "instanceA"
        4. - *
        5. - *
        - *
      4. - *
      5. instanceB the folder with the log files for - * "experimentB" on benchmark instance name "instanceB" - *
          - *
        1. run1.csv the first run log file for - * "experimentB" on "instanceB"
        2. - *
        3. run2.txt the second run log file for - * "experimentB" on "instanceB"
        4. - *
        5. - *
        - *
      6. - *
      7. - *
      - *
    8. - *
    9. - *
    - *
  2. - *
- */ -public final class CSVEDIInput extends EDIInputToolBase { - - /** the base name for dimensions files */ - private static final String DIMENSIONS_BASE = "dimensions"; //$NON-NLS-1$ - - /** the base name for instances files */ - private static final String INSTANCES_BASE = "instances"; //$NON-NLS-1$ - - /** the base name for experiment files */ - private static final String EXPERIMENT_BASE = "experiment"; //$NON-NLS-1$ - - /** the candidates for the dimensions file */ - private static final String[] DIMENSIONS_FILE_CANDIDATES; - /** the candidates for the instances file */ - private static final String[] INSTANCES_FILE_CANDIDATES; - /** the candidates for the experiment file */ - private static final String[] EXPERIMENT_FILE_CANDIDATES; - - static { - final LinkedHashSet candidates; - - candidates = new LinkedHashSet<>(); - CSVEDIInput.__add(CSVEDIInput.DIMENSIONS_BASE, candidates); - DIMENSIONS_FILE_CANDIDATES = candidates.toArray(new String[candidates - .size()]); - - candidates.clear(); - CSVEDIInput.__add(CSVEDIInput.INSTANCES_BASE, candidates); - INSTANCES_FILE_CANDIDATES = candidates.toArray(new String[candidates - .size()]); - - candidates.clear(); - CSVEDIInput.__add(CSVEDIInput.EXPERIMENT_BASE, candidates); - EXPERIMENT_FILE_CANDIDATES = candidates.toArray(new String[candidates - .size()]); - } - - /** the comments */ - private static final String[] COMMENTS = { "#", //$NON-NLS-1$ - "//"//$NON-NLS-1$ - }; - - /** - * add a file to the linked hash set - * - * @param base - * the base file name - * @param dest - * the destination - */ - private static final void __add(final String base, - final LinkedHashSet dest) { - for (final String str1 : new String[] { base, - TextUtils.toUpperCase(base) }) { - for (final String str2 : new String[] { - EDI.EDI_XML.getDefaultSuffix(),// - "edi", //$NON-NLS-1$ - "xml", //$NON-NLS-1$ - XMLFileType.XML.getDefaultSuffix() }) { - for (final String str3 : new String[] { str2, - TextUtils.toUpperCase(str2) }) { - dest.add(str1 + '.' + str3); - } - } - } - } - - /** create */ - CSVEDIInput() { - super(); - } - - /** {@inheritDoc} */ - @Override - protected _CSVEDIContext createToken(final IOJob job, - final ExperimentSetContext data) throws Throwable { - return new _CSVEDIContext(data); - } - - /** {@inheritDoc} */ - @Override - public final String toString() { - return "CSV+EDI Experiment Data Input"; //$NON-NLS-1$ - } - - /** - * Check whether a regular file may be CSV file. Files are considered to - * be CSV files if their suffix is either {@code csv} or {@code txt}. - * - * @param job - * the IO job - * @param data - * the data - * @param path - * the path - * @param attributes - * the file attributes - * @return {@code true} if the file is a CSV file - * @throws Throwable - * if something goes wrong - */ - protected boolean isCSV(final IOJob job, - final ExperimentSetContext data, final Path path, - final BasicFileAttributes attributes) throws Throwable { - final String n; - final char lm3, lm2, lm1, lm0; - int len; - - n = path.toString(); - len = n.length(); - if (len <= 4) { - return false; - } - - lm0 = (n.charAt(--len)); - lm1 = (n.charAt(--len)); - lm2 = (n.charAt(--len)); - lm3 = (n.charAt(--len)); - - return (((lm3 == '.') && (// - (((lm2 == 'c') || (lm2 == 'C'))// - && ((lm1 == 's') || (lm1 == 'S'))// - && ((lm0 == 'v') || (lm0 == 'V'))) || // - (((lm2 == 't') || (lm2 == 'T'))// - && ((lm1 == 'x') || (lm1 == 'X'))// - && ((lm0 == 't') || (lm0 == 'T')))))); - } - - /** {@inheritDoc} */ - @Override - protected boolean isFileInDirectoryLoadable(final IOJob job, - final ExperimentSetContext data, final Path path, - final BasicFileAttributes attributes) throws Throwable { - return (super.isFileInDirectoryLoadable(job, data, path, attributes) || // - this.isCSV(job, data, path, attributes)); - } - - /** {@inheritDoc} */ - @Override - protected void file(final IOJob job, final ExperimentSetContext data, - final Path path, final BasicFileAttributes attributes, - final StreamEncoding encoding) throws Throwable { - final _CSVEDIContext context; - - context = ((_CSVEDIContext) job.getToken()); - if (context._isNew(path, attributes)) { - if (this.isEDI(job, data, path, attributes)) { - super.file(job, data, path, attributes, encoding); - } else { - if (this.isCSV(job, data, path, attributes)) { - this.__csv(context, path, encoding); - } else { - throw new IllegalStateException("Path '" + path //$NON-NLS-1$ - + "' is neither a CSV nor an EDI file."); //$NON-NLS-1$ - } - } - } - } - - /** {@inheritDoc} */ - @Override - protected boolean enterDirectory(final IOJob job, - final ExperimentSetContext data, final Path path, - final BasicFileAttributes attributes) throws Throwable { - final _CSVEDIContext context; - final Logger logger; - Instance inst; - BasicFileAttributes candidateAttrs; - Path candidate; - - logger = job.getLogger(); - - if (super.enterDirectory(job, data, path, attributes)) { - - context = ((_CSVEDIContext) (job.getToken())); - if (context._isNew(path, attributes)) { - - // check for a dimension definition file - if (!(context._hasDimensions())) { - dims: for (final String name : CSVEDIInput.DIMENSIONS_FILE_CANDIDATES) { - candidate = PathUtils.createPathInside(path, name); - if (candidate != null) { - try { - candidateAttrs = Files.readAttributes(candidate, - BasicFileAttributes.class); - } catch (final Throwable t) { - continue dims; - } - - if ((candidateAttrs != null) - && (candidateAttrs.isRegularFile())) { - if (context._isNew(candidate, candidateAttrs)) { - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Now loading dimensions definition " //$NON-NLS-1$ - + candidate); - } - - context._dimensionsFound(); - super.file(job, data, candidate, attributes, - StreamEncoding.TEXT); - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Done loading dimensions definition " //$NON-NLS-1$ - + candidate); - } - - break dims; - } - } - } - } - } - - // check for an instances definition file - if (!(context._hasInstances())) { - insts: for (final String name : CSVEDIInput.INSTANCES_FILE_CANDIDATES) { - candidate = PathUtils.createPathInside(path, name); - if (candidate != null) { - try { - candidateAttrs = Files.readAttributes(candidate, - BasicFileAttributes.class); - } catch (final Throwable t) { - continue insts; - } - - if ((candidateAttrs != null) - && (candidateAttrs.isRegularFile())) { - if (context._isNew(candidate, candidateAttrs)) { - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Now loading instances definition " //$NON-NLS-1$ - + candidate); - } - - context._instancesFound(); - super.file(job, data, candidate, attributes, - StreamEncoding.TEXT); - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Done loading instances definition " //$NON-NLS-1$ - + candidate); - } - - break insts; - } - } - } - } - } - - // check for an experiment description file - exp: for (final String name : CSVEDIInput.EXPERIMENT_FILE_CANDIDATES) { - candidate = PathUtils.createPathInside(path, name); - if (candidate != null) { - try { - candidateAttrs = Files.readAttributes(candidate, - BasicFileAttributes.class); - } catch (final Throwable t) { - continue exp; - } - - if ((candidateAttrs != null) - && (candidateAttrs.isRegularFile())) { - if (context._isNew(candidate, candidateAttrs)) { - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Now loading experiment definition " //$NON-NLS-1$ - + candidate); - } - - super.file(job, data, candidate, attributes, - StreamEncoding.TEXT); - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Done loading experiment definition " //$NON-NLS-1$ - + candidate); - } - - break exp; - } - } - } - } - - // check if we are in an instance run set - if (context._hasInstances()) { - inst = context.instanceGetAll().find(PathUtils.getName(path)); - if (inst != null) { - context.runsBegin(true); - context.runsSetInstance(inst); - } - } - - return true; - } - } - - return false; - } - - /** - * Process a file as CSV file - * - * @param job - * the job - * @param path - * the path - * @param encoding - * the encoding - * @throws Throwable - * if something goes wrong - */ - private final void __csv(final _CSVEDIContext job, final Path path, - final StreamEncoding encoding) throws Throwable { - String line; - int idx; - - try (final InputStream is = PathUtils.openInputStream(path)) { - - try (final Reader ir = (((encoding != null) && (Reader.class - .isAssignableFrom(encoding.getInputClass())))// - ? ((Reader) (encoding.wrapInputStream(is)))// - : new InputStreamReader(is))) { - try (final BufferedReader br = ((ir instanceof BufferedReader)// - ? ((BufferedReader) ir)// - : new BufferedReader(ir))) { - job.runBegin(true); - - while ((line = br.readLine()) != null) { - line = TextUtils.prepare(line); - if (line == null) { - continue; - } - - for (final String comment : CSVEDIInput.COMMENTS) { - idx = line.indexOf(comment); - if (idx >= 0) { - line = line.substring(0, idx); - } - } - - line = TextUtils.prepare(line); - if (line == null) { - continue; - } - - job.runAddDataPoint(line); - } - - job.runEnd(); - } - } - } - } - - /** - * get the instance of the {@link CSVEDIInput} - * - * @return the instance of the {@link CSVEDIInput} - */ - public static final CSVEDIInput getInstance() { - return __EDIInputLoader.INSTANCE; - } - - /** the loader */ - private static final class __EDIInputLoader { - /** create */ - static final CSVEDIInput INSTANCE = new CSVEDIInput(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/old/CSVEDIInput.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/old/CSVEDIInput.java deleted file mode 100755 index dd1cd93..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/old/CSVEDIInput.java +++ /dev/null @@ -1,480 +0,0 @@ -package org.optimizationBenchmarking.experimentation.io.impl.csvedi; - -import java.io.BufferedReader; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.LinkedHashSet; -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.optimizationBenchmarking.experimentation.data.impl.ref.ExperimentSetContext; -import org.optimizationBenchmarking.experimentation.data.impl.ref.Instance; -import org.optimizationBenchmarking.experimentation.io.impl.edi.EDI; -import org.optimizationBenchmarking.experimentation.io.impl.edi.EDIInputToolBase; -import org.optimizationBenchmarking.utils.io.encoding.StreamEncoding; -import org.optimizationBenchmarking.utils.io.paths.PathUtils; -import org.optimizationBenchmarking.utils.io.structured.impl.abstr.IOJob; -import org.optimizationBenchmarking.utils.io.xml.XMLFileType; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - *

- * A driver for mixing Comma-Separated Values (CSV) with Experiment Data - * Interchange (EDI) input. EDI is our default, canonical format for - * storing and exchanging - * {@link org.optimizationBenchmarking.experimentation.data experiment data - * structures}. - *

- *

- * This driver looks for the following files: - *

- *
    - *
  1. {@code dimensions.edi} or {@code dimensions.xml} to load the - * definition of the measurement dimensions.
  2. - *
  3. {@code instances.edi} or {@code instances.xml} to load the - * definition of the benchmark instance dimensions.
  4. - *
  5. {@code experiment.edi} or {@code experiment.xml} to load the - * parameter values of an experiment.
  6. - *
- *

- * The overall folder structure this loader can deal with looks as follows: - *

- *
    - *
  1. Root Folder - *
      - *
    1. dimensions.edi or dimensions.xml defining - * the dimensions
    2. - *
    3. instances.edi or instances.xml defining - * the instances
    4. - *
    5. experimentA the folder for the first experiment - *
        - *
      1. experiment.edi or experiment.xml to define - * the parameters of the first experiment
      2. - *
      3. instanceA the folder with the log files for - * "experimentA" on benchmark instance name "instanceA" - *
          - *
        1. run1.csv the first run log file for - * "experimentA" on "instanceA"
        2. - *
        3. run2.txt the second run log file for - * "experimentA" on "instanceA"
        4. - *
        5. - *
        - *
      4. - *
      5. instanceB the folder with the log files for - * "experimentA" on benchmark instance name "instanceB" - *
          - *
        1. run1.csv the first run log file for - * "experimentA" on "instanceB"
        2. - *
        3. run2.txt the second run log file for - * "experimentA" on "instanceB"
        4. - *
        5. - *
        - *
      6. - *
      7. - *
      - *
    6. - *
    7. experimentB the folder for the first experiment - *
        - *
      1. experiment.edi or experiment.xml to define - * the parameters of the second experiment
      2. - *
      3. instanceA the folder with the log files for - * "experimentB" on benchmark instance name "instanceA" - *
          - *
        1. run1.csv the first run log file for - * "experimentB" on "instanceA"
        2. - *
        3. run2.txt the second run log file for - * "experimentB" on "instanceA"
        4. - *
        5. - *
        - *
      4. - *
      5. instanceB the folder with the log files for - * "experimentB" on benchmark instance name "instanceB" - *
          - *
        1. run1.csv the first run log file for - * "experimentB" on "instanceB"
        2. - *
        3. run2.txt the second run log file for - * "experimentB" on "instanceB"
        4. - *
        5. - *
        - *
      6. - *
      7. - *
      - *
    8. - *
    9. - *
    - *
  2. - *
- */ -public final class CSVEDIInput extends EDIInputToolBase { - - /** the base name for dimensions files */ - private static final String DIMENSIONS_BASE = "dimensions"; //$NON-NLS-1$ - - /** the base name for instances files */ - private static final String INSTANCES_BASE = "instances"; //$NON-NLS-1$ - - /** the base name for experiment files */ - private static final String EXPERIMENT_BASE = "experiment"; //$NON-NLS-1$ - - /** the candidates for the dimensions file */ - private static final String[] DIMENSIONS_FILE_CANDIDATES; - /** the candidates for the instances file */ - private static final String[] INSTANCES_FILE_CANDIDATES; - /** the candidates for the experiment file */ - private static final String[] EXPERIMENT_FILE_CANDIDATES; - - static { - final LinkedHashSet candidates; - - candidates = new LinkedHashSet<>(); - CSVEDIInput.__add(CSVEDIInput.DIMENSIONS_BASE, candidates); - DIMENSIONS_FILE_CANDIDATES = candidates.toArray(new String[candidates - .size()]); - - candidates.clear(); - CSVEDIInput.__add(CSVEDIInput.INSTANCES_BASE, candidates); - INSTANCES_FILE_CANDIDATES = candidates.toArray(new String[candidates - .size()]); - - candidates.clear(); - CSVEDIInput.__add(CSVEDIInput.EXPERIMENT_BASE, candidates); - EXPERIMENT_FILE_CANDIDATES = candidates.toArray(new String[candidates - .size()]); - } - - /** the comments */ - private static final String[] COMMENTS = { "#", //$NON-NLS-1$ - "//"//$NON-NLS-1$ - }; - - /** - * add a file to the linked hash set - * - * @param base - * the base file name - * @param dest - * the destination - */ - private static final void __add(final String base, - final LinkedHashSet dest) { - for (final String str1 : new String[] { base, base.toUpperCase() }) { - for (final String str2 : new String[] { - EDI.EDI_XML.getDefaultSuffix(),// - "edi", //$NON-NLS-1$ - "xml", //$NON-NLS-1$ - XMLFileType.XML.getDefaultSuffix() }) { - for (final String str3 : new String[] { str2, str2.toUpperCase() }) { - dest.add(str1 + '.' + str3); - } - } - } - } - - /** create */ - CSVEDIInput() { - super(); - } - - /** {@inheritDoc} */ - @Override - protected _CSVEDIContext createToken(final IOJob job, - final ExperimentSetContext data) throws Throwable { - return new _CSVEDIContext(data); - } - - /** {@inheritDoc} */ - @Override - public final String toString() { - return "CSV+EDI Experiment Data Input"; //$NON-NLS-1$ - } - - /** - * Check whether a regular file may be CSV file. Files are considered to - * be CSV files if their suffix is either {@code csv} or {@code txt}. - * - * @param job - * the IO job - * @param data - * the data - * @param path - * the path - * @param attributes - * the file attributes - * @return {@code true} if the file is a CSV file - * @throws Throwable - * if something goes wrong - */ - protected boolean isCSV(final IOJob job, - final ExperimentSetContext data, final Path path, - final BasicFileAttributes attributes) throws Throwable { - final String n; - final char lm3, lm2, lm1, lm0; - int len; - - n = path.toString(); - len = n.length(); - if (len <= 4) { - return false; - } - - lm0 = (n.charAt(--len)); - lm1 = (n.charAt(--len)); - lm2 = (n.charAt(--len)); - lm3 = (n.charAt(--len)); - - return (((lm3 == '.') && (// - (((lm2 == 'c') || (lm2 == 'C'))// - && ((lm1 == 's') || (lm1 == 'S'))// - && ((lm0 == 'v') || (lm0 == 'V'))) || // - (((lm2 == 't') || (lm2 == 'T'))// - && ((lm1 == 'x') || (lm1 == 'X'))// - && ((lm0 == 't') || (lm0 == 'T')))))); - } - - /** {@inheritDoc} */ - @Override - protected boolean isFileInDirectoryLoadable(final IOJob job, - final ExperimentSetContext data, final Path path, - final BasicFileAttributes attributes) throws Throwable { - return (super.isFileInDirectoryLoadable(job, data, path, attributes) || // - this.isCSV(job, data, path, attributes)); - } - - /** {@inheritDoc} */ - @Override - protected void file(final IOJob job, final ExperimentSetContext data, - final Path path, final BasicFileAttributes attributes, - final StreamEncoding encoding) throws Throwable { - final _CSVEDIContext context; - - context = ((_CSVEDIContext) job.getToken()); - if (context._isNew(path, attributes)) { - if (this.isEDI(job, data, path, attributes)) { - super.file(job, data, path, attributes, encoding); - } else { - if (this.isCSV(job, data, path, attributes)) { - this.__csv(context, path, encoding); - } else { - throw new IllegalStateException("Path '" + path //$NON-NLS-1$ - + "' is neither a CSV nor an EDI file."); //$NON-NLS-1$ - } - } - } - } - - /** {@inheritDoc} */ - @Override - protected boolean enterDirectory(final IOJob job, - final ExperimentSetContext data, final Path path, - final BasicFileAttributes attributes) throws Throwable { - final _CSVEDIContext context; - final Logger logger; - Instance inst; - BasicFileAttributes candidateAttrs; - Path candidate; - - logger = job.getLogger(); - - if (super.enterDirectory(job, data, path, attributes)) { - - context = ((_CSVEDIContext) (job.getToken())); - if (context._isNew(path, attributes)) { - - // check for a dimension definition file - if (!(context._hasDimensions())) { - dims: for (final String name : CSVEDIInput.DIMENSIONS_FILE_CANDIDATES) { - candidate = PathUtils.createPathInside(path, name); - if (candidate != null) { - try { - candidateAttrs = Files.readAttributes(candidate, - BasicFileAttributes.class); - } catch (final Throwable t) { - continue dims; - } - - if ((candidateAttrs != null) - && (candidateAttrs.isRegularFile())) { - if (context._isNew(candidate, candidateAttrs)) { - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Now loading dimensions definition " //$NON-NLS-1$ - + candidate); - } - - context._dimensionsFound(); - super.file(job, data, candidate, attributes, - StreamEncoding.TEXT); - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Done loading dimensions definition " //$NON-NLS-1$ - + candidate); - } - - break dims; - } - } - } - } - } - - // check for an instances definition file - if (!(context._hasInstances())) { - insts: for (final String name : CSVEDIInput.INSTANCES_FILE_CANDIDATES) { - candidate = PathUtils.createPathInside(path, name); - if (candidate != null) { - try { - candidateAttrs = Files.readAttributes(candidate, - BasicFileAttributes.class); - } catch (final Throwable t) { - continue insts; - } - - if ((candidateAttrs != null) - && (candidateAttrs.isRegularFile())) { - if (context._isNew(candidate, candidateAttrs)) { - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Now loading instances definition " //$NON-NLS-1$ - + candidate); - } - - context._instancesFound(); - super.file(job, data, candidate, attributes, - StreamEncoding.TEXT); - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Done loading instances definition " //$NON-NLS-1$ - + candidate); - } - - break insts; - } - } - } - } - } - - // check for an experiment description file - exp: for (final String name : CSVEDIInput.EXPERIMENT_FILE_CANDIDATES) { - candidate = PathUtils.createPathInside(path, name); - if (candidate != null) { - try { - candidateAttrs = Files.readAttributes(candidate, - BasicFileAttributes.class); - } catch (final Throwable t) { - continue exp; - } - - if ((candidateAttrs != null) - && (candidateAttrs.isRegularFile())) { - if (context._isNew(candidate, candidateAttrs)) { - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Now loading experiment definition " //$NON-NLS-1$ - + candidate); - } - - super.file(job, data, candidate, attributes, - StreamEncoding.TEXT); - - if ((logger != null) && (logger.isLoggable(Level.FINER))) { - logger.finer("Done loading experiment definition " //$NON-NLS-1$ - + candidate); - } - - break exp; - } - } - } - } - - // check if we are in an instance run set - if (context._hasInstances()) { - inst = context.instanceGetAll().find(PathUtils.getName(path)); - if (inst != null) { - context.runsBegin(true); - context.runsSetInstance(inst); - } - } - - return true; - } - } - - return false; - } - - /** - * Process a file as CSV file - * - * @param job - * the job - * @param path - * the path - * @param encoding - * the encoding - * @throws Throwable - * if something goes wrong - */ - private final void __csv(final _CSVEDIContext job, final Path path, - final StreamEncoding encoding) throws Throwable { - String line; - int idx; - - try (final InputStream is = PathUtils.openInputStream(path)) { - - try (final Reader ir = (((encoding != null) && (Reader.class - .isAssignableFrom(encoding.getInputClass())))// - ? ((Reader) (encoding.wrapInputStream(is)))// - : new InputStreamReader(is))) { - try (final BufferedReader br = ((ir instanceof BufferedReader)// - ? ((BufferedReader) ir)// - : new BufferedReader(ir))) { - job.runBegin(true); - - while ((line = br.readLine()) != null) { - line = TextUtils.prepare(line); - if (line == null) { - continue; - } - - for (final String comment : CSVEDIInput.COMMENTS) { - idx = line.indexOf(comment); - if (idx >= 0) { - line = line.substring(0, idx); - } - } - - line = TextUtils.prepare(line); - if (line == null) { - continue; - } - - job.runAddDataPoint(line); - } - - job.runEnd(); - } - } - } - } - - /** - * get the instance of the {@link CSVEDIInput} - * - * @return the instance of the {@link CSVEDIInput} - */ - public static final CSVEDIInput getInstance() { - return __EDIInputLoader.INSTANCE; - } - - /** the loader */ - private static final class __EDIInputLoader { - /** create */ - static final CSVEDIInput INSTANCE = new CSVEDIInput(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/pair.info deleted file mode 100755 index 7792b5a..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75469/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75469 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/experimentation/io/impl/csvedi/CSVEDIInput.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/experimentation/io/impl/csvedi/CSVEDIInput.java -StartLineNum:164 -EndLineNum:164 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/comMsg.txt deleted file mode 100755 index 4412b08..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/comMsg.txt +++ /dev/null @@ -1,10 +0,0 @@ -Consider Locale when doing toUpperCase and toLowerCase - -Today I saw an unrelated topic in the internet -(http://stackoverflow.com/questions/228477) -which made me aware that toLowerCase (and probably toUpperCase) may -behave differently on different systems (systems with different default -locale, i.e., language settings). - -In order to avoid such kind of bugs, I centralize all toLowerCase and -toUpperCase in the TextUtils class and use Locale.ENGLISH by default. \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/diff.diff deleted file mode 100755 index f3bc975..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/org/optimizationBenchmarking/utils/text/predicates/StringInListIgnoreCase.java b/src/main/java/org/optimizationBenchmarking/utils/text/predicates/StringInListIgnoreCase.java -index ca4ddc41..e62cf996 100644 ---- a/src/main/java/org/optimizationBenchmarking/utils/text/predicates/StringInListIgnoreCase.java -+++ b/src/main/java/org/optimizationBenchmarking/utils/text/predicates/StringInListIgnoreCase.java -@@ -6,0 +7 @@ import org.optimizationBenchmarking.utils.EmptyUtils; -+import org.optimizationBenchmarking.utils.text.TextUtils; -@@ -49 +50 @@ public class StringInListIgnoreCase extends StringInList { -- list[i] = list[i].toLowerCase(); -+ list[i] = TextUtils.toLowerCase(list[i]); -@@ -59 +60 @@ public class StringInListIgnoreCase extends StringInList { -- return super.getString(object).toLowerCase(); -+ return TextUtils.toLowerCase(super.getString(object)); \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/new/StringInListIgnoreCase.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/new/StringInListIgnoreCase.java deleted file mode 100755 index e62cf99..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/new/StringInListIgnoreCase.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.optimizationBenchmarking.utils.text.predicates; - -import java.util.Arrays; -import java.util.Collection; - -import org.optimizationBenchmarking.utils.EmptyUtils; -import org.optimizationBenchmarking.utils.text.TextUtils; - -/** - * check whether a string is in a list - * - * @param - * the object type - */ -public class StringInListIgnoreCase extends StringInList { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** - * Create the predicate - * - * @param list - * the string list - */ - public StringInListIgnoreCase(final String... list) { - super(list); - } - - /** - * Create the predicate - * - * @param list - * the string list - */ - public StringInListIgnoreCase(final Collection list) { - super(list); - } - - /** {@inheritDoc} */ - @Override - final String[] _getList(final String[] list) { - int i; - - if ((list == null) || ((i = list.length) <= 0)) { - return EmptyUtils.EMPTY_STRINGS; - } - - for (; (--i) >= 0;) { - list[i] = TextUtils.toLowerCase(list[i]); - } - Arrays.sort(list); - - return list; - } - - /** {@inheritDoc} */ - @Override - protected String getString(final T object) { - return TextUtils.toLowerCase(super.getString(object)); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/old/StringInListIgnoreCase.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/old/StringInListIgnoreCase.java deleted file mode 100755 index ca4ddc4..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/old/StringInListIgnoreCase.java +++ /dev/null @@ -1,61 +0,0 @@ -package org.optimizationBenchmarking.utils.text.predicates; - -import java.util.Arrays; -import java.util.Collection; - -import org.optimizationBenchmarking.utils.EmptyUtils; - -/** - * check whether a string is in a list - * - * @param - * the object type - */ -public class StringInListIgnoreCase extends StringInList { - - /** the serial version uid */ - private static final long serialVersionUID = 1L; - - /** - * Create the predicate - * - * @param list - * the string list - */ - public StringInListIgnoreCase(final String... list) { - super(list); - } - - /** - * Create the predicate - * - * @param list - * the string list - */ - public StringInListIgnoreCase(final Collection list) { - super(list); - } - - /** {@inheritDoc} */ - @Override - final String[] _getList(final String[] list) { - int i; - - if ((list == null) || ((i = list.length) <= 0)) { - return EmptyUtils.EMPTY_STRINGS; - } - - for (; (--i) >= 0;) { - list[i] = list[i].toLowerCase(); - } - Arrays.sort(list); - - return list; - } - - /** {@inheritDoc} */ - @Override - protected String getString(final T object) { - return super.getString(object).toLowerCase(); - } -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/pair.info deleted file mode 100755 index f2efef5..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75525/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75525 -comSha:e39327fb9de4ae258b64fff179a96aa8812223fc -parentComSha:c069f6619b4d9666859109881cdb80cdcc226545 -BuggyFilePath:src/main/java/org/optimizationBenchmarking/utils/text/predicates/StringInListIgnoreCase.java -FixedFilePath:src/main/java/org/optimizationBenchmarking/utils/text/predicates/StringInListIgnoreCase.java -StartLineNum:59 -EndLineNum:59 -repoName:optimizationBenchmarking#optimizationBenchmarking \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/comMsg.txt b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/comMsg.txt deleted file mode 100755 index bab2e8f..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/comMsg.txt +++ /dev/null @@ -1,2 +0,0 @@ -Fixed wrong imported file extension detection. Unit test is part of -less.js 1.3.3 tests, so I did not added special one. Close #113 \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/diff.diff b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/diff.diff deleted file mode 100755 index 4a52464..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/com/github/sommeri/less4j/core/compiler/stages/SimpleImportsSolver.java b/src/main/java/com/github/sommeri/less4j/core/compiler/stages/SimpleImportsSolver.java -index 38dfa5b3..d5eb276d 100644 ---- a/src/main/java/com/github/sommeri/less4j/core/compiler/stages/SimpleImportsSolver.java -+++ b/src/main/java/com/github/sommeri/less4j/core/compiler/stages/SimpleImportsSolver.java -@@ -2,0 +3 @@ package com.github.sommeri.less4j.core.compiler.stages; -+import java.io.File; -@@ -148 +149 @@ public class SimpleImportsSolver { -- if (filename.toLowerCase().contains(".")) -+ if ((new File(filename)).getName().contains(".")) \ No newline at end of file diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/new/SimpleImportsSolver.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/new/SimpleImportsSolver.java deleted file mode 100755 index d5eb276..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/new/SimpleImportsSolver.java +++ /dev/null @@ -1,182 +0,0 @@ -package com.github.sommeri.less4j.core.compiler.stages; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.github.sommeri.less4j.LessSource; -import com.github.sommeri.less4j.LessSource.CannotReadFile; -import com.github.sommeri.less4j.LessSource.FileNotFound; -import com.github.sommeri.less4j.LessSource.StringSourceException; -import com.github.sommeri.less4j.core.ast.ASTCssNode; -import com.github.sommeri.less4j.core.ast.ASTCssNodeType; -import com.github.sommeri.less4j.core.ast.Expression; -import com.github.sommeri.less4j.core.ast.FaultyNode; -import com.github.sommeri.less4j.core.ast.FunctionExpression; -import com.github.sommeri.less4j.core.ast.GeneralBody; -import com.github.sommeri.less4j.core.ast.Import; -import com.github.sommeri.less4j.core.ast.Import.ImportKind; -import com.github.sommeri.less4j.core.ast.Media; -import com.github.sommeri.less4j.core.ast.StyleSheet; -import com.github.sommeri.less4j.core.compiler.expressions.ExpressionEvaluator; -import com.github.sommeri.less4j.core.compiler.expressions.TypesConversionUtils; -import com.github.sommeri.less4j.core.parser.ANTLRParser; -import com.github.sommeri.less4j.core.parser.ASTBuilder; -import com.github.sommeri.less4j.core.parser.HiddenTokenAwareTree; -import com.github.sommeri.less4j.core.problems.ProblemsHandler; -import com.github.sommeri.less4j.platform.Constants; - -public class SimpleImportsSolver { - - private final ProblemsHandler problemsHandler; - private TypesConversionUtils conversionUtils = new TypesConversionUtils(); - private ASTManipulator astManipulator = new ASTManipulator(); - - private Set importedSources = new HashSet(); - - public SimpleImportsSolver(ProblemsHandler problemsHandler) { - this.problemsHandler = problemsHandler; - } - - public void solveImports(StyleSheet node, LessSource source) { - doSolveImports(node, source); - } - - private void doSolveImports(StyleSheet node, LessSource source) { - List childs = new ArrayList(node.getChilds()); - for (ASTCssNode kid : childs) { - if (kid.getType() == ASTCssNodeType.IMPORT) { - importEncountered((Import) kid, source); - } - } - } - - private void importEncountered(Import node, LessSource source) { - String filename = evaluateFilename(node.getUrlExpression()); - if (filename == null) { - problemsHandler.errorWrongImport(node.getUrlExpression()); - return; - } - String urlParams = ""; - int paramsIndx = filename.lastIndexOf("?"); - if (paramsIndx != -1) { - urlParams = filename.substring(paramsIndx); - filename = filename.substring(0, paramsIndx); - } - - if (isCssFile(filename)) - // css file imports should be left as they are - return; - - // add .less suffix if needed - filename = normalizeFileName(filename, urlParams); - LessSource importedSource; - try { - importedSource = source.relativeSource(filename); - } catch (FileNotFound ex) { - problemsHandler.errorImportedFileNotFound(node, filename); - return; - } catch (CannotReadFile e) { - problemsHandler.errorImportedFileCanNotBeRead(node, filename); - return; - } catch (StringSourceException ex) { - // imports are relative to current file and we do not know its location - problemsHandler.warnLessImportNoBaseDirectory(node.getUrlExpression()); - return; - } - - // import once should not import a file that was already imported - if (isImportOnce(node) && alreadyVisited(importedSource)) { - astManipulator.removeFromBody(node); - return; - } - importedSources.add(importedSource); - - String importedContent; - try { - importedContent = importedSource.getContent(); - } catch (FileNotFound e) { - problemsHandler.errorImportedFileNotFound(node, filename); - return; - } catch (CannotReadFile e) { - problemsHandler.errorImportedFileCanNotBeRead(node, filename); - return; - } - - // parse imported file - StyleSheet importedAst = parseContent(node, importedContent, importedSource); - solveImports(importedAst, importedSource); - - // add media queries if needed - if (node.hasMediums()) { - HiddenTokenAwareTree underlyingStructure = node.getUnderlyingStructure(); - Media media = new Media(underlyingStructure); - media.setMediums(node.getMediums()); - media.setBody(new GeneralBody(underlyingStructure, importedAst.getMembers())); - media.configureParentToAllChilds(); - astManipulator.replaceInBody(node, media); - } else { - astManipulator.replaceInBody(node, importedAst.getChilds()); - } - } - - private boolean isImportOnce(Import node) { - return node.getKind() == ImportKind.IMPORT_ONCE; - } - - private boolean alreadyVisited(LessSource importedSource) { - return importedSources.contains(importedSource); - } - - private StyleSheet parseContent(Import importNode, String importedContent, LessSource source) { - ANTLRParser parser = new ANTLRParser(); - ANTLRParser.ParseResult parsedSheet = parser.parseStyleSheet(importedContent, source); - if (parsedSheet.hasErrors()) { - StyleSheet result = new StyleSheet(importNode.getUnderlyingStructure()); - result.addMember(new FaultyNode(importNode)); - problemsHandler.addErrors(parsedSheet.getErrors()); - return result; - } - ASTBuilder astBuilder = new ASTBuilder(problemsHandler); - StyleSheet lessStyleSheet = astBuilder.parse(parsedSheet.getTree()); - return lessStyleSheet; - - } - - private String normalizeFileName(String filename, String urlParams) { - if ((new File(filename)).getName().contains(".")) - return filename; - - return filename + ".less" + urlParams; - } - - private boolean isCssFile(String filename) { - return filename.toLowerCase().endsWith(".css"); - } - - private String evaluateFilename(Expression urlInput) { - ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator(problemsHandler); - Expression urlExpression = expressionEvaluator.evaluate(urlInput); - - if (urlExpression.getType() != ASTCssNodeType.FUNCTION) - return toJavaFileSeparator(conversionUtils.contentToString(urlExpression)); - - //this is the only place in the compiler that can interpret the url function - FunctionExpression function = (FunctionExpression) urlExpression; - if (!"url".equals(function.getName().toLowerCase())) - return null; - - return toJavaFileSeparator(conversionUtils.contentToString(expressionEvaluator.evaluate(function.getParameter()))); - } - - private String toJavaFileSeparator(String path) { - if (Constants.FILE_SEPARATOR.equals("/")) { - return path; - } - - return path.replace(Constants.FILE_SEPARATOR, "/"); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/old/SimpleImportsSolver.java b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/old/SimpleImportsSolver.java deleted file mode 100755 index 38dfa5b..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/old/SimpleImportsSolver.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.github.sommeri.less4j.core.compiler.stages; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.github.sommeri.less4j.LessSource; -import com.github.sommeri.less4j.LessSource.CannotReadFile; -import com.github.sommeri.less4j.LessSource.FileNotFound; -import com.github.sommeri.less4j.LessSource.StringSourceException; -import com.github.sommeri.less4j.core.ast.ASTCssNode; -import com.github.sommeri.less4j.core.ast.ASTCssNodeType; -import com.github.sommeri.less4j.core.ast.Expression; -import com.github.sommeri.less4j.core.ast.FaultyNode; -import com.github.sommeri.less4j.core.ast.FunctionExpression; -import com.github.sommeri.less4j.core.ast.GeneralBody; -import com.github.sommeri.less4j.core.ast.Import; -import com.github.sommeri.less4j.core.ast.Import.ImportKind; -import com.github.sommeri.less4j.core.ast.Media; -import com.github.sommeri.less4j.core.ast.StyleSheet; -import com.github.sommeri.less4j.core.compiler.expressions.ExpressionEvaluator; -import com.github.sommeri.less4j.core.compiler.expressions.TypesConversionUtils; -import com.github.sommeri.less4j.core.parser.ANTLRParser; -import com.github.sommeri.less4j.core.parser.ASTBuilder; -import com.github.sommeri.less4j.core.parser.HiddenTokenAwareTree; -import com.github.sommeri.less4j.core.problems.ProblemsHandler; -import com.github.sommeri.less4j.platform.Constants; - -public class SimpleImportsSolver { - - private final ProblemsHandler problemsHandler; - private TypesConversionUtils conversionUtils = new TypesConversionUtils(); - private ASTManipulator astManipulator = new ASTManipulator(); - - private Set importedSources = new HashSet(); - - public SimpleImportsSolver(ProblemsHandler problemsHandler) { - this.problemsHandler = problemsHandler; - } - - public void solveImports(StyleSheet node, LessSource source) { - doSolveImports(node, source); - } - - private void doSolveImports(StyleSheet node, LessSource source) { - List childs = new ArrayList(node.getChilds()); - for (ASTCssNode kid : childs) { - if (kid.getType() == ASTCssNodeType.IMPORT) { - importEncountered((Import) kid, source); - } - } - } - - private void importEncountered(Import node, LessSource source) { - String filename = evaluateFilename(node.getUrlExpression()); - if (filename == null) { - problemsHandler.errorWrongImport(node.getUrlExpression()); - return; - } - String urlParams = ""; - int paramsIndx = filename.lastIndexOf("?"); - if (paramsIndx != -1) { - urlParams = filename.substring(paramsIndx); - filename = filename.substring(0, paramsIndx); - } - - if (isCssFile(filename)) - // css file imports should be left as they are - return; - - // add .less suffix if needed - filename = normalizeFileName(filename, urlParams); - LessSource importedSource; - try { - importedSource = source.relativeSource(filename); - } catch (FileNotFound ex) { - problemsHandler.errorImportedFileNotFound(node, filename); - return; - } catch (CannotReadFile e) { - problemsHandler.errorImportedFileCanNotBeRead(node, filename); - return; - } catch (StringSourceException ex) { - // imports are relative to current file and we do not know its location - problemsHandler.warnLessImportNoBaseDirectory(node.getUrlExpression()); - return; - } - - // import once should not import a file that was already imported - if (isImportOnce(node) && alreadyVisited(importedSource)) { - astManipulator.removeFromBody(node); - return; - } - importedSources.add(importedSource); - - String importedContent; - try { - importedContent = importedSource.getContent(); - } catch (FileNotFound e) { - problemsHandler.errorImportedFileNotFound(node, filename); - return; - } catch (CannotReadFile e) { - problemsHandler.errorImportedFileCanNotBeRead(node, filename); - return; - } - - // parse imported file - StyleSheet importedAst = parseContent(node, importedContent, importedSource); - solveImports(importedAst, importedSource); - - // add media queries if needed - if (node.hasMediums()) { - HiddenTokenAwareTree underlyingStructure = node.getUnderlyingStructure(); - Media media = new Media(underlyingStructure); - media.setMediums(node.getMediums()); - media.setBody(new GeneralBody(underlyingStructure, importedAst.getMembers())); - media.configureParentToAllChilds(); - astManipulator.replaceInBody(node, media); - } else { - astManipulator.replaceInBody(node, importedAst.getChilds()); - } - } - - private boolean isImportOnce(Import node) { - return node.getKind() == ImportKind.IMPORT_ONCE; - } - - private boolean alreadyVisited(LessSource importedSource) { - return importedSources.contains(importedSource); - } - - private StyleSheet parseContent(Import importNode, String importedContent, LessSource source) { - ANTLRParser parser = new ANTLRParser(); - ANTLRParser.ParseResult parsedSheet = parser.parseStyleSheet(importedContent, source); - if (parsedSheet.hasErrors()) { - StyleSheet result = new StyleSheet(importNode.getUnderlyingStructure()); - result.addMember(new FaultyNode(importNode)); - problemsHandler.addErrors(parsedSheet.getErrors()); - return result; - } - ASTBuilder astBuilder = new ASTBuilder(problemsHandler); - StyleSheet lessStyleSheet = astBuilder.parse(parsedSheet.getTree()); - return lessStyleSheet; - - } - - private String normalizeFileName(String filename, String urlParams) { - if (filename.toLowerCase().contains(".")) - return filename; - - return filename + ".less" + urlParams; - } - - private boolean isCssFile(String filename) { - return filename.toLowerCase().endsWith(".css"); - } - - private String evaluateFilename(Expression urlInput) { - ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator(problemsHandler); - Expression urlExpression = expressionEvaluator.evaluate(urlInput); - - if (urlExpression.getType() != ASTCssNodeType.FUNCTION) - return toJavaFileSeparator(conversionUtils.contentToString(urlExpression)); - - //this is the only place in the compiler that can interpret the url function - FunctionExpression function = (FunctionExpression) urlExpression; - if (!"url".equals(function.getName().toLowerCase())) - return null; - - return toJavaFileSeparator(conversionUtils.contentToString(expressionEvaluator.evaluate(function.getParameter()))); - } - - private String toJavaFileSeparator(String path) { - if (Constants.FILE_SEPARATOR.equals("/")) { - return path; - } - - return path.replace(Constants.FILE_SEPARATOR, "/"); - } - -} diff --git a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/pair.info b/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/pair.info deleted file mode 100755 index ad8da14..0000000 --- a/All/FindBugs-DM_CONVERT_CASE/FBViolation#75805/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75805 -comSha:19c12371d5f97aaededc9c92c63cf9753f9f9476 -parentComSha:a20ccf1645f33302ead053396e0362bd7c692b1c -BuggyFilePath:src/main/java/com/github/sommeri/less4j/core/compiler/stages/SimpleImportsSolver.java -FixedFilePath:src/main/java/com/github/sommeri/less4j/core/compiler/stages/SimpleImportsSolver.java -StartLineNum:148 -EndLineNum:148 -repoName:SomMeri#less4j \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/comMsg.txt deleted file mode 100755 index feef59a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Version 7929 - -git-svn-id: svn://svn.code.sf.net/p/plantuml/code/trunk@194 2bfd43ce-aac2-44f9-bcbc-61bf0d4e0ab5 \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/diff.diff deleted file mode 100755 index 57b0aca..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/net/sourceforge/plantuml/sequencediagram/graphic/SequenceDiagramTxtMaker.java b/src/net/sourceforge/plantuml/sequencediagram/graphic/SequenceDiagramTxtMaker.java -index a61618c9..9a448022 100644 ---- a/src/net/sourceforge/plantuml/sequencediagram/graphic/SequenceDiagramTxtMaker.java -+++ b/src/net/sourceforge/plantuml/sequencediagram/graphic/SequenceDiagramTxtMaker.java -@@ -116 +115,0 @@ public class SequenceDiagramTxtMaker implements FileMaker { -- final PrintStream ps = new PrintStream(os); -@@ -117,0 +117 @@ public class SequenceDiagramTxtMaker implements FileMaker { -+ final PrintStream ps = new PrintStream(os, true, "UTF-8"); -@@ -119,0 +120 @@ public class SequenceDiagramTxtMaker implements FileMaker { -+ final PrintStream ps = new PrintStream(os); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/new/SequenceDiagramTxtMaker.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/new/SequenceDiagramTxtMaker.java deleted file mode 100755 index 9a44802..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/new/SequenceDiagramTxtMaker.java +++ /dev/null @@ -1,133 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2012, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4935 $ - * - */ -package net.sourceforge.plantuml.sequencediagram.graphic; - -import java.awt.geom.Dimension2D; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; - -import net.sourceforge.plantuml.FileFormat; -import net.sourceforge.plantuml.UmlDiagramInfo; -import net.sourceforge.plantuml.asciiart.TextSkin; -import net.sourceforge.plantuml.asciiart.TextStringBounder; -import net.sourceforge.plantuml.graphic.StringBounder; -import net.sourceforge.plantuml.sequencediagram.Event; -import net.sourceforge.plantuml.sequencediagram.LifeEvent; -import net.sourceforge.plantuml.sequencediagram.LifeEventType; -import net.sourceforge.plantuml.sequencediagram.Message; -import net.sourceforge.plantuml.sequencediagram.Participant; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagram; -import net.sourceforge.plantuml.skin.Skin; -import net.sourceforge.plantuml.ugraphic.txt.UGraphicTxt; - -public class SequenceDiagramTxtMaker implements FileMaker { - - private final SequenceDiagram diagram; - private final DrawableSet drawableSet; - private final Dimension2D fullDimension; - private final StringBounder dummyStringBounder = new TextStringBounder(); - private final UGraphicTxt ug = new UGraphicTxt(); - private final FileFormat fileFormat; - private final Skin skin; - - public SequenceDiagramTxtMaker(SequenceDiagram sequenceDiagram, FileFormat fileFormat) { - this.fileFormat = fileFormat; - this.diagram = sequenceDiagram; - this.skin = new TextSkin(fileFormat); - - final DrawableSetInitializer initializer = new DrawableSetInitializer(skin, sequenceDiagram.getSkinParam(), - sequenceDiagram.isShowFootbox(), sequenceDiagram.getAutonewpage()); - - for (Participant p : sequenceDiagram.participants().values()) { - initializer.addParticipant(p, null); - } - for (Event ev : sequenceDiagram.events()) { - initializer.addEvent(ev); - if (ev instanceof Message) { - // TODO mieux faire - final Message m = (Message) ev; - for (LifeEvent lifeEvent : m.getLiveEvents()) { - if (lifeEvent.getType() == LifeEventType.DESTROY - /* - * || lifeEvent.getType() == LifeEventType.CREATE - */) { - initializer.addEvent(lifeEvent); - } - } - } - } - drawableSet = initializer.createDrawableSet(dummyStringBounder); - // final List newpages = new ArrayList(); - // for (Event ev : drawableSet.getAllEvents()) { - // if (ev instanceof Newpage) { - // newpages.add((Newpage) ev); - // } - // } - fullDimension = drawableSet.getDimension(); - final double headerHeight = drawableSet.getHeadHeight(dummyStringBounder); - final double tailHeight = drawableSet.getTailHeight(dummyStringBounder, diagram.isShowFootbox()); - final double newpage2 = fullDimension.getHeight() - (diagram.isShowFootbox() ? tailHeight : 0) - headerHeight; - final Page page = new Page(headerHeight, 0, newpage2, tailHeight, 0, null); - drawableSet.drawU(ug, 0, fullDimension.getWidth(), page, diagram.isShowFootbox()); - } - - // public List createManyRRMV(File suggestedFile) throws IOException { - // if (fileFormat == FileFormat.UTXT) { - // ug.getCharArea().print(new PrintStream(suggestedFile, "UTF-8")); - // } else { - // ug.getCharArea().print(new PrintStream(suggestedFile)); - // } - // return Collections.singletonList(suggestedFile); - // } - - public UmlDiagramInfo createOne2(OutputStream os, int index) throws IOException { - if (fileFormat == FileFormat.UTXT) { - final PrintStream ps = new PrintStream(os, true, "UTF-8"); - ug.getCharArea().print(ps); - } else { - final PrintStream ps = new PrintStream(os); - ug.getCharArea().print(ps); - } - return null; - } - - public int getNbPages() { - return 1; - } - - public void appendCmap(StringBuilder cmap) { - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/old/SequenceDiagramTxtMaker.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/old/SequenceDiagramTxtMaker.java deleted file mode 100755 index a61618c..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/old/SequenceDiagramTxtMaker.java +++ /dev/null @@ -1,132 +0,0 @@ -/* ======================================================================== - * PlantUML : a free UML diagram generator - * ======================================================================== - * - * (C) Copyright 2009-2012, Arnaud Roques - * - * Project Info: http://plantuml.sourceforge.net - * - * This file is part of PlantUML. - * - * PlantUML is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * PlantUML distributed in the hope that it will be useful, but - * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY - * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public - * License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, - * USA. - * - * [Java is a trademark or registered trademark of Sun Microsystems, Inc. - * in the United States and other countries.] - * - * Original Author: Arnaud Roques - * - * Revision $Revision: 4935 $ - * - */ -package net.sourceforge.plantuml.sequencediagram.graphic; - -import java.awt.geom.Dimension2D; -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintStream; - -import net.sourceforge.plantuml.FileFormat; -import net.sourceforge.plantuml.UmlDiagramInfo; -import net.sourceforge.plantuml.asciiart.TextSkin; -import net.sourceforge.plantuml.asciiart.TextStringBounder; -import net.sourceforge.plantuml.graphic.StringBounder; -import net.sourceforge.plantuml.sequencediagram.Event; -import net.sourceforge.plantuml.sequencediagram.LifeEvent; -import net.sourceforge.plantuml.sequencediagram.LifeEventType; -import net.sourceforge.plantuml.sequencediagram.Message; -import net.sourceforge.plantuml.sequencediagram.Participant; -import net.sourceforge.plantuml.sequencediagram.SequenceDiagram; -import net.sourceforge.plantuml.skin.Skin; -import net.sourceforge.plantuml.ugraphic.txt.UGraphicTxt; - -public class SequenceDiagramTxtMaker implements FileMaker { - - private final SequenceDiagram diagram; - private final DrawableSet drawableSet; - private final Dimension2D fullDimension; - private final StringBounder dummyStringBounder = new TextStringBounder(); - private final UGraphicTxt ug = new UGraphicTxt(); - private final FileFormat fileFormat; - private final Skin skin; - - public SequenceDiagramTxtMaker(SequenceDiagram sequenceDiagram, FileFormat fileFormat) { - this.fileFormat = fileFormat; - this.diagram = sequenceDiagram; - this.skin = new TextSkin(fileFormat); - - final DrawableSetInitializer initializer = new DrawableSetInitializer(skin, sequenceDiagram.getSkinParam(), - sequenceDiagram.isShowFootbox(), sequenceDiagram.getAutonewpage()); - - for (Participant p : sequenceDiagram.participants().values()) { - initializer.addParticipant(p, null); - } - for (Event ev : sequenceDiagram.events()) { - initializer.addEvent(ev); - if (ev instanceof Message) { - // TODO mieux faire - final Message m = (Message) ev; - for (LifeEvent lifeEvent : m.getLiveEvents()) { - if (lifeEvent.getType() == LifeEventType.DESTROY - /* - * || lifeEvent.getType() == LifeEventType.CREATE - */) { - initializer.addEvent(lifeEvent); - } - } - } - } - drawableSet = initializer.createDrawableSet(dummyStringBounder); - // final List newpages = new ArrayList(); - // for (Event ev : drawableSet.getAllEvents()) { - // if (ev instanceof Newpage) { - // newpages.add((Newpage) ev); - // } - // } - fullDimension = drawableSet.getDimension(); - final double headerHeight = drawableSet.getHeadHeight(dummyStringBounder); - final double tailHeight = drawableSet.getTailHeight(dummyStringBounder, diagram.isShowFootbox()); - final double newpage2 = fullDimension.getHeight() - (diagram.isShowFootbox() ? tailHeight : 0) - headerHeight; - final Page page = new Page(headerHeight, 0, newpage2, tailHeight, 0, null); - drawableSet.drawU(ug, 0, fullDimension.getWidth(), page, diagram.isShowFootbox()); - } - - // public List createManyRRMV(File suggestedFile) throws IOException { - // if (fileFormat == FileFormat.UTXT) { - // ug.getCharArea().print(new PrintStream(suggestedFile, "UTF-8")); - // } else { - // ug.getCharArea().print(new PrintStream(suggestedFile)); - // } - // return Collections.singletonList(suggestedFile); - // } - - public UmlDiagramInfo createOne2(OutputStream os, int index) throws IOException { - final PrintStream ps = new PrintStream(os); - if (fileFormat == FileFormat.UTXT) { - ug.getCharArea().print(ps); - } else { - ug.getCharArea().print(ps); - } - return null; - } - - public int getNbPages() { - return 1; - } - - public void appendCmap(StringBuilder cmap) { - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/pair.info deleted file mode 100755 index 80dbf82..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#22214/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:22214 -comSha:ce765c150cabfd2412cfb5c0766106ea2a29b89f -parentComSha:c27d266efaff13ac277f7d0969369c46e28096ad -BuggyFilePath:src/net/sourceforge/plantuml/sequencediagram/graphic/SequenceDiagramTxtMaker.java -FixedFilePath:src/net/sourceforge/plantuml/sequencediagram/graphic/SequenceDiagramTxtMaker.java -StartLineNum:116 -EndLineNum:116 -repoName:jensnerche#plantuml \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/comMsg.txt deleted file mode 100755 index 5398b00..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -always use utf-8 for getBytes() calls \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/diff.diff deleted file mode 100755 index 8766482..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/ch/ralscha/extdirectspring/bean/ExtDirectResponseBuilder.java b/src/main/java/ch/ralscha/extdirectspring/bean/ExtDirectResponseBuilder.java -index e56f8f65..d2e859d4 100644 ---- a/src/main/java/ch/ralscha/extdirectspring/bean/ExtDirectResponseBuilder.java -+++ b/src/main/java/ch/ralscha/extdirectspring/bean/ExtDirectResponseBuilder.java -@@ -224 +224 @@ public class ExtDirectResponseBuilder { -- bos.write("".getBytes()); -+ bos.write(responseJson.getBytes("UTF-8")); -+ bos.write("".getBytes("UTF-8")); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/new/ExtDirectResponseBuilder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/new/ExtDirectResponseBuilder.java deleted file mode 100755 index d2e859d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/new/ExtDirectResponseBuilder.java +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Copyright 2010-2012 Ralph Schaer - * - * 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 ch.ralscha.extdirectspring.bean; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.context.MessageSource; -import org.springframework.util.FileCopyUtils; -import org.springframework.validation.BindingResult; -import org.springframework.validation.FieldError; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.support.RequestContextUtils; - -import ch.ralscha.extdirectspring.controller.Configuration; -import ch.ralscha.extdirectspring.controller.RouterController; -import ch.ralscha.extdirectspring.util.ExtDirectSpringUtil; - -/** - * An utility class that helps building the response for a FORM_POST method. The - * response is written directly into the - * {@link HttpServletResponse#getOutputStream()} with {@link #buildAndWrite()}. - * - * @author Ralph Schaer - */ -public class ExtDirectResponseBuilder { - - private final ExtDirectResponse extDirectResponse; - - private final HttpServletRequest request; - - private final HttpServletResponse response; - - private final Map result; - - /** - * Creates a builder that builds and writes the response of a FORM_POST - * method. Sets the successful flag to true, can be changed with the - * {@link #successful()} and {@link #unsuccessful()} methods. - * - * @param request the current http servlet request object - * @param response the current http servlet response object - */ - public ExtDirectResponseBuilder(final HttpServletRequest request, final HttpServletResponse response) { - this.request = request; - this.response = response; - - extDirectResponse = new ExtDirectResponse(request); - result = new HashMap(); - successful(); - extDirectResponse.setResult(result); - } - - /** - * Creates a builder instance. - * - * @see #ExtDirectResponseBuilder(HttpServletRequest, HttpServletResponse) - * - * @param request the current http servlet request object - * @param response the current http servlet response object - * - * @return the created builder instance - */ - public static ExtDirectResponseBuilder create(final HttpServletRequest request, final HttpServletResponse response) { - return new ExtDirectResponseBuilder(request, response); - } - - /** - * Creates an "exception" response. Calls - * {@link ExtDirectResponse#setType(String)} with a value of "exception". - * Calls {@link ExtDirectResponse#setMessage(String)} and - * {@link ExtDirectResponse#setWhere(String)} according to the - * {@link Configuration}. - * - * This is a method primarly used for implementations of - * {@link HandlerExceptionResolver}. - * - * @param exception the exception that was thrown. - * @return this instance - */ - public ExtDirectResponseBuilder setException(final Exception exception) { - unsuccessful(); - - WebApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request); - Configuration configuration = null; - try { - configuration = ctx.getBean(Configuration.class); - } catch (NoSuchBeanDefinitionException e) { - configuration = new Configuration(); - } - - extDirectResponse.setType("exception"); - extDirectResponse.setMessage(configuration.getMessage(exception)); - - if (configuration.isSendStacktrace()) { - extDirectResponse.setWhere(ExtDirectSpringUtil.getStackTrace(exception)); - } else { - extDirectResponse.setWhere(null); - } - - return this; - } - - /** - * Adds an "errors" property in the response if there are any errors in the - * bindingResult. Sets the success flag to false if there are errors. - * - * @param bindingResult - * @return this instance - */ - public ExtDirectResponseBuilder addErrors(final BindingResult bindingResult) { - addErrors(null, null, bindingResult); - return this; - } - - /** - * Adds an "errors" property in the response if there are any errors in the - * bindingResult. Sets the success flag to false if there are errors. - * - * @param locale - * @param messageSource - * @param bindingResult - * @return this instance - */ - public ExtDirectResponseBuilder addErrors(final Locale locale, final MessageSource messageSource, - final BindingResult bindingResult) { - if (bindingResult != null && bindingResult.hasFieldErrors()) { - Map> errorMap = new HashMap>(); - for (FieldError fieldError : bindingResult.getFieldErrors()) { - String message = fieldError.getDefaultMessage(); - if (messageSource != null) { - Locale loc = (locale != null ? locale : Locale.getDefault()); - message = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), loc); - } - List fieldErrors = errorMap.get(fieldError.getField()); - - if (fieldErrors == null) { - fieldErrors = new ArrayList(); - errorMap.put(fieldError.getField(), fieldErrors); - } - - fieldErrors.add(message); - } - if (errorMap.isEmpty()) { - addResultProperty("success", true); - } else { - addResultProperty("errors", errorMap); - addResultProperty("success", false); - } - } - return this; - } - - /** - * Add additional property to the response. - * - * @param key the key of the property - * @param value the value of this property - * @return this instance - */ - public ExtDirectResponseBuilder addResultProperty(final String key, final Object value) { - result.put(key, value); - return this; - } - - /** - * Sets success flag to true. - * @return this instance - */ - public ExtDirectResponseBuilder successful() { - result.put("success", true); - return this; - } - - /** - * Sets success flag to false. - * @return this instance - */ - public ExtDirectResponseBuilder unsuccessful() { - result.put("success", false); - return this; - } - - /** - * Builds and writes the response into the OutputStream of - * {@link HttpServletResponse}. This methods has to be called at the end of - * a FORM_POST method. - */ - public void buildAndWrite() { - - try { - RouterController routerController = RequestContextUtils.getWebApplicationContext(request).getBean( - RouterController.class); - - if (isMultipart()) { - response.setContentType(RouterController.TEXT_HTML.toString()); - response.setCharacterEncoding(RouterController.TEXT_HTML.getCharSet().name()); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); - bos.write("".getBytes("UTF-8")); - - response.setContentLength(bos.size()); - FileCopyUtils.copy(bos.toByteArray(), response.getOutputStream()); - } else { - routerController.writeJsonResponse(response, extDirectResponse, routerController.getConfiguration() - .isStreamResponse()); - } - } catch (IOException e) { - LogFactory.getLog(getClass()).error("buildAndWrite", e); - throw new RuntimeException(e); - } - - } - - private boolean isMultipart() { - if (!"post".equals(request.getMethod().toLowerCase())) { - return false; - } - String contentType = request.getContentType(); - return (contentType != null && contentType.toLowerCase().startsWith("multipart/")); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/old/ExtDirectResponseBuilder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/old/ExtDirectResponseBuilder.java deleted file mode 100755 index e56f8f6..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/old/ExtDirectResponseBuilder.java +++ /dev/null @@ -1,253 +0,0 @@ -/** - * Copyright 2010-2012 Ralph Schaer - * - * 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 ch.ralscha.extdirectspring.bean; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.NoSuchBeanDefinitionException; -import org.springframework.context.MessageSource; -import org.springframework.util.FileCopyUtils; -import org.springframework.validation.BindingResult; -import org.springframework.validation.FieldError; -import org.springframework.web.context.WebApplicationContext; -import org.springframework.web.servlet.HandlerExceptionResolver; -import org.springframework.web.servlet.support.RequestContextUtils; - -import ch.ralscha.extdirectspring.controller.Configuration; -import ch.ralscha.extdirectspring.controller.RouterController; -import ch.ralscha.extdirectspring.util.ExtDirectSpringUtil; - -/** - * An utility class that helps building the response for a FORM_POST method. The - * response is written directly into the - * {@link HttpServletResponse#getOutputStream()} with {@link #buildAndWrite()}. - * - * @author Ralph Schaer - */ -public class ExtDirectResponseBuilder { - - private final ExtDirectResponse extDirectResponse; - - private final HttpServletRequest request; - - private final HttpServletResponse response; - - private final Map result; - - /** - * Creates a builder that builds and writes the response of a FORM_POST - * method. Sets the successful flag to true, can be changed with the - * {@link #successful()} and {@link #unsuccessful()} methods. - * - * @param request the current http servlet request object - * @param response the current http servlet response object - */ - public ExtDirectResponseBuilder(final HttpServletRequest request, final HttpServletResponse response) { - this.request = request; - this.response = response; - - extDirectResponse = new ExtDirectResponse(request); - result = new HashMap(); - successful(); - extDirectResponse.setResult(result); - } - - /** - * Creates a builder instance. - * - * @see #ExtDirectResponseBuilder(HttpServletRequest, HttpServletResponse) - * - * @param request the current http servlet request object - * @param response the current http servlet response object - * - * @return the created builder instance - */ - public static ExtDirectResponseBuilder create(final HttpServletRequest request, final HttpServletResponse response) { - return new ExtDirectResponseBuilder(request, response); - } - - /** - * Creates an "exception" response. Calls - * {@link ExtDirectResponse#setType(String)} with a value of "exception". - * Calls {@link ExtDirectResponse#setMessage(String)} and - * {@link ExtDirectResponse#setWhere(String)} according to the - * {@link Configuration}. - * - * This is a method primarly used for implementations of - * {@link HandlerExceptionResolver}. - * - * @param exception the exception that was thrown. - * @return this instance - */ - public ExtDirectResponseBuilder setException(final Exception exception) { - unsuccessful(); - - WebApplicationContext ctx = RequestContextUtils.getWebApplicationContext(request); - Configuration configuration = null; - try { - configuration = ctx.getBean(Configuration.class); - } catch (NoSuchBeanDefinitionException e) { - configuration = new Configuration(); - } - - extDirectResponse.setType("exception"); - extDirectResponse.setMessage(configuration.getMessage(exception)); - - if (configuration.isSendStacktrace()) { - extDirectResponse.setWhere(ExtDirectSpringUtil.getStackTrace(exception)); - } else { - extDirectResponse.setWhere(null); - } - - return this; - } - - /** - * Adds an "errors" property in the response if there are any errors in the - * bindingResult. Sets the success flag to false if there are errors. - * - * @param bindingResult - * @return this instance - */ - public ExtDirectResponseBuilder addErrors(final BindingResult bindingResult) { - addErrors(null, null, bindingResult); - return this; - } - - /** - * Adds an "errors" property in the response if there are any errors in the - * bindingResult. Sets the success flag to false if there are errors. - * - * @param locale - * @param messageSource - * @param bindingResult - * @return this instance - */ - public ExtDirectResponseBuilder addErrors(final Locale locale, final MessageSource messageSource, - final BindingResult bindingResult) { - if (bindingResult != null && bindingResult.hasFieldErrors()) { - Map> errorMap = new HashMap>(); - for (FieldError fieldError : bindingResult.getFieldErrors()) { - String message = fieldError.getDefaultMessage(); - if (messageSource != null) { - Locale loc = (locale != null ? locale : Locale.getDefault()); - message = messageSource.getMessage(fieldError.getCode(), fieldError.getArguments(), loc); - } - List fieldErrors = errorMap.get(fieldError.getField()); - - if (fieldErrors == null) { - fieldErrors = new ArrayList(); - errorMap.put(fieldError.getField(), fieldErrors); - } - - fieldErrors.add(message); - } - if (errorMap.isEmpty()) { - addResultProperty("success", true); - } else { - addResultProperty("errors", errorMap); - addResultProperty("success", false); - } - } - return this; - } - - /** - * Add additional property to the response. - * - * @param key the key of the property - * @param value the value of this property - * @return this instance - */ - public ExtDirectResponseBuilder addResultProperty(final String key, final Object value) { - result.put(key, value); - return this; - } - - /** - * Sets success flag to true. - * @return this instance - */ - public ExtDirectResponseBuilder successful() { - result.put("success", true); - return this; - } - - /** - * Sets success flag to false. - * @return this instance - */ - public ExtDirectResponseBuilder unsuccessful() { - result.put("success", false); - return this; - } - - /** - * Builds and writes the response into the OutputStream of - * {@link HttpServletResponse}. This methods has to be called at the end of - * a FORM_POST method. - */ - public void buildAndWrite() { - - try { - RouterController routerController = RequestContextUtils.getWebApplicationContext(request).getBean( - RouterController.class); - - if (isMultipart()) { - response.setContentType(RouterController.TEXT_HTML.toString()); - response.setCharacterEncoding(RouterController.TEXT_HTML.getCharSet().name()); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); - bos.write("".getBytes()); - - response.setContentLength(bos.size()); - FileCopyUtils.copy(bos.toByteArray(), response.getOutputStream()); - } else { - routerController.writeJsonResponse(response, extDirectResponse, routerController.getConfiguration() - .isStreamResponse()); - } - } catch (IOException e) { - LogFactory.getLog(getClass()).error("buildAndWrite", e); - throw new RuntimeException(e); - } - - } - - private boolean isMultipart() { - if (!"post".equals(request.getMethod().toLowerCase())) { - return false; - } - String contentType = request.getContentType(); - return (contentType != null && contentType.toLowerCase().startsWith("multipart/")); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/pair.info deleted file mode 100755 index 9be9e3c..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#25251/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:25251 -comSha:d4208fc231566b1b325c3089c5a44af041d45861 -parentComSha:d87c702581f3e4cfcf9dc2785f3d4c5d2ee862a1 -BuggyFilePath:src/main/java/ch/ralscha/extdirectspring/bean/ExtDirectResponseBuilder.java -FixedFilePath:src/main/java/ch/ralscha/extdirectspring/bean/ExtDirectResponseBuilder.java -StartLineNum:224 -EndLineNum:224 -repoName:ralscha#extdirectspring \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/comMsg.txt deleted file mode 100755 index 852a4ac..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'stable' of github.com:code4craft/webmagic \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/diff.diff deleted file mode 100755 index c5b59ce..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/webmagic-core/src/main/java/us/codecraft/webmagic/pipeline/FilePipeline.java b/webmagic-core/src/main/java/us/codecraft/webmagic/pipeline/FilePipeline.java -index 8eab426..57d6eea 100644 ---- a/webmagic-core/src/main/java/us/codecraft/webmagic/pipeline/FilePipeline.java -+++ b/webmagic-core/src/main/java/us/codecraft/webmagic/pipeline/FilePipeline.java -@@ -6,0 +7 @@ import org.slf4j.LoggerFactory; -+ -@@ -11 +12 @@ import us.codecraft.webmagic.utils.FilePersistentBase; --import java.io.FileWriter; -+import java.io.FileOutputStream; -@@ -12,0 +14 @@ import java.io.IOException; -+import java.io.OutputStreamWriter; -@@ -42 +44 @@ public class FilePipeline extends FilePersistentBase implements Pipeline { -- PrintWriter printWriter = new PrintWriter(new FileWriter(getFile(path + DigestUtils.md5Hex(resultItems.getRequest().getUrl()) + ".html"))); -+ PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(getFile(path + DigestUtils.md5Hex(resultItems.getRequest().getUrl()) + ".html")),"UTF-8")); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/new/FilePipeline.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/new/FilePipeline.java deleted file mode 100755 index 57d6eea..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/new/FilePipeline.java +++ /dev/null @@ -1,62 +0,0 @@ -package us.codecraft.webmagic.pipeline; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.http.annotation.ThreadSafe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import us.codecraft.webmagic.ResultItems; -import us.codecraft.webmagic.Task; -import us.codecraft.webmagic.utils.FilePersistentBase; - -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.util.Map; - -/** - * Store results in files.
- * - * @author code4crafter@gmail.com
- * @since 0.1.0 - */ -@ThreadSafe -public class FilePipeline extends FilePersistentBase implements Pipeline { - - private Logger logger = LoggerFactory.getLogger(getClass()); - - /** - * create a FilePipeline with default path"/data/webmagic/" - */ - public FilePipeline() { - setPath("/data/webmagic/"); - } - - public FilePipeline(String path) { - setPath(path); - } - - @Override - public void process(ResultItems resultItems, Task task) { - String path = this.path + PATH_SEPERATOR + task.getUUID() + PATH_SEPERATOR; - try { - PrintWriter printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(getFile(path + DigestUtils.md5Hex(resultItems.getRequest().getUrl()) + ".html")),"UTF-8")); - printWriter.println("url:\t" + resultItems.getRequest().getUrl()); - for (Map.Entry entry : resultItems.getAll().entrySet()) { - if (entry.getValue() instanceof Iterable) { - Iterable value = (Iterable) entry.getValue(); - printWriter.println(entry.getKey() + ":"); - for (Object o : value) { - printWriter.println(o); - } - } else { - printWriter.println(entry.getKey() + ":\t" + entry.getValue()); - } - } - printWriter.close(); - } catch (IOException e) { - logger.warn("write file error", e); - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/old/FilePipeline.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/old/FilePipeline.java deleted file mode 100755 index 8eab426..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/old/FilePipeline.java +++ /dev/null @@ -1,60 +0,0 @@ -package us.codecraft.webmagic.pipeline; - -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.http.annotation.ThreadSafe; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import us.codecraft.webmagic.ResultItems; -import us.codecraft.webmagic.Task; -import us.codecraft.webmagic.utils.FilePersistentBase; - -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Map; - -/** - * Store results in files.
- * - * @author code4crafter@gmail.com
- * @since 0.1.0 - */ -@ThreadSafe -public class FilePipeline extends FilePersistentBase implements Pipeline { - - private Logger logger = LoggerFactory.getLogger(getClass()); - - /** - * create a FilePipeline with default path"/data/webmagic/" - */ - public FilePipeline() { - setPath("/data/webmagic/"); - } - - public FilePipeline(String path) { - setPath(path); - } - - @Override - public void process(ResultItems resultItems, Task task) { - String path = this.path + PATH_SEPERATOR + task.getUUID() + PATH_SEPERATOR; - try { - PrintWriter printWriter = new PrintWriter(new FileWriter(getFile(path + DigestUtils.md5Hex(resultItems.getRequest().getUrl()) + ".html"))); - printWriter.println("url:\t" + resultItems.getRequest().getUrl()); - for (Map.Entry entry : resultItems.getAll().entrySet()) { - if (entry.getValue() instanceof Iterable) { - Iterable value = (Iterable) entry.getValue(); - printWriter.println(entry.getKey() + ":"); - for (Object o : value) { - printWriter.println(o); - } - } else { - printWriter.println(entry.getKey() + ":\t" + entry.getValue()); - } - } - printWriter.close(); - } catch (IOException e) { - logger.warn("write file error", e); - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/pair.info deleted file mode 100755 index a50a311..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#27140/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:27140 -comSha:8c33be48a60f1646b39e69f373164ead36e5ba8b -parentComSha:b21e20fe425ebcffc655a065eaa12d0052db46ef -BuggyFilePath:webmagic-core/src/main/java/us/codecraft/webmagic/pipeline/FilePipeline.java -FixedFilePath:webmagic-core/src/main/java/us/codecraft/webmagic/pipeline/FilePipeline.java -StartLineNum:42 -EndLineNum:42 -repoName:code4craft#webmagic \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/comMsg.txt deleted file mode 100755 index d76a500..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/comMsg.txt +++ /dev/null @@ -1,5 +0,0 @@ -Merge remote-tracking branch 'origin/merged-prod-cons' - -Conflicts: - src/main/java/teetime/framework/AbstractStage.java - src/main/java/teetime/framework/RunnableStage.java \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/diff.diff deleted file mode 100755 index 69998cf..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/teetime/framework/pipe/PipeFactoryLoader.java b/src/main/java/teetime/framework/pipe/PipeFactoryLoader.java -index 2e129e2f..6e564014 100644 ---- a/src/main/java/teetime/framework/pipe/PipeFactoryLoader.java -+++ b/src/main/java/teetime/framework/pipe/PipeFactoryLoader.java -@@ -17 +17 @@ import teetime.framework.FileSearcher; --public class PipeFactoryLoader { -+public final class PipeFactoryLoader { -@@ -28 +28 @@ public class PipeFactoryLoader { -- BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream)); -+ BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/new/PipeFactoryLoader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/new/PipeFactoryLoader.java deleted file mode 100755 index 6e56401..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/new/PipeFactoryLoader.java +++ /dev/null @@ -1,81 +0,0 @@ -package teetime.framework.pipe; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import teetime.framework.FileSearcher; - -public final class PipeFactoryLoader { - - private static final Logger LOGGER = LoggerFactory.getLogger(PipeFactoryLoader.class); - - private PipeFactoryLoader() { - // utility class - } - - public static List loadFromStream(final InputStream stream) throws IOException { - List pipeFactories = new LinkedList(); - - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); - try { - String line; - while (null != (line = bufferedReader.readLine())) { - try { - line = line.trim(); - if (!line.isEmpty()) { - Class clazz = Class.forName(line); - Class pipeFactoryClass = clazz.asSubclass(IPipeFactory.class); - IPipeFactory pipeFactory = pipeFactoryClass.newInstance(); - pipeFactories.add(pipeFactory); - } - } catch (ClassNotFoundException e) { - LOGGER.warn("Could not find class: " + line, e); - } catch (InstantiationException e) { - LOGGER.warn("Could not instantiate pipe factory", e); - } catch (IllegalAccessException e) { - LOGGER.warn("Could not instantiate pipe factory", e); - } - } - } finally { - bufferedReader.close(); - } - - return pipeFactories; - } - - public static List loadPipeFactoriesFromClasspath(final String configFileName) { - - List files = null; - - try { - files = FileSearcher.loadResources(configFileName); - } catch (IOException e) { - throw new IllegalStateException(e); - } - return mergeFiles(files); - } - - public static List mergeFiles(final List files) { - ArrayList list = new ArrayList(); - for (URL url : files) { - try { - InputStream is = url.openStream(); - list.addAll(loadFromStream(is)); - is.close(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - - } - return list; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/old/PipeFactoryLoader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/old/PipeFactoryLoader.java deleted file mode 100755 index 2e129e2..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/old/PipeFactoryLoader.java +++ /dev/null @@ -1,81 +0,0 @@ -package teetime.framework.pipe; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import teetime.framework.FileSearcher; - -public class PipeFactoryLoader { - - private static final Logger LOGGER = LoggerFactory.getLogger(PipeFactoryLoader.class); - - private PipeFactoryLoader() { - // utility class - } - - public static List loadFromStream(final InputStream stream) throws IOException { - List pipeFactories = new LinkedList(); - - BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream)); - try { - String line; - while (null != (line = bufferedReader.readLine())) { - try { - line = line.trim(); - if (!line.isEmpty()) { - Class clazz = Class.forName(line); - Class pipeFactoryClass = clazz.asSubclass(IPipeFactory.class); - IPipeFactory pipeFactory = pipeFactoryClass.newInstance(); - pipeFactories.add(pipeFactory); - } - } catch (ClassNotFoundException e) { - LOGGER.warn("Could not find class: " + line, e); - } catch (InstantiationException e) { - LOGGER.warn("Could not instantiate pipe factory", e); - } catch (IllegalAccessException e) { - LOGGER.warn("Could not instantiate pipe factory", e); - } - } - } finally { - bufferedReader.close(); - } - - return pipeFactories; - } - - public static List loadPipeFactoriesFromClasspath(final String configFileName) { - - List files = null; - - try { - files = FileSearcher.loadResources(configFileName); - } catch (IOException e) { - throw new IllegalStateException(e); - } - return mergeFiles(files); - } - - public static List mergeFiles(final List files) { - ArrayList list = new ArrayList(); - for (URL url : files) { - try { - InputStream is = url.openStream(); - list.addAll(loadFromStream(is)); - is.close(); - } catch (IOException e) { - throw new IllegalStateException(e); - } - - } - return list; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/pair.info deleted file mode 100755 index c79ca8e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28064/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:28064 -comSha:0b650ceedaace3be4bce73b51aea4544836fdccc -parentComSha:088233e7c66e7e4b2627221c6efd5c8200d46a23 -BuggyFilePath:src/main/java/teetime/framework/pipe/PipeFactoryLoader.java -FixedFilePath:src/main/java/teetime/framework/pipe/PipeFactoryLoader.java -StartLineNum:28 -EndLineNum:28 -repoName:eXistence#TeeTime \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/comMsg.txt deleted file mode 100755 index d76a500..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/comMsg.txt +++ /dev/null @@ -1,5 +0,0 @@ -Merge remote-tracking branch 'origin/merged-prod-cons' - -Conflicts: - src/main/java/teetime/framework/AbstractStage.java - src/main/java/teetime/framework/RunnableStage.java \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/diff.diff deleted file mode 100755 index da6753d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/teetime/stage/ByteArray2String.java b/src/main/java/teetime/stage/ByteArray2String.java -index d00ccca9..8eed70b8 100644 ---- a/src/main/java/teetime/stage/ByteArray2String.java -+++ b/src/main/java/teetime/stage/ByteArray2String.java -@@ -2,0 +3,2 @@ package teetime.stage; -+import java.nio.charset.Charset; -+ -@@ -12 +14 @@ public class ByteArray2String extends ConsumerStage { -- this.send(this.outputPort, new String(element)); -+ this.send(this.outputPort, new String(element, Charset.forName("UTF-8"))); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/new/ByteArray2String.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/new/ByteArray2String.java deleted file mode 100755 index 8eed70b..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/new/ByteArray2String.java +++ /dev/null @@ -1,20 +0,0 @@ -package teetime.stage; - -import java.nio.charset.Charset; - -import teetime.framework.ConsumerStage; -import teetime.framework.OutputPort; - -public class ByteArray2String extends ConsumerStage { - - private final OutputPort outputPort = this.createOutputPort(); - - @Override - protected void execute(final byte[] element) { - this.send(this.outputPort, new String(element, Charset.forName("UTF-8"))); - } - - public OutputPort getOutputPort() { - return this.outputPort; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/old/ByteArray2String.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/old/ByteArray2String.java deleted file mode 100755 index d00ccca..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/old/ByteArray2String.java +++ /dev/null @@ -1,18 +0,0 @@ -package teetime.stage; - -import teetime.framework.ConsumerStage; -import teetime.framework.OutputPort; - -public class ByteArray2String extends ConsumerStage { - - private final OutputPort outputPort = this.createOutputPort(); - - @Override - protected void execute(final byte[] element) { - this.send(this.outputPort, new String(element)); - } - - public OutputPort getOutputPort() { - return this.outputPort; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/pair.info deleted file mode 100755 index fd8956f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28086/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:28086 -comSha:0b650ceedaace3be4bce73b51aea4544836fdccc -parentComSha:088233e7c66e7e4b2627221c6efd5c8200d46a23 -BuggyFilePath:src/main/java/teetime/stage/ByteArray2String.java -FixedFilePath:src/main/java/teetime/stage/ByteArray2String.java -StartLineNum:12 -EndLineNum:12 -repoName:eXistence#TeeTime \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/comMsg.txt deleted file mode 100755 index efbedb8..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -findbugs: default encoding \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/diff.diff deleted file mode 100755 index 6804631..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/drools-planner-examples/src/main/java/org/drools/planner/examples/machinereassignment/persistence/MachineReassignmentSolutionImporter.java b/drools-planner-examples/src/main/java/org/drools/planner/examples/machinereassignment/persistence/MachineReassignmentSolutionImporter.java -index 0afcd2979..b26aaedf4 100644 ---- a/drools-planner-examples/src/main/java/org/drools/planner/examples/machinereassignment/persistence/MachineReassignmentSolutionImporter.java -+++ b/drools-planner-examples/src/main/java/org/drools/planner/examples/machinereassignment/persistence/MachineReassignmentSolutionImporter.java -@@ -20,0 +21 @@ import java.io.File; -+import java.io.FileInputStream; -@@ -22,0 +24 @@ import java.io.IOException; -+import java.io.InputStreamReader; -@@ -354 +356,2 @@ public class MachineReassignmentSolutionImporter extends AbstractTxtSolutionImpo -- assignmentBufferedReader = new BufferedReader(new FileReader(assignmentInputFile)); -+ assignmentBufferedReader = new BufferedReader(new InputStreamReader( -+ new FileInputStream(assignmentInputFile), "UTF-8")); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/new/MachineReassignmentSolutionImporter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/new/MachineReassignmentSolutionImporter.java deleted file mode 100755 index b26aaed..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/new/MachineReassignmentSolutionImporter.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * Copyright 2011 JBoss 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 org.drools.planner.examples.machinereassignment.persistence; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.io.IOUtils; -import org.drools.planner.core.solution.Solution; -import org.drools.planner.examples.common.persistence.AbstractTxtSolutionImporter; -import org.drools.planner.examples.machinereassignment.domain.MachineReassignment; -import org.drools.planner.examples.machinereassignment.domain.MrBalancePenalty; -import org.drools.planner.examples.machinereassignment.domain.MrMachineCapacity; -import org.drools.planner.examples.machinereassignment.domain.MrGlobalPenaltyInfo; -import org.drools.planner.examples.machinereassignment.domain.MrLocation; -import org.drools.planner.examples.machinereassignment.domain.MrMachine; -import org.drools.planner.examples.machinereassignment.domain.MrMachineMoveCost; -import org.drools.planner.examples.machinereassignment.domain.MrNeighborhood; -import org.drools.planner.examples.machinereassignment.domain.MrProcess; -import org.drools.planner.examples.machinereassignment.domain.MrProcessAssignment; -import org.drools.planner.examples.machinereassignment.domain.MrProcessRequirement; -import org.drools.planner.examples.machinereassignment.domain.MrResource; -import org.drools.planner.examples.machinereassignment.domain.MrService; -import org.drools.planner.examples.machinereassignment.domain.MrServiceDependency; - -public class MachineReassignmentSolutionImporter extends AbstractTxtSolutionImporter { - - public static void main(String[] args) { - new MachineReassignmentSolutionImporter().convertAll(); - } - - public MachineReassignmentSolutionImporter() { - super(new MachineReassignmentDaoImpl()); - } - - @Override - public boolean acceptInputFile(File inputFile) { - return super.acceptInputFile(inputFile) && inputFile.getName().startsWith("model_"); - } - - public TxtInputBuilder createTxtInputBuilder() { - return new MachineReassignmentInputBuilder(); - } - - public class MachineReassignmentInputBuilder extends TxtInputBuilder { - - private MachineReassignment machineReassignment; - - private int resourceListSize; - private List resourceList; - private List serviceList; - private List machineList; - private int processListSize; - private List processList; - - public Solution readSolution() throws IOException { - machineReassignment = new MachineReassignment(); - machineReassignment.setId(0L); - readResourceList(); - readMachineList(); - readServiceList(); - readProcessList(); - readBalancePenaltyList(); - readGlobalPenaltyInfo(); - readProcessAssignmentList(); - logger.info("MachineReassignment with {} resources, {} neighborhoods, {} locations, {} machines," + - " {} services, {} processes and {} balancePenalties.", - new Object[]{machineReassignment.getResourceList().size(), - machineReassignment.getNeighborhoodList().size(), - machineReassignment.getLocationList().size(), - machineReassignment.getMachineList().size(), - machineReassignment.getServiceList().size(), - machineReassignment.getProcessList().size(), - machineReassignment.getBalancePenaltyList().size()}); - BigInteger possibleSolutionSize = BigInteger.valueOf(machineReassignment.getMachineList().size()).pow( - machineReassignment.getProcessList().size()); - String flooredPossibleSolutionSize = "10^" + (possibleSolutionSize.toString().length() - 1); - logger.info("MachineReassignment with flooredPossibleSolutionSize ({}) and possibleSolutionSize ({}).", - flooredPossibleSolutionSize, possibleSolutionSize); - return machineReassignment; - } - - private void readResourceList() throws IOException { - resourceListSize = readIntegerValue(); - resourceList = new ArrayList(resourceListSize); - long resourceId = 0L; - for (int i = 0; i < resourceListSize; i++) { - String line = readStringValue(); - String[] lineTokens = splitBySpace(line, 2); - MrResource resource = new MrResource(); - resource.setId(resourceId); - resource.setIndex(i); - resource.setTransientlyConsumed(parseBooleanFromNumber(lineTokens[0])); - resource.setLoadCostWeight(Integer.parseInt(lineTokens[1])); - resourceList.add(resource); - resourceId++; - } - machineReassignment.setResourceList(resourceList); - } - - private void readMachineList() throws IOException { - int machineListSize = readIntegerValue(); - List neighborhoodList = new ArrayList(machineListSize); - Map idToNeighborhoodMap = new HashMap(machineListSize); - List locationList = new ArrayList(machineListSize); - Map idToLocationMap = new HashMap(machineListSize); - machineList = new ArrayList(machineListSize); - long machineId = 0L; - List machineCapacityList = new ArrayList(machineListSize * resourceListSize); - long machineCapacityId = 0L; - List machineMoveCostList = new ArrayList(machineListSize * machineListSize); - long machineMoveCostId = 0L; - // 2 phases because service dependencies are not in low to high order - for (int i = 0; i < machineListSize; i++) { - MrMachine machine = new MrMachine(); - machine.setId(machineId); - machineList.add(machine); - machineId++; - } - for (int i = 0; i < machineListSize; i++) { - MrMachine machine = machineList.get(i); - String line = readStringValue(); - int moveCostOffset = 2 + (resourceListSize * 2); - String[] lineTokens = splitBySpace(line, moveCostOffset + machineListSize); - long neighborhoodId = Long.parseLong(lineTokens[0]); - MrNeighborhood neighborhood = idToNeighborhoodMap.get(neighborhoodId); - if (neighborhood == null) { - neighborhood = new MrNeighborhood(); - neighborhood.setId(neighborhoodId); - neighborhoodList.add(neighborhood); - idToNeighborhoodMap.put(neighborhoodId, neighborhood); - } - machine.setNeighborhood(neighborhood); - long locationId = Long.parseLong(lineTokens[1]); - MrLocation location = idToLocationMap.get(locationId); - if (location == null) { - location = new MrLocation(); - location.setId(locationId); - locationList.add(location); - idToLocationMap.put(locationId, location); - } - machine.setLocation(location); - List machineCapacityListOfMachine - = new ArrayList(resourceListSize); - for (int j = 0; j < resourceListSize; j++) { - MrMachineCapacity machineCapacity = new MrMachineCapacity(); - machineCapacity.setId(machineCapacityId); - machineCapacity.setMachine(machine); - machineCapacity.setResource(resourceList.get(j)); - machineCapacity.setMaximumCapacity(Integer.parseInt(lineTokens[2 + j])); - machineCapacity.setSafetyCapacity(Integer.parseInt(lineTokens[2 + resourceListSize + j])); - machineCapacityList.add(machineCapacity); - machineCapacityListOfMachine.add(machineCapacity); - machineCapacityId++; - } - machine.setMachineCapacityList(machineCapacityListOfMachine); - Map machineMoveCostMap - = new LinkedHashMap(machineListSize); - for (int j = 0; j < machineListSize; j++) { - MrMachineMoveCost machineMoveCost = new MrMachineMoveCost(); - machineMoveCost.setId(machineMoveCostId); - machineMoveCost.setFromMachine(machine); - MrMachine toMachine = machineList.get(j); - machineMoveCost.setToMachine(toMachine); - machineMoveCost.setMoveCost(Integer.parseInt(lineTokens[moveCostOffset + j])); - machineMoveCostList.add(machineMoveCost); - machineMoveCostMap.put(toMachine, machineMoveCost); - machineMoveCostId++; - } - machine.setMachineMoveCostMap(machineMoveCostMap); - } - machineReassignment.setNeighborhoodList(neighborhoodList); - machineReassignment.setLocationList(locationList); - machineReassignment.setMachineList(machineList); - machineReassignment.setMachineCapacityList(machineCapacityList); - machineReassignment.setMachineMoveCostList(machineMoveCostList); - } - - private void readServiceList() throws IOException { - int serviceListSize = readIntegerValue(); - serviceList = new ArrayList(serviceListSize); - long serviceId = 0L; - // 2 phases because service dependencies are not in low to high order - for (int i = 0; i < serviceListSize; i++) { - MrService service = new MrService(); - service.setId(serviceId); - serviceList.add(service); - serviceId++; - } - List serviceDependencyList = new ArrayList(serviceListSize * 5); - long serviceDependencyId = 0L; - for (int i = 0; i < serviceListSize; i++) { - MrService service = serviceList.get(i); - String line = readStringValue(); - String[] lineTokens = splitBySpace(line); - service.setLocationSpread(Integer.parseInt(lineTokens[0])); - int serviceDependencyListSize = Integer.parseInt(lineTokens[1]); - for (int j = 0; j < serviceDependencyListSize; j++) { - MrServiceDependency serviceDependency = new MrServiceDependency(); - serviceDependency.setId(serviceDependencyId); - serviceDependency.setFromService(service); - int toServiceIndex = Integer.parseInt(lineTokens[2 + j]); - if (toServiceIndex >= serviceList.size()) { - throw new IllegalArgumentException("Service with id (" + serviceId - + ") has a non existing toServiceIndex (" + toServiceIndex + ")."); - } - MrService toService = serviceList.get(toServiceIndex); - serviceDependency.setToService(toService); - serviceDependencyList.add(serviceDependency); - serviceDependencyId++; - } - int numberOfTokens = 2 + serviceDependencyListSize; - if (lineTokens.length != numberOfTokens) { - throw new IllegalArgumentException("Read line (" + line + ") has " + lineTokens.length - + " tokens but is expected to contain " + numberOfTokens + " tokens separated by space."); - } - } - machineReassignment.setServiceList(serviceList); - machineReassignment.setServiceDependencyList(serviceDependencyList); - } - - private void readProcessList() throws IOException { - processListSize = readIntegerValue(); - processList = new ArrayList(processListSize); - long processId = 0L; - long processRequirementId = 0L; - for (int i = 0; i < processListSize; i++) { - String line = readStringValue(); - String[] lineTokens = splitBySpace(line, 2 + resourceListSize); - MrProcess process = new MrProcess(); - process.setId(processId); - int serviceIndex = Integer.parseInt(lineTokens[0]); - if (serviceIndex >= serviceList.size()) { - throw new IllegalArgumentException("Process with id (" + processId - + ") has a non existing serviceIndex (" + serviceIndex + ")."); - } - MrService service = serviceList.get(serviceIndex); - process.setService(service); - List processRequirementList - = new ArrayList(resourceListSize); - for (int j = 0; j < resourceListSize; j++) { - MrProcessRequirement processRequirement = new MrProcessRequirement(); - processRequirement.setId(processRequirementId); - processRequirement.setProcess(process); - processRequirement.setResource(resourceList.get(j)); - processRequirement.setUsage(Integer.parseInt(lineTokens[1 + j])); - processRequirementList.add(processRequirement); - processRequirementId++; - } - process.setProcessRequirementList(processRequirementList); - process.setMoveCost(Integer.parseInt(lineTokens[1 + resourceListSize])); - processList.add(process); - processId++; - } - machineReassignment.setProcessList(processList); - } - - private void readBalancePenaltyList() throws IOException { - int balancePenaltyListSize = readIntegerValue(); - List balancePenaltyList = new ArrayList(balancePenaltyListSize); - long balancePenaltyId = 0L; - for (int i = 0; i < balancePenaltyListSize; i++) { - String line = readStringValue(); - String[] lineTokens = splitBySpace(line, 3); - MrBalancePenalty balancePenalty = new MrBalancePenalty(); - balancePenalty.setId(balancePenaltyId); - int originResourceIndex = Integer.parseInt(lineTokens[0]); - if (originResourceIndex >= resourceListSize) { - throw new IllegalArgumentException("BalancePenalty with id (" + balancePenaltyId - + ") has a non existing originResourceIndex (" + originResourceIndex + ")."); - } - balancePenalty.setOriginResource(resourceList.get(originResourceIndex)); - int targetResourceIndex = Integer.parseInt(lineTokens[1]); - if (targetResourceIndex >= resourceListSize) { - throw new IllegalArgumentException("BalancePenalty with id (" + balancePenaltyId - + ") has a non existing targetResourceIndex (" + targetResourceIndex + ")."); - } - balancePenalty.setTargetResource(resourceList.get(targetResourceIndex)); - balancePenalty.setMultiplicand(Integer.parseInt(lineTokens[2])); - // Read a new line (weird in the input definition) - balancePenalty.setWeight(readIntegerValue()); - balancePenaltyList.add(balancePenalty); - balancePenaltyId++; - } - machineReassignment.setBalancePenaltyList(balancePenaltyList); - } - - private void readGlobalPenaltyInfo() throws IOException { - MrGlobalPenaltyInfo globalPenaltyInfo = new MrGlobalPenaltyInfo(); - globalPenaltyInfo.setId(0L); - String line = readStringValue(); - String[] lineTokens = splitBySpace(line, 3); - globalPenaltyInfo.setProcessMoveCostWeight(Integer.parseInt(lineTokens[0])); - globalPenaltyInfo.setServiceMoveCostWeight(Integer.parseInt(lineTokens[1])); - globalPenaltyInfo.setMachineMoveCostWeight(Integer.parseInt(lineTokens[2])); - machineReassignment.setGlobalPenaltyInfo(globalPenaltyInfo); - } - - private void readProcessAssignmentList() { - String line = readOriginalProcessAssignmentLine(); - String[] lineTokens = splitBySpace(line, processListSize); - List processAssignmentList = new ArrayList(processListSize); - long processAssignmentId = 0L; - for (int i = 0; i < processListSize; i++) { - MrProcessAssignment processAssignment = new MrProcessAssignment(); - processAssignment.setId(processAssignmentId); - processAssignment.setProcess(processList.get(i)); - int machineIndex = Integer.parseInt(lineTokens[i]); - if (machineIndex >= machineList.size()) { - throw new IllegalArgumentException("ProcessAssignment with id (" + processAssignmentId - + ") has a non existing machineIndex (" + machineIndex + ")."); - } - processAssignment.setOriginalMachine(machineList.get(machineIndex)); - // Notice that we leave the PlanningVariable properties on null - processAssignmentList.add(processAssignment); - processAssignmentId++; - } - machineReassignment.setProcessAssignmentList(processAssignmentList); - } - - private String readOriginalProcessAssignmentLine() { - String inputFileName = inputFile.getName(); - String inputFilePrefix = "model_"; - if (!inputFileName.startsWith(inputFilePrefix)) { - throw new IllegalArgumentException("The inputFile (" + inputFile - + ") is expected to start with \"" + inputFilePrefix + "\"."); - } - File assignmentInputFile = new File(inputFile.getParent(), - inputFileName.replaceFirst(inputFilePrefix, "assignment_")); - BufferedReader assignmentBufferedReader = null; - try { - assignmentBufferedReader = new BufferedReader(new InputStreamReader( - new FileInputStream(assignmentInputFile), "UTF-8")); - try { - return assignmentBufferedReader.readLine(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Exception in assignmentInputFile (" - + assignmentInputFile + ")", e); - } catch (IllegalStateException e) { - throw new IllegalStateException("Exception in assignmentInputFile (" - + assignmentInputFile + ")", e); - } - } catch (IOException e) { - throw new IllegalArgumentException("Could not read the file (" + assignmentInputFile.getName() + ").", e); - } finally { - IOUtils.closeQuietly(assignmentBufferedReader); - } - } - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/old/MachineReassignmentSolutionImporter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/old/MachineReassignmentSolutionImporter.java deleted file mode 100755 index 0afcd29..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/old/MachineReassignmentSolutionImporter.java +++ /dev/null @@ -1,373 +0,0 @@ -/* - * Copyright 2011 JBoss 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 org.drools.planner.examples.machinereassignment.persistence; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.commons.io.IOUtils; -import org.drools.planner.core.solution.Solution; -import org.drools.planner.examples.common.persistence.AbstractTxtSolutionImporter; -import org.drools.planner.examples.machinereassignment.domain.MachineReassignment; -import org.drools.planner.examples.machinereassignment.domain.MrBalancePenalty; -import org.drools.planner.examples.machinereassignment.domain.MrMachineCapacity; -import org.drools.planner.examples.machinereassignment.domain.MrGlobalPenaltyInfo; -import org.drools.planner.examples.machinereassignment.domain.MrLocation; -import org.drools.planner.examples.machinereassignment.domain.MrMachine; -import org.drools.planner.examples.machinereassignment.domain.MrMachineMoveCost; -import org.drools.planner.examples.machinereassignment.domain.MrNeighborhood; -import org.drools.planner.examples.machinereassignment.domain.MrProcess; -import org.drools.planner.examples.machinereassignment.domain.MrProcessAssignment; -import org.drools.planner.examples.machinereassignment.domain.MrProcessRequirement; -import org.drools.planner.examples.machinereassignment.domain.MrResource; -import org.drools.planner.examples.machinereassignment.domain.MrService; -import org.drools.planner.examples.machinereassignment.domain.MrServiceDependency; - -public class MachineReassignmentSolutionImporter extends AbstractTxtSolutionImporter { - - public static void main(String[] args) { - new MachineReassignmentSolutionImporter().convertAll(); - } - - public MachineReassignmentSolutionImporter() { - super(new MachineReassignmentDaoImpl()); - } - - @Override - public boolean acceptInputFile(File inputFile) { - return super.acceptInputFile(inputFile) && inputFile.getName().startsWith("model_"); - } - - public TxtInputBuilder createTxtInputBuilder() { - return new MachineReassignmentInputBuilder(); - } - - public class MachineReassignmentInputBuilder extends TxtInputBuilder { - - private MachineReassignment machineReassignment; - - private int resourceListSize; - private List resourceList; - private List serviceList; - private List machineList; - private int processListSize; - private List processList; - - public Solution readSolution() throws IOException { - machineReassignment = new MachineReassignment(); - machineReassignment.setId(0L); - readResourceList(); - readMachineList(); - readServiceList(); - readProcessList(); - readBalancePenaltyList(); - readGlobalPenaltyInfo(); - readProcessAssignmentList(); - logger.info("MachineReassignment with {} resources, {} neighborhoods, {} locations, {} machines," + - " {} services, {} processes and {} balancePenalties.", - new Object[]{machineReassignment.getResourceList().size(), - machineReassignment.getNeighborhoodList().size(), - machineReassignment.getLocationList().size(), - machineReassignment.getMachineList().size(), - machineReassignment.getServiceList().size(), - machineReassignment.getProcessList().size(), - machineReassignment.getBalancePenaltyList().size()}); - BigInteger possibleSolutionSize = BigInteger.valueOf(machineReassignment.getMachineList().size()).pow( - machineReassignment.getProcessList().size()); - String flooredPossibleSolutionSize = "10^" + (possibleSolutionSize.toString().length() - 1); - logger.info("MachineReassignment with flooredPossibleSolutionSize ({}) and possibleSolutionSize ({}).", - flooredPossibleSolutionSize, possibleSolutionSize); - return machineReassignment; - } - - private void readResourceList() throws IOException { - resourceListSize = readIntegerValue(); - resourceList = new ArrayList(resourceListSize); - long resourceId = 0L; - for (int i = 0; i < resourceListSize; i++) { - String line = readStringValue(); - String[] lineTokens = splitBySpace(line, 2); - MrResource resource = new MrResource(); - resource.setId(resourceId); - resource.setIndex(i); - resource.setTransientlyConsumed(parseBooleanFromNumber(lineTokens[0])); - resource.setLoadCostWeight(Integer.parseInt(lineTokens[1])); - resourceList.add(resource); - resourceId++; - } - machineReassignment.setResourceList(resourceList); - } - - private void readMachineList() throws IOException { - int machineListSize = readIntegerValue(); - List neighborhoodList = new ArrayList(machineListSize); - Map idToNeighborhoodMap = new HashMap(machineListSize); - List locationList = new ArrayList(machineListSize); - Map idToLocationMap = new HashMap(machineListSize); - machineList = new ArrayList(machineListSize); - long machineId = 0L; - List machineCapacityList = new ArrayList(machineListSize * resourceListSize); - long machineCapacityId = 0L; - List machineMoveCostList = new ArrayList(machineListSize * machineListSize); - long machineMoveCostId = 0L; - // 2 phases because service dependencies are not in low to high order - for (int i = 0; i < machineListSize; i++) { - MrMachine machine = new MrMachine(); - machine.setId(machineId); - machineList.add(machine); - machineId++; - } - for (int i = 0; i < machineListSize; i++) { - MrMachine machine = machineList.get(i); - String line = readStringValue(); - int moveCostOffset = 2 + (resourceListSize * 2); - String[] lineTokens = splitBySpace(line, moveCostOffset + machineListSize); - long neighborhoodId = Long.parseLong(lineTokens[0]); - MrNeighborhood neighborhood = idToNeighborhoodMap.get(neighborhoodId); - if (neighborhood == null) { - neighborhood = new MrNeighborhood(); - neighborhood.setId(neighborhoodId); - neighborhoodList.add(neighborhood); - idToNeighborhoodMap.put(neighborhoodId, neighborhood); - } - machine.setNeighborhood(neighborhood); - long locationId = Long.parseLong(lineTokens[1]); - MrLocation location = idToLocationMap.get(locationId); - if (location == null) { - location = new MrLocation(); - location.setId(locationId); - locationList.add(location); - idToLocationMap.put(locationId, location); - } - machine.setLocation(location); - List machineCapacityListOfMachine - = new ArrayList(resourceListSize); - for (int j = 0; j < resourceListSize; j++) { - MrMachineCapacity machineCapacity = new MrMachineCapacity(); - machineCapacity.setId(machineCapacityId); - machineCapacity.setMachine(machine); - machineCapacity.setResource(resourceList.get(j)); - machineCapacity.setMaximumCapacity(Integer.parseInt(lineTokens[2 + j])); - machineCapacity.setSafetyCapacity(Integer.parseInt(lineTokens[2 + resourceListSize + j])); - machineCapacityList.add(machineCapacity); - machineCapacityListOfMachine.add(machineCapacity); - machineCapacityId++; - } - machine.setMachineCapacityList(machineCapacityListOfMachine); - Map machineMoveCostMap - = new LinkedHashMap(machineListSize); - for (int j = 0; j < machineListSize; j++) { - MrMachineMoveCost machineMoveCost = new MrMachineMoveCost(); - machineMoveCost.setId(machineMoveCostId); - machineMoveCost.setFromMachine(machine); - MrMachine toMachine = machineList.get(j); - machineMoveCost.setToMachine(toMachine); - machineMoveCost.setMoveCost(Integer.parseInt(lineTokens[moveCostOffset + j])); - machineMoveCostList.add(machineMoveCost); - machineMoveCostMap.put(toMachine, machineMoveCost); - machineMoveCostId++; - } - machine.setMachineMoveCostMap(machineMoveCostMap); - } - machineReassignment.setNeighborhoodList(neighborhoodList); - machineReassignment.setLocationList(locationList); - machineReassignment.setMachineList(machineList); - machineReassignment.setMachineCapacityList(machineCapacityList); - machineReassignment.setMachineMoveCostList(machineMoveCostList); - } - - private void readServiceList() throws IOException { - int serviceListSize = readIntegerValue(); - serviceList = new ArrayList(serviceListSize); - long serviceId = 0L; - // 2 phases because service dependencies are not in low to high order - for (int i = 0; i < serviceListSize; i++) { - MrService service = new MrService(); - service.setId(serviceId); - serviceList.add(service); - serviceId++; - } - List serviceDependencyList = new ArrayList(serviceListSize * 5); - long serviceDependencyId = 0L; - for (int i = 0; i < serviceListSize; i++) { - MrService service = serviceList.get(i); - String line = readStringValue(); - String[] lineTokens = splitBySpace(line); - service.setLocationSpread(Integer.parseInt(lineTokens[0])); - int serviceDependencyListSize = Integer.parseInt(lineTokens[1]); - for (int j = 0; j < serviceDependencyListSize; j++) { - MrServiceDependency serviceDependency = new MrServiceDependency(); - serviceDependency.setId(serviceDependencyId); - serviceDependency.setFromService(service); - int toServiceIndex = Integer.parseInt(lineTokens[2 + j]); - if (toServiceIndex >= serviceList.size()) { - throw new IllegalArgumentException("Service with id (" + serviceId - + ") has a non existing toServiceIndex (" + toServiceIndex + ")."); - } - MrService toService = serviceList.get(toServiceIndex); - serviceDependency.setToService(toService); - serviceDependencyList.add(serviceDependency); - serviceDependencyId++; - } - int numberOfTokens = 2 + serviceDependencyListSize; - if (lineTokens.length != numberOfTokens) { - throw new IllegalArgumentException("Read line (" + line + ") has " + lineTokens.length - + " tokens but is expected to contain " + numberOfTokens + " tokens separated by space."); - } - } - machineReassignment.setServiceList(serviceList); - machineReassignment.setServiceDependencyList(serviceDependencyList); - } - - private void readProcessList() throws IOException { - processListSize = readIntegerValue(); - processList = new ArrayList(processListSize); - long processId = 0L; - long processRequirementId = 0L; - for (int i = 0; i < processListSize; i++) { - String line = readStringValue(); - String[] lineTokens = splitBySpace(line, 2 + resourceListSize); - MrProcess process = new MrProcess(); - process.setId(processId); - int serviceIndex = Integer.parseInt(lineTokens[0]); - if (serviceIndex >= serviceList.size()) { - throw new IllegalArgumentException("Process with id (" + processId - + ") has a non existing serviceIndex (" + serviceIndex + ")."); - } - MrService service = serviceList.get(serviceIndex); - process.setService(service); - List processRequirementList - = new ArrayList(resourceListSize); - for (int j = 0; j < resourceListSize; j++) { - MrProcessRequirement processRequirement = new MrProcessRequirement(); - processRequirement.setId(processRequirementId); - processRequirement.setProcess(process); - processRequirement.setResource(resourceList.get(j)); - processRequirement.setUsage(Integer.parseInt(lineTokens[1 + j])); - processRequirementList.add(processRequirement); - processRequirementId++; - } - process.setProcessRequirementList(processRequirementList); - process.setMoveCost(Integer.parseInt(lineTokens[1 + resourceListSize])); - processList.add(process); - processId++; - } - machineReassignment.setProcessList(processList); - } - - private void readBalancePenaltyList() throws IOException { - int balancePenaltyListSize = readIntegerValue(); - List balancePenaltyList = new ArrayList(balancePenaltyListSize); - long balancePenaltyId = 0L; - for (int i = 0; i < balancePenaltyListSize; i++) { - String line = readStringValue(); - String[] lineTokens = splitBySpace(line, 3); - MrBalancePenalty balancePenalty = new MrBalancePenalty(); - balancePenalty.setId(balancePenaltyId); - int originResourceIndex = Integer.parseInt(lineTokens[0]); - if (originResourceIndex >= resourceListSize) { - throw new IllegalArgumentException("BalancePenalty with id (" + balancePenaltyId - + ") has a non existing originResourceIndex (" + originResourceIndex + ")."); - } - balancePenalty.setOriginResource(resourceList.get(originResourceIndex)); - int targetResourceIndex = Integer.parseInt(lineTokens[1]); - if (targetResourceIndex >= resourceListSize) { - throw new IllegalArgumentException("BalancePenalty with id (" + balancePenaltyId - + ") has a non existing targetResourceIndex (" + targetResourceIndex + ")."); - } - balancePenalty.setTargetResource(resourceList.get(targetResourceIndex)); - balancePenalty.setMultiplicand(Integer.parseInt(lineTokens[2])); - // Read a new line (weird in the input definition) - balancePenalty.setWeight(readIntegerValue()); - balancePenaltyList.add(balancePenalty); - balancePenaltyId++; - } - machineReassignment.setBalancePenaltyList(balancePenaltyList); - } - - private void readGlobalPenaltyInfo() throws IOException { - MrGlobalPenaltyInfo globalPenaltyInfo = new MrGlobalPenaltyInfo(); - globalPenaltyInfo.setId(0L); - String line = readStringValue(); - String[] lineTokens = splitBySpace(line, 3); - globalPenaltyInfo.setProcessMoveCostWeight(Integer.parseInt(lineTokens[0])); - globalPenaltyInfo.setServiceMoveCostWeight(Integer.parseInt(lineTokens[1])); - globalPenaltyInfo.setMachineMoveCostWeight(Integer.parseInt(lineTokens[2])); - machineReassignment.setGlobalPenaltyInfo(globalPenaltyInfo); - } - - private void readProcessAssignmentList() { - String line = readOriginalProcessAssignmentLine(); - String[] lineTokens = splitBySpace(line, processListSize); - List processAssignmentList = new ArrayList(processListSize); - long processAssignmentId = 0L; - for (int i = 0; i < processListSize; i++) { - MrProcessAssignment processAssignment = new MrProcessAssignment(); - processAssignment.setId(processAssignmentId); - processAssignment.setProcess(processList.get(i)); - int machineIndex = Integer.parseInt(lineTokens[i]); - if (machineIndex >= machineList.size()) { - throw new IllegalArgumentException("ProcessAssignment with id (" + processAssignmentId - + ") has a non existing machineIndex (" + machineIndex + ")."); - } - processAssignment.setOriginalMachine(machineList.get(machineIndex)); - // Notice that we leave the PlanningVariable properties on null - processAssignmentList.add(processAssignment); - processAssignmentId++; - } - machineReassignment.setProcessAssignmentList(processAssignmentList); - } - - private String readOriginalProcessAssignmentLine() { - String inputFileName = inputFile.getName(); - String inputFilePrefix = "model_"; - if (!inputFileName.startsWith(inputFilePrefix)) { - throw new IllegalArgumentException("The inputFile (" + inputFile - + ") is expected to start with \"" + inputFilePrefix + "\"."); - } - File assignmentInputFile = new File(inputFile.getParent(), - inputFileName.replaceFirst(inputFilePrefix, "assignment_")); - BufferedReader assignmentBufferedReader = null; - try { - assignmentBufferedReader = new BufferedReader(new FileReader(assignmentInputFile)); - try { - return assignmentBufferedReader.readLine(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Exception in assignmentInputFile (" - + assignmentInputFile + ")", e); - } catch (IllegalStateException e) { - throw new IllegalStateException("Exception in assignmentInputFile (" - + assignmentInputFile + ")", e); - } - } catch (IOException e) { - throw new IllegalArgumentException("Could not read the file (" + assignmentInputFile.getName() + ").", e); - } finally { - IOUtils.closeQuietly(assignmentBufferedReader); - } - } - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/pair.info deleted file mode 100755 index a5dfa69..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28809/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:28809 -comSha:291305f54d705ab6432a59e3c95743ac5656e512 -parentComSha:19ec8ffd5c6fc6adceaab3ccdfb6977e03352bcc -BuggyFilePath:drools-planner-examples/src/main/java/org/drools/planner/examples/machinereassignment/persistence/MachineReassignmentSolutionImporter.java -FixedFilePath:drools-planner-examples/src/main/java/org/drools/planner/examples/machinereassignment/persistence/MachineReassignmentSolutionImporter.java -StartLineNum:354 -EndLineNum:354 -repoName:droolsjbpm#optaplanner \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/comMsg.txt deleted file mode 100755 index efbedb8..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -findbugs: default encoding \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/diff.diff deleted file mode 100755 index ac9252b..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtSolutionImporter.java b/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtSolutionImporter.java -index 5d6c295e5..7eb3e300c 100644 ---- a/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtSolutionImporter.java -+++ b/drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtSolutionImporter.java -@@ -20,0 +21 @@ import java.io.File; -+import java.io.FileInputStream; -@@ -22,0 +24 @@ import java.io.IOException; -+import java.io.InputStreamReader; -@@ -44 +46 @@ public abstract class AbstractTxtSolutionImporter extends AbstractSolutionImport -- bufferedReader = new BufferedReader(new FileReader(inputFile)); -+ bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/new/AbstractTxtSolutionImporter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/new/AbstractTxtSolutionImporter.java deleted file mode 100755 index 7eb3e30..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/new/AbstractTxtSolutionImporter.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Copyright 2010 JBoss 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 org.drools.planner.examples.common.persistence; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; - -import org.apache.commons.io.IOUtils; -import org.drools.planner.core.solution.Solution; - -public abstract class AbstractTxtSolutionImporter extends AbstractSolutionImporter { - - private static final String DEFAULT_INPUT_FILE_SUFFIX = ".txt"; - - protected AbstractTxtSolutionImporter(SolutionDao solutionDao) { - super(solutionDao); - } - - protected String getInputFileSuffix() { - return DEFAULT_INPUT_FILE_SUFFIX; - } - - public abstract TxtInputBuilder createTxtInputBuilder(); - - public Solution readSolution(File inputFile) { - BufferedReader bufferedReader = null; - try { - bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFile), "UTF-8")); - TxtInputBuilder txtInputBuilder = createTxtInputBuilder(); - txtInputBuilder.setInputFile(inputFile); - txtInputBuilder.setBufferedReader(bufferedReader); - try { - return txtInputBuilder.readSolution(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Exception in inputFile (" + inputFile + ")", e); - } catch (IllegalStateException e) { - throw new IllegalStateException("Exception in inputFile (" + inputFile + ")", e); - } - } catch (IOException e) { - throw new IllegalArgumentException("Could not read the file (" + inputFile.getName() + ").", e); - } finally { - IOUtils.closeQuietly(bufferedReader); - } - } - - public abstract class TxtInputBuilder { - - protected File inputFile; - protected BufferedReader bufferedReader; - - public void setInputFile(File inputFile) { - this.inputFile = inputFile; - } - - public void setBufferedReader(BufferedReader bufferedReader) { - this.bufferedReader = bufferedReader; - } - - public abstract Solution readSolution() throws IOException; - - // ************************************************************************ - // Helper methods - // ************************************************************************ - - public void readEmptyLine() throws IOException { - readConstantLine(""); - } - - public void readConstantLine(String constantValue) throws IOException { - String line = bufferedReader.readLine(); - if (line == null) { - throw new IllegalArgumentException("File ends before a line is expected to be a constant value (" - + constantValue + ")."); - } - String value = line.trim(); - if (!value.equals(constantValue)) { - throw new IllegalArgumentException("Read line (" + line + ") is expected to be a constant value (" - + constantValue + ")."); - } - } - - public void readUntilConstantLine(String constantValue) throws IOException { - String line; - String value; - do { - line = bufferedReader.readLine(); - if (line == null) { - throw new IllegalArgumentException("File ends before a line is expected to be a constant value (" - + constantValue + ")."); - } - value = line.trim(); - } while (!value.equals(constantValue)); - } - - public int readIntegerValue() throws IOException { - return readIntegerValue(""); - } - - public int readIntegerValue(String prefix) throws IOException { - return readIntegerValue(prefix, ""); - } - - public int readIntegerValue(String prefix, String suffix) throws IOException { - String line = bufferedReader.readLine(); - if (line == null) { - throw new IllegalArgumentException("File ends before a line is expected to contain an integer value (" - + prefix + "" + suffix + ")."); - } - String value = removePrefixSuffixFromLine(line, prefix, suffix); - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Read line (" + line + ") is expected to contain an integer value (" - + value + ").", e); - } - } - - public String readStringValue() throws IOException { - return readStringValue(""); - } - - public String readStringValue(String prefix) throws IOException { - return readStringValue(prefix, ""); - } - - public String readStringValue(String prefix, String suffix) throws IOException { - String line = bufferedReader.readLine(); - if (line == null) { - throw new IllegalArgumentException("File ends before a line is expected to contain an string value (" - + prefix + "" + suffix + ")."); - } - return removePrefixSuffixFromLine(line, prefix, suffix); - } - - public String removePrefixSuffixFromLine(String line, String prefix, String suffix) { - String value = line.trim(); - if (!value.startsWith(prefix)) { - throw new IllegalArgumentException("Read line (" + line + ") is expected to start with prefix (" - + prefix + ")."); - } - value = value.substring(prefix.length()); - if (!value.endsWith(suffix)) { - throw new IllegalArgumentException("Read line (" + line + ") is expected to end with suffix (" - + suffix + ")."); - } - value = value.substring(0, value.length() - suffix.length()); - value = value.trim(); - return value; - } - - public String[] splitBySpace(String line) { - return splitBySpace(line, null); - } - - public String[] splitBySpace(String line, Integer numberOfTokens) { - return splitBy(line, "\\ ", "a space ( )", numberOfTokens, false, false); - } - - public String[] splitBySpace(String line, Integer minimumNumberOfTokens, Integer maximumNumberOfTokens) { - return splitBy(line, "\\ ", "a space ( )", minimumNumberOfTokens, maximumNumberOfTokens, false, false); - } - - public String[] splitBySpacesOrTabs(String line) { - return splitBySpacesOrTabs(line, null); - } - - public String[] splitBySpacesOrTabs(String line, Integer numberOfTokens) { - return splitBy(line, "[\\ \\t]+", "spaces or tabs", numberOfTokens, false, false); - } - - public String[] splitByPipelineAndTrim(String line, int numberOfTokens) { - return splitBy(line, "\\|", "a pipeline (|)", numberOfTokens, true, false); - } - - public String[] splitBySemicolonSeparatedValue(String line, int numberOfTokens) { - return splitBy(line, ";", "a semicolon (;)", numberOfTokens, false, true); - } - - public String[] splitBy(String line, String tokenRegex, String tokenName, - Integer numberOfTokens, boolean trim, boolean removeQuotes) { - return splitBy(line, tokenRegex, tokenName, numberOfTokens, numberOfTokens, trim, removeQuotes); - } - - public String[] splitBy(String line, String tokenRegex, String tokenName, - Integer minimumNumberOfTokens, Integer maximumNumberOfTokens, boolean trim, boolean removeQuotes) { - String[] lineTokens = line.split(tokenRegex); - if (minimumNumberOfTokens != null && lineTokens.length < minimumNumberOfTokens) { - throw new IllegalArgumentException("Read line (" + line + ") has " + lineTokens.length - + " tokens but is expected to contain at least " + minimumNumberOfTokens - + " tokens separated by " + tokenName + "."); - } - if (maximumNumberOfTokens != null && lineTokens.length > maximumNumberOfTokens) { - throw new IllegalArgumentException("Read line (" + line + ") has " + lineTokens.length - + " tokens but is expected to contain at most " + maximumNumberOfTokens - + " tokens separated by " + tokenName + "."); - } - if (trim) { - for (int i = 0; i < lineTokens.length; i++) { - lineTokens[i] = lineTokens[i].trim(); - } - } - if (removeQuotes) { - for (int i = 0; i < lineTokens.length; i++) { - if (lineTokens[i].startsWith("\"") && lineTokens[i].endsWith("\"")) { - lineTokens[i] = lineTokens[i].substring(1, lineTokens[i].length() - 1); - } - } - } - return lineTokens; - } - - public boolean parseBooleanFromNumber(String token) { - if (token.equals("0")) { - return false; - } else if (token.equals("1")) { - return true; - } else { - throw new IllegalArgumentException("The token (" + token - + ") is expected to be 0 or 1 representing a boolean."); - } - } - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/old/AbstractTxtSolutionImporter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/old/AbstractTxtSolutionImporter.java deleted file mode 100755 index 5d6c295..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/old/AbstractTxtSolutionImporter.java +++ /dev/null @@ -1,241 +0,0 @@ -/* - * Copyright 2010 JBoss 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 org.drools.planner.examples.common.persistence; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; - -import org.apache.commons.io.IOUtils; -import org.drools.planner.core.solution.Solution; - -public abstract class AbstractTxtSolutionImporter extends AbstractSolutionImporter { - - private static final String DEFAULT_INPUT_FILE_SUFFIX = ".txt"; - - protected AbstractTxtSolutionImporter(SolutionDao solutionDao) { - super(solutionDao); - } - - protected String getInputFileSuffix() { - return DEFAULT_INPUT_FILE_SUFFIX; - } - - public abstract TxtInputBuilder createTxtInputBuilder(); - - public Solution readSolution(File inputFile) { - BufferedReader bufferedReader = null; - try { - bufferedReader = new BufferedReader(new FileReader(inputFile)); - TxtInputBuilder txtInputBuilder = createTxtInputBuilder(); - txtInputBuilder.setInputFile(inputFile); - txtInputBuilder.setBufferedReader(bufferedReader); - try { - return txtInputBuilder.readSolution(); - } catch (IllegalArgumentException e) { - throw new IllegalArgumentException("Exception in inputFile (" + inputFile + ")", e); - } catch (IllegalStateException e) { - throw new IllegalStateException("Exception in inputFile (" + inputFile + ")", e); - } - } catch (IOException e) { - throw new IllegalArgumentException("Could not read the file (" + inputFile.getName() + ").", e); - } finally { - IOUtils.closeQuietly(bufferedReader); - } - } - - public abstract class TxtInputBuilder { - - protected File inputFile; - protected BufferedReader bufferedReader; - - public void setInputFile(File inputFile) { - this.inputFile = inputFile; - } - - public void setBufferedReader(BufferedReader bufferedReader) { - this.bufferedReader = bufferedReader; - } - - public abstract Solution readSolution() throws IOException; - - // ************************************************************************ - // Helper methods - // ************************************************************************ - - public void readEmptyLine() throws IOException { - readConstantLine(""); - } - - public void readConstantLine(String constantValue) throws IOException { - String line = bufferedReader.readLine(); - if (line == null) { - throw new IllegalArgumentException("File ends before a line is expected to be a constant value (" - + constantValue + ")."); - } - String value = line.trim(); - if (!value.equals(constantValue)) { - throw new IllegalArgumentException("Read line (" + line + ") is expected to be a constant value (" - + constantValue + ")."); - } - } - - public void readUntilConstantLine(String constantValue) throws IOException { - String line; - String value; - do { - line = bufferedReader.readLine(); - if (line == null) { - throw new IllegalArgumentException("File ends before a line is expected to be a constant value (" - + constantValue + ")."); - } - value = line.trim(); - } while (!value.equals(constantValue)); - } - - public int readIntegerValue() throws IOException { - return readIntegerValue(""); - } - - public int readIntegerValue(String prefix) throws IOException { - return readIntegerValue(prefix, ""); - } - - public int readIntegerValue(String prefix, String suffix) throws IOException { - String line = bufferedReader.readLine(); - if (line == null) { - throw new IllegalArgumentException("File ends before a line is expected to contain an integer value (" - + prefix + "" + suffix + ")."); - } - String value = removePrefixSuffixFromLine(line, prefix, suffix); - try { - return Integer.parseInt(value); - } catch (NumberFormatException e) { - throw new IllegalArgumentException("Read line (" + line + ") is expected to contain an integer value (" - + value + ").", e); - } - } - - public String readStringValue() throws IOException { - return readStringValue(""); - } - - public String readStringValue(String prefix) throws IOException { - return readStringValue(prefix, ""); - } - - public String readStringValue(String prefix, String suffix) throws IOException { - String line = bufferedReader.readLine(); - if (line == null) { - throw new IllegalArgumentException("File ends before a line is expected to contain an string value (" - + prefix + "" + suffix + ")."); - } - return removePrefixSuffixFromLine(line, prefix, suffix); - } - - public String removePrefixSuffixFromLine(String line, String prefix, String suffix) { - String value = line.trim(); - if (!value.startsWith(prefix)) { - throw new IllegalArgumentException("Read line (" + line + ") is expected to start with prefix (" - + prefix + ")."); - } - value = value.substring(prefix.length()); - if (!value.endsWith(suffix)) { - throw new IllegalArgumentException("Read line (" + line + ") is expected to end with suffix (" - + suffix + ")."); - } - value = value.substring(0, value.length() - suffix.length()); - value = value.trim(); - return value; - } - - public String[] splitBySpace(String line) { - return splitBySpace(line, null); - } - - public String[] splitBySpace(String line, Integer numberOfTokens) { - return splitBy(line, "\\ ", "a space ( )", numberOfTokens, false, false); - } - - public String[] splitBySpace(String line, Integer minimumNumberOfTokens, Integer maximumNumberOfTokens) { - return splitBy(line, "\\ ", "a space ( )", minimumNumberOfTokens, maximumNumberOfTokens, false, false); - } - - public String[] splitBySpacesOrTabs(String line) { - return splitBySpacesOrTabs(line, null); - } - - public String[] splitBySpacesOrTabs(String line, Integer numberOfTokens) { - return splitBy(line, "[\\ \\t]+", "spaces or tabs", numberOfTokens, false, false); - } - - public String[] splitByPipelineAndTrim(String line, int numberOfTokens) { - return splitBy(line, "\\|", "a pipeline (|)", numberOfTokens, true, false); - } - - public String[] splitBySemicolonSeparatedValue(String line, int numberOfTokens) { - return splitBy(line, ";", "a semicolon (;)", numberOfTokens, false, true); - } - - public String[] splitBy(String line, String tokenRegex, String tokenName, - Integer numberOfTokens, boolean trim, boolean removeQuotes) { - return splitBy(line, tokenRegex, tokenName, numberOfTokens, numberOfTokens, trim, removeQuotes); - } - - public String[] splitBy(String line, String tokenRegex, String tokenName, - Integer minimumNumberOfTokens, Integer maximumNumberOfTokens, boolean trim, boolean removeQuotes) { - String[] lineTokens = line.split(tokenRegex); - if (minimumNumberOfTokens != null && lineTokens.length < minimumNumberOfTokens) { - throw new IllegalArgumentException("Read line (" + line + ") has " + lineTokens.length - + " tokens but is expected to contain at least " + minimumNumberOfTokens - + " tokens separated by " + tokenName + "."); - } - if (maximumNumberOfTokens != null && lineTokens.length > maximumNumberOfTokens) { - throw new IllegalArgumentException("Read line (" + line + ") has " + lineTokens.length - + " tokens but is expected to contain at most " + maximumNumberOfTokens - + " tokens separated by " + tokenName + "."); - } - if (trim) { - for (int i = 0; i < lineTokens.length; i++) { - lineTokens[i] = lineTokens[i].trim(); - } - } - if (removeQuotes) { - for (int i = 0; i < lineTokens.length; i++) { - if (lineTokens[i].startsWith("\"") && lineTokens[i].endsWith("\"")) { - lineTokens[i] = lineTokens[i].substring(1, lineTokens[i].length() - 1); - } - } - } - return lineTokens; - } - - public boolean parseBooleanFromNumber(String token) { - if (token.equals("0")) { - return false; - } else if (token.equals("1")) { - return true; - } else { - throw new IllegalArgumentException("The token (" + token - + ") is expected to be 0 or 1 representing a boolean."); - } - } - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/pair.info deleted file mode 100755 index 21c49e0..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#28897/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:28897 -comSha:8682ca1685e30c067d5507b3bae568948d06fa7d -parentComSha:69a9374d15cb390f5576df67782a1ded2b009552 -BuggyFilePath:drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtSolutionImporter.java -FixedFilePath:drools-planner-examples/src/main/java/org/drools/planner/examples/common/persistence/AbstractTxtSolutionImporter.java -StartLineNum:44 -EndLineNum:44 -repoName:droolsjbpm#optaplanner \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/comMsg.txt deleted file mode 100755 index 73cc4c6..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -set charset (UTF-8) in CsvFileWriter, rather than depending on defaults \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/diff.diff deleted file mode 100755 index 8fe9814..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/main/java/com/ldbc/driver/util/CsvFileWriter.java b/src/main/java/com/ldbc/driver/util/CsvFileWriter.java -index b40cdb5f..be737c66 100644 ---- a/src/main/java/com/ldbc/driver/util/CsvFileWriter.java -+++ b/src/main/java/com/ldbc/driver/util/CsvFileWriter.java -@@ -3,4 +3,3 @@ package com.ldbc.driver.util; --import java.io.BufferedWriter; --import java.io.File; --import java.io.FileWriter; --import java.io.IOException; -+import com.google.common.base.Charsets; -+ -+import java.io.*; -@@ -17 +16,2 @@ public class CsvFileWriter { -- this.bufferedWriter = new BufferedWriter(new FileWriter(file)); -+ this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)); -+ \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/new/CsvFileWriter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/new/CsvFileWriter.java deleted file mode 100755 index be737c6..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/new/CsvFileWriter.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.ldbc.driver.util; - -import com.google.common.base.Charsets; - -import java.io.*; -import java.util.Iterator; - -public class CsvFileWriter { - public static final String DEFAULT_COLUMN_SEPARATOR_STRING = "|"; - public static final String DEFAULT_COLUMN_SEPARATOR_REGEX_STRING = "\\|"; - - private final BufferedWriter bufferedWriter; - private final String columnSeparator; - - public CsvFileWriter(File file, String columnSeparator) throws IOException { - this.bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), Charsets.UTF_8)); - - this.columnSeparator = columnSeparator; - } - - synchronized public void writeRows(Iterator csvRows) throws IOException { - while (csvRows.hasNext()) - writeRow(csvRows.next()); - } - - synchronized public void writeRow(String... columns) throws IOException { - for (int i = 0; i < columns.length - 1; i++) { - bufferedWriter.write(columns[i]); - bufferedWriter.write(columnSeparator); - } - bufferedWriter.write(columns[columns.length - 1]); - bufferedWriter.newLine(); - } - - public void close() throws IOException { - bufferedWriter.flush(); - bufferedWriter.close(); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/old/CsvFileWriter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/old/CsvFileWriter.java deleted file mode 100755 index b40cdb5..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/old/CsvFileWriter.java +++ /dev/null @@ -1,39 +0,0 @@ -package com.ldbc.driver.util; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.Iterator; - -public class CsvFileWriter { - public static final String DEFAULT_COLUMN_SEPARATOR_STRING = "|"; - public static final String DEFAULT_COLUMN_SEPARATOR_REGEX_STRING = "\\|"; - - private final BufferedWriter bufferedWriter; - private final String columnSeparator; - - public CsvFileWriter(File file, String columnSeparator) throws IOException { - this.bufferedWriter = new BufferedWriter(new FileWriter(file)); - this.columnSeparator = columnSeparator; - } - - synchronized public void writeRows(Iterator csvRows) throws IOException { - while (csvRows.hasNext()) - writeRow(csvRows.next()); - } - - synchronized public void writeRow(String... columns) throws IOException { - for (int i = 0; i < columns.length - 1; i++) { - bufferedWriter.write(columns[i]); - bufferedWriter.write(columnSeparator); - } - bufferedWriter.write(columns[columns.length - 1]); - bufferedWriter.newLine(); - } - - public void close() throws IOException { - bufferedWriter.flush(); - bufferedWriter.close(); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/pair.info deleted file mode 100755 index be44a5e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#29005/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:29005 -comSha:7a4197d84f82fae320864e1a9f761243960eb1aa -parentComSha:7d425ea91b5430de8e24ff17e0baa8e98eaa79f7 -BuggyFilePath:src/main/java/com/ldbc/driver/util/CsvFileWriter.java -FixedFilePath:src/main/java/com/ldbc/driver/util/CsvFileWriter.java -StartLineNum:17 -EndLineNum:17 -repoName:ldbc#ldbc_driver \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/comMsg.txt deleted file mode 100755 index 8e00a83..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -force CsvFileReader to use UTF-8 \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/diff.diff deleted file mode 100755 index 1f9b95d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/com/ldbc/driver/util/CsvFileReader.java b/src/main/java/com/ldbc/driver/util/CsvFileReader.java -index 2d2c4133..112f098c 100644 ---- a/src/main/java/com/ldbc/driver/util/CsvFileReader.java -+++ b/src/main/java/com/ldbc/driver/util/CsvFileReader.java -@@ -2,0 +3,2 @@ package com.ldbc.driver.util; -+import com.google.common.base.Charsets; -+ -@@ -9,2 +10,0 @@ public class CsvFileReader implements Iterator { -- public static final String CSV_SEPARATOR = "\\|"; -- -@@ -18 +18 @@ public class CsvFileReader implements Iterator { -- this.csvReader = new BufferedReader(new FileReader(csvFile)); -+ this.csvReader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), Charsets.UTF_8)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/new/CsvFileReader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/new/CsvFileReader.java deleted file mode 100755 index 112f098..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/new/CsvFileReader.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.ldbc.driver.util; - -import com.google.common.base.Charsets; - -import java.io.*; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.regex.Pattern; - -public class CsvFileReader implements Iterator { - private final Pattern columnSeparatorPattern; - private final BufferedReader csvReader; - - private String[] next = null; - private boolean closed = false; - - public CsvFileReader(File csvFile, String regexSeparator) throws FileNotFoundException { - this.csvReader = new BufferedReader(new InputStreamReader(new FileInputStream(csvFile), Charsets.UTF_8)); - this.columnSeparatorPattern = Pattern.compile(regexSeparator); - } - - @Override - public boolean hasNext() { - if (closed) return false; - next = (next == null) ? nextLine() : next; - if (null == next) closed = closeReader(); - return (null != next); - } - - @Override - public String[] next() { - next = (null == next) ? nextLine() : next; - if (null == next) throw new NoSuchElementException("No more lines to read"); - String[] tempNext = next; - next = null; - return tempNext; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - private String[] nextLine() { - String csvLine; - try { - csvLine = csvReader.readLine(); - if (null == csvLine) return null; - return parseLine(csvLine); - } catch (IOException e) { - throw new RuntimeException(String.format("Error retrieving next csv entry from file [%s]", csvReader), e); - } - } - - private String[] parseLine(String csvLine) { - return columnSeparatorPattern.split(csvLine, -1); - } - - public boolean closeReader() { - if (closed) { - return true; - } - if (null == csvReader) { - throw new RuntimeException("Can not close file - reader is null"); - } - try { - csvReader.close(); - } catch (IOException e) { - throw new RuntimeException(String.format("Error closing file [%s]", csvReader), e); - } - return true; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/old/CsvFileReader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/old/CsvFileReader.java deleted file mode 100755 index 2d2c413..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/old/CsvFileReader.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.ldbc.driver.util; - -import java.io.*; -import java.util.Iterator; -import java.util.NoSuchElementException; -import java.util.regex.Pattern; - -public class CsvFileReader implements Iterator { - public static final String CSV_SEPARATOR = "\\|"; - - private final Pattern columnSeparatorPattern; - private final BufferedReader csvReader; - - private String[] next = null; - private boolean closed = false; - - public CsvFileReader(File csvFile, String regexSeparator) throws FileNotFoundException { - this.csvReader = new BufferedReader(new FileReader(csvFile)); - this.columnSeparatorPattern = Pattern.compile(regexSeparator); - } - - @Override - public boolean hasNext() { - if (closed) return false; - next = (next == null) ? nextLine() : next; - if (null == next) closed = closeReader(); - return (null != next); - } - - @Override - public String[] next() { - next = (null == next) ? nextLine() : next; - if (null == next) throw new NoSuchElementException("No more lines to read"); - String[] tempNext = next; - next = null; - return tempNext; - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - - private String[] nextLine() { - String csvLine; - try { - csvLine = csvReader.readLine(); - if (null == csvLine) return null; - return parseLine(csvLine); - } catch (IOException e) { - throw new RuntimeException(String.format("Error retrieving next csv entry from file [%s]", csvReader), e); - } - } - - private String[] parseLine(String csvLine) { - return columnSeparatorPattern.split(csvLine, -1); - } - - public boolean closeReader() { - if (closed) { - return true; - } - if (null == csvReader) { - throw new RuntimeException("Can not close file - reader is null"); - } - try { - csvReader.close(); - } catch (IOException e) { - throw new RuntimeException(String.format("Error closing file [%s]", csvReader), e); - } - return true; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/pair.info deleted file mode 100755 index 4ca9876..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30025/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:30025 -comSha:9f260ade0b3f373777f1febd042fa37e03caef09 -parentComSha:7a4197d84f82fae320864e1a9f761243960eb1aa -BuggyFilePath:src/main/java/com/ldbc/driver/util/CsvFileReader.java -FixedFilePath:src/main/java/com/ldbc/driver/util/CsvFileReader.java -StartLineNum:18 -EndLineNum:18 -repoName:ldbc#ldbc_driver \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/comMsg.txt deleted file mode 100755 index 1e2d9a8..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/comMsg.txt +++ /dev/null @@ -1,4 +0,0 @@ -Made ContentStoreDir independent of default encoding. - -The TOC file would be read and written using the default encoding, which -is platform dependent. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/diff.diff deleted file mode 100755 index 7cc70f7..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/main/java/nl/inl/blacklab/externalstorage/ContentStoreDir.java b/src/main/java/nl/inl/blacklab/externalstorage/ContentStoreDir.java -index 2a4fe6f6..3dfa564a 100644 ---- a/src/main/java/nl/inl/blacklab/externalstorage/ContentStoreDir.java -+++ b/src/main/java/nl/inl/blacklab/externalstorage/ContentStoreDir.java -@@ -23 +22,0 @@ import java.io.FileOutputStream; --import java.io.FileReader; -@@ -25,0 +25 @@ import java.io.IOException; -+import java.io.InputStreamReader; -@@ -186 +186 @@ public class ContentStoreDir extends ContentStoreDirAbstract { -- BufferedReader f = new BufferedReader(new FileReader(tocFile)); -+ BufferedReader f = new BufferedReader(new InputStreamReader(new FileInputStream(tocFile), "utf-8")); -@@ -220 +220 @@ public class ContentStoreDir extends ContentStoreDirAbstract { -- PrintWriter f = new PrintWriter(new FileWriter(tocFile)); -+ PrintWriter f = new PrintWriter(new OutputStreamWriter(new FileOutputStream(tocFile), "utf-8")); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/new/ContentStoreDir.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/new/ContentStoreDir.java deleted file mode 100755 index 3dfa564..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/new/ContentStoreDir.java +++ /dev/null @@ -1,430 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Institute for Dutch Lexicology - * - * 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 nl.inl.blacklab.externalstorage; - -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Writer; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import nl.inl.util.ExUtil; - -/** - * Store string content by id in a directory of compound files with a TOC file. Quickly retrieve - * (parts of) the string content. - */ -public class ContentStoreDir extends ContentStoreDirAbstract { - private static final String CHAR_ENCODING = "UTF-16LE"; - - private static final int BYTES_PER_CHAR = 2; - - private static final int BYTE_ORDER_MARK_SIZE = 0; - - /** Table of contents entry */ - static class TocEntry { - /** id of the string */ - public int id; - - /** id of the file the string was stored in */ - public int fileId; - - /** byte offset into the file of the string */ - public long offset; - - /** length of the string (in bytes) */ - public int length; - - /** was this entry deleted? (remove in next compacting run) */ - public boolean deleted; - - public TocEntry(int id, int fileId, long offset, int length, boolean deleted) { - super(); - this.id = id; - this.fileId = fileId; - this.offset = offset; - this.length = length; - this.deleted = deleted; - } - - /** - * Convert TOC entry to a string for storing in the TOC file - * - * @return string representation of entry - */ - public String serialize() { - return String.format("%d\t%d\t%d\t%d\t%d", id, fileId, offset, length, deleted ? 1 : 0); - } - - /** - * Convert string representation back into a TOC entry. - * - * @param line - * the line read from the TOC file - * @return new TocEntry - */ - public static TocEntry deserialize(String line) { - String[] parts = line.trim().split("\t", -1); - int id = Integer.parseInt(parts[0]); - int fileId = Integer.parseInt(parts[1]); - int offset = Integer.parseInt(parts[2]); - int length = Integer.parseInt(parts[3]); - boolean deleted = Integer.parseInt(parts[4]) != 0; - return new TocEntry(id, fileId, offset, length, deleted); - } - } - - /** - * The TOC entries - */ - private Map toc; - - /** - * The table of contents (TOC) file - */ - private File tocFile; - - /** - * Preferred size of data files. Note that the data files consist only of whole documents, so - * this size may be exceeded. - */ - private long dataFileSizeHint = 100000000; // 100M - - /** - * Next content ID. - */ - private int nextId = 1; - - /** - * File ID of the current file we're writing to. - */ - private int currentFileId = 1; - - /** - * Length of the file we're writing to. - */ - private long currentFileLength = 0; - - /** - * If we're writing content in chunks, this keeps track of how many bytes were already written. - * Used by store() to calculate the total content length. - */ - private int charsAlreadyWritten = 0; - - /** - * @param dir directory to use for the content store - */ - public ContentStoreDir(File dir) { - this(dir, false); - } - - /** - * @param dir directory to use for the content store - * @param create if true, create a new content store. Otherwise append to the existing one - */ - public ContentStoreDir(File dir, boolean create) { - this.dir = dir; - if (!dir.exists()) - dir.mkdir(); - tocFile = new File(dir, "toc.dat"); - toc = new HashMap(); - if (tocFile.exists()) - readToc(); - if (create) { - clear(); - setStoreType("utf16", "1"); - } - } - - /** - * Delete all content in the document store - */ - @Override - public void clear() { - // delete all data files and empty TOC - for (Map.Entry me : toc.entrySet()) { - TocEntry e = me.getValue(); - File f = getContentFile(e.fileId); - if (f.exists()) - f.delete(); - } - toc.clear(); - currentFileId = 1; - currentFileLength = 0; - nextId = 1; - } - - /** - * Read the table of contents from the file - */ - private void readToc() { - try { - BufferedReader f = new BufferedReader(new InputStreamReader(new FileInputStream(tocFile), "utf-8")); - try { - while (true) { - String line = f.readLine(); - if (line == null) - break; - TocEntry e = TocEntry.deserialize(line); - toc.put(e.id, e); - if (e.fileId > currentFileId) { - currentFileId = e.fileId; - currentFileLength = 0; - } - if (e.fileId == currentFileId) { - long endOfEntry = e.offset + e.length; - if (endOfEntry > currentFileLength) - currentFileLength = endOfEntry; - } - if (e.id + 1 > nextId) - nextId = e.id + 1; - } - } finally { - f.close(); - } - } catch (Exception e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - /** - * Write the table of contents to the file - */ - @Override - public void close() { - try { - PrintWriter f = new PrintWriter(new OutputStreamWriter(new FileOutputStream(tocFile), "utf-8")); - try { - for (Map.Entry e : toc.entrySet()) { - f.println(e.getValue().serialize()); - } - } finally { - f.close(); - } - } catch (Exception e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - /** - * Indicate preferred maximum size of data files (defaults to 10M) - * - * @param dataFileSizeHint - */ - public void setDataFileSizeHint(long dataFileSizeHint) { - this.dataFileSizeHint = dataFileSizeHint; - } - - /** - * Store part of a piece of large content. This may be called several times to store chunks of - * content, but MUST be *finished* by calling the "normal" store() method. You may call store() - * with the empty string if you wish. - * - * @param content - * the content to store - */ - @Override - public synchronized void storePart(String content) { - try { - Writer w = openCurrentStoreFile(); - try { - if (content.length() > 0) { - w.write(content); - charsAlreadyWritten += content.length(); - } - } finally { - w.close(); - } - } catch (IOException e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - /** - * Store the given content and assign an id to it - * - * @param content - * the content to store - * @return the id assigned to the content - */ - @Override - public synchronized int store(String content) { - try { - Writer w = openCurrentStoreFile(); - try { - if (content.length() > 0) - w.write(content); - int entryLengthChars = charsAlreadyWritten + content.length(); - TocEntry e = new TocEntry(nextId, currentFileId, currentFileLength, - entryLengthChars * BYTES_PER_CHAR, false); - nextId++; - currentFileLength += e.length; - toc.put(e.id, e); - charsAlreadyWritten = 0; - return e.id; - } finally { - w.close(); - } - } catch (IOException e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - private Writer openCurrentStoreFile() { - try { - if (currentFileLength > dataFileSizeHint) { - currentFileId++; - currentFileLength = 0; - } - File f = getContentFile(currentFileId); - return new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(f, true)), - CHAR_ENCODING); - } catch (Exception e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - /** - * Get a data File object, given the data file id. - * - * @param fileId - * the data file id - * @return the File object - */ - private File getContentFile(int fileId) { - File f = new File(dir, String.format("data%04d.dat", fileId)); - return f; - } - - /** - * Retrieve content with given id - * - * @param id - * the id - * @return the string - */ - @Override - public String retrieve(int id) { - String[] rv = retrieveParts(id, new int[] { -1 }, new int[] { -1 }); - return rv == null ? null : rv[0]; - } - - /** - * Retrieve one or more substrings from the specified content. - * - * This is more efficient than retrieving the whole content, or retrieving parts in separate - * calls, because the file is only opened once and random access is used to read only the - * required parts. - * - * NOTE: if offset and length are both -1, retrieves the whole content. This is used by the - * retrieve(id) method. - * - * @param contentId - * id of the entry to get substrings from - * @param start - * the starting points of the substrings (in characters) - * @param end - * the end points of the substrings (in characters) - * @return the parts - */ - @Override - public synchronized String[] retrieveParts(int contentId, int[] start, int[] end) { - try { - TocEntry e = toc.get(contentId); - if (e == null || e.deleted) - return null; - - int n = start.length; - if (n != end.length) - throw new RuntimeException("start and end must be of equal length"); - String[] result = new String[n]; - - File f = getContentFile(e.fileId); - FileInputStream fileInputStream = new FileInputStream(f); - try { - FileChannel fileChannel = fileInputStream.getChannel(); - int charLength = e.length / BYTES_PER_CHAR; // take BOM size into account? - for (int i = 0; i < n; i++) { - if (start[i] == -1 && end[i] == -1) { - // whole content - start[i] = 0; - end[i] = charLength; - } - if (start[i] < 0 || end[i] < 0) { - throw new RuntimeException("Illegal values, start = " + start[i] - + ", end = " + end[i]); - } - if (start[i] > charLength || end[i] > charLength) { - throw new RuntimeException("Value(s) out of range, start = " + start[i] - + ", end = " + end[i] + ", content length = " + charLength); - } - if (end[i] <= start[i]) { - throw new RuntimeException( - "Tried to read empty or negative length snippet (from " + start[i] - + " to " + end[i] + ")"); - } - long startOffsetBytes = e.offset + start[i] * BYTES_PER_CHAR - + BYTE_ORDER_MARK_SIZE; - int bytesToRead = (end[i] - start[i]) * BYTES_PER_CHAR; - ByteBuffer buffer = ByteBuffer.allocate(bytesToRead); - int bytesRead = fileChannel.read(buffer, startOffsetBytes); - if (bytesRead < bytesToRead) - throw new RuntimeException("Not enough bytes read, " + bytesRead + " < " - + bytesToRead); - result[i] = new String(buffer.array(), 0, bytesRead, CHAR_ENCODING); - } - } finally { - fileInputStream.close(); - } - return result; - } catch (Exception e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - @Override - public synchronized void delete(int id) { - TocEntry e = toc.get(id); - e.deleted = true; - } - - @Override - public Set getDocIds() { - return toc.keySet(); - } - - @Override - public boolean isDeleted(int id) { - return toc.get(id).deleted; - } - - @Override - public int getDocLength(int id) { - return toc.get(id).length; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/old/ContentStoreDir.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/old/ContentStoreDir.java deleted file mode 100755 index 2a4fe6f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/old/ContentStoreDir.java +++ /dev/null @@ -1,430 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2010, 2012 Institute for Dutch Lexicology - * - * 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 nl.inl.blacklab.externalstorage; - -import java.io.BufferedOutputStream; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Writer; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -import nl.inl.util.ExUtil; - -/** - * Store string content by id in a directory of compound files with a TOC file. Quickly retrieve - * (parts of) the string content. - */ -public class ContentStoreDir extends ContentStoreDirAbstract { - private static final String CHAR_ENCODING = "UTF-16LE"; - - private static final int BYTES_PER_CHAR = 2; - - private static final int BYTE_ORDER_MARK_SIZE = 0; - - /** Table of contents entry */ - static class TocEntry { - /** id of the string */ - public int id; - - /** id of the file the string was stored in */ - public int fileId; - - /** byte offset into the file of the string */ - public long offset; - - /** length of the string (in bytes) */ - public int length; - - /** was this entry deleted? (remove in next compacting run) */ - public boolean deleted; - - public TocEntry(int id, int fileId, long offset, int length, boolean deleted) { - super(); - this.id = id; - this.fileId = fileId; - this.offset = offset; - this.length = length; - this.deleted = deleted; - } - - /** - * Convert TOC entry to a string for storing in the TOC file - * - * @return string representation of entry - */ - public String serialize() { - return String.format("%d\t%d\t%d\t%d\t%d", id, fileId, offset, length, deleted ? 1 : 0); - } - - /** - * Convert string representation back into a TOC entry. - * - * @param line - * the line read from the TOC file - * @return new TocEntry - */ - public static TocEntry deserialize(String line) { - String[] parts = line.trim().split("\t", -1); - int id = Integer.parseInt(parts[0]); - int fileId = Integer.parseInt(parts[1]); - int offset = Integer.parseInt(parts[2]); - int length = Integer.parseInt(parts[3]); - boolean deleted = Integer.parseInt(parts[4]) != 0; - return new TocEntry(id, fileId, offset, length, deleted); - } - } - - /** - * The TOC entries - */ - private Map toc; - - /** - * The table of contents (TOC) file - */ - private File tocFile; - - /** - * Preferred size of data files. Note that the data files consist only of whole documents, so - * this size may be exceeded. - */ - private long dataFileSizeHint = 100000000; // 100M - - /** - * Next content ID. - */ - private int nextId = 1; - - /** - * File ID of the current file we're writing to. - */ - private int currentFileId = 1; - - /** - * Length of the file we're writing to. - */ - private long currentFileLength = 0; - - /** - * If we're writing content in chunks, this keeps track of how many bytes were already written. - * Used by store() to calculate the total content length. - */ - private int charsAlreadyWritten = 0; - - /** - * @param dir directory to use for the content store - */ - public ContentStoreDir(File dir) { - this(dir, false); - } - - /** - * @param dir directory to use for the content store - * @param create if true, create a new content store. Otherwise append to the existing one - */ - public ContentStoreDir(File dir, boolean create) { - this.dir = dir; - if (!dir.exists()) - dir.mkdir(); - tocFile = new File(dir, "toc.dat"); - toc = new HashMap(); - if (tocFile.exists()) - readToc(); - if (create) { - clear(); - setStoreType("utf16", "1"); - } - } - - /** - * Delete all content in the document store - */ - @Override - public void clear() { - // delete all data files and empty TOC - for (Map.Entry me : toc.entrySet()) { - TocEntry e = me.getValue(); - File f = getContentFile(e.fileId); - if (f.exists()) - f.delete(); - } - toc.clear(); - currentFileId = 1; - currentFileLength = 0; - nextId = 1; - } - - /** - * Read the table of contents from the file - */ - private void readToc() { - try { - BufferedReader f = new BufferedReader(new FileReader(tocFile)); - try { - while (true) { - String line = f.readLine(); - if (line == null) - break; - TocEntry e = TocEntry.deserialize(line); - toc.put(e.id, e); - if (e.fileId > currentFileId) { - currentFileId = e.fileId; - currentFileLength = 0; - } - if (e.fileId == currentFileId) { - long endOfEntry = e.offset + e.length; - if (endOfEntry > currentFileLength) - currentFileLength = endOfEntry; - } - if (e.id + 1 > nextId) - nextId = e.id + 1; - } - } finally { - f.close(); - } - } catch (Exception e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - /** - * Write the table of contents to the file - */ - @Override - public void close() { - try { - PrintWriter f = new PrintWriter(new FileWriter(tocFile)); - try { - for (Map.Entry e : toc.entrySet()) { - f.println(e.getValue().serialize()); - } - } finally { - f.close(); - } - } catch (Exception e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - /** - * Indicate preferred maximum size of data files (defaults to 10M) - * - * @param dataFileSizeHint - */ - public void setDataFileSizeHint(long dataFileSizeHint) { - this.dataFileSizeHint = dataFileSizeHint; - } - - /** - * Store part of a piece of large content. This may be called several times to store chunks of - * content, but MUST be *finished* by calling the "normal" store() method. You may call store() - * with the empty string if you wish. - * - * @param content - * the content to store - */ - @Override - public synchronized void storePart(String content) { - try { - Writer w = openCurrentStoreFile(); - try { - if (content.length() > 0) { - w.write(content); - charsAlreadyWritten += content.length(); - } - } finally { - w.close(); - } - } catch (IOException e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - /** - * Store the given content and assign an id to it - * - * @param content - * the content to store - * @return the id assigned to the content - */ - @Override - public synchronized int store(String content) { - try { - Writer w = openCurrentStoreFile(); - try { - if (content.length() > 0) - w.write(content); - int entryLengthChars = charsAlreadyWritten + content.length(); - TocEntry e = new TocEntry(nextId, currentFileId, currentFileLength, - entryLengthChars * BYTES_PER_CHAR, false); - nextId++; - currentFileLength += e.length; - toc.put(e.id, e); - charsAlreadyWritten = 0; - return e.id; - } finally { - w.close(); - } - } catch (IOException e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - private Writer openCurrentStoreFile() { - try { - if (currentFileLength > dataFileSizeHint) { - currentFileId++; - currentFileLength = 0; - } - File f = getContentFile(currentFileId); - return new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(f, true)), - CHAR_ENCODING); - } catch (Exception e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - /** - * Get a data File object, given the data file id. - * - * @param fileId - * the data file id - * @return the File object - */ - private File getContentFile(int fileId) { - File f = new File(dir, String.format("data%04d.dat", fileId)); - return f; - } - - /** - * Retrieve content with given id - * - * @param id - * the id - * @return the string - */ - @Override - public String retrieve(int id) { - String[] rv = retrieveParts(id, new int[] { -1 }, new int[] { -1 }); - return rv == null ? null : rv[0]; - } - - /** - * Retrieve one or more substrings from the specified content. - * - * This is more efficient than retrieving the whole content, or retrieving parts in separate - * calls, because the file is only opened once and random access is used to read only the - * required parts. - * - * NOTE: if offset and length are both -1, retrieves the whole content. This is used by the - * retrieve(id) method. - * - * @param contentId - * id of the entry to get substrings from - * @param start - * the starting points of the substrings (in characters) - * @param end - * the end points of the substrings (in characters) - * @return the parts - */ - @Override - public synchronized String[] retrieveParts(int contentId, int[] start, int[] end) { - try { - TocEntry e = toc.get(contentId); - if (e == null || e.deleted) - return null; - - int n = start.length; - if (n != end.length) - throw new RuntimeException("start and end must be of equal length"); - String[] result = new String[n]; - - File f = getContentFile(e.fileId); - FileInputStream fileInputStream = new FileInputStream(f); - try { - FileChannel fileChannel = fileInputStream.getChannel(); - int charLength = e.length / BYTES_PER_CHAR; // take BOM size into account? - for (int i = 0; i < n; i++) { - if (start[i] == -1 && end[i] == -1) { - // whole content - start[i] = 0; - end[i] = charLength; - } - if (start[i] < 0 || end[i] < 0) { - throw new RuntimeException("Illegal values, start = " + start[i] - + ", end = " + end[i]); - } - if (start[i] > charLength || end[i] > charLength) { - throw new RuntimeException("Value(s) out of range, start = " + start[i] - + ", end = " + end[i] + ", content length = " + charLength); - } - if (end[i] <= start[i]) { - throw new RuntimeException( - "Tried to read empty or negative length snippet (from " + start[i] - + " to " + end[i] + ")"); - } - long startOffsetBytes = e.offset + start[i] * BYTES_PER_CHAR - + BYTE_ORDER_MARK_SIZE; - int bytesToRead = (end[i] - start[i]) * BYTES_PER_CHAR; - ByteBuffer buffer = ByteBuffer.allocate(bytesToRead); - int bytesRead = fileChannel.read(buffer, startOffsetBytes); - if (bytesRead < bytesToRead) - throw new RuntimeException("Not enough bytes read, " + bytesRead + " < " - + bytesToRead); - result[i] = new String(buffer.array(), 0, bytesRead, CHAR_ENCODING); - } - } finally { - fileInputStream.close(); - } - return result; - } catch (Exception e) { - throw ExUtil.wrapRuntimeException(e); - } - } - - @Override - public synchronized void delete(int id) { - TocEntry e = toc.get(id); - e.deleted = true; - } - - @Override - public Set getDocIds() { - return toc.keySet(); - } - - @Override - public boolean isDeleted(int id) { - return toc.get(id).deleted; - } - - @Override - public int getDocLength(int id) { - return toc.get(id).length; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/pair.info deleted file mode 100755 index 338fdc5..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#30115/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:30115 -comSha:bf02fdbe35dd1177552f31e6c5c484340d99b0a6 -parentComSha:c6e444a7ea1d2a5d513bce18e57fb8aa4363114d -BuggyFilePath:src/main/java/nl/inl/blacklab/externalstorage/ContentStoreDir.java -FixedFilePath:src/main/java/nl/inl/blacklab/externalstorage/ContentStoreDir.java -StartLineNum:186 -EndLineNum:186 -repoName:INL#BlackLab \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/comMsg.txt deleted file mode 100755 index 48d5fe7..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Fix issues found with findbugs for java.io stream usages where no encoding is defined. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/diff.diff deleted file mode 100755 index 6e7fa9d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/STARReadsMapper.java b/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/STARReadsMapper.java -index 3996a7ed..08b6634a 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/STARReadsMapper.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/STARReadsMapper.java -@@ -29 +28,0 @@ import java.io.File; --import java.io.FileReader; -@@ -35,0 +35,3 @@ import java.util.List; -+import com.google.common.io.Files; -+ -+import fr.ens.transcriptome.eoulsan.Globals; -@@ -88 +90,2 @@ public class STARReadsMapper extends AbstractSequenceReadsMapper { -- try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { -+ try (BufferedReader reader = -+ Files.newReader(logFile, Globals.DEFAULT_CHARSET)) { \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/new/STARReadsMapper.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/new/STARReadsMapper.java deleted file mode 100755 index 08b6634..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/new/STARReadsMapper.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.readsmappers; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import com.google.common.io.Files; - -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.bio.GenomeDescription; -import fr.ens.transcriptome.eoulsan.data.DataFormat; -import fr.ens.transcriptome.eoulsan.data.DataFormats; -import fr.ens.transcriptome.eoulsan.util.ReporterIncrementer; - -/** - * This class define a wrapper on the STAR mapper. - * @since 2.0 - * @author Laurent Jourdren - */ -public class STARReadsMapper extends AbstractSequenceReadsMapper { - - private static final String DEFAULT_PACKAGE_VERSION = "2.4.0e"; - private static final String MAPPER_EXECUTABLE = "STARstatic"; - private static final String INDEXER_EXECUTABLE = MAPPER_EXECUTABLE; - - public static final String DEFAULT_ARGUMENTS = ""; - - private static final String SYNC = STARReadsMapper.class.getName(); - private static final String MAPPER_NAME = "STAR"; - - @Override - public String getMapperName() { - - return MAPPER_NAME; - } - - @Override - public String getMapperVersion() { - - try { - final String execPath; - - synchronized (SYNC) { - execPath = install(MAPPER_EXECUTABLE); - } - - // Create temporary directory - final File tempDir = File.createTempFile("STAR-get-version-", ".tmp"); - tempDir.delete(); - tempDir.mkdir(); - - // Execute STAR with no argument - final ProcessBuilder pb = new ProcessBuilder(execPath); - pb.directory(tempDir); - final Process p = pb.start(); - p.waitFor(); - - final File logFile = new File(tempDir, "Log.out"); - - // Read STAR version from STAR log file - String version = null; - try (BufferedReader reader = - Files.newReader(logFile, Globals.DEFAULT_CHARSET)) { - final String line = reader.readLine(); - - if (line != null && line.indexOf('=') != -1) { - version = line.substring(line.indexOf('=') + 1).trim(); - if (version.startsWith("STAR_")) { - version = version.substring("STAR_".length()); - } - } - - } catch (IOException e) { - e.printStackTrace(); - return null; - } - - // Delete temporary files - new File(tempDir, "Log.progress.out").delete(); - new File(tempDir, "Aligned.out.sam").delete(); - new File(tempDir, "_tmp").delete(); - logFile.delete(); - tempDir.delete(); - - return version; - } catch (IOException e) { - - e.printStackTrace(); - - return null; - } catch (InterruptedException e) { - e.printStackTrace(); - return null; - } - } - - @Override - public boolean isSplitsAllowed() { - - return true; - } - - @Override - public DataFormat getArchiveFormat() { - - return DataFormats.STAR_INDEX_ZIP; - } - - @Override - protected String getPackageVersion() { - - return DEFAULT_PACKAGE_VERSION; - } - - @Override - protected String getIndexerExecutable() { - - return INDEXER_EXECUTABLE; - } - - @Override - protected List getIndexerCommand(String indexerPathname, - String genomePathname) { - - final File genomeFile = new File(genomePathname); - List cmd = new ArrayList(); - cmd.add(indexerPathname); - cmd.add("--runThreadN"); - cmd.add("" + getThreadsNumber()); - cmd.add("--runMode"); - cmd.add("genomeGenerate"); - cmd.add("--genomeDir"); - cmd.add(genomeFile.getParentFile().getAbsolutePath()); - cmd.add("--genomeFastaFiles"); - cmd.add(genomePathname); - - return cmd; - } - - @Override - protected InputStream internalMapSE(File readsFile, File archiveIndex, - GenomeDescription gd) throws IOException { - - final String starPath; - - synchronized (SYNC) { - starPath = install(MAPPER_EXECUTABLE); - } - - final MapperProcess mapperProcess = - createMapperProcessSE(starPath, archiveIndex.getAbsolutePath(), - readsFile, true); - - return mapperProcess.getStout(); - } - - @Override - protected InputStream internalMapPE(File readsFile1, File readsFile2, - File archiveIndex, GenomeDescription gd) throws IOException { - - final String starPath; - - synchronized (SYNC) { - starPath = install(MAPPER_EXECUTABLE); - } - - final MapperProcess mapperProcess = - createMapperProcessPE(starPath, archiveIndex.getAbsolutePath(), - readsFile1, readsFile2, true); - - return mapperProcess.getStout(); - } - - @Override - protected MapperProcess internalMapSE(File archiveIndex, GenomeDescription gd) - throws IOException { - - final String gsnapPath; - - synchronized (SYNC) { - gsnapPath = install(MAPPER_EXECUTABLE); - } - - return createMapperProcessSE(gsnapPath, archiveIndex.getAbsolutePath(), - null, false); - } - - @Override - protected MapperProcess internalMapPE(File archiveIndex, GenomeDescription gd) - throws IOException { - - final String starPath; - - synchronized (SYNC) { - starPath = install(MAPPER_EXECUTABLE); - } - - return createMapperProcessPE(starPath, archiveIndex.getAbsolutePath(), - null, null, false); - } - - private MapperProcess createMapperProcessSE(final String starPath, - final String archivePath, final File readsPath, final boolean fileMode) - throws IOException { - - return new MapperProcess(this, fileMode, false, false) { - - @Override - protected List> createCommandLines() { - - // Build the command line - final List cmd = new ArrayList(); - cmd.add(starPath); - cmd.add("--runThreadN"); - cmd.add("" + getThreadsNumber()); - cmd.add("--genomeDir"); - cmd.add(archivePath); - cmd.add("--outStd"); - cmd.add("SAM"); - - cmd.addAll(getListMapperArguments()); - - cmd.add("--readFilesIn"); - if (fileMode) { - cmd.add(readsPath.getAbsolutePath()); - } else { - cmd.add(getTmpInputFile1().getAbsolutePath()); - } - - return Collections.singletonList(cmd); - } - - }; - } - - private MapperProcess createMapperProcessPE(final String starPath, - final String archivePath, final File reads1File, final File reads2File, - final boolean fileMode) throws IOException { - - return new MapperProcess(this, fileMode, false, false) { - - @Override - protected List> createCommandLines() { - - // Build the command line - final List cmd = new ArrayList(); - cmd.add(starPath); - cmd.add("--runThreadN"); - cmd.add("" + getThreadsNumber()); - cmd.add("--genomeDir"); - cmd.add(archivePath); - cmd.add("--outStd"); - cmd.add("SAM"); - - cmd.addAll(getListMapperArguments()); - - cmd.add("--readFilesIn"); - if (fileMode) { - cmd.add(reads1File.getAbsolutePath()); - cmd.add(reads2File.getAbsolutePath()); - } else { - cmd.add(getTmpInputFile1().getAbsolutePath()); - cmd.add(getTmpInputFile2().getAbsolutePath()); - } - - return Collections.singletonList(cmd); - } - - }; - } - - // - // Init - // - - @Override - public void init(final File archiveIndexFile, final File archiveIndexDir, - final ReporterIncrementer incrementer, final String counterGroup) - throws IOException { - - super.init(archiveIndexFile, archiveIndexDir, incrementer, counterGroup); - setMapperArguments(DEFAULT_ARGUMENTS); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/old/STARReadsMapper.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/old/STARReadsMapper.java deleted file mode 100755 index 3996a7e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/old/STARReadsMapper.java +++ /dev/null @@ -1,310 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.readsmappers; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import fr.ens.transcriptome.eoulsan.bio.GenomeDescription; -import fr.ens.transcriptome.eoulsan.data.DataFormat; -import fr.ens.transcriptome.eoulsan.data.DataFormats; -import fr.ens.transcriptome.eoulsan.util.ReporterIncrementer; - -/** - * This class define a wrapper on the STAR mapper. - * @since 2.0 - * @author Laurent Jourdren - */ -public class STARReadsMapper extends AbstractSequenceReadsMapper { - - private static final String DEFAULT_PACKAGE_VERSION = "2.4.0e"; - private static final String MAPPER_EXECUTABLE = "STARstatic"; - private static final String INDEXER_EXECUTABLE = MAPPER_EXECUTABLE; - - public static final String DEFAULT_ARGUMENTS = ""; - - private static final String SYNC = STARReadsMapper.class.getName(); - private static final String MAPPER_NAME = "STAR"; - - @Override - public String getMapperName() { - - return MAPPER_NAME; - } - - @Override - public String getMapperVersion() { - - try { - final String execPath; - - synchronized (SYNC) { - execPath = install(MAPPER_EXECUTABLE); - } - - // Create temporary directory - final File tempDir = File.createTempFile("STAR-get-version-", ".tmp"); - tempDir.delete(); - tempDir.mkdir(); - - // Execute STAR with no argument - final ProcessBuilder pb = new ProcessBuilder(execPath); - pb.directory(tempDir); - final Process p = pb.start(); - p.waitFor(); - - final File logFile = new File(tempDir, "Log.out"); - - // Read STAR version from STAR log file - String version = null; - try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) { - final String line = reader.readLine(); - - if (line != null && line.indexOf('=') != -1) { - version = line.substring(line.indexOf('=') + 1).trim(); - if (version.startsWith("STAR_")) { - version = version.substring("STAR_".length()); - } - } - - } catch (IOException e) { - e.printStackTrace(); - return null; - } - - // Delete temporary files - new File(tempDir, "Log.progress.out").delete(); - new File(tempDir, "Aligned.out.sam").delete(); - new File(tempDir, "_tmp").delete(); - logFile.delete(); - tempDir.delete(); - - return version; - } catch (IOException e) { - - e.printStackTrace(); - - return null; - } catch (InterruptedException e) { - e.printStackTrace(); - return null; - } - } - - @Override - public boolean isSplitsAllowed() { - - return true; - } - - @Override - public DataFormat getArchiveFormat() { - - return DataFormats.STAR_INDEX_ZIP; - } - - @Override - protected String getPackageVersion() { - - return DEFAULT_PACKAGE_VERSION; - } - - @Override - protected String getIndexerExecutable() { - - return INDEXER_EXECUTABLE; - } - - @Override - protected List getIndexerCommand(String indexerPathname, - String genomePathname) { - - final File genomeFile = new File(genomePathname); - List cmd = new ArrayList(); - cmd.add(indexerPathname); - cmd.add("--runThreadN"); - cmd.add("" + getThreadsNumber()); - cmd.add("--runMode"); - cmd.add("genomeGenerate"); - cmd.add("--genomeDir"); - cmd.add(genomeFile.getParentFile().getAbsolutePath()); - cmd.add("--genomeFastaFiles"); - cmd.add(genomePathname); - - return cmd; - } - - @Override - protected InputStream internalMapSE(File readsFile, File archiveIndex, - GenomeDescription gd) throws IOException { - - final String starPath; - - synchronized (SYNC) { - starPath = install(MAPPER_EXECUTABLE); - } - - final MapperProcess mapperProcess = - createMapperProcessSE(starPath, archiveIndex.getAbsolutePath(), - readsFile, true); - - return mapperProcess.getStout(); - } - - @Override - protected InputStream internalMapPE(File readsFile1, File readsFile2, - File archiveIndex, GenomeDescription gd) throws IOException { - - final String starPath; - - synchronized (SYNC) { - starPath = install(MAPPER_EXECUTABLE); - } - - final MapperProcess mapperProcess = - createMapperProcessPE(starPath, archiveIndex.getAbsolutePath(), - readsFile1, readsFile2, true); - - return mapperProcess.getStout(); - } - - @Override - protected MapperProcess internalMapSE(File archiveIndex, GenomeDescription gd) - throws IOException { - - final String gsnapPath; - - synchronized (SYNC) { - gsnapPath = install(MAPPER_EXECUTABLE); - } - - return createMapperProcessSE(gsnapPath, archiveIndex.getAbsolutePath(), - null, false); - } - - @Override - protected MapperProcess internalMapPE(File archiveIndex, GenomeDescription gd) - throws IOException { - - final String starPath; - - synchronized (SYNC) { - starPath = install(MAPPER_EXECUTABLE); - } - - return createMapperProcessPE(starPath, archiveIndex.getAbsolutePath(), - null, null, false); - } - - private MapperProcess createMapperProcessSE(final String starPath, - final String archivePath, final File readsPath, final boolean fileMode) - throws IOException { - - return new MapperProcess(this, fileMode, false, false) { - - @Override - protected List> createCommandLines() { - - // Build the command line - final List cmd = new ArrayList(); - cmd.add(starPath); - cmd.add("--runThreadN"); - cmd.add("" + getThreadsNumber()); - cmd.add("--genomeDir"); - cmd.add(archivePath); - cmd.add("--outStd"); - cmd.add("SAM"); - - cmd.addAll(getListMapperArguments()); - - cmd.add("--readFilesIn"); - if (fileMode) { - cmd.add(readsPath.getAbsolutePath()); - } else { - cmd.add(getTmpInputFile1().getAbsolutePath()); - } - - return Collections.singletonList(cmd); - } - - }; - } - - private MapperProcess createMapperProcessPE(final String starPath, - final String archivePath, final File reads1File, final File reads2File, - final boolean fileMode) throws IOException { - - return new MapperProcess(this, fileMode, false, false) { - - @Override - protected List> createCommandLines() { - - // Build the command line - final List cmd = new ArrayList(); - cmd.add(starPath); - cmd.add("--runThreadN"); - cmd.add("" + getThreadsNumber()); - cmd.add("--genomeDir"); - cmd.add(archivePath); - cmd.add("--outStd"); - cmd.add("SAM"); - - cmd.addAll(getListMapperArguments()); - - cmd.add("--readFilesIn"); - if (fileMode) { - cmd.add(reads1File.getAbsolutePath()); - cmd.add(reads2File.getAbsolutePath()); - } else { - cmd.add(getTmpInputFile1().getAbsolutePath()); - cmd.add(getTmpInputFile2().getAbsolutePath()); - } - - return Collections.singletonList(cmd); - } - - }; - } - - // - // Init - // - - @Override - public void init(final File archiveIndexFile, final File archiveIndexDir, - final ReporterIncrementer incrementer, final String counterGroup) - throws IOException { - - super.init(archiveIndexFile, archiveIndexDir, incrementer, counterGroup); - setMapperArguments(DEFAULT_ARGUMENTS); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/pair.info deleted file mode 100755 index 3b66d7d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#31882/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:31882 -comSha:a8aa6a4d759a91a3a112cfecab982ca64e4135fd -parentComSha:d118dfdf1a72f3e4a0f33ced5071e4d1038c9620 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/STARReadsMapper.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/STARReadsMapper.java -StartLineNum:88 -EndLineNum:88 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/comMsg.txt deleted file mode 100755 index 48d5fe7..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Fix issues found with findbugs for java.io stream usages where no encoding is defined. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/diff.diff deleted file mode 100755 index d930123..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/translators/TranslatorUtils.java b/src/main/java/fr/ens/transcriptome/eoulsan/translators/TranslatorUtils.java -index a0c1c33a..b462366c 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/translators/TranslatorUtils.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/translators/TranslatorUtils.java -@@ -34,0 +35 @@ import java.io.InputStreamReader; -+import fr.ens.transcriptome.eoulsan.Globals; -@@ -75 +76,2 @@ public class TranslatorUtils { -- final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); -+ final BufferedReader reader = -+ new BufferedReader(new InputStreamReader(is, Globals.DEFAULT_CHARSET)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/new/TranslatorUtils.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/new/TranslatorUtils.java deleted file mode 100755 index b462366..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/new/TranslatorUtils.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.translators; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.translators.io.TranslatorOutputFormat; - -/** - * This class implements utility methods for translators. - * @since 2.0 - * @author Laurent Jourdren - */ -public class TranslatorUtils { - - /** - * Create a file with additional annotation. - * @param inputFile input file - * @param fieldToTranslate field to use with translator - * @param translator translator to use - * @throws FileNotFoundException if a file cannot be found - * @throws IOException if an error occurs while creating the output file - */ - public static void addTranslatorFields(final File inputFile, - int fieldToTranslate, final Translator translator, - final TranslatorOutputFormat of) throws FileNotFoundException, - IOException { - - addTranslatorFields(new FileInputStream(inputFile), fieldToTranslate, - translator, of); - } - - public static void addTranslatorFields(final InputStream is, - int fieldToTranslate, final Translator translator, - final TranslatorOutputFormat of) throws IOException { - - if (is == null) - throw new NullPointerException("InputStream is null"); - if (translator == null) - throw new NullPointerException("Translator is null"); - if (of == null) - throw new NullPointerException("OutputFormat is null"); - - String[] translatorFieldnames = translator.getFields(); - final int n = translatorFieldnames.length; - - final BufferedReader reader = - new BufferedReader(new InputStreamReader(is, Globals.DEFAULT_CHARSET)); - String line; - boolean first = true; - - while ((line = reader.readLine()) != null) { - - final String[] fields = line.split("\t"); - - if (first) { - - // Write original file header - for (int i = 0; i < fields.length; i++) - of.addHeaderField(fields[i]); - - // Write original file header - for (int i = 0; i < n; i++) - of.addHeaderField(translatorFieldnames[i]); - - first = false; - } else { - - of.newLine(); - - // Write orignal file data - for (int i = 0; i < fields.length; i++) - try { - of.writeDouble(Double.parseDouble(fields[i])); - } catch (NumberFormatException e) { - - of.writeText(fields[i]); - } - - // Write annotation - for (int i = 0; i < n; i++) { - - final String field = translatorFieldnames[i]; - final String valueToTranslate = fields[fieldToTranslate]; - final String value; - - if (field == null) - value = null; - else - value = translator.translateField(valueToTranslate, field); - - String link; - - if (value == null || !translator.isLinkInfo(field)) - link = null; - else - link = translator.getLinkInfo(value, field); - - if (value == null) - of.writeEmpty(); - else { - - if (link == null) - of.writeText(value); - else - of.writeLink(value, link); - - } - } - } - - } - - reader.close(); - of.close(); - } - - // - // Constructor - // - - private TranslatorUtils() { - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/old/TranslatorUtils.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/old/TranslatorUtils.java deleted file mode 100755 index a0c1c33..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/old/TranslatorUtils.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.translators; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import fr.ens.transcriptome.eoulsan.translators.io.TranslatorOutputFormat; - -/** - * This class implements utility methods for translators. - * @since 2.0 - * @author Laurent Jourdren - */ -public class TranslatorUtils { - - /** - * Create a file with additional annotation. - * @param inputFile input file - * @param fieldToTranslate field to use with translator - * @param translator translator to use - * @throws FileNotFoundException if a file cannot be found - * @throws IOException if an error occurs while creating the output file - */ - public static void addTranslatorFields(final File inputFile, - int fieldToTranslate, final Translator translator, - final TranslatorOutputFormat of) throws FileNotFoundException, - IOException { - - addTranslatorFields(new FileInputStream(inputFile), fieldToTranslate, - translator, of); - } - - public static void addTranslatorFields(final InputStream is, - int fieldToTranslate, final Translator translator, - final TranslatorOutputFormat of) throws IOException { - - if (is == null) - throw new NullPointerException("InputStream is null"); - if (translator == null) - throw new NullPointerException("Translator is null"); - if (of == null) - throw new NullPointerException("OutputFormat is null"); - - String[] translatorFieldnames = translator.getFields(); - final int n = translatorFieldnames.length; - - final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - String line; - boolean first = true; - - while ((line = reader.readLine()) != null) { - - final String[] fields = line.split("\t"); - - if (first) { - - // Write original file header - for (int i = 0; i < fields.length; i++) - of.addHeaderField(fields[i]); - - // Write original file header - for (int i = 0; i < n; i++) - of.addHeaderField(translatorFieldnames[i]); - - first = false; - } else { - - of.newLine(); - - // Write orignal file data - for (int i = 0; i < fields.length; i++) - try { - of.writeDouble(Double.parseDouble(fields[i])); - } catch (NumberFormatException e) { - - of.writeText(fields[i]); - } - - // Write annotation - for (int i = 0; i < n; i++) { - - final String field = translatorFieldnames[i]; - final String valueToTranslate = fields[fieldToTranslate]; - final String value; - - if (field == null) - value = null; - else - value = translator.translateField(valueToTranslate, field); - - String link; - - if (value == null || !translator.isLinkInfo(field)) - link = null; - else - link = translator.getLinkInfo(value, field); - - if (value == null) - of.writeEmpty(); - else { - - if (link == null) - of.writeText(value); - else - of.writeLink(value, link); - - } - } - } - - } - - reader.close(); - of.close(); - } - - // - // Constructor - // - - private TranslatorUtils() { - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/pair.info deleted file mode 100755 index ca50a77..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32149/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:32149 -comSha:a8aa6a4d759a91a3a112cfecab982ca64e4135fd -parentComSha:d118dfdf1a72f3e4a0f33ced5071e4d1038c9620 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/translators/TranslatorUtils.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/translators/TranslatorUtils.java -StartLineNum:75 -EndLineNum:75 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/comMsg.txt deleted file mode 100755 index 7467cc1..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'master' into new_workflow \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/diff.diff deleted file mode 100755 index f117f5d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java b/src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -index b0f78a50..fc88a77f 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -@@ -27,0 +28 @@ import static com.google.common.collect.Lists.newArrayList; -+import static fr.ens.transcriptome.eoulsan.bio.io.BioCharsets.SAM_CHARSET; -@@ -44,0 +46 @@ import com.google.common.collect.Lists; -+import fr.ens.transcriptome.eoulsan.EoulsanLogger; -@@ -59 +61 @@ public class SAMFilterMapper extends Mapper { -- private static final Logger LOGGER = Logger.getLogger(Globals.APP_NAME); -+ private static final Logger LOGGER = EoulsanLogger.getLogger(); -@@ -191 +193 @@ public class SAMFilterMapper extends Mapper { -- context.getConfiguration())); -+ context.getConfiguration()), SAM_CHARSET); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/new/SAMFilterMapper.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/new/SAMFilterMapper.java deleted file mode 100755 index fc88a77..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/new/SAMFilterMapper.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.steps.mapping.hadoop; - -import static com.google.common.collect.Lists.newArrayList; -import static fr.ens.transcriptome.eoulsan.bio.io.BioCharsets.SAM_CHARSET; -import static fr.ens.transcriptome.eoulsan.steps.mapping.MappingCounters.INPUT_ALIGNMENTS_COUNTER; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.List; -import java.util.logging.Logger; - -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.io.LongWritable; -import org.apache.hadoop.io.Text; -import org.apache.hadoop.mapreduce.Mapper; - -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; - -import fr.ens.transcriptome.eoulsan.EoulsanLogger; -import fr.ens.transcriptome.eoulsan.EoulsanRuntime; -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.HadoopEoulsanRuntime; -import fr.ens.transcriptome.eoulsan.core.CommonHadoop; -import fr.ens.transcriptome.eoulsan.util.hadoop.PathUtils; - -/** - * This class defines a mapper for alignment filtering. - * @since 1.0 - * @author Laurent Jourdren - */ -public class SAMFilterMapper extends Mapper { - - /** Logger */ - private static final Logger LOGGER = EoulsanLogger.getLogger(); - - // Parameters keys - static final String MAPPING_QUALITY_THRESOLD_KEY = Globals.PARAMETER_PREFIX - + ".samfilter.mapping.quality.threshold"; - static final String GENOME_DESC_PATH_KEY = Globals.PARAMETER_PREFIX - + ".samfilter.genome.desc.file"; - - static final String SAM_HEADER_FILE_PREFIX = "_samheader_"; - - private static final Splitter ID_SPLITTER = Splitter.on(':').trimResults(); - private List idFields = newArrayList(); - - private String counterGroup; - - private final Text outKey = new Text(); - private final Text outValue = new Text(); - - @Override - protected void setup(final Context context) throws IOException, - InterruptedException { - - LOGGER.info("Start of configure()"); - - // Get configuration object - final Configuration conf = context.getConfiguration(); - - // Initialize Eoulsan DataProtocols - if (!EoulsanRuntime.isRuntime()) { - HadoopEoulsanRuntime.newEoulsanRuntime(conf); - } - - // Counter group - this.counterGroup = conf.get(CommonHadoop.COUNTER_GROUP_KEY); - if (this.counterGroup == null) { - throw new IOException("No counter group defined"); - } - - LOGGER.info("End of setup()"); - } - - /** - * 'key': offset of the beginning of the line from the beginning of the SAM - * file if data are in single-end mode or in TSAM file if data are in - * paired-end mode. 'value': the SAM or TSAM line. - */ - @Override - protected void map(final LongWritable key, final Text value, - final Context context) throws IOException, InterruptedException { - - final String line = value.toString(); - - // Avoid empty and header lines - if (!isValidLineAndSaveSAMHeader(line, context)) - return; - - context.getCounter(this.counterGroup, - INPUT_ALIGNMENTS_COUNTER.counterName()).increment(1); - - final int indexOfFirstTab = line.indexOf("\t"); - String completeId = line.substring(0, indexOfFirstTab); - int endReadId; - - idFields.clear(); - for (String e : ID_SPLITTER.split(completeId)) { - idFields.add(e); - } - - // Read identifiant format : before Casava 1.8 or other technologies that - // Illumina - if (idFields.size() < 7) { - endReadId = completeId.indexOf('/'); - // single-end mode - if (endReadId == -1) { - this.outKey.set(completeId); - this.outValue.set(line.substring(indexOfFirstTab)); - } - // paired-end mode - else { - this.outKey.set(line.substring(0, endReadId + 1)); - this.outValue.set(line.substring(endReadId + 1)); - } - } - - // Read identifiant format : Illumina - Casava 1.8 - else { - endReadId = completeId.indexOf(' '); - // mapped read - if (endReadId == -1) { - this.outKey.set(completeId); - this.outValue.set(line.substring(indexOfFirstTab)); - } - // unmapped read - else { - this.outKey.set(line.substring(0, endReadId)); - this.outValue.set(line.substring(endReadId)); - } - } - - context.write(this.outKey, this.outValue); - } - - @Override - protected void cleanup(Context context) throws IOException, - InterruptedException { - } - - private List headers; - - private final boolean isValidLineAndSaveSAMHeader(final String line, - final Context context) throws IOException { - - // Test empty line - if (line.length() == 0) - return false; - - if (line.charAt(0) != '@') { - - // If headers previously found write it in a file - if (this.headers != null) { - - // Save headers - - // TODO change for Hadoop 2.0 - final Path outputPath = - new Path(context.getConfiguration().get("mapred.output.dir")); - - final Path headerPath = - new Path(outputPath, SAM_HEADER_FILE_PREFIX - + context.getTaskAttemptID().toString()); - final Writer writer = - new OutputStreamWriter(PathUtils.createOutputStream(headerPath, - context.getConfiguration()), SAM_CHARSET); - - for (String l : this.headers) - writer.write(l + "\n"); - - writer.close(); - - this.headers = null; - } - - // The line is an alignment - return true; - } - - if (this.headers == null) - this.headers = Lists.newArrayList(); - - this.headers.add(line); - - // The line is an header - return false; - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/old/SAMFilterMapper.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/old/SAMFilterMapper.java deleted file mode 100755 index b0f78a5..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/old/SAMFilterMapper.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.steps.mapping.hadoop; - -import static com.google.common.collect.Lists.newArrayList; -import static fr.ens.transcriptome.eoulsan.steps.mapping.MappingCounters.INPUT_ALIGNMENTS_COUNTER; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.List; -import java.util.logging.Logger; - -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.io.LongWritable; -import org.apache.hadoop.io.Text; -import org.apache.hadoop.mapreduce.Mapper; - -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; - -import fr.ens.transcriptome.eoulsan.EoulsanRuntime; -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.HadoopEoulsanRuntime; -import fr.ens.transcriptome.eoulsan.core.CommonHadoop; -import fr.ens.transcriptome.eoulsan.util.hadoop.PathUtils; - -/** - * This class defines a mapper for alignment filtering. - * @since 1.0 - * @author Laurent Jourdren - */ -public class SAMFilterMapper extends Mapper { - - /** Logger */ - private static final Logger LOGGER = Logger.getLogger(Globals.APP_NAME); - - // Parameters keys - static final String MAPPING_QUALITY_THRESOLD_KEY = Globals.PARAMETER_PREFIX - + ".samfilter.mapping.quality.threshold"; - static final String GENOME_DESC_PATH_KEY = Globals.PARAMETER_PREFIX - + ".samfilter.genome.desc.file"; - - static final String SAM_HEADER_FILE_PREFIX = "_samheader_"; - - private static final Splitter ID_SPLITTER = Splitter.on(':').trimResults(); - private List idFields = newArrayList(); - - private String counterGroup; - - private final Text outKey = new Text(); - private final Text outValue = new Text(); - - @Override - protected void setup(final Context context) throws IOException, - InterruptedException { - - LOGGER.info("Start of configure()"); - - // Get configuration object - final Configuration conf = context.getConfiguration(); - - // Initialize Eoulsan DataProtocols - if (!EoulsanRuntime.isRuntime()) { - HadoopEoulsanRuntime.newEoulsanRuntime(conf); - } - - // Counter group - this.counterGroup = conf.get(CommonHadoop.COUNTER_GROUP_KEY); - if (this.counterGroup == null) { - throw new IOException("No counter group defined"); - } - - LOGGER.info("End of setup()"); - } - - /** - * 'key': offset of the beginning of the line from the beginning of the SAM - * file if data are in single-end mode or in TSAM file if data are in - * paired-end mode. 'value': the SAM or TSAM line. - */ - @Override - protected void map(final LongWritable key, final Text value, - final Context context) throws IOException, InterruptedException { - - final String line = value.toString(); - - // Avoid empty and header lines - if (!isValidLineAndSaveSAMHeader(line, context)) - return; - - context.getCounter(this.counterGroup, - INPUT_ALIGNMENTS_COUNTER.counterName()).increment(1); - - final int indexOfFirstTab = line.indexOf("\t"); - String completeId = line.substring(0, indexOfFirstTab); - int endReadId; - - idFields.clear(); - for (String e : ID_SPLITTER.split(completeId)) { - idFields.add(e); - } - - // Read identifiant format : before Casava 1.8 or other technologies that - // Illumina - if (idFields.size() < 7) { - endReadId = completeId.indexOf('/'); - // single-end mode - if (endReadId == -1) { - this.outKey.set(completeId); - this.outValue.set(line.substring(indexOfFirstTab)); - } - // paired-end mode - else { - this.outKey.set(line.substring(0, endReadId + 1)); - this.outValue.set(line.substring(endReadId + 1)); - } - } - - // Read identifiant format : Illumina - Casava 1.8 - else { - endReadId = completeId.indexOf(' '); - // mapped read - if (endReadId == -1) { - this.outKey.set(completeId); - this.outValue.set(line.substring(indexOfFirstTab)); - } - // unmapped read - else { - this.outKey.set(line.substring(0, endReadId)); - this.outValue.set(line.substring(endReadId)); - } - } - - context.write(this.outKey, this.outValue); - } - - @Override - protected void cleanup(Context context) throws IOException, - InterruptedException { - } - - private List headers; - - private final boolean isValidLineAndSaveSAMHeader(final String line, - final Context context) throws IOException { - - // Test empty line - if (line.length() == 0) - return false; - - if (line.charAt(0) != '@') { - - // If headers previously found write it in a file - if (this.headers != null) { - - // Save headers - - // TODO change for Hadoop 2.0 - final Path outputPath = - new Path(context.getConfiguration().get("mapred.output.dir")); - - final Path headerPath = - new Path(outputPath, SAM_HEADER_FILE_PREFIX - + context.getTaskAttemptID().toString()); - final Writer writer = - new OutputStreamWriter(PathUtils.createOutputStream(headerPath, - context.getConfiguration())); - - for (String l : this.headers) - writer.write(l + "\n"); - - writer.close(); - - this.headers = null; - } - - // The line is an alignment - return true; - } - - if (this.headers == null) - this.headers = Lists.newArrayList(); - - this.headers.add(line); - - // The line is an header - return false; - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/pair.info deleted file mode 100755 index cfdc350..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32329/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:32329 -comSha:48e0e6bf0270df966b8364625a332cd11d97a265 -parentComSha:6c1e13bd2018d7d214d6a84e12e3df520999b6ca -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -StartLineNum:189 -EndLineNum:189 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/comMsg.txt deleted file mode 100755 index 846907d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Many code fix after findbugs. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/diff.diff deleted file mode 100755 index b8a66b6..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/bio/io/GFFReader.java b/src/main/java/fr/ens/transcriptome/eoulsan/bio/io/GFFReader.java -index 9df5ac29..91c5c013 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/bio/io/GFFReader.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/bio/io/GFFReader.java -@@ -35,0 +36 @@ import java.io.InputStreamReader; -+import java.nio.charset.Charset; -@@ -50,0 +52,3 @@ public class GFFReader implements Iterator, Iterable, -+ /* Default Charset. */ -+ private static final Charset CHARSET = Charset.forName("ISO-8859-1"); -+ -@@ -190 +194 @@ public class GFFReader implements Iterator, Iterable, -- this.reader = new BufferedReader(new InputStreamReader(is)); -+ this.reader = new BufferedReader(new InputStreamReader(is, CHARSET)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/new/GFFReader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/new/GFFReader.java deleted file mode 100755 index 91c5c01..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/new/GFFReader.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.io; - -import static fr.ens.transcriptome.eoulsan.util.Utils.newLinkedHashMap; - -import java.io.BufferedReader; -import java.io.Closeable; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; - -import fr.ens.transcriptome.eoulsan.bio.BadBioEntryException; -import fr.ens.transcriptome.eoulsan.bio.GFFEntry; -import fr.ens.transcriptome.eoulsan.util.FileUtils; - -/** - * This class define a GFF reader. - * @author Laurent Jourdren - */ -public class GFFReader implements Iterator, Iterable, - Closeable { - - /* Default Charset. */ - private static final Charset CHARSET = Charset.forName("ISO-8859-1"); - - private BufferedReader reader; - private GFFEntry result = null; - private int count; - private boolean end; - private boolean fastaSectionFound; - - private Map metadata = newLinkedHashMap(); - private boolean nextCallDone = true; - protected IOException ioException; - protected BadBioEntryException bbeException; - - @Override - public Iterator iterator() { - - return this; - } - - /** - * Test if a fasta section was found. - * @return true if a Fasta section was found - */ - public boolean isFastaSectionFound() { - - return this.fastaSectionFound; - } - - @Override - public boolean hasNext() { - - if (this.end) - return false; - - String line = null; - - result = new GFFEntry(); - - try { - while ((line = this.reader.readLine()) != null) { - - if (line.startsWith("###")) - continue; - - if (line.startsWith("##FASTA")) { - this.fastaSectionFound = true; - this.end = true; - return false; - } - - if (line.startsWith("##")) { - - final int posTab = line.indexOf('\t'); - if (posTab == -1) - continue; - - final String mdKey = line.substring(2, posTab).trim(); - final String mdValue = line.substring(posTab + 1).trim(); - - this.metadata.put(mdKey, mdValue); - - } else if (line.startsWith("#")) - continue; - else { - - result.parse(line.trim()); - result.setId(count++); - - // Add metadata if not reuse result object - result.addMetaDataEntries(this.metadata); - - this.nextCallDone = false; - return true; - } - } - } catch (IOException e) { - this.ioException = e; - } catch (BadBioEntryException e) { - this.bbeException = e; - } - - this.end = true; - - return false; - } - - @Override - public GFFEntry next() { - - if (this.nextCallDone) - throw new NoSuchElementException(); - - this.nextCallDone = true; - - return this.result; - } - - @Override - public void remove() { - - throw new UnsupportedOperationException("Unsupported operation"); - } - - /** - * Close the stream. - * @throws IOException - */ - public void close() throws IOException { - - this.reader.close(); - } - - /** - * Throw an exception if an exception has been caught while last hasNext() - * method call. - * @throws IOException if an exception has been caught while last hasNext() - * method call - * @throws BadBioEntryException if the last entry is not valid - */ - public void throwException() throws IOException, BadBioEntryException { - - if (this.ioException != null) - throw this.ioException; - - if (this.bbeException != null) - throw this.bbeException; - } - - // - // Constructor - // - - /** - * Public constructor - * @param is InputStream to use - */ - public GFFReader(final InputStream is) { - - if (is == null) - throw new NullPointerException("InputStream is null"); - - this.reader = new BufferedReader(new InputStreamReader(is, CHARSET)); - } - - /** - * Public constructor - * @param file File to use - */ - public GFFReader(final File file) throws FileNotFoundException { - - if (file == null) - throw new NullPointerException("File is null"); - - if (!file.isFile()) - throw new FileNotFoundException("File not found: " - + file.getAbsolutePath()); - - this.reader = FileUtils.createBufferedReader(file); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/old/GFFReader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/old/GFFReader.java deleted file mode 100755 index 9df5ac2..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/old/GFFReader.java +++ /dev/null @@ -1,209 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.io; - -import static fr.ens.transcriptome.eoulsan.util.Utils.newLinkedHashMap; - -import java.io.BufferedReader; -import java.io.Closeable; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Iterator; -import java.util.Map; -import java.util.NoSuchElementException; - -import fr.ens.transcriptome.eoulsan.bio.BadBioEntryException; -import fr.ens.transcriptome.eoulsan.bio.GFFEntry; -import fr.ens.transcriptome.eoulsan.util.FileUtils; - -/** - * This class define a GFF reader. - * @author Laurent Jourdren - */ -public class GFFReader implements Iterator, Iterable, - Closeable { - - private BufferedReader reader; - private GFFEntry result = null; - private int count; - private boolean end; - private boolean fastaSectionFound; - - private Map metadata = newLinkedHashMap(); - private boolean nextCallDone = true; - protected IOException ioException; - protected BadBioEntryException bbeException; - - @Override - public Iterator iterator() { - - return this; - } - - /** - * Test if a fasta section was found. - * @return true if a Fasta section was found - */ - public boolean isFastaSectionFound() { - - return this.fastaSectionFound; - } - - @Override - public boolean hasNext() { - - if (this.end) - return false; - - String line = null; - - result = new GFFEntry(); - - try { - while ((line = this.reader.readLine()) != null) { - - if (line.startsWith("###")) - continue; - - if (line.startsWith("##FASTA")) { - this.fastaSectionFound = true; - this.end = true; - return false; - } - - if (line.startsWith("##")) { - - final int posTab = line.indexOf('\t'); - if (posTab == -1) - continue; - - final String mdKey = line.substring(2, posTab).trim(); - final String mdValue = line.substring(posTab + 1).trim(); - - this.metadata.put(mdKey, mdValue); - - } else if (line.startsWith("#")) - continue; - else { - - result.parse(line.trim()); - result.setId(count++); - - // Add metadata if not reuse result object - result.addMetaDataEntries(this.metadata); - - this.nextCallDone = false; - return true; - } - } - } catch (IOException e) { - this.ioException = e; - } catch (BadBioEntryException e) { - this.bbeException = e; - } - - this.end = true; - - return false; - } - - @Override - public GFFEntry next() { - - if (this.nextCallDone) - throw new NoSuchElementException(); - - this.nextCallDone = true; - - return this.result; - } - - @Override - public void remove() { - - throw new UnsupportedOperationException("Unsupported operation"); - } - - /** - * Close the stream. - * @throws IOException - */ - public void close() throws IOException { - - this.reader.close(); - } - - /** - * Throw an exception if an exception has been caught while last hasNext() - * method call. - * @throws IOException if an exception has been caught while last hasNext() - * method call - * @throws BadBioEntryException if the last entry is not valid - */ - public void throwException() throws IOException, BadBioEntryException { - - if (this.ioException != null) - throw this.ioException; - - if (this.bbeException != null) - throw this.bbeException; - } - - // - // Constructor - // - - /** - * Public constructor - * @param is InputStream to use - */ - public GFFReader(final InputStream is) { - - if (is == null) - throw new NullPointerException("InputStream is null"); - - this.reader = new BufferedReader(new InputStreamReader(is)); - } - - /** - * Public constructor - * @param file File to use - */ - public GFFReader(final File file) throws FileNotFoundException { - - if (file == null) - throw new NullPointerException("File is null"); - - if (!file.isFile()) - throw new FileNotFoundException("File not found: " - + file.getAbsolutePath()); - - this.reader = FileUtils.createBufferedReader(file); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/pair.info deleted file mode 100755 index c226305..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32461/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:32461 -comSha:4a4f273ebcb53fc498dd0c45bc5dd4ea66cf5480 -parentComSha:237a7830c382d17dfa2fd10951c13d1ad46075b2 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/io/GFFReader.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/io/GFFReader.java -StartLineNum:190 -EndLineNum:190 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/comMsg.txt deleted file mode 100755 index 48d5fe7..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Fix issues found with findbugs for java.io stream usages where no encoding is defined. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/diff.diff deleted file mode 100755 index 7dda47c..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/TextComparator.java b/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/TextComparator.java -index 4e322728..4a8912e5 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/TextComparator.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/TextComparator.java -@@ -33,0 +34 @@ import com.google.common.collect.Sets; -+import fr.ens.transcriptome.eoulsan.Globals; -@@ -53 +54,2 @@ public class TextComparator extends AbstractComparatorWithBloomFilter { -- final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); -+ final BufferedReader reader = -+ new BufferedReader(new InputStreamReader(is, Globals.DEFAULT_CHARSET)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/new/TextComparator.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/new/TextComparator.java deleted file mode 100755 index 4a8912e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/new/TextComparator.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ -package fr.ens.transcriptome.eoulsan.io.comparators; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Collection; - -import com.google.common.collect.Sets; - -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.util.BloomFilterUtils; - -/** - * This class allow compare two text files with use BloomFilter. - * @since 2.0 - * @author Sandrine Perrin - */ -public class TextComparator extends AbstractComparatorWithBloomFilter { - - private static final String NAME_COMPARATOR = "TextComparator"; - private static final Collection EXTENSIONS = Sets.newHashSet(".txt", - ".tsv", ".csv", ".xml"); - - private int numberElementsCompared; - - @Override - public boolean compareFiles(BloomFilterUtils filter, InputStream is) - throws IOException { - - final BufferedReader reader = - new BufferedReader(new InputStreamReader(is, Globals.DEFAULT_CHARSET)); - String line = null; - numberElementsCompared = 0; - - while ((line = reader.readLine()) != null) { - numberElementsCompared++; - - if (!filter.mightContain(line)) { - // Save line occurs fail comparison - setCauseFailComparison(line); - - reader.close(); - return false; - } - } - reader.close(); - - // Check count element is the same between two files - if (numberElementsCompared != filter.getAddedNumberOfElements()) { - setCauseFailComparison("Different count elements " - + this.numberElementsCompared + " was " - + filter.getAddedNumberOfElements() + " expected."); - return false; - } - return true; - } - - // - // Getter - // - public Collection getExtensions() { - return EXTENSIONS; - } - - @Override - public String getName() { - - return NAME_COMPARATOR; - } - - @Override - public int getNumberElementsCompared() { - return this.numberElementsCompared; - } - - // - // Constructor - // - - /** - * Public constructor - * @param useSerializeFile true if it needed to save BloomFilter in file with - * extension '.ser' - */ - public TextComparator(final boolean useSerializeFile) { - super(useSerializeFile); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/old/TextComparator.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/old/TextComparator.java deleted file mode 100755 index 4e32272..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/old/TextComparator.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ -package fr.ens.transcriptome.eoulsan.io.comparators; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Collection; - -import com.google.common.collect.Sets; - -import fr.ens.transcriptome.eoulsan.util.BloomFilterUtils; - -/** - * This class allow compare two text files with use BloomFilter. - * @since 2.0 - * @author Sandrine Perrin - */ -public class TextComparator extends AbstractComparatorWithBloomFilter { - - private static final String NAME_COMPARATOR = "TextComparator"; - private static final Collection EXTENSIONS = Sets.newHashSet(".txt", - ".tsv", ".csv", ".xml"); - - private int numberElementsCompared; - - @Override - public boolean compareFiles(BloomFilterUtils filter, InputStream is) - throws IOException { - - final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - String line = null; - numberElementsCompared = 0; - - while ((line = reader.readLine()) != null) { - numberElementsCompared++; - - if (!filter.mightContain(line)) { - // Save line occurs fail comparison - setCauseFailComparison(line); - - reader.close(); - return false; - } - } - reader.close(); - - // Check count element is the same between two files - if (numberElementsCompared != filter.getAddedNumberOfElements()) { - setCauseFailComparison("Different count elements " - + this.numberElementsCompared + " was " - + filter.getAddedNumberOfElements() + " expected."); - return false; - } - return true; - } - - // - // Getter - // - public Collection getExtensions() { - return EXTENSIONS; - } - - @Override - public String getName() { - - return NAME_COMPARATOR; - } - - @Override - public int getNumberElementsCompared() { - return this.numberElementsCompared; - } - - // - // Constructor - // - - /** - * Public constructor - * @param useSerializeFile true if it needed to save BloomFilter in file with - * extension '.ser' - */ - public TextComparator(final boolean useSerializeFile) { - super(useSerializeFile); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/pair.info deleted file mode 100755 index f3367f1..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32484/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:32484 -comSha:a8aa6a4d759a91a3a112cfecab982ca64e4135fd -parentComSha:d118dfdf1a72f3e4a0f33ced5071e4d1038c9620 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/TextComparator.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/TextComparator.java -StartLineNum:53 -EndLineNum:53 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/comMsg.txt deleted file mode 100755 index 48d5fe7..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Fix issues found with findbugs for java.io stream usages where no encoding is defined. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/diff.diff deleted file mode 100755 index ee96297..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/SAMComparator.java b/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/SAMComparator.java -index 8b202c45..60569aeb 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/SAMComparator.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/SAMComparator.java -@@ -36,0 +37 @@ import com.google.common.collect.Sets; -+import fr.ens.transcriptome.eoulsan.Globals; -@@ -57 +58,2 @@ public class SAMComparator extends AbstractComparatorWithBloomFilter { -- final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); -+ final BufferedReader reader = -+ new BufferedReader(new InputStreamReader(is, Globals.DEFAULT_CHARSET)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/new/SAMComparator.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/new/SAMComparator.java deleted file mode 100755 index 60569ae..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/new/SAMComparator.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.io.comparators; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import com.google.common.collect.Sets; - -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.util.BloomFilterUtils; - -/** - * This class allow compare two SAM file with use BloomFilter. - * @since 2.0 - * @author Sandrine Perrin - */ -public class SAMComparator extends AbstractComparatorWithBloomFilter { - - public static final String COMPARATOR_NAME = "SAMComparator"; - private static final Collection EXTENSIONS = Sets.newHashSet(".sam"); - - final Set tagsToNotCompare; - - private int numberElementsCompared; - - @Override - public boolean compareFiles(BloomFilterUtils filter, InputStream is) - throws IOException { - - final BufferedReader reader = - new BufferedReader(new InputStreamReader(is, Globals.DEFAULT_CHARSET)); - String line = null; - numberElementsCompared = 0; - - while ((line = reader.readLine()) != null) { - numberElementsCompared++; - - // Header - if (line.charAt(0) == '@') { - - // Skip specified tag in header sam file - if (!this.tagsToNotCompare.contains(getTag(line))) { - - if (!filter.mightContain(line)) { - // Save line occurs fail comparison - setCauseFailComparison(line); - - reader.close(); - return false; - } - } - } else { - // Line - if (!filter.mightContain(line)) { - // Save line occurs fail comparison - setCauseFailComparison(line); - - reader.close(); - return false; - } - } - } - reader.close(); - - // Check count element is the same between two files - if (this.numberElementsCompared != filter.getAddedNumberOfElements()) { - setCauseFailComparison("Different count elements " - + this.numberElementsCompared + " was " - + filter.getAddedNumberOfElements() + " expected."); - return false; - } - - return true; - } - - // - // Other methods - // - - private static String getTag(final String samHeaderLine) { - - if (samHeaderLine.length() == 0) - return ""; - - final int pos = samHeaderLine.indexOf('\t'); - - if (pos == -1) - return samHeaderLine.substring(1); - - return samHeaderLine.substring(1, pos); - } - - @Override - public String getName() { - - return COMPARATOR_NAME; - } - - @Override - public Collection getExtensions() { - return EXTENSIONS; - } - - @Override - public int getNumberElementsCompared() { - return this.numberElementsCompared; - } - - // - // Constructor - // - - /** - * Public constructor public FastqComparator(final boolean useSerializeFile) { - * super(useSerializeFile); } /** Public constructor - * @param useSerializeFile true if it needed to save BloomFilter in file with - * extension '.ser' - */ - public SAMComparator(final boolean useSerializeFile) { - super(useSerializeFile); - - this.tagsToNotCompare = new HashSet<>(); - } - - /** - * Public constructor, specify all headers tags not used to compare. - * @param useSerializeFile true if it needed to save BloomFilter in file with - * extension '.ser' - * @param headersTags all headers tags - */ - public SAMComparator(boolean useSerializeFile, String... headersTags) { - super(useSerializeFile); - - if (headersTags == null) - throw new NullPointerException("headersTags is null"); - - this.tagsToNotCompare = Sets.newHashSet(headersTags); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/old/SAMComparator.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/old/SAMComparator.java deleted file mode 100755 index 8b202c4..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/old/SAMComparator.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.io.comparators; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import com.google.common.collect.Sets; - -import fr.ens.transcriptome.eoulsan.util.BloomFilterUtils; - -/** - * This class allow compare two SAM file with use BloomFilter. - * @since 2.0 - * @author Sandrine Perrin - */ -public class SAMComparator extends AbstractComparatorWithBloomFilter { - - public static final String COMPARATOR_NAME = "SAMComparator"; - private static final Collection EXTENSIONS = Sets.newHashSet(".sam"); - - final Set tagsToNotCompare; - - private int numberElementsCompared; - - @Override - public boolean compareFiles(BloomFilterUtils filter, InputStream is) - throws IOException { - - final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - String line = null; - numberElementsCompared = 0; - - while ((line = reader.readLine()) != null) { - numberElementsCompared++; - - // Header - if (line.charAt(0) == '@') { - - // Skip specified tag in header sam file - if (!this.tagsToNotCompare.contains(getTag(line))) { - - if (!filter.mightContain(line)) { - // Save line occurs fail comparison - setCauseFailComparison(line); - - reader.close(); - return false; - } - } - } else { - // Line - if (!filter.mightContain(line)) { - // Save line occurs fail comparison - setCauseFailComparison(line); - - reader.close(); - return false; - } - } - } - reader.close(); - - // Check count element is the same between two files - if (this.numberElementsCompared != filter.getAddedNumberOfElements()) { - setCauseFailComparison("Different count elements " - + this.numberElementsCompared + " was " - + filter.getAddedNumberOfElements() + " expected."); - return false; - } - - return true; - } - - // - // Other methods - // - - private static String getTag(final String samHeaderLine) { - - if (samHeaderLine.length() == 0) - return ""; - - final int pos = samHeaderLine.indexOf('\t'); - - if (pos == -1) - return samHeaderLine.substring(1); - - return samHeaderLine.substring(1, pos); - } - - @Override - public String getName() { - - return COMPARATOR_NAME; - } - - @Override - public Collection getExtensions() { - return EXTENSIONS; - } - - @Override - public int getNumberElementsCompared() { - return this.numberElementsCompared; - } - - // - // Constructor - // - - /** - * Public constructor public FastqComparator(final boolean useSerializeFile) { - * super(useSerializeFile); } /** Public constructor - * @param useSerializeFile true if it needed to save BloomFilter in file with - * extension '.ser' - */ - public SAMComparator(final boolean useSerializeFile) { - super(useSerializeFile); - - this.tagsToNotCompare = new HashSet<>(); - } - - /** - * Public constructor, specify all headers tags not used to compare. - * @param useSerializeFile true if it needed to save BloomFilter in file with - * extension '.ser' - * @param headersTags all headers tags - */ - public SAMComparator(boolean useSerializeFile, String... headersTags) { - super(useSerializeFile); - - if (headersTags == null) - throw new NullPointerException("headersTags is null"); - - this.tagsToNotCompare = Sets.newHashSet(headersTags); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/pair.info deleted file mode 100755 index 0ec1c9b..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32693/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:32693 -comSha:a8aa6a4d759a91a3a112cfecab982ca64e4135fd -parentComSha:d118dfdf1a72f3e4a0f33ced5071e4d1038c9620 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/SAMComparator.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/SAMComparator.java -StartLineNum:57 -EndLineNum:57 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/comMsg.txt deleted file mode 100755 index d9d4ae0..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -With findbugs, fixes all bugs in Internationalization category. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/diff.diff deleted file mode 100755 index 0d7a8a7..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/steps/expression/HTSeqCount.java b/src/main/java/fr/ens/transcriptome/eoulsan/steps/expression/HTSeqCount.java -index a2ebb187..fa6424ef 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/steps/expression/HTSeqCount.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/steps/expression/HTSeqCount.java -@@ -28 +27,0 @@ import java.io.File; --import java.io.FileWriter; -@@ -52,0 +52 @@ import fr.ens.transcriptome.eoulsan.bio.io.GFFReader; -+import fr.ens.transcriptome.eoulsan.util.FileUtils; -@@ -72 +72 @@ public class HTSeqCount { -- Writer writer = new FileWriter(output); -+ Writer writer = FileUtils.createBufferedWriter(output); -@@ -291 +291 @@ public class HTSeqCount { -- Writer writer = new FileWriter(output); -+ Writer writer = FileUtils.createBufferedWriter(output); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/new/HTSeqCount.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/new/HTSeqCount.java deleted file mode 100755 index fa6424e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/new/HTSeqCount.java +++ /dev/null @@ -1,739 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.steps.expression; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import net.sf.samtools.Cigar; -import net.sf.samtools.CigarElement; -import net.sf.samtools.CigarOperator; -import net.sf.samtools.SAMFileReader; -import net.sf.samtools.SAMRecord; -import net.sf.samtools.SAMRecordIterator; -import fr.ens.transcriptome.eoulsan.EoulsanException; -import fr.ens.transcriptome.eoulsan.bio.BadBioEntryException; -import fr.ens.transcriptome.eoulsan.bio.GFFEntry; -import fr.ens.transcriptome.eoulsan.bio.GenomicArray; -import fr.ens.transcriptome.eoulsan.bio.GenomicInterval; -import fr.ens.transcriptome.eoulsan.bio.io.GFFReader; -import fr.ens.transcriptome.eoulsan.util.FileUtils; -import fr.ens.transcriptome.eoulsan.util.Utils; - -/** - * This class is the java implementation of the HTSeq-count program. - * @since 1.2 - * @author Laurent Jourdren - */ -public class HTSeqCount { - - public static void countReadsInFeatures(final File samFile, - final File gffFile, final File output, final String stranded, - final String overlapMode, final String featureType, - final String attributeId, final boolean quiet, final int minAverageQual, - final File samOutFile) throws EoulsanException, IOException, - BadBioEntryException { - - final GenomicArray features = new GenomicArray(); - final Map counts = Utils.newHashMap(); - - Writer writer = FileUtils.createBufferedWriter(output); - - boolean pairedEnd = false; - - final GFFReader gffReader = new GFFReader(gffFile); - - // Read the annotation file - for (final GFFEntry gff : gffReader) { - - if (featureType.equals(gff.getType())) { - - final String featureId = gff.getAttributeValue(attributeId); - if (featureId == null) { - writer.close(); - gffReader.close(); - throw new EoulsanException("Feature " - + featureType + " does not contain a " + attributeId - + " attribute"); - } - - if ((stranded.equals("yes") || stranded.equals("reverse")) - && '.' == gff.getStrand()) { - writer.close(); - gffReader.close(); - throw new EoulsanException("Feature " - + featureType - + " does not have strand information but you are running " - + "htseq-count in stranded mode."); - } - - // Addition to the list of features of a GenomicInterval object - // corresponding to the current annotation line - boolean saveStrandInfo = - "yes".equals(stranded) || "reverse".equals(stranded); - features.addEntry(new GenomicInterval(gff, saveStrandInfo), featureId); - counts.put(featureId, 0); - } - } - gffReader.throwException(); - gffReader.close(); - - if (counts.size() == 0) { - writer.close(); - throw new EoulsanException("Warning: No features of type '" - + featureType + "' found.\n"); - } - - List ivSeq = new ArrayList(); - - final SAMFileReader inputSam = new SAMFileReader(samFile); - - // paired-end mode ? - final SAMFileReader input = new SAMFileReader(samFile); - SAMRecordIterator samIterator = input.iterator(); - SAMRecord firstRecord = samIterator.next(); - if (firstRecord.getReadPairedFlag()) - pairedEnd = true; - input.close(); - - int empty = 0; - int ambiguous = 0; - int notaligned = 0; - int lowqual = 0; - int nonunique = 0; - int i = 0; - SAMRecord sam1 = null, sam2 = null; - - // Read the SAM file - for (final SAMRecord samRecord : inputSam) { - - i++; - if (i % 1000000 == 0) - System.out.println(i + " sam entries read."); - - // single-end mode - if (!pairedEnd) { - - ivSeq.clear(); - - // unmapped read - if (samRecord.getReadUnmappedFlag()) { - notaligned++; - // System.out.println("not_aligned"); - continue; - } - - // multiple alignment - if (samRecord.getAttribute("NH") != null - && samRecord.getIntegerAttribute("NH") > 1) { - nonunique++; - // System.out.println("non_unique"); - continue; - } - - // too low quality - if (samRecord.getMappingQuality() < minAverageQual) { - lowqual++; - continue; - } - - ivSeq.addAll(addIntervals(samRecord, stranded)); - - } - - // paired-end mode - else { - - if (sam1 != null && sam2 != null) { - sam1 = null; - sam2 = null; - ivSeq.clear(); - } - - if (samRecord.getFirstOfPairFlag()) - sam1 = samRecord; - else - sam2 = samRecord; - - if (sam1 == null || sam2 == null) - continue; - - if (!sam1.getReadName().equals(sam2.getReadName())) { - sam1 = sam2; - sam2 = null; - continue; - } - - if (sam1 != null && !sam1.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam1, stranded)); - } - - if (sam2 != null && !sam2.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam2, stranded)); - } - - // unmapped read - if (sam1.getReadUnmappedFlag() && sam2.getReadUnmappedFlag()) { - notaligned++; - continue; - } - - // multiple alignment - if ((sam1.getAttribute("NH") != null && sam1.getIntegerAttribute("NH") > 1) - || (sam2.getAttribute("NH") != null && sam2 - .getIntegerAttribute("NH") > 1)) { - nonunique++; - continue; - } - - // too low quality - if (sam1.getMappingQuality() < minAverageQual - || sam2.getMappingQuality() < minAverageQual) { - lowqual++; - continue; - } - - } - - Set fs = null; - - fs = featuresOverlapped(ivSeq, features, overlapMode, stranded); - - if (fs == null) - fs = new HashSet(); - - switch (fs.size()) { - case 0: - empty++; - // writer.write("no_feature\n"); - // System.out.println("no_feature"); - break; - - case 1: - final String id = fs.iterator().next(); - counts.put(id, counts.get(id) + 1); - // writer.write("count\n"); - // System.out.println("count"); - break; - - default: - ambiguous++; - // writer.write("ambiguous\n"); - // System.out.println("ambiguous"); - break; - } - - } - - inputSam.close(); - - final List keysSorted = new ArrayList(counts.keySet()); - Collections.sort(keysSorted); - - // Writer writer = new - // FileWriter("/home/wallon/Bureau/TEST_HTSEQ/test-java"); - - for (String key : keysSorted) { - writer.write(key + "\t" + counts.get(key) + "\n"); - } - - writer.write("no_feature\t%" + empty + '\n'); - writer.write("ambiguous\t%d\n" + ambiguous + '\n'); - writer.write("too_low_aQual\t%d\n" + lowqual + '\n'); - writer.write("not_aligned\t%d\n" + notaligned + '\n'); - writer.write("alignment_not_unique\t%d\n" + nonunique + '\n'); - - writer.close(); - } - - public static void countReadsInFeatures(final InputStream samFile, - final File gffFile, final File output, final String stranded, - final String overlapMode, final String featureType, - final String attributeId, final boolean quiet, final int minAverageQual, - final File samOutFile) throws EoulsanException, IOException, - BadBioEntryException { - - final GenomicArray features = new GenomicArray(); - final Map counts = Utils.newHashMap(); - - Writer writer = FileUtils.createBufferedWriter(output); - - boolean pairedEnd = false; - - final GFFReader gffReader = new GFFReader(gffFile); - - // Read the annotation file - for (final GFFEntry gff : gffReader) { - - if (featureType.equals(gff.getType())) { - - final String featureId = gff.getAttributeValue(attributeId); - if (featureId == null) { - writer.close(); - gffReader.close(); - throw new EoulsanException("Feature " - + featureType + " does not contain a " + attributeId - + " attribute"); - } - - if (stranded.equals("yes") && '.' == gff.getStrand()) { - writer.close(); - gffReader.close(); - throw new EoulsanException("Feature " - + featureType - + " does not have strand information but you are running " - + "htseq-count in stranded mode."); - } - - // Addition to the list of features of a GenomicInterval object - // corresponding to the current annotation line - boolean saveStrandInfo = - "yes".equals(stranded) || "reverse".equals(stranded); - features.addEntry(new GenomicInterval(gff, saveStrandInfo), featureId); - counts.put(featureId, 0); - } - } - gffReader.throwException(); - gffReader.close(); - - if (counts.size() == 0) { - writer.close(); - throw new EoulsanException("Warning: No features of type '" - + featureType + "' found.\n"); - } - - List ivSeq = new ArrayList(); - - final SAMFileReader inputSam = new SAMFileReader(samFile); - - // paired-end mode ? - final SAMFileReader input = new SAMFileReader(samFile); - SAMRecordIterator samIterator = input.iterator(); - SAMRecord firstRecord; - if (samIterator.hasNext()) - firstRecord = samIterator.next(); - else { - writer.close(); - input.close(); - inputSam.close(); - throw new EoulsanException("The SAM file is empty."); - } - if (firstRecord.getReadPairedFlag()) - pairedEnd = true; - input.close(); - - int empty = 0; - int ambiguous = 0; - int notaligned = 0; - int lowqual = 0; - int nonunique = 0; - int i = 0; - SAMRecord sam1 = null, sam2 = null; - - // Read the SAM file - for (final SAMRecord samRecord : inputSam) { - - i++; - if (i % 1000000 == 0) - System.out.println(i + " sam entries read."); - - // single-end mode - if (!pairedEnd) { - - ivSeq.clear(); - - // unmapped read - if (samRecord.getReadUnmappedFlag()) { - notaligned++; - continue; - } - - // multiple alignment - if (samRecord.getAttribute("NH") != null - && samRecord.getIntegerAttribute("NH") > 1) { - nonunique++; - continue; - } - - // too low quality - if (samRecord.getMappingQuality() < minAverageQual) { - lowqual++; - continue; - } - - ivSeq.addAll(addIntervals(samRecord, stranded)); - - } - - // paired-end mode - else { - - if (sam1 != null && sam2 != null) { - sam1 = null; - sam2 = null; - ivSeq.clear(); - } - - if (samRecord.getFirstOfPairFlag()) - sam1 = samRecord; - else - sam2 = samRecord; - - if (sam1 == null || sam2 == null) - continue; - - if (!sam1.getReadName().equals(sam2.getReadName())) { - sam1 = sam2; - sam2 = null; - continue; - } - - if (sam1 != null && !sam1.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam1, stranded)); - } - - if (sam2 != null && !sam2.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam2, stranded)); - } - - // unmapped read - if (sam1.getReadUnmappedFlag() && sam2.getReadUnmappedFlag()) { - notaligned++; - continue; - } - - // multiple alignment - if ((sam1.getAttribute("NH") != null && sam1.getIntegerAttribute("NH") > 1) - || (sam2.getAttribute("NH") != null && sam2 - .getIntegerAttribute("NH") > 1)) { - nonunique++; - continue; - } - - // too low quality - if (sam1.getMappingQuality() < minAverageQual - || sam2.getMappingQuality() < minAverageQual) { - lowqual++; - continue; - } - - } - - Set fs = null; - - fs = featuresOverlapped(ivSeq, features, overlapMode, stranded); - - if (fs == null) - fs = new HashSet(); - - switch (fs.size()) { - case 0: - empty++; - break; - - case 1: - final String id = fs.iterator().next(); - counts.put(id, counts.get(id) + 1); - break; - - default: - ambiguous++; - break; - } - - } - - inputSam.close(); - - final List keysSorted = new ArrayList(counts.keySet()); - Collections.sort(keysSorted); - - for (String key : keysSorted) { - writer.write(key + "\t" + counts.get(key) + "\n"); - } - - writer.write("no_feature\t" + empty + '\n'); - writer.write("ambiguous\t" + ambiguous + '\n'); - writer.write("too_low_aQual\t" + lowqual + '\n'); - writer.write("not_aligned\t" + notaligned + '\n'); - writer.write("alignment_not_unique\t" + nonunique + '\n'); - - writer.close(); - } - - private static Set featuresOverlapped(List ivList, - GenomicArray features, String mode, String stranded) - throws EoulsanException { - - Set fs = null; - Map inter = new HashMap(); - - // Overlap mode "union" - if (mode.equals("union")) { - - fs = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded.equals("yes") || stranded.equals("reverse")) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - if (intervals != null) { - Collection values = intervals.values(); - if (values != null) { - fs.addAll(values); - } - } - } - } - - // Overlap mode "intersection-nonempty" - else if (mode.equals("intersection-nonempty")) { - - final Set featureTmp = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlapped the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded.equals("yes") || stranded.equals("reverse")) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // At least one interval is found - if (intervals != null) { - Collection values = intervals.values(); - if (values != null) { - - for (int pos = iv.getStart(); pos <= iv.getEnd(); pos++) { - - featureTmp.clear(); - - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().include(pos, pos)) - featureTmp.add(e.getValue()); - } - - if (featureTmp.size() > 0) { - if (fs == null) { - fs = new HashSet(); - fs.addAll(featureTmp); - } else - fs.retainAll(featureTmp); - } - - } - } - } - } - } - - // Overlap mode "intersection-strict" - else if ("intersection-strict".equals(mode)) { - - final Set featureTmp = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlapped the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded.equals("yes") || stranded.equals("reverse")) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // At least one interval is found - if (intervals != null) { - Collection values = intervals.values(); - if (values != null) { - - for (int pos = iv.getStart(); pos <= iv.getEnd(); pos++) { - - featureTmp.clear(); - - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().include(pos, pos)) { - featureTmp.add(e.getValue()); - } - } - - if (fs == null) { - fs = new HashSet(); - fs.addAll(featureTmp); - } else - fs.retainAll(featureTmp); - } - } - } - - // no interval found - else { - if (fs == null) - fs = new HashSet(); - else - fs.clear(); - } - - } - } - - return fs; - } - - private static List addIntervals(SAMRecord record, - String stranded) { - - if (record == null) - return null; - - List result = new ArrayList(); - - if (!record.getReadPairedFlag() - || (record.getReadPairedFlag() && record.getFirstOfPairFlag())) { - if ("reverse".equals(stranded)) - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '+' : '-')); - else - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '-' : '+')); - } - - else if (record.getReadPairedFlag() && !record.getFirstOfPairFlag()) { - if ("reverse".equals(stranded)) - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '-' : '+')); - else - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '+' : '-')); - } - - return result; - } - - private static final List parseCigar(Cigar cigar, - final String chromosome, final int start, final char strand) { - - if (cigar == null) - return null; - - final List result = new ArrayList(); - - int pos = start; - for (CigarElement ce : cigar.getCigarElements()) { - - final int len = ce.getLength(); - - // the CIGAR element correspond to a mapped region - if (ce.getOperator() == CigarOperator.M) { - result.add(new GenomicInterval(chromosome, pos, pos + len - 1, strand)); - pos += len; - } - // the CIGAR element did not correspond to a mapped region - else { - // regions coded by a 'I' (insertion) do not have to be counted - // (are there other cases like this one ?) - if (pos != start && ce.getOperator() != CigarOperator.I) - pos += len; - } - } - - return result; - } - - public static void main(String[] args) throws EoulsanException, IOException, - BadBioEntryException { - - final File dir = new File("/home/wallon/Bureau/TEST_HTSEQ/EOULSAN"); - // final File samFile = new File(dir, "filtered_mapper_results_1.sam"); - // final File samFile = new - // File("/home/wallon/Bureau/GSNAP/PE/500head.sam"); - final File samFile = new File(dir, "filtered_mapper_results_1.sam"); - final File gffFile = new File("/home/wallon/Bureau/DATA/annotation.gff"); - // final File gffFile = new File("/home/wallon/Bureau/GSNAP/PE/mouse.gff"); - final File output = new File(dir, "test-java-strict-yes"); - - final long startTime = System.currentTimeMillis(); - System.out.println("start."); - countReadsInFeatures(samFile, gffFile, output, "yes", - "intersection-strict", "exon", "ID", false, 0, null); - System.out.println("end."); - System.out.println("Duration: " - + (System.currentTimeMillis() - startTime) + " ms."); - - // Python - // real 19m51.548s - // user 19m9.692s - // sys 0m13.385s - - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/old/HTSeqCount.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/old/HTSeqCount.java deleted file mode 100755 index a2ebb18..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/old/HTSeqCount.java +++ /dev/null @@ -1,739 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.steps.expression; - -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import net.sf.samtools.Cigar; -import net.sf.samtools.CigarElement; -import net.sf.samtools.CigarOperator; -import net.sf.samtools.SAMFileReader; -import net.sf.samtools.SAMRecord; -import net.sf.samtools.SAMRecordIterator; -import fr.ens.transcriptome.eoulsan.EoulsanException; -import fr.ens.transcriptome.eoulsan.bio.BadBioEntryException; -import fr.ens.transcriptome.eoulsan.bio.GFFEntry; -import fr.ens.transcriptome.eoulsan.bio.GenomicArray; -import fr.ens.transcriptome.eoulsan.bio.GenomicInterval; -import fr.ens.transcriptome.eoulsan.bio.io.GFFReader; -import fr.ens.transcriptome.eoulsan.util.Utils; - -/** - * This class is the java implementation of the HTSeq-count program. - * @since 1.2 - * @author Laurent Jourdren - */ -public class HTSeqCount { - - public static void countReadsInFeatures(final File samFile, - final File gffFile, final File output, final String stranded, - final String overlapMode, final String featureType, - final String attributeId, final boolean quiet, final int minAverageQual, - final File samOutFile) throws EoulsanException, IOException, - BadBioEntryException { - - final GenomicArray features = new GenomicArray(); - final Map counts = Utils.newHashMap(); - - Writer writer = new FileWriter(output); - - boolean pairedEnd = false; - - final GFFReader gffReader = new GFFReader(gffFile); - - // Read the annotation file - for (final GFFEntry gff : gffReader) { - - if (featureType.equals(gff.getType())) { - - final String featureId = gff.getAttributeValue(attributeId); - if (featureId == null) { - writer.close(); - gffReader.close(); - throw new EoulsanException("Feature " - + featureType + " does not contain a " + attributeId - + " attribute"); - } - - if ((stranded.equals("yes") || stranded.equals("reverse")) - && '.' == gff.getStrand()) { - writer.close(); - gffReader.close(); - throw new EoulsanException("Feature " - + featureType - + " does not have strand information but you are running " - + "htseq-count in stranded mode."); - } - - // Addition to the list of features of a GenomicInterval object - // corresponding to the current annotation line - boolean saveStrandInfo = - "yes".equals(stranded) || "reverse".equals(stranded); - features.addEntry(new GenomicInterval(gff, saveStrandInfo), featureId); - counts.put(featureId, 0); - } - } - gffReader.throwException(); - gffReader.close(); - - if (counts.size() == 0) { - writer.close(); - throw new EoulsanException("Warning: No features of type '" - + featureType + "' found.\n"); - } - - List ivSeq = new ArrayList(); - - final SAMFileReader inputSam = new SAMFileReader(samFile); - - // paired-end mode ? - final SAMFileReader input = new SAMFileReader(samFile); - SAMRecordIterator samIterator = input.iterator(); - SAMRecord firstRecord = samIterator.next(); - if (firstRecord.getReadPairedFlag()) - pairedEnd = true; - input.close(); - - int empty = 0; - int ambiguous = 0; - int notaligned = 0; - int lowqual = 0; - int nonunique = 0; - int i = 0; - SAMRecord sam1 = null, sam2 = null; - - // Read the SAM file - for (final SAMRecord samRecord : inputSam) { - - i++; - if (i % 1000000 == 0) - System.out.println(i + " sam entries read."); - - // single-end mode - if (!pairedEnd) { - - ivSeq.clear(); - - // unmapped read - if (samRecord.getReadUnmappedFlag()) { - notaligned++; - // System.out.println("not_aligned"); - continue; - } - - // multiple alignment - if (samRecord.getAttribute("NH") != null - && samRecord.getIntegerAttribute("NH") > 1) { - nonunique++; - // System.out.println("non_unique"); - continue; - } - - // too low quality - if (samRecord.getMappingQuality() < minAverageQual) { - lowqual++; - continue; - } - - ivSeq.addAll(addIntervals(samRecord, stranded)); - - } - - // paired-end mode - else { - - if (sam1 != null && sam2 != null) { - sam1 = null; - sam2 = null; - ivSeq.clear(); - } - - if (samRecord.getFirstOfPairFlag()) - sam1 = samRecord; - else - sam2 = samRecord; - - if (sam1 == null || sam2 == null) - continue; - - if (!sam1.getReadName().equals(sam2.getReadName())) { - sam1 = sam2; - sam2 = null; - continue; - } - - if (sam1 != null && !sam1.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam1, stranded)); - } - - if (sam2 != null && !sam2.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam2, stranded)); - } - - // unmapped read - if (sam1.getReadUnmappedFlag() && sam2.getReadUnmappedFlag()) { - notaligned++; - continue; - } - - // multiple alignment - if ((sam1.getAttribute("NH") != null && sam1.getIntegerAttribute("NH") > 1) - || (sam2.getAttribute("NH") != null && sam2 - .getIntegerAttribute("NH") > 1)) { - nonunique++; - continue; - } - - // too low quality - if (sam1.getMappingQuality() < minAverageQual - || sam2.getMappingQuality() < minAverageQual) { - lowqual++; - continue; - } - - } - - Set fs = null; - - fs = featuresOverlapped(ivSeq, features, overlapMode, stranded); - - if (fs == null) - fs = new HashSet(); - - switch (fs.size()) { - case 0: - empty++; - // writer.write("no_feature\n"); - // System.out.println("no_feature"); - break; - - case 1: - final String id = fs.iterator().next(); - counts.put(id, counts.get(id) + 1); - // writer.write("count\n"); - // System.out.println("count"); - break; - - default: - ambiguous++; - // writer.write("ambiguous\n"); - // System.out.println("ambiguous"); - break; - } - - } - - inputSam.close(); - - final List keysSorted = new ArrayList(counts.keySet()); - Collections.sort(keysSorted); - - // Writer writer = new - // FileWriter("/home/wallon/Bureau/TEST_HTSEQ/test-java"); - - for (String key : keysSorted) { - writer.write(key + "\t" + counts.get(key) + "\n"); - } - - writer.write("no_feature\t%" + empty + '\n'); - writer.write("ambiguous\t%d\n" + ambiguous + '\n'); - writer.write("too_low_aQual\t%d\n" + lowqual + '\n'); - writer.write("not_aligned\t%d\n" + notaligned + '\n'); - writer.write("alignment_not_unique\t%d\n" + nonunique + '\n'); - - writer.close(); - } - - public static void countReadsInFeatures(final InputStream samFile, - final File gffFile, final File output, final String stranded, - final String overlapMode, final String featureType, - final String attributeId, final boolean quiet, final int minAverageQual, - final File samOutFile) throws EoulsanException, IOException, - BadBioEntryException { - - final GenomicArray features = new GenomicArray(); - final Map counts = Utils.newHashMap(); - - Writer writer = new FileWriter(output); - - boolean pairedEnd = false; - - final GFFReader gffReader = new GFFReader(gffFile); - - // Read the annotation file - for (final GFFEntry gff : gffReader) { - - if (featureType.equals(gff.getType())) { - - final String featureId = gff.getAttributeValue(attributeId); - if (featureId == null) { - writer.close(); - gffReader.close(); - throw new EoulsanException("Feature " - + featureType + " does not contain a " + attributeId - + " attribute"); - } - - if (stranded.equals("yes") && '.' == gff.getStrand()) { - writer.close(); - gffReader.close(); - throw new EoulsanException("Feature " - + featureType - + " does not have strand information but you are running " - + "htseq-count in stranded mode."); - } - - // Addition to the list of features of a GenomicInterval object - // corresponding to the current annotation line - boolean saveStrandInfo = - "yes".equals(stranded) || "reverse".equals(stranded); - features.addEntry(new GenomicInterval(gff, saveStrandInfo), featureId); - counts.put(featureId, 0); - } - } - gffReader.throwException(); - gffReader.close(); - - if (counts.size() == 0) { - writer.close(); - throw new EoulsanException("Warning: No features of type '" - + featureType + "' found.\n"); - } - - List ivSeq = new ArrayList(); - - final SAMFileReader inputSam = new SAMFileReader(samFile); - - // paired-end mode ? - final SAMFileReader input = new SAMFileReader(samFile); - SAMRecordIterator samIterator = input.iterator(); - SAMRecord firstRecord; - if (samIterator.hasNext()) - firstRecord = samIterator.next(); - else { - writer.close(); - input.close(); - inputSam.close(); - throw new EoulsanException("The SAM file is empty."); - } - if (firstRecord.getReadPairedFlag()) - pairedEnd = true; - input.close(); - - int empty = 0; - int ambiguous = 0; - int notaligned = 0; - int lowqual = 0; - int nonunique = 0; - int i = 0; - SAMRecord sam1 = null, sam2 = null; - - // Read the SAM file - for (final SAMRecord samRecord : inputSam) { - - i++; - if (i % 1000000 == 0) - System.out.println(i + " sam entries read."); - - // single-end mode - if (!pairedEnd) { - - ivSeq.clear(); - - // unmapped read - if (samRecord.getReadUnmappedFlag()) { - notaligned++; - continue; - } - - // multiple alignment - if (samRecord.getAttribute("NH") != null - && samRecord.getIntegerAttribute("NH") > 1) { - nonunique++; - continue; - } - - // too low quality - if (samRecord.getMappingQuality() < minAverageQual) { - lowqual++; - continue; - } - - ivSeq.addAll(addIntervals(samRecord, stranded)); - - } - - // paired-end mode - else { - - if (sam1 != null && sam2 != null) { - sam1 = null; - sam2 = null; - ivSeq.clear(); - } - - if (samRecord.getFirstOfPairFlag()) - sam1 = samRecord; - else - sam2 = samRecord; - - if (sam1 == null || sam2 == null) - continue; - - if (!sam1.getReadName().equals(sam2.getReadName())) { - sam1 = sam2; - sam2 = null; - continue; - } - - if (sam1 != null && !sam1.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam1, stranded)); - } - - if (sam2 != null && !sam2.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam2, stranded)); - } - - // unmapped read - if (sam1.getReadUnmappedFlag() && sam2.getReadUnmappedFlag()) { - notaligned++; - continue; - } - - // multiple alignment - if ((sam1.getAttribute("NH") != null && sam1.getIntegerAttribute("NH") > 1) - || (sam2.getAttribute("NH") != null && sam2 - .getIntegerAttribute("NH") > 1)) { - nonunique++; - continue; - } - - // too low quality - if (sam1.getMappingQuality() < minAverageQual - || sam2.getMappingQuality() < minAverageQual) { - lowqual++; - continue; - } - - } - - Set fs = null; - - fs = featuresOverlapped(ivSeq, features, overlapMode, stranded); - - if (fs == null) - fs = new HashSet(); - - switch (fs.size()) { - case 0: - empty++; - break; - - case 1: - final String id = fs.iterator().next(); - counts.put(id, counts.get(id) + 1); - break; - - default: - ambiguous++; - break; - } - - } - - inputSam.close(); - - final List keysSorted = new ArrayList(counts.keySet()); - Collections.sort(keysSorted); - - for (String key : keysSorted) { - writer.write(key + "\t" + counts.get(key) + "\n"); - } - - writer.write("no_feature\t" + empty + '\n'); - writer.write("ambiguous\t" + ambiguous + '\n'); - writer.write("too_low_aQual\t" + lowqual + '\n'); - writer.write("not_aligned\t" + notaligned + '\n'); - writer.write("alignment_not_unique\t" + nonunique + '\n'); - - writer.close(); - } - - private static Set featuresOverlapped(List ivList, - GenomicArray features, String mode, String stranded) - throws EoulsanException { - - Set fs = null; - Map inter = new HashMap(); - - // Overlap mode "union" - if (mode.equals("union")) { - - fs = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded.equals("yes") || stranded.equals("reverse")) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - if (intervals != null) { - Collection values = intervals.values(); - if (values != null) { - fs.addAll(values); - } - } - } - } - - // Overlap mode "intersection-nonempty" - else if (mode.equals("intersection-nonempty")) { - - final Set featureTmp = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlapped the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded.equals("yes") || stranded.equals("reverse")) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // At least one interval is found - if (intervals != null) { - Collection values = intervals.values(); - if (values != null) { - - for (int pos = iv.getStart(); pos <= iv.getEnd(); pos++) { - - featureTmp.clear(); - - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().include(pos, pos)) - featureTmp.add(e.getValue()); - } - - if (featureTmp.size() > 0) { - if (fs == null) { - fs = new HashSet(); - fs.addAll(featureTmp); - } else - fs.retainAll(featureTmp); - } - - } - } - } - } - } - - // Overlap mode "intersection-strict" - else if ("intersection-strict".equals(mode)) { - - final Set featureTmp = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlapped the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded.equals("yes") || stranded.equals("reverse")) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // At least one interval is found - if (intervals != null) { - Collection values = intervals.values(); - if (values != null) { - - for (int pos = iv.getStart(); pos <= iv.getEnd(); pos++) { - - featureTmp.clear(); - - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().include(pos, pos)) { - featureTmp.add(e.getValue()); - } - } - - if (fs == null) { - fs = new HashSet(); - fs.addAll(featureTmp); - } else - fs.retainAll(featureTmp); - } - } - } - - // no interval found - else { - if (fs == null) - fs = new HashSet(); - else - fs.clear(); - } - - } - } - - return fs; - } - - private static List addIntervals(SAMRecord record, - String stranded) { - - if (record == null) - return null; - - List result = new ArrayList(); - - if (!record.getReadPairedFlag() - || (record.getReadPairedFlag() && record.getFirstOfPairFlag())) { - if ("reverse".equals(stranded)) - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '+' : '-')); - else - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '-' : '+')); - } - - else if (record.getReadPairedFlag() && !record.getFirstOfPairFlag()) { - if ("reverse".equals(stranded)) - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '-' : '+')); - else - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '+' : '-')); - } - - return result; - } - - private static final List parseCigar(Cigar cigar, - final String chromosome, final int start, final char strand) { - - if (cigar == null) - return null; - - final List result = new ArrayList(); - - int pos = start; - for (CigarElement ce : cigar.getCigarElements()) { - - final int len = ce.getLength(); - - // the CIGAR element correspond to a mapped region - if (ce.getOperator() == CigarOperator.M) { - result.add(new GenomicInterval(chromosome, pos, pos + len - 1, strand)); - pos += len; - } - // the CIGAR element did not correspond to a mapped region - else { - // regions coded by a 'I' (insertion) do not have to be counted - // (are there other cases like this one ?) - if (pos != start && ce.getOperator() != CigarOperator.I) - pos += len; - } - } - - return result; - } - - public static void main(String[] args) throws EoulsanException, IOException, - BadBioEntryException { - - final File dir = new File("/home/wallon/Bureau/TEST_HTSEQ/EOULSAN"); - // final File samFile = new File(dir, "filtered_mapper_results_1.sam"); - // final File samFile = new - // File("/home/wallon/Bureau/GSNAP/PE/500head.sam"); - final File samFile = new File(dir, "filtered_mapper_results_1.sam"); - final File gffFile = new File("/home/wallon/Bureau/DATA/annotation.gff"); - // final File gffFile = new File("/home/wallon/Bureau/GSNAP/PE/mouse.gff"); - final File output = new File(dir, "test-java-strict-yes"); - - final long startTime = System.currentTimeMillis(); - System.out.println("start."); - countReadsInFeatures(samFile, gffFile, output, "yes", - "intersection-strict", "exon", "ID", false, 0, null); - System.out.println("end."); - System.out.println("Duration: " - + (System.currentTimeMillis() - startTime) + " ms."); - - // Python - // real 19m51.548s - // user 19m9.692s - // sys 0m13.385s - - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/pair.info deleted file mode 100755 index 555b156..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#32871/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:32871 -comSha:8ae4eb8cfcb27185be49de726d96703b5911be67 -parentComSha:30cbbe29c7dfa484099ae2b1a2ac1e301b208fe5 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/steps/expression/HTSeqCount.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/steps/expression/HTSeqCount.java -StartLineNum:72 -EndLineNum:72 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/comMsg.txt deleted file mode 100755 index 846907d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Many code fix after findbugs. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/diff.diff deleted file mode 100755 index 3d84afc..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/checkers/GenomeChecker.java b/src/main/java/fr/ens/transcriptome/eoulsan/checkers/GenomeChecker.java -index e5820273..f77ad028 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/checkers/GenomeChecker.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/checkers/GenomeChecker.java -@@ -36,0 +37 @@ import fr.ens.transcriptome.eoulsan.EoulsanException; -+import fr.ens.transcriptome.eoulsan.Globals; -@@ -123 +124,3 @@ public class GenomeChecker implements Checker { -- final BufferedReader br = new BufferedReader(new InputStreamReader(is)); -+ final BufferedReader br = -+ new BufferedReader(new InputStreamReader(is, -+ Globals.DEFAULT_FILE_ENCODING)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/new/GenomeChecker.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/new/GenomeChecker.java deleted file mode 100755 index f77ad02..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/new/GenomeChecker.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.checkers; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import fr.ens.transcriptome.eoulsan.EoulsanException; -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.bio.BadBioEntryException; -import fr.ens.transcriptome.eoulsan.core.Context; -import fr.ens.transcriptome.eoulsan.core.Parameter; -import fr.ens.transcriptome.eoulsan.data.DataFile; -import fr.ens.transcriptome.eoulsan.data.DataFormats; -import fr.ens.transcriptome.eoulsan.design.Design; -import fr.ens.transcriptome.eoulsan.design.Sample; - -public class GenomeChecker implements Checker { - - public static final String INFO_CHROMOSOME = "info_chromosomes"; - - @Override - public String getName() { - - return "genome_checker"; - } - - @Override - public void configure(final Set stepParameters) - throws EoulsanException { - } - - @Override - public boolean check(final Design design, final Context context, - final CheckStore checkInfo) throws EoulsanException { - - if (design == null) - throw new NullPointerException("The design is null"); - - if (context == null) - throw new NullPointerException("The execution context is null"); - - if (checkInfo == null) - throw new NullPointerException("The check info info is null"); - - final List samples = design.getSamples(); - - if (samples == null) - throw new NullPointerException("The samples are null"); - - if (samples.size() == 0) - throw new EoulsanException("No samples found in design"); - - // If genome has already been checked do not launch check another time - if (checkInfo.contains(INFO_CHROMOSOME)) { - context.getLogger().info("Genome check has already been done"); - return true; - } - - final Sample s = samples.get(0); - - final InputStream is; - - final DataFile file = context.getOtherDataFile(DataFormats.GENOME_FASTA, s); - try { - - if (!file.exists()) - return true; - - is = file.open(); - - checkInfo.add(INFO_CHROMOSOME, checkGenomeFile(is)); - - } catch (IOException e) { - throw new EoulsanException("Error while reading genome " - + file.getSource() + " for checking"); - } catch (BadBioEntryException e) { - throw new EoulsanException("Found bad read entry in genome " - + file.getSource() + ": " + e.getMessage()); - } - - return true; - } - - /** - * Check a genome file. - * @param is Input stream to read for the checking - * @return a map the the sizes of the chromosomes - * @throws IOException if an error occurs while reading data - * @throws BadBioEntryException if the name or the sequence of the chromosome - * is not valid - */ - private Map checkGenomeFile(final InputStream is) - throws IOException, BadBioEntryException { - - final BufferedReader br = - new BufferedReader(new InputStreamReader(is, - Globals.DEFAULT_FILE_ENCODING)); - - String line = null; - - final Map chromosomes = new HashMap(); - String currentChr = null; - int currentSize = 0; - - while ((line = br.readLine()) != null) { - - line = line.trim(); - if ("".equals(line)) - continue; - - if (line.startsWith(">")) { - chromosomes.put(currentChr, currentSize); - currentChr = parseFastaEntryHeader(line); - - // Check if two sequences exists with the same name exists - if (chromosomes.containsKey(currentChr)) - throw new BadBioEntryException("Sequence name found twice: " - + currentChr, line); - - currentSize = 0; - } else { - if (currentChr == null) - throw new BadBioEntryException( - "No fasta header found at the start of the fasta file.", line); - currentSize += checkBases(line.trim()); - } - } - - chromosomes.put(currentChr, currentSize); - - is.close(); - return chromosomes; - } - - /** - * Check the base used in a sequence - * @param sequence sequence - * @return the length of the sequence - * @throws BadBioEntryException if an invalid base is found - */ - private int checkBases(final String sequence) throws BadBioEntryException { - - final int len = sequence.length(); - - for (int i = 0; i < len; i++) - switch (sequence.charAt(i)) { - - case 'A': - case 'a': - case 'C': - case 'c': - case 'G': - case 'g': - case 'T': - case 't': - case 'U': - case 'R': - case 'Y': - case 'K': - case 'M': - case 'S': - case 'W': - case 'B': - case 'D': - case 'H': - case 'V': - case 'N': - case 'n': - - break; - - default: - throw new BadBioEntryException("Invalid base in genome: " - + sequence.charAt(i), sequence); - } - - return len; - } - - /** - * Parse a fasta entry header. - * @param fastaHeader fasta header - * @return the first word of the header - * @throws BadBioEntryException if there is an error in the name of the - * sequence - */ - private String parseFastaEntryHeader(final String fastaHeader) - throws BadBioEntryException { - - if (fastaHeader == null) - return null; - - final String s = fastaHeader.substring(1); - - if (s.startsWith(" ")) - throw new BadBioEntryException( - "A whitespace was found at the begining of the sequence name: ", - fastaHeader); - - String[] fields = s.split("\\s"); - - if (fields == null || fields.length == 0) - throw new BadBioEntryException("Invalid sequence header", fastaHeader); - - final String result = fields[0].trim(); - - if ("".equals(result)) - throw new BadBioEntryException("Invalid sequence name: " + result, - fastaHeader); - - return result; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/old/GenomeChecker.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/old/GenomeChecker.java deleted file mode 100755 index e582027..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/old/GenomeChecker.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.checkers; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import fr.ens.transcriptome.eoulsan.EoulsanException; -import fr.ens.transcriptome.eoulsan.bio.BadBioEntryException; -import fr.ens.transcriptome.eoulsan.core.Context; -import fr.ens.transcriptome.eoulsan.core.Parameter; -import fr.ens.transcriptome.eoulsan.data.DataFile; -import fr.ens.transcriptome.eoulsan.data.DataFormats; -import fr.ens.transcriptome.eoulsan.design.Design; -import fr.ens.transcriptome.eoulsan.design.Sample; - -public class GenomeChecker implements Checker { - - public static final String INFO_CHROMOSOME = "info_chromosomes"; - - @Override - public String getName() { - - return "genome_checker"; - } - - @Override - public void configure(final Set stepParameters) - throws EoulsanException { - } - - @Override - public boolean check(final Design design, final Context context, - final CheckStore checkInfo) throws EoulsanException { - - if (design == null) - throw new NullPointerException("The design is null"); - - if (context == null) - throw new NullPointerException("The execution context is null"); - - if (checkInfo == null) - throw new NullPointerException("The check info info is null"); - - final List samples = design.getSamples(); - - if (samples == null) - throw new NullPointerException("The samples are null"); - - if (samples.size() == 0) - throw new EoulsanException("No samples found in design"); - - // If genome has already been checked do not launch check another time - if (checkInfo.contains(INFO_CHROMOSOME)) { - context.getLogger().info("Genome check has already been done"); - return true; - } - - final Sample s = samples.get(0); - - final InputStream is; - - final DataFile file = context.getOtherDataFile(DataFormats.GENOME_FASTA, s); - try { - - if (!file.exists()) - return true; - - is = file.open(); - - checkInfo.add(INFO_CHROMOSOME, checkGenomeFile(is)); - - } catch (IOException e) { - throw new EoulsanException("Error while reading genome " - + file.getSource() + " for checking"); - } catch (BadBioEntryException e) { - throw new EoulsanException("Found bad read entry in genome " - + file.getSource() + ": " + e.getMessage()); - } - - return true; - } - - /** - * Check a genome file. - * @param is Input stream to read for the checking - * @return a map the the sizes of the chromosomes - * @throws IOException if an error occurs while reading data - * @throws BadBioEntryException if the name or the sequence of the chromosome - * is not valid - */ - private Map checkGenomeFile(final InputStream is) - throws IOException, BadBioEntryException { - - final BufferedReader br = new BufferedReader(new InputStreamReader(is)); - - String line = null; - - final Map chromosomes = new HashMap(); - String currentChr = null; - int currentSize = 0; - - while ((line = br.readLine()) != null) { - - line = line.trim(); - if ("".equals(line)) - continue; - - if (line.startsWith(">")) { - chromosomes.put(currentChr, currentSize); - currentChr = parseFastaEntryHeader(line); - - // Check if two sequences exists with the same name exists - if (chromosomes.containsKey(currentChr)) - throw new BadBioEntryException("Sequence name found twice: " - + currentChr, line); - - currentSize = 0; - } else { - if (currentChr == null) - throw new BadBioEntryException( - "No fasta header found at the start of the fasta file.", line); - currentSize += checkBases(line.trim()); - } - } - - chromosomes.put(currentChr, currentSize); - - is.close(); - return chromosomes; - } - - /** - * Check the base used in a sequence - * @param sequence sequence - * @return the length of the sequence - * @throws BadBioEntryException if an invalid base is found - */ - private int checkBases(final String sequence) throws BadBioEntryException { - - final int len = sequence.length(); - - for (int i = 0; i < len; i++) - switch (sequence.charAt(i)) { - - case 'A': - case 'a': - case 'C': - case 'c': - case 'G': - case 'g': - case 'T': - case 't': - case 'U': - case 'R': - case 'Y': - case 'K': - case 'M': - case 'S': - case 'W': - case 'B': - case 'D': - case 'H': - case 'V': - case 'N': - case 'n': - - break; - - default: - throw new BadBioEntryException("Invalid base in genome: " - + sequence.charAt(i), sequence); - } - - return len; - } - - /** - * Parse a fasta entry header. - * @param fastaHeader fasta header - * @return the first word of the header - * @throws BadBioEntryException if there is an error in the name of the - * sequence - */ - private String parseFastaEntryHeader(final String fastaHeader) - throws BadBioEntryException { - - if (fastaHeader == null) - return null; - - final String s = fastaHeader.substring(1); - - if (s.startsWith(" ")) - throw new BadBioEntryException( - "A whitespace was found at the begining of the sequence name: ", - fastaHeader); - - String[] fields = s.split("\\s"); - - if (fields == null || fields.length == 0) - throw new BadBioEntryException("Invalid sequence header", fastaHeader); - - final String result = fields[0].trim(); - - if ("".equals(result)) - throw new BadBioEntryException("Invalid sequence name: " + result, - fastaHeader); - - return result; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/pair.info deleted file mode 100755 index 2a1d8ea..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33126/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:33126 -comSha:4a4f273ebcb53fc498dd0c45bc5dd4ea66cf5480 -parentComSha:237a7830c382d17dfa2fd10951c13d1ad46075b2 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/checkers/GenomeChecker.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/checkers/GenomeChecker.java -StartLineNum:123 -EndLineNum:123 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/comMsg.txt deleted file mode 100755 index 846907d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Many code fix after findbugs. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/diff.diff deleted file mode 100755 index b94c7f0..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/bio/GenomeDescription.java b/src/main/java/fr/ens/transcriptome/eoulsan/bio/GenomeDescription.java -index fe2b7e6c..ff32dccc 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/bio/GenomeDescription.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/bio/GenomeDescription.java -@@ -323 +323 @@ public class GenomeDescription { -- md5Digest.update(name.getBytes()); -+ md5Digest.update(name.getBytes(Globals.DEFAULT_FILE_ENCODING)); -@@ -327 +327 @@ public class GenomeDescription { -- md5Digest.update(s.getBytes()); -+ md5Digest.update(s.getBytes(Globals.DEFAULT_FILE_ENCODING)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/new/GenomeDescription.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/new/GenomeDescription.java deleted file mode 100755 index ff32dcc..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/new/GenomeDescription.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio; - -import static fr.ens.transcriptome.eoulsan.util.Utils.checkNotNull; -import static fr.ens.transcriptome.eoulsan.util.Utils.newArrayList; -import static fr.ens.transcriptome.eoulsan.util.Utils.newLinkedHashMap; -import static java.util.Arrays.asList; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Writer; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; - -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.bio.io.FastaReader; -import fr.ens.transcriptome.eoulsan.util.FileUtils; -import fr.ens.transcriptome.eoulsan.util.StringUtils; - -/** - * This class define a genome description. - * @author Laurent Jourdren - */ -public class GenomeDescription { - - /** Logger */ - private static final Logger LOGGER = Logger.getLogger(Globals.APP_NAME); - - private static final int STRING_LENGTH_BUFFER = 1024 * 1024; - - private static final String PREFIX = "genome."; - private static final String NAME_PREFIX = PREFIX + "name"; - private static final String LENGTH_PREFIX = PREFIX + "length"; - private static final String MD5_PREFIX = PREFIX + "md5"; - private static final String SEQUENCE_PREFIX = PREFIX + "sequence."; - private static final String SEQUENCES_COUNT_PREFIX = PREFIX + "sequences"; - - private String genomeName; - private Map sequences = newLinkedHashMap(); - private String md5Sum; - - // - // Setters - // - - /** - * Set the genome name. - * @param genomeName name of the genome - */ - private void setGenomeName(final String genomeName) { - - this.genomeName = genomeName; - } - - /** - * Add a sequence. - * @param sequenceName name of the sequence - * @param sequenceLength length of the sequence - */ - public void addSequence(final String sequenceName, final long sequenceLength) { - - LOGGER.fine("Add sequence: " - + sequenceName + " with " + sequenceLength + " pb"); - - this.sequences.put(sequenceName, sequenceLength); - } - - /** - * Set the md5 digest of the genome file - * @param md5Digest the md5 digest - */ - public void setMD5Sum(final String md5Digest) { - - this.md5Sum = md5Digest; - } - - // - // Getters - // - - /** - * Get the genome name. - * @return the genome name - */ - public String getGenomeName() { - - return this.genomeName; - } - - /** - * Get the length of a sequence - * @param sequenceName name of the sequence - * @return the length of the sequence or -1 if the sequence does not exists - */ - public long getSequenceLength(final String sequenceName) { - - if (this.sequences.containsKey(sequenceName)) { - - return this.sequences.get(sequenceName); - } - - return -1; - } - - /** - * Get the names of the sequences. - * @return a set with the name of the sequence - */ - public List getSequencesNames() { - - return Collections.unmodifiableList(newArrayList(this.sequences.keySet())); - } - - /** - * Get the md5 sum for the genome. - * @return the md5 sum - */ - public String getMD5Sum() { - - return this.md5Sum; - } - - /** - * Get the number of sequences in the genome. - * @return the number of sequences in the genome - */ - public int getSequenceCount() { - - return this.sequences.size(); - } - - /** - * Get the genome length; - * @return the genome length - */ - public long getGenomeLength() { - - long count = 0; - - for (Map.Entry e : this.sequences.entrySet()) - count += e.getValue(); - - return count; - } - - // - // Save description - // - - /** - * Save genome description. - * @param os OutputStream to use for genome description writing - */ - public void save(final OutputStream os) throws IOException { - - checkNotNull(os, "OutputStream is null"); - - final Writer writer = FileUtils.createFastBufferedWriter(os); - - if (this.genomeName != null) - writer.write(NAME_PREFIX + "=" + getGenomeName() + '\n'); - - if (this.md5Sum != null) - writer.write(MD5_PREFIX + "=" + getMD5Sum() + '\n'); - - writer.write(SEQUENCES_COUNT_PREFIX + '=' + getSequenceCount() + '\n'); - - writer.write(LENGTH_PREFIX + '=' + getGenomeLength() + '\n'); - - for (String seqName : getSequencesNames()) { - - writer.write(SEQUENCE_PREFIX - + seqName + "=" + getSequenceLength(seqName) + "\n"); - } - - writer.close(); - } - - /** - * Save genome description. - * @param file output file - */ - public void save(final File file) throws FileNotFoundException, IOException { - - checkNotNull(file, "File is null"); - save(FileUtils.createOutputStream(file)); - } - - // - // Load description - // - - /** - * Load genome description. - * @param is InputStream to use - */ - public static GenomeDescription load(final InputStream is) throws IOException { - - checkNotNull(is, "InputStream is null"); - - final GenomeDescription result = new GenomeDescription(); - - final BufferedReader read = FileUtils.createBufferedReader(is); - - String line = null; - - while ((line = read.readLine()) != null) { - - final List fields = asList(line.split("=")); - - if (fields.size() > 1) { - - final String key = fields.get(0).trim(); - - if (key.startsWith(NAME_PREFIX)) - result.setGenomeName(fields.get(1)); - if (key.startsWith(MD5_PREFIX)) - result.setMD5Sum(fields.get(1)); - else - try { - if (key.startsWith(SEQUENCE_PREFIX)) - result.addSequence(key.substring(SEQUENCE_PREFIX.length()), - Integer.parseInt(fields.get(1))); - } catch (NumberFormatException e) { - - } - } - } - - is.close(); - - return result; - } - - /** - * Load genome description. - * @param file File to use - */ - public static GenomeDescription load(final File file) throws IOException { - - checkNotNull(file, "File is null"); - return load(FileUtils.createInputStream(file)); - } - - // - // Static methods - // - - /** - * Create a GenomeDescription object from a Fasta file. - * @param genomeFastaIs InputStream - */ - public static GenomeDescription createGenomeDescFromFasta( - final File genomeFastaFile) throws BadBioEntryException, IOException { - - checkNotNull(genomeFastaFile, "The genome file is null"); - - return createGenomeDescFromFasta( - FileUtils.createInputStream(genomeFastaFile), genomeFastaFile.getName()); - } - - /** - * Create a GenomeDescription object from a Fasta file. - * @param genomeFastaIs InputStream - */ - public static GenomeDescription createGenomeDescFromFasta( - final InputStream genomeFastaIs, final String filename) - throws BadBioEntryException, IOException { - - checkNotNull(genomeFastaIs, "The input stream of the genome is null"); - - final GenomeDescription result = new GenomeDescription(); - result.setGenomeName(StringUtils.basename(filename)); - - MessageDigest md5Digest; - try { - md5Digest = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - md5Digest = null; - } - - final FastaReader reader = new FastaReader(genomeFastaIs); - - for (final Sequence sequence : reader) { - - long len = checkBases(sequence); - final String name = parseChromosomeName(sequence.getName()); - - // Update digest with chromosome name - if (md5Digest != null) { - md5Digest.update(name.getBytes(Globals.DEFAULT_FILE_ENCODING)); - - for (final String s : StringUtils.splitStringIterator( - sequence.getSequence(), STRING_LENGTH_BUFFER)) - md5Digest.update(s.getBytes(Globals.DEFAULT_FILE_ENCODING)); - } - - // Add sequence - result.addSequence(name, len); - } - reader.throwException(); - - // Compute final MD5 sum - if (md5Digest != null) - result.setMD5Sum(digestToString(md5Digest)); - - genomeFastaIs.close(); - - return result; - } - - private static String parseChromosomeName(final String fastaHeader) { - - if (fastaHeader == null) - return null; - - final String s = fastaHeader.trim(); - String[] fields = s.split("\\s"); - - if (fields == null || fields.length == 0) - return null; - - return fields[0]; - } - - private static long checkBases(final Sequence sequence) - throws BadBioEntryException { - - final Alphabet alphabet = Alphabets.AMBIGUOUS_DNA_ALPHABET; - - long result = 0; - - for (final String s : StringUtils.splitStringIterator( - sequence.getSequence(), STRING_LENGTH_BUFFER)) { - - final char[] array = s.toCharArray(); - - for (final char c : array) - if (!alphabet.isLetterValid(c)) - throw new BadBioEntryException("Invalid base in genome: " + c, - sequence.getName()); - - result += array.length; - } - - return result; - } - - private static final String digestToString(final MessageDigest md) { - - if (md == null) - return null; - - final BigInteger bigInt = new BigInteger(1, md.digest()); - - return bigInt.toString(16); - } - - // - // Other methods - // - - @Override - public String toString() { - - return this.getClass().getSimpleName() - + "{genomeName=" + genomeName + ", sequencesCount=" - + this.sequences.size() + ", md5Sum=" + this.md5Sum + ", sequences=" - + this.sequences + "}"; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/old/GenomeDescription.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/old/GenomeDescription.java deleted file mode 100755 index fe2b7e6..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/old/GenomeDescription.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio; - -import static fr.ens.transcriptome.eoulsan.util.Utils.checkNotNull; -import static fr.ens.transcriptome.eoulsan.util.Utils.newArrayList; -import static fr.ens.transcriptome.eoulsan.util.Utils.newLinkedHashMap; -import static java.util.Arrays.asList; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Writer; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; - -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.bio.io.FastaReader; -import fr.ens.transcriptome.eoulsan.util.FileUtils; -import fr.ens.transcriptome.eoulsan.util.StringUtils; - -/** - * This class define a genome description. - * @author Laurent Jourdren - */ -public class GenomeDescription { - - /** Logger */ - private static final Logger LOGGER = Logger.getLogger(Globals.APP_NAME); - - private static final int STRING_LENGTH_BUFFER = 1024 * 1024; - - private static final String PREFIX = "genome."; - private static final String NAME_PREFIX = PREFIX + "name"; - private static final String LENGTH_PREFIX = PREFIX + "length"; - private static final String MD5_PREFIX = PREFIX + "md5"; - private static final String SEQUENCE_PREFIX = PREFIX + "sequence."; - private static final String SEQUENCES_COUNT_PREFIX = PREFIX + "sequences"; - - private String genomeName; - private Map sequences = newLinkedHashMap(); - private String md5Sum; - - // - // Setters - // - - /** - * Set the genome name. - * @param genomeName name of the genome - */ - private void setGenomeName(final String genomeName) { - - this.genomeName = genomeName; - } - - /** - * Add a sequence. - * @param sequenceName name of the sequence - * @param sequenceLength length of the sequence - */ - public void addSequence(final String sequenceName, final long sequenceLength) { - - LOGGER.fine("Add sequence: " - + sequenceName + " with " + sequenceLength + " pb"); - - this.sequences.put(sequenceName, sequenceLength); - } - - /** - * Set the md5 digest of the genome file - * @param md5Digest the md5 digest - */ - public void setMD5Sum(final String md5Digest) { - - this.md5Sum = md5Digest; - } - - // - // Getters - // - - /** - * Get the genome name. - * @return the genome name - */ - public String getGenomeName() { - - return this.genomeName; - } - - /** - * Get the length of a sequence - * @param sequenceName name of the sequence - * @return the length of the sequence or -1 if the sequence does not exists - */ - public long getSequenceLength(final String sequenceName) { - - if (this.sequences.containsKey(sequenceName)) { - - return this.sequences.get(sequenceName); - } - - return -1; - } - - /** - * Get the names of the sequences. - * @return a set with the name of the sequence - */ - public List getSequencesNames() { - - return Collections.unmodifiableList(newArrayList(this.sequences.keySet())); - } - - /** - * Get the md5 sum for the genome. - * @return the md5 sum - */ - public String getMD5Sum() { - - return this.md5Sum; - } - - /** - * Get the number of sequences in the genome. - * @return the number of sequences in the genome - */ - public int getSequenceCount() { - - return this.sequences.size(); - } - - /** - * Get the genome length; - * @return the genome length - */ - public long getGenomeLength() { - - long count = 0; - - for (Map.Entry e : this.sequences.entrySet()) - count += e.getValue(); - - return count; - } - - // - // Save description - // - - /** - * Save genome description. - * @param os OutputStream to use for genome description writing - */ - public void save(final OutputStream os) throws IOException { - - checkNotNull(os, "OutputStream is null"); - - final Writer writer = FileUtils.createFastBufferedWriter(os); - - if (this.genomeName != null) - writer.write(NAME_PREFIX + "=" + getGenomeName() + '\n'); - - if (this.md5Sum != null) - writer.write(MD5_PREFIX + "=" + getMD5Sum() + '\n'); - - writer.write(SEQUENCES_COUNT_PREFIX + '=' + getSequenceCount() + '\n'); - - writer.write(LENGTH_PREFIX + '=' + getGenomeLength() + '\n'); - - for (String seqName : getSequencesNames()) { - - writer.write(SEQUENCE_PREFIX - + seqName + "=" + getSequenceLength(seqName) + "\n"); - } - - writer.close(); - } - - /** - * Save genome description. - * @param file output file - */ - public void save(final File file) throws FileNotFoundException, IOException { - - checkNotNull(file, "File is null"); - save(FileUtils.createOutputStream(file)); - } - - // - // Load description - // - - /** - * Load genome description. - * @param is InputStream to use - */ - public static GenomeDescription load(final InputStream is) throws IOException { - - checkNotNull(is, "InputStream is null"); - - final GenomeDescription result = new GenomeDescription(); - - final BufferedReader read = FileUtils.createBufferedReader(is); - - String line = null; - - while ((line = read.readLine()) != null) { - - final List fields = asList(line.split("=")); - - if (fields.size() > 1) { - - final String key = fields.get(0).trim(); - - if (key.startsWith(NAME_PREFIX)) - result.setGenomeName(fields.get(1)); - if (key.startsWith(MD5_PREFIX)) - result.setMD5Sum(fields.get(1)); - else - try { - if (key.startsWith(SEQUENCE_PREFIX)) - result.addSequence(key.substring(SEQUENCE_PREFIX.length()), - Integer.parseInt(fields.get(1))); - } catch (NumberFormatException e) { - - } - } - } - - is.close(); - - return result; - } - - /** - * Load genome description. - * @param file File to use - */ - public static GenomeDescription load(final File file) throws IOException { - - checkNotNull(file, "File is null"); - return load(FileUtils.createInputStream(file)); - } - - // - // Static methods - // - - /** - * Create a GenomeDescription object from a Fasta file. - * @param genomeFastaIs InputStream - */ - public static GenomeDescription createGenomeDescFromFasta( - final File genomeFastaFile) throws BadBioEntryException, IOException { - - checkNotNull(genomeFastaFile, "The genome file is null"); - - return createGenomeDescFromFasta( - FileUtils.createInputStream(genomeFastaFile), genomeFastaFile.getName()); - } - - /** - * Create a GenomeDescription object from a Fasta file. - * @param genomeFastaIs InputStream - */ - public static GenomeDescription createGenomeDescFromFasta( - final InputStream genomeFastaIs, final String filename) - throws BadBioEntryException, IOException { - - checkNotNull(genomeFastaIs, "The input stream of the genome is null"); - - final GenomeDescription result = new GenomeDescription(); - result.setGenomeName(StringUtils.basename(filename)); - - MessageDigest md5Digest; - try { - md5Digest = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - md5Digest = null; - } - - final FastaReader reader = new FastaReader(genomeFastaIs); - - for (final Sequence sequence : reader) { - - long len = checkBases(sequence); - final String name = parseChromosomeName(sequence.getName()); - - // Update digest with chromosome name - if (md5Digest != null) { - md5Digest.update(name.getBytes()); - - for (final String s : StringUtils.splitStringIterator( - sequence.getSequence(), STRING_LENGTH_BUFFER)) - md5Digest.update(s.getBytes()); - } - - // Add sequence - result.addSequence(name, len); - } - reader.throwException(); - - // Compute final MD5 sum - if (md5Digest != null) - result.setMD5Sum(digestToString(md5Digest)); - - genomeFastaIs.close(); - - return result; - } - - private static String parseChromosomeName(final String fastaHeader) { - - if (fastaHeader == null) - return null; - - final String s = fastaHeader.trim(); - String[] fields = s.split("\\s"); - - if (fields == null || fields.length == 0) - return null; - - return fields[0]; - } - - private static long checkBases(final Sequence sequence) - throws BadBioEntryException { - - final Alphabet alphabet = Alphabets.AMBIGUOUS_DNA_ALPHABET; - - long result = 0; - - for (final String s : StringUtils.splitStringIterator( - sequence.getSequence(), STRING_LENGTH_BUFFER)) { - - final char[] array = s.toCharArray(); - - for (final char c : array) - if (!alphabet.isLetterValid(c)) - throw new BadBioEntryException("Invalid base in genome: " + c, - sequence.getName()); - - result += array.length; - } - - return result; - } - - private static final String digestToString(final MessageDigest md) { - - if (md == null) - return null; - - final BigInteger bigInt = new BigInteger(1, md.digest()); - - return bigInt.toString(16); - } - - // - // Other methods - // - - @Override - public String toString() { - - return this.getClass().getSimpleName() - + "{genomeName=" + genomeName + ", sequencesCount=" - + this.sequences.size() + ", md5Sum=" + this.md5Sum + ", sequences=" - + this.sequences + "}"; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/pair.info deleted file mode 100755 index a986f29..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33235/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:33235 -comSha:4a4f273ebcb53fc498dd0c45bc5dd4ea66cf5480 -parentComSha:237a7830c382d17dfa2fd10951c13d1ad46075b2 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/GenomeDescription.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/GenomeDescription.java -StartLineNum:323 -EndLineNum:323 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/comMsg.txt deleted file mode 100755 index 48d5fe7..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Fix issues found with findbugs for java.io stream usages where no encoding is defined. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/diff.diff deleted file mode 100755 index 684a93a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/MapperResult2SAMInputStream.java b/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/MapperResult2SAMInputStream.java -index 3e120f6b..4f120831 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/MapperResult2SAMInputStream.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/MapperResult2SAMInputStream.java -@@ -38,0 +39,2 @@ import com.google.common.collect.Lists; -+import fr.ens.transcriptome.eoulsan.Globals; -+ -@@ -74 +76 @@ public class MapperResult2SAMInputStream extends FilterInputStream { -- - this.pos)); -+ - this.pos, Globals.DEFAULT_CHARSET)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/new/MapperResult2SAMInputStream.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/new/MapperResult2SAMInputStream.java deleted file mode 100755 index 4f12083..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/new/MapperResult2SAMInputStream.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.readsmappers; - -import java.io.BufferedReader; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.List; - -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; - -import fr.ens.transcriptome.eoulsan.Globals; - -/** - * This class allow to transform the output of a mapper into SAM format. - * @author Laurent Jourdren - * @since 2.0 - */ -public class MapperResult2SAMInputStream extends FilterInputStream { - - private byte[] buffer = new byte[0]; - private int pos; - private final BufferedReader reader; - private boolean endStream; - - private static final Charset CHARSET = StandardCharsets.ISO_8859_1; - private final StringBuilder sb = new StringBuilder(); - - protected List transform(final String s) { - - if (s == null) - return null; - - return Lists.newArrayList(Splitter.on('\t').split(s)); - } - - private boolean fillBuffer(final int minSize) throws IOException { - - final int finalPos = this.pos + minSize; - - if (finalPos < this.buffer.length) - return false; - - if (this.endStream) - return true; - - this.sb.setLength(0); - this.sb.append(new String(this.buffer, this.pos, this.buffer.length - - this.pos, Globals.DEFAULT_CHARSET)); - - do { - String line = this.reader.readLine(); - final List lines; - - if (line == null) { - lines = transform(null); - this.endStream = true; - } else { - lines = transform(line); - } - - if (lines != null) - for (String l : lines) { - this.sb.append(l); - this.sb.append('\n'); - } - - } while (sb.length() < minSize || this.endStream); - - this.buffer = this.sb.toString().getBytes(CHARSET); - this.pos = 0; - - return false; - } - - @Override - public void close() throws IOException { - - this.reader.close(); - } - - @Override - public int read() throws IOException { - - if (fillBuffer(1)) - return -1; - - return buffer[pos++]; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - - if (len < 1) - throw new IllegalArgumentException("len must be > 0"); - - if (fillBuffer(len)) - return -1; - - final int copyLen = Math.min(len, this.buffer.length - this.pos); - - System.arraycopy(this.buffer, pos, b, off, copyLen); - this.pos += copyLen; - - return copyLen; - } - - @Override - public int available() throws IOException { - - return this.buffer.length - this.pos; - } - - @Override - public synchronized void mark(final int readlimit) { - } - - @Override - public boolean markSupported() { - - return false; - } - - @Override - public synchronized void reset() throws IOException { - throw new IOException("mark/reset not supported"); - } - - @Override - public long skip(final long n) throws IOException { - // TODO Auto-generated method stub - return super.skip(n); - } - - // - // Constructor - // - - protected MapperResult2SAMInputStream(final InputStream in) { - - super(in); - this.reader = - new BufferedReader(new InputStreamReader(this.in, - StandardCharsets.ISO_8859_1)); - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/old/MapperResult2SAMInputStream.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/old/MapperResult2SAMInputStream.java deleted file mode 100755 index 3e120f6..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/old/MapperResult2SAMInputStream.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.readsmappers; - -import java.io.BufferedReader; -import java.io.FilterInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.List; - -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; - -/** - * This class allow to transform the output of a mapper into SAM format. - * @author Laurent Jourdren - * @since 2.0 - */ -public class MapperResult2SAMInputStream extends FilterInputStream { - - private byte[] buffer = new byte[0]; - private int pos; - private final BufferedReader reader; - private boolean endStream; - - private static final Charset CHARSET = StandardCharsets.ISO_8859_1; - private final StringBuilder sb = new StringBuilder(); - - protected List transform(final String s) { - - if (s == null) - return null; - - return Lists.newArrayList(Splitter.on('\t').split(s)); - } - - private boolean fillBuffer(final int minSize) throws IOException { - - final int finalPos = this.pos + minSize; - - if (finalPos < this.buffer.length) - return false; - - if (this.endStream) - return true; - - this.sb.setLength(0); - this.sb.append(new String(this.buffer, this.pos, this.buffer.length - - this.pos)); - - do { - String line = this.reader.readLine(); - final List lines; - - if (line == null) { - lines = transform(null); - this.endStream = true; - } else { - lines = transform(line); - } - - if (lines != null) - for (String l : lines) { - this.sb.append(l); - this.sb.append('\n'); - } - - } while (sb.length() < minSize || this.endStream); - - this.buffer = this.sb.toString().getBytes(CHARSET); - this.pos = 0; - - return false; - } - - @Override - public void close() throws IOException { - - this.reader.close(); - } - - @Override - public int read() throws IOException { - - if (fillBuffer(1)) - return -1; - - return buffer[pos++]; - } - - @Override - public int read(byte[] b, int off, int len) throws IOException { - - if (len < 1) - throw new IllegalArgumentException("len must be > 0"); - - if (fillBuffer(len)) - return -1; - - final int copyLen = Math.min(len, this.buffer.length - this.pos); - - System.arraycopy(this.buffer, pos, b, off, copyLen); - this.pos += copyLen; - - return copyLen; - } - - @Override - public int available() throws IOException { - - return this.buffer.length - this.pos; - } - - @Override - public synchronized void mark(final int readlimit) { - } - - @Override - public boolean markSupported() { - - return false; - } - - @Override - public synchronized void reset() throws IOException { - throw new IOException("mark/reset not supported"); - } - - @Override - public long skip(final long n) throws IOException { - // TODO Auto-generated method stub - return super.skip(n); - } - - // - // Constructor - // - - protected MapperResult2SAMInputStream(final InputStream in) { - - super(in); - this.reader = - new BufferedReader(new InputStreamReader(this.in, - StandardCharsets.ISO_8859_1)); - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/pair.info deleted file mode 100755 index e854776..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33372/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:33372 -comSha:a8aa6a4d759a91a3a112cfecab982ca64e4135fd -parentComSha:d118dfdf1a72f3e4a0f33ced5071e4d1038c9620 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/MapperResult2SAMInputStream.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/MapperResult2SAMInputStream.java -StartLineNum:73 -EndLineNum:73 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/comMsg.txt deleted file mode 100755 index 48d5fe7..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Fix issues found with findbugs for java.io stream usages where no encoding is defined. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/diff.diff deleted file mode 100755 index 88bc67d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/AbstractComparatorWithBloomFilter.java b/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/AbstractComparatorWithBloomFilter.java -index bd66e568..3829813e 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/AbstractComparatorWithBloomFilter.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/AbstractComparatorWithBloomFilter.java -@@ -35,0 +36 @@ import java.io.InputStreamReader; -+import fr.ens.transcriptome.eoulsan.Globals; -@@ -146 +147,2 @@ public abstract class AbstractComparatorWithBloomFilter extends -- final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); -+ final BufferedReader reader = -+ new BufferedReader(new InputStreamReader(is, Globals.DEFAULT_CHARSET)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/new/AbstractComparatorWithBloomFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/new/AbstractComparatorWithBloomFilter.java deleted file mode 100755 index 3829813..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/new/AbstractComparatorWithBloomFilter.java +++ /dev/null @@ -1,236 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ -package fr.ens.transcriptome.eoulsan.io.comparators; - -import static fr.ens.transcriptome.eoulsan.io.CompressionType.getCompressionTypeByFilename; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.io.CompressionType; -import fr.ens.transcriptome.eoulsan.util.BloomFilterUtils; - -/** - * This abstract class define methods to compare files with use BloomFilter. - * @since 2.0 - * @author Sandrine Perrin - */ -public abstract class AbstractComparatorWithBloomFilter extends - AbstractComparator { - - // Limited create serialize bloomfilter file for size file inferior to - // size of serialize bloomfilter file 27369839 bytes with default parameters - private final long sizeMinimalCreateSerializeFile = 40000000; - - private double falsePositiveProbability = 0.1; - private int expectedNumberOfElements = 30000000; - private boolean useSerializeFile = false; - - @Override - public boolean compareFiles(final File fileA, final File fileB) - throws FileNotFoundException, IOException { - - // Check input files - if (!checkFiles(fileA, fileB) && checkFileSize()) - return false; - - // Check path file (abstract and symbolic) is the same - if (fileA.getCanonicalFile().equals(fileB.getCanonicalFile())) { - return true; - } - - final InputStream isB = - getCompressionTypeByFilename(fileB.getAbsolutePath()) - .createInputStream(new FileInputStream(fileB)); - - return compareFiles(getBloomFilter(fileA), isB); - } - - @Override - public boolean compareFiles(InputStream isA, InputStream isB) - throws IOException { - return compareFiles(buildBloomFilter(isA), isB); - } - - /** - * Compare two files no ordered, check if they are the same contents. - * @param filter from BloomFilterUtils represented the first file - * @param is the path to the second file, - * @return boolean true if files are same. - * @throws IOException if an error occurs while comparing the files. - */ - abstract public boolean compareFiles(BloomFilterUtils filter, InputStream is) - throws IOException; - - /** - * Initialize BloomFilter with the expected number of elements. - * @param expectedNumberOfElements expected number of elements - */ - protected static BloomFilterUtils initBloomFilter( - final int expectedNumberOfElements) { - - return new BloomFilterUtils(expectedNumberOfElements); - } - - /** - * In case Serialization is asked, check if the file.ser exists : true - * retrieve the bloom filter else create the filter and file.Ser - * corresponding. - * @param file source to create bloom filter - * @return bloomFilter completed with the file - */ - public BloomFilterUtils getBloomFilter(final File file) throws IOException { - - final File bloomFilterSer = new File(file.getAbsolutePath() + ".ser"); - final BloomFilterUtils bloomFilter; - - if (this.useSerializeFile && bloomFilterSer.exists()) { - // Retrieve marshalling bloom filter - bloomFilter = BloomFilterUtils.deserializationBloomFilter(bloomFilterSer); - - return bloomFilter; - } - - final CompressionType zType = - getCompressionTypeByFilename(file.getAbsolutePath()); - - // Create new filter - bloomFilter = - buildBloomFilter(zType.createInputStream(new FileInputStream(file))); - - // If need serialize bloomFilter in file only for file - if (isCreateSerializeFile(file, zType)) { - BloomFilterUtils.serializationBloomFilter(bloomFilterSer, bloomFilter); - } - - return bloomFilter; - } - - /** - * Build BloomFilter represented the input stream. - * @param is the input stream source - * @return BloomFilter corresponding to the input stream - * @throws IOException - */ - protected BloomFilterUtils buildBloomFilter(InputStream is) - throws IOException { - final BloomFilterUtils filter = - initBloomFilter(getExpectedNumberOfElements()); - - final BufferedReader reader = - new BufferedReader(new InputStreamReader(is, Globals.DEFAULT_CHARSET)); - - String line = null; - - // Read the first file and store hashcodes - while ((line = reader.readLine()) != null) { - filter.put(line); - } - - reader.close(); - return filter; - } - - @Override - public String toString() { - - return getName() - + " compares files with extensions " + getExtensions() - + " use Bloom filter with parameters: expected numbers elements " - + getExpectedNumberOfElements() + " and false positif probability " - + getFalsePositiveProbability(); - - } - - /** - * Define if serialization bloomfilter file is necessary according parameter - * useSerializeFile and size file. - * @param file file source for build bloomfilter - * @param zType compression type of file - * @return true if creating serialization file is necessary - */ - private boolean isCreateSerializeFile(final File file, - final CompressionType zType) { - - // No serialize file require - if (!this.useSerializeFile) - return false; - - // Compressed file and serialize require - if (zType != CompressionType.NONE) - return true; - - // File size in bytes - final long fileSize = file.length(); - // Check to choice - return fileSize > this.sizeMinimalCreateSerializeFile; - } - - // - // Getters & setters - // - - public boolean isUseSerializeFile() { - return useSerializeFile; - } - - public void setUseSerializeFile(boolean useSerializeFile) { - this.useSerializeFile = useSerializeFile; - } - - protected int getExpectedNumberOfElements() { - return expectedNumberOfElements; - } - - protected void setExpectedNumberOfElements(int expectedNumberOfElements) { - this.expectedNumberOfElements = expectedNumberOfElements; - } - - protected void setFalsePositiveProbability(double falsePositiveProba) { - this.falsePositiveProbability = falsePositiveProba; - } - - protected double getFalsePositiveProbability() { - return falsePositiveProbability; - } - - // - // Constructor - // - - /** - * Public constructor - * @param useSerializeFile true if it needed to save BloomFilter in file with - * extension '.ser' - */ - public AbstractComparatorWithBloomFilter(final boolean useSerializeFile) { - this.useSerializeFile = useSerializeFile; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/old/AbstractComparatorWithBloomFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/old/AbstractComparatorWithBloomFilter.java deleted file mode 100755 index bd66e56..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/old/AbstractComparatorWithBloomFilter.java +++ /dev/null @@ -1,234 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ -package fr.ens.transcriptome.eoulsan.io.comparators; - -import static fr.ens.transcriptome.eoulsan.io.CompressionType.getCompressionTypeByFilename; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; - -import fr.ens.transcriptome.eoulsan.io.CompressionType; -import fr.ens.transcriptome.eoulsan.util.BloomFilterUtils; - -/** - * This abstract class define methods to compare files with use BloomFilter. - * @since 2.0 - * @author Sandrine Perrin - */ -public abstract class AbstractComparatorWithBloomFilter extends - AbstractComparator { - - // Limited create serialize bloomfilter file for size file inferior to - // size of serialize bloomfilter file 27369839 bytes with default parameters - private final long sizeMinimalCreateSerializeFile = 40000000; - - private double falsePositiveProbability = 0.1; - private int expectedNumberOfElements = 30000000; - private boolean useSerializeFile = false; - - @Override - public boolean compareFiles(final File fileA, final File fileB) - throws FileNotFoundException, IOException { - - // Check input files - if (!checkFiles(fileA, fileB) && checkFileSize()) - return false; - - // Check path file (abstract and symbolic) is the same - if (fileA.getCanonicalFile().equals(fileB.getCanonicalFile())) { - return true; - } - - final InputStream isB = - getCompressionTypeByFilename(fileB.getAbsolutePath()) - .createInputStream(new FileInputStream(fileB)); - - return compareFiles(getBloomFilter(fileA), isB); - } - - @Override - public boolean compareFiles(InputStream isA, InputStream isB) - throws IOException { - return compareFiles(buildBloomFilter(isA), isB); - } - - /** - * Compare two files no ordered, check if they are the same contents. - * @param filter from BloomFilterUtils represented the first file - * @param is the path to the second file, - * @return boolean true if files are same. - * @throws IOException if an error occurs while comparing the files. - */ - abstract public boolean compareFiles(BloomFilterUtils filter, InputStream is) - throws IOException; - - /** - * Initialize BloomFilter with the expected number of elements. - * @param expectedNumberOfElements expected number of elements - */ - protected static BloomFilterUtils initBloomFilter( - final int expectedNumberOfElements) { - - return new BloomFilterUtils(expectedNumberOfElements); - } - - /** - * In case Serialization is asked, check if the file.ser exists : true - * retrieve the bloom filter else create the filter and file.Ser - * corresponding. - * @param file source to create bloom filter - * @return bloomFilter completed with the file - */ - public BloomFilterUtils getBloomFilter(final File file) throws IOException { - - final File bloomFilterSer = new File(file.getAbsolutePath() + ".ser"); - final BloomFilterUtils bloomFilter; - - if (this.useSerializeFile && bloomFilterSer.exists()) { - // Retrieve marshalling bloom filter - bloomFilter = BloomFilterUtils.deserializationBloomFilter(bloomFilterSer); - - return bloomFilter; - } - - final CompressionType zType = - getCompressionTypeByFilename(file.getAbsolutePath()); - - // Create new filter - bloomFilter = - buildBloomFilter(zType.createInputStream(new FileInputStream(file))); - - // If need serialize bloomFilter in file only for file - if (isCreateSerializeFile(file, zType)) { - BloomFilterUtils.serializationBloomFilter(bloomFilterSer, bloomFilter); - } - - return bloomFilter; - } - - /** - * Build BloomFilter represented the input stream. - * @param is the input stream source - * @return BloomFilter corresponding to the input stream - * @throws IOException - */ - protected BloomFilterUtils buildBloomFilter(InputStream is) - throws IOException { - final BloomFilterUtils filter = - initBloomFilter(getExpectedNumberOfElements()); - - final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); - - String line = null; - - // Read the first file and store hashcodes - while ((line = reader.readLine()) != null) { - filter.put(line); - } - - reader.close(); - return filter; - } - - @Override - public String toString() { - - return getName() - + " compares files with extensions " + getExtensions() - + " use Bloom filter with parameters: expected numbers elements " - + getExpectedNumberOfElements() + " and false positif probability " - + getFalsePositiveProbability(); - - } - - /** - * Define if serialization bloomfilter file is necessary according parameter - * useSerializeFile and size file. - * @param file file source for build bloomfilter - * @param zType compression type of file - * @return true if creating serialization file is necessary - */ - private boolean isCreateSerializeFile(final File file, - final CompressionType zType) { - - // No serialize file require - if (!this.useSerializeFile) - return false; - - // Compressed file and serialize require - if (zType != CompressionType.NONE) - return true; - - // File size in bytes - final long fileSize = file.length(); - // Check to choice - return fileSize > this.sizeMinimalCreateSerializeFile; - } - - // - // Getters & setters - // - - public boolean isUseSerializeFile() { - return useSerializeFile; - } - - public void setUseSerializeFile(boolean useSerializeFile) { - this.useSerializeFile = useSerializeFile; - } - - protected int getExpectedNumberOfElements() { - return expectedNumberOfElements; - } - - protected void setExpectedNumberOfElements(int expectedNumberOfElements) { - this.expectedNumberOfElements = expectedNumberOfElements; - } - - protected void setFalsePositiveProbability(double falsePositiveProba) { - this.falsePositiveProbability = falsePositiveProba; - } - - protected double getFalsePositiveProbability() { - return falsePositiveProbability; - } - - // - // Constructor - // - - /** - * Public constructor - * @param useSerializeFile true if it needed to save BloomFilter in file with - * extension '.ser' - */ - public AbstractComparatorWithBloomFilter(final boolean useSerializeFile) { - this.useSerializeFile = useSerializeFile; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/pair.info deleted file mode 100755 index c80d02b..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33443/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:33443 -comSha:a8aa6a4d759a91a3a112cfecab982ca64e4135fd -parentComSha:d118dfdf1a72f3e4a0f33ced5071e4d1038c9620 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/AbstractComparatorWithBloomFilter.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/io/comparators/AbstractComparatorWithBloomFilter.java -StartLineNum:146 -EndLineNum:146 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/comMsg.txt deleted file mode 100755 index cf36e8f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/comMsg.txt +++ /dev/null @@ -1,13 +0,0 @@ -Merge branch 'master' into new_workflow_token - -Conflicts: - pom.xml - src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/AbstractBowtieReadsMapper.java - src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/AbstractSequenceReadsMapper.java - src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/BWAReadsMapper.java - src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/GSNAPReadsMapper.java - src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/GmapReadsMapper.java - src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/SOAPReadsMapper.java - src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/ReadsMapperMapper.java - src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/local/ReadsMapperLocalStep.java - src/main/java/fr/ens/transcriptome/eoulsan/util/Reporter.java \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/diff.diff deleted file mode 100755 index 7b3ff7b..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java b/src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -index a0f0d725..a93acdde 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -@@ -27,0 +28 @@ import static com.google.common.collect.Lists.newArrayList; -+import static fr.ens.transcriptome.eoulsan.bio.io.BioCharsets.SAM_CHARSET; -@@ -44,0 +46 @@ import com.google.common.collect.Lists; -+import fr.ens.transcriptome.eoulsan.EoulsanLogger; -@@ -59 +61 @@ public class SAMFilterMapper extends Mapper { -- private static final Logger LOGGER = Logger.getLogger(Globals.APP_NAME); -+ private static final Logger LOGGER = EoulsanLogger.getLogger(); -@@ -191 +193 @@ public class SAMFilterMapper extends Mapper { -- context.getConfiguration())); -+ context.getConfiguration()), SAM_CHARSET); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/new/SAMFilterMapper.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/new/SAMFilterMapper.java deleted file mode 100755 index a93acdd..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/new/SAMFilterMapper.java +++ /dev/null @@ -1,215 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.steps.mapping.hadoop; - -import static com.google.common.collect.Lists.newArrayList; -import static fr.ens.transcriptome.eoulsan.bio.io.BioCharsets.SAM_CHARSET; -import static fr.ens.transcriptome.eoulsan.steps.mapping.MappingCounters.INPUT_ALIGNMENTS_COUNTER; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.List; -import java.util.logging.Logger; - -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.io.LongWritable; -import org.apache.hadoop.io.Text; -import org.apache.hadoop.mapreduce.Mapper; - -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; - -import fr.ens.transcriptome.eoulsan.EoulsanLogger; -import fr.ens.transcriptome.eoulsan.EoulsanRuntime; -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.HadoopEoulsanRuntime; -import fr.ens.transcriptome.eoulsan.core.CommonHadoop; -import fr.ens.transcriptome.eoulsan.util.hadoop.PathUtils; - -/** - * This class defines a mapper for alignment filtering. - * @since 1.0 - * @author Laurent Jourdren - */ -public class SAMFilterMapper extends Mapper { - - /** Logger */ - private static final Logger LOGGER = EoulsanLogger.getLogger(); - - // Parameters keys - static final String MAPPING_QUALITY_THRESOLD_KEY = Globals.PARAMETER_PREFIX - + ".samfilter.mapping.quality.threshold"; - static final String GENOME_DESC_PATH_KEY = Globals.PARAMETER_PREFIX - + ".samfilter.genome.desc.file"; - - static final String SAM_HEADER_FILE_PREFIX = "_samheader_"; - - private static final Splitter ID_SPLITTER = Splitter.on(':').trimResults(); - private List idFields = newArrayList(); - - private String counterGroup; - - private final Text outKey = new Text(); - private final Text outValue = new Text(); - - @Override - protected void setup(final Context context) throws IOException, - InterruptedException { - - LOGGER.info("Start of configure()"); - - // Get configuration object - final Configuration conf = context.getConfiguration(); - - // Initialize Eoulsan DataProtocols - if (!EoulsanRuntime.isRuntime()) { - HadoopEoulsanRuntime.newEoulsanRuntime(conf); - } - - // Counter group - this.counterGroup = conf.get(CommonHadoop.COUNTER_GROUP_KEY); - if (this.counterGroup == null) { - throw new IOException("No counter group defined"); - } - - LOGGER.info("End of setup()"); - } - - /** - * 'key': offset of the beginning of the line from the beginning of the SAM - * file if data are in single-end mode or in TSAM file if data are in - * paired-end mode. 'value': the SAM or TSAM line. - */ - @Override - protected void map(final LongWritable key, final Text value, - final Context context) throws IOException, InterruptedException { - - final String line = value.toString(); - - // Avoid empty and header lines - if (!isValidLineAndSaveSAMHeader(line, context)) - return; - - context.getCounter(this.counterGroup, - INPUT_ALIGNMENTS_COUNTER.counterName()).increment(1); - - final int indexOfFirstTab = line.indexOf("\t"); - String completeId = line.substring(0, indexOfFirstTab); - int endReadId; - - idFields.clear(); - for (String e : ID_SPLITTER.split(completeId)) { - idFields.add(e); - } - - // Read identifiant format : before Casava 1.8 or other technologies that - // Illumina - if (idFields.size() < 7) { - endReadId = completeId.indexOf('/'); - // single-end mode - if (endReadId == -1) { - this.outKey.set(completeId); - this.outValue.set(line.substring(indexOfFirstTab)); - } - // paired-end mode - else { - this.outKey.set(line.substring(0, endReadId + 1)); - this.outValue.set(line.substring(endReadId + 1)); - } - } - - // Read identifiant format : Illumina - Casava 1.8 - else { - endReadId = completeId.indexOf(' '); - // mapped read - if (endReadId == -1) { - this.outKey.set(completeId); - this.outValue.set(line.substring(indexOfFirstTab)); - } - // unmapped read - else { - this.outKey.set(line.substring(0, endReadId)); - this.outValue.set(line.substring(endReadId)); - } - } - - context.write(this.outKey, this.outValue); - } - - @Override - protected void cleanup(Context context) throws IOException, - InterruptedException { - } - - private List headers; - - private final boolean isValidLineAndSaveSAMHeader(final String line, - final Context context) throws IOException { - - // Test empty line - if (line.length() == 0) - return false; - - if (line.charAt(0) != '@') { - - // If headers previously found write it in a file - if (this.headers != null) { - - // Save headers - - // TODO change for Hadoop 2.0 - final Path outputPath = - new Path(context.getConfiguration().get("mapred.output.dir")); - - final Path headerPath = - new Path(outputPath, SAM_HEADER_FILE_PREFIX - + context.getTaskAttemptID().toString()); - final Writer writer = - new OutputStreamWriter(PathUtils.createOutputStream(headerPath, - context.getConfiguration()), SAM_CHARSET); - - for (String l : this.headers) - writer.write(l + "\n"); - - writer.close(); - - this.headers = null; - } - - // The line is an alignment - return true; - } - - if (this.headers == null) - this.headers = Lists.newArrayList(); - - this.headers.add(line); - - // The line is an header - return false; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/old/SAMFilterMapper.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/old/SAMFilterMapper.java deleted file mode 100755 index a0f0d72..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/old/SAMFilterMapper.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.steps.mapping.hadoop; - -import static com.google.common.collect.Lists.newArrayList; -import static fr.ens.transcriptome.eoulsan.steps.mapping.MappingCounters.INPUT_ALIGNMENTS_COUNTER; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.Writer; -import java.util.List; -import java.util.logging.Logger; - -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.io.LongWritable; -import org.apache.hadoop.io.Text; -import org.apache.hadoop.mapreduce.Mapper; - -import com.google.common.base.Splitter; -import com.google.common.collect.Lists; - -import fr.ens.transcriptome.eoulsan.EoulsanRuntime; -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.HadoopEoulsanRuntime; -import fr.ens.transcriptome.eoulsan.core.CommonHadoop; -import fr.ens.transcriptome.eoulsan.util.hadoop.PathUtils; - -/** - * This class defines a mapper for alignment filtering. - * @since 1.0 - * @author Laurent Jourdren - */ -public class SAMFilterMapper extends Mapper { - - /** Logger */ - private static final Logger LOGGER = Logger.getLogger(Globals.APP_NAME); - - // Parameters keys - static final String MAPPING_QUALITY_THRESOLD_KEY = Globals.PARAMETER_PREFIX - + ".samfilter.mapping.quality.threshold"; - static final String GENOME_DESC_PATH_KEY = Globals.PARAMETER_PREFIX - + ".samfilter.genome.desc.file"; - - static final String SAM_HEADER_FILE_PREFIX = "_samheader_"; - - private static final Splitter ID_SPLITTER = Splitter.on(':').trimResults(); - private List idFields = newArrayList(); - - private String counterGroup; - - private final Text outKey = new Text(); - private final Text outValue = new Text(); - - @Override - protected void setup(final Context context) throws IOException, - InterruptedException { - - LOGGER.info("Start of configure()"); - - // Get configuration object - final Configuration conf = context.getConfiguration(); - - // Initialize Eoulsan DataProtocols - if (!EoulsanRuntime.isRuntime()) { - HadoopEoulsanRuntime.newEoulsanRuntime(conf); - } - - // Counter group - this.counterGroup = conf.get(CommonHadoop.COUNTER_GROUP_KEY); - if (this.counterGroup == null) { - throw new IOException("No counter group defined"); - } - - LOGGER.info("End of setup()"); - } - - /** - * 'key': offset of the beginning of the line from the beginning of the SAM - * file if data are in single-end mode or in TSAM file if data are in - * paired-end mode. 'value': the SAM or TSAM line. - */ - @Override - protected void map(final LongWritable key, final Text value, - final Context context) throws IOException, InterruptedException { - - final String line = value.toString(); - - // Avoid empty and header lines - if (!isValidLineAndSaveSAMHeader(line, context)) - return; - - context.getCounter(this.counterGroup, - INPUT_ALIGNMENTS_COUNTER.counterName()).increment(1); - - final int indexOfFirstTab = line.indexOf("\t"); - String completeId = line.substring(0, indexOfFirstTab); - int endReadId; - - idFields.clear(); - for (String e : ID_SPLITTER.split(completeId)) { - idFields.add(e); - } - - // Read identifiant format : before Casava 1.8 or other technologies that - // Illumina - if (idFields.size() < 7) { - endReadId = completeId.indexOf('/'); - // single-end mode - if (endReadId == -1) { - this.outKey.set(completeId); - this.outValue.set(line.substring(indexOfFirstTab)); - } - // paired-end mode - else { - this.outKey.set(line.substring(0, endReadId + 1)); - this.outValue.set(line.substring(endReadId + 1)); - } - } - - // Read identifiant format : Illumina - Casava 1.8 - else { - endReadId = completeId.indexOf(' '); - // mapped read - if (endReadId == -1) { - this.outKey.set(completeId); - this.outValue.set(line.substring(indexOfFirstTab)); - } - // unmapped read - else { - this.outKey.set(line.substring(0, endReadId)); - this.outValue.set(line.substring(endReadId)); - } - } - - context.write(this.outKey, this.outValue); - } - - @Override - protected void cleanup(Context context) throws IOException, - InterruptedException { - } - - private List headers; - - private final boolean isValidLineAndSaveSAMHeader(final String line, - final Context context) throws IOException { - - // Test empty line - if (line.length() == 0) - return false; - - if (line.charAt(0) != '@') { - - // If headers previously found write it in a file - if (this.headers != null) { - - // Save headers - - // TODO change for Hadoop 2.0 - final Path outputPath = - new Path(context.getConfiguration().get("mapred.output.dir")); - - final Path headerPath = - new Path(outputPath, SAM_HEADER_FILE_PREFIX - + context.getTaskAttemptID().toString()); - final Writer writer = - new OutputStreamWriter(PathUtils.createOutputStream(headerPath, - context.getConfiguration())); - - for (String l : this.headers) - writer.write(l + "\n"); - - writer.close(); - - this.headers = null; - } - - // The line is an alignment - return true; - } - - if (this.headers == null) - this.headers = Lists.newArrayList(); - - this.headers.add(line); - - // The line is an header - return false; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/pair.info deleted file mode 100755 index e232854..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33451/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:33451 -comSha:8e3192d53b36e552e5b8c23b2ddd8275913ba76a -parentComSha:1bd7b534f4dfff8094ce2dd0fdceb6e3d02f8a06 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/steps/mapping/hadoop/SAMFilterMapper.java -StartLineNum:189 -EndLineNum:189 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/comMsg.txt deleted file mode 100755 index 846907d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Many code fix after findbugs. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/diff.diff deleted file mode 100755 index 3157e53..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/bio/io/FastaReader.java b/src/main/java/fr/ens/transcriptome/eoulsan/bio/io/FastaReader.java -index b107bf07..80135bbf 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/bio/io/FastaReader.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/bio/io/FastaReader.java -@@ -32,0 +33 @@ import java.io.InputStreamReader; -+import java.nio.charset.Charset; -@@ -44,0 +46,3 @@ public class FastaReader implements SequenceReader { -+ /* Default Charset. */ -+ private static final Charset CHARSET = Charset.forName("ISO-8859-1"); -+ -@@ -163 +167 @@ public class FastaReader implements SequenceReader { -- this.reader = new BufferedReader(new InputStreamReader(is)); -+ this.reader = new BufferedReader(new InputStreamReader(is, CHARSET)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/new/FastaReader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/new/FastaReader.java deleted file mode 100755 index 80135bb..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/new/FastaReader.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.io; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import fr.ens.transcriptome.eoulsan.bio.Sequence; -import fr.ens.transcriptome.eoulsan.util.FileUtils; - -/** - * This class define a Fasta reader. - * @author Laurent Jourdren - */ -public class FastaReader implements SequenceReader { - - /* Default Charset. */ - private static final Charset CHARSET = Charset.forName("ISO-8859-1"); - - protected BufferedReader reader; - - private Sequence result = null; - private final StringBuilder sb = new StringBuilder(); - - private String nextSequenceName; - private boolean end = false; - private boolean nextCallDone = true; - private int count; - protected IOException exception; - - @Override - public void close() throws IOException { - - this.reader.close(); - } - - @Override - public Iterator iterator() { - - return this; - } - - @Override - public boolean hasNext() { - - if (this.end) - return false; - - result = new Sequence(); - - String line = null; - - try { - while ((line = this.reader.readLine()) != null) { - - // Trim the line - final String trim = line.trim(); - - // discard empty lines - if ("".equals(trim)) - continue; - - if (trim.charAt(0) == '>') { - - if (this.nextSequenceName != null) { - - result.setName(this.nextSequenceName); - result.setSequence(sb.toString()); - result.setId(this.count++); - sb.setLength(0); - this.nextSequenceName = trim.substring(1); - this.nextCallDone = false; - - return true; - } - - this.nextSequenceName = trim.substring(1); - - } else { - sb.append(trim); - } - } - - result.setName(this.nextSequenceName); - result.setSequence(sb.toString()); - result.setId(this.count++); - sb.setLength(0); - - this.nextCallDone = false; - this.end = true; - - return true; - } catch (IOException e) { - - this.exception = e; - this.end = true; - return false; - } - } - - @Override - public Sequence next() { - - if (this.nextCallDone) - throw new NoSuchElementException(); - - this.nextCallDone = true; - - return this.result; - } - - @Override - public void remove() { - - throw new UnsupportedOperationException("Unsupported operation"); - } - - @Override - public void throwException() throws IOException { - - if (this.exception != null) - throw this.exception; - } - - // - // Constructors - // - - /** - * Public constructor - * @param is InputStream to use - */ - public FastaReader(final InputStream is) { - - if (is == null) - throw new NullPointerException("InputStream is null"); - - this.reader = new BufferedReader(new InputStreamReader(is, CHARSET)); - } - - /** - * Public constructor - * @param file File to use - */ - public FastaReader(final File file) throws FileNotFoundException { - - if (file == null) - throw new NullPointerException("File is null"); - - if (!file.isFile()) - throw new FileNotFoundException("File not found: " - + file.getAbsolutePath()); - - this.reader = FileUtils.createBufferedReader(file); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/old/FastaReader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/old/FastaReader.java deleted file mode 100755 index b107bf0..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/old/FastaReader.java +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.io; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.util.Iterator; -import java.util.NoSuchElementException; - -import fr.ens.transcriptome.eoulsan.bio.Sequence; -import fr.ens.transcriptome.eoulsan.util.FileUtils; - -/** - * This class define a Fasta reader. - * @author Laurent Jourdren - */ -public class FastaReader implements SequenceReader { - - protected BufferedReader reader; - - private Sequence result = null; - private final StringBuilder sb = new StringBuilder(); - - private String nextSequenceName; - private boolean end = false; - private boolean nextCallDone = true; - private int count; - protected IOException exception; - - @Override - public void close() throws IOException { - - this.reader.close(); - } - - @Override - public Iterator iterator() { - - return this; - } - - @Override - public boolean hasNext() { - - if (this.end) - return false; - - result = new Sequence(); - - String line = null; - - try { - while ((line = this.reader.readLine()) != null) { - - // Trim the line - final String trim = line.trim(); - - // discard empty lines - if ("".equals(trim)) - continue; - - if (trim.charAt(0) == '>') { - - if (this.nextSequenceName != null) { - - result.setName(this.nextSequenceName); - result.setSequence(sb.toString()); - result.setId(this.count++); - sb.setLength(0); - this.nextSequenceName = trim.substring(1); - this.nextCallDone = false; - - return true; - } - - this.nextSequenceName = trim.substring(1); - - } else { - sb.append(trim); - } - } - - result.setName(this.nextSequenceName); - result.setSequence(sb.toString()); - result.setId(this.count++); - sb.setLength(0); - - this.nextCallDone = false; - this.end = true; - - return true; - } catch (IOException e) { - - this.exception = e; - this.end = true; - return false; - } - } - - @Override - public Sequence next() { - - if (this.nextCallDone) - throw new NoSuchElementException(); - - this.nextCallDone = true; - - return this.result; - } - - @Override - public void remove() { - - throw new UnsupportedOperationException("Unsupported operation"); - } - - @Override - public void throwException() throws IOException { - - if (this.exception != null) - throw this.exception; - } - - // - // Constructors - // - - /** - * Public constructor - * @param is InputStream to use - */ - public FastaReader(final InputStream is) { - - if (is == null) - throw new NullPointerException("InputStream is null"); - - this.reader = new BufferedReader(new InputStreamReader(is)); - } - - /** - * Public constructor - * @param file File to use - */ - public FastaReader(final File file) throws FileNotFoundException { - - if (file == null) - throw new NullPointerException("File is null"); - - if (!file.isFile()) - throw new FileNotFoundException("File not found: " - + file.getAbsolutePath()); - - this.reader = FileUtils.createBufferedReader(file); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/pair.info deleted file mode 100755 index a71cab6..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33669/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:33669 -comSha:4a4f273ebcb53fc498dd0c45bc5dd4ea66cf5480 -parentComSha:237a7830c382d17dfa2fd10951c13d1ad46075b2 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/io/FastaReader.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/io/FastaReader.java -StartLineNum:163 -EndLineNum:163 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/comMsg.txt deleted file mode 100755 index d9d4ae0..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -With findbugs, fixes all bugs in Internationalization category. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/diff.diff deleted file mode 100755 index fb5eaff..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/bio/expressioncounters/HTSeqCounter.java b/src/main/java/fr/ens/transcriptome/eoulsan/bio/expressioncounters/HTSeqCounter.java -index 00d0cbf0..9da4c5ea 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/bio/expressioncounters/HTSeqCounter.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/bio/expressioncounters/HTSeqCounter.java -@@ -29 +28,0 @@ import java.io.FileInputStream; --import java.io.FileWriter; -@@ -55,0 +55 @@ import fr.ens.transcriptome.eoulsan.steps.expression.ExpressionCounters; -+import fr.ens.transcriptome.eoulsan.util.FileUtils; -@@ -126 +126 @@ public class HTSeqCounter extends AbstractExpressionCounter { -- Writer writer = new FileWriter(outFile); -+ final Writer writer = FileUtils.createBufferedWriter(outFile); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/new/HTSeqCounter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/new/HTSeqCounter.java deleted file mode 100755 index 9da4c5e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/new/HTSeqCounter.java +++ /dev/null @@ -1,672 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.expressioncounters; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import net.sf.samtools.Cigar; -import net.sf.samtools.CigarElement; -import net.sf.samtools.CigarOperator; -import net.sf.samtools.SAMFileReader; -import net.sf.samtools.SAMRecord; -import net.sf.samtools.SAMRecordIterator; -import fr.ens.transcriptome.eoulsan.EoulsanException; -import fr.ens.transcriptome.eoulsan.bio.BadBioEntryException; -import fr.ens.transcriptome.eoulsan.bio.GFFEntry; -import fr.ens.transcriptome.eoulsan.bio.GenomicArray; -import fr.ens.transcriptome.eoulsan.bio.GenomicInterval; -import fr.ens.transcriptome.eoulsan.bio.io.GFFReader; -import fr.ens.transcriptome.eoulsan.data.DataFile; -import fr.ens.transcriptome.eoulsan.steps.expression.ExpressionCounters; -import fr.ens.transcriptome.eoulsan.util.FileUtils; -import fr.ens.transcriptome.eoulsan.util.Reporter; -import fr.ens.transcriptome.eoulsan.util.Utils; - -/** - * This class define a wrapper on the HTSeq-count counter. - * @since 1.2 - * @author Claire Wallon - */ -public class HTSeqCounter extends AbstractExpressionCounter { - - private static final String COUNTER_NAME = "htseq-count"; - - @Override - public String getCounterName() { - - return COUNTER_NAME; - } - - @Override - protected void internalCount(File alignmentFile, DataFile annotationFile, - File expressionFile, final DataFile GenomeDescFile, Reporter reporter, - String counterGroup) throws IOException { - - try { - - countReadsInFeatures(alignmentFile, annotationFile.open(), - expressionFile, getStranded(), getOverlapMode(), getGenomicType(), - "ID", false, 0, null, reporter, counterGroup); - - } catch (EoulsanException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (BadBioEntryException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - /** - * Count the number of alignments for all the features of the annotation file. - * @param samFile SAM file that contains alignments. - * @param gffFile annotation file. - * @param outFile output file. - * @param stranded strand to consider. - * @param overlapMode overlap mode to consider. - * @param featureType annotation feature type to consider. - * @param attributeId annotation attribute id to consider. - * @param quiet if true : suppress progress report and warnings. - * @param minAverageQual minimum value for alignment quality. - * @param samOutFile output SAM file annotating each line with its assignment - * to a feature or a special counter (as an optional field with tag - * 'XF'). - * @param reporter Reporter object. - * @param counterGroup counter group for the Reporter object. - * @throws EoulsanException - * @throws IOException - * @throws BadBioEntryException - */ - private static void countReadsInFeatures(final File samFile, - final InputStream gffFile, final File outFile, - final StrandUsage stranded, final OverlapMode overlapMode, - final String featureType, final String attributeId, final boolean quiet, - final int minAverageQual, final File samOutFile, Reporter reporter, - String counterGroup) throws EoulsanException, IOException, - BadBioEntryException { - - final GenomicArray features = new GenomicArray(); - final Map counts = Utils.newHashMap(); - - final Writer writer = FileUtils.createBufferedWriter(outFile); - - boolean pairedEnd = false; - - // features = readAnnotation(gffFile, stranded, featureType, attributeId); - - final GFFReader gffReader = new GFFReader(gffFile); - - // Read the annotation file - for (final GFFEntry gff : gffReader) { - - if (featureType.equals(gff.getType())) { - - final String featureId = gff.getAttributeValue(attributeId); - if (featureId == null) { - gffReader.close(); - writer.close(); - throw new EoulsanException("Feature " - + featureType + " does not contain a " + attributeId - + " attribute"); - } - - if ((stranded == StrandUsage.YES || stranded == StrandUsage.REVERSE) - && '.' == gff.getStrand()) { - gffReader.close(); - writer.close(); - throw new EoulsanException("Feature " - + featureType - + " does not have strand information but you are running " - + "htseq-count in stranded mode."); - } - - // Addition to the list of features of a GenomicInterval object - // corresponding to the current annotation line - features.addEntry( - new GenomicInterval(gff, stranded.isSaveStrandInfo()), featureId); - counts.put(featureId, 0); - } - } - gffReader.throwException(); - gffReader.close(); - - if (counts.size() == 0) { - writer.close(); - throw new EoulsanException("Warning: No features of type '" - + featureType + "' found.\n"); - } - - List ivSeq = new ArrayList(); - - final SAMFileReader inputSam = new SAMFileReader(samFile); - - // paired-end mode ? - final SAMFileReader input = new SAMFileReader(samFile); - SAMRecordIterator samIterator = input.iterator(); - SAMRecord firstRecord = samIterator.next(); - if (firstRecord.getReadPairedFlag()) - pairedEnd = true; - input.close(); - - int empty = 0; - int ambiguous = 0; - int notaligned = 0; - int lowqual = 0; - int nonunique = 0; - int i = 0; - SAMRecord sam1 = null, sam2 = null; - - // Read the SAM file - for (final SAMRecord samRecord : inputSam) { - - reporter.incrCounter(counterGroup, - ExpressionCounters.TOTAL_ALIGNMENTS_COUNTER.counterName(), 1); - - i++; - if (i % 1000000 == 0) - System.out.println(i + " sam entries read."); - - // single-end mode - if (!pairedEnd) { - - ivSeq.clear(); - - // unmapped read - if (samRecord.getReadUnmappedFlag()) { - notaligned++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - // multiple alignment - if (samRecord.getAttribute("NH") != null - && samRecord.getIntegerAttribute("NH") > 1) { - nonunique++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - // too low quality - if (samRecord.getMappingQuality() < minAverageQual) { - lowqual++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - ivSeq.addAll(addIntervals(samRecord, stranded)); - - } - - // paired-end mode - else { - - if (sam1 != null && sam2 != null) { - sam1 = null; - sam2 = null; - ivSeq.clear(); - } - - if (samRecord.getFirstOfPairFlag()) - sam1 = samRecord; - else - sam2 = samRecord; - - if (sam1 == null || sam2 == null) - continue; - - if (!sam1.getReadName().equals(sam2.getReadName())) { - sam1 = sam2; - sam2 = null; - continue; - } - - if (sam1 != null && !sam1.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam1, stranded)); - } - - if (sam2 != null && !sam2.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam2, stranded)); - } - - // unmapped read - if (sam1.getReadUnmappedFlag() && sam2.getReadUnmappedFlag()) { - notaligned++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - // multiple alignment - if ((sam1.getAttribute("NH") != null && sam1.getIntegerAttribute("NH") > 1) - || (sam2.getAttribute("NH") != null && sam2 - .getIntegerAttribute("NH") > 1)) { - nonunique++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - // too low quality - if (sam1.getMappingQuality() < minAverageQual - || sam2.getMappingQuality() < minAverageQual) { - lowqual++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - } - - Set fs = null; - - fs = featuresOverlapped(ivSeq, features, overlapMode, stranded); - - if (fs == null) - fs = new HashSet(); - - switch (fs.size()) { - case 0: - empty++; - reporter.incrCounter(counterGroup, - ExpressionCounters.UNMAPPED_READS_COUNTER.counterName(), 1); - break; - - case 1: - final String id = fs.iterator().next(); - counts.put(id, counts.get(id) + 1); - break; - - default: - ambiguous++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - break; - } - - } - - inputSam.close(); - - // Write results - final List keysSorted = new ArrayList(counts.keySet()); - Collections.sort(keysSorted); - - for (String key : keysSorted) { - writer.write(key + "\t" + counts.get(key) + "\n"); - } - - writer.write("no_feature\t" + empty + '\n'); - writer.write("ambiguous\t" + ambiguous + '\n'); - writer.write("too_low_aQual\t" + lowqual + '\n'); - writer.write("not_aligned\t" + notaligned + '\n'); - writer.write("alignment_not_unique\t" + nonunique + '\n'); - - writer.close(); - } - - // private static final GenomicArray readAnnotation( - // final InputStream gffFile, final String stranded, - // final String featureType, final String attributeId) { - // - // final GenomicArray features = new GenomicArray(); - // final GFFReader gffReader = new GFFReader(gffFile); - // - // // Read the annotation file - // for (final GFFEntry gff : gffReader) { - // - // if (featureType.equals(gff.getType())) { - // - // final String featureId = gff.getAttributeValue(attributeId); - // if (featureId == null) - // throw new EoulsanException("Feature " - // + featureType + " does not contain a " + attributeId - // + " attribute"); - // - // if (stranded.equals("yes") && '.' == gff.getStrand()) - // throw new EoulsanException("Feature " - // + featureType - // + " does not have strand information but you are running " - // + "htseq-count in stranded mode."); - // - // // Addition to the list of features of a GenomicInterval object - // // corresponding to the current annotation line - // features.addEntry(new GenomicInterval(gff, stranded), featureId); - // counts.put(featureId, 0); - // } - // } - // gffReader.throwException(); - // gffReader.close(); - // - // return features; - // } - - /** - * Add intervals of a SAM record that are alignment matches. - * @param record the SAM record to treat. - * @param stranded strand to consider. - * @return the list of intervals of the SAM record. - */ - private static List addIntervals(final SAMRecord record, - final StrandUsage stranded) { - - if (record == null) - return null; - - List result = new ArrayList(); - - // single-end mode or first read in the paired-end mode - if (!record.getReadPairedFlag() - || (record.getReadPairedFlag() && record.getFirstOfPairFlag())) { - - // the read has to be mapped to the opposite strand as the feature - if (stranded == StrandUsage.REVERSE) - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '+' : '-')); - - // stranded == "yes" (so the read has to be mapped to the same strand as - // the feature) or stranded == "no" (so the read is considered - // overlapping with a feature regardless of whether it is mapped to the - // same or the opposite strand as the feature) - else - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '-' : '+')); - } - - // second read in the paired-end mode - else if (record.getReadPairedFlag() && !record.getFirstOfPairFlag()) { - - // the read has to be mapped to the opposite strand as the feature - if (stranded == StrandUsage.REVERSE) - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '-' : '+')); - - // stranded == "yes" (so the read has to be mapped to the same strand as - // the feature) or stranded == "no" (so the read is considered - // overlapping with a feature regardless of whether it is mapped to the - // same or the opposite strand as the feature) - else - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '+' : '-')); - } - - return result; - } - - /** - * Parse a CIGAR string to have intervals of a chromosome that are alignments - * matches. - * @param cigar CIGAR string to parse. - * @param chromosome chromosome that support the alignment. - * @param start start position of the alignment. - * @param strand strand to consider. - * @return the list of intervals that are alignments matches. - */ - private static final List parseCigar(Cigar cigar, - final String chromosome, final int start, final char strand) { - - if (cigar == null) - return null; - - final List result = new ArrayList(); - - int pos = start; - for (CigarElement ce : cigar.getCigarElements()) { - - final int len = ce.getLength(); - - // the CIGAR element correspond to a mapped region - if (ce.getOperator() == CigarOperator.M) { - result.add(new GenomicInterval(chromosome, pos, pos + len - 1, strand)); - pos += len; - } - // the CIGAR element did not correspond to a mapped region - else { - // regions coded by a 'I' (insertion) do not have to be counted - // (are there other cases like this one ?) - if (pos != start && ce.getOperator() != CigarOperator.I) - pos += len; - } - } - - return result; - } - - /** - * Determine features that overlap genomic intervals. - * @param ivList the list of genomic intervals. - * @param features the list of features. - * @param mode the overlap mode. - * @return the set of features that overlap genomic intervals according to the - * overlap mode. - * @throws EoulsanException - */ - private static Set featuresOverlapped(List ivList, - GenomicArray features, OverlapMode mode, StrandUsage stranded) - throws EoulsanException { - - Set fs = null; - Map inter = new HashMap(); - - // Overlap mode "union" - if (mode == OverlapMode.UNION) { - - fs = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlap the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded == StrandUsage.YES || stranded == StrandUsage.REVERSE) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // At least one interval is found - if (intervals != null && intervals.size() > 0) { - Collection values = intervals.values(); - // Add all the features that overlap the current interval to the set - if (values != null) - fs.addAll(values); - } - } - } - - // Overlap mode "intersection-nonempty" - else if (mode == OverlapMode.INTERSECTION_NONEMPTY) { - - final Set featureTmp = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlap the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded == StrandUsage.YES || stranded == StrandUsage.REVERSE) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // At least one interval is found - if (intervals != null && intervals.size() > 0) { - Collection values = intervals.values(); - if (values != null) { - - // Determine features that correspond to the overlap mode - for (int pos = iv.getStart(); pos <= iv.getEnd(); pos++) { - - featureTmp.clear(); - - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().include(pos, pos)) - featureTmp.add(e.getValue()); - } - - if (featureTmp.size() > 0) { - if (fs == null) { - fs = new HashSet(); - fs.addAll(featureTmp); - } else - fs.retainAll(featureTmp); - } - - } - } - } - } - } - - // Overlap mode "intersection-strict" - else if (mode == OverlapMode.INTERSECTION_STRICT) { - - final Set featureTmp = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlapped the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - // LOGGER.info("intervals size before : "+intervals.size()); - - if (stranded == StrandUsage.YES || stranded == StrandUsage.REVERSE) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // LOGGER.info("intervals size after : "+intervals.size()); - - // At least one interval is found - if (intervals != null && intervals.size() > 0) { - Collection values = intervals.values(); - if (values != null) { - - // Determine features that correspond to the overlap mode - for (int pos = iv.getStart(); pos <= iv.getEnd(); pos++) { - - featureTmp.clear(); - - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().include(pos, pos)) { - featureTmp.add(e.getValue()); - } - } - - if (fs == null) { - fs = new HashSet(); - fs.addAll(featureTmp); - } else - fs.retainAll(featureTmp); - } - } - } - - // no interval found - else { - if (fs == null) - fs = new HashSet(); - else - fs.clear(); - } - - } - } - - return fs; - } - - public static void main(String[] args) throws EoulsanException, IOException, - BadBioEntryException { - - final File dir = new File("/home/wallon/Bureau/TEST_HTSEQ/EOULSAN"); - // final File samFile = new File(dir, "filtered_mapper_results_1.sam"); - // final File samFile = new - // File("/home/wallon/Bureau/GSNAP/PE/500head.sam"); - final File samFile = new File(dir, "filtered_mapper_results_1.sam"); - final FileInputStream gffFile = - new FileInputStream(new File("/home/wallon/Bureau/DATA/annotation.gff")); - // final File gffFile = new File("/home/wallon/Bureau/GSNAP/PE/mouse.gff"); - final File output = new File(dir, "counter-test-java-strict-yes"); - Reporter reporter = new Reporter(); - String counterGroup = "expression-test"; - - final long startTime = System.currentTimeMillis(); - System.out.println("start."); - countReadsInFeatures(samFile, gffFile, output, StrandUsage.YES, - OverlapMode.INTERSECTION_STRICT, "exon", "ID", false, 0, null, - reporter, counterGroup); - System.out.println("end."); - System.out.println("Duration: " - + (System.currentTimeMillis() - startTime) + " ms."); - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/old/HTSeqCounter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/old/HTSeqCounter.java deleted file mode 100755 index 00d0cbf..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/old/HTSeqCounter.java +++ /dev/null @@ -1,672 +0,0 @@ -/* - * Eoulsan development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public License version 2.1 or - * later and CeCILL-C. This should be distributed with the code. - * If you do not have a copy, see: - * - * http://www.gnu.org/licenses/lgpl-2.1.txt - * http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.txt - * - * Copyright for this code is held jointly by the Genomic platform - * of the Institut de Biologie de l'École Normale Supérieure and - * the individual authors. These should be listed in @author doc - * comments. - * - * For more information on the Eoulsan project and its aims, - * or to join the Eoulsan Google group, visit the home page - * at: - * - * http://www.transcriptome.ens.fr/eoulsan - * - */ - -package fr.ens.transcriptome.eoulsan.bio.expressioncounters; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import net.sf.samtools.Cigar; -import net.sf.samtools.CigarElement; -import net.sf.samtools.CigarOperator; -import net.sf.samtools.SAMFileReader; -import net.sf.samtools.SAMRecord; -import net.sf.samtools.SAMRecordIterator; -import fr.ens.transcriptome.eoulsan.EoulsanException; -import fr.ens.transcriptome.eoulsan.bio.BadBioEntryException; -import fr.ens.transcriptome.eoulsan.bio.GFFEntry; -import fr.ens.transcriptome.eoulsan.bio.GenomicArray; -import fr.ens.transcriptome.eoulsan.bio.GenomicInterval; -import fr.ens.transcriptome.eoulsan.bio.io.GFFReader; -import fr.ens.transcriptome.eoulsan.data.DataFile; -import fr.ens.transcriptome.eoulsan.steps.expression.ExpressionCounters; -import fr.ens.transcriptome.eoulsan.util.Reporter; -import fr.ens.transcriptome.eoulsan.util.Utils; - -/** - * This class define a wrapper on the HTSeq-count counter. - * @since 1.2 - * @author Claire Wallon - */ -public class HTSeqCounter extends AbstractExpressionCounter { - - private static final String COUNTER_NAME = "htseq-count"; - - @Override - public String getCounterName() { - - return COUNTER_NAME; - } - - @Override - protected void internalCount(File alignmentFile, DataFile annotationFile, - File expressionFile, final DataFile GenomeDescFile, Reporter reporter, - String counterGroup) throws IOException { - - try { - - countReadsInFeatures(alignmentFile, annotationFile.open(), - expressionFile, getStranded(), getOverlapMode(), getGenomicType(), - "ID", false, 0, null, reporter, counterGroup); - - } catch (EoulsanException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (BadBioEntryException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - } - - /** - * Count the number of alignments for all the features of the annotation file. - * @param samFile SAM file that contains alignments. - * @param gffFile annotation file. - * @param outFile output file. - * @param stranded strand to consider. - * @param overlapMode overlap mode to consider. - * @param featureType annotation feature type to consider. - * @param attributeId annotation attribute id to consider. - * @param quiet if true : suppress progress report and warnings. - * @param minAverageQual minimum value for alignment quality. - * @param samOutFile output SAM file annotating each line with its assignment - * to a feature or a special counter (as an optional field with tag - * 'XF'). - * @param reporter Reporter object. - * @param counterGroup counter group for the Reporter object. - * @throws EoulsanException - * @throws IOException - * @throws BadBioEntryException - */ - private static void countReadsInFeatures(final File samFile, - final InputStream gffFile, final File outFile, - final StrandUsage stranded, final OverlapMode overlapMode, - final String featureType, final String attributeId, final boolean quiet, - final int minAverageQual, final File samOutFile, Reporter reporter, - String counterGroup) throws EoulsanException, IOException, - BadBioEntryException { - - final GenomicArray features = new GenomicArray(); - final Map counts = Utils.newHashMap(); - - Writer writer = new FileWriter(outFile); - - boolean pairedEnd = false; - - // features = readAnnotation(gffFile, stranded, featureType, attributeId); - - final GFFReader gffReader = new GFFReader(gffFile); - - // Read the annotation file - for (final GFFEntry gff : gffReader) { - - if (featureType.equals(gff.getType())) { - - final String featureId = gff.getAttributeValue(attributeId); - if (featureId == null) { - gffReader.close(); - writer.close(); - throw new EoulsanException("Feature " - + featureType + " does not contain a " + attributeId - + " attribute"); - } - - if ((stranded == StrandUsage.YES || stranded == StrandUsage.REVERSE) - && '.' == gff.getStrand()) { - gffReader.close(); - writer.close(); - throw new EoulsanException("Feature " - + featureType - + " does not have strand information but you are running " - + "htseq-count in stranded mode."); - } - - // Addition to the list of features of a GenomicInterval object - // corresponding to the current annotation line - features.addEntry( - new GenomicInterval(gff, stranded.isSaveStrandInfo()), featureId); - counts.put(featureId, 0); - } - } - gffReader.throwException(); - gffReader.close(); - - if (counts.size() == 0) { - writer.close(); - throw new EoulsanException("Warning: No features of type '" - + featureType + "' found.\n"); - } - - List ivSeq = new ArrayList(); - - final SAMFileReader inputSam = new SAMFileReader(samFile); - - // paired-end mode ? - final SAMFileReader input = new SAMFileReader(samFile); - SAMRecordIterator samIterator = input.iterator(); - SAMRecord firstRecord = samIterator.next(); - if (firstRecord.getReadPairedFlag()) - pairedEnd = true; - input.close(); - - int empty = 0; - int ambiguous = 0; - int notaligned = 0; - int lowqual = 0; - int nonunique = 0; - int i = 0; - SAMRecord sam1 = null, sam2 = null; - - // Read the SAM file - for (final SAMRecord samRecord : inputSam) { - - reporter.incrCounter(counterGroup, - ExpressionCounters.TOTAL_ALIGNMENTS_COUNTER.counterName(), 1); - - i++; - if (i % 1000000 == 0) - System.out.println(i + " sam entries read."); - - // single-end mode - if (!pairedEnd) { - - ivSeq.clear(); - - // unmapped read - if (samRecord.getReadUnmappedFlag()) { - notaligned++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - // multiple alignment - if (samRecord.getAttribute("NH") != null - && samRecord.getIntegerAttribute("NH") > 1) { - nonunique++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - // too low quality - if (samRecord.getMappingQuality() < minAverageQual) { - lowqual++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - ivSeq.addAll(addIntervals(samRecord, stranded)); - - } - - // paired-end mode - else { - - if (sam1 != null && sam2 != null) { - sam1 = null; - sam2 = null; - ivSeq.clear(); - } - - if (samRecord.getFirstOfPairFlag()) - sam1 = samRecord; - else - sam2 = samRecord; - - if (sam1 == null || sam2 == null) - continue; - - if (!sam1.getReadName().equals(sam2.getReadName())) { - sam1 = sam2; - sam2 = null; - continue; - } - - if (sam1 != null && !sam1.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam1, stranded)); - } - - if (sam2 != null && !sam2.getReadUnmappedFlag()) { - ivSeq.addAll(addIntervals(sam2, stranded)); - } - - // unmapped read - if (sam1.getReadUnmappedFlag() && sam2.getReadUnmappedFlag()) { - notaligned++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - // multiple alignment - if ((sam1.getAttribute("NH") != null && sam1.getIntegerAttribute("NH") > 1) - || (sam2.getAttribute("NH") != null && sam2 - .getIntegerAttribute("NH") > 1)) { - nonunique++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - // too low quality - if (sam1.getMappingQuality() < minAverageQual - || sam2.getMappingQuality() < minAverageQual) { - lowqual++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - continue; - } - - } - - Set fs = null; - - fs = featuresOverlapped(ivSeq, features, overlapMode, stranded); - - if (fs == null) - fs = new HashSet(); - - switch (fs.size()) { - case 0: - empty++; - reporter.incrCounter(counterGroup, - ExpressionCounters.UNMAPPED_READS_COUNTER.counterName(), 1); - break; - - case 1: - final String id = fs.iterator().next(); - counts.put(id, counts.get(id) + 1); - break; - - default: - ambiguous++; - reporter.incrCounter(counterGroup, - ExpressionCounters.ELIMINATED_READS_COUNTER.counterName(), 1); - break; - } - - } - - inputSam.close(); - - // Write results - final List keysSorted = new ArrayList(counts.keySet()); - Collections.sort(keysSorted); - - for (String key : keysSorted) { - writer.write(key + "\t" + counts.get(key) + "\n"); - } - - writer.write("no_feature\t" + empty + '\n'); - writer.write("ambiguous\t" + ambiguous + '\n'); - writer.write("too_low_aQual\t" + lowqual + '\n'); - writer.write("not_aligned\t" + notaligned + '\n'); - writer.write("alignment_not_unique\t" + nonunique + '\n'); - - writer.close(); - } - - // private static final GenomicArray readAnnotation( - // final InputStream gffFile, final String stranded, - // final String featureType, final String attributeId) { - // - // final GenomicArray features = new GenomicArray(); - // final GFFReader gffReader = new GFFReader(gffFile); - // - // // Read the annotation file - // for (final GFFEntry gff : gffReader) { - // - // if (featureType.equals(gff.getType())) { - // - // final String featureId = gff.getAttributeValue(attributeId); - // if (featureId == null) - // throw new EoulsanException("Feature " - // + featureType + " does not contain a " + attributeId - // + " attribute"); - // - // if (stranded.equals("yes") && '.' == gff.getStrand()) - // throw new EoulsanException("Feature " - // + featureType - // + " does not have strand information but you are running " - // + "htseq-count in stranded mode."); - // - // // Addition to the list of features of a GenomicInterval object - // // corresponding to the current annotation line - // features.addEntry(new GenomicInterval(gff, stranded), featureId); - // counts.put(featureId, 0); - // } - // } - // gffReader.throwException(); - // gffReader.close(); - // - // return features; - // } - - /** - * Add intervals of a SAM record that are alignment matches. - * @param record the SAM record to treat. - * @param stranded strand to consider. - * @return the list of intervals of the SAM record. - */ - private static List addIntervals(final SAMRecord record, - final StrandUsage stranded) { - - if (record == null) - return null; - - List result = new ArrayList(); - - // single-end mode or first read in the paired-end mode - if (!record.getReadPairedFlag() - || (record.getReadPairedFlag() && record.getFirstOfPairFlag())) { - - // the read has to be mapped to the opposite strand as the feature - if (stranded == StrandUsage.REVERSE) - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '+' : '-')); - - // stranded == "yes" (so the read has to be mapped to the same strand as - // the feature) or stranded == "no" (so the read is considered - // overlapping with a feature regardless of whether it is mapped to the - // same or the opposite strand as the feature) - else - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '-' : '+')); - } - - // second read in the paired-end mode - else if (record.getReadPairedFlag() && !record.getFirstOfPairFlag()) { - - // the read has to be mapped to the opposite strand as the feature - if (stranded == StrandUsage.REVERSE) - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '-' : '+')); - - // stranded == "yes" (so the read has to be mapped to the same strand as - // the feature) or stranded == "no" (so the read is considered - // overlapping with a feature regardless of whether it is mapped to the - // same or the opposite strand as the feature) - else - result.addAll(parseCigar(record.getCigar(), record.getReferenceName(), - record.getAlignmentStart(), record.getReadNegativeStrandFlag() - ? '+' : '-')); - } - - return result; - } - - /** - * Parse a CIGAR string to have intervals of a chromosome that are alignments - * matches. - * @param cigar CIGAR string to parse. - * @param chromosome chromosome that support the alignment. - * @param start start position of the alignment. - * @param strand strand to consider. - * @return the list of intervals that are alignments matches. - */ - private static final List parseCigar(Cigar cigar, - final String chromosome, final int start, final char strand) { - - if (cigar == null) - return null; - - final List result = new ArrayList(); - - int pos = start; - for (CigarElement ce : cigar.getCigarElements()) { - - final int len = ce.getLength(); - - // the CIGAR element correspond to a mapped region - if (ce.getOperator() == CigarOperator.M) { - result.add(new GenomicInterval(chromosome, pos, pos + len - 1, strand)); - pos += len; - } - // the CIGAR element did not correspond to a mapped region - else { - // regions coded by a 'I' (insertion) do not have to be counted - // (are there other cases like this one ?) - if (pos != start && ce.getOperator() != CigarOperator.I) - pos += len; - } - } - - return result; - } - - /** - * Determine features that overlap genomic intervals. - * @param ivList the list of genomic intervals. - * @param features the list of features. - * @param mode the overlap mode. - * @return the set of features that overlap genomic intervals according to the - * overlap mode. - * @throws EoulsanException - */ - private static Set featuresOverlapped(List ivList, - GenomicArray features, OverlapMode mode, StrandUsage stranded) - throws EoulsanException { - - Set fs = null; - Map inter = new HashMap(); - - // Overlap mode "union" - if (mode == OverlapMode.UNION) { - - fs = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlap the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded == StrandUsage.YES || stranded == StrandUsage.REVERSE) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // At least one interval is found - if (intervals != null && intervals.size() > 0) { - Collection values = intervals.values(); - // Add all the features that overlap the current interval to the set - if (values != null) - fs.addAll(values); - } - } - } - - // Overlap mode "intersection-nonempty" - else if (mode == OverlapMode.INTERSECTION_NONEMPTY) { - - final Set featureTmp = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlap the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - if (stranded == StrandUsage.YES || stranded == StrandUsage.REVERSE) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // At least one interval is found - if (intervals != null && intervals.size() > 0) { - Collection values = intervals.values(); - if (values != null) { - - // Determine features that correspond to the overlap mode - for (int pos = iv.getStart(); pos <= iv.getEnd(); pos++) { - - featureTmp.clear(); - - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().include(pos, pos)) - featureTmp.add(e.getValue()); - } - - if (featureTmp.size() > 0) { - if (fs == null) { - fs = new HashSet(); - fs.addAll(featureTmp); - } else - fs.retainAll(featureTmp); - } - - } - } - } - } - } - - // Overlap mode "intersection-strict" - else if (mode == OverlapMode.INTERSECTION_STRICT) { - - final Set featureTmp = new HashSet(); - - for (final GenomicInterval iv : ivList) { - - final String chr = iv.getChromosome(); - - if (!features.containsChromosome(chr)) - throw new EoulsanException("Unknown chromosome: " + chr); - - // Get features that overlapped the current interval of the read - Map intervals = - features.getEntries(chr, iv.getStart(), iv.getEnd()); - - // LOGGER.info("intervals size before : "+intervals.size()); - - if (stranded == StrandUsage.YES || stranded == StrandUsage.REVERSE) { - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().getStrand() == iv.getStrand()) - inter.put(e.getKey(), e.getValue()); - } - intervals = inter; - } - - // LOGGER.info("intervals size after : "+intervals.size()); - - // At least one interval is found - if (intervals != null && intervals.size() > 0) { - Collection values = intervals.values(); - if (values != null) { - - // Determine features that correspond to the overlap mode - for (int pos = iv.getStart(); pos <= iv.getEnd(); pos++) { - - featureTmp.clear(); - - for (Map.Entry e : intervals.entrySet()) { - if (e.getKey().include(pos, pos)) { - featureTmp.add(e.getValue()); - } - } - - if (fs == null) { - fs = new HashSet(); - fs.addAll(featureTmp); - } else - fs.retainAll(featureTmp); - } - } - } - - // no interval found - else { - if (fs == null) - fs = new HashSet(); - else - fs.clear(); - } - - } - } - - return fs; - } - - public static void main(String[] args) throws EoulsanException, IOException, - BadBioEntryException { - - final File dir = new File("/home/wallon/Bureau/TEST_HTSEQ/EOULSAN"); - // final File samFile = new File(dir, "filtered_mapper_results_1.sam"); - // final File samFile = new - // File("/home/wallon/Bureau/GSNAP/PE/500head.sam"); - final File samFile = new File(dir, "filtered_mapper_results_1.sam"); - final FileInputStream gffFile = - new FileInputStream(new File("/home/wallon/Bureau/DATA/annotation.gff")); - // final File gffFile = new File("/home/wallon/Bureau/GSNAP/PE/mouse.gff"); - final File output = new File(dir, "counter-test-java-strict-yes"); - Reporter reporter = new Reporter(); - String counterGroup = "expression-test"; - - final long startTime = System.currentTimeMillis(); - System.out.println("start."); - countReadsInFeatures(samFile, gffFile, output, StrandUsage.YES, - OverlapMode.INTERSECTION_STRICT, "exon", "ID", false, 0, null, - reporter, counterGroup); - System.out.println("end."); - System.out.println("Duration: " - + (System.currentTimeMillis() - startTime) + " ms."); - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/pair.info deleted file mode 100755 index 9054e95..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33678/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:33678 -comSha:8ae4eb8cfcb27185be49de726d96703b5911be67 -parentComSha:30cbbe29c7dfa484099ae2b1a2ac1e301b208fe5 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/expressioncounters/HTSeqCounter.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/expressioncounters/HTSeqCounter.java -StartLineNum:126 -EndLineNum:126 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/comMsg.txt deleted file mode 100755 index 846907d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FIX: Many code fix after findbugs. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/diff.diff deleted file mode 100755 index 1d86330..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/SimpleGenomeIndexStorage.java b/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/SimpleGenomeIndexStorage.java -index d7c00da0..075cd68f 100644 ---- a/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/SimpleGenomeIndexStorage.java -+++ b/src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/SimpleGenomeIndexStorage.java -@@ -137 +137,2 @@ public class SimpleGenomeIndexStorage implements GenomeIndexStorage { -- new BufferedReader(new InputStreamReader(indexFile.open())); -+ new BufferedReader(new InputStreamReader(indexFile.open(), -+ Globals.DEFAULT_FILE_ENCODING)); -@@ -180 +181,2 @@ public class SimpleGenomeIndexStorage implements GenomeIndexStorage { -- new BufferedWriter(new OutputStreamWriter(indexFile.create())); -+ new BufferedWriter(new OutputStreamWriter(indexFile.create(), -+ Globals.DEFAULT_FILE_ENCODING)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/new/SimpleGenomeIndexStorage.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/new/SimpleGenomeIndexStorage.java deleted file mode 100755 index 075cd68..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/new/SimpleGenomeIndexStorage.java +++ /dev/null @@ -1,264 +0,0 @@ -package fr.ens.transcriptome.eoulsan.bio.readsmappers; - -import static fr.ens.transcriptome.eoulsan.util.Utils.checkNotNull; -import static fr.ens.transcriptome.eoulsan.util.Utils.newLinkedHashMap; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.bio.GenomeDescription; -import fr.ens.transcriptome.eoulsan.data.DataFile; -import fr.ens.transcriptome.eoulsan.util.FileUtils; - -/** - * This class define a basic GenomeIndexStorage based on an index file. - * @author Laurent Jourdren - */ -public class SimpleGenomeIndexStorage implements GenomeIndexStorage { - - /** Logger */ - private static final Logger LOGGER = Logger.getLogger(Globals.APP_NAME); - - private static final String INDEX_FILENAME = "genomes_index_storage.txt"; - - private final DataFile dir; - private Map entries = newLinkedHashMap(); - - /** - * This inner class define an entry of the index file. - * @author Laurent Jourdren - */ - private static final class IndexEntry { - - String genomeName; - int sequences; - long length; - String genomeMD5; - String mapperName; - DataFile file; - - String getKey() { - return createKey(this.mapperName, this.genomeMD5); - } - - @Override - public String toString() { - return this.getClass().getSimpleName() - + "{genomeName=" + genomeName + ", sequences=" + sequences - + ", length=" + length + ", genomeMD5=" + genomeMD5 - + ", mapperName= " + mapperName + ", file=" + file + "}"; - } - }; - - // - // Interface methods - // - - @Override - public DataFile get(final SequenceReadsMapper mapper, - final GenomeDescription genome) { - - checkNotNull(mapper, "Mapper is null"); - checkNotNull(mapper, "Genome description is null"); - - final IndexEntry entry = this.entries.get(createKey(mapper, genome)); - - return entry == null ? null : entry.file; - } - - @Override - public void put(final SequenceReadsMapper mapper, - final GenomeDescription genome, DataFile indexArchive) { - - checkNotNull(mapper, "Mapper is null"); - checkNotNull(genome, "Genome description is null"); - checkNotNull(indexArchive, "IndexArchive is null"); - - if (!indexArchive.exists()) - return; - - final String key = createKey(mapper, genome); - - if (entries.containsKey(key)) - return; - - final IndexEntry entry = new IndexEntry(); - entry.genomeName = genome.getGenomeName().trim(); - entry.sequences = genome.getSequenceCount(); - entry.length = genome.getGenomeLength(); - entry.genomeMD5 = genome.getMD5Sum().trim(); - entry.mapperName = mapper.getMapperName().toLowerCase().trim(); - entry.file = - new DataFile(dir, entry.mapperName + "-" + entry.genomeMD5 + ".zip"); - - try { - FileUtils.copy(indexArchive.rawOpen(), entry.file.create()); - this.entries.put(entry.getKey(), entry); - save(); - LOGGER.info("Successully added " - + indexArchive.getName() + " index archive to genome index storage."); - } catch (IOException e) { - } - } - - // - // Index management methods - // - - /** - * Load the information from the index file - * @throws IOException if an error occurs while loading the index file - */ - private void load() throws IOException { - - if (!this.dir.exists()) - throw new IOException("Genome index storage directory not found: " - + this.dir.getSource()); - - final DataFile indexFile = new DataFile(dir, INDEX_FILENAME); - - // Create an empty index file if no index exists - if (!indexFile.exists()) { - - save(); - return; - } - - final BufferedReader br = - new BufferedReader(new InputStreamReader(indexFile.open(), - Globals.DEFAULT_FILE_ENCODING)); - - final Pattern pattern = Pattern.compile("\t"); - String line = null; - - while ((line = br.readLine()) != null) { - - final String trimmedLine = line.trim(); - if ("".equals(trimmedLine) || trimmedLine.startsWith("#")) - continue; - - final List fields = Arrays.asList(pattern.split(trimmedLine)); - - if (fields.size() != 6) - continue; - - final IndexEntry e = new IndexEntry(); - e.genomeName = fields.get(0); - e.genomeMD5 = fields.get(1); - e.mapperName = fields.get(4); - e.file = new DataFile(dir, fields.get(5)); - - if (e.file.exists()) - this.entries.put(e.getKey(), e); - } - - br.close(); - } - - /** - * Save the information in the index file - * @throws IOException if an error occurs while saving the index file - */ - private void save() throws IOException { - - if (!this.dir.exists()) - throw new IOException("Genome index storage directory not found: " - + this.dir.getSource()); - - final DataFile indexFile = new DataFile(dir, INDEX_FILENAME); - - // Create an empty index file - final BufferedWriter writer = - new BufferedWriter(new OutputStreamWriter(indexFile.create(), - Globals.DEFAULT_FILE_ENCODING)); - writer - .write("#Genome\tGenomeMD5\tGenomeSequences\tGenomeLength\tMapper\tIndexFile\n"); - - for (Map.Entry e : this.entries.entrySet()) { - - IndexEntry ie = e.getValue(); - - writer.append(ie.genomeName == null ? "???" : ie.genomeName); - writer.append("\t"); - writer.append(ie.genomeMD5); - writer.append("\t"); - writer.append(Integer.toString(ie.sequences)); - writer.append("\t"); - writer.append(Long.toString(ie.length)); - writer.append("\t"); - writer.append(ie.mapperName); - writer.append("\t"); - writer.append(ie.file.getName()); - writer.append("\n"); - } - - writer.close(); - } - - // - // Other methods - // - - private static final String createKey(final SequenceReadsMapper mapper, - final GenomeDescription genome) { - - return createKey(mapper.getMapperName(), genome.getMD5Sum()); - } - - private static final String createKey(final String mapperName, - final String genomeMD5) { - - return mapperName.toLowerCase().trim() + '\t' + genomeMD5; - } - - // - // Static methods - // - - /** - * Create a GenomeIndexStorage - * @param dir the path of the index storage - * @return a GenomeIndexStorage object if the path contains an index storage - * or null if no index storage is found - */ - public static final GenomeIndexStorage getInstance(final DataFile dir) { - - try { - return new SimpleGenomeIndexStorage(dir); - } catch (IOException e) { - return null; - } catch (NullPointerException e) { - return null; - } - } - - // - // Constructor - // - - /** - * Private constructor. - * @param dir Path to the index storage - * @throws IOException if an error occurs while testing the index storage - */ - private SimpleGenomeIndexStorage(final DataFile dir) throws IOException { - - checkNotNull(dir, "Index directory is null"); - - this.dir = dir; - load(); - - LOGGER.info("Genome index storage found." - + this.entries.size() + " entries in : " + dir.getSource()); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/old/SimpleGenomeIndexStorage.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/old/SimpleGenomeIndexStorage.java deleted file mode 100755 index d7c00da..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/old/SimpleGenomeIndexStorage.java +++ /dev/null @@ -1,262 +0,0 @@ -package fr.ens.transcriptome.eoulsan.bio.readsmappers; - -import static fr.ens.transcriptome.eoulsan.util.Utils.checkNotNull; -import static fr.ens.transcriptome.eoulsan.util.Utils.newLinkedHashMap; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; -import java.util.regex.Pattern; - -import fr.ens.transcriptome.eoulsan.Globals; -import fr.ens.transcriptome.eoulsan.bio.GenomeDescription; -import fr.ens.transcriptome.eoulsan.data.DataFile; -import fr.ens.transcriptome.eoulsan.util.FileUtils; - -/** - * This class define a basic GenomeIndexStorage based on an index file. - * @author Laurent Jourdren - */ -public class SimpleGenomeIndexStorage implements GenomeIndexStorage { - - /** Logger */ - private static final Logger LOGGER = Logger.getLogger(Globals.APP_NAME); - - private static final String INDEX_FILENAME = "genomes_index_storage.txt"; - - private final DataFile dir; - private Map entries = newLinkedHashMap(); - - /** - * This inner class define an entry of the index file. - * @author Laurent Jourdren - */ - private static final class IndexEntry { - - String genomeName; - int sequences; - long length; - String genomeMD5; - String mapperName; - DataFile file; - - String getKey() { - return createKey(this.mapperName, this.genomeMD5); - } - - @Override - public String toString() { - return this.getClass().getSimpleName() - + "{genomeName=" + genomeName + ", sequences=" + sequences - + ", length=" + length + ", genomeMD5=" + genomeMD5 - + ", mapperName= " + mapperName + ", file=" + file + "}"; - } - }; - - // - // Interface methods - // - - @Override - public DataFile get(final SequenceReadsMapper mapper, - final GenomeDescription genome) { - - checkNotNull(mapper, "Mapper is null"); - checkNotNull(mapper, "Genome description is null"); - - final IndexEntry entry = this.entries.get(createKey(mapper, genome)); - - return entry == null ? null : entry.file; - } - - @Override - public void put(final SequenceReadsMapper mapper, - final GenomeDescription genome, DataFile indexArchive) { - - checkNotNull(mapper, "Mapper is null"); - checkNotNull(genome, "Genome description is null"); - checkNotNull(indexArchive, "IndexArchive is null"); - - if (!indexArchive.exists()) - return; - - final String key = createKey(mapper, genome); - - if (entries.containsKey(key)) - return; - - final IndexEntry entry = new IndexEntry(); - entry.genomeName = genome.getGenomeName().trim(); - entry.sequences = genome.getSequenceCount(); - entry.length = genome.getGenomeLength(); - entry.genomeMD5 = genome.getMD5Sum().trim(); - entry.mapperName = mapper.getMapperName().toLowerCase().trim(); - entry.file = - new DataFile(dir, entry.mapperName + "-" + entry.genomeMD5 + ".zip"); - - try { - FileUtils.copy(indexArchive.rawOpen(), entry.file.create()); - this.entries.put(entry.getKey(), entry); - save(); - LOGGER.info("Successully added " - + indexArchive.getName() + " index archive to genome index storage."); - } catch (IOException e) { - } - } - - // - // Index management methods - // - - /** - * Load the information from the index file - * @throws IOException if an error occurs while loading the index file - */ - private void load() throws IOException { - - if (!this.dir.exists()) - throw new IOException("Genome index storage directory not found: " - + this.dir.getSource()); - - final DataFile indexFile = new DataFile(dir, INDEX_FILENAME); - - // Create an empty index file if no index exists - if (!indexFile.exists()) { - - save(); - return; - } - - final BufferedReader br = - new BufferedReader(new InputStreamReader(indexFile.open())); - - final Pattern pattern = Pattern.compile("\t"); - String line = null; - - while ((line = br.readLine()) != null) { - - final String trimmedLine = line.trim(); - if ("".equals(trimmedLine) || trimmedLine.startsWith("#")) - continue; - - final List fields = Arrays.asList(pattern.split(trimmedLine)); - - if (fields.size() != 6) - continue; - - final IndexEntry e = new IndexEntry(); - e.genomeName = fields.get(0); - e.genomeMD5 = fields.get(1); - e.mapperName = fields.get(4); - e.file = new DataFile(dir, fields.get(5)); - - if (e.file.exists()) - this.entries.put(e.getKey(), e); - } - - br.close(); - } - - /** - * Save the information in the index file - * @throws IOException if an error occurs while saving the index file - */ - private void save() throws IOException { - - if (!this.dir.exists()) - throw new IOException("Genome index storage directory not found: " - + this.dir.getSource()); - - final DataFile indexFile = new DataFile(dir, INDEX_FILENAME); - - // Create an empty index file - final BufferedWriter writer = - new BufferedWriter(new OutputStreamWriter(indexFile.create())); - writer - .write("#Genome\tGenomeMD5\tGenomeSequences\tGenomeLength\tMapper\tIndexFile\n"); - - for (Map.Entry e : this.entries.entrySet()) { - - IndexEntry ie = e.getValue(); - - writer.append(ie.genomeName == null ? "???" : ie.genomeName); - writer.append("\t"); - writer.append(ie.genomeMD5); - writer.append("\t"); - writer.append(Integer.toString(ie.sequences)); - writer.append("\t"); - writer.append(Long.toString(ie.length)); - writer.append("\t"); - writer.append(ie.mapperName); - writer.append("\t"); - writer.append(ie.file.getName()); - writer.append("\n"); - } - - writer.close(); - } - - // - // Other methods - // - - private static final String createKey(final SequenceReadsMapper mapper, - final GenomeDescription genome) { - - return createKey(mapper.getMapperName(), genome.getMD5Sum()); - } - - private static final String createKey(final String mapperName, - final String genomeMD5) { - - return mapperName.toLowerCase().trim() + '\t' + genomeMD5; - } - - // - // Static methods - // - - /** - * Create a GenomeIndexStorage - * @param dir the path of the index storage - * @return a GenomeIndexStorage object if the path contains an index storage - * or null if no index storage is found - */ - public static final GenomeIndexStorage getInstance(final DataFile dir) { - - try { - return new SimpleGenomeIndexStorage(dir); - } catch (IOException e) { - return null; - } catch (NullPointerException e) { - return null; - } - } - - // - // Constructor - // - - /** - * Private constructor. - * @param dir Path to the index storage - * @throws IOException if an error occurs while testing the index storage - */ - private SimpleGenomeIndexStorage(final DataFile dir) throws IOException { - - checkNotNull(dir, "Index directory is null"); - - this.dir = dir; - load(); - - LOGGER.info("Genome index storage found." - + this.entries.size() + " entries in : " + dir.getSource()); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/pair.info deleted file mode 100755 index 0c3df82..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#33732/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:33732 -comSha:4a4f273ebcb53fc498dd0c45bc5dd4ea66cf5480 -parentComSha:237a7830c382d17dfa2fd10951c13d1ad46075b2 -BuggyFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/SimpleGenomeIndexStorage.java -FixedFilePath:src/main/java/fr/ens/transcriptome/eoulsan/bio/readsmappers/SimpleGenomeIndexStorage.java -StartLineNum:136 -EndLineNum:136 -repoName:GenomicParisCentre#eoulsan \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/comMsg.txt deleted file mode 100755 index 13cd2ec..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/comMsg.txt +++ /dev/null @@ -1,6 +0,0 @@ -Issue #1555: Specify encoding explicitly - -Fixes `ImplicitDefaultCharsetUsage` inspection violations. - -Description: ->Reports method and constructor calls which implicitly use the platform's default charset. These can produce different results on (e.g. foreign language) systems that use a different default charset, resulting in unexpected behaviour. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/diff.diff deleted file mode 100755 index a56a66c..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/it/java/com/google/checkstyle/test/base/IndentationConfigurationBuilder.java b/src/it/java/com/google/checkstyle/test/base/IndentationConfigurationBuilder.java -index 4f6f34fe1..33967f995 100644 ---- a/src/it/java/com/google/checkstyle/test/base/IndentationConfigurationBuilder.java -+++ b/src/it/java/com/google/checkstyle/test/base/IndentationConfigurationBuilder.java -@@ -4,0 +5 @@ import java.io.File; -+import java.io.FileInputStream; -@@ -6,0 +8,2 @@ import java.io.IOException; -+import java.io.InputStreamReader; -+import java.nio.charset.StandardCharsets; -@@ -51 +54,2 @@ public class IndentationConfigurationBuilder extends ConfigurationBuilder -- try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) { -+ try (BufferedReader br = new BufferedReader(new InputStreamReader( -+ new FileInputStream(aFileName), StandardCharsets.UTF_8))) { \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/new/IndentationConfigurationBuilder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/new/IndentationConfigurationBuilder.java deleted file mode 100755 index 33967f9..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/new/IndentationConfigurationBuilder.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.google.checkstyle.test.base; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.puppycrawl.tools.checkstyle.utils.CommonUtils; - -public class IndentationConfigurationBuilder extends ConfigurationBuilder -{ - private static final int TAB_WIDTH = 4; - - public IndentationConfigurationBuilder(File aROOT) { - super(aROOT); - } - - @Override - public Integer[] getLinesWithWarn(String aFileName) throws IOException { - return getLinesWithWarnAndCheckComments(aFileName, TAB_WIDTH); - } - - private static final Pattern NONEMPTY_LINE_REGEX = - Pattern.compile(".*?\\S+.*?"); - - private static final Pattern LINE_WITH_COMMENT_REGEX = - Pattern.compile(".*?\\S+.*?(//indent:(\\d+) exp:((>=\\d+)|(\\d+(,\\d+)*?))( warn)?)"); - - private static final Pattern GET_INDENT_FROM_COMMENT_REGEX = - Pattern.compile("//indent:(\\d+).*?"); - - private static final Pattern MULTILEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:(\\d+(,\\d+)+?)( warn)?"); - - private static final Pattern SINGLE_LEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:(\\d+)( warn)?"); - - private static final Pattern NON_STRICT_LEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:>=(\\d+)( warn)?"); - - private static Integer[] getLinesWithWarnAndCheckComments(String aFileName, - final int tabWidth) - throws IOException - { - List result = new ArrayList<>(); - try (BufferedReader br = new BufferedReader(new InputStreamReader( - new FileInputStream(aFileName), StandardCharsets.UTF_8))) { - int lineNumber = 1; - for (String line = br.readLine(); line != null; line = br.readLine()) { - Matcher match = LINE_WITH_COMMENT_REGEX.matcher(line); - if (match.matches()) { - final String comment = match.group(1); - final int indentInComment = getIndentFromComment(comment); - final int actualIndent = getLineStart(line, tabWidth); - - if (actualIndent != indentInComment) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has incorrect indentation in comment." - + "Line %2$d: comment:%3$d, actual:%4$d.", - aFileName, - lineNumber, - indentInComment, - actualIndent)); - } - - if (isWarnComment(comment)) { - result.add(lineNumber); - } - - if (!isCommentConsistent(comment)) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has inconsistent comment on line %2$d", - aFileName, - lineNumber)); - } - } - else if (NONEMPTY_LINE_REGEX.matcher(line).matches()) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has no indentation comment or its format " - + "malformed. Error on line: %2$d(%3$s)", - aFileName, - lineNumber, - line)); - } - lineNumber++; - } - } - return result.toArray(new Integer[result.size()]); - } - - private static int getIndentFromComment(String comment) - { - final Matcher match = GET_INDENT_FROM_COMMENT_REGEX.matcher(comment); - match.matches(); - return Integer.parseInt(match.group(1)); - } - - private static boolean isWarnComment(String comment) - { - return comment.endsWith(" warn"); - } - - private static boolean isCommentConsistent(String comment) - { - final int indentInComment = getIndentFromComment(comment); - final boolean isWarnComment = isWarnComment(comment); - - Matcher match = MULTILEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final String[] levels = match.group(1).split(","); - final String indentInCommentStr = String.valueOf(indentInComment); - final boolean containsActualLevel = - Arrays.asList(levels).contains(indentInCommentStr); - - return containsActualLevel && !isWarnComment - || !containsActualLevel && isWarnComment; - } - - match = SINGLE_LEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final int expectedLevel = Integer.parseInt(match.group(1)); - - return expectedLevel == indentInComment && !isWarnComment - || expectedLevel != indentInComment && isWarnComment; - } - - match = NON_STRICT_LEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final int expectedMinimalIndent = Integer.parseInt(match.group(1)); - - return indentInComment >= expectedMinimalIndent && !isWarnComment - || indentInComment < expectedMinimalIndent && isWarnComment; - } - - throw new IllegalArgumentException("Cannot determine if commit is consistent"); - } - - private static int getLineStart(String line, final int tabWidth) - { - for (int index = 0; index < line.length(); ++index) { - if (!Character.isWhitespace(line.charAt(index))) { - return CommonUtils.lengthExpandedTabs(line, index, tabWidth); - } - } - return 0; - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/old/IndentationConfigurationBuilder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/old/IndentationConfigurationBuilder.java deleted file mode 100755 index 4f6f34f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/old/IndentationConfigurationBuilder.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.google.checkstyle.test.base; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.puppycrawl.tools.checkstyle.utils.CommonUtils; - -public class IndentationConfigurationBuilder extends ConfigurationBuilder -{ - private static final int TAB_WIDTH = 4; - - public IndentationConfigurationBuilder(File aROOT) { - super(aROOT); - } - - @Override - public Integer[] getLinesWithWarn(String aFileName) throws IOException { - return getLinesWithWarnAndCheckComments(aFileName, TAB_WIDTH); - } - - private static final Pattern NONEMPTY_LINE_REGEX = - Pattern.compile(".*?\\S+.*?"); - - private static final Pattern LINE_WITH_COMMENT_REGEX = - Pattern.compile(".*?\\S+.*?(//indent:(\\d+) exp:((>=\\d+)|(\\d+(,\\d+)*?))( warn)?)"); - - private static final Pattern GET_INDENT_FROM_COMMENT_REGEX = - Pattern.compile("//indent:(\\d+).*?"); - - private static final Pattern MULTILEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:(\\d+(,\\d+)+?)( warn)?"); - - private static final Pattern SINGLE_LEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:(\\d+)( warn)?"); - - private static final Pattern NON_STRICT_LEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:>=(\\d+)( warn)?"); - - private static Integer[] getLinesWithWarnAndCheckComments(String aFileName, - final int tabWidth) - throws IOException - { - List result = new ArrayList<>(); - try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) { - int lineNumber = 1; - for (String line = br.readLine(); line != null; line = br.readLine()) { - Matcher match = LINE_WITH_COMMENT_REGEX.matcher(line); - if (match.matches()) { - final String comment = match.group(1); - final int indentInComment = getIndentFromComment(comment); - final int actualIndent = getLineStart(line, tabWidth); - - if (actualIndent != indentInComment) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has incorrect indentation in comment." - + "Line %2$d: comment:%3$d, actual:%4$d.", - aFileName, - lineNumber, - indentInComment, - actualIndent)); - } - - if (isWarnComment(comment)) { - result.add(lineNumber); - } - - if (!isCommentConsistent(comment)) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has inconsistent comment on line %2$d", - aFileName, - lineNumber)); - } - } - else if (NONEMPTY_LINE_REGEX.matcher(line).matches()) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has no indentation comment or its format " - + "malformed. Error on line: %2$d(%3$s)", - aFileName, - lineNumber, - line)); - } - lineNumber++; - } - } - return result.toArray(new Integer[result.size()]); - } - - private static int getIndentFromComment(String comment) - { - final Matcher match = GET_INDENT_FROM_COMMENT_REGEX.matcher(comment); - match.matches(); - return Integer.parseInt(match.group(1)); - } - - private static boolean isWarnComment(String comment) - { - return comment.endsWith(" warn"); - } - - private static boolean isCommentConsistent(String comment) - { - final int indentInComment = getIndentFromComment(comment); - final boolean isWarnComment = isWarnComment(comment); - - Matcher match = MULTILEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final String[] levels = match.group(1).split(","); - final String indentInCommentStr = String.valueOf(indentInComment); - final boolean containsActualLevel = - Arrays.asList(levels).contains(indentInCommentStr); - - return containsActualLevel && !isWarnComment - || !containsActualLevel && isWarnComment; - } - - match = SINGLE_LEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final int expectedLevel = Integer.parseInt(match.group(1)); - - return expectedLevel == indentInComment && !isWarnComment - || expectedLevel != indentInComment && isWarnComment; - } - - match = NON_STRICT_LEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final int expectedMinimalIndent = Integer.parseInt(match.group(1)); - - return indentInComment >= expectedMinimalIndent && !isWarnComment - || indentInComment < expectedMinimalIndent && isWarnComment; - } - - throw new IllegalArgumentException("Cannot determine if commit is consistent"); - } - - private static int getLineStart(String line, final int tabWidth) - { - for (int index = 0; index < line.length(); ++index) { - if (!Character.isWhitespace(line.charAt(index))) { - return CommonUtils.lengthExpandedTabs(line, index, tabWidth); - } - } - return 0; - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/pair.info deleted file mode 100755 index 404898d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48980/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:48980 -comSha:9cc86b38df9a086713d1fcdf01b451b41c0d6f65 -parentComSha:a827b7cbbf1f29e24e3f814149809941e754c93c -BuggyFilePath:src/it/java/com/google/checkstyle/test/base/IndentationConfigurationBuilder.java -FixedFilePath:src/it/java/com/google/checkstyle/test/base/IndentationConfigurationBuilder.java -StartLineNum:51 -EndLineNum:51 -repoName:checkstyle#checkstyle \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/comMsg.txt deleted file mode 100755 index 13cd2ec..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/comMsg.txt +++ /dev/null @@ -1,6 +0,0 @@ -Issue #1555: Specify encoding explicitly - -Fixes `ImplicitDefaultCharsetUsage` inspection violations. - -Description: ->Reports method and constructor calls which implicitly use the platform's default charset. These can produce different results on (e.g. foreign language) systems that use a different default charset, resulting in unexpected behaviour. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/diff.diff deleted file mode 100755 index c001ffb..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/it/java/com/google/checkstyle/test/base/ConfigurationBuilder.java b/src/it/java/com/google/checkstyle/test/base/ConfigurationBuilder.java -index a194c0d3e..5a7cff9e5 100644 ---- a/src/it/java/com/google/checkstyle/test/base/ConfigurationBuilder.java -+++ b/src/it/java/com/google/checkstyle/test/base/ConfigurationBuilder.java -@@ -4,0 +5 @@ import java.io.File; -+import java.io.FileInputStream; -@@ -6,0 +8 @@ import java.io.IOException; -+import java.io.InputStreamReader; -@@ -7,0 +10 @@ import java.net.URL; -+import java.nio.charset.StandardCharsets; -@@ -107 +110,2 @@ public class ConfigurationBuilder extends BaseCheckTestSupport { -- try(BufferedReader br = new BufferedReader(new FileReader(aFileName))) { -+ try(BufferedReader br = new BufferedReader(new InputStreamReader( -+ new FileInputStream(aFileName), StandardCharsets.UTF_8))) { \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/new/ConfigurationBuilder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/new/ConfigurationBuilder.java deleted file mode 100755 index 5a7cff9..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/new/ConfigurationBuilder.java +++ /dev/null @@ -1,126 +0,0 @@ -package com.google.checkstyle.test.base; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.regex.Pattern; - -import com.puppycrawl.tools.checkstyle.ConfigurationLoader; -import com.puppycrawl.tools.checkstyle.PropertiesExpander; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.utils.CommonUtils; - -public class ConfigurationBuilder extends BaseCheckTestSupport { - - private static final String XML_NAME = "/google_checks.xml"; - - private final File root; - - private final List files = new ArrayList<>(); - - private final Configuration configuration; - - private final Pattern warnPattern = CommonUtils.createPattern(".*[ ]*//[ ]*warn[ ]*|/[*]warn[*]/"); - - private URL url; - - public ConfigurationBuilder(File aROOT) { - root = aROOT; - configuration = getConfigurationFromXML(XML_NAME, System.getProperties()); - listFiles(files, root, "java"); - } - - private static Configuration getConfigurationFromXML(String aConfigName, - Properties aProps) { - try { - return ConfigurationLoader.loadConfiguration(aConfigName, - new PropertiesExpander(aProps)); - } catch (final CheckstyleException e) { - System.out.println("Error loading configuration file"); - e.printStackTrace(System.out); - System.exit(1); - return null; - } - } - - Configuration getConfiguration() { - return configuration; - } - - public Configuration getCheckConfig(String aCheckName) { - for (Configuration currentConfig : configuration.getChildren()) { - if ("TreeWalker".equals(currentConfig.getName())) { - for (Configuration checkConfig : currentConfig.getChildren()) { - if (aCheckName.equals(checkConfig.getName())) { - return checkConfig; - } - } - } else if (aCheckName.equals(currentConfig.getName())) { - return currentConfig; - } - } - return null; - } - - public String getFilePath(String aFileName) { - String absoluteRootPath = root.getAbsolutePath(); - String rootPath = absoluteRootPath.substring(0, - absoluteRootPath.lastIndexOf("src")); - for (File file : files) { - if (file.toString().endsWith(aFileName+".java")) { - return rootPath + file; - } - } - return null; - } - - private static void listFiles(final List files, final File folder, - final String extension) { - if (folder.canRead()) { - if (folder.isDirectory()) { - for (final File file : folder.listFiles()) { - listFiles(files, file, extension); - } - } else if (folder.toString().endsWith("." + extension)) { - files.add(folder); - } - } - } - - public File getRoot() { - return root; - } - - public List getFiles() { - return Collections.unmodifiableList(files); - } - - public Integer[] getLinesWithWarn(String aFileName) throws IOException { - List result = new ArrayList<>(); - try(BufferedReader br = new BufferedReader(new InputStreamReader( - new FileInputStream(aFileName), StandardCharsets.UTF_8))) { - int lineNumber = 1; - while (true) { - String line = br.readLine(); - if (line == null) { - break; - } - if (warnPattern.matcher(line).find()) { - result.add(lineNumber); - } - lineNumber++; - } - } - return result.toArray(new Integer[result.size()]); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/old/ConfigurationBuilder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/old/ConfigurationBuilder.java deleted file mode 100755 index a194c0d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/old/ConfigurationBuilder.java +++ /dev/null @@ -1,122 +0,0 @@ -package com.google.checkstyle.test.base; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; -import java.util.regex.Pattern; - -import com.puppycrawl.tools.checkstyle.ConfigurationLoader; -import com.puppycrawl.tools.checkstyle.PropertiesExpander; -import com.puppycrawl.tools.checkstyle.api.CheckstyleException; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.utils.CommonUtils; - -public class ConfigurationBuilder extends BaseCheckTestSupport { - - private static final String XML_NAME = "/google_checks.xml"; - - private final File root; - - private final List files = new ArrayList<>(); - - private final Configuration configuration; - - private final Pattern warnPattern = CommonUtils.createPattern(".*[ ]*//[ ]*warn[ ]*|/[*]warn[*]/"); - - private URL url; - - public ConfigurationBuilder(File aROOT) { - root = aROOT; - configuration = getConfigurationFromXML(XML_NAME, System.getProperties()); - listFiles(files, root, "java"); - } - - private static Configuration getConfigurationFromXML(String aConfigName, - Properties aProps) { - try { - return ConfigurationLoader.loadConfiguration(aConfigName, - new PropertiesExpander(aProps)); - } catch (final CheckstyleException e) { - System.out.println("Error loading configuration file"); - e.printStackTrace(System.out); - System.exit(1); - return null; - } - } - - Configuration getConfiguration() { - return configuration; - } - - public Configuration getCheckConfig(String aCheckName) { - for (Configuration currentConfig : configuration.getChildren()) { - if ("TreeWalker".equals(currentConfig.getName())) { - for (Configuration checkConfig : currentConfig.getChildren()) { - if (aCheckName.equals(checkConfig.getName())) { - return checkConfig; - } - } - } else if (aCheckName.equals(currentConfig.getName())) { - return currentConfig; - } - } - return null; - } - - public String getFilePath(String aFileName) { - String absoluteRootPath = root.getAbsolutePath(); - String rootPath = absoluteRootPath.substring(0, - absoluteRootPath.lastIndexOf("src")); - for (File file : files) { - if (file.toString().endsWith(aFileName+".java")) { - return rootPath + file; - } - } - return null; - } - - private static void listFiles(final List files, final File folder, - final String extension) { - if (folder.canRead()) { - if (folder.isDirectory()) { - for (final File file : folder.listFiles()) { - listFiles(files, file, extension); - } - } else if (folder.toString().endsWith("." + extension)) { - files.add(folder); - } - } - } - - public File getRoot() { - return root; - } - - public List getFiles() { - return Collections.unmodifiableList(files); - } - - public Integer[] getLinesWithWarn(String aFileName) throws IOException { - List result = new ArrayList<>(); - try(BufferedReader br = new BufferedReader(new FileReader(aFileName))) { - int lineNumber = 1; - while (true) { - String line = br.readLine(); - if (line == null) { - break; - } - if (warnPattern.matcher(line).find()) { - result.add(lineNumber); - } - lineNumber++; - } - } - return result.toArray(new Integer[result.size()]); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/pair.info deleted file mode 100755 index 27b4b24..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#48993/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:48993 -comSha:9cc86b38df9a086713d1fcdf01b451b41c0d6f65 -parentComSha:a827b7cbbf1f29e24e3f814149809941e754c93c -BuggyFilePath:src/it/java/com/google/checkstyle/test/base/ConfigurationBuilder.java -FixedFilePath:src/it/java/com/google/checkstyle/test/base/ConfigurationBuilder.java -StartLineNum:107 -EndLineNum:107 -repoName:checkstyle#checkstyle \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/comMsg.txt deleted file mode 100755 index 13cd2ec..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/comMsg.txt +++ /dev/null @@ -1,6 +0,0 @@ -Issue #1555: Specify encoding explicitly - -Fixes `ImplicitDefaultCharsetUsage` inspection violations. - -Description: ->Reports method and constructor calls which implicitly use the platform's default charset. These can produce different results on (e.g. foreign language) systems that use a different default charset, resulting in unexpected behaviour. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/diff.diff deleted file mode 100755 index 8269370..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java -index cdea0f1d8..f73441e5b 100644 ---- a/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java -+++ b/src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java -@@ -30 +30 @@ import java.io.BufferedReader; --import java.io.FileReader; -+import java.io.FileInputStream; -@@ -31,0 +32,2 @@ import java.io.IOException; -+import java.io.InputStreamReader; -+import java.nio.charset.StandardCharsets; -@@ -73 +75,2 @@ public class IndentationCheckTest extends BaseCheckTestSupport { -- try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) { -+ try (BufferedReader br = new BufferedReader(new InputStreamReader( -+ new FileInputStream(aFileName), StandardCharsets.UTF_8))) { \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/new/IndentationCheckTest.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/new/IndentationCheckTest.java deleted file mode 100755 index f73441e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/new/IndentationCheckTest.java +++ /dev/null @@ -1,1570 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2015 the original author or authors. -// -// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.puppycrawl.tools.checkstyle.checks.indentation; - -import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_CHILD_ERROR; -import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_CHILD_ERROR_MULTI; -import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_ERROR; -import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_ERROR_MULTI; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.ArrayUtils; -import org.junit.Test; - -import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.utils.CommonUtils; - -/** - * - * @author jrichard - */ -public class IndentationCheckTest extends BaseCheckTestSupport { - private static final Pattern NONEMPTY_LINE_REGEX = - Pattern.compile(".*?\\S+.*?"); - - private static final Pattern LINE_WITH_COMMENT_REGEX = - Pattern.compile(".*?\\S+.*?(//indent:(\\d+) exp:((>=\\d+)|(\\d+(,\\d+)*?))( warn)?)"); - - private static final Pattern GET_INDENT_FROM_COMMENT_REGEX = - Pattern.compile("//indent:(\\d+).*?"); - - private static final Pattern MULTILEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:(\\d+(,\\d+)+?)( warn)?"); - - private static final Pattern SINGLELEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:(\\d+)( warn)?"); - - private static final Pattern NONSTRICT_LEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:>=(\\d+)( warn)?"); - - private static Integer[] getLinesWithWarnAndCheckComments(String aFileName, - final int tabWidth) - throws IOException { - List result = new ArrayList<>(); - try (BufferedReader br = new BufferedReader(new InputStreamReader( - new FileInputStream(aFileName), StandardCharsets.UTF_8))) { - int lineNumber = 1; - for (String line = br.readLine(); line != null; line = br.readLine()) { - Matcher match = LINE_WITH_COMMENT_REGEX.matcher(line); - if (match.matches()) { - final String comment = match.group(1); - final int indentInComment = getIndentFromComment(comment); - final int actualIndent = getLineStart(line, tabWidth); - - if (actualIndent != indentInComment) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has incorrect indentation in comment." - + "Line %2$d: comment:%3$d, actual:%4$d.", - aFileName, - lineNumber, - indentInComment, - actualIndent)); - } - - if (isWarnComment(comment)) { - result.add(lineNumber); - } - - if (!isCommentConsistent(comment)) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has inconsistent comment on line %2$d", - aFileName, - lineNumber)); - } - } - else if (NONEMPTY_LINE_REGEX.matcher(line).matches()) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has no indentation comment or its format " - + "malformed. Error on line: %2$d", - aFileName, - lineNumber)); - } - lineNumber++; - } - } - return result.toArray(new Integer[result.size()]); - } - - private static int getIndentFromComment(String comment) { - final Matcher match = GET_INDENT_FROM_COMMENT_REGEX.matcher(comment); - match.matches(); - return Integer.parseInt(match.group(1)); - } - - private static boolean isWarnComment(String comment) { - return comment.endsWith(" warn"); - } - - private static boolean isCommentConsistent(String comment) { - final int indentInComment = getIndentFromComment(comment); - final boolean isWarnComment = isWarnComment(comment); - - Matcher match = MULTILEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final String[] levels = match.group(1).split(","); - final String indentInCommentStr = String.valueOf(indentInComment); - final boolean containsActualLevel = - Arrays.asList(levels).contains(indentInCommentStr); - - return containsActualLevel && !isWarnComment - || !containsActualLevel && isWarnComment; - } - - match = SINGLELEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final int expectedLevel = Integer.parseInt(match.group(1)); - - return expectedLevel == indentInComment && !isWarnComment - || expectedLevel != indentInComment && isWarnComment; - } - - match = NONSTRICT_LEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final int expectedMinimalIndent = Integer.parseInt(match.group(1)); - - return indentInComment >= expectedMinimalIndent && !isWarnComment - || indentInComment < expectedMinimalIndent && isWarnComment; - } - - throw new IllegalStateException("Comments are not consistent"); - } - - private static int getLineStart(String line, final int tabWidth) { - for (int index = 0; index < line.length(); ++index) { - if (!Character.isWhitespace(line.charAt(index))) { - return CommonUtils.lengthExpandedTabs(line, index, tabWidth); - } - } - return 0; - } - - private void verifyWarns(Configuration config, String filePath, - String[] expected, int warnCountCorrection) - throws Exception { - final int tabWidth = Integer.parseInt(config.getAttribute("tabWidth")); - Integer[] linesWithWarn = - getLinesWithWarnAndCheckComments(filePath, tabWidth); - assertEquals("Expected warning count in UT does not match warn" - + " comment count in input file", linesWithWarn.length - + warnCountCorrection, - expected.length); - verify(config, filePath, expected); - } - - private void verifyWarns(Configuration config, String filePath, - String... expected) - throws Exception { - verifyWarns(config, filePath, expected, 0); - } - - @Test - public void testGetRequiredTokens() { - IndentationCheck checkObj = new IndentationCheck(); - final HandlerFactory handlerFactory = new HandlerFactory(); - int[] expected = handlerFactory.getHandledTypes(); - assertArrayEquals(expected, checkObj.getRequiredTokens()); - } - - @Test - public void testGetAcceptableTokens() { - IndentationCheck checkObj = new IndentationCheck(); - final HandlerFactory handlerFactory = new HandlerFactory(); - int[] expected = handlerFactory.getHandledTypes(); - assertArrayEquals(expected, checkObj.getAcceptableTokens()); - } - - @Test - public void testThrowsIndentProperty() { - IndentationCheck indentationCheck = new IndentationCheck(); - - indentationCheck.setThrowsIndent(1); - - assertEquals(1, indentationCheck.getThrowsIndent()); - } - - @Test - public void forbidCStyle() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "true"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = { - "20: " + getCheckMessage(MSG_ERROR, "int", 29, 12), - "21: " + getCheckMessage(MSG_ERROR, "int", 29, 12), - }; - verifyWarns(checkConfig, getPath("indentation/InputMethodCStyle.java"), expected); - } - - @Test - public void testZeroCaseLevel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "0"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputZeroCaseLevel.java"), expected); - } - - @Test - public void testAndroidStyle() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = { - "42: " + getCheckMessage(MSG_ERROR, "extends", 3, 8), - "44: " + getCheckMessage(MSG_ERROR, "member def type", 3, 4), - "47: " + getCheckMessage(MSG_ERROR, "foo", 8, 12), - "50: " + getCheckMessage(MSG_ERROR, "int", 8, 12), - "53: " + getCheckMessage(MSG_ERROR, "true", 13, 16), - "56: " + getCheckMessage(MSG_ERROR, "+", 16, 20), - "57: " + getCheckMessage(MSG_ERROR, "if", 8, 12), - "60: " + getCheckMessage(MSG_ERROR, "if rcurly", 11, 12), - "62: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 7, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputAndroidStyle.java"), expected); - } - - @Test - public void testMethodCallLineWrap() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "51: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 18, 20), - "52: " + getCheckMessage(MSG_ERROR, "method call rparen", 14, 16), - }; - verifyWarns(checkConfig, getPath("indentation/InputMethodCallLineWrap.java"), expected); - } - - @Test - public void testDifficultAnnotations() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "40: " + getCheckMessage(MSG_ERROR, "@", 0, 4), - "41: " + getCheckMessage(MSG_ERROR, "@", 0, 4), - "50: " + getCheckMessage(MSG_ERROR, "@", 6, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputDifficultAnnotations.java"), expected); - } - - @Test - public void testAnonClassesFromGuava() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/FromGuava2.java"), expected); - } - - @Test - public void testAnnotations() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/FromGuava.java"), expected); - } - - @Test - public void testCorrectIfAndParameters() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/IndentationCorrectIfAndParameterInput.java"), expected); - } - - @Test - public void testAnonymousClasses() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputAnonymousClasses.java"), expected); - } - - @Test - public void testArrays() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "2"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputArrays.java"), expected); - } - - @Test - public void testLabels() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputLabels.java"), expected); - } - - @Test - public void testClassesAndMethods() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputClassesMethods.java"), expected); - } - - @Test - public void testMembers() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "22: " + getCheckMessage(MSG_ERROR, "=", 5, 6), - "57: " + getCheckMessage(MSG_ERROR, "class def rcurly", 3, 2), - }; - - verifyWarns(checkConfig, getPath("indentation/InputMembers.java"), expected); - } - - @Test - public void testInvalidLabel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "24: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 10, "8, 12"), - "33: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 2, "4, 8"), - "36: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 18, "8, 12"), - "37: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 18, 8), - "39: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 6, "8, 12"), - "41: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 6, "8, 12"), - }; - verifyWarns(checkConfig, getPath("indentation/InputInvalidLabelIndent.java"), expected); - } - - @Test - public void testInvalidLabelWithWhileLoop() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "18: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 9, "4, 8"), - "19: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 9, "8, 12"), - "19: " + getCheckMessage(MSG_ERROR_MULTI, "while", 9, "8, 12"), - }; - verifyWarns(checkConfig, getPath("indentation/InputInvalidLabelWithWhileLoopIndent.java"), - expected); - } - - @Test - public void testValidLabel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputValidLabelIndent.java"), expected); - } - - @Test - public void testValidIfWithChecker() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidIfIndent.java"); - final String[] expected = { - "231: " + getCheckMessage(MSG_ERROR, "(", 8, 12), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidDotWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidDotIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidMethodWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidMethodIndent.java"); - final String[] expected = { - "129: " + getCheckMessage(MSG_ERROR, "void", 4, 8), - "130: " + getCheckMessage(MSG_ERROR, "method5", 4, 8), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidMethodWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidMethodIndent.java"); - final String[] expected = { - "23: " + getCheckMessage(MSG_ERROR, "ctor def rcurly", 6, 4), - "26: " + getCheckMessage(MSG_ERROR, "ctor def modifier", 6, 4), - "27: " + getCheckMessage(MSG_ERROR, "ctor def lcurly", 2, 4), - "28: " + getCheckMessage(MSG_ERROR, "ctor def rcurly", 6, 4), - "31: " + getCheckMessage(MSG_ERROR, "method def modifier", 2, 4), - "32: " + getCheckMessage(MSG_ERROR, "method def rcurly", 6, 4), - "69: " + getCheckMessage(MSG_ERROR, "method def modifier", 5, 4), - "70: " + getCheckMessage(MSG_ERROR, "final", 5, 9), - "71: " + getCheckMessage(MSG_ERROR, "void", 5, 9), - "72: " + getCheckMessage(MSG_ERROR, "method5", 4, 9), - "80: " + getCheckMessage(MSG_ERROR, "method def modifier", 3, 4), - "81: " + getCheckMessage(MSG_ERROR, "final", 3, 7), - "82: " + getCheckMessage(MSG_ERROR, "void", 3, 7), - "83: " + getCheckMessage(MSG_ERROR, "method6", 5, 7), - "93: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 4, 8), - "93: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 4, 8), - "98: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - "98: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 6, 8), - "99: " + getCheckMessage(MSG_ERROR, "if", 6, 8), - "100: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "100: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "101: " + getCheckMessage(MSG_ERROR, "if rcurly", 6, 8), - "104: " + getCheckMessage(MSG_ERROR, "Arrays", 10, 12), - "113: " + getCheckMessage(MSG_ERROR, "+", 10, 12), - "113: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "122: " + getCheckMessage(MSG_ERROR, "new", 10, 12), - "126: " + getCheckMessage(MSG_ERROR, "new", 10, 12), - "127: " + getCheckMessage(MSG_ERROR, ")", 6, 8), - "131: " + getCheckMessage(MSG_ERROR, "method call rparen", 6, 8), - "145: " + getCheckMessage(MSG_ERROR, "6", 10, 12), - "145: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "148: " + getCheckMessage(MSG_ERROR, "6", 10, 12), - "148: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "158: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 6, 12), - "170: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 4, 8), - "175: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 4, 8), - "179: " + getCheckMessage(MSG_ERROR, "int", 0, 8), - "180: " + getCheckMessage(MSG_ERROR, "method9", 4, 8), - "190: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 12, 8), - }; - verifyWarns(checkConfig, fname, expected, 6); - } - - @Test - public void testInvalidSwitchWithChecker() - throws Exception { - - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidSwitchIndent.java"); - final String[] expected = { - "30: " + getCheckMessage(MSG_ERROR, "switch", 6, 8), - "32: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 12), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 14, 16), - "37: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "39: " + getCheckMessage(MSG_CHILD_ERROR, "case", 14, 12), - "40: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 12), - "43: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 12), - "44: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "44: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 14, 16), - "45: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "53: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "53: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 14, 16), - "54: " + getCheckMessage(MSG_CHILD_ERROR, "block", 18, 16), - "55: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), - "59: " + getCheckMessage(MSG_ERROR, "block lcurly", 10, 12), - "62: " + getCheckMessage(MSG_ERROR, "block rcurly", 14, 12), - "66: " + getCheckMessage(MSG_ERROR, "block lcurly", 14, 12), - "69: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), - "76: " + getCheckMessage(MSG_CHILD_ERROR, "case", 14, 16), - "81: " + getCheckMessage(MSG_CHILD_ERROR, "case", 14, 16), - "89: " + getCheckMessage(MSG_ERROR, "switch rcurly", 6, 8), - "92: " + getCheckMessage(MSG_ERROR, "switch lcurly", 6, 8), - "93: " + getCheckMessage(MSG_ERROR, "switch rcurly", 10, 8), - "95: " + getCheckMessage(MSG_ERROR, "switch lcurly", 10, 8), - "96: " + getCheckMessage(MSG_ERROR, "switch rcurly", 6, 8), - }; - verifyWarns(checkConfig, fname, expected, 3); - } - - @Test - public void testValidSwitchWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidSwitchIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidArrayInitDefaultIndentWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidArrayInitDefaultIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidArrayInitWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "8"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidArrayInitIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidArrayInitWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidArrayInitIndent.java"); - final String[] expected = { - "21: " + getCheckMessage(MSG_ERROR, "member def type", 2, 4), - "22: " + getCheckMessage(MSG_ERROR, "member def type", 6, 4), - "24: " + getCheckMessage(MSG_ERROR, "member def type", 2, 4), - "28: " + getCheckMessage(MSG_ERROR, "member def type", 6, 4), - "29: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 8, 10), - "30: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 4, "6, 10"), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 9, 8), - "34: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 7, 8), - "35: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 9, 8), - "40: " + getCheckMessage(MSG_ERROR, "array initialization lcurly", 2, 4), - "44: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "4, 8"), - "48: " + getCheckMessage(MSG_ERROR, "array initialization lcurly", 2, 4), - "52: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "array initialization", 20, "8, 31, 33"), - "53: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "array initialization", 4, "8, 31, 33"), - "58: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 6, 8), - "63: " + getCheckMessage(MSG_ERROR, "member def type", 2, 4), - "65: " + getCheckMessage(MSG_ERROR, "member def type", 6, 4), - "66: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 2, "6, 10"), - "69: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 6, 8), - "76: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), - "89: " + getCheckMessage(MSG_ERROR, "1", 8, 12), - "89: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 8, 12), - "100: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), - "101: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 14, 12), - "104: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), - "105: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 14, 12), - "106: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "8, 12"), - "109: " + getCheckMessage(MSG_ERROR, "array initialization lcurly", 6, 8), - "110: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 14, 12), - "111: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), - "112: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "8, 12"), - }; - - //Test input for this test case is not checked due to issue #693. - verify(checkConfig, fname, expected); - } - - @Test - public void testValidTryWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidTryIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidTryWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidTryIndent.java"); - final String[] expected = { - "25: " + getCheckMessage(MSG_ERROR, "try", 9, 8), - "26: " + getCheckMessage(MSG_ERROR, "try rcurly", 7, 8), - "28: " + getCheckMessage(MSG_ERROR, "catch rcurly", 7, 8), - "30: " + getCheckMessage(MSG_ERROR, "try", 4, 8), - "31: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), - "31: " + getCheckMessage(MSG_CHILD_ERROR, "try", 8, 12), - "32: " + getCheckMessage(MSG_ERROR, "try rcurly", 4, 8), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "finally", 8, 12), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), - "38: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 8, 12), - "38: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), - "43: " + getCheckMessage(MSG_ERROR, "try rcurly", 10, 8), - "45: " + getCheckMessage(MSG_ERROR, "catch rcurly", 6, 8), - "52: " + getCheckMessage(MSG_ERROR, "catch rcurly", 5, 8), - "59: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 10, 12), - "59: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "60: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 14, 12), - "61: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 10, 12), - "61: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "63: " + getCheckMessage(MSG_ERROR, "catch", 6, 8), - "70: " + getCheckMessage(MSG_ERROR, "try lcurly", 10, 8), - "72: " + getCheckMessage(MSG_ERROR, "try rcurly", 10, 8), - "74: " + getCheckMessage(MSG_ERROR, "catch lcurly", 6, 8), - "77: " + getCheckMessage(MSG_ERROR, "catch rcurly", 10, 8), - "80: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 10, 12), - "80: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - }; - verifyWarns(checkConfig, fname, expected, 6); - } - - @Test - public void testInvalidClassDefWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidClassDefIndent.java"); - final String[] expected = { - "22: " + getCheckMessage(MSG_ERROR, "class def modifier", 2, 0), - "28: " + getCheckMessage(MSG_ERROR, "class def lcurly", 2, 0), - "31: " + getCheckMessage(MSG_ERROR, "class def rcurly", 2, 0), - "34: " + getCheckMessage(MSG_ERROR, "class def ident", 2, 0), - "38: " + getCheckMessage(MSG_ERROR, "class def rcurly", 2, 0), - "43: " + getCheckMessage(MSG_ERROR, "extends", 2, 4), - "44: " + getCheckMessage(MSG_ERROR, "implements", 2, 4), - "50: " + getCheckMessage(MSG_ERROR, "extends", 2, 4), - "58: " + getCheckMessage(MSG_ERROR, "implements", 2, 4), - "59: " + getCheckMessage(MSG_ERROR, "java", 2, 4), - "64: " + getCheckMessage(MSG_ERROR, "class def modifier", 2, 0), - "65: " + getCheckMessage(MSG_ERROR, "class def lcurly", 2, 0), - "73: " + getCheckMessage(MSG_ERROR, "class def rcurly", 2, 0), - "77: " + getCheckMessage(MSG_ERROR, "extends", 2, 4), - "86: " + getCheckMessage(MSG_ERROR, "class def ident", 2, 4), - "88: " + getCheckMessage(MSG_ERROR, "class def ident", 6, 4), - "91: " + getCheckMessage(MSG_ERROR, "class def ident", 2, 4), - "95: " + getCheckMessage(MSG_ERROR, "member def modifier", 6, 8), - "101: " + getCheckMessage(MSG_ERROR, "int", 10, 12), - "106: " + getCheckMessage(MSG_ERROR, "member def modifier", 6, 8), - "111: " + getCheckMessage(MSG_ERROR, "class def rcurly", 6, 4), - "113: " + getCheckMessage(MSG_ERROR, "class def ident", 6, 4), - "119: " + getCheckMessage(MSG_ERROR, "class def ident", 6, 8), - "122: " + getCheckMessage(MSG_ERROR, "class def ident", 10, 8), - "124: " + getCheckMessage(MSG_ERROR, "class def rcurly", 10, 8), - "127: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "132: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 10, 8), - "133: " + getCheckMessage(MSG_ERROR_MULTI, "object def lcurly", 8, "10, 14"), - "137: " + getCheckMessage(MSG_ERROR_MULTI, "object def rcurly", 8, "10, 14"), - "141: " + getCheckMessage(MSG_ERROR_MULTI, "object def lcurly", 6, "8, 12"), - "142: " + getCheckMessage(MSG_ERROR, "method def modifier", 12, 10), - "144: " + getCheckMessage(MSG_ERROR, "method def rcurly", 12, 10), - "145: " + getCheckMessage(MSG_ERROR_MULTI, "object def rcurly", 6, "8, 12"), - "150: " + getCheckMessage(MSG_ERROR, "method def modifier", 10, 12), - "152: " + getCheckMessage(MSG_ERROR, "method def rcurly", 10, 12), - "188: " + getCheckMessage(MSG_ERROR, "class", 0, 4), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidBlockWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidBlockIndent.java"); - final String[] expected = { - "26: " + getCheckMessage(MSG_ERROR, "block lcurly", 7, 8), - "27: " + getCheckMessage(MSG_ERROR, "block lcurly", 9, 8), - "29: " + getCheckMessage(MSG_ERROR, "block lcurly", 9, 8), - "30: " + getCheckMessage(MSG_ERROR, "block rcurly", 7, 8), - "32: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), - "34: " + getCheckMessage(MSG_ERROR, "block rcurly", 6, 8), - "35: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), - "38: " + getCheckMessage(MSG_ERROR, "block lcurly", 9, 8), - "39: " + getCheckMessage(MSG_CHILD_ERROR, "block", 13, 12), - "39: " + getCheckMessage(MSG_ERROR, "member def type", 13, 12), - "41: " + getCheckMessage(MSG_CHILD_ERROR, "block", 13, 12), - "42: " + getCheckMessage(MSG_ERROR, "block rcurly", 9, 8), - "45: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), - "46: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), - "46: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "48: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), - "49: " + getCheckMessage(MSG_ERROR, "block rcurly", 6, 8), - "52: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), - "55: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), - "55: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "59: " + getCheckMessage(MSG_ERROR, "block lcurly", 10, 12), - "63: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), - "68: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), - "70: " + getCheckMessage(MSG_ERROR, "block lcurly", 10, 12), - "71: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "71: " + getCheckMessage(MSG_ERROR, "member def type", 14, 16), - "86: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), - "95: " + getCheckMessage(MSG_ERROR, "static initialization", 2, 4), - "96: " + getCheckMessage(MSG_ERROR, "static initialization", 6, 4), - "100: " + getCheckMessage(MSG_ERROR, "member def type", 7, 8), - "100: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 7, 8), - "103: " + getCheckMessage(MSG_ERROR, "static initialization", 6, 4), - "105: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 2, 4), - "107: " + getCheckMessage(MSG_ERROR, "static initialization", 2, 4), - "109: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 6, 4), - "111: " + getCheckMessage(MSG_ERROR, "static initialization", 2, 4), - "113: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - "113: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 6, 8), - "116: " + getCheckMessage(MSG_ERROR, "static initialization lcurly", 2, 4), - "117: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - "117: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 6, 8), - "118: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 6, 4), - "123: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - "123: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 6, 8), - "128: " + getCheckMessage(MSG_ERROR, "member def type", 4, 8), - "128: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 4, 8), - "129: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 2, 4), - "134: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 6, 4), - "137: " + getCheckMessage(MSG_ERROR, "block lcurly", 2, 4), - "138: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 4), - "141: " + getCheckMessage(MSG_ERROR, "block lcurly", 2, 4), - "143: " + getCheckMessage(MSG_ERROR, "block rcurly", 6, 4), - "145: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 4), - "147: " + getCheckMessage(MSG_ERROR, "block rcurly", 2, 4), - "150: " + getCheckMessage(MSG_CHILD_ERROR, "block", 6, 8), - "150: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - }; - verifyWarns(checkConfig, fname, expected, 10); - } - - @Test - public void testInvalidIfWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidIfIndent.java"); - final String[] expected = { - "55: " + getCheckMessage(MSG_ERROR, "if", 1, 8), - "60: " + getCheckMessage(MSG_ERROR, "if", 9, 8), - "61: " + getCheckMessage(MSG_ERROR, "if lcurly", 9, 8), - "62: " + getCheckMessage(MSG_ERROR, "if rcurly", 7, 8), - "64: " + getCheckMessage(MSG_ERROR, "if", 6, 8), - "65: " + getCheckMessage(MSG_ERROR, "if lcurly", 5, 8), - "66: " + getCheckMessage(MSG_ERROR, "if rcurly", 5, 8), - "70: " + getCheckMessage(MSG_ERROR, "if rcurly", 10, 8), - "71: " + getCheckMessage(MSG_ERROR, "else rcurly", 7, 8), - "74: " + getCheckMessage(MSG_ERROR, "if", 9, 8), - - "75: " + getCheckMessage(MSG_ERROR, "if lcurly", 7, 8), - "77: " + getCheckMessage(MSG_ERROR, "else", 9, 8), - "79: " + getCheckMessage(MSG_ERROR, "else rcurly", 9, 8), - "82: " + getCheckMessage(MSG_ERROR, "if", 10, 8), - "83: " + getCheckMessage(MSG_ERROR, "if rcurly", 7, 8), - "84: " + getCheckMessage(MSG_ERROR, "else", 9, 8), - "85: " + getCheckMessage(MSG_ERROR, "else lcurly", 7, 8), - "86: " + getCheckMessage(MSG_ERROR, "else rcurly", 9, 8), - - "90: " + getCheckMessage(MSG_ERROR, "if", 9, 8), - "91: " + getCheckMessage(MSG_ERROR, "if lcurly", 9, 8), - "92: " + getCheckMessage(MSG_ERROR, "if rcurly", 9, 8), - "93: " + getCheckMessage(MSG_ERROR, "else lcurly", 7, 8), - "94: " + getCheckMessage(MSG_ERROR, "else rcurly", 10, 8), - "97: " + getCheckMessage(MSG_ERROR, "if", 6, 8), - "98: " + getCheckMessage(MSG_ERROR, "if lcurly", 10, 8), - "99: " + getCheckMessage(MSG_ERROR, "if rcurly", 10, 8), - "100: " + getCheckMessage(MSG_ERROR, "else rcurly", 7, 8), - "103: " + getCheckMessage(MSG_ERROR, "if", 5, 8), - "104: " + getCheckMessage(MSG_ERROR, "if rcurly", 11, 8), - "105: " + getCheckMessage(MSG_ERROR, "else", 5, 8), - "106: " + getCheckMessage(MSG_ERROR, "else rcurly", 11, 8), - - "126: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), - "131: " + getCheckMessage(MSG_ERROR, "if lcurly", 10, 8), - "132: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "132: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "137: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), - "138: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "140: " + getCheckMessage(MSG_CHILD_ERROR, "else", 10, 12), - "140: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "141: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), - - "148: " + getCheckMessage(MSG_CHILD_ERROR, "if", 16, 12), - "149: " + getCheckMessage(MSG_ERROR, "if rcurly", 9, 8), - "152: " + getCheckMessage(MSG_CHILD_ERROR, "else", 16, 12), - "158: " + getCheckMessage(MSG_CHILD_ERROR, "if", 0, 12), - "158: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 0, 12), - "162: " + getCheckMessage(MSG_CHILD_ERROR, "else", 40, 12), - "169: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), - - "172: " + getCheckMessage(MSG_CHILD_ERROR, "else", 14, 12), - "178: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "178: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "180: " + getCheckMessage(MSG_CHILD_ERROR, "else", 10, 12), - "180: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "184: " + getCheckMessage(MSG_ERROR, "if", 10, 8), - "185: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), - "186: " + getCheckMessage(MSG_ERROR, "if rcurly", 10, 8), - "187: " + getCheckMessage(MSG_ERROR, "else", 10, 8), - - "188: " + getCheckMessage(MSG_CHILD_ERROR, "else", 14, 12), - "189: " + getCheckMessage(MSG_ERROR, "else rcurly", 10, 8), - "192: " + getCheckMessage(MSG_ERROR, "&&", 9, 12), - "192: " + getCheckMessage(MSG_CHILD_ERROR, "if", 9, 12), - "193: " + getCheckMessage(MSG_ERROR, "&&", 11, 12), - "193: " + getCheckMessage(MSG_CHILD_ERROR, "if", 11, 12), - "197: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "200: " + getCheckMessage(MSG_ERROR, "if rcurly", 7, 8), - "207: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "207: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "209: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "209: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - - "225: " + getCheckMessage(MSG_ERROR, "if", 10, 12), - "229: " + getCheckMessage(MSG_CHILD_ERROR, "if", 18, 20), - "229: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 18, 20), - "233: " + getCheckMessage(MSG_ERROR, "if rcurly", 40, 8), - "240: " + getCheckMessage(MSG_ERROR, "if rparen", 10, 8), - "245: " + getCheckMessage(MSG_ERROR, "if rparen", 6, 8), - "251: " + getCheckMessage(MSG_ERROR, "(", 6, 12), - "251: " + getCheckMessage(MSG_ERROR, "if lparen", 6, 8), - "253: " + getCheckMessage(MSG_ERROR, "if rparen", 6, 8), - }; - verifyWarns(checkConfig, fname, expected, 11); - } - - @Test - public void testInvalidWhileWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidWhileIndent.java"); - final String[] expected = { - "25: " + getCheckMessage(MSG_ERROR, "while", 9, 8), - "26: " + getCheckMessage(MSG_ERROR, "while rcurly", 7, 8), - "28: " + getCheckMessage(MSG_ERROR, "while", 7, 8), - "29: " + getCheckMessage(MSG_ERROR, "while lcurly", 9, 8), - "30: " + getCheckMessage(MSG_ERROR, "while rcurly", 9, 8), - - "32: " + getCheckMessage(MSG_ERROR, "while", 9, 8), - "33: " + getCheckMessage(MSG_ERROR, "while lcurly", 6, 8), - "34: " + getCheckMessage(MSG_CHILD_ERROR, "while", 14, 12), - "35: " + getCheckMessage(MSG_ERROR, "while rcurly", 6, 8), - - "37: " + getCheckMessage(MSG_ERROR, "while", 10, 8), - "39: " + getCheckMessage(MSG_ERROR, "while rcurly", 10, 8), - "41: " + getCheckMessage(MSG_ERROR, "while", 10, 8), - "44: " + getCheckMessage(MSG_ERROR, "while rcurly", 10, 8), - - "46: " + getCheckMessage(MSG_ERROR, "while", 6, 8), - "47: " + getCheckMessage(MSG_ERROR, "while lcurly", 10, 8), - "50: " + getCheckMessage(MSG_ERROR, "while rcurly", 6, 8), - "53: " + getCheckMessage(MSG_ERROR, "if", 14, 12), - "54: " + getCheckMessage(MSG_CHILD_ERROR, "if", 18, 16), - "55: " + getCheckMessage(MSG_ERROR, "if rcurly", 14, 12), - "56: " + getCheckMessage(MSG_CHILD_ERROR, "while", 14, 12), - "57: " + getCheckMessage(MSG_ERROR, "while rcurly", 10, 8), - - "60: " + getCheckMessage(MSG_CHILD_ERROR, "while", 10, 12), - "66: " + getCheckMessage(MSG_CHILD_ERROR, "while", 10, 12), - "71: " + getCheckMessage(MSG_CHILD_ERROR, "while", 10, 12), - "78: " + getCheckMessage(MSG_ERROR, "while rparen", 5, 8), - "85: " + getCheckMessage(MSG_ERROR, "while rparen", 10, 8), - "92: " + getCheckMessage(MSG_ERROR, "while rparen", 10, 8), - "99: " + getCheckMessage(MSG_CHILD_ERROR, "while", 8, 12), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidInvalidAnonymousClass() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidAnonymousClassIndent.java"); - final String[] expected = { - "28: " + getCheckMessage(MSG_ERROR_MULTI, "method def rcurly", 17, "12, 16"), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidForWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidForIndent.java"); - final String[] expected = { - "26: " + getCheckMessage(MSG_ERROR, "for", 6, 8), - "27: " + getCheckMessage(MSG_ERROR, "for rcurly", 10, 8), - "29: " + getCheckMessage(MSG_ERROR, "for", 9, 8), - "30: " + getCheckMessage(MSG_ERROR, "for lcurly", 6, 8), - "31: " + getCheckMessage(MSG_ERROR, "for rcurly", 6, 8), - "35: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "35: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - - "36: " + getCheckMessage(MSG_ERROR, "for rcurly", 10, 8), - "39: " + getCheckMessage(MSG_ERROR, "for lcurly", 10, 8), - "40: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "40: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "48: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "48: " + getCheckMessage(MSG_ERROR, "i", 10, 12), - "54: " + getCheckMessage(MSG_ERROR, "for", 7, 8), - - "55: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "55: " + getCheckMessage(MSG_ERROR, "int", 10, 11), - "55: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "64: " + getCheckMessage(MSG_CHILD_ERROR, "for", 7, 12), - "64: " + getCheckMessage(MSG_ERROR, "i", 7, 12), - - "69: " + getCheckMessage(MSG_ERROR, "for", 6, 8), - "70: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "71: " + getCheckMessage(MSG_CHILD_ERROR, "for", 14, 16), - "72: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "77: " + getCheckMessage(MSG_ERROR, "for rcurly", 39, 8), - "81: " + getCheckMessage(MSG_ERROR, "for rparen", 12, 8), - }; - verifyWarns(checkConfig, fname, expected, 6); - } - - @Test - public void testValidForWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidForIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidDoWhileWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidDoWhileIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidBlockWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidBlockIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidWhileWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidWhileIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidClassDefWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidClassDefIndent.java"); - final String[] expected = { - "49: " + getCheckMessage(MSG_ERROR, "class", 0, 4), - "71: " + getCheckMessage(MSG_ERROR, "int", 8, 12), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidInterfaceDefWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidInterfaceDefIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidCommaWithChecker() - throws Exception { - - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidCommaIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testTabs() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "29: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 9, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputUseTabs.java"), expected); - } - - @Test - public void testIndentationLevel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "2"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "29: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 5, 4), - }; - verifyWarns(checkConfig, getPath("indentation/InputUseTwoSpaces.java"), expected); - } - - @Test - public void testThrowsIndentationLevel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InvalidInputThrowsIndent.java"), expected); - } - - @Test - public void testCaseLevel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "0"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "27: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputCaseLevel.java"), expected); - } - - @Test - public void testBraceAdjustment() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "2"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "28: " + getCheckMessage(MSG_ERROR, "if rcurly", 8, 10), - }; - verifyWarns(checkConfig, getPath("indentation/InputBraceAdjustment.java"), expected); - } - - @Test - public void testInvalidAssignWithChecker() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "22: " + getCheckMessage(MSG_ERROR, "getLineNo", 10, 12), - "24: " + getCheckMessage(MSG_ERROR, "getLine", 10, 12), - "28: " + getCheckMessage(MSG_ERROR, "=", 9, 12), - "29: " + getCheckMessage(MSG_ERROR, "1", 10, 12), - }; - verifyWarns(checkConfig, getPath("indentation/InputInvalidAssignIndent.java"), expected); - } - - @Test - public void testInvalidImportIndent() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("basicOffset", "8"); - checkConfig.addAttribute("tabWidth", "4"); - final String[] expected = { - "4: " + getCheckMessage(MSG_CHILD_ERROR, "import", 2, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputInvalidImportIndent.java"), expected); - } - - @Test - public void testValidAssignWithChecker() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputValidAssignIndent.java"), expected); - } - - @Test - public void test15Extensions() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/Input15Extensions.java"), expected); - } - - @Test - public void testTryResources() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputValidTryResourcesIndent.java"), - expected); - } - - @Test - public void testSwitchCustom() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputSwitchCustom.java"), - expected); - } - - @Test - public void testSynchronizedStatement() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputSynchronizedStatement.java"), expected); - } - - @Test - public void testSynchronizedMethod() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputSynchronizedMethod.java"), expected); - } - - @Test - public void testAnonymousClassInMethod() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("tabWidth", "8"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "2"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - checkConfig.addAttribute("arrayInitIndent", "2"); - final String[] expected = { - "19: " + getCheckMessage(MSG_ERROR, "method def modifier", 8, 2), - "20: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 16, 4), - "21: " + getCheckMessage(MSG_ERROR_MULTI, "method def modifier", 24, "18, 20, 22"), - "23: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "method def", 32, "20, 22, 24"), - "24: " + getCheckMessage(MSG_ERROR_MULTI, "method def rcurly", 24, "18, 20, 22"), - "26: " + getCheckMessage(MSG_ERROR, "method def rcurly", 8, 2), - }; - verifyWarns(checkConfig, getPath("indentation/InputAnonymousClassInMethod.java"), expected); - } - - @Test - public void testAnnotationDefinition() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("tabWidth", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputAnnotationDefinition.java"), expected); - } - - @Test - public void testPackageDeclaration() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("tabWidth", "4"); - final String[] expected = { - "1: " + getCheckMessage(MSG_ERROR, "package def", 1, 0), - }; - verifyWarns(checkConfig, getPath("indentation/InputPackageDeclaration.java"), expected); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/old/IndentationCheckTest.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/old/IndentationCheckTest.java deleted file mode 100755 index cdea0f1..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/old/IndentationCheckTest.java +++ /dev/null @@ -1,1567 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2015 the original author or authors. -// -// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// - -package com.puppycrawl.tools.checkstyle.checks.indentation; - -import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_CHILD_ERROR; -import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_CHILD_ERROR_MULTI; -import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_ERROR; -import static com.puppycrawl.tools.checkstyle.checks.indentation.AbstractExpressionHandler.MSG_ERROR_MULTI; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.lang3.ArrayUtils; -import org.junit.Test; - -import com.puppycrawl.tools.checkstyle.BaseCheckTestSupport; -import com.puppycrawl.tools.checkstyle.DefaultConfiguration; -import com.puppycrawl.tools.checkstyle.api.Configuration; -import com.puppycrawl.tools.checkstyle.utils.CommonUtils; - -/** - * - * @author jrichard - */ -public class IndentationCheckTest extends BaseCheckTestSupport { - private static final Pattern NONEMPTY_LINE_REGEX = - Pattern.compile(".*?\\S+.*?"); - - private static final Pattern LINE_WITH_COMMENT_REGEX = - Pattern.compile(".*?\\S+.*?(//indent:(\\d+) exp:((>=\\d+)|(\\d+(,\\d+)*?))( warn)?)"); - - private static final Pattern GET_INDENT_FROM_COMMENT_REGEX = - Pattern.compile("//indent:(\\d+).*?"); - - private static final Pattern MULTILEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:(\\d+(,\\d+)+?)( warn)?"); - - private static final Pattern SINGLELEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:(\\d+)( warn)?"); - - private static final Pattern NONSTRICT_LEVEL_COMMENT_REGEX = - Pattern.compile("//indent:\\d+ exp:>=(\\d+)( warn)?"); - - private static Integer[] getLinesWithWarnAndCheckComments(String aFileName, - final int tabWidth) - throws IOException { - List result = new ArrayList<>(); - try (BufferedReader br = new BufferedReader(new FileReader(aFileName))) { - int lineNumber = 1; - for (String line = br.readLine(); line != null; line = br.readLine()) { - Matcher match = LINE_WITH_COMMENT_REGEX.matcher(line); - if (match.matches()) { - final String comment = match.group(1); - final int indentInComment = getIndentFromComment(comment); - final int actualIndent = getLineStart(line, tabWidth); - - if (actualIndent != indentInComment) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has incorrect indentation in comment." - + "Line %2$d: comment:%3$d, actual:%4$d.", - aFileName, - lineNumber, - indentInComment, - actualIndent)); - } - - if (isWarnComment(comment)) { - result.add(lineNumber); - } - - if (!isCommentConsistent(comment)) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has inconsistent comment on line %2$d", - aFileName, - lineNumber)); - } - } - else if (NONEMPTY_LINE_REGEX.matcher(line).matches()) { - throw new IllegalStateException(String.format( - "File \"%1$s\" has no indentation comment or its format " - + "malformed. Error on line: %2$d", - aFileName, - lineNumber)); - } - lineNumber++; - } - } - return result.toArray(new Integer[result.size()]); - } - - private static int getIndentFromComment(String comment) { - final Matcher match = GET_INDENT_FROM_COMMENT_REGEX.matcher(comment); - match.matches(); - return Integer.parseInt(match.group(1)); - } - - private static boolean isWarnComment(String comment) { - return comment.endsWith(" warn"); - } - - private static boolean isCommentConsistent(String comment) { - final int indentInComment = getIndentFromComment(comment); - final boolean isWarnComment = isWarnComment(comment); - - Matcher match = MULTILEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final String[] levels = match.group(1).split(","); - final String indentInCommentStr = String.valueOf(indentInComment); - final boolean containsActualLevel = - Arrays.asList(levels).contains(indentInCommentStr); - - return containsActualLevel && !isWarnComment - || !containsActualLevel && isWarnComment; - } - - match = SINGLELEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final int expectedLevel = Integer.parseInt(match.group(1)); - - return expectedLevel == indentInComment && !isWarnComment - || expectedLevel != indentInComment && isWarnComment; - } - - match = NONSTRICT_LEVEL_COMMENT_REGEX.matcher(comment); - if (match.matches()) { - final int expectedMinimalIndent = Integer.parseInt(match.group(1)); - - return indentInComment >= expectedMinimalIndent && !isWarnComment - || indentInComment < expectedMinimalIndent && isWarnComment; - } - - throw new IllegalStateException("Comments are not consistent"); - } - - private static int getLineStart(String line, final int tabWidth) { - for (int index = 0; index < line.length(); ++index) { - if (!Character.isWhitespace(line.charAt(index))) { - return CommonUtils.lengthExpandedTabs(line, index, tabWidth); - } - } - return 0; - } - - private void verifyWarns(Configuration config, String filePath, - String[] expected, int warnCountCorrection) - throws Exception { - final int tabWidth = Integer.parseInt(config.getAttribute("tabWidth")); - Integer[] linesWithWarn = - getLinesWithWarnAndCheckComments(filePath, tabWidth); - assertEquals("Expected warning count in UT does not match warn" - + " comment count in input file", linesWithWarn.length - + warnCountCorrection, - expected.length); - verify(config, filePath, expected); - } - - private void verifyWarns(Configuration config, String filePath, - String... expected) - throws Exception { - verifyWarns(config, filePath, expected, 0); - } - - @Test - public void testGetRequiredTokens() { - IndentationCheck checkObj = new IndentationCheck(); - final HandlerFactory handlerFactory = new HandlerFactory(); - int[] expected = handlerFactory.getHandledTypes(); - assertArrayEquals(expected, checkObj.getRequiredTokens()); - } - - @Test - public void testGetAcceptableTokens() { - IndentationCheck checkObj = new IndentationCheck(); - final HandlerFactory handlerFactory = new HandlerFactory(); - int[] expected = handlerFactory.getHandledTypes(); - assertArrayEquals(expected, checkObj.getAcceptableTokens()); - } - - @Test - public void testThrowsIndentProperty() { - IndentationCheck indentationCheck = new IndentationCheck(); - - indentationCheck.setThrowsIndent(1); - - assertEquals(1, indentationCheck.getThrowsIndent()); - } - - @Test - public void forbidCStyle() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "true"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = { - "20: " + getCheckMessage(MSG_ERROR, "int", 29, 12), - "21: " + getCheckMessage(MSG_ERROR, "int", 29, 12), - }; - verifyWarns(checkConfig, getPath("indentation/InputMethodCStyle.java"), expected); - } - - @Test - public void testZeroCaseLevel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "0"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputZeroCaseLevel.java"), expected); - } - - @Test - public void testAndroidStyle() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = { - "42: " + getCheckMessage(MSG_ERROR, "extends", 3, 8), - "44: " + getCheckMessage(MSG_ERROR, "member def type", 3, 4), - "47: " + getCheckMessage(MSG_ERROR, "foo", 8, 12), - "50: " + getCheckMessage(MSG_ERROR, "int", 8, 12), - "53: " + getCheckMessage(MSG_ERROR, "true", 13, 16), - "56: " + getCheckMessage(MSG_ERROR, "+", 16, 20), - "57: " + getCheckMessage(MSG_ERROR, "if", 8, 12), - "60: " + getCheckMessage(MSG_ERROR, "if rcurly", 11, 12), - "62: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 7, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputAndroidStyle.java"), expected); - } - - @Test - public void testMethodCallLineWrap() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "51: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 18, 20), - "52: " + getCheckMessage(MSG_ERROR, "method call rparen", 14, 16), - }; - verifyWarns(checkConfig, getPath("indentation/InputMethodCallLineWrap.java"), expected); - } - - @Test - public void testDifficultAnnotations() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "40: " + getCheckMessage(MSG_ERROR, "@", 0, 4), - "41: " + getCheckMessage(MSG_ERROR, "@", 0, 4), - "50: " + getCheckMessage(MSG_ERROR, "@", 6, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputDifficultAnnotations.java"), expected); - } - - @Test - public void testAnonClassesFromGuava() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/FromGuava2.java"), expected); - } - - @Test - public void testAnnotations() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/FromGuava.java"), expected); - } - - @Test - public void testCorrectIfAndParameters() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/IndentationCorrectIfAndParameterInput.java"), expected); - } - - @Test - public void testAnonymousClasses() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputAnonymousClasses.java"), expected); - } - - @Test - public void testArrays() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "2"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputArrays.java"), expected); - } - - @Test - public void testLabels() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputLabels.java"), expected); - } - - @Test - public void testClassesAndMethods() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputClassesMethods.java"), expected); - } - - @Test - public void testMembers() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "22: " + getCheckMessage(MSG_ERROR, "=", 5, 6), - "57: " + getCheckMessage(MSG_ERROR, "class def rcurly", 3, 2), - }; - - verifyWarns(checkConfig, getPath("indentation/InputMembers.java"), expected); - } - - @Test - public void testInvalidLabel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "24: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 10, "8, 12"), - "33: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 2, "4, 8"), - "36: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 18, "8, 12"), - "37: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 18, 8), - "39: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 6, "8, 12"), - "41: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 6, "8, 12"), - }; - verifyWarns(checkConfig, getPath("indentation/InputInvalidLabelIndent.java"), expected); - } - - @Test - public void testInvalidLabelWithWhileLoop() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "18: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 9, "4, 8"), - "19: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "label", 9, "8, 12"), - "19: " + getCheckMessage(MSG_ERROR_MULTI, "while", 9, "8, 12"), - }; - verifyWarns(checkConfig, getPath("indentation/InputInvalidLabelWithWhileLoopIndent.java"), - expected); - } - - @Test - public void testValidLabel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputValidLabelIndent.java"), expected); - } - - @Test - public void testValidIfWithChecker() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidIfIndent.java"); - final String[] expected = { - "231: " + getCheckMessage(MSG_ERROR, "(", 8, 12), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidDotWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidDotIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidMethodWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidMethodIndent.java"); - final String[] expected = { - "129: " + getCheckMessage(MSG_ERROR, "void", 4, 8), - "130: " + getCheckMessage(MSG_ERROR, "method5", 4, 8), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidMethodWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidMethodIndent.java"); - final String[] expected = { - "23: " + getCheckMessage(MSG_ERROR, "ctor def rcurly", 6, 4), - "26: " + getCheckMessage(MSG_ERROR, "ctor def modifier", 6, 4), - "27: " + getCheckMessage(MSG_ERROR, "ctor def lcurly", 2, 4), - "28: " + getCheckMessage(MSG_ERROR, "ctor def rcurly", 6, 4), - "31: " + getCheckMessage(MSG_ERROR, "method def modifier", 2, 4), - "32: " + getCheckMessage(MSG_ERROR, "method def rcurly", 6, 4), - "69: " + getCheckMessage(MSG_ERROR, "method def modifier", 5, 4), - "70: " + getCheckMessage(MSG_ERROR, "final", 5, 9), - "71: " + getCheckMessage(MSG_ERROR, "void", 5, 9), - "72: " + getCheckMessage(MSG_ERROR, "method5", 4, 9), - "80: " + getCheckMessage(MSG_ERROR, "method def modifier", 3, 4), - "81: " + getCheckMessage(MSG_ERROR, "final", 3, 7), - "82: " + getCheckMessage(MSG_ERROR, "void", 3, 7), - "83: " + getCheckMessage(MSG_ERROR, "method6", 5, 7), - "93: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 4, 8), - "93: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 4, 8), - "98: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - "98: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 6, 8), - "99: " + getCheckMessage(MSG_ERROR, "if", 6, 8), - "100: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "100: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "101: " + getCheckMessage(MSG_ERROR, "if rcurly", 6, 8), - "104: " + getCheckMessage(MSG_ERROR, "Arrays", 10, 12), - "113: " + getCheckMessage(MSG_ERROR, "+", 10, 12), - "113: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "122: " + getCheckMessage(MSG_ERROR, "new", 10, 12), - "126: " + getCheckMessage(MSG_ERROR, "new", 10, 12), - "127: " + getCheckMessage(MSG_ERROR, ")", 6, 8), - "131: " + getCheckMessage(MSG_ERROR, "method call rparen", 6, 8), - "145: " + getCheckMessage(MSG_ERROR, "6", 10, 12), - "145: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "148: " + getCheckMessage(MSG_ERROR, "6", 10, 12), - "148: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "158: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 6, 12), - "170: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 4, 8), - "175: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 4, 8), - "179: " + getCheckMessage(MSG_ERROR, "int", 0, 8), - "180: " + getCheckMessage(MSG_ERROR, "method9", 4, 8), - "190: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 12, 8), - }; - verifyWarns(checkConfig, fname, expected, 6); - } - - @Test - public void testInvalidSwitchWithChecker() - throws Exception { - - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidSwitchIndent.java"); - final String[] expected = { - "30: " + getCheckMessage(MSG_ERROR, "switch", 6, 8), - "32: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 12), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 14, 16), - "37: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "39: " + getCheckMessage(MSG_CHILD_ERROR, "case", 14, 12), - "40: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 12), - "43: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 12), - "44: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "44: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 14, 16), - "45: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "53: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "53: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 14, 16), - "54: " + getCheckMessage(MSG_CHILD_ERROR, "block", 18, 16), - "55: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), - "59: " + getCheckMessage(MSG_ERROR, "block lcurly", 10, 12), - "62: " + getCheckMessage(MSG_ERROR, "block rcurly", 14, 12), - "66: " + getCheckMessage(MSG_ERROR, "block lcurly", 14, 12), - "69: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), - "76: " + getCheckMessage(MSG_CHILD_ERROR, "case", 14, 16), - "81: " + getCheckMessage(MSG_CHILD_ERROR, "case", 14, 16), - "89: " + getCheckMessage(MSG_ERROR, "switch rcurly", 6, 8), - "92: " + getCheckMessage(MSG_ERROR, "switch lcurly", 6, 8), - "93: " + getCheckMessage(MSG_ERROR, "switch rcurly", 10, 8), - "95: " + getCheckMessage(MSG_ERROR, "switch lcurly", 10, 8), - "96: " + getCheckMessage(MSG_ERROR, "switch rcurly", 6, 8), - }; - verifyWarns(checkConfig, fname, expected, 3); - } - - @Test - public void testValidSwitchWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidSwitchIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidArrayInitDefaultIndentWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidArrayInitDefaultIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidArrayInitWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "8"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidArrayInitIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidArrayInitWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidArrayInitIndent.java"); - final String[] expected = { - "21: " + getCheckMessage(MSG_ERROR, "member def type", 2, 4), - "22: " + getCheckMessage(MSG_ERROR, "member def type", 6, 4), - "24: " + getCheckMessage(MSG_ERROR, "member def type", 2, 4), - "28: " + getCheckMessage(MSG_ERROR, "member def type", 6, 4), - "29: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 8, 10), - "30: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 4, "6, 10"), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 9, 8), - "34: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 7, 8), - "35: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 9, 8), - "40: " + getCheckMessage(MSG_ERROR, "array initialization lcurly", 2, 4), - "44: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "4, 8"), - "48: " + getCheckMessage(MSG_ERROR, "array initialization lcurly", 2, 4), - "52: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "array initialization", 20, "8, 31, 33"), - "53: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "array initialization", 4, "8, 31, 33"), - "58: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 6, 8), - "63: " + getCheckMessage(MSG_ERROR, "member def type", 2, 4), - "65: " + getCheckMessage(MSG_ERROR, "member def type", 6, 4), - "66: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 2, "6, 10"), - "69: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 6, 8), - "76: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), - "89: " + getCheckMessage(MSG_ERROR, "1", 8, 12), - "89: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 8, 12), - "100: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), - "101: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 14, 12), - "104: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), - "105: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 14, 12), - "106: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "8, 12"), - "109: " + getCheckMessage(MSG_ERROR, "array initialization lcurly", 6, 8), - "110: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 14, 12), - "111: " + getCheckMessage(MSG_CHILD_ERROR, "array initialization", 10, 12), - "112: " + getCheckMessage(MSG_ERROR_MULTI, "array initialization rcurly", 6, "8, 12"), - }; - - //Test input for this test case is not checked due to issue #693. - verify(checkConfig, fname, expected); - } - - @Test - public void testValidTryWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidTryIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidTryWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidTryIndent.java"); - final String[] expected = { - "25: " + getCheckMessage(MSG_ERROR, "try", 9, 8), - "26: " + getCheckMessage(MSG_ERROR, "try rcurly", 7, 8), - "28: " + getCheckMessage(MSG_ERROR, "catch rcurly", 7, 8), - "30: " + getCheckMessage(MSG_ERROR, "try", 4, 8), - "31: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), - "31: " + getCheckMessage(MSG_CHILD_ERROR, "try", 8, 12), - "32: " + getCheckMessage(MSG_ERROR, "try rcurly", 4, 8), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "finally", 8, 12), - "33: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), - "38: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 8, 12), - "38: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), - "43: " + getCheckMessage(MSG_ERROR, "try rcurly", 10, 8), - "45: " + getCheckMessage(MSG_ERROR, "catch rcurly", 6, 8), - "52: " + getCheckMessage(MSG_ERROR, "catch rcurly", 5, 8), - "59: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 10, 12), - "59: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "60: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 14, 12), - "61: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 10, 12), - "61: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "63: " + getCheckMessage(MSG_ERROR, "catch", 6, 8), - "70: " + getCheckMessage(MSG_ERROR, "try lcurly", 10, 8), - "72: " + getCheckMessage(MSG_ERROR, "try rcurly", 10, 8), - "74: " + getCheckMessage(MSG_ERROR, "catch lcurly", 6, 8), - "77: " + getCheckMessage(MSG_ERROR, "catch rcurly", 10, 8), - "80: " + getCheckMessage(MSG_CHILD_ERROR, "catch", 10, 12), - "80: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - }; - verifyWarns(checkConfig, fname, expected, 6); - } - - @Test - public void testInvalidClassDefWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidClassDefIndent.java"); - final String[] expected = { - "22: " + getCheckMessage(MSG_ERROR, "class def modifier", 2, 0), - "28: " + getCheckMessage(MSG_ERROR, "class def lcurly", 2, 0), - "31: " + getCheckMessage(MSG_ERROR, "class def rcurly", 2, 0), - "34: " + getCheckMessage(MSG_ERROR, "class def ident", 2, 0), - "38: " + getCheckMessage(MSG_ERROR, "class def rcurly", 2, 0), - "43: " + getCheckMessage(MSG_ERROR, "extends", 2, 4), - "44: " + getCheckMessage(MSG_ERROR, "implements", 2, 4), - "50: " + getCheckMessage(MSG_ERROR, "extends", 2, 4), - "58: " + getCheckMessage(MSG_ERROR, "implements", 2, 4), - "59: " + getCheckMessage(MSG_ERROR, "java", 2, 4), - "64: " + getCheckMessage(MSG_ERROR, "class def modifier", 2, 0), - "65: " + getCheckMessage(MSG_ERROR, "class def lcurly", 2, 0), - "73: " + getCheckMessage(MSG_ERROR, "class def rcurly", 2, 0), - "77: " + getCheckMessage(MSG_ERROR, "extends", 2, 4), - "86: " + getCheckMessage(MSG_ERROR, "class def ident", 2, 4), - "88: " + getCheckMessage(MSG_ERROR, "class def ident", 6, 4), - "91: " + getCheckMessage(MSG_ERROR, "class def ident", 2, 4), - "95: " + getCheckMessage(MSG_ERROR, "member def modifier", 6, 8), - "101: " + getCheckMessage(MSG_ERROR, "int", 10, 12), - "106: " + getCheckMessage(MSG_ERROR, "member def modifier", 6, 8), - "111: " + getCheckMessage(MSG_ERROR, "class def rcurly", 6, 4), - "113: " + getCheckMessage(MSG_ERROR, "class def ident", 6, 4), - "119: " + getCheckMessage(MSG_ERROR, "class def ident", 6, 8), - "122: " + getCheckMessage(MSG_ERROR, "class def ident", 10, 8), - "124: " + getCheckMessage(MSG_ERROR, "class def rcurly", 10, 8), - "127: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "132: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 10, 8), - "133: " + getCheckMessage(MSG_ERROR_MULTI, "object def lcurly", 8, "10, 14"), - "137: " + getCheckMessage(MSG_ERROR_MULTI, "object def rcurly", 8, "10, 14"), - "141: " + getCheckMessage(MSG_ERROR_MULTI, "object def lcurly", 6, "8, 12"), - "142: " + getCheckMessage(MSG_ERROR, "method def modifier", 12, 10), - "144: " + getCheckMessage(MSG_ERROR, "method def rcurly", 12, 10), - "145: " + getCheckMessage(MSG_ERROR_MULTI, "object def rcurly", 6, "8, 12"), - "150: " + getCheckMessage(MSG_ERROR, "method def modifier", 10, 12), - "152: " + getCheckMessage(MSG_ERROR, "method def rcurly", 10, 12), - "188: " + getCheckMessage(MSG_ERROR, "class", 0, 4), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidBlockWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidBlockIndent.java"); - final String[] expected = { - "26: " + getCheckMessage(MSG_ERROR, "block lcurly", 7, 8), - "27: " + getCheckMessage(MSG_ERROR, "block lcurly", 9, 8), - "29: " + getCheckMessage(MSG_ERROR, "block lcurly", 9, 8), - "30: " + getCheckMessage(MSG_ERROR, "block rcurly", 7, 8), - "32: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), - "34: " + getCheckMessage(MSG_ERROR, "block rcurly", 6, 8), - "35: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), - "38: " + getCheckMessage(MSG_ERROR, "block lcurly", 9, 8), - "39: " + getCheckMessage(MSG_CHILD_ERROR, "block", 13, 12), - "39: " + getCheckMessage(MSG_ERROR, "member def type", 13, 12), - "41: " + getCheckMessage(MSG_CHILD_ERROR, "block", 13, 12), - "42: " + getCheckMessage(MSG_ERROR, "block rcurly", 9, 8), - "45: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), - "46: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), - "46: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "48: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), - "49: " + getCheckMessage(MSG_ERROR, "block rcurly", 6, 8), - "52: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 8), - "55: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), - "55: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "59: " + getCheckMessage(MSG_ERROR, "block lcurly", 10, 12), - "63: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), - "68: " + getCheckMessage(MSG_CHILD_ERROR, "block", 10, 12), - "70: " + getCheckMessage(MSG_ERROR, "block lcurly", 10, 12), - "71: " + getCheckMessage(MSG_CHILD_ERROR, "block", 14, 16), - "71: " + getCheckMessage(MSG_ERROR, "member def type", 14, 16), - "86: " + getCheckMessage(MSG_ERROR, "block rcurly", 10, 12), - "95: " + getCheckMessage(MSG_ERROR, "static initialization", 2, 4), - "96: " + getCheckMessage(MSG_ERROR, "static initialization", 6, 4), - "100: " + getCheckMessage(MSG_ERROR, "member def type", 7, 8), - "100: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 7, 8), - "103: " + getCheckMessage(MSG_ERROR, "static initialization", 6, 4), - "105: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 2, 4), - "107: " + getCheckMessage(MSG_ERROR, "static initialization", 2, 4), - "109: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 6, 4), - "111: " + getCheckMessage(MSG_ERROR, "static initialization", 2, 4), - "113: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - "113: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 6, 8), - "116: " + getCheckMessage(MSG_ERROR, "static initialization lcurly", 2, 4), - "117: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - "117: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 6, 8), - "118: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 6, 4), - "123: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - "123: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 6, 8), - "128: " + getCheckMessage(MSG_ERROR, "member def type", 4, 8), - "128: " + getCheckMessage(MSG_CHILD_ERROR, "static initialization", 4, 8), - "129: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 2, 4), - "134: " + getCheckMessage(MSG_ERROR, "static initialization rcurly", 6, 4), - "137: " + getCheckMessage(MSG_ERROR, "block lcurly", 2, 4), - "138: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 4), - "141: " + getCheckMessage(MSG_ERROR, "block lcurly", 2, 4), - "143: " + getCheckMessage(MSG_ERROR, "block rcurly", 6, 4), - "145: " + getCheckMessage(MSG_ERROR, "block lcurly", 6, 4), - "147: " + getCheckMessage(MSG_ERROR, "block rcurly", 2, 4), - "150: " + getCheckMessage(MSG_CHILD_ERROR, "block", 6, 8), - "150: " + getCheckMessage(MSG_ERROR, "member def type", 6, 8), - }; - verifyWarns(checkConfig, fname, expected, 10); - } - - @Test - public void testInvalidIfWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidIfIndent.java"); - final String[] expected = { - "55: " + getCheckMessage(MSG_ERROR, "if", 1, 8), - "60: " + getCheckMessage(MSG_ERROR, "if", 9, 8), - "61: " + getCheckMessage(MSG_ERROR, "if lcurly", 9, 8), - "62: " + getCheckMessage(MSG_ERROR, "if rcurly", 7, 8), - "64: " + getCheckMessage(MSG_ERROR, "if", 6, 8), - "65: " + getCheckMessage(MSG_ERROR, "if lcurly", 5, 8), - "66: " + getCheckMessage(MSG_ERROR, "if rcurly", 5, 8), - "70: " + getCheckMessage(MSG_ERROR, "if rcurly", 10, 8), - "71: " + getCheckMessage(MSG_ERROR, "else rcurly", 7, 8), - "74: " + getCheckMessage(MSG_ERROR, "if", 9, 8), - - "75: " + getCheckMessage(MSG_ERROR, "if lcurly", 7, 8), - "77: " + getCheckMessage(MSG_ERROR, "else", 9, 8), - "79: " + getCheckMessage(MSG_ERROR, "else rcurly", 9, 8), - "82: " + getCheckMessage(MSG_ERROR, "if", 10, 8), - "83: " + getCheckMessage(MSG_ERROR, "if rcurly", 7, 8), - "84: " + getCheckMessage(MSG_ERROR, "else", 9, 8), - "85: " + getCheckMessage(MSG_ERROR, "else lcurly", 7, 8), - "86: " + getCheckMessage(MSG_ERROR, "else rcurly", 9, 8), - - "90: " + getCheckMessage(MSG_ERROR, "if", 9, 8), - "91: " + getCheckMessage(MSG_ERROR, "if lcurly", 9, 8), - "92: " + getCheckMessage(MSG_ERROR, "if rcurly", 9, 8), - "93: " + getCheckMessage(MSG_ERROR, "else lcurly", 7, 8), - "94: " + getCheckMessage(MSG_ERROR, "else rcurly", 10, 8), - "97: " + getCheckMessage(MSG_ERROR, "if", 6, 8), - "98: " + getCheckMessage(MSG_ERROR, "if lcurly", 10, 8), - "99: " + getCheckMessage(MSG_ERROR, "if rcurly", 10, 8), - "100: " + getCheckMessage(MSG_ERROR, "else rcurly", 7, 8), - "103: " + getCheckMessage(MSG_ERROR, "if", 5, 8), - "104: " + getCheckMessage(MSG_ERROR, "if rcurly", 11, 8), - "105: " + getCheckMessage(MSG_ERROR, "else", 5, 8), - "106: " + getCheckMessage(MSG_ERROR, "else rcurly", 11, 8), - - "126: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), - "131: " + getCheckMessage(MSG_ERROR, "if lcurly", 10, 8), - "132: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "132: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "137: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), - "138: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "140: " + getCheckMessage(MSG_CHILD_ERROR, "else", 10, 12), - "140: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "141: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 8, 12), - - "148: " + getCheckMessage(MSG_CHILD_ERROR, "if", 16, 12), - "149: " + getCheckMessage(MSG_ERROR, "if rcurly", 9, 8), - "152: " + getCheckMessage(MSG_CHILD_ERROR, "else", 16, 12), - "158: " + getCheckMessage(MSG_CHILD_ERROR, "if", 0, 12), - "158: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 0, 12), - "162: " + getCheckMessage(MSG_CHILD_ERROR, "else", 40, 12), - "169: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), - - "172: " + getCheckMessage(MSG_CHILD_ERROR, "else", 14, 12), - "178: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "178: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "180: " + getCheckMessage(MSG_CHILD_ERROR, "else", 10, 12), - "180: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "184: " + getCheckMessage(MSG_ERROR, "if", 10, 8), - "185: " + getCheckMessage(MSG_CHILD_ERROR, "if", 14, 12), - "186: " + getCheckMessage(MSG_ERROR, "if rcurly", 10, 8), - "187: " + getCheckMessage(MSG_ERROR, "else", 10, 8), - - "188: " + getCheckMessage(MSG_CHILD_ERROR, "else", 14, 12), - "189: " + getCheckMessage(MSG_ERROR, "else rcurly", 10, 8), - "192: " + getCheckMessage(MSG_ERROR, "&&", 9, 12), - "192: " + getCheckMessage(MSG_CHILD_ERROR, "if", 9, 12), - "193: " + getCheckMessage(MSG_ERROR, "&&", 11, 12), - "193: " + getCheckMessage(MSG_CHILD_ERROR, "if", 11, 12), - "197: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "200: " + getCheckMessage(MSG_ERROR, "if rcurly", 7, 8), - "207: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "207: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - "209: " + getCheckMessage(MSG_CHILD_ERROR, "if", 10, 12), - "209: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - - "225: " + getCheckMessage(MSG_ERROR, "if", 10, 12), - "229: " + getCheckMessage(MSG_CHILD_ERROR, "if", 18, 20), - "229: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 18, 20), - "233: " + getCheckMessage(MSG_ERROR, "if rcurly", 40, 8), - "240: " + getCheckMessage(MSG_ERROR, "if rparen", 10, 8), - "245: " + getCheckMessage(MSG_ERROR, "if rparen", 6, 8), - "251: " + getCheckMessage(MSG_ERROR, "(", 6, 12), - "251: " + getCheckMessage(MSG_ERROR, "if lparen", 6, 8), - "253: " + getCheckMessage(MSG_ERROR, "if rparen", 6, 8), - }; - verifyWarns(checkConfig, fname, expected, 11); - } - - @Test - public void testInvalidWhileWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidWhileIndent.java"); - final String[] expected = { - "25: " + getCheckMessage(MSG_ERROR, "while", 9, 8), - "26: " + getCheckMessage(MSG_ERROR, "while rcurly", 7, 8), - "28: " + getCheckMessage(MSG_ERROR, "while", 7, 8), - "29: " + getCheckMessage(MSG_ERROR, "while lcurly", 9, 8), - "30: " + getCheckMessage(MSG_ERROR, "while rcurly", 9, 8), - - "32: " + getCheckMessage(MSG_ERROR, "while", 9, 8), - "33: " + getCheckMessage(MSG_ERROR, "while lcurly", 6, 8), - "34: " + getCheckMessage(MSG_CHILD_ERROR, "while", 14, 12), - "35: " + getCheckMessage(MSG_ERROR, "while rcurly", 6, 8), - - "37: " + getCheckMessage(MSG_ERROR, "while", 10, 8), - "39: " + getCheckMessage(MSG_ERROR, "while rcurly", 10, 8), - "41: " + getCheckMessage(MSG_ERROR, "while", 10, 8), - "44: " + getCheckMessage(MSG_ERROR, "while rcurly", 10, 8), - - "46: " + getCheckMessage(MSG_ERROR, "while", 6, 8), - "47: " + getCheckMessage(MSG_ERROR, "while lcurly", 10, 8), - "50: " + getCheckMessage(MSG_ERROR, "while rcurly", 6, 8), - "53: " + getCheckMessage(MSG_ERROR, "if", 14, 12), - "54: " + getCheckMessage(MSG_CHILD_ERROR, "if", 18, 16), - "55: " + getCheckMessage(MSG_ERROR, "if rcurly", 14, 12), - "56: " + getCheckMessage(MSG_CHILD_ERROR, "while", 14, 12), - "57: " + getCheckMessage(MSG_ERROR, "while rcurly", 10, 8), - - "60: " + getCheckMessage(MSG_CHILD_ERROR, "while", 10, 12), - "66: " + getCheckMessage(MSG_CHILD_ERROR, "while", 10, 12), - "71: " + getCheckMessage(MSG_CHILD_ERROR, "while", 10, 12), - "78: " + getCheckMessage(MSG_ERROR, "while rparen", 5, 8), - "85: " + getCheckMessage(MSG_ERROR, "while rparen", 10, 8), - "92: " + getCheckMessage(MSG_ERROR, "while rparen", 10, 8), - "99: " + getCheckMessage(MSG_CHILD_ERROR, "while", 8, 12), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidInvalidAnonymousClass() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidAnonymousClassIndent.java"); - final String[] expected = { - "28: " + getCheckMessage(MSG_ERROR_MULTI, "method def rcurly", 17, "12, 16"), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testInvalidForWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputInvalidForIndent.java"); - final String[] expected = { - "26: " + getCheckMessage(MSG_ERROR, "for", 6, 8), - "27: " + getCheckMessage(MSG_ERROR, "for rcurly", 10, 8), - "29: " + getCheckMessage(MSG_ERROR, "for", 9, 8), - "30: " + getCheckMessage(MSG_ERROR, "for lcurly", 6, 8), - "31: " + getCheckMessage(MSG_ERROR, "for rcurly", 6, 8), - "35: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "35: " + getCheckMessage(MSG_CHILD_ERROR, "method call", 10, 12), - - "36: " + getCheckMessage(MSG_ERROR, "for rcurly", 10, 8), - "39: " + getCheckMessage(MSG_ERROR, "for lcurly", 10, 8), - "40: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "40: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "48: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "48: " + getCheckMessage(MSG_ERROR, "i", 10, 12), - "54: " + getCheckMessage(MSG_ERROR, "for", 7, 8), - - "55: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "55: " + getCheckMessage(MSG_ERROR, "int", 10, 11), - "55: " + getCheckMessage(MSG_ERROR, "member def type", 10, 12), - "64: " + getCheckMessage(MSG_CHILD_ERROR, "for", 7, 12), - "64: " + getCheckMessage(MSG_ERROR, "i", 7, 12), - - "69: " + getCheckMessage(MSG_ERROR, "for", 6, 8), - "70: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "71: " + getCheckMessage(MSG_CHILD_ERROR, "for", 14, 16), - "72: " + getCheckMessage(MSG_CHILD_ERROR, "for", 10, 12), - "77: " + getCheckMessage(MSG_ERROR, "for rcurly", 39, 8), - "81: " + getCheckMessage(MSG_ERROR, "for rparen", 12, 8), - }; - verifyWarns(checkConfig, fname, expected, 6); - } - - @Test - public void testValidForWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidForIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidDoWhileWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidDoWhileIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidBlockWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidBlockIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidWhileWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidWhileIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidClassDefWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidClassDefIndent.java"); - final String[] expected = { - "49: " + getCheckMessage(MSG_ERROR, "class", 0, 4), - "71: " + getCheckMessage(MSG_ERROR, "int", 8, 12), - }; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidInterfaceDefWithChecker() - throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidInterfaceDefIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testValidCommaWithChecker() - throws Exception { - - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String fname = getPath("indentation/InputValidCommaIndent.java"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, fname, expected); - } - - @Test - public void testTabs() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "29: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 9, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputUseTabs.java"), expected); - } - - @Test - public void testIndentationLevel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "2"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "29: " + getCheckMessage(MSG_CHILD_ERROR, "ctor def", 5, 4), - }; - verifyWarns(checkConfig, getPath("indentation/InputUseTwoSpaces.java"), expected); - } - - @Test - public void testThrowsIndentationLevel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InvalidInputThrowsIndent.java"), expected); - } - - @Test - public void testCaseLevel() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "0"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "27: " + getCheckMessage(MSG_CHILD_ERROR, "case", 10, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputCaseLevel.java"), expected); - } - - @Test - public void testBraceAdjustment() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "2"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "28: " + getCheckMessage(MSG_ERROR, "if rcurly", 8, 10), - }; - verifyWarns(checkConfig, getPath("indentation/InputBraceAdjustment.java"), expected); - } - - @Test - public void testInvalidAssignWithChecker() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = { - "22: " + getCheckMessage(MSG_ERROR, "getLineNo", 10, 12), - "24: " + getCheckMessage(MSG_ERROR, "getLine", 10, 12), - "28: " + getCheckMessage(MSG_ERROR, "=", 9, 12), - "29: " + getCheckMessage(MSG_ERROR, "1", 10, 12), - }; - verifyWarns(checkConfig, getPath("indentation/InputInvalidAssignIndent.java"), expected); - } - - @Test - public void testInvalidImportIndent() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("basicOffset", "8"); - checkConfig.addAttribute("tabWidth", "4"); - final String[] expected = { - "4: " + getCheckMessage(MSG_CHILD_ERROR, "import", 2, 8), - }; - verifyWarns(checkConfig, getPath("indentation/InputInvalidImportIndent.java"), expected); - } - - @Test - public void testValidAssignWithChecker() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputValidAssignIndent.java"), expected); - } - - @Test - public void test15Extensions() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/Input15Extensions.java"), expected); - } - - @Test - public void testTryResources() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputValidTryResourcesIndent.java"), - expected); - } - - @Test - public void testSwitchCustom() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputSwitchCustom.java"), - expected); - } - - @Test - public void testSynchronizedStatement() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputSynchronizedStatement.java"), expected); - } - - @Test - public void testSynchronizedMethod() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("arrayInitIndent", "4"); - checkConfig.addAttribute("basicOffset", "4"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "4"); - checkConfig.addAttribute("forceStrictCondition", "false"); - checkConfig.addAttribute("lineWrappingIndentation", "8"); - checkConfig.addAttribute("tabWidth", "4"); - checkConfig.addAttribute("throwsIndent", "8"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputSynchronizedMethod.java"), expected); - } - - @Test - public void testAnonymousClassInMethod() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("tabWidth", "8"); - checkConfig.addAttribute("basicOffset", "2"); - checkConfig.addAttribute("braceAdjustment", "0"); - checkConfig.addAttribute("caseIndent", "2"); - checkConfig.addAttribute("lineWrappingIndentation", "4"); - checkConfig.addAttribute("throwsIndent", "4"); - checkConfig.addAttribute("arrayInitIndent", "2"); - final String[] expected = { - "19: " + getCheckMessage(MSG_ERROR, "method def modifier", 8, 2), - "20: " + getCheckMessage(MSG_CHILD_ERROR, "method def", 16, 4), - "21: " + getCheckMessage(MSG_ERROR_MULTI, "method def modifier", 24, "18, 20, 22"), - "23: " + getCheckMessage(MSG_CHILD_ERROR_MULTI, "method def", 32, "20, 22, 24"), - "24: " + getCheckMessage(MSG_ERROR_MULTI, "method def rcurly", 24, "18, 20, 22"), - "26: " + getCheckMessage(MSG_ERROR, "method def rcurly", 8, 2), - }; - verifyWarns(checkConfig, getPath("indentation/InputAnonymousClassInMethod.java"), expected); - } - - @Test - public void testAnnotationDefinition() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("tabWidth", "4"); - final String[] expected = ArrayUtils.EMPTY_STRING_ARRAY; - verifyWarns(checkConfig, getPath("indentation/InputAnnotationDefinition.java"), expected); - } - - @Test - public void testPackageDeclaration() throws Exception { - final DefaultConfiguration checkConfig = createCheckConfig(IndentationCheck.class); - checkConfig.addAttribute("tabWidth", "4"); - final String[] expected = { - "1: " + getCheckMessage(MSG_ERROR, "package def", 1, 0), - }; - verifyWarns(checkConfig, getPath("indentation/InputPackageDeclaration.java"), expected); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/pair.info deleted file mode 100755 index e607ad0..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#49001/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:49001 -comSha:9cc86b38df9a086713d1fcdf01b451b41c0d6f65 -parentComSha:a827b7cbbf1f29e24e3f814149809941e754c93c -BuggyFilePath:src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java -FixedFilePath:src/test/java/com/puppycrawl/tools/checkstyle/checks/indentation/IndentationCheckTest.java -StartLineNum:73 -EndLineNum:73 -repoName:checkstyle#checkstyle \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/comMsg.txt deleted file mode 100755 index 4f66f4a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of DM_DEFAULT_ENCODING from FindBugs. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/diff.diff deleted file mode 100755 index 7c6d6cc..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java b/util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -index e419ad80..dc113ebc 100644 ---- a/util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -+++ b/util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -@@ -3,0 +4 @@ import java.io.IOException; -+import java.io.OutputStreamWriter; -@@ -80 +81,3 @@ public class LogCaptureFilter extends AbstractFilter { -- writer = new PrintWriter(response.getOutputStream()); -+ writer = new PrintWriter(new OutputStreamWriter( -+ response.getOutputStream(), -+ response.getCharacterEncoding())); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/new/LogCaptureFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/new/LogCaptureFilter.java deleted file mode 100755 index dc113eb..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/new/LogCaptureFilter.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.util.Enumeration; -import java.util.List; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Captures log messages and writes them to the response based on request - * parameters. - */ -public class LogCaptureFilter extends AbstractFilter { - - /** - * Setting key for prefix to parameters that control which logs to - * capture. - */ - public static final String PARAMETER_PREFIX_SETTING = "dari/logCaptureFilterParameterPrefix"; - - /** Default prefix to parameters that control which logs to capture. */ - public static final String DEFAULT_PARAMETER_PREFIX = "_log."; - - // --- AbstractFilter support --- - - @Override - @SuppressWarnings("unchecked") - protected void doRequest( - HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws IOException, ServletException { - - if (!Settings.isProduction()) { - chain.doFilter(request, response); - return; - } - - String parameterPrefix = Settings.getOrDefault(String.class, PARAMETER_PREFIX_SETTING, DEFAULT_PARAMETER_PREFIX); - LogCapture capture = null; - - for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) { - String name = e.nextElement(); - - if (name.startsWith(parameterPrefix)) { - if (capture == null) { - capture = new LogCapture(); - } - capture.putLogger( - Logger.getLogger(name.substring(parameterPrefix.length())), - Level.parse(request.getParameter(name))); - } - } - - if (capture == null) { - chain.doFilter(request, response); - return; - } - - try { - capture.start(); - - chain.doFilter(request, response); - - } finally { - List logs = capture.stop(); - String contentType = response.getContentType(); - PrintWriter writer = null; - - try { - writer = response.getWriter(); - } catch (IllegalStateException ex) { - writer = new PrintWriter(new OutputStreamWriter( - response.getOutputStream(), - response.getCharacterEncoding())); - } - - if (contentType != null) { - contentType = contentType.toLowerCase(Locale.ENGLISH); - - if (contentType.contains("json") || - contentType.contains("javascript")) { - writer.println("/*"); - for (String log : logs) { - writer.println(log); - } - writer.println("*/"); - return; - - } else if (contentType.contains("html")) { - writer.println("
");
-                    for (String log : logs) {
-                        writer.println(StringUtils.escapeHtml(log));
-                    }
-                    writer.println("
"); - return; - } - } - - for (String log : logs) { - writer.println(log); - } - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/old/LogCaptureFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/old/LogCaptureFilter.java deleted file mode 100755 index e419ad8..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/old/LogCaptureFilter.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; -import java.util.Enumeration; -import java.util.List; -import java.util.Locale; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * Captures log messages and writes them to the response based on request - * parameters. - */ -public class LogCaptureFilter extends AbstractFilter { - - /** - * Setting key for prefix to parameters that control which logs to - * capture. - */ - public static final String PARAMETER_PREFIX_SETTING = "dari/logCaptureFilterParameterPrefix"; - - /** Default prefix to parameters that control which logs to capture. */ - public static final String DEFAULT_PARAMETER_PREFIX = "_log."; - - // --- AbstractFilter support --- - - @Override - @SuppressWarnings("unchecked") - protected void doRequest( - HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws IOException, ServletException { - - if (!Settings.isProduction()) { - chain.doFilter(request, response); - return; - } - - String parameterPrefix = Settings.getOrDefault(String.class, PARAMETER_PREFIX_SETTING, DEFAULT_PARAMETER_PREFIX); - LogCapture capture = null; - - for (Enumeration e = request.getParameterNames(); e.hasMoreElements(); ) { - String name = e.nextElement(); - - if (name.startsWith(parameterPrefix)) { - if (capture == null) { - capture = new LogCapture(); - } - capture.putLogger( - Logger.getLogger(name.substring(parameterPrefix.length())), - Level.parse(request.getParameter(name))); - } - } - - if (capture == null) { - chain.doFilter(request, response); - return; - } - - try { - capture.start(); - - chain.doFilter(request, response); - - } finally { - List logs = capture.stop(); - String contentType = response.getContentType(); - PrintWriter writer = null; - - try { - writer = response.getWriter(); - } catch (IllegalStateException ex) { - writer = new PrintWriter(response.getOutputStream()); - } - - if (contentType != null) { - contentType = contentType.toLowerCase(Locale.ENGLISH); - - if (contentType.contains("json") || - contentType.contains("javascript")) { - writer.println("/*"); - for (String log : logs) { - writer.println(log); - } - writer.println("*/"); - return; - - } else if (contentType.contains("html")) { - writer.println("
");
-                    for (String log : logs) {
-                        writer.println(StringUtils.escapeHtml(log));
-                    }
-                    writer.println("
"); - return; - } - } - - for (String log : logs) { - writer.println(log); - } - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/pair.info deleted file mode 100755 index 0dcdfb2..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#51948/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:51948 -comSha:7a9e20fb2b863e37ccee4dbc61cf0eaf0b3c369d -parentComSha:2d3b35e6aac1466d93e5f7829098a195efc59449 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/LogCaptureFilter.java -StartLineNum:80 -EndLineNum:80 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/comMsg.txt deleted file mode 100755 index 4f66f4a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of DM_DEFAULT_ENCODING from FindBugs. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/diff.diff deleted file mode 100755 index 0a4df3b..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/SourceFilter.java b/util/src/main/java/com/psddev/dari/util/SourceFilter.java -index cf6456f2..fe2535f2 100644 ---- a/util/src/main/java/com/psddev/dari/util/SourceFilter.java -+++ b/util/src/main/java/com/psddev/dari/util/SourceFilter.java -@@ -7,0 +8 @@ import java.io.OutputStream; -+import java.io.OutputStreamWriter; -@@ -945 +946 @@ public class SourceFilter extends AbstractFilter { -- private final PrintWriter writer = new PrintWriter(output); -+ private final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StringUtils.UTF_8)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/new/SourceFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/new/SourceFilter.java deleted file mode 100755 index fe2535f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/new/SourceFilter.java +++ /dev/null @@ -1,970 +0,0 @@ -package com.psddev.dari.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.instrument.ClassDefinition; -import java.lang.instrument.Instrumentation; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.servlet.FilterChain; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.tools.Diagnostic; -import javax.tools.DiagnosticCollector; -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; -import javax.tools.StandardJavaFileManager; -import javax.tools.StandardLocation; -import javax.tools.ToolProvider; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Enables rapid web application development by making source code changes - * immediately available. - * - *

To configure, add these definitions to the {@code web.xml} deployment - * descriptor file: - * - *

{@literal
-
-    SourceFilter
-    com.psddev.dari.util.SourceFilter
-
-
-    SourceFilter
-    /*
-
- * }
- * - *

And the application must include a {@code build.properties} file - * that specifies the locations of the source code: - * - *

    - *
  • {@link CodeUtils#JAVA_SOURCE_DIRECTORY_PROPERTY} - *
  • {@link #WEBAPP_SOURCES_PROPERTY} - *
- * - *

You can skip this step if the project uses Apache Maven to manage - * the build and inherits from {@code com.psddev:dari-parent}, because - * that parent POM automatically adds those properties during the - * {@code generate-resources} phase. - */ -public class SourceFilter extends AbstractFilter { - - /** - * Build property that specifies the directory containing the - * web application sources, such as JSPs. - */ - public static final String WEBAPP_SOURCES_PROPERTY = "webappSourceDirectory"; - - public static final String DEFAULT_INTERCEPT_PATH = "/_sourceFilter"; - public static final String INTERCEPT_PATH_SETTING = "dari/sourceFilterInterceptPath"; - - public static final String DEFAULT_RELOADER_PATH = "/reloader/"; - public static final String RELOADER_PATH_SETTING = "dari/sourceFilterReloaderPath"; - public static final String RELOADER_ACTION_PARAMETER = "action"; - public static final String RELOADER_PING_ACTION = "ping"; - public static final String RELOADER_RELOAD_ACTION = "reload"; - public static final String RELOADER_CONTEXT_PATH_PARAMETER = "contextPath"; - public static final String RELOADER_REQUEST_PATH_PARAMETER = "requestPath"; - - private static final JavaCompiler COMPILER = ToolProvider.getSystemJavaCompiler(); - private static final Logger LOGGER = LoggerFactory.getLogger(SourceFilter.class); - - private static final String CLASSES_PATH = "/WEB-INF/classes/"; - private static final String BUILD_PROPERTIES_PATH = "build.properties"; - private static final String ISOLATING_RESPONSE_ATTRIBUTE = SourceFilter.class.getName() + ".isolatingResponse"; - private static final String IS_ISOLATION_DONE_ATTRIBUTE = SourceFilter.class.getName() + ".isIsolationDone"; - private static final String COPIED_ATTRIBUTE = SourceFilter.class.getName() + ".copied"; - - private static final String CATALINA_BASE_PROPERTY = "catalina.base"; - private static final String RELOADER_MAVEN_ARTIFACT_ID = "dari-reloader-tomcat6"; - private static final String RELOADER_MAVEN_VERSION = "2.0-SNAPSHOT"; - private static final String RELOADER_MAVEN_URL = "http://public.psddev.com/maven/com/psddev/" + RELOADER_MAVEN_ARTIFACT_ID + "/" + RELOADER_MAVEN_VERSION + "/"; - private static final Pattern BUILD_NUMBER_PATTERN = Pattern.compile("([^<]*)"); - private static final Pattern TIMESTAMP_PATTERN = Pattern.compile("([^<]*)"); - - private File classOutput; - private final Set javaSourcesSet = new HashSet(); - private final Map webappSourcesMap = new HashMap(); - private final Map sourceModifieds = new HashMap(); - private final Map changedClasses = new TreeMap(); - - // --- AbstractFilter support --- - - @Override - protected void doInit() { - if (COMPILER == null) { - LOGGER.info("Java compiler not available!"); - return; - } - - ServletContext context = getServletContext(); - String classOutputString = context.getRealPath(CLASSES_PATH); - if (classOutputString == null) { - LOGGER.info("Can't get the real path to [{}]!", CLASSES_PATH); - return; - } - - classOutput = new File(classOutputString); - if (classOutput.exists()) { - LOGGER.info("Saving recompiled Java classes to [{}]", classOutput); - } else { - LOGGER.info("[{}] doesn't exist!", classOutput); - classOutput = null; - return; - } - - javaSourcesSet.addAll(CodeUtils.getSourceDirectories()); - - processWarBuildProperties(context, ""); - for (String contextPath : JspUtils.getEmbeddedSettings(context).keySet()) { - processWarBuildProperties(context, contextPath); - } - } - - /** - * Processes the build properties file associated with the given - * {@code context} and {@code contextPath} and adds its source - * directories. - * - * @param context Can't be {@code null}. - * @param contextPath Can't be {@code null}. - */ - private void processWarBuildProperties(ServletContext context, String contextPath) { - InputStream buildPropertiesInput = context.getResourceAsStream(contextPath + CLASSES_PATH + BUILD_PROPERTIES_PATH); - if (buildPropertiesInput == null) { - return; - } - - try { - try { - Properties buildProperties = new Properties(); - buildProperties.load(buildPropertiesInput); - - String javaSourcesString = buildProperties.getProperty(CodeUtils.JAVA_SOURCE_DIRECTORY_PROPERTY); - if (javaSourcesString != null) { - File javaSources = new File(javaSourcesString); - if (javaSources.exists()) { - javaSourcesSet.add(javaSources); - LOGGER.info("Found Java sources in [{}]", javaSources); - } - } - - String webappSourcesString = buildProperties.getProperty(WEBAPP_SOURCES_PROPERTY); - if (webappSourcesString != null) { - File webappSources = new File(webappSourcesString); - if (webappSources.exists()) { - LOGGER.info("Copying webapp sources from [{}] to [{}/]", webappSources, contextPath); - webappSourcesMap.put(contextPath, webappSources); - } - } - - } finally { - buildPropertiesInput.close(); - } - - } catch (IOException error) { - LOGGER.debug("Can't read WAR build properties!", error); - } - } - - @Override - protected void doDestroy() { - classOutput = null; - javaSourcesSet.clear(); - webappSourcesMap.clear(); - sourceModifieds.clear(); - changedClasses.clear(); - } - - @Override - protected void doDispatch( - HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws Exception { - - if (Settings.isProduction()) { - chain.doFilter(request, response); - return; - } - - if (request.getAttribute(IS_ISOLATION_DONE_ATTRIBUTE) != null) { - return; - } - - IsolatingResponse isolatingResponse = (IsolatingResponse) request.getAttribute(ISOLATING_RESPONSE_ATTRIBUTE); - if (isolatingResponse != null) { - if (!JspUtils.getCurrentServletPath(request).equals(isolatingResponse.jsp)) { - isolatingResponse = null; - - } else { - @SuppressWarnings("all") - HtmlWriter html = new HtmlWriter(isolatingResponse.getResponse().getWriter()); - html.putAllStandardDefaults(); - - try { - StringWriter writer = new StringWriter(); - JspUtils.include(request, response, writer, request.getParameter("_draft")); - html.writeStart("pre"); - html.writeHtml(writer.toString().trim()); - html.writeEnd(); - - } catch (Exception ex) { - html.writeStart("pre", "class", "alert alert-error"); - html.writeObject(ex); - html.writeEnd(); - - } finally { - request.setAttribute(IS_ISOLATION_DONE_ATTRIBUTE, Boolean.TRUE); - } - return; - } - } - - copyWebappSource(request); - super.doDispatch(request, response, chain); - } - - @Override - protected void doRequest( - final HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws IOException, ServletException { - - COPY_RESOURCES.get(); - - // Intercept special actions. - if (!ObjectUtils.isBlank(request.getParameter("_reload")) && - isReloaderAvailable(request)) { - compileJavaSources(); - response.sendRedirect(StringUtils.addQueryParameters( - getReloaderPath(), - RELOADER_CONTEXT_PATH_PARAMETER, request.getContextPath(), - RELOADER_REQUEST_PATH_PARAMETER, JspUtils.getAbsolutePath(request, "", "_reload", null), - RELOADER_ACTION_PARAMETER, RELOADER_RELOAD_ACTION)); - return; - } - - String servletPath = request.getServletPath(); - if (servletPath.startsWith(getInterceptPath())) { - String action = request.getParameter("action"); - - if ("ping".equals(action)) { - response.setContentType("text/plain"); - response.setCharacterEncoding("UTF-8"); - response.getWriter().write("OK"); - - } else if ("install".equals(action)) { - if (isReloaderAvailable(request)) { - String requestPath = request.getParameter("requestPath"); - response.sendRedirect(ObjectUtils.isBlank(requestPath) ? "/" : requestPath); - } else { - @SuppressWarnings("all") - ReloaderInstaller installer = new ReloaderInstaller(request, response); - installer.writeStart(); - } - - } else { - throw new IllegalArgumentException(String.format( - "[%s] isn't a valid intercept action!", action)); - } - return; - } - - String contentType = ObjectUtils.getContentType(servletPath); - if (contentType.startsWith("image/") || - contentType.startsWith("video/") || - contentType.equals("text/css") || - contentType.equals("text/javascript")) { - chain.doFilter(request, response); - return; - } - - final DiagnosticCollector errors = compileJavaSources(); - final boolean hasBackgroundTasks; - if (errors == null && - !changedClasses.isEmpty() && - !JspUtils.isAjaxRequest(request)) { - - if (hasBackgroundTasks()) { - hasBackgroundTasks = true; - - } else if (isReloaderAvailable(request)) { - changedClasses.clear(); - response.sendRedirect(StringUtils.addQueryParameters( - getReloaderPath(), - RELOADER_CONTEXT_PATH_PARAMETER, request.getContextPath(), - RELOADER_REQUEST_PATH_PARAMETER, JspUtils.getAbsolutePath(request, ""), - RELOADER_ACTION_PARAMETER, RELOADER_RELOAD_ACTION)); - return; - - } else { - hasBackgroundTasks = false; - } - - } else { - hasBackgroundTasks = false; - } - - IsolatingResponse isolatingResponse = null; - String jsp = request.getParameter("_jsp"); - if (!ObjectUtils.isBlank(jsp)) { - response.setContentType("text/plain"); - isolatingResponse = new IsolatingResponse(response, jsp); - response = isolatingResponse; - request.setAttribute(ISOLATING_RESPONSE_ATTRIBUTE, isolatingResponse); - } - - chain.doFilter(request, response); - if (errors == null && ( - changedClasses.isEmpty() || - JspUtils.isAjaxRequest(request) || - isolatingResponse != null)) { - return; - } - - // Can't reload automatically so at least let the user know - // if viewing an HTML page. - String responseContentType = response.getContentType(); - if (responseContentType == null || - !responseContentType.startsWith("text/html")) { - return; - } - - new HtmlWriter(response.getWriter()) {{ - putDefault(StackTraceElement.class, HtmlFormatter.STACK_TRACE_ELEMENT); - putDefault(Throwable.class, HtmlFormatter.THROWABLE); - - write("

"); - - if (errors == null) { - if (hasBackgroundTasks) { - writeHtml("The application wasn't reloaded automatically because there are background tasks running!"); - - } else { - writeHtml("The application must be reloaded before the changes to these classes become visible. "); - writeStart("a", - "href", JspUtils.getAbsolutePath(request, getInterceptPath(), - "action", "install", - "requestPath", JspUtils.getAbsolutePath(request, "")), - "style", "color: white; text-decoration: underline;"); - writeHtml("Install the reloader"); - writeEnd(); - writeHtml(" to automate this process."); - writeTag("br"); - writeTag("br"); - - for (Map.Entry entry : changedClasses.entrySet()) { - writeHtml(entry.getKey()); - writeHtml(" - "); - writeObject(entry.getValue()); - writeTag("br"); - } - } - - } else { - writeHtml("Syntax errors!"); - writeStart("ol"); - for (Diagnostic diagnostic : errors.getDiagnostics()) { - if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { - writeStart("li", "data-line", diagnostic.getLineNumber(), "data-column", diagnostic.getColumnNumber()); - writeHtml(diagnostic.getMessage(null)); - writeEnd(); - } - } - writeEnd(); - } - - write("
"); - }}; - } - - /** - * Returns the path that intercepts all special actions. - * - * @return Always starts and ends with a slash. - */ - private static String getInterceptPath() { - return StringUtils.ensureStart(Settings.getOrDefault(String.class, INTERCEPT_PATH_SETTING, DEFAULT_INTERCEPT_PATH), "/"); - } - - /** - * Returns the path to the application that can reload this one. - * - * @return Always starts and ends with a slash. - */ - private static String getReloaderPath() { - return StringUtils.ensureSurrounding(Settings.getOrDefault(String.class, RELOADER_PATH_SETTING, DEFAULT_RELOADER_PATH), "/"); - } - - /** - * Returns {@code true} if the reloader is available in the same - * server as this application. - * - * @param request Can't be {@code null}. - */ - private boolean isReloaderAvailable(HttpServletRequest request) { - String servletPath = request.getServletPath(); - String reloaderPath = getReloaderPath(); - - if (!reloaderPath.startsWith(servletPath)) { - try { - URL pingUrl = new URL(StringUtils.addQueryParameters( - JspUtils.getHostUrl(request) + reloaderPath, - RELOADER_ACTION_PARAMETER, RELOADER_PING_ACTION)); - - // To avoid infinite redirects in case the ping hits this - // application. - URLConnection pingConnection = pingUrl.openConnection(); - if (pingConnection instanceof HttpURLConnection) { - ((HttpURLConnection) pingConnection).setInstanceFollowRedirects(false); - } - - InputStream pingInput = pingConnection.getInputStream(); - try { - return "OK".equals(IoUtils.toString(pingInput, StringUtils.UTF_8)); - } finally { - pingInput.close(); - } - - } catch (IOException error) { - // If the ping fails for any reason, assume that the reloader - // isn't available. - } - } - - return false; - } - - /** Returns {@code true} if there are any background tasks running. */ - private boolean hasBackgroundTasks() { - for (TaskExecutor executor : TaskExecutor.Static.getAll()) { - String executorName = executor.getName(); - if (!("Periodic Caches".equals(executorName) || - "Miscellaneous Tasks".equals(executorName))) { - for (Object task : executor.getTasks()) { - if (task instanceof Task && ((Task) task).isRunning()) { - return true; - } - } - } - } - return false; - } - - /** Copies all resources. */ - private final PullThroughValue COPY_RESOURCES = new PullThroughValue() { - - @Override - protected boolean isExpired(Date lastProduce) { - return System.currentTimeMillis() - lastProduce.getTime() > 1000; - } - - @Override - protected Void produce() throws IOException { - if (classOutput != null) { - for (File resourceDirectory : CodeUtils.getResourceDirectories()) { - Long jarModified = CodeUtils.getJarLastModified(resourceDirectory); - copy(resourceDirectory, jarModified, resourceDirectory); - } - } - return null; - } - - private void copy(File resourceDirectory, Long jarModified, File resource) throws IOException { - if (resource.isDirectory()) { - for (File child : resource.listFiles()) { - copy(resourceDirectory, jarModified, child); - } - - } else { - File output = new File(classOutput, resource.toString().substring(resourceDirectory.toString().length()).replace(File.separatorChar, '/')); - - long resourceModified = resource.lastModified(); - long outputModified = output.lastModified(); - if ((jarModified == null || resourceModified > jarModified) && - resourceModified > outputModified) { - IoUtils.copy(resource, output); - LOGGER.info("Copied [{}]", resource); - } - } - } - }; - - /** - * Compile any Java source files that's changed and redefine them - * in place if possible. - */ - private DiagnosticCollector compileJavaSources() throws IOException { - if (javaSourcesSet.isEmpty()) { - return null; - } - - StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(null, null, null); - Set newSourceFiles = new HashSet(); - Map expectedOutputFiles = new HashMap(); - Map notRedefinedClasses = new HashMap(); - List toBeRedefined = new ArrayList(); - - try { - fileManager.setLocation(StandardLocation.SOURCE_PATH, javaSourcesSet); - fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classOutput)); - - for (JavaFileObject sourceFile : fileManager.list( - StandardLocation.SOURCE_PATH, - "", - Collections.singleton(JavaFileObject.Kind.SOURCE), - true)) { - - String className = fileManager.inferBinaryName(StandardLocation.SOURCE_PATH, sourceFile); - JavaFileObject outputFile = fileManager.getJavaFileForOutput( - StandardLocation.CLASS_OUTPUT, - className, - JavaFileObject.Kind.CLASS, - null); - - // Did the source file originate from a JAR? - Long jarModified = null; - String sourcePath = sourceFile.toUri().getPath(); - for (File javaSources : javaSourcesSet) { - if (sourcePath.startsWith(javaSources.getPath())) { - jarModified = CodeUtils.getJarLastModified(javaSources); - break; - } - } - - long sourceModified = sourceFile.getLastModified(); - Long outputModified = outputFile.getLastModified(); - if ((jarModified == null || sourceModified > jarModified) && - ((outputModified != 0 && sourceModified > outputModified) || - (outputModified == 0 && - ((outputModified = sourceModifieds.get(outputFile)) == null || - sourceModified > outputModified)))) { - newSourceFiles.add(sourceFile); - expectedOutputFiles.put(outputFile, className); - sourceModifieds.put(outputFile, sourceModified); - } - } - - if (!newSourceFiles.isEmpty()) { - LOGGER.info("Recompiling {}", newSourceFiles); - - // Compiler can't use the current class loader so try to - // guess all of its class paths. - Set classPaths = new LinkedHashSet(); - for (ClassLoader loader = ObjectUtils.getCurrentClassLoader(); - loader != null; - loader = loader.getParent()) { - if (loader instanceof URLClassLoader) { - for (URL url : ((URLClassLoader) loader).getURLs()) { - File file = IoUtils.toFile(url, StringUtils.UTF_8); - if (file != null) { - classPaths.add(file); - } - } - } - } - - fileManager.setLocation(StandardLocation.CLASS_PATH, classPaths); - DiagnosticCollector diagnostics = new DiagnosticCollector(); - - // Compiler can't process multiple tasks at the same time. - synchronized (COMPILER) { - - // File systems can't usually handle microsecond resolution. - long compileStart = System.currentTimeMillis() / 1000 * 1000; - - if (!COMPILER.getTask(null, fileManager, diagnostics, Arrays.asList("-g"), null, newSourceFiles).call()) { - return diagnostics; - - } else { - Set> enhancerClasses = ObjectUtils.findClasses(ClassEnhancer.class); - - for (JavaFileObject outputFile : fileManager.list( - StandardLocation.CLASS_OUTPUT, - "", - Collections.singleton(JavaFileObject.Kind.CLASS), - true)) { - if (outputFile.getLastModified() < compileStart) { - continue; - } - - InputStream input = outputFile.openInputStream(); - byte[] bytecode; - try { - bytecode = IoUtils.toByteArray(input); - } finally { - input.close(); - } - - byte[] enhancedBytecode = ClassEnhancer.Static.enhance(bytecode, enhancerClasses); - if (enhancedBytecode != null) { - bytecode = enhancedBytecode; - } - - OutputStream output = outputFile.openOutputStream(); - try { - output.write(bytecode); - } finally { - output.close(); - } - - String outputClassName = fileManager.inferBinaryName(StandardLocation.CLASS_OUTPUT, outputFile); - notRedefinedClasses.put(outputClassName, new Date(outputFile.getLastModified())); - - Class outputClass = ObjectUtils.getClassByName(outputClassName); - if (outputClass != null) { - toBeRedefined.add(new ClassDefinition(outputClass, bytecode)); - } - } - - // Try to redefine the classes in place. - List failures = CodeUtils.redefineClasses(toBeRedefined); - toBeRedefined.removeAll(failures); - - for (ClassDefinition success : toBeRedefined) { - notRedefinedClasses.remove(success.getDefinitionClass().getName()); - } - - if (!failures.isEmpty() && LOGGER.isInfoEnabled()) { - StringBuilder messageBuilder = new StringBuilder(); - messageBuilder.append("Can't redefine ["); - for (ClassDefinition failure : failures) { - messageBuilder.append(failure.getDefinitionClass().getName()); - messageBuilder.append(", "); - } - messageBuilder.setLength(messageBuilder.length() - 2); - messageBuilder.append("]!"); - } - } - } - } - - } finally { - fileManager.close(); - } - - // Remember all classes that's changed but not yet redefined. - changedClasses.putAll(notRedefinedClasses); - return null; - } - - /** - * Copies the webapp source associated with the given {@code request}. - * - * @param request Can't be {@code null}. - */ - private void copyWebappSource(HttpServletRequest request) throws IOException { - ServletContext context = getServletContext(); - String path = JspUtils.getCurrentServletPath(request); - if (path.startsWith("/WEB-INF/_draft/")) { - return; - } - - String contextPath = JspUtils.getEmbeddedContextPath(context, path); - File webappSources = webappSourcesMap.get(contextPath); - if (webappSources == null) { - return; - } - - String outputFileString = context.getRealPath(path); - if (outputFileString == null) { - return; - } - - @SuppressWarnings("unchecked") - Set copied = (Set) request.getAttribute(COPIED_ATTRIBUTE); - if (copied == null) { - copied = new HashSet(); - request.setAttribute(COPIED_ATTRIBUTE, copied); - } - if (copied.contains(outputFileString)) { - return; - } else { - copied.add(outputFileString); - } - - File sourceFile = new File(webappSources, path.substring(contextPath.length()).replace('/', File.separatorChar)); - File outputFile = new File(outputFileString); - if (sourceFile.isDirectory() || - outputFile.isDirectory()) { - return; - } - - if (sourceFile.exists()) { - if (!outputFile.exists()) { - IoUtils.createParentDirectories(outputFile); - } else if (sourceFile.lastModified() <= outputFile.lastModified()) { - return; - } - - IoUtils.copy(sourceFile, outputFile); - LOGGER.info("Copied [{}]", sourceFile); - - } else if (outputFile.exists() && - !outputFile.isDirectory()) { - LOGGER.info("[{}] disappeared!", sourceFile); - } - } - - /** {@linkplain SourceFilter} utility methods. */ - public static final class Static { - - /** - * Returns the servlet path for pinging this web application to - * make sure that it's running. - * - * @return Never {@code null}. - */ - public static String getInterceptPingPath() { - return StringUtils.addQueryParameters(getInterceptPath(), "action", "ping"); - } - - /** @deprecated Use {@link CodeUtils#getInstrumentation} instead. */ - @Deprecated - public static Instrumentation getInstrumentation() { - return CodeUtils.getInstrumentation(); - } - } - - /** Installs an web application that can reload other web applications. */ - private class ReloaderInstaller extends HtmlWriter { - - private final HttpServletRequest request; - private final HttpServletResponse response; - - public ReloaderInstaller( - HttpServletRequest request, - HttpServletResponse response) - throws IOException { - - super(response.getWriter()); - this.request = request; - this.response = response; - } - - public void writeStart() throws IOException { - response.setContentType("text/html"); - response.setCharacterEncoding("UTF-8"); - - writeTag("!doctype html"); - writeStart("html"); - writeStart("head"); - - writeStart("title").writeHtml("Installing Reloader").writeEnd(); - - writeStart("link", - "href", JspUtils.getAbsolutePath(request, "/_resource/bootstrap/css/bootstrap.css"), - "rel", "stylesheet", - "type", "text/css"); - writeStart("style", "type", "text/css"); - write(".hero-unit { background: transparent; left: 0; margin: -72px 0 0 60px; padding: 0; position: absolute; top: 50%; }"); - write(".hero-unit h1 { line-height: 1.33; }"); - writeEnd(); - - writeEnd(); - writeStart("body"); - - writeStart("div", "class", "hero-unit"); - writeStart("h1"); - writeHtml("Installing Reloader"); - writeEnd(); - try { - writeStart("ul", "class", "muted"); - try { - flush(); - install(); - writeStart("script", "type", "text/javascript"); - write("location.href = '" + StringUtils.escapeJavaScript( - JspUtils.getAbsolutePath(request, "")) + "';"); - writeEnd(); - } finally { - writeEnd(); - } - } catch (Exception ex) { - writeObject(ex); - } - writeEnd(); - - writeEnd(); - writeEnd(); - } - - private void addProgress(Object... messageParts) throws IOException { - writeStart("li"); - for (int i = 0, length = messageParts.length; i < length; ++ i) { - Object part = messageParts[i]; - if (i % 2 == 0) { - writeHtml(part); - } else { - writeStart("em"); - writeHtml(part); - writeEnd(); - } - } - writeEnd(); - flush(); - } - - private void install() throws IOException { - String catalinaBase = System.getProperty(CATALINA_BASE_PROPERTY); - if (ObjectUtils.isBlank(catalinaBase)) { - throw new IllegalStateException(String.format( - "[%s] system property isn't set!", CATALINA_BASE_PROPERTY)); - } - - URL metadataUrl = new URL(RELOADER_MAVEN_URL + "maven-metadata.xml"); - String metadata = IoUtils.toString(metadataUrl); - addProgress("Looking for it using ", metadataUrl); - - Matcher timestampMatcher = TIMESTAMP_PATTERN.matcher(metadata); - if (!timestampMatcher.find()) { - throw new IllegalStateException("No timestamp in Maven metadata!"); - } - - Matcher buildNumberMatcher = BUILD_NUMBER_PATTERN.matcher(metadata); - if (!buildNumberMatcher.find()) { - throw new IllegalStateException("No build number in Maven metadata!"); - } - - File webappsDirectory = new File(catalinaBase, "webapps"); - File war = File.createTempFile("dari-reloader-", null, webappsDirectory); - try { - - URL warUrl = new URL( - RELOADER_MAVEN_URL + - RELOADER_MAVEN_ARTIFACT_ID + "-" + - RELOADER_MAVEN_VERSION.replace("-SNAPSHOT", "") + "-" + - timestampMatcher.group(1) + "-" + - buildNumberMatcher.group(1) + ".war"); - addProgress("Downloading it from ", warUrl); - addProgress("Saving it to ", war); - - InputStream warInput = warUrl.openStream(); - try { - FileOutputStream warOutput = new FileOutputStream(war); - try { - IoUtils.copy(warInput, warOutput); - } finally { - warOutput.close(); - } - } finally { - warInput.close(); - } - - String reloaderPath = getReloaderPath(); - reloaderPath = reloaderPath.substring(1, reloaderPath.length() - 1); - File reloaderWar = new File(webappsDirectory, reloaderPath + ".war"); - - IoUtils.delete(reloaderWar); - IoUtils.delete(new File(catalinaBase, - "conf" + File.separator + - "Catalina" + File.separator + - "localhost" + File.separator + - reloaderPath + ".xml")); - - addProgress("Deploying it to ", "/" + reloaderPath); - IoUtils.rename(war, reloaderWar); - - for (int i = 0; i < 20; ++ i) { - if (isReloaderAvailable(request)) { - addProgress("Finished!"); - return; - } - - try { - Thread.sleep(2000); - } catch (InterruptedException ex) { - break; - } - } - - throw new IllegalStateException("Can't deploy!"); - - } finally { - IoUtils.delete(war); - } - } - } - - private static class IsolatingResponse extends HttpServletResponseWrapper { - - public final String jsp; - - private final ServletOutputStream output = new IsolatingOutputStream(); - private final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StringUtils.UTF_8)); - - public IsolatingResponse(HttpServletResponse response, String jsp) { - super(response); - this.jsp = jsp; - } - - @Override - public ServletOutputStream getOutputStream() throws IOException { - return output; - } - - @Override - public PrintWriter getWriter() throws IOException { - return writer; - } - } - - private static final class IsolatingOutputStream extends ServletOutputStream { - - @Override - public void write(int b) { - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/old/SourceFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/old/SourceFilter.java deleted file mode 100755 index cf6456f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/old/SourceFilter.java +++ /dev/null @@ -1,969 +0,0 @@ -package com.psddev.dari.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.lang.instrument.ClassDefinition; -import java.lang.instrument.Instrumentation; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLClassLoader; -import java.net.URLConnection; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.servlet.FilterChain; -import javax.servlet.ServletContext; -import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; -import javax.tools.Diagnostic; -import javax.tools.DiagnosticCollector; -import javax.tools.JavaCompiler; -import javax.tools.JavaFileObject; -import javax.tools.StandardJavaFileManager; -import javax.tools.StandardLocation; -import javax.tools.ToolProvider; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Enables rapid web application development by making source code changes - * immediately available. - * - *

To configure, add these definitions to the {@code web.xml} deployment - * descriptor file: - * - *

{@literal
-
-    SourceFilter
-    com.psddev.dari.util.SourceFilter
-
-
-    SourceFilter
-    /*
-
- * }
- * - *

And the application must include a {@code build.properties} file - * that specifies the locations of the source code: - * - *

    - *
  • {@link CodeUtils#JAVA_SOURCE_DIRECTORY_PROPERTY} - *
  • {@link #WEBAPP_SOURCES_PROPERTY} - *
- * - *

You can skip this step if the project uses Apache Maven to manage - * the build and inherits from {@code com.psddev:dari-parent}, because - * that parent POM automatically adds those properties during the - * {@code generate-resources} phase. - */ -public class SourceFilter extends AbstractFilter { - - /** - * Build property that specifies the directory containing the - * web application sources, such as JSPs. - */ - public static final String WEBAPP_SOURCES_PROPERTY = "webappSourceDirectory"; - - public static final String DEFAULT_INTERCEPT_PATH = "/_sourceFilter"; - public static final String INTERCEPT_PATH_SETTING = "dari/sourceFilterInterceptPath"; - - public static final String DEFAULT_RELOADER_PATH = "/reloader/"; - public static final String RELOADER_PATH_SETTING = "dari/sourceFilterReloaderPath"; - public static final String RELOADER_ACTION_PARAMETER = "action"; - public static final String RELOADER_PING_ACTION = "ping"; - public static final String RELOADER_RELOAD_ACTION = "reload"; - public static final String RELOADER_CONTEXT_PATH_PARAMETER = "contextPath"; - public static final String RELOADER_REQUEST_PATH_PARAMETER = "requestPath"; - - private static final JavaCompiler COMPILER = ToolProvider.getSystemJavaCompiler(); - private static final Logger LOGGER = LoggerFactory.getLogger(SourceFilter.class); - - private static final String CLASSES_PATH = "/WEB-INF/classes/"; - private static final String BUILD_PROPERTIES_PATH = "build.properties"; - private static final String ISOLATING_RESPONSE_ATTRIBUTE = SourceFilter.class.getName() + ".isolatingResponse"; - private static final String IS_ISOLATION_DONE_ATTRIBUTE = SourceFilter.class.getName() + ".isIsolationDone"; - private static final String COPIED_ATTRIBUTE = SourceFilter.class.getName() + ".copied"; - - private static final String CATALINA_BASE_PROPERTY = "catalina.base"; - private static final String RELOADER_MAVEN_ARTIFACT_ID = "dari-reloader-tomcat6"; - private static final String RELOADER_MAVEN_VERSION = "2.0-SNAPSHOT"; - private static final String RELOADER_MAVEN_URL = "http://public.psddev.com/maven/com/psddev/" + RELOADER_MAVEN_ARTIFACT_ID + "/" + RELOADER_MAVEN_VERSION + "/"; - private static final Pattern BUILD_NUMBER_PATTERN = Pattern.compile("([^<]*)"); - private static final Pattern TIMESTAMP_PATTERN = Pattern.compile("([^<]*)"); - - private File classOutput; - private final Set javaSourcesSet = new HashSet(); - private final Map webappSourcesMap = new HashMap(); - private final Map sourceModifieds = new HashMap(); - private final Map changedClasses = new TreeMap(); - - // --- AbstractFilter support --- - - @Override - protected void doInit() { - if (COMPILER == null) { - LOGGER.info("Java compiler not available!"); - return; - } - - ServletContext context = getServletContext(); - String classOutputString = context.getRealPath(CLASSES_PATH); - if (classOutputString == null) { - LOGGER.info("Can't get the real path to [{}]!", CLASSES_PATH); - return; - } - - classOutput = new File(classOutputString); - if (classOutput.exists()) { - LOGGER.info("Saving recompiled Java classes to [{}]", classOutput); - } else { - LOGGER.info("[{}] doesn't exist!", classOutput); - classOutput = null; - return; - } - - javaSourcesSet.addAll(CodeUtils.getSourceDirectories()); - - processWarBuildProperties(context, ""); - for (String contextPath : JspUtils.getEmbeddedSettings(context).keySet()) { - processWarBuildProperties(context, contextPath); - } - } - - /** - * Processes the build properties file associated with the given - * {@code context} and {@code contextPath} and adds its source - * directories. - * - * @param context Can't be {@code null}. - * @param contextPath Can't be {@code null}. - */ - private void processWarBuildProperties(ServletContext context, String contextPath) { - InputStream buildPropertiesInput = context.getResourceAsStream(contextPath + CLASSES_PATH + BUILD_PROPERTIES_PATH); - if (buildPropertiesInput == null) { - return; - } - - try { - try { - Properties buildProperties = new Properties(); - buildProperties.load(buildPropertiesInput); - - String javaSourcesString = buildProperties.getProperty(CodeUtils.JAVA_SOURCE_DIRECTORY_PROPERTY); - if (javaSourcesString != null) { - File javaSources = new File(javaSourcesString); - if (javaSources.exists()) { - javaSourcesSet.add(javaSources); - LOGGER.info("Found Java sources in [{}]", javaSources); - } - } - - String webappSourcesString = buildProperties.getProperty(WEBAPP_SOURCES_PROPERTY); - if (webappSourcesString != null) { - File webappSources = new File(webappSourcesString); - if (webappSources.exists()) { - LOGGER.info("Copying webapp sources from [{}] to [{}/]", webappSources, contextPath); - webappSourcesMap.put(contextPath, webappSources); - } - } - - } finally { - buildPropertiesInput.close(); - } - - } catch (IOException error) { - LOGGER.debug("Can't read WAR build properties!", error); - } - } - - @Override - protected void doDestroy() { - classOutput = null; - javaSourcesSet.clear(); - webappSourcesMap.clear(); - sourceModifieds.clear(); - changedClasses.clear(); - } - - @Override - protected void doDispatch( - HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws Exception { - - if (Settings.isProduction()) { - chain.doFilter(request, response); - return; - } - - if (request.getAttribute(IS_ISOLATION_DONE_ATTRIBUTE) != null) { - return; - } - - IsolatingResponse isolatingResponse = (IsolatingResponse) request.getAttribute(ISOLATING_RESPONSE_ATTRIBUTE); - if (isolatingResponse != null) { - if (!JspUtils.getCurrentServletPath(request).equals(isolatingResponse.jsp)) { - isolatingResponse = null; - - } else { - @SuppressWarnings("all") - HtmlWriter html = new HtmlWriter(isolatingResponse.getResponse().getWriter()); - html.putAllStandardDefaults(); - - try { - StringWriter writer = new StringWriter(); - JspUtils.include(request, response, writer, request.getParameter("_draft")); - html.writeStart("pre"); - html.writeHtml(writer.toString().trim()); - html.writeEnd(); - - } catch (Exception ex) { - html.writeStart("pre", "class", "alert alert-error"); - html.writeObject(ex); - html.writeEnd(); - - } finally { - request.setAttribute(IS_ISOLATION_DONE_ATTRIBUTE, Boolean.TRUE); - } - return; - } - } - - copyWebappSource(request); - super.doDispatch(request, response, chain); - } - - @Override - protected void doRequest( - final HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws IOException, ServletException { - - COPY_RESOURCES.get(); - - // Intercept special actions. - if (!ObjectUtils.isBlank(request.getParameter("_reload")) && - isReloaderAvailable(request)) { - compileJavaSources(); - response.sendRedirect(StringUtils.addQueryParameters( - getReloaderPath(), - RELOADER_CONTEXT_PATH_PARAMETER, request.getContextPath(), - RELOADER_REQUEST_PATH_PARAMETER, JspUtils.getAbsolutePath(request, "", "_reload", null), - RELOADER_ACTION_PARAMETER, RELOADER_RELOAD_ACTION)); - return; - } - - String servletPath = request.getServletPath(); - if (servletPath.startsWith(getInterceptPath())) { - String action = request.getParameter("action"); - - if ("ping".equals(action)) { - response.setContentType("text/plain"); - response.setCharacterEncoding("UTF-8"); - response.getWriter().write("OK"); - - } else if ("install".equals(action)) { - if (isReloaderAvailable(request)) { - String requestPath = request.getParameter("requestPath"); - response.sendRedirect(ObjectUtils.isBlank(requestPath) ? "/" : requestPath); - } else { - @SuppressWarnings("all") - ReloaderInstaller installer = new ReloaderInstaller(request, response); - installer.writeStart(); - } - - } else { - throw new IllegalArgumentException(String.format( - "[%s] isn't a valid intercept action!", action)); - } - return; - } - - String contentType = ObjectUtils.getContentType(servletPath); - if (contentType.startsWith("image/") || - contentType.startsWith("video/") || - contentType.equals("text/css") || - contentType.equals("text/javascript")) { - chain.doFilter(request, response); - return; - } - - final DiagnosticCollector errors = compileJavaSources(); - final boolean hasBackgroundTasks; - if (errors == null && - !changedClasses.isEmpty() && - !JspUtils.isAjaxRequest(request)) { - - if (hasBackgroundTasks()) { - hasBackgroundTasks = true; - - } else if (isReloaderAvailable(request)) { - changedClasses.clear(); - response.sendRedirect(StringUtils.addQueryParameters( - getReloaderPath(), - RELOADER_CONTEXT_PATH_PARAMETER, request.getContextPath(), - RELOADER_REQUEST_PATH_PARAMETER, JspUtils.getAbsolutePath(request, ""), - RELOADER_ACTION_PARAMETER, RELOADER_RELOAD_ACTION)); - return; - - } else { - hasBackgroundTasks = false; - } - - } else { - hasBackgroundTasks = false; - } - - IsolatingResponse isolatingResponse = null; - String jsp = request.getParameter("_jsp"); - if (!ObjectUtils.isBlank(jsp)) { - response.setContentType("text/plain"); - isolatingResponse = new IsolatingResponse(response, jsp); - response = isolatingResponse; - request.setAttribute(ISOLATING_RESPONSE_ATTRIBUTE, isolatingResponse); - } - - chain.doFilter(request, response); - if (errors == null && ( - changedClasses.isEmpty() || - JspUtils.isAjaxRequest(request) || - isolatingResponse != null)) { - return; - } - - // Can't reload automatically so at least let the user know - // if viewing an HTML page. - String responseContentType = response.getContentType(); - if (responseContentType == null || - !responseContentType.startsWith("text/html")) { - return; - } - - new HtmlWriter(response.getWriter()) {{ - putDefault(StackTraceElement.class, HtmlFormatter.STACK_TRACE_ELEMENT); - putDefault(Throwable.class, HtmlFormatter.THROWABLE); - - write("

"); - - if (errors == null) { - if (hasBackgroundTasks) { - writeHtml("The application wasn't reloaded automatically because there are background tasks running!"); - - } else { - writeHtml("The application must be reloaded before the changes to these classes become visible. "); - writeStart("a", - "href", JspUtils.getAbsolutePath(request, getInterceptPath(), - "action", "install", - "requestPath", JspUtils.getAbsolutePath(request, "")), - "style", "color: white; text-decoration: underline;"); - writeHtml("Install the reloader"); - writeEnd(); - writeHtml(" to automate this process."); - writeTag("br"); - writeTag("br"); - - for (Map.Entry entry : changedClasses.entrySet()) { - writeHtml(entry.getKey()); - writeHtml(" - "); - writeObject(entry.getValue()); - writeTag("br"); - } - } - - } else { - writeHtml("Syntax errors!"); - writeStart("ol"); - for (Diagnostic diagnostic : errors.getDiagnostics()) { - if (diagnostic.getKind() == Diagnostic.Kind.ERROR) { - writeStart("li", "data-line", diagnostic.getLineNumber(), "data-column", diagnostic.getColumnNumber()); - writeHtml(diagnostic.getMessage(null)); - writeEnd(); - } - } - writeEnd(); - } - - write("
"); - }}; - } - - /** - * Returns the path that intercepts all special actions. - * - * @return Always starts and ends with a slash. - */ - private static String getInterceptPath() { - return StringUtils.ensureStart(Settings.getOrDefault(String.class, INTERCEPT_PATH_SETTING, DEFAULT_INTERCEPT_PATH), "/"); - } - - /** - * Returns the path to the application that can reload this one. - * - * @return Always starts and ends with a slash. - */ - private static String getReloaderPath() { - return StringUtils.ensureSurrounding(Settings.getOrDefault(String.class, RELOADER_PATH_SETTING, DEFAULT_RELOADER_PATH), "/"); - } - - /** - * Returns {@code true} if the reloader is available in the same - * server as this application. - * - * @param request Can't be {@code null}. - */ - private boolean isReloaderAvailable(HttpServletRequest request) { - String servletPath = request.getServletPath(); - String reloaderPath = getReloaderPath(); - - if (!reloaderPath.startsWith(servletPath)) { - try { - URL pingUrl = new URL(StringUtils.addQueryParameters( - JspUtils.getHostUrl(request) + reloaderPath, - RELOADER_ACTION_PARAMETER, RELOADER_PING_ACTION)); - - // To avoid infinite redirects in case the ping hits this - // application. - URLConnection pingConnection = pingUrl.openConnection(); - if (pingConnection instanceof HttpURLConnection) { - ((HttpURLConnection) pingConnection).setInstanceFollowRedirects(false); - } - - InputStream pingInput = pingConnection.getInputStream(); - try { - return "OK".equals(IoUtils.toString(pingInput, StringUtils.UTF_8)); - } finally { - pingInput.close(); - } - - } catch (IOException error) { - // If the ping fails for any reason, assume that the reloader - // isn't available. - } - } - - return false; - } - - /** Returns {@code true} if there are any background tasks running. */ - private boolean hasBackgroundTasks() { - for (TaskExecutor executor : TaskExecutor.Static.getAll()) { - String executorName = executor.getName(); - if (!("Periodic Caches".equals(executorName) || - "Miscellaneous Tasks".equals(executorName))) { - for (Object task : executor.getTasks()) { - if (task instanceof Task && ((Task) task).isRunning()) { - return true; - } - } - } - } - return false; - } - - /** Copies all resources. */ - private final PullThroughValue COPY_RESOURCES = new PullThroughValue() { - - @Override - protected boolean isExpired(Date lastProduce) { - return System.currentTimeMillis() - lastProduce.getTime() > 1000; - } - - @Override - protected Void produce() throws IOException { - if (classOutput != null) { - for (File resourceDirectory : CodeUtils.getResourceDirectories()) { - Long jarModified = CodeUtils.getJarLastModified(resourceDirectory); - copy(resourceDirectory, jarModified, resourceDirectory); - } - } - return null; - } - - private void copy(File resourceDirectory, Long jarModified, File resource) throws IOException { - if (resource.isDirectory()) { - for (File child : resource.listFiles()) { - copy(resourceDirectory, jarModified, child); - } - - } else { - File output = new File(classOutput, resource.toString().substring(resourceDirectory.toString().length()).replace(File.separatorChar, '/')); - - long resourceModified = resource.lastModified(); - long outputModified = output.lastModified(); - if ((jarModified == null || resourceModified > jarModified) && - resourceModified > outputModified) { - IoUtils.copy(resource, output); - LOGGER.info("Copied [{}]", resource); - } - } - } - }; - - /** - * Compile any Java source files that's changed and redefine them - * in place if possible. - */ - private DiagnosticCollector compileJavaSources() throws IOException { - if (javaSourcesSet.isEmpty()) { - return null; - } - - StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(null, null, null); - Set newSourceFiles = new HashSet(); - Map expectedOutputFiles = new HashMap(); - Map notRedefinedClasses = new HashMap(); - List toBeRedefined = new ArrayList(); - - try { - fileManager.setLocation(StandardLocation.SOURCE_PATH, javaSourcesSet); - fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classOutput)); - - for (JavaFileObject sourceFile : fileManager.list( - StandardLocation.SOURCE_PATH, - "", - Collections.singleton(JavaFileObject.Kind.SOURCE), - true)) { - - String className = fileManager.inferBinaryName(StandardLocation.SOURCE_PATH, sourceFile); - JavaFileObject outputFile = fileManager.getJavaFileForOutput( - StandardLocation.CLASS_OUTPUT, - className, - JavaFileObject.Kind.CLASS, - null); - - // Did the source file originate from a JAR? - Long jarModified = null; - String sourcePath = sourceFile.toUri().getPath(); - for (File javaSources : javaSourcesSet) { - if (sourcePath.startsWith(javaSources.getPath())) { - jarModified = CodeUtils.getJarLastModified(javaSources); - break; - } - } - - long sourceModified = sourceFile.getLastModified(); - Long outputModified = outputFile.getLastModified(); - if ((jarModified == null || sourceModified > jarModified) && - ((outputModified != 0 && sourceModified > outputModified) || - (outputModified == 0 && - ((outputModified = sourceModifieds.get(outputFile)) == null || - sourceModified > outputModified)))) { - newSourceFiles.add(sourceFile); - expectedOutputFiles.put(outputFile, className); - sourceModifieds.put(outputFile, sourceModified); - } - } - - if (!newSourceFiles.isEmpty()) { - LOGGER.info("Recompiling {}", newSourceFiles); - - // Compiler can't use the current class loader so try to - // guess all of its class paths. - Set classPaths = new LinkedHashSet(); - for (ClassLoader loader = ObjectUtils.getCurrentClassLoader(); - loader != null; - loader = loader.getParent()) { - if (loader instanceof URLClassLoader) { - for (URL url : ((URLClassLoader) loader).getURLs()) { - File file = IoUtils.toFile(url, StringUtils.UTF_8); - if (file != null) { - classPaths.add(file); - } - } - } - } - - fileManager.setLocation(StandardLocation.CLASS_PATH, classPaths); - DiagnosticCollector diagnostics = new DiagnosticCollector(); - - // Compiler can't process multiple tasks at the same time. - synchronized (COMPILER) { - - // File systems can't usually handle microsecond resolution. - long compileStart = System.currentTimeMillis() / 1000 * 1000; - - if (!COMPILER.getTask(null, fileManager, diagnostics, Arrays.asList("-g"), null, newSourceFiles).call()) { - return diagnostics; - - } else { - Set> enhancerClasses = ObjectUtils.findClasses(ClassEnhancer.class); - - for (JavaFileObject outputFile : fileManager.list( - StandardLocation.CLASS_OUTPUT, - "", - Collections.singleton(JavaFileObject.Kind.CLASS), - true)) { - if (outputFile.getLastModified() < compileStart) { - continue; - } - - InputStream input = outputFile.openInputStream(); - byte[] bytecode; - try { - bytecode = IoUtils.toByteArray(input); - } finally { - input.close(); - } - - byte[] enhancedBytecode = ClassEnhancer.Static.enhance(bytecode, enhancerClasses); - if (enhancedBytecode != null) { - bytecode = enhancedBytecode; - } - - OutputStream output = outputFile.openOutputStream(); - try { - output.write(bytecode); - } finally { - output.close(); - } - - String outputClassName = fileManager.inferBinaryName(StandardLocation.CLASS_OUTPUT, outputFile); - notRedefinedClasses.put(outputClassName, new Date(outputFile.getLastModified())); - - Class outputClass = ObjectUtils.getClassByName(outputClassName); - if (outputClass != null) { - toBeRedefined.add(new ClassDefinition(outputClass, bytecode)); - } - } - - // Try to redefine the classes in place. - List failures = CodeUtils.redefineClasses(toBeRedefined); - toBeRedefined.removeAll(failures); - - for (ClassDefinition success : toBeRedefined) { - notRedefinedClasses.remove(success.getDefinitionClass().getName()); - } - - if (!failures.isEmpty() && LOGGER.isInfoEnabled()) { - StringBuilder messageBuilder = new StringBuilder(); - messageBuilder.append("Can't redefine ["); - for (ClassDefinition failure : failures) { - messageBuilder.append(failure.getDefinitionClass().getName()); - messageBuilder.append(", "); - } - messageBuilder.setLength(messageBuilder.length() - 2); - messageBuilder.append("]!"); - } - } - } - } - - } finally { - fileManager.close(); - } - - // Remember all classes that's changed but not yet redefined. - changedClasses.putAll(notRedefinedClasses); - return null; - } - - /** - * Copies the webapp source associated with the given {@code request}. - * - * @param request Can't be {@code null}. - */ - private void copyWebappSource(HttpServletRequest request) throws IOException { - ServletContext context = getServletContext(); - String path = JspUtils.getCurrentServletPath(request); - if (path.startsWith("/WEB-INF/_draft/")) { - return; - } - - String contextPath = JspUtils.getEmbeddedContextPath(context, path); - File webappSources = webappSourcesMap.get(contextPath); - if (webappSources == null) { - return; - } - - String outputFileString = context.getRealPath(path); - if (outputFileString == null) { - return; - } - - @SuppressWarnings("unchecked") - Set copied = (Set) request.getAttribute(COPIED_ATTRIBUTE); - if (copied == null) { - copied = new HashSet(); - request.setAttribute(COPIED_ATTRIBUTE, copied); - } - if (copied.contains(outputFileString)) { - return; - } else { - copied.add(outputFileString); - } - - File sourceFile = new File(webappSources, path.substring(contextPath.length()).replace('/', File.separatorChar)); - File outputFile = new File(outputFileString); - if (sourceFile.isDirectory() || - outputFile.isDirectory()) { - return; - } - - if (sourceFile.exists()) { - if (!outputFile.exists()) { - IoUtils.createParentDirectories(outputFile); - } else if (sourceFile.lastModified() <= outputFile.lastModified()) { - return; - } - - IoUtils.copy(sourceFile, outputFile); - LOGGER.info("Copied [{}]", sourceFile); - - } else if (outputFile.exists() && - !outputFile.isDirectory()) { - LOGGER.info("[{}] disappeared!", sourceFile); - } - } - - /** {@linkplain SourceFilter} utility methods. */ - public static final class Static { - - /** - * Returns the servlet path for pinging this web application to - * make sure that it's running. - * - * @return Never {@code null}. - */ - public static String getInterceptPingPath() { - return StringUtils.addQueryParameters(getInterceptPath(), "action", "ping"); - } - - /** @deprecated Use {@link CodeUtils#getInstrumentation} instead. */ - @Deprecated - public static Instrumentation getInstrumentation() { - return CodeUtils.getInstrumentation(); - } - } - - /** Installs an web application that can reload other web applications. */ - private class ReloaderInstaller extends HtmlWriter { - - private final HttpServletRequest request; - private final HttpServletResponse response; - - public ReloaderInstaller( - HttpServletRequest request, - HttpServletResponse response) - throws IOException { - - super(response.getWriter()); - this.request = request; - this.response = response; - } - - public void writeStart() throws IOException { - response.setContentType("text/html"); - response.setCharacterEncoding("UTF-8"); - - writeTag("!doctype html"); - writeStart("html"); - writeStart("head"); - - writeStart("title").writeHtml("Installing Reloader").writeEnd(); - - writeStart("link", - "href", JspUtils.getAbsolutePath(request, "/_resource/bootstrap/css/bootstrap.css"), - "rel", "stylesheet", - "type", "text/css"); - writeStart("style", "type", "text/css"); - write(".hero-unit { background: transparent; left: 0; margin: -72px 0 0 60px; padding: 0; position: absolute; top: 50%; }"); - write(".hero-unit h1 { line-height: 1.33; }"); - writeEnd(); - - writeEnd(); - writeStart("body"); - - writeStart("div", "class", "hero-unit"); - writeStart("h1"); - writeHtml("Installing Reloader"); - writeEnd(); - try { - writeStart("ul", "class", "muted"); - try { - flush(); - install(); - writeStart("script", "type", "text/javascript"); - write("location.href = '" + StringUtils.escapeJavaScript( - JspUtils.getAbsolutePath(request, "")) + "';"); - writeEnd(); - } finally { - writeEnd(); - } - } catch (Exception ex) { - writeObject(ex); - } - writeEnd(); - - writeEnd(); - writeEnd(); - } - - private void addProgress(Object... messageParts) throws IOException { - writeStart("li"); - for (int i = 0, length = messageParts.length; i < length; ++ i) { - Object part = messageParts[i]; - if (i % 2 == 0) { - writeHtml(part); - } else { - writeStart("em"); - writeHtml(part); - writeEnd(); - } - } - writeEnd(); - flush(); - } - - private void install() throws IOException { - String catalinaBase = System.getProperty(CATALINA_BASE_PROPERTY); - if (ObjectUtils.isBlank(catalinaBase)) { - throw new IllegalStateException(String.format( - "[%s] system property isn't set!", CATALINA_BASE_PROPERTY)); - } - - URL metadataUrl = new URL(RELOADER_MAVEN_URL + "maven-metadata.xml"); - String metadata = IoUtils.toString(metadataUrl); - addProgress("Looking for it using ", metadataUrl); - - Matcher timestampMatcher = TIMESTAMP_PATTERN.matcher(metadata); - if (!timestampMatcher.find()) { - throw new IllegalStateException("No timestamp in Maven metadata!"); - } - - Matcher buildNumberMatcher = BUILD_NUMBER_PATTERN.matcher(metadata); - if (!buildNumberMatcher.find()) { - throw new IllegalStateException("No build number in Maven metadata!"); - } - - File webappsDirectory = new File(catalinaBase, "webapps"); - File war = File.createTempFile("dari-reloader-", null, webappsDirectory); - try { - - URL warUrl = new URL( - RELOADER_MAVEN_URL + - RELOADER_MAVEN_ARTIFACT_ID + "-" + - RELOADER_MAVEN_VERSION.replace("-SNAPSHOT", "") + "-" + - timestampMatcher.group(1) + "-" + - buildNumberMatcher.group(1) + ".war"); - addProgress("Downloading it from ", warUrl); - addProgress("Saving it to ", war); - - InputStream warInput = warUrl.openStream(); - try { - FileOutputStream warOutput = new FileOutputStream(war); - try { - IoUtils.copy(warInput, warOutput); - } finally { - warOutput.close(); - } - } finally { - warInput.close(); - } - - String reloaderPath = getReloaderPath(); - reloaderPath = reloaderPath.substring(1, reloaderPath.length() - 1); - File reloaderWar = new File(webappsDirectory, reloaderPath + ".war"); - - IoUtils.delete(reloaderWar); - IoUtils.delete(new File(catalinaBase, - "conf" + File.separator + - "Catalina" + File.separator + - "localhost" + File.separator + - reloaderPath + ".xml")); - - addProgress("Deploying it to ", "/" + reloaderPath); - IoUtils.rename(war, reloaderWar); - - for (int i = 0; i < 20; ++ i) { - if (isReloaderAvailable(request)) { - addProgress("Finished!"); - return; - } - - try { - Thread.sleep(2000); - } catch (InterruptedException ex) { - break; - } - } - - throw new IllegalStateException("Can't deploy!"); - - } finally { - IoUtils.delete(war); - } - } - } - - private static class IsolatingResponse extends HttpServletResponseWrapper { - - public final String jsp; - - private final ServletOutputStream output = new IsolatingOutputStream(); - private final PrintWriter writer = new PrintWriter(output); - - public IsolatingResponse(HttpServletResponse response, String jsp) { - super(response); - this.jsp = jsp; - } - - @Override - public ServletOutputStream getOutputStream() throws IOException { - return output; - } - - @Override - public PrintWriter getWriter() throws IOException { - return writer; - } - } - - private static final class IsolatingOutputStream extends ServletOutputStream { - - @Override - public void write(int b) { - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/pair.info deleted file mode 100755 index 81cf571..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52015/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:52015 -comSha:7a9e20fb2b863e37ccee4dbc61cf0eaf0b3c369d -parentComSha:2d3b35e6aac1466d93e5f7829098a195efc59449 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/SourceFilter.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/SourceFilter.java -StartLineNum:945 -EndLineNum:945 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/comMsg.txt deleted file mode 100755 index 4f66f4a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixes all violations of DM_DEFAULT_ENCODING from FindBugs. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/diff.diff deleted file mode 100755 index c7177fd..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/util/src/main/java/com/psddev/dari/util/FrameFilter.java b/util/src/main/java/com/psddev/dari/util/FrameFilter.java -index 67887510..1ab7f341 100644 ---- a/util/src/main/java/com/psddev/dari/util/FrameFilter.java -+++ b/util/src/main/java/com/psddev/dari/util/FrameFilter.java -@@ -3,0 +4 @@ import java.io.IOException; -+import java.io.OutputStreamWriter; -@@ -109 +110 @@ public class FrameFilter extends AbstractFilter { -- private final PrintWriter writer = new PrintWriter(output); -+ private final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StringUtils.UTF_8)); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/new/FrameFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/new/FrameFilter.java deleted file mode 100755 index 1ab7f34..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/new/FrameFilter.java +++ /dev/null @@ -1,134 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; - -public class FrameFilter extends AbstractFilter { - - private static final String PARAMETER_PREFIX = "_frame."; - public static final String PATH_PARAMETER = PARAMETER_PREFIX + "path"; - public static final String NAME_PARAMETER = PARAMETER_PREFIX + "name"; - public static final String LAZY_PARAMETER = PARAMETER_PREFIX + "lazy"; - - private static final String ATTRIBUTE_PREFIX = FrameFilter.class.getName() + "."; - private static final String DISCARDING_RESPONSE_ATTRIBUTE = ATTRIBUTE_PREFIX + "discardingResponse"; - private static final String DISCARDING_DONE_ATTRIBUTE = ATTRIBUTE_PREFIX + "discardingDone"; - public static final String BODY_ATTRIBUTE = ATTRIBUTE_PREFIX + "frameBody"; - - @Override - protected void doRequest( - final HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws IOException, ServletException { - - String path = request.getParameter(PATH_PARAMETER); - - if (ObjectUtils.isBlank(path)) { - chain.doFilter(request, response); - - } else { - DiscardingResponse discarding = new DiscardingResponse(response, path); - - request.setAttribute(DISCARDING_RESPONSE_ATTRIBUTE, discarding); - chain.doFilter(request, discarding); - - ServletResponse headerResponse = JspUtils.getHeaderResponse(request, response); - String name = request.getParameter(NAME_PARAMETER); - - if (headerResponse instanceof HeaderResponse) { - String location = ((HeaderResponse) headerResponse).getHeader("Location"); - - if (location != null) { - response.setHeader("Location", - StringUtils.addQueryParameters(location, - PATH_PARAMETER, path, - NAME_PARAMETER, name)); - return; - } - } - - String body = (String) request.getAttribute(BODY_ATTRIBUTE); - - if (body != null) { - PrintWriter writer = response.getWriter(); - - if (JspUtils.isAjaxRequest(request)) { - response.setContentType("text/plain"); - writer.write(body); - - } else { - response.setContentType("text/html"); - writer.write("
"); - writer.write(StringUtils.escapeHtml(body)); - writer.write("
"); - } - } - } - } - - @Override - protected void doInclude( - HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws Exception { - - if (Boolean.TRUE.equals(request.getAttribute(DISCARDING_DONE_ATTRIBUTE))) { - return; - } - - try { - chain.doFilter(request, response); - - } finally { - DiscardingResponse discarding = (DiscardingResponse) request.getAttribute(DISCARDING_RESPONSE_ATTRIBUTE); - - if (discarding != null && - JspUtils.getCurrentServletPath(request).equals(discarding.donePath)) { - request.setAttribute(DISCARDING_DONE_ATTRIBUTE, Boolean.TRUE); - } - } - } - - private static class DiscardingResponse extends HttpServletResponseWrapper { - - public final String donePath; - - private final ServletOutputStream output = new DiscardingOutputStream(); - private final PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, StringUtils.UTF_8)); - - public DiscardingResponse(HttpServletResponse response, String donePath) { - super(response); - this.donePath = donePath; - } - - @Override - public ServletOutputStream getOutputStream() throws IOException { - return output; - } - - @Override - public PrintWriter getWriter() throws IOException { - return writer; - } - } - - private static final class DiscardingOutputStream extends ServletOutputStream { - - @Override - public void write(int b) { - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/old/FrameFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/old/FrameFilter.java deleted file mode 100755 index 6788751..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/old/FrameFilter.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.psddev.dari.util; - -import java.io.IOException; -import java.io.PrintWriter; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletOutputStream; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpServletResponseWrapper; - -public class FrameFilter extends AbstractFilter { - - private static final String PARAMETER_PREFIX = "_frame."; - public static final String PATH_PARAMETER = PARAMETER_PREFIX + "path"; - public static final String NAME_PARAMETER = PARAMETER_PREFIX + "name"; - public static final String LAZY_PARAMETER = PARAMETER_PREFIX + "lazy"; - - private static final String ATTRIBUTE_PREFIX = FrameFilter.class.getName() + "."; - private static final String DISCARDING_RESPONSE_ATTRIBUTE = ATTRIBUTE_PREFIX + "discardingResponse"; - private static final String DISCARDING_DONE_ATTRIBUTE = ATTRIBUTE_PREFIX + "discardingDone"; - public static final String BODY_ATTRIBUTE = ATTRIBUTE_PREFIX + "frameBody"; - - @Override - protected void doRequest( - final HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws IOException, ServletException { - - String path = request.getParameter(PATH_PARAMETER); - - if (ObjectUtils.isBlank(path)) { - chain.doFilter(request, response); - - } else { - DiscardingResponse discarding = new DiscardingResponse(response, path); - - request.setAttribute(DISCARDING_RESPONSE_ATTRIBUTE, discarding); - chain.doFilter(request, discarding); - - ServletResponse headerResponse = JspUtils.getHeaderResponse(request, response); - String name = request.getParameter(NAME_PARAMETER); - - if (headerResponse instanceof HeaderResponse) { - String location = ((HeaderResponse) headerResponse).getHeader("Location"); - - if (location != null) { - response.setHeader("Location", - StringUtils.addQueryParameters(location, - PATH_PARAMETER, path, - NAME_PARAMETER, name)); - return; - } - } - - String body = (String) request.getAttribute(BODY_ATTRIBUTE); - - if (body != null) { - PrintWriter writer = response.getWriter(); - - if (JspUtils.isAjaxRequest(request)) { - response.setContentType("text/plain"); - writer.write(body); - - } else { - response.setContentType("text/html"); - writer.write("
"); - writer.write(StringUtils.escapeHtml(body)); - writer.write("
"); - } - } - } - } - - @Override - protected void doInclude( - HttpServletRequest request, - HttpServletResponse response, - FilterChain chain) - throws Exception { - - if (Boolean.TRUE.equals(request.getAttribute(DISCARDING_DONE_ATTRIBUTE))) { - return; - } - - try { - chain.doFilter(request, response); - - } finally { - DiscardingResponse discarding = (DiscardingResponse) request.getAttribute(DISCARDING_RESPONSE_ATTRIBUTE); - - if (discarding != null && - JspUtils.getCurrentServletPath(request).equals(discarding.donePath)) { - request.setAttribute(DISCARDING_DONE_ATTRIBUTE, Boolean.TRUE); - } - } - } - - private static class DiscardingResponse extends HttpServletResponseWrapper { - - public final String donePath; - - private final ServletOutputStream output = new DiscardingOutputStream(); - private final PrintWriter writer = new PrintWriter(output); - - public DiscardingResponse(HttpServletResponse response, String donePath) { - super(response); - this.donePath = donePath; - } - - @Override - public ServletOutputStream getOutputStream() throws IOException { - return output; - } - - @Override - public PrintWriter getWriter() throws IOException { - return writer; - } - } - - private static final class DiscardingOutputStream extends ServletOutputStream { - - @Override - public void write(int b) { - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/pair.info deleted file mode 100755 index 5093543..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#52037/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:52037 -comSha:7a9e20fb2b863e37ccee4dbc61cf0eaf0b3c369d -parentComSha:2d3b35e6aac1466d93e5f7829098a195efc59449 -BuggyFilePath:util/src/main/java/com/psddev/dari/util/FrameFilter.java -FixedFilePath:util/src/main/java/com/psddev/dari/util/FrameFilter.java -StartLineNum:109 -EndLineNum:109 -repoName:perfectsense#dari \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/comMsg.txt deleted file mode 100755 index e42fa13..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Merge pull request #170 from jmxtrans/fix-findbugs-errors - -Fixed all Findbugs warnings \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/diff.diff deleted file mode 100755 index 1ab0522..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/com/googlecode/jmxtrans/model/output/OpenTSDBWriter.java b/src/com/googlecode/jmxtrans/model/output/OpenTSDBWriter.java -index 60921cd50..80c488f4f 100644 ---- a/src/com/googlecode/jmxtrans/model/output/OpenTSDBWriter.java -+++ b/src/com/googlecode/jmxtrans/model/output/OpenTSDBWriter.java -@@ -2,0 +3 @@ package com.googlecode.jmxtrans.model.output; -+import com.google.common.base.Charsets; -@@ -14,0 +16,2 @@ import com.googlecode.jmxtrans.util.LifecycleException; -+import static com.google.common.base.Charsets.UTF_8; -+ -@@ -113 +116 @@ public class OpenTSDBWriter extends OpenTSDBGenericWriter { -- InputStreamReader socketInputStream = new InputStreamReader(socket.getInputStream()); -+ InputStreamReader socketInputStream = new InputStreamReader(socket.getInputStream(), UTF_8); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/new/OpenTSDBWriter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/new/OpenTSDBWriter.java deleted file mode 100755 index 80c488f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/new/OpenTSDBWriter.java +++ /dev/null @@ -1,123 +0,0 @@ -package com.googlecode.jmxtrans.model.output; - -import com.google.common.base.Charsets; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.googlecode.jmxtrans.util.LifecycleException; - -import static com.google.common.base.Charsets.UTF_8; - -/** - * OpenTSDBWriter which directly sends - *

- * Created from sources originally written by Balazs Kossovics - */ - -public class OpenTSDBWriter extends OpenTSDBGenericWriter { - private static final Logger log = LoggerFactory.getLogger(OpenTSDBWriter.class); - - protected Socket socket; - protected DataOutputStream out; - - /** - * Add the hostname tag "host" with the name of the host by default since OpenTSDB otherwise does not have this - * information. - */ - @Override - protected boolean getAddHostnameTagDefault() { - return true; - } - - /** - * Prepare for sending metrics. - */ - @Override - protected void prepareSender() throws LifecycleException { - - if (host == null || port == null) { - throw new LifecycleException("Host and port for " + this.getClass().getSimpleName() + " output can't be null"); - } - - try { - socket = new Socket(host, port); - } catch (UnknownHostException e) { - log.error("error opening socket to OpenTSDB", e); - throw new LifecycleException(e); - } catch (IOException e) { - log.error("error opening socket to OpenTSDB", e); - throw new LifecycleException(e); - } - } - - /** - * Shutdown the sender as it will no longer be used to send metrics. - */ - @Override - protected void shutdownSender() throws LifecycleException { - try { - socket.close(); - } catch (IOException e) { - log.error("error closing socket to OpenTSDB", e); - throw new LifecycleException(e); - } - } - - /** - * Start the output for the results of a Query to OpenTSDB. - */ - @Override - protected void startOutput() throws IOException { - try { - this.out = new DataOutputStream(socket.getOutputStream()); - } catch (IOException e) { - log.error("error getting the output stream", e); - throw e; - } - } - - /** - * Send a single metric to the server. - * - * @param metricLine - the line containing the metric name, value, and tags for a single metric; excludes the - * "put" keyword expected by OpenTSDB and the trailing newline character. - */ - @Override - protected void sendOutput(String metricLine) throws IOException { - try { - this.out.writeBytes("put " + metricLine + "\n"); - } catch (IOException e) { - log.error("error writing result to the output stream", e); - throw e; - } - } - - /** - * Finish the output for a single Query, flushing all data to the server and logging the server's response. - */ - @Override - protected void finishOutput() throws IOException { - try { - this.out.flush(); - } catch (IOException e) { - log.error("flush failed", e); - throw e; - } - - // Read and log the response from the server for diagnostic purposes. - - InputStreamReader socketInputStream = new InputStreamReader(socket.getInputStream(), UTF_8); - BufferedReader bufferedSocketInputStream = new BufferedReader(socketInputStream); - String line; - while (socketInputStream.ready() && (line = bufferedSocketInputStream.readLine()) != null) { - log.warn("OpenTSDB says: " + line); - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/old/OpenTSDBWriter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/old/OpenTSDBWriter.java deleted file mode 100755 index 60921cd..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/old/OpenTSDBWriter.java +++ /dev/null @@ -1,120 +0,0 @@ -package com.googlecode.jmxtrans.model.output; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.BufferedReader; -import java.io.DataOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.Socket; -import java.net.UnknownHostException; - -import com.googlecode.jmxtrans.util.LifecycleException; - -/** - * OpenTSDBWriter which directly sends - *

- * Created from sources originally written by Balazs Kossovics - */ - -public class OpenTSDBWriter extends OpenTSDBGenericWriter { - private static final Logger log = LoggerFactory.getLogger(OpenTSDBWriter.class); - - protected Socket socket; - protected DataOutputStream out; - - /** - * Add the hostname tag "host" with the name of the host by default since OpenTSDB otherwise does not have this - * information. - */ - @Override - protected boolean getAddHostnameTagDefault() { - return true; - } - - /** - * Prepare for sending metrics. - */ - @Override - protected void prepareSender() throws LifecycleException { - - if (host == null || port == null) { - throw new LifecycleException("Host and port for " + this.getClass().getSimpleName() + " output can't be null"); - } - - try { - socket = new Socket(host, port); - } catch (UnknownHostException e) { - log.error("error opening socket to OpenTSDB", e); - throw new LifecycleException(e); - } catch (IOException e) { - log.error("error opening socket to OpenTSDB", e); - throw new LifecycleException(e); - } - } - - /** - * Shutdown the sender as it will no longer be used to send metrics. - */ - @Override - protected void shutdownSender() throws LifecycleException { - try { - socket.close(); - } catch (IOException e) { - log.error("error closing socket to OpenTSDB", e); - throw new LifecycleException(e); - } - } - - /** - * Start the output for the results of a Query to OpenTSDB. - */ - @Override - protected void startOutput() throws IOException { - try { - this.out = new DataOutputStream(socket.getOutputStream()); - } catch (IOException e) { - log.error("error getting the output stream", e); - throw e; - } - } - - /** - * Send a single metric to the server. - * - * @param metricLine - the line containing the metric name, value, and tags for a single metric; excludes the - * "put" keyword expected by OpenTSDB and the trailing newline character. - */ - @Override - protected void sendOutput(String metricLine) throws IOException { - try { - this.out.writeBytes("put " + metricLine + "\n"); - } catch (IOException e) { - log.error("error writing result to the output stream", e); - throw e; - } - } - - /** - * Finish the output for a single Query, flushing all data to the server and logging the server's response. - */ - @Override - protected void finishOutput() throws IOException { - try { - this.out.flush(); - } catch (IOException e) { - log.error("flush failed", e); - throw e; - } - - // Read and log the response from the server for diagnostic purposes. - - InputStreamReader socketInputStream = new InputStreamReader(socket.getInputStream()); - BufferedReader bufferedSocketInputStream = new BufferedReader(socketInputStream); - String line; - while (socketInputStream.ready() && (line = bufferedSocketInputStream.readLine()) != null) { - log.warn("OpenTSDB says: " + line); - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/pair.info deleted file mode 100755 index 17bc4ca..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53428/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:53428 -comSha:c644d2145d5d4f59f234bffaa61d11ec7ee94c3b -parentComSha:a2285f07035c3c68b727d16453cc5f3ee66ee672 -BuggyFilePath:src/com/googlecode/jmxtrans/model/output/OpenTSDBWriter.java -FixedFilePath:src/com/googlecode/jmxtrans/model/output/OpenTSDBWriter.java -StartLineNum:113 -EndLineNum:113 -repoName:jmxtrans#jmxtrans \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/comMsg.txt deleted file mode 100755 index e42fa13..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Merge pull request #170 from jmxtrans/fix-findbugs-errors - -Fixed all Findbugs warnings \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/diff.diff deleted file mode 100755 index 40e2f46..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java b/src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java -index c0b4cf281..ac74a46f1 100644 ---- a/src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java -+++ b/src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java -@@ -2,0 +3 @@ package com.googlecode.jmxtrans.model.output; -+import com.google.common.base.Charsets; -@@ -9,0 +11 @@ import javax.management.ObjectName; -+import java.io.OutputStreamWriter; -@@ -33,0 +36,2 @@ import com.googlecode.jmxtrans.util.ValidationException; -+import static com.google.common.base.Charsets.UTF_8; -+ -@@ -153 +157 @@ public class GraphiteWriter extends BaseOutputWriter { -- PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); -+ PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/new/GraphiteWriter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/new/GraphiteWriter.java deleted file mode 100755 index ac74a46..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/new/GraphiteWriter.java +++ /dev/null @@ -1,243 +0,0 @@ -package com.googlecode.jmxtrans.model.output; - -import com.google.common.base.Charsets; -import org.apache.commons.pool.KeyedObjectPool; -import org.apache.commons.pool.impl.GenericKeyedObjectPool; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.management.MBeanServer; -import javax.management.ObjectName; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.lang.management.ManagementFactory; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import com.googlecode.jmxtrans.jmx.ManagedGenericKeyedObjectPool; -import com.googlecode.jmxtrans.jmx.ManagedObject; -import com.googlecode.jmxtrans.model.Query; -import com.googlecode.jmxtrans.model.Result; -import com.googlecode.jmxtrans.model.Server; -import com.googlecode.jmxtrans.util.BaseOutputWriter; -import com.googlecode.jmxtrans.util.JmxUtils; -import com.googlecode.jmxtrans.util.LifecycleException; -import com.googlecode.jmxtrans.util.NumberUtils; -import com.googlecode.jmxtrans.util.SocketFactory; -import com.googlecode.jmxtrans.util.ValidationException; - -import static com.google.common.base.Charsets.UTF_8; - -/** - * This low latency and thread save output writer sends data to a host/port combination - * in the Graphite format. - * - * @see http://graphite.wikidot.com/getting-your-data-into-graphite - * - * @author jon - */ -public class GraphiteWriter extends BaseOutputWriter { - - private static final Logger log = LoggerFactory.getLogger(GraphiteWriter.class); - public static final String ROOT_PREFIX = "rootPrefix"; - - private String host; - private Integer port; - private String rootPrefix = "servers"; - - private static KeyedObjectPool pool = null; - private static AtomicInteger activeServers = new AtomicInteger(0); - - private Lock statusLock = new ReentrantLock(); - private Condition statusConditionStarted = statusLock.newCondition(); - private Condition statusConditionStopped = statusLock.newCondition(); - private GraphiteWriterStatus status = GraphiteWriterStatus.STOPPED; - - private ManagedObject mbean; - private InetSocketAddress address; - - /** - * Uses JmxUtils.getDefaultPoolMap() - */ - public GraphiteWriter() { } - - /** - * If pool already started, just increase number of activeServers, - * if it is not, start the pool and register it on JMX - */ - @Override - public void start() throws LifecycleException { - statusLock.lock(); - try { - if (status != GraphiteWriterStatus.STOPPED) { - throw new LifecycleException("GraphiteWriter instance should be stopped"); - } - - int activeServersLocal = activeServers.incrementAndGet(); - - // Start the pool when the first instance starts - if (activeServersLocal == 1) { - startPool(); - } - - status = GraphiteWriterStatus.STARTED; - statusConditionStarted.signal(); - } finally { - statusLock.unlock(); - } - } - - @Override - public void stop() throws LifecycleException { - statusLock.lock(); - try { - if (status != GraphiteWriterStatus.STARTED) { - throw new LifecycleException("GraphiteWriter instance shold be started"); - } - - // Stop the pool if there is no more started instances - if(activeServers.decrementAndGet() == 0) { - stopPool(); - } - - status = GraphiteWriterStatus.STOPPED; - statusConditionStopped.signal(); - } finally { - statusLock.unlock(); - } - } - - /** */ - public void validateSetup(Query query) throws ValidationException { - host = (String) this.getSettings().get(HOST); - Object portObj = this.getSettings().get(PORT); - if (portObj instanceof String) { - port = Integer.parseInt((String) portObj); - } else if (portObj instanceof Integer) { - port = (Integer) portObj; - } - - if (host == null || port == null) { - throw new ValidationException("Host and port can't be null", query); - } - - String rootPrefixTmp = (String) this.getSettings().get(ROOT_PREFIX); - if (rootPrefixTmp != null) { - rootPrefix = rootPrefixTmp; - } - - this.address = new InetSocketAddress(host, port); - } - - /** */ - public void doWrite(Query query) throws Exception { - Socket socket = null; - statusLock.lock(); - try { - while (status == GraphiteWriterStatus.STARTING) { - statusConditionStarted.await(); - } - if (status != GraphiteWriterStatus.STARTED) { - throw new LifecycleException("GraphiteWriter instance should be started"); - } - socket = (Socket) pool.borrowObject(address); - } finally { - statusLock.unlock(); - } - - try { - PrintWriter writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), UTF_8), true); - - List typeNames = this.getTypeNames(); - - for (Result result : query.getResults()) { - if (isDebugEnabled()) { - log.debug("Query result: " + result.toString()); - } - Map resultValues = result.getValues(); - if (resultValues != null) { - for (Entry values : resultValues.entrySet()) { - Object value = values.getValue(); - if (NumberUtils.isNumeric(value)) { - StringBuilder sb = new StringBuilder(); - - sb.append(JmxUtils.getKeyString(query, result, values, typeNames, rootPrefix).replaceAll("[()]", "_")); - - sb.append(" "); - sb.append(value.toString()); - sb.append(" "); - sb.append(result.getEpoch() / 1000); - sb.append("\n"); - - String line = sb.toString(); - if (isDebugEnabled()) { - log.debug("Graphite Message: " + line.trim()); - } - writer.write(line); - writer.flush(); - } else { - if (log.isWarnEnabled()) { - log.warn("Unable to submit non-numeric value to Graphite: \"" + value + "\" from result " + result); - } - } - } - } - } - } finally { - pool.returnObject(address, socket); - } - } - - /** - * Starts the pool and register it with JMX - * - * @throws LifecycleException - */ - private void startPool() throws LifecycleException { - pool = JmxUtils.getObjectPool(new SocketFactory()); - - try { - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - ObjectName objectName = new ObjectName("com.googlecode.jmxtrans:Type=GenericKeyedObjectPool,PoolName=SocketFactory,Name=GWManagedGenericKeyedObjectPool"); - - if (!mbs.isRegistered(objectName) ) { - this.mbean = new ManagedGenericKeyedObjectPool((GenericKeyedObjectPool)pool, Server.SOCKET_FACTORY_POOL); - this.mbean.setObjectName(objectName); - JmxUtils.registerJMX(this.mbean); - } - log.debug("GraptiteWriter connection pool is started"); - } catch (Exception e) { - throw new LifecycleException(e); - } - } - - /** - * Stops the pool and removes it from JMX - * - * @throws LifecycleException - */ - private void stopPool() throws LifecycleException { - try { - if (this.mbean != null) { - JmxUtils.unregisterJMX(this.mbean); - this.mbean = null; - } - if (pool != null) { - pool.close(); - pool = null; - } - log.debug("GraptiteWriter connection pool is stopped"); - } catch (Exception e) { - throw new LifecycleException(e); - } - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/old/GraphiteWriter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/old/GraphiteWriter.java deleted file mode 100755 index c0b4cf2..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/old/GraphiteWriter.java +++ /dev/null @@ -1,239 +0,0 @@ -package com.googlecode.jmxtrans.model.output; - -import org.apache.commons.pool.KeyedObjectPool; -import org.apache.commons.pool.impl.GenericKeyedObjectPool; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.management.MBeanServer; -import javax.management.ObjectName; -import java.io.PrintWriter; -import java.lang.management.ManagementFactory; -import java.net.InetSocketAddress; -import java.net.Socket; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - -import com.googlecode.jmxtrans.jmx.ManagedGenericKeyedObjectPool; -import com.googlecode.jmxtrans.jmx.ManagedObject; -import com.googlecode.jmxtrans.model.Query; -import com.googlecode.jmxtrans.model.Result; -import com.googlecode.jmxtrans.model.Server; -import com.googlecode.jmxtrans.util.BaseOutputWriter; -import com.googlecode.jmxtrans.util.JmxUtils; -import com.googlecode.jmxtrans.util.LifecycleException; -import com.googlecode.jmxtrans.util.NumberUtils; -import com.googlecode.jmxtrans.util.SocketFactory; -import com.googlecode.jmxtrans.util.ValidationException; - -/** - * This low latency and thread save output writer sends data to a host/port combination - * in the Graphite format. - * - * @see http://graphite.wikidot.com/getting-your-data-into-graphite - * - * @author jon - */ -public class GraphiteWriter extends BaseOutputWriter { - - private static final Logger log = LoggerFactory.getLogger(GraphiteWriter.class); - public static final String ROOT_PREFIX = "rootPrefix"; - - private String host; - private Integer port; - private String rootPrefix = "servers"; - - private static KeyedObjectPool pool = null; - private static AtomicInteger activeServers = new AtomicInteger(0); - - private Lock statusLock = new ReentrantLock(); - private Condition statusConditionStarted = statusLock.newCondition(); - private Condition statusConditionStopped = statusLock.newCondition(); - private GraphiteWriterStatus status = GraphiteWriterStatus.STOPPED; - - private ManagedObject mbean; - private InetSocketAddress address; - - /** - * Uses JmxUtils.getDefaultPoolMap() - */ - public GraphiteWriter() { } - - /** - * If pool already started, just increase number of activeServers, - * if it is not, start the pool and register it on JMX - */ - @Override - public void start() throws LifecycleException { - statusLock.lock(); - try { - if (status != GraphiteWriterStatus.STOPPED) { - throw new LifecycleException("GraphiteWriter instance should be stopped"); - } - - int activeServersLocal = activeServers.incrementAndGet(); - - // Start the pool when the first instance starts - if (activeServersLocal == 1) { - startPool(); - } - - status = GraphiteWriterStatus.STARTED; - statusConditionStarted.signal(); - } finally { - statusLock.unlock(); - } - } - - @Override - public void stop() throws LifecycleException { - statusLock.lock(); - try { - if (status != GraphiteWriterStatus.STARTED) { - throw new LifecycleException("GraphiteWriter instance shold be started"); - } - - // Stop the pool if there is no more started instances - if(activeServers.decrementAndGet() == 0) { - stopPool(); - } - - status = GraphiteWriterStatus.STOPPED; - statusConditionStopped.signal(); - } finally { - statusLock.unlock(); - } - } - - /** */ - public void validateSetup(Query query) throws ValidationException { - host = (String) this.getSettings().get(HOST); - Object portObj = this.getSettings().get(PORT); - if (portObj instanceof String) { - port = Integer.parseInt((String) portObj); - } else if (portObj instanceof Integer) { - port = (Integer) portObj; - } - - if (host == null || port == null) { - throw new ValidationException("Host and port can't be null", query); - } - - String rootPrefixTmp = (String) this.getSettings().get(ROOT_PREFIX); - if (rootPrefixTmp != null) { - rootPrefix = rootPrefixTmp; - } - - this.address = new InetSocketAddress(host, port); - } - - /** */ - public void doWrite(Query query) throws Exception { - Socket socket = null; - statusLock.lock(); - try { - while (status == GraphiteWriterStatus.STARTING) { - statusConditionStarted.await(); - } - if (status != GraphiteWriterStatus.STARTED) { - throw new LifecycleException("GraphiteWriter instance should be started"); - } - socket = (Socket) pool.borrowObject(address); - } finally { - statusLock.unlock(); - } - - try { - PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); - - List typeNames = this.getTypeNames(); - - for (Result result : query.getResults()) { - if (isDebugEnabled()) { - log.debug("Query result: " + result.toString()); - } - Map resultValues = result.getValues(); - if (resultValues != null) { - for (Entry values : resultValues.entrySet()) { - Object value = values.getValue(); - if (NumberUtils.isNumeric(value)) { - StringBuilder sb = new StringBuilder(); - - sb.append(JmxUtils.getKeyString(query, result, values, typeNames, rootPrefix).replaceAll("[()]", "_")); - - sb.append(" "); - sb.append(value.toString()); - sb.append(" "); - sb.append(result.getEpoch() / 1000); - sb.append("\n"); - - String line = sb.toString(); - if (isDebugEnabled()) { - log.debug("Graphite Message: " + line.trim()); - } - writer.write(line); - writer.flush(); - } else { - if (log.isWarnEnabled()) { - log.warn("Unable to submit non-numeric value to Graphite: \"" + value + "\" from result " + result); - } - } - } - } - } - } finally { - pool.returnObject(address, socket); - } - } - - /** - * Starts the pool and register it with JMX - * - * @throws LifecycleException - */ - private void startPool() throws LifecycleException { - pool = JmxUtils.getObjectPool(new SocketFactory()); - - try { - MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); - ObjectName objectName = new ObjectName("com.googlecode.jmxtrans:Type=GenericKeyedObjectPool,PoolName=SocketFactory,Name=GWManagedGenericKeyedObjectPool"); - - if (!mbs.isRegistered(objectName) ) { - this.mbean = new ManagedGenericKeyedObjectPool((GenericKeyedObjectPool)pool, Server.SOCKET_FACTORY_POOL); - this.mbean.setObjectName(objectName); - JmxUtils.registerJMX(this.mbean); - } - log.debug("GraptiteWriter connection pool is started"); - } catch (Exception e) { - throw new LifecycleException(e); - } - } - - /** - * Stops the pool and removes it from JMX - * - * @throws LifecycleException - */ - private void stopPool() throws LifecycleException { - try { - if (this.mbean != null) { - JmxUtils.unregisterJMX(this.mbean); - this.mbean = null; - } - if (pool != null) { - pool.close(); - pool = null; - } - log.debug("GraptiteWriter connection pool is stopped"); - } catch (Exception e) { - throw new LifecycleException(e); - } - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/pair.info deleted file mode 100755 index 2b70d89..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#53431/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:53431 -comSha:c644d2145d5d4f59f234bffaa61d11ec7ee94c3b -parentComSha:a2285f07035c3c68b727d16453cc5f3ee66ee672 -BuggyFilePath:src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java -FixedFilePath:src/com/googlecode/jmxtrans/model/output/GraphiteWriter.java -StartLineNum:153 -EndLineNum:153 -repoName:jmxtrans#jmxtrans \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/comMsg.txt deleted file mode 100755 index 52374e0..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix warning reported by FindBugs tool \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/diff.diff deleted file mode 100755 index 9049710..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/org/traccar/api/SecurityRequestFilter.java b/src/org/traccar/api/SecurityRequestFilter.java -index b1e09048..63295a8b 100644 ---- a/src/org/traccar/api/SecurityRequestFilter.java -+++ b/src/org/traccar/api/SecurityRequestFilter.java -@@ -20,0 +21 @@ import org.traccar.model.User; -+import java.nio.charset.Charset; -@@ -38 +39 @@ public class SecurityRequestFilter implements ContainerRequestFilter { -- return new String(decodedBytes).split(":", 2); -+ return new String(decodedBytes, Charset.defaultCharset()).split(":", 2); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/new/SecurityRequestFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/new/SecurityRequestFilter.java deleted file mode 100755 index 63295a8..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/new/SecurityRequestFilter.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.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. - */ -package org.traccar.api; - -import org.traccar.Context; -import org.traccar.model.User; - -import java.nio.charset.Charset; -import java.sql.SQLException; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; - -public class SecurityRequestFilter implements ContainerRequestFilter { - - public static final String AUTHORIZATION_HEADER = "Authorization"; - public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; - public static final String BASIC_REALM = "Basic realm=\"api\""; - - public static String[] decodeBasicAuth(String auth) { - auth = auth.replaceFirst("[B|b]asic ", ""); - byte[] decodedBytes = DatatypeConverter.parseBase64Binary(auth); - if (decodedBytes != null && decodedBytes.length > 0) { - return new String(decodedBytes, Charset.defaultCharset()).split(":", 2); - } - return null; - } - - @Override - public void filter(ContainerRequestContext requestContext) { - try { - String[] auth = decodeBasicAuth(requestContext.getHeaderString(AUTHORIZATION_HEADER)); - User user = Context.getDataManager().login(auth[0], auth[1]); - if (user != null) { - requestContext.setSecurityContext( - new UserSecurityContext(new UserPrincipal(user.getId(), user.getName()))); - } else { - throw new WebApplicationException( - Response.status(Response.Status.UNAUTHORIZED).header(WWW_AUTHENTICATE, BASIC_REALM).build()); - } - } catch (SQLException e) { - throw new WebApplicationException(e); - } - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/old/SecurityRequestFilter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/old/SecurityRequestFilter.java deleted file mode 100755 index b1e0904..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/old/SecurityRequestFilter.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.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. - */ -package org.traccar.api; - -import org.traccar.Context; -import org.traccar.model.User; - -import java.sql.SQLException; -import javax.ws.rs.WebApplicationException; -import javax.ws.rs.container.ContainerRequestContext; -import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Response; -import javax.xml.bind.DatatypeConverter; - -public class SecurityRequestFilter implements ContainerRequestFilter { - - public static final String AUTHORIZATION_HEADER = "Authorization"; - public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; - public static final String BASIC_REALM = "Basic realm=\"api\""; - - public static String[] decodeBasicAuth(String auth) { - auth = auth.replaceFirst("[B|b]asic ", ""); - byte[] decodedBytes = DatatypeConverter.parseBase64Binary(auth); - if (decodedBytes != null && decodedBytes.length > 0) { - return new String(decodedBytes).split(":", 2); - } - return null; - } - - @Override - public void filter(ContainerRequestContext requestContext) { - try { - String[] auth = decodeBasicAuth(requestContext.getHeaderString(AUTHORIZATION_HEADER)); - User user = Context.getDataManager().login(auth[0], auth[1]); - if (user != null) { - requestContext.setSecurityContext( - new UserSecurityContext(new UserPrincipal(user.getId(), user.getName()))); - } else { - throw new WebApplicationException( - Response.status(Response.Status.UNAUTHORIZED).header(WWW_AUTHENTICATE, BASIC_REALM).build()); - } - } catch (SQLException e) { - throw new WebApplicationException(e); - } - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/pair.info deleted file mode 100755 index 9686a70..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68702/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:68702 -comSha:53f70085891cdb0feae56df8990c1245091352a1 -parentComSha:4ed22fb839fab2f19a6220bb8540317521209c4a -BuggyFilePath:src/org/traccar/api/SecurityRequestFilter.java -FixedFilePath:src/org/traccar/api/SecurityRequestFilter.java -StartLineNum:38 -EndLineNum:38 -repoName:tananaev#traccar \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/comMsg.txt deleted file mode 100755 index d74f8f4..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix some FindBugs and style issues \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/diff.diff deleted file mode 100755 index 9e81e12..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/org/traccar/protocol/Gt06ProtocolEncoder.java b/src/org/traccar/protocol/Gt06ProtocolEncoder.java -index f5b914b1..f518d422 100644 ---- a/src/org/traccar/protocol/Gt06ProtocolEncoder.java -+++ b/src/org/traccar/protocol/Gt06ProtocolEncoder.java -@@ -23,0 +24,2 @@ import org.traccar.model.Command; -+import java.nio.charset.Charset; -+ -@@ -39 +41 @@ public class Gt06ProtocolEncoder extends BaseProtocolEncoder { -- buf.writeBytes(content.getBytes()); // command -+ buf.writeBytes(content.getBytes(Charset.defaultCharset())); // command \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/new/Gt06ProtocolEncoder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/new/Gt06ProtocolEncoder.java deleted file mode 100755 index f518d42..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/new/Gt06ProtocolEncoder.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.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. - */ -package org.traccar.protocol; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.traccar.BaseProtocolEncoder; -import org.traccar.helper.Checksum; -import org.traccar.model.Command; - -import java.nio.charset.Charset; - -public class Gt06ProtocolEncoder extends BaseProtocolEncoder { - - private ChannelBuffer encodeContent(String content) { - - ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); - - buf.writeByte(0x78); - buf.writeByte(0x78); - - buf.writeByte(1 + 1 + 4 + content.length() + 2 + 2); // message length - - buf.writeByte(0x80); // message type - - buf.writeByte(4 + content.length()); // command length - buf.writeInt(0); - buf.writeBytes(content.getBytes(Charset.defaultCharset())); // command - - buf.writeShort(0); // message index - - buf.writeShort(Checksum.crc16(Checksum.CRC16_X25, buf.toByteBuffer(2, buf.writerIndex() - 2))); - - buf.writeByte('\r'); - buf.writeByte('\n'); - - return buf; - } - - @Override - protected Object encodeCommand(Command command) { - - switch (command.getType()) { - case Command.TYPE_ENGINE_STOP: - return encodeContent("Relay,1#"); - case Command.TYPE_ENGINE_RESUME: - return encodeContent("Relay,0#"); - } - - return null; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/old/Gt06ProtocolEncoder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/old/Gt06ProtocolEncoder.java deleted file mode 100755 index f5b914b..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/old/Gt06ProtocolEncoder.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2015 Anton Tananaev (anton.tananaev@gmail.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. - */ -package org.traccar.protocol; - -import org.jboss.netty.buffer.ChannelBuffer; -import org.jboss.netty.buffer.ChannelBuffers; -import org.traccar.BaseProtocolEncoder; -import org.traccar.helper.Checksum; -import org.traccar.model.Command; - -public class Gt06ProtocolEncoder extends BaseProtocolEncoder { - - private ChannelBuffer encodeContent(String content) { - - ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); - - buf.writeByte(0x78); - buf.writeByte(0x78); - - buf.writeByte(1 + 1 + 4 + content.length() + 2 + 2); // message length - - buf.writeByte(0x80); // message type - - buf.writeByte(4 + content.length()); // command length - buf.writeInt(0); - buf.writeBytes(content.getBytes()); // command - - buf.writeShort(0); // message index - - buf.writeShort(Checksum.crc16(Checksum.CRC16_X25, buf.toByteBuffer(2, buf.writerIndex() - 2))); - - buf.writeByte('\r'); - buf.writeByte('\n'); - - return buf; - } - - @Override - protected Object encodeCommand(Command command) { - - switch (command.getType()) { - case Command.TYPE_ENGINE_STOP: - return encodeContent("Relay,1#"); - case Command.TYPE_ENGINE_RESUME: - return encodeContent("Relay,0#"); - } - - return null; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/pair.info deleted file mode 100755 index 25c2a74..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#68852/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:68852 -comSha:81a7fba08c37fd8032c747ada5d9a77340298647 -parentComSha:8e555ab17b231d93ab51713d6cb25510c0f92476 -BuggyFilePath:src/org/traccar/protocol/Gt06ProtocolEncoder.java -FixedFilePath:src/org/traccar/protocol/Gt06ProtocolEncoder.java -StartLineNum:39 -EndLineNum:39 -repoName:tananaev#traccar \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/comMsg.txt deleted file mode 100755 index b6312f9..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixed some small code issues \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/diff.diff deleted file mode 100755 index b2dbb8f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/geom/src/main/java/com/github/rinde/rinsim/geom/io/AbstractGraphIO.java b/geom/src/main/java/com/github/rinde/rinsim/geom/io/AbstractGraphIO.java -index 12fb80c2..3e2a8191 100644 ---- a/geom/src/main/java/com/github/rinde/rinsim/geom/io/AbstractGraphIO.java -+++ b/geom/src/main/java/com/github/rinde/rinsim/geom/io/AbstractGraphIO.java -@@ -45 +45 @@ public abstract class AbstractGraphIO { -- abstract public Graph read(Reader reader) throws IOException; -+ public abstract Graph read(Reader reader) throws IOException; -@@ -64 +64 @@ public abstract class AbstractGraphIO { -- return readReader(new InputStreamReader(stream)); -+ return readReader(new InputStreamReader(stream, Charsets.UTF_8)); -@@ -83 +83 @@ public abstract class AbstractGraphIO { -- abstract public void write(Graph graph, Writer writer) -+ public abstract void write(Graph graph, Writer writer) \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/new/AbstractGraphIO.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/new/AbstractGraphIO.java deleted file mode 100755 index 3e2a819..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/new/AbstractGraphIO.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2011-2015 Rinde van Lon, iMinds-DistriNet, KU Leuven - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.github.rinde.rinsim.geom.io; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.Writer; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.Path; - -import com.github.rinde.rinsim.geom.ConnectionData; -import com.github.rinde.rinsim.geom.Graph; -import com.google.common.base.Charsets; - -/** - * Common abstract class for graph input and output operations. - * @param Type of connection data. - * @author Bartosz Michalik - * @author Rinde van Lon - */ -public abstract class AbstractGraphIO { - /** - * Reads a graph from the specified reader. - * @param reader The reader to user for reading. - * @return A {@link Graph} instance. - * @throws IOException If something goes wrong while reading. - */ - public abstract Graph read(Reader reader) throws IOException; - - /** - * Reads a graph from the specified path. - * @param path The path to read from. - * @return A {@link Graph} instance. - * @throws IOException If something goes wrong while reading. - */ - public Graph read(Path path) throws IOException { - return read(Files.newInputStream(path)); - } - - /** - * Reads a graph from the specified stream. - * @param stream The stream to read from. - * @return A {@link Graph} instance. - * @throws IOException If something goes wrong while reading. - */ - public Graph read(InputStream stream) throws IOException { - return readReader(new InputStreamReader(stream, Charsets.UTF_8)); - } - - /** - * Reads a graph from the specified file. - * @param filePath A path to a file containing a graph. - * @return A {@link Graph} instance. - * @throws IOException If something goes wrong while reading. - */ - public Graph read(String filePath) throws IOException { - return read(FileSystems.getDefault().getPath(filePath)); - } - - /** - * Writes a graph to the specified writer. - * @param graph The graph to write. - * @param writer The writer to use for writing to. - * @throws IOException If something goes wrong while writing. - */ - public abstract void write(Graph graph, Writer writer) - throws IOException; - - /** - * Writes a graph to the specified path. - * @param graph The graph to write. - * @param path The path to write to. - * @throws IOException If something goes wrong while writing. - */ - public void write(Graph graph, Path path) throws IOException { - final BufferedWriter writer = Files.newBufferedWriter(path, Charsets.UTF_8); - write(graph, writer); - writer.close(); - } - - /** - * Writes a graph to the specified path. - * @param graph The graph to write. - * @param filePath The path to write to. - * @throws IOException If something goes wrong while writing. - */ - public void write(Graph graph, String filePath) throws IOException { - write(graph, FileSystems.getDefault().getPath(filePath)); - } - - Graph readReader(Reader r) throws IOException { - final Graph graph = read(r); - r.close(); - return graph; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/old/AbstractGraphIO.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/old/AbstractGraphIO.java deleted file mode 100755 index 12fb80c..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/old/AbstractGraphIO.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (C) 2011-2015 Rinde van Lon, iMinds-DistriNet, KU Leuven - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.github.rinde.rinsim.geom.io; - -import java.io.BufferedWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.Writer; -import java.nio.file.FileSystems; -import java.nio.file.Files; -import java.nio.file.Path; - -import com.github.rinde.rinsim.geom.ConnectionData; -import com.github.rinde.rinsim.geom.Graph; -import com.google.common.base.Charsets; - -/** - * Common abstract class for graph input and output operations. - * @param Type of connection data. - * @author Bartosz Michalik - * @author Rinde van Lon - */ -public abstract class AbstractGraphIO { - /** - * Reads a graph from the specified reader. - * @param reader The reader to user for reading. - * @return A {@link Graph} instance. - * @throws IOException If something goes wrong while reading. - */ - abstract public Graph read(Reader reader) throws IOException; - - /** - * Reads a graph from the specified path. - * @param path The path to read from. - * @return A {@link Graph} instance. - * @throws IOException If something goes wrong while reading. - */ - public Graph read(Path path) throws IOException { - return read(Files.newInputStream(path)); - } - - /** - * Reads a graph from the specified stream. - * @param stream The stream to read from. - * @return A {@link Graph} instance. - * @throws IOException If something goes wrong while reading. - */ - public Graph read(InputStream stream) throws IOException { - return readReader(new InputStreamReader(stream)); - } - - /** - * Reads a graph from the specified file. - * @param filePath A path to a file containing a graph. - * @return A {@link Graph} instance. - * @throws IOException If something goes wrong while reading. - */ - public Graph read(String filePath) throws IOException { - return read(FileSystems.getDefault().getPath(filePath)); - } - - /** - * Writes a graph to the specified writer. - * @param graph The graph to write. - * @param writer The writer to use for writing to. - * @throws IOException If something goes wrong while writing. - */ - abstract public void write(Graph graph, Writer writer) - throws IOException; - - /** - * Writes a graph to the specified path. - * @param graph The graph to write. - * @param path The path to write to. - * @throws IOException If something goes wrong while writing. - */ - public void write(Graph graph, Path path) throws IOException { - final BufferedWriter writer = Files.newBufferedWriter(path, Charsets.UTF_8); - write(graph, writer); - writer.close(); - } - - /** - * Writes a graph to the specified path. - * @param graph The graph to write. - * @param filePath The path to write to. - * @throws IOException If something goes wrong while writing. - */ - public void write(Graph graph, String filePath) throws IOException { - write(graph, FileSystems.getDefault().getPath(filePath)); - } - - Graph readReader(Reader r) throws IOException { - final Graph graph = read(r); - r.close(); - return graph; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/pair.info deleted file mode 100755 index 31c0b35..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70603/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:70603 -comSha:5e565827c5b1d314e11ca86f9defc82c1d1894e2 -parentComSha:1fae171c652180a7d6ab45b814d3c19bc61f8771 -BuggyFilePath:geom/src/main/java/com/github/rinde/rinsim/geom/io/AbstractGraphIO.java -FixedFilePath:geom/src/main/java/com/github/rinde/rinsim/geom/io/AbstractGraphIO.java -StartLineNum:64 -EndLineNum:64 -repoName:rinde#RinSim \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/comMsg.txt deleted file mode 100755 index fbbf6dc..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/comMsg.txt +++ /dev/null @@ -1,2 +0,0 @@ -Huge amount of changes, mostly Query parsing rewrite -Basic scoring implementation \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/diff.diff deleted file mode 100755 index c5be732..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/de/unihildesheim/iw/tools/StopwordsFileReader.java b/src/main/java/de/unihildesheim/iw/tools/StopwordsFileReader.java -index fcccb0f..6d6cdbc 100644 ---- a/src/main/java/de/unihildesheim/iw/tools/StopwordsFileReader.java -+++ b/src/main/java/de/unihildesheim/iw/tools/StopwordsFileReader.java -@@ -23,0 +24 @@ import java.io.InputStreamReader; -+import java.nio.charset.Charset; -@@ -41 +42,2 @@ public class StopwordsFileReader { -- public static Set readWords(final Format format, final String source) -+ public static Set readWords(final Format format, -+ final String source, final Charset cs) -@@ -50 +52 @@ public class StopwordsFileReader { -- new InputStreamReader(new FileInputStream(source)))) { -+ new InputStreamReader(new FileInputStream(source), cs))) { \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/new/StopwordsFileReader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/new/StopwordsFileReader.java deleted file mode 100755 index 6d6cdbc..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/new/StopwordsFileReader.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2014 Jens Bertram - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package de.unihildesheim.iw.tools; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.nio.charset.Charset; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -/** - * Simple file reader to build a list of stopwords. - * - * @author Jens Bertram - */ -public class StopwordsFileReader { - - /** - * Private empty constructor for utility class. - */ - private StopwordsFileReader() { - } - - public static Set readWords(final Format format, - final String source, final Charset cs) - throws IOException { - Objects.requireNonNull(format, "Format was null."); - if (Objects.requireNonNull(source, "Source was null.").trim().isEmpty()) { - throw new IllegalArgumentException("Empty source."); - } - - Set words; - try (BufferedReader reader = new BufferedReader( - new InputStreamReader(new FileInputStream(source), cs))) { - - words = new HashSet<>(); - - String line; - while ((line = reader.readLine()) != null) { - line = line.trim(); - - // ignore empty lines - if (line.isEmpty()) { - continue; - } - - // skip snowball comment lines - if (Format.SNOWBALL.equals(format) && line.charAt(0) == '|') { - continue; - } - - // add the first word - words.add(line.split(" ", 2)[0]); - } - } - return words; - } - - /** - * Tries to get the format type from the given string. - * - * @param format String naming the format - * @return Format or null, if none is matching - */ - public static Format getFormatFromString(final String format) { - if (Objects.requireNonNull(format, "Format was null.").trim().isEmpty()) { - throw new IllegalArgumentException("Format type string was empty."); - } - if (Format.PLAIN.name().equalsIgnoreCase(format)) { - return Format.PLAIN; - } else if (Format.SNOWBALL.name().equalsIgnoreCase(format)) { - return Format.SNOWBALL; - } - return null; - } - - public enum Format { - /** - * Plain file with one word per line. - */ - PLAIN, - /** - * Snowball format. Comments starting with | (pipe). - */ - SNOWBALL - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/old/StopwordsFileReader.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/old/StopwordsFileReader.java deleted file mode 100755 index fcccb0f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/old/StopwordsFileReader.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2014 Jens Bertram - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package de.unihildesheim.iw.tools; - -import java.io.BufferedReader; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.HashSet; -import java.util.Objects; -import java.util.Set; - -/** - * Simple file reader to build a list of stopwords. - * - * @author Jens Bertram - */ -public class StopwordsFileReader { - - /** - * Private empty constructor for utility class. - */ - private StopwordsFileReader() { - } - - public static Set readWords(final Format format, final String source) - throws IOException { - Objects.requireNonNull(format, "Format was null."); - if (Objects.requireNonNull(source, "Source was null.").trim().isEmpty()) { - throw new IllegalArgumentException("Empty source."); - } - - Set words; - try (BufferedReader reader = new BufferedReader( - new InputStreamReader(new FileInputStream(source)))) { - - words = new HashSet<>(); - - String line; - while ((line = reader.readLine()) != null) { - line = line.trim(); - - // ignore empty lines - if (line.isEmpty()) { - continue; - } - - // skip snowball comment lines - if (Format.SNOWBALL.equals(format) && line.charAt(0) == '|') { - continue; - } - - // add the first word - words.add(line.split(" ", 2)[0]); - } - } - return words; - } - - /** - * Tries to get the format type from the given string. - * - * @param format String naming the format - * @return Format or null, if none is matching - */ - public static Format getFormatFromString(final String format) { - if (Objects.requireNonNull(format, "Format was null.").trim().isEmpty()) { - throw new IllegalArgumentException("Format type string was empty."); - } - if (Format.PLAIN.name().equalsIgnoreCase(format)) { - return Format.PLAIN; - } else if (Format.SNOWBALL.name().equalsIgnoreCase(format)) { - return Format.SNOWBALL; - } - return null; - } - - public enum Format { - /** - * Plain file with one word per line. - */ - PLAIN, - /** - * Snowball format. Comments starting with | (pipe). - */ - SNOWBALL - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/pair.info deleted file mode 100755 index a83953e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#70674/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:70674 -comSha:bab5090b7580ede74ed9f977937374474ddce970 -parentComSha:2f8a490a8784886fe0acdd119f5b3146f20217a6 -BuggyFilePath:src/main/java/de/unihildesheim/iw/tools/StopwordsFileReader.java -FixedFilePath:src/main/java/de/unihildesheim/iw/tools/StopwordsFileReader.java -StartLineNum:49 -EndLineNum:49 -repoName:JensBee#QueryClarity \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/comMsg.txt deleted file mode 100755 index dee05dc..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Read JSON files in with UTF8 to prevent language related issues \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/diff.diff deleted file mode 100755 index bc90246..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/com/atlauncher/nio/JsonFile.java b/src/main/java/com/atlauncher/nio/JsonFile.java -index a6618806..12257c2b 100644 ---- a/src/main/java/com/atlauncher/nio/JsonFile.java -+++ b/src/main/java/com/atlauncher/nio/JsonFile.java -@@ -85 +85 @@ public final class JsonFile { -- return gson.fromJson(new InputStreamReader(stream), tClass); -+ return gson.fromJson(new InputStreamReader(stream, "UTF-8"), tClass); -@@ -94 +94 @@ public final class JsonFile { -- return gson.fromJson(new InputStreamReader(stream), type); -+ return gson.fromJson(new InputStreamReader(stream, "UTF-8"), type); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/new/JsonFile.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/new/JsonFile.java deleted file mode 100755 index 12257c2..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/new/JsonFile.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * ATLauncher - https://github.com/ATLauncher/ATLauncher - * Copyright (C) 2013 ATLauncher - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.atlauncher.nio; - -import com.atlauncher.FileSystem; -import com.atlauncher.Gsons; -import com.google.gson.Gson; - -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.lang.reflect.Type; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; - -public final class JsonFile { - public static T of(String name, Class tClass) throws Exception { - return create(name).convert(tClass); - } - - public static T of(String name, Type type) throws Exception { - return create(name).convert(type); - } - - public static JsonFile create(String name) throws Exception { - return new JsonFile(FileSystem.JSON.resolve(name)); - } - - private final Path path; - - public JsonFile(Path path) throws FileNotFoundException { - this(path, false); - } - - public JsonFile(Path path, boolean write) throws FileNotFoundException { - if (!Files.exists(path) && !write) { - throw new FileNotFoundException("File " + path + " wasn't found"); - } - - this.path = path; - } - - public void write(Object obj) throws Exception { - write(Gsons.DEFAULT, obj); - } - - public void write(Gson gson, Object obj) throws Exception { - OutputStream os = Files.newOutputStream(this.path, StandardOpenOption.WRITE); - OutputStreamWriter osw = new OutputStreamWriter(os); - - gson.toJson(obj, osw); - - osw.close(); - os.close(); - } - - public T convert(Class tClass) throws Exception { - return convert(Gsons.DEFAULT, tClass); - } - - public T convert(Type type) throws Exception { - return convert(Gsons.DEFAULT, type); - } - - public T convert(Gson gson, Class tClass) throws Exception { - try (InputStream stream = Files.newInputStream(this.path)) { - return gson.fromJson(new InputStreamReader(stream, "UTF-8"), tClass); - } catch (Exception e) { - e.printStackTrace(System.err); - return null; - } - } - - public T convert(Gson gson, Type type) throws Exception { - try (InputStream stream = Files.newInputStream(this.path)) { - return gson.fromJson(new InputStreamReader(stream, "UTF-8"), type); - } - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/old/JsonFile.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/old/JsonFile.java deleted file mode 100755 index a661880..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/old/JsonFile.java +++ /dev/null @@ -1,97 +0,0 @@ -/* - * ATLauncher - https://github.com/ATLauncher/ATLauncher - * Copyright (C) 2013 ATLauncher - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package com.atlauncher.nio; - -import com.atlauncher.FileSystem; -import com.atlauncher.Gsons; -import com.google.gson.Gson; - -import java.io.FileNotFoundException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.lang.reflect.Type; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.StandardOpenOption; - -public final class JsonFile { - public static T of(String name, Class tClass) throws Exception { - return create(name).convert(tClass); - } - - public static T of(String name, Type type) throws Exception { - return create(name).convert(type); - } - - public static JsonFile create(String name) throws Exception { - return new JsonFile(FileSystem.JSON.resolve(name)); - } - - private final Path path; - - public JsonFile(Path path) throws FileNotFoundException { - this(path, false); - } - - public JsonFile(Path path, boolean write) throws FileNotFoundException { - if (!Files.exists(path) && !write) { - throw new FileNotFoundException("File " + path + " wasn't found"); - } - - this.path = path; - } - - public void write(Object obj) throws Exception { - write(Gsons.DEFAULT, obj); - } - - public void write(Gson gson, Object obj) throws Exception { - OutputStream os = Files.newOutputStream(this.path, StandardOpenOption.WRITE); - OutputStreamWriter osw = new OutputStreamWriter(os); - - gson.toJson(obj, osw); - - osw.close(); - os.close(); - } - - public T convert(Class tClass) throws Exception { - return convert(Gsons.DEFAULT, tClass); - } - - public T convert(Type type) throws Exception { - return convert(Gsons.DEFAULT, type); - } - - public T convert(Gson gson, Class tClass) throws Exception { - try (InputStream stream = Files.newInputStream(this.path)) { - return gson.fromJson(new InputStreamReader(stream), tClass); - } catch (Exception e) { - e.printStackTrace(System.err); - return null; - } - } - - public T convert(Gson gson, Type type) throws Exception { - try (InputStream stream = Files.newInputStream(this.path)) { - return gson.fromJson(new InputStreamReader(stream), type); - } - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/pair.info deleted file mode 100755 index f14cc9a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#72605/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:72605 -comSha:bc6007e902ade78d5753bef8872b90aec217823e -parentComSha:84c7ae3a9db7847f3626e24b54063dd2a5504ca4 -BuggyFilePath:src/main/java/com/atlauncher/nio/JsonFile.java -FixedFilePath:src/main/java/com/atlauncher/nio/JsonFile.java -StartLineNum:85 -EndLineNum:85 -repoName:ATLauncher#ATLauncher \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/comMsg.txt deleted file mode 100755 index 5578b10..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix last bugs (FindBugs). Add sprint reports. \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/diff.diff deleted file mode 100755 index 30840dc..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/diff.diff +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/src/main/java/nl/tudelft/ti2806/pl1/gui/contentpane/PhyloPanel.java b/src/main/java/nl/tudelft/ti2806/pl1/gui/contentpane/PhyloPanel.java -index ea1779a..d46880a 100644 ---- a/src/main/java/nl/tudelft/ti2806/pl1/gui/contentpane/PhyloPanel.java -+++ b/src/main/java/nl/tudelft/ti2806/pl1/gui/contentpane/PhyloPanel.java -@@ -11 +11 @@ import java.io.File; --import java.io.FileReader; -+import java.io.FileInputStream; -@@ -12,0 +13 @@ import java.io.IOException; -+import java.io.InputStreamReader; -@@ -233 +234 @@ public class PhyloPanel extends JScrollPane implements ContentTab { -- * when something goes wrong xD -+ * when file reading goes wrong. -@@ -237,2 +238,2 @@ public class PhyloPanel extends JScrollPane implements ContentTab { -- -- final BufferedReader in = new BufferedReader(new FileReader(file)); -+ final BufferedReader in = new BufferedReader(new BufferedReader( -+ new InputStreamReader(new FileInputStream(file), "UTF-8"))); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/new/PhyloPanel.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/new/PhyloPanel.java deleted file mode 100755 index d46880a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/new/PhyloPanel.java +++ /dev/null @@ -1,248 +0,0 @@ -package nl.tudelft.ti2806.pl1.gui.contentpane; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Insets; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JComponent; -import javax.swing.JScrollPane; - -import nl.tudelft.ti2806.pl1.gui.Event; -import nl.tudelft.ti2806.pl1.gui.ToolBar; -import nl.tudelft.ti2806.pl1.phylotree.BinaryTree; - -import com.wordpress.tips4java.ScrollablePanel; - -/** - * @author Maarten - * - */ -public class PhyloPanel extends JScrollPane implements ContentTab { - - /** The serial version UID. */ - private static final long serialVersionUID = -1936473122898892804L; - - /** The size of the nodes. */ - private static final int NODE_WIDTH = 100, NODE_HEIGHT = 25; - - /** The width of the edges connecting the nodes. */ - private static final float EDGE_WIDTH = 2; - - /** The number of decimal places to round the path lengths to. */ - private static final int DIST_ROUND_TO_N = 3; - - /** The color of a chosen/selected node. */ - public static final Color NODE_SELECTED_COLOR = Color.ORANGE; - - /** The color of an edge between two chosen/selected nodes. */ - public static final Color EDGE_BETWEEN_SELECTED_COLOR = Color.ORANGE; - - /** The color of a collapsed inner node. */ - public static final Color INNER_NODE_COLLAPSED = Color.RED; - - /** The color of a normal (not collapsed) inner node. */ - public static final Color INNER_NODE_NORMAL = Color.BLACK; - - /** The default color to use. */ - public static final Color DEFAULT_COLOR = Color.BLACK; - - /** The tree that this panel will show. */ - private BinaryTree tree; - - /** - * @return The loaded tree. - */ - public final BinaryTree getTree() { - return tree; - } - - /** The Newick formatted input string. */ - private String newickSource; - - /** The scroll panel. */ - private ScrollablePanel treePanel; - - /** The space in between the nodes. */ - private static final Insets INSETS = new Insets(3, 10, 0, 0); - - /** - * Initializes the panel. - */ - public PhyloPanel() { - treePanel = new ScrollablePanel() { - /** The serial version UID */ - private static final long serialVersionUID = 118748767146413611L; - - @Override - protected final void paintComponent(final Graphics g) { - super.paintComponent(g); - if (tree != null) { - drawLines(g, tree); - } - } - }; - treePanel.setLayout(null); - setViewportView(treePanel); - } - - @Override - public List getToolBarControls() { - List ret = new ArrayList(2); - ret.add(ToolBar.makeButton("Highlight selection", null, null, null)); - ret.add(ToolBar.makeButton("Filter selection", null, null, null)); - return ret; - } - - /** - * Draws all the lines from given node and its children recursively. - * - * @param g - * The graphics object. - * @param node - * The root of the tree to draw lines in. - */ - private void drawLines(final Graphics g, final BinaryTree node) { - Graphics2D g2 = (Graphics2D) g; - g2.setStroke(new BasicStroke(EDGE_WIDTH)); - if (!node.isCollapsed()) { - List children = node.getChildren(); - int x = (int) node.getCenter().getX(); - int y = (int) node.getCenter().getY(); - for (BinaryTree child : children) { - g2.setColor(getLineColor(node, child)); - int childX = (int) child.getCenter().getX(); - int childY = (int) child.getCenter().getY(); - if (childY == y) { - g2.drawLine(x, y, childX, y); - g2.drawString(child.getPathLengthN(DIST_ROUND_TO_N), - (x + childX) / 2, childY); - } else { - g2.drawLine(x, y, x, childY); - g2.drawLine(x, childY, childX, childY); - g2.drawString(child.getPathLengthN(DIST_ROUND_TO_N), x, - (y + childY) / 2); - } - g2.setColor(DEFAULT_COLOR); - drawLines(g, child); - } - } - } - - /** - * Determines the color to draw the connecting line between two connected - * nodes with. - * - * @param parent - * The parent node. - * @param child - * The child node. - * @return The appropriate line color to connect the parent to - * the child with. - */ - private Color getLineColor(final BinaryTree parent, final BinaryTree child) { - if (parent.getChildren().contains(child) && parent.isChosen() - && child.isChosen()) { - return EDGE_BETWEEN_SELECTED_COLOR; - } - return DEFAULT_COLOR; - } - - /** - * Loads a newick file. - * - * @param newick - * The Newick file to load. - * @return true iff the tree was loaded successfully. - */ - public final boolean loadTree(final File newick) { - boolean ret = true; - try { - this.newickSource = readIntoString(newick); - } catch (IOException e) { - ret = false; - Event.statusBarError("File " + newick.getAbsolutePath() - + " could not be read."); - e.printStackTrace(); - } - this.tree = BinaryTree.parseNewick(newickSource, this); - plotTree(); - return ret; - } - - /** - * Plots the tree as a button. - */ - public final void plotTree() { - removeTree(); - int treeWidth = tree.computePlacement(0, 0); - int treeHeight = tree.height(); - // System.out.println(tree.toString()); - addNode(tree); - treePanel.setPreferredSize(new Dimension((treeHeight + 1) - * (NODE_WIDTH + INSETS.left) + INSETS.left, (treeWidth + 1) - * (NODE_HEIGHT + INSETS.top) + INSETS.top)); - repaint(); - revalidate(); - } - - /** - * Empties the panel. All tree components will be deleted. - */ - public final void removeTree() { - treePanel.removeAll(); - } - - /** - * Adds the current tree and all its children if it is not collapsed. - * - * @param bintree - * The current tree - */ - private void addNode(final BinaryTree bintree) { - // treePanel.remove(tree); - int x = (int) bintree.getGridCoordinates().getX(); - int y = (int) bintree.getGridCoordinates().getY(); - bintree.setBounds(x * (NODE_WIDTH + INSETS.left) + INSETS.left, y - * (NODE_HEIGHT + INSETS.top) + INSETS.top, NODE_WIDTH, - NODE_HEIGHT); - bintree.setText(bintree.getID()); - treePanel.add(bintree); - if (!bintree.isCollapsed()) { - for (BinaryTree t : bintree.getChildren()) { - addNode(t); - } - } - } - - /** - * Copies the entire file content into a single String, and returns it. - * - * @param file - * The file to read. - * @return the file content as a continuous string - * @throws IOException - * when file reading goes wrong. - */ - public static String readIntoString(final File file) throws IOException { - final StringBuffer buff = new StringBuffer(); - final BufferedReader in = new BufferedReader(new BufferedReader( - new InputStreamReader(new FileInputStream(file), "UTF-8"))); - String line; - while ((line = in.readLine()) != null) { - buff.append(line); - } - in.close(); - - return buff.toString(); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/old/PhyloPanel.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/old/PhyloPanel.java deleted file mode 100755 index ea1779a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/old/PhyloPanel.java +++ /dev/null @@ -1,247 +0,0 @@ -package nl.tudelft.ti2806.pl1.gui.contentpane; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Insets; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import javax.swing.JComponent; -import javax.swing.JScrollPane; - -import nl.tudelft.ti2806.pl1.gui.Event; -import nl.tudelft.ti2806.pl1.gui.ToolBar; -import nl.tudelft.ti2806.pl1.phylotree.BinaryTree; - -import com.wordpress.tips4java.ScrollablePanel; - -/** - * @author Maarten - * - */ -public class PhyloPanel extends JScrollPane implements ContentTab { - - /** The serial version UID. */ - private static final long serialVersionUID = -1936473122898892804L; - - /** The size of the nodes. */ - private static final int NODE_WIDTH = 100, NODE_HEIGHT = 25; - - /** The width of the edges connecting the nodes. */ - private static final float EDGE_WIDTH = 2; - - /** The number of decimal places to round the path lengths to. */ - private static final int DIST_ROUND_TO_N = 3; - - /** The color of a chosen/selected node. */ - public static final Color NODE_SELECTED_COLOR = Color.ORANGE; - - /** The color of an edge between two chosen/selected nodes. */ - public static final Color EDGE_BETWEEN_SELECTED_COLOR = Color.ORANGE; - - /** The color of a collapsed inner node. */ - public static final Color INNER_NODE_COLLAPSED = Color.RED; - - /** The color of a normal (not collapsed) inner node. */ - public static final Color INNER_NODE_NORMAL = Color.BLACK; - - /** The default color to use. */ - public static final Color DEFAULT_COLOR = Color.BLACK; - - /** The tree that this panel will show. */ - private BinaryTree tree; - - /** - * @return The loaded tree. - */ - public final BinaryTree getTree() { - return tree; - } - - /** The Newick formatted input string. */ - private String newickSource; - - /** The scroll panel. */ - private ScrollablePanel treePanel; - - /** The space in between the nodes. */ - private static final Insets INSETS = new Insets(3, 10, 0, 0); - - /** - * Initializes the panel. - */ - public PhyloPanel() { - treePanel = new ScrollablePanel() { - /** The serial version UID */ - private static final long serialVersionUID = 118748767146413611L; - - @Override - protected final void paintComponent(final Graphics g) { - super.paintComponent(g); - if (tree != null) { - drawLines(g, tree); - } - } - }; - treePanel.setLayout(null); - setViewportView(treePanel); - } - - @Override - public List getToolBarControls() { - List ret = new ArrayList(2); - ret.add(ToolBar.makeButton("Highlight selection", null, null, null)); - ret.add(ToolBar.makeButton("Filter selection", null, null, null)); - return ret; - } - - /** - * Draws all the lines from given node and its children recursively. - * - * @param g - * The graphics object. - * @param node - * The root of the tree to draw lines in. - */ - private void drawLines(final Graphics g, final BinaryTree node) { - Graphics2D g2 = (Graphics2D) g; - g2.setStroke(new BasicStroke(EDGE_WIDTH)); - if (!node.isCollapsed()) { - List children = node.getChildren(); - int x = (int) node.getCenter().getX(); - int y = (int) node.getCenter().getY(); - for (BinaryTree child : children) { - g2.setColor(getLineColor(node, child)); - int childX = (int) child.getCenter().getX(); - int childY = (int) child.getCenter().getY(); - if (childY == y) { - g2.drawLine(x, y, childX, y); - g2.drawString(child.getPathLengthN(DIST_ROUND_TO_N), - (x + childX) / 2, childY); - } else { - g2.drawLine(x, y, x, childY); - g2.drawLine(x, childY, childX, childY); - g2.drawString(child.getPathLengthN(DIST_ROUND_TO_N), x, - (y + childY) / 2); - } - g2.setColor(DEFAULT_COLOR); - drawLines(g, child); - } - } - } - - /** - * Determines the color to draw the connecting line between two connected - * nodes with. - * - * @param parent - * The parent node. - * @param child - * The child node. - * @return The appropriate line color to connect the parent to - * the child with. - */ - private Color getLineColor(final BinaryTree parent, final BinaryTree child) { - if (parent.getChildren().contains(child) && parent.isChosen() - && child.isChosen()) { - return EDGE_BETWEEN_SELECTED_COLOR; - } - return DEFAULT_COLOR; - } - - /** - * Loads a newick file. - * - * @param newick - * The Newick file to load. - * @return true iff the tree was loaded successfully. - */ - public final boolean loadTree(final File newick) { - boolean ret = true; - try { - this.newickSource = readIntoString(newick); - } catch (IOException e) { - ret = false; - Event.statusBarError("File " + newick.getAbsolutePath() - + " could not be read."); - e.printStackTrace(); - } - this.tree = BinaryTree.parseNewick(newickSource, this); - plotTree(); - return ret; - } - - /** - * Plots the tree as a button. - */ - public final void plotTree() { - removeTree(); - int treeWidth = tree.computePlacement(0, 0); - int treeHeight = tree.height(); - // System.out.println(tree.toString()); - addNode(tree); - treePanel.setPreferredSize(new Dimension((treeHeight + 1) - * (NODE_WIDTH + INSETS.left) + INSETS.left, (treeWidth + 1) - * (NODE_HEIGHT + INSETS.top) + INSETS.top)); - repaint(); - revalidate(); - } - - /** - * Empties the panel. All tree components will be deleted. - */ - public final void removeTree() { - treePanel.removeAll(); - } - - /** - * Adds the current tree and all its children if it is not collapsed. - * - * @param bintree - * The current tree - */ - private void addNode(final BinaryTree bintree) { - // treePanel.remove(tree); - int x = (int) bintree.getGridCoordinates().getX(); - int y = (int) bintree.getGridCoordinates().getY(); - bintree.setBounds(x * (NODE_WIDTH + INSETS.left) + INSETS.left, y - * (NODE_HEIGHT + INSETS.top) + INSETS.top, NODE_WIDTH, - NODE_HEIGHT); - bintree.setText(bintree.getID()); - treePanel.add(bintree); - if (!bintree.isCollapsed()) { - for (BinaryTree t : bintree.getChildren()) { - addNode(t); - } - } - } - - /** - * Copies the entire file content into a single String, and returns it. - * - * @param file - * The file to read. - * @return the file content as a continuous string - * @throws IOException - * when something goes wrong xD - */ - public static String readIntoString(final File file) throws IOException { - final StringBuffer buff = new StringBuffer(); - - final BufferedReader in = new BufferedReader(new FileReader(file)); - String line; - while ((line = in.readLine()) != null) { - buff.append(line); - } - in.close(); - - return buff.toString(); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/pair.info deleted file mode 100755 index 837470a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#73968/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:73968 -comSha:2f62a7b19eba236ac4525bf88e729cc3c0dc9d0b -parentComSha:20a7e9d95201587b24c625ff648cbff32c81d7cf -BuggyFilePath:src/main/java/nl/tudelft/ti2806/pl1/gui/contentpane/PhyloPanel.java -FixedFilePath:src/main/java/nl/tudelft/ti2806/pl1/gui/contentpane/PhyloPanel.java -StartLineNum:238 -EndLineNum:238 -repoName:maartentbm#ContextPL1 \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/comMsg.txt deleted file mode 100755 index fc5a604..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixed conflicts \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/diff.diff deleted file mode 100755 index 208248f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/org/perfcake/reporting/destinations/CSVDestination.java b/src/main/java/org/perfcake/reporting/destinations/CSVDestination.java -index 87742689..15594564 100644 ---- a/src/main/java/org/perfcake/reporting/destinations/CSVDestination.java -+++ b/src/main/java/org/perfcake/reporting/destinations/CSVDestination.java -@@ -24 +24 @@ import java.io.File; --import java.io.FileWriter; -+import java.io.FileOutputStream; -@@ -25,0 +26 @@ import java.io.IOException; -+import java.io.OutputStreamWriter; -@@ -151 +152 @@ public class CSVDestination implements Destination { -- try (BufferedWriter bw = new BufferedWriter(new FileWriter(csvFile, true))) { -+ try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile, true), Utils.getDefaultEncoding()))) { \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/new/CSVDestination.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/new/CSVDestination.java deleted file mode 100755 index 1559456..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/new/CSVDestination.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.reporting.destinations; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.log4j.Logger; -import org.perfcake.reporting.Measurement; -import org.perfcake.reporting.Quantity; -import org.perfcake.reporting.ReportingException; -import org.perfcake.util.Utils; - -/** - * The destination that appends the {@link Measurement} into a CSV file. - * - * @author Pavel Macík - * - */ -public class CSVDestination implements Destination { - - /** - * Output CSV file path. - */ - private String path = ""; - - /** - * Output CSV file. - */ - private File csvFile = null; - - /** - * CSV delimiter. - */ - private String delimiter = ";"; - - /** - * The destination's logger. - */ - private static final Logger log = Logger.getLogger(CSVDestination.class); - - /** - * The list containing names of results from measurement. - */ - private final List resultNames = new LinkedList<>(); - - /* - * (non-Javadoc) - * - * @see org.perfcake.reporting.destinations.Destination#open() - */ - @Override - public void open() { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.reporting.destinations.Destination#close() - */ - @Override - public void close() { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.reporting.destinations.Destination#report(org.perfcake.reporting.Measurement) - */ - @Override - public void report(final Measurement m) throws ReportingException { - StringBuffer sb = new StringBuffer(); - if (csvFile == null) { - csvFile = new File(path); - if (log.isDebugEnabled()) { - log.debug("Output path not specified. Using the default one: " + csvFile.getPath()); - } - } - - final Map results = m.getAll(); - - Object defaultResult = m.get(); - // make sure the order of columns is consisten - if (!csvFile.exists()) { - sb.append("Time"); - sb.append(delimiter); - sb.append("Iterations"); - if (defaultResult != null) { - sb.append(delimiter); - sb.append(Measurement.DEFAULT_RESULT); - } - for (String key : results.keySet()) { - if (!key.equals(Measurement.DEFAULT_RESULT)) { - resultNames.add(key); - sb.append(delimiter); - sb.append(key); - } - } - sb.append("\n"); - } - - sb.append(Utils.timeToHMS(m.getTime())); - sb.append(delimiter); - sb.append(m.getIteration()); - if (defaultResult != null) { - sb.append(delimiter); - if (defaultResult instanceof Quantity) { - sb.append(((Quantity) defaultResult).getNumber()); - } else { - sb.append(defaultResult); - } - } - - Object currentResult; - for (String resultName : resultNames) { - sb.append(delimiter); - currentResult = results.get(resultName); - if (currentResult instanceof Quantity) { - sb.append(((Quantity) currentResult).getNumber()); - } else { - sb.append(currentResult); - } - } - - try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile, true), Utils.getDefaultEncoding()))) { - bw.append(sb.toString()); - bw.newLine(); - } catch (IOException ioe) { - throw new ReportingException("Could not append a report to the file: " + csvFile.getPath(), ioe); - } - } - - /** - * Used to read the value of path. - * - * @return The path value. - */ - public String getPath() { - return path; - } - - /** - * Used to set the value of path. - * - * @param path - * The path value to set. - */ - public void setPath(final String path) { - this.path = path; - this.csvFile = new File(this.path); - } - - /** - * Used to read the value of delimiter. - * - * @return The delimiter value. - */ - public String getDelimiter() { - return delimiter; - } - - /** - * Used to set the value of delimiter. - * - * @param delimiter - * The delimiter value to set. - */ - public void setDelimiter(final String delimiter) { - this.delimiter = delimiter; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/old/CSVDestination.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/old/CSVDestination.java deleted file mode 100755 index 8774268..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/old/CSVDestination.java +++ /dev/null @@ -1,198 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.reporting.destinations; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import org.apache.log4j.Logger; -import org.perfcake.reporting.Measurement; -import org.perfcake.reporting.Quantity; -import org.perfcake.reporting.ReportingException; -import org.perfcake.util.Utils; - -/** - * The destination that appends the {@link Measurement} into a CSV file. - * - * @author Pavel Macík - * - */ -public class CSVDestination implements Destination { - - /** - * Output CSV file path. - */ - private String path = ""; - - /** - * Output CSV file. - */ - private File csvFile = null; - - /** - * CSV delimiter. - */ - private String delimiter = ";"; - - /** - * The destination's logger. - */ - private static final Logger log = Logger.getLogger(CSVDestination.class); - - /** - * The list containing names of results from measurement. - */ - private final List resultNames = new LinkedList<>(); - - /* - * (non-Javadoc) - * - * @see org.perfcake.reporting.destinations.Destination#open() - */ - @Override - public void open() { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.reporting.destinations.Destination#close() - */ - @Override - public void close() { - // TODO Auto-generated method stub - - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.reporting.destinations.Destination#report(org.perfcake.reporting.Measurement) - */ - @Override - public void report(final Measurement m) throws ReportingException { - StringBuffer sb = new StringBuffer(); - if (csvFile == null) { - csvFile = new File(path); - if (log.isDebugEnabled()) { - log.debug("Output path not specified. Using the default one: " + csvFile.getPath()); - } - } - - final Map results = m.getAll(); - - Object defaultResult = m.get(); - // make sure the order of columns is consisten - if (!csvFile.exists()) { - sb.append("Time"); - sb.append(delimiter); - sb.append("Iterations"); - if (defaultResult != null) { - sb.append(delimiter); - sb.append(Measurement.DEFAULT_RESULT); - } - for (String key : results.keySet()) { - if (!key.equals(Measurement.DEFAULT_RESULT)) { - resultNames.add(key); - sb.append(delimiter); - sb.append(key); - } - } - sb.append("\n"); - } - - sb.append(Utils.timeToHMS(m.getTime())); - sb.append(delimiter); - sb.append(m.getIteration()); - if (defaultResult != null) { - sb.append(delimiter); - if (defaultResult instanceof Quantity) { - sb.append(((Quantity) defaultResult).getNumber()); - } else { - sb.append(defaultResult); - } - } - - Object currentResult; - for (String resultName : resultNames) { - sb.append(delimiter); - currentResult = results.get(resultName); - if (currentResult instanceof Quantity) { - sb.append(((Quantity) currentResult).getNumber()); - } else { - sb.append(currentResult); - } - } - - try (BufferedWriter bw = new BufferedWriter(new FileWriter(csvFile, true))) { - bw.append(sb.toString()); - bw.newLine(); - } catch (IOException ioe) { - throw new ReportingException("Could not append a report to the file: " + csvFile.getPath(), ioe); - } - } - - /** - * Used to read the value of path. - * - * @return The path value. - */ - public String getPath() { - return path; - } - - /** - * Used to set the value of path. - * - * @param path - * The path value to set. - */ - public void setPath(final String path) { - this.path = path; - this.csvFile = new File(this.path); - } - - /** - * Used to read the value of delimiter. - * - * @return The delimiter value. - */ - public String getDelimiter() { - return delimiter; - } - - /** - * Used to set the value of delimiter. - * - * @param delimiter - * The delimiter value to set. - */ - public void setDelimiter(final String delimiter) { - this.delimiter = delimiter; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/pair.info deleted file mode 100755 index 1cf3c85..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#75991/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:75991 -comSha:14a53ed4fd80e5d7a044b39cd1fd167f53650e99 -parentComSha:fa24bb5b38d6b928f40a8684394155c1bdffec3e -BuggyFilePath:src/main/java/org/perfcake/reporting/destinations/CSVDestination.java -FixedFilePath:src/main/java/org/perfcake/reporting/destinations/CSVDestination.java -StartLineNum:151 -EndLineNum:151 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/comMsg.txt deleted file mode 100755 index c97bd7f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -findbugs issues cleaning, UtilsTest \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/diff.diff deleted file mode 100755 index defd3a9..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/main/java/org/perfcake/message/sender/HTTPSender.java b/src/main/java/org/perfcake/message/sender/HTTPSender.java -index 55c18158..5ead2335 100644 ---- a/src/main/java/org/perfcake/message/sender/HTTPSender.java -+++ b/src/main/java/org/perfcake/message/sender/HTTPSender.java -@@ -37,0 +38 @@ import org.perfcake.reporting.MeasurementUnit; -+import org.perfcake.util.Utils; -@@ -246 +247 @@ public class HTTPSender extends AbstractSender { -- OutputStreamWriter out = new OutputStreamWriter(requestConnection.getOutputStream()); -+ OutputStreamWriter out = new OutputStreamWriter(requestConnection.getOutputStream(), Utils.getDefaultEncoding()); -@@ -248,0 +250 @@ public class HTTPSender extends AbstractSender { -+ out.close(); -@@ -267 +269 @@ public class HTTPSender extends AbstractSender { -- InputStreamReader read = new InputStreamReader(rcis); -+ InputStreamReader read = new InputStreamReader(rcis, Utils.getDefaultEncoding()); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/new/HTTPSender.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/new/HTTPSender.java deleted file mode 100755 index 5ead233..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/new/HTTPSender.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.message.sender; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Serializable; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.perfcake.PerfCakeException; -import org.perfcake.message.Message; -import org.perfcake.reporting.MeasurementUnit; -import org.perfcake.util.Utils; - -/** - * The sender that is able to send the messages via HTTP protocol. - * - * @author Martin Večeřa - * @author Pavel Macík - * - */ -public class HTTPSender extends AbstractSender { - - /** - * Default expected response code. - */ - protected static final int DEFAULT_EXPECTED_CODE = 200; - - /** - * The sender's logger. - */ - private static final Logger log = Logger.getLogger(HTTPSender.class); - - /** - * The URL where the HTTP request is send. - */ - private URL url; - - /** - * The HTTP method that will be used. - */ - private Method method = Method.POST; - - /** - * Enumeration on available HTTP methods. - */ - public static enum Method { - GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE - } - - /** - * The list of response codes that are expected to be returned by HTTP response. - */ - private List expectedResponseCodeList = Arrays.asList(DEFAULT_EXPECTED_CODE); - - /** - * The property for expected response codes. - */ - private String expectedResponseCodes = String.valueOf(DEFAULT_EXPECTED_CODE); - - /** - * The HTTP request connection. - */ - protected HttpURLConnection requestConnection; - - /** - * The request payload. - */ - private String payload; - - /** - * The request payload lenght. - */ - private int payloadLenght; - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#init() - */ - @Override - public void init() throws Exception { - url = new URL(target); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#close() - */ - @Override - public void close() { - // nop - } - - /** - * Sets the value of expectedResponseCodes property. - * - * @param expectedResponseCodes - * The expectedResponseCodes property to set. - */ - public void setExpectedResponseCodes(final String expectedResponseCodes) { - this.expectedResponseCodes = expectedResponseCodes; - setExpectedResponseCodesList(expectedResponseCodes.split(",")); - } - - /** - * Used to read the list of expected response codes. - * - * @return The list of expected response codes. - */ - public List getExpectedResponseCodeList() { - return expectedResponseCodeList; - } - - /** - * Used to read the value of expectedResponseCodes property. - * - * @return The expectedResponseCodes. - */ - public String getExpectedResponseCodes() { - return expectedResponseCodes; - } - - /** - * Sets a list of expected response codes. - * - * @param codes - * The array of codes. - */ - protected void setExpectedResponseCodesList(final String[] codes) { - LinkedList numCodes = new LinkedList(); - for (String code : codes) { - numCodes.add(Integer.parseInt(code.trim())); - } - expectedResponseCodeList = numCodes; - } - - /** - * Checks if the code is expected. - * - * @param code - * Checked response code. - * @return - * true/false according to if the code is expected or not. - */ - private boolean checkResponseCode(final int code) { - for (int i : expectedResponseCodeList) { - if (i == code) { - return true; - } - } - return false; - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#preSend(org.perfcake.message.Message, java.util.Map) - */ - @Override - public void preSend(final Message message, final Map properties) throws Exception { - super.preSend(message, properties); - payload = message.getPayload().toString(); - if (payload != null) { - payloadLenght = payload.length(); - } else { - payloadLenght = 0; - } - - requestConnection = (HttpURLConnection) url.openConnection(); - requestConnection.setRequestMethod(method.name()); - requestConnection.setDoInput(true); - if (method == Method.POST || method == Method.PUT) { - requestConnection.setDoOutput(true); - } - requestConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); - if (payloadLenght > 0) { - requestConnection.setRequestProperty("Content-Length", Integer.toString(payloadLenght)); - } - Set propertyNameSet = message.getProperties().stringPropertyNames(); - for (String property : propertyNameSet) { - requestConnection.setRequestProperty(property, message.getProperty(property)); - } - // set additional properties - if (log.isDebugEnabled()) { - log.debug("Setting HTTP headers"); - } - if (properties != null) { - propertyNameSet = properties.keySet(); - for (String property : propertyNameSet) { - String pValue = (properties.get(property)); - requestConnection.setRequestProperty(property, pValue); - if (log.isDebugEnabled()) { - log.debug(property + ": " + pValue); - } - } - } - - if (message.getHeaders().size() > 0) { - Set headerNameSet = message.getHeaders().stringPropertyNames(); - for (String header : headerNameSet) { - String hValue = message.getHeader(header); - if (log.isDebugEnabled()) { - log.debug(header + ": " + hValue); - } - requestConnection.setRequestProperty(header, hValue); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#doSend(org.perfcake.message.Message, java.util.Map, org.perfcake.reporting.MeasurementUnit) - */ - @Override - public Serializable doSend(final Message message, final Map properties, final MeasurementUnit mu) throws Exception { - int respCode = -1; - requestConnection.connect(); - if (payload != null && (method == Method.POST || method == Method.PUT)) { - OutputStreamWriter out = new OutputStreamWriter(requestConnection.getOutputStream(), Utils.getDefaultEncoding()); - out.write(payload, 0, payloadLenght); - out.flush(); - out.close(); - requestConnection.getOutputStream().close(); - } - - respCode = requestConnection.getResponseCode(); - if (!checkResponseCode(respCode)) { - String errorMess = "The server returned an unexpected HTTP response code: " + respCode + " " + "\"" + requestConnection.getResponseMessage() + "\". Expected HTTP codes are "; - for (int code : expectedResponseCodeList) { - errorMess += Integer.toString(code) + ", "; - } - throw new PerfCakeException(errorMess.substring(0, errorMess.length() - 2) + "."); - } - InputStream rcis = null; - if (respCode < 400) { - rcis = requestConnection.getInputStream(); - } else { - rcis = requestConnection.getErrorStream(); - } - char[] cbuf = new char[10 * 1024]; - InputStreamReader read = new InputStreamReader(rcis, Utils.getDefaultEncoding()); - // note that Content-Length is available at this point - StringBuilder sb = new StringBuilder(); - int ch = read.read(cbuf); - while (ch != -1) { - sb.append(cbuf, 0, ch); - ch = read.read(cbuf); - } - read.close(); - rcis.close(); - String payload = sb.toString(); - - return payload; - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#postSend(org.perfcake.message.Message) - */ - @Override - public void postSend(final Message message) throws Exception { - super.postSend(message); - requestConnection.disconnect(); - } - - /** - * Used to read the value of HTTP method. - * - * @return The HTTP method. - */ - public Method getMethod() { - return method; - } - - /** - * Sets the value of HTTP method. - * - * @param method - * The HTTP method to set. - */ - public void setMethod(final Method method) { - this.method = method; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/old/HTTPSender.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/old/HTTPSender.java deleted file mode 100755 index 55c1815..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/old/HTTPSender.java +++ /dev/null @@ -1,312 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.message.sender; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.Serializable; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Arrays; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.log4j.Logger; -import org.perfcake.PerfCakeException; -import org.perfcake.message.Message; -import org.perfcake.reporting.MeasurementUnit; - -/** - * The sender that is able to send the messages via HTTP protocol. - * - * @author Martin Večeřa - * @author Pavel Macík - * - */ -public class HTTPSender extends AbstractSender { - - /** - * Default expected response code. - */ - protected static final int DEFAULT_EXPECTED_CODE = 200; - - /** - * The sender's logger. - */ - private static final Logger log = Logger.getLogger(HTTPSender.class); - - /** - * The URL where the HTTP request is send. - */ - private URL url; - - /** - * The HTTP method that will be used. - */ - private Method method = Method.POST; - - /** - * Enumeration on available HTTP methods. - */ - public static enum Method { - GET, POST, HEAD, OPTIONS, PUT, DELETE, TRACE - } - - /** - * The list of response codes that are expected to be returned by HTTP response. - */ - private List expectedResponseCodeList = Arrays.asList(DEFAULT_EXPECTED_CODE); - - /** - * The property for expected response codes. - */ - private String expectedResponseCodes = String.valueOf(DEFAULT_EXPECTED_CODE); - - /** - * The HTTP request connection. - */ - protected HttpURLConnection requestConnection; - - /** - * The request payload. - */ - private String payload; - - /** - * The request payload lenght. - */ - private int payloadLenght; - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#init() - */ - @Override - public void init() throws Exception { - url = new URL(target); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#close() - */ - @Override - public void close() { - // nop - } - - /** - * Sets the value of expectedResponseCodes property. - * - * @param expectedResponseCodes - * The expectedResponseCodes property to set. - */ - public void setExpectedResponseCodes(final String expectedResponseCodes) { - this.expectedResponseCodes = expectedResponseCodes; - setExpectedResponseCodesList(expectedResponseCodes.split(",")); - } - - /** - * Used to read the list of expected response codes. - * - * @return The list of expected response codes. - */ - public List getExpectedResponseCodeList() { - return expectedResponseCodeList; - } - - /** - * Used to read the value of expectedResponseCodes property. - * - * @return The expectedResponseCodes. - */ - public String getExpectedResponseCodes() { - return expectedResponseCodes; - } - - /** - * Sets a list of expected response codes. - * - * @param codes - * The array of codes. - */ - protected void setExpectedResponseCodesList(final String[] codes) { - LinkedList numCodes = new LinkedList(); - for (String code : codes) { - numCodes.add(Integer.parseInt(code.trim())); - } - expectedResponseCodeList = numCodes; - } - - /** - * Checks if the code is expected. - * - * @param code - * Checked response code. - * @return - * true/false according to if the code is expected or not. - */ - private boolean checkResponseCode(final int code) { - for (int i : expectedResponseCodeList) { - if (i == code) { - return true; - } - } - return false; - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#preSend(org.perfcake.message.Message, java.util.Map) - */ - @Override - public void preSend(final Message message, final Map properties) throws Exception { - super.preSend(message, properties); - payload = message.getPayload().toString(); - if (payload != null) { - payloadLenght = payload.length(); - } else { - payloadLenght = 0; - } - - requestConnection = (HttpURLConnection) url.openConnection(); - requestConnection.setRequestMethod(method.name()); - requestConnection.setDoInput(true); - if (method == Method.POST || method == Method.PUT) { - requestConnection.setDoOutput(true); - } - requestConnection.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); - if (payloadLenght > 0) { - requestConnection.setRequestProperty("Content-Length", Integer.toString(payloadLenght)); - } - Set propertyNameSet = message.getProperties().stringPropertyNames(); - for (String property : propertyNameSet) { - requestConnection.setRequestProperty(property, message.getProperty(property)); - } - // set additional properties - if (log.isDebugEnabled()) { - log.debug("Setting HTTP headers"); - } - if (properties != null) { - propertyNameSet = properties.keySet(); - for (String property : propertyNameSet) { - String pValue = (properties.get(property)); - requestConnection.setRequestProperty(property, pValue); - if (log.isDebugEnabled()) { - log.debug(property + ": " + pValue); - } - } - } - - if (message.getHeaders().size() > 0) { - Set headerNameSet = message.getHeaders().stringPropertyNames(); - for (String header : headerNameSet) { - String hValue = message.getHeader(header); - if (log.isDebugEnabled()) { - log.debug(header + ": " + hValue); - } - requestConnection.setRequestProperty(header, hValue); - } - } - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#doSend(org.perfcake.message.Message, java.util.Map, org.perfcake.reporting.MeasurementUnit) - */ - @Override - public Serializable doSend(final Message message, final Map properties, final MeasurementUnit mu) throws Exception { - int respCode = -1; - requestConnection.connect(); - if (payload != null && (method == Method.POST || method == Method.PUT)) { - OutputStreamWriter out = new OutputStreamWriter(requestConnection.getOutputStream()); - out.write(payload, 0, payloadLenght); - out.flush(); - requestConnection.getOutputStream().close(); - } - - respCode = requestConnection.getResponseCode(); - if (!checkResponseCode(respCode)) { - String errorMess = "The server returned an unexpected HTTP response code: " + respCode + " " + "\"" + requestConnection.getResponseMessage() + "\". Expected HTTP codes are "; - for (int code : expectedResponseCodeList) { - errorMess += Integer.toString(code) + ", "; - } - throw new PerfCakeException(errorMess.substring(0, errorMess.length() - 2) + "."); - } - InputStream rcis = null; - if (respCode < 400) { - rcis = requestConnection.getInputStream(); - } else { - rcis = requestConnection.getErrorStream(); - } - char[] cbuf = new char[10 * 1024]; - InputStreamReader read = new InputStreamReader(rcis); - // note that Content-Length is available at this point - StringBuilder sb = new StringBuilder(); - int ch = read.read(cbuf); - while (ch != -1) { - sb.append(cbuf, 0, ch); - ch = read.read(cbuf); - } - read.close(); - rcis.close(); - String payload = sb.toString(); - - return payload; - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#postSend(org.perfcake.message.Message) - */ - @Override - public void postSend(final Message message) throws Exception { - super.postSend(message); - requestConnection.disconnect(); - } - - /** - * Used to read the value of HTTP method. - * - * @return The HTTP method. - */ - public Method getMethod() { - return method; - } - - /** - * Sets the value of HTTP method. - * - * @param method - * The HTTP method to set. - */ - public void setMethod(final Method method) { - this.method = method; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/pair.info deleted file mode 100755 index 6821463..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76017/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76017 -comSha:fcc8a9f6f76d554be3c5a5b792f3b6019ae78b5a -parentComSha:691018806eb0762dfee4fb0b1a03efccdc7ce9e1 -BuggyFilePath:src/main/java/org/perfcake/message/sender/HTTPSender.java -FixedFilePath:src/main/java/org/perfcake/message/sender/HTTPSender.java -StartLineNum:246 -EndLineNum:246 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/comMsg.txt deleted file mode 100755 index 84f2d8e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'devel' of github.com:PerfCake/PerfCake into devel \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/diff.diff deleted file mode 100755 index 4578d09..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/main/java/org/perfcake/util/agent/AgentThread.java b/src/main/java/org/perfcake/util/agent/AgentThread.java -index e0b25fa6..7305723e 100644 ---- a/src/main/java/org/perfcake/util/agent/AgentThread.java -+++ b/src/main/java/org/perfcake/util/agent/AgentThread.java -@@ -6,0 +7 @@ import java.io.InputStreamReader; -+import java.io.OutputStreamWriter; -@@ -12,0 +14 @@ import java.util.Properties; -+import org.perfcake.util.Utils; -@@ -40 +42 @@ public class AgentThread implements Runnable { -- if (agentArgs != "" && agentArgs != null) { -+ if (!"".equals(agentArgs) && agentArgs != null) { -@@ -69,2 +71,2 @@ public class AgentThread implements Runnable { -- BufferedReader br = new BufferedReader(new InputStreamReader(is)); -- PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); -+ BufferedReader br = new BufferedReader(new InputStreamReader(is, Utils.getDefaultEncoding())); -+ PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Utils.getDefaultEncoding()), true); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/new/AgentThread.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/new/AgentThread.java deleted file mode 100755 index 7305723..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/new/AgentThread.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.perfcake.util.agent; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.Properties; - -import org.perfcake.util.Utils; -import org.perfcake.util.agent.PerfCakeAgent.Memory; - -public class AgentThread implements Runnable { - - private String agentArgs; - - public AgentThread(String agentArgs) { - super(); - this.agentArgs = agentArgs; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - InetAddress host = null; - int port = 8849; // default - ServerSocket ssocket = null; - Socket socket = null; - InputStream is = null; - - try { - // parse agent properties - Properties props = new Properties(); - if (!"".equals(agentArgs) && agentArgs != null) { - String[] args = agentArgs.split(","); - for (String arg : args) { - String[] keyValuePair = arg.split("="); - if (keyValuePair.length == 2) { - props.put(keyValuePair[0], keyValuePair[1]); - } else { - err("Invalid agent argument \"" + arg + "\" - ignoring"); - } - } - } - - if (props.get("port") != null) { - port = Integer.valueOf((String) props.get("port")); - } - - if (props.get("hostname") != null) { - host = InetAddress.getByName(props.getProperty("hostname")); - } else { - host = InetAddress.getLocalHost(); - } - - ssocket = new ServerSocket(port, 1, host); - while (true) { - log("Listening at " + ssocket.getInetAddress().getHostAddress() + " on port " + ssocket.getLocalPort()); - socket = ssocket.accept(); - log("Client connected from " + socket.getInetAddress().getHostAddress()); - is = socket.getInputStream(); - String input = null; - BufferedReader br = new BufferedReader(new InputStreamReader(is, Utils.getDefaultEncoding())); - PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Utils.getDefaultEncoding()), true); - while ((input = br.readLine()) != null) { - String response = "Unrecognized command!"; - Runtime rt = Runtime.getRuntime(); - try { - switch (Memory.valueOf(input.toUpperCase())) { - case FREE: - response = String.valueOf(rt.freeMemory()); - break; - case MAX: - response = String.valueOf(rt.maxMemory()); - break; - case TOTAL: - response = String.valueOf(rt.totalMemory()); - break; - case USED: - response = String.valueOf(rt.totalMemory() - rt.freeMemory()); - break; - } - } catch (IllegalArgumentException iae) { - err(iae.getLocalizedMessage()); - } - pw.println(response); - } - log("Client disconnected"); - } - - } catch (Throwable e) { - e.printStackTrace(); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - private static void log(String msg) { - System.out.println(PerfCakeAgent.class.getSimpleName() + " > " + msg); - } - - private static void err(String msg) { - System.err.println(PerfCakeAgent.class.getSimpleName() + " > ERROR: " + msg); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/old/AgentThread.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/old/AgentThread.java deleted file mode 100755 index e0b25fa..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/old/AgentThread.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.perfcake.util.agent; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.Properties; - -import org.perfcake.util.agent.PerfCakeAgent.Memory; - -public class AgentThread implements Runnable { - - private String agentArgs; - - public AgentThread(String agentArgs) { - super(); - this.agentArgs = agentArgs; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - InetAddress host = null; - int port = 8849; // default - ServerSocket ssocket = null; - Socket socket = null; - InputStream is = null; - - try { - // parse agent properties - Properties props = new Properties(); - if (agentArgs != "" && agentArgs != null) { - String[] args = agentArgs.split(","); - for (String arg : args) { - String[] keyValuePair = arg.split("="); - if (keyValuePair.length == 2) { - props.put(keyValuePair[0], keyValuePair[1]); - } else { - err("Invalid agent argument \"" + arg + "\" - ignoring"); - } - } - } - - if (props.get("port") != null) { - port = Integer.valueOf((String) props.get("port")); - } - - if (props.get("hostname") != null) { - host = InetAddress.getByName(props.getProperty("hostname")); - } else { - host = InetAddress.getLocalHost(); - } - - ssocket = new ServerSocket(port, 1, host); - while (true) { - log("Listening at " + ssocket.getInetAddress().getHostAddress() + " on port " + ssocket.getLocalPort()); - socket = ssocket.accept(); - log("Client connected from " + socket.getInetAddress().getHostAddress()); - is = socket.getInputStream(); - String input = null; - BufferedReader br = new BufferedReader(new InputStreamReader(is)); - PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); - while ((input = br.readLine()) != null) { - String response = "Unrecognized command!"; - Runtime rt = Runtime.getRuntime(); - try { - switch (Memory.valueOf(input.toUpperCase())) { - case FREE: - response = String.valueOf(rt.freeMemory()); - break; - case MAX: - response = String.valueOf(rt.maxMemory()); - break; - case TOTAL: - response = String.valueOf(rt.totalMemory()); - break; - case USED: - response = String.valueOf(rt.totalMemory() - rt.freeMemory()); - break; - } - } catch (IllegalArgumentException iae) { - err(iae.getLocalizedMessage()); - } - pw.println(response); - } - log("Client disconnected"); - } - - } catch (Throwable e) { - e.printStackTrace(); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - private static void log(String msg) { - System.out.println(PerfCakeAgent.class.getSimpleName() + " > " + msg); - } - - private static void err(String msg) { - System.err.println(PerfCakeAgent.class.getSimpleName() + " > ERROR: " + msg); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/pair.info deleted file mode 100755 index 80a2713..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76038/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76038 -comSha:eea8160f9d629c116161357c5bd37228103936b2 -parentComSha:2b86dff4da79d1b24b11dd8a4236edba3f3409ef -BuggyFilePath:src/main/java/org/perfcake/util/agent/AgentThread.java -FixedFilePath:src/main/java/org/perfcake/util/agent/AgentThread.java -StartLineNum:70 -EndLineNum:70 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/comMsg.txt deleted file mode 100755 index 84f2d8e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Merge branch 'devel' of github.com:PerfCake/PerfCake into devel \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/diff.diff deleted file mode 100755 index e32a62a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/org/perfcake/parser/ScenarioParser.java b/src/main/java/org/perfcake/parser/ScenarioParser.java -index 4bcd86e3..8da6458b 100644 ---- a/src/main/java/org/perfcake/parser/ScenarioParser.java -+++ b/src/main/java/org/perfcake/parser/ScenarioParser.java -@@ -23,0 +24 @@ import java.io.IOException; -+import java.io.UnsupportedEncodingException; -@@ -79 +80 @@ public class ScenarioParser { -- Source scenarioXML = new StreamSource(new ByteArrayInputStream(scenarioConfig.getBytes())); -+ Source scenarioXML = new StreamSource(new ByteArrayInputStream(scenarioConfig.getBytes(Utils.getDefaultEncoding()))); -@@ -92,0 +94,2 @@ public class ScenarioParser { -+ } catch (UnsupportedEncodingException e) { -+ throw new PerfCakeException("set encoding is not supported: ", e); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/new/ScenarioParser.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/new/ScenarioParser.java deleted file mode 100755 index 8da6458..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/new/ScenarioParser.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.parser; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.MalformedURLException; -import java.net.URL; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; - -import org.apache.log4j.Logger; -import org.perfcake.PerfCakeException; -import org.perfcake.Scenario; -import org.perfcake.util.Utils; -import org.xml.sax.SAXException; - -/** - * ScenarioParser is a tool for loading XML document with scenario description from URL and producing JAXB model representation - * - * @author Pavel Macík - * @author Martin Večeřa - * @author Jiří Sedláček - */ -public class ScenarioParser { - - public static final Logger log = Logger.getLogger(ScenarioParser.class); - - private String scenarioConfig; - - /** - * - * @param scenario - * @throws PerfCakeException - * if URL cannot be read - */ - public ScenarioParser(final URL scenario) throws PerfCakeException { - try { - this.scenarioConfig = Utils.readFilteredContent(scenario); - - } catch (IOException e) { - throw new PerfCakeException("Cannot read scenario configuration: ", e); - } - } - - /** - * Do the parsing itself by using JAXB - * - * @return - * @throws PerfCakeException - * if XML is not valid or cannot be successfully parsed - */ - public org.perfcake.model.Scenario parse() throws PerfCakeException { - try { - Source scenarioXML = new StreamSource(new ByteArrayInputStream(scenarioConfig.getBytes(Utils.getDefaultEncoding()))); - SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - Schema schema = schemaFactory.newSchema(new URL("http://schema.perfcake.org/perfcake-scenario-" + Scenario.VERSION + ".xsd")); - - JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class); - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setSchema(schema); - return (org.perfcake.model.Scenario) unmarshaller.unmarshal(scenarioXML); - } catch (SAXException e) { - throw new PerfCakeException("Cannot validate scenario configuration: ", e); - } catch (JAXBException e) { - throw new PerfCakeException("Cannot parse scenario configuration: ", e); - } catch (MalformedURLException e) { - throw new PerfCakeException("Cannot read scenario schema to validate it: ", e); - } catch (UnsupportedEncodingException e) { - throw new PerfCakeException("set encoding is not supported: ", e); - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/old/ScenarioParser.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/old/ScenarioParser.java deleted file mode 100755 index 4bcd86e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/old/ScenarioParser.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.parser; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; - -import javax.xml.XMLConstants; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.transform.Source; -import javax.xml.transform.stream.StreamSource; -import javax.xml.validation.Schema; -import javax.xml.validation.SchemaFactory; - -import org.apache.log4j.Logger; -import org.perfcake.PerfCakeException; -import org.perfcake.Scenario; -import org.perfcake.util.Utils; -import org.xml.sax.SAXException; - -/** - * ScenarioParser is a tool for loading XML document with scenario description from URL and producing JAXB model representation - * - * @author Pavel Macík - * @author Martin Večeřa - * @author Jiří Sedláček - */ -public class ScenarioParser { - - public static final Logger log = Logger.getLogger(ScenarioParser.class); - - private String scenarioConfig; - - /** - * - * @param scenario - * @throws PerfCakeException - * if URL cannot be read - */ - public ScenarioParser(final URL scenario) throws PerfCakeException { - try { - this.scenarioConfig = Utils.readFilteredContent(scenario); - - } catch (IOException e) { - throw new PerfCakeException("Cannot read scenario configuration: ", e); - } - } - - /** - * Do the parsing itself by using JAXB - * - * @return - * @throws PerfCakeException - * if XML is not valid or cannot be successfully parsed - */ - public org.perfcake.model.Scenario parse() throws PerfCakeException { - try { - Source scenarioXML = new StreamSource(new ByteArrayInputStream(scenarioConfig.getBytes())); - SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); - Schema schema = schemaFactory.newSchema(new URL("http://schema.perfcake.org/perfcake-scenario-" + Scenario.VERSION + ".xsd")); - - JAXBContext context = JAXBContext.newInstance(org.perfcake.model.Scenario.class); - Unmarshaller unmarshaller = context.createUnmarshaller(); - unmarshaller.setSchema(schema); - return (org.perfcake.model.Scenario) unmarshaller.unmarshal(scenarioXML); - } catch (SAXException e) { - throw new PerfCakeException("Cannot validate scenario configuration: ", e); - } catch (JAXBException e) { - throw new PerfCakeException("Cannot parse scenario configuration: ", e); - } catch (MalformedURLException e) { - throw new PerfCakeException("Cannot read scenario schema to validate it: ", e); - } - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/pair.info deleted file mode 100755 index 306a9a6..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76053/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76053 -comSha:eea8160f9d629c116161357c5bd37228103936b2 -parentComSha:2b86dff4da79d1b24b11dd8a4236edba3f3409ef -BuggyFilePath:src/main/java/org/perfcake/parser/ScenarioParser.java -FixedFilePath:src/main/java/org/perfcake/parser/ScenarioParser.java -StartLineNum:79 -EndLineNum:79 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/comMsg.txt deleted file mode 100755 index 27e9496..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -removed FindBugs warnings \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/diff.diff deleted file mode 100755 index f825c51..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/org/perfcake/reporting/destinations/chart/Chart.java b/src/main/java/org/perfcake/reporting/destinations/chart/Chart.java -index b7fc8b96..068444bd 100644 ---- a/src/main/java/org/perfcake/reporting/destinations/chart/Chart.java -+++ b/src/main/java/org/perfcake/reporting/destinations/chart/Chart.java -@@ -193 +193 @@ public class Chart { -- final String loaderEntry = new String(Files.readAllBytes(Paths.get(descriptionFile.toURI()))); -+ final String loaderEntry = new String(Files.readAllBytes(Paths.get(descriptionFile.toURI())), Utils.getDefaultEncoding()); -@@ -208,0 +209,4 @@ public class Chart { -+ if (firstDataLine == null) { -+ throw new IOException(String.format("Cannot read chart from file %s. No entries in the data file.", descriptionFile.getAbsolutePath())); -+ } -+ \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/new/Chart.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/new/Chart.java deleted file mode 100755 index 068444b..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/new/Chart.java +++ /dev/null @@ -1,497 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.reporting.destinations.chart; - -import org.perfcake.PerfCakeConst; -import org.perfcake.PerfCakeException; -import org.perfcake.common.PeriodType; -import org.perfcake.reporting.Measurement; -import org.perfcake.reporting.ReportingException; -import org.perfcake.util.Utils; -import org.perfcake.validation.StringUtil; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * Represents a single Google chart data file(s) stored in the file system. - * Charts once read from a description file cannot be further modified and stored again! - * - * @author Martin Večeřa - */ -public class Chart { - - /** - * Prefix of the files of the charts created as a combination of measured results. - */ - protected static final String DATA_ARRAY_PREFIX = "data_array_"; - - /** - * A logger for the class. - */ - private static final Logger log = LogManager.getLogger(Chart.class); - - /** - * File counter for the stored combined chart. - */ - private static int fileCounter = 1; - - /** - * Base of the file name of the chart file. E.g. from '/some/path/data/stats201501272232.js' it is just 'stats201501272232'. - */ - private String baseName; - - /** - * The JavaScript file representing chart data. This is not set for charts created as a combination of existing ones. - */ - private File dataFile; - - /** - * Target path for storing all data files related to this chart. These are the data itself (.js), the description file (.dat), - * and the quick view file (.html). - */ - private Path target; - - /** - * Name of this chart. - */ - private String name; - - /** - * The legend of the X axis of this chart. - */ - private String xAxis; - - /** - * The legend of the Y axis of this chart. - */ - private String yAxis; - - /** - * The type of the X axis. It can display the overall progress of the test in Percents, Time, or Iteration numbers. - */ - private PeriodType xAxisType = PeriodType.TIME; - - /** - * Attributes that should be stored from the Measurement. - */ - private List attributes; - - /** - * The chart's group name. Charts from multiple measurements that have the same group name are later searched for matching attributes. - */ - private String group; - - /** - * Was this chart created as a concatenation of other charts? - */ - private boolean concat = false; - - /** - * Create a new chart based on the information loaded from a description file. - * - * @param baseName - * Base of the data files. - * @param group - * The name of the group the chart belongs to. - * @param attributes - * Attributes stored for the chart. - * @param name - * Name of this chart. - * @param xAxis - * Legend of the X axis. - * @param yAxis - * Legend of the Y axis. - */ - private Chart(final String baseName, final String group, final List attributes, final String name, final String xAxis, final String yAxis) { - this.baseName = baseName; - this.group = group; - this.attributes = attributes; - this.name = name; - this.xAxis = xAxis; - this.yAxis = yAxis; - } - - /** - * Create a new chart instance. - * - * @param target - * Target path where to store the data. - * @param group - * Group of this chart. - * @param attributes - * Attributes to be stored for this chart. - * @param name - * Name of the chart. - * @param xAxis - * Legend of the X axis. - * @param yAxis - * Legend of the Y axis. - * @throws PerfCakeException - * When it was not possible to create necessary data files. - */ - public Chart(final Path target, final String group, final List attributes, final String name, final String xAxis, final String yAxis) throws PerfCakeException { - this.target = target; - this.attributes = attributes; - this.name = name; - this.xAxis = xAxis; - this.yAxis = yAxis; - this.group = group; - - baseName = group + System.getProperty(PerfCakeConst.NICE_TIMESTAMP_PROPERTY); - dataFile = Paths.get(target.toString(), "data", baseName + ".js").toFile(); - - writeDataFileHeader(); - writeDescriptionFile(); - writeQuickView(); - } - - /** - * Get a chart instance based on the given description file. The resulting instance will carry all the needed information but cannot - * be later changed and stored again. - * - * @param descriptionFile - * The description file where to read the chart data from. - * @return A new chart instance based on the information in the description file. - * @throws IOException - * When it was not possible to read the data. - */ - public static Chart fromDescriptionFile(final File descriptionFile) throws IOException { - final String base = descriptionFile.getName().substring(0, descriptionFile.getName().length() - 4); - final String group = base.substring(0, base.length() - 14); - final String loaderEntry = new String(Files.readAllBytes(Paths.get(descriptionFile.toURI())), Utils.getDefaultEncoding()); - - // drawChart(stats20150124220000, 'chart_stats20150124220000_div', [0, 1, 2], 'Time of test', 'Iterations per second', 'Performance'); - String name = loaderEntry.substring(loaderEntry.lastIndexOf(", ") + 3); - name = name.substring(0, name.lastIndexOf("'")); - - String axises = loaderEntry.substring(loaderEntry.indexOf("], '") + 4, loaderEntry.lastIndexOf("', '")); - String xAxis = axises.substring(0, axises.indexOf("', '")); - String yAxis = axises.substring(axises.indexOf("', '") + 4); - - final File jsFile = new File(descriptionFile.getAbsolutePath().substring(0, descriptionFile.getAbsolutePath().length() - 4) + ".js"); - String firstDataLine = ""; - try (BufferedReader br = Files.newBufferedReader(jsFile.toPath(), Charset.forName(Utils.getDefaultEncoding()));) { - firstDataLine = br.readLine(); - } - - if (firstDataLine == null) { - throw new IOException(String.format("Cannot read chart from file %s. No entries in the data file.", descriptionFile.getAbsolutePath())); - } - - firstDataLine = firstDataLine.substring(firstDataLine.indexOf("[ [ ") + 4); - firstDataLine = firstDataLine.substring(0, firstDataLine.indexOf(" ] ]")); - String[] columnNames = firstDataLine.split(", "); - List columnsList = new ArrayList<>(); - for (String s : columnNames) { - columnsList.add(StringUtil.trim(s, "'")); - } - - return new Chart(base, group, columnsList, name, xAxis, yAxis); - } - - /** - * Creates and saves a new chart as a combination of the given attribute and charts. The result is stored to the given path. - * - * @param target - * The path where to store the resulting chart. - * @param match - * The name of the attribute that all the charts have in common. The resulting chart will display this attributed from all the charts. - * @param charts - * The charts to be combined based on the given attribute. - * @return The resulting chart representing the combination. - * @throws PerfCakeException - * When it was not possible to store the created chart. - */ - public static Chart combineCharts(final Path target, final String match, final List charts) throws PerfCakeException { - String base, baseFile; - Path dataFile; - do { - base = DATA_ARRAY_PREFIX + (fileCounter++); - baseFile = base + ".js"; - dataFile = Paths.get(target.toString(), "data", baseFile); - } while (dataFile.toFile().exists()); - - final List columnNames = new ArrayList<>(); - columnNames.add("Time"); - final StringBuilder baseNames = new StringBuilder(); - final StringBuilder columns = new StringBuilder(); - final StringBuilder lengths = new StringBuilder(); - final StringBuilder quotedNames = new StringBuilder(); - for (Chart chart : charts) { - if (baseNames.length() > 0) { - baseNames.append(", "); - columns.append(", "); - lengths.append(", "); - quotedNames.append(", "); - } - - columnNames.add(chart.getBaseName()); - - baseNames.append(chart.getBaseName()); - columns.append(chart.getAttributes().indexOf(match)); - lengths.append(chart.getBaseName()); - lengths.append(".length"); - quotedNames.append("'"); - quotedNames.append(chart.getName()); - quotedNames.append("'"); - } - - final Properties dataProps = new Properties(); - dataProps.setProperty("baseName", base); - dataProps.setProperty("chartCols", columns.toString()); - dataProps.setProperty("chartLen", lengths.toString()); - dataProps.setProperty("chartsQuoted", quotedNames.toString()); - dataProps.setProperty("charts", baseNames.toString()); - Utils.copyTemplateFromResource("/charts/data-array.js", dataFile, dataProps); - - final Chart result = new Chart(base, charts.get(0).getGroup(), columnNames, "Group: " + charts.get(0).getGroup() + ", Match of axis: " + match, charts.get(0).getxAxis(), charts.get(0).getyAxis()); - result.concat = true; - - return result; - } - - /** - * Gets the base name of the data files of this chart. - * - * @return The base name of the data files of this chart. - */ - public String getBaseName() { - return baseName; - } - - /** - * Gets the name of the chart. - * - * @return The name of the chart. - */ - public String getName() { - return name; - } - - /** - * Gets the legend of the X axis of the chart. - * - * @return The legend of the X axis of the chart. - */ - public String getxAxis() { - return xAxis; - } - - /** - * Gets the legend of the Y axis of the chart. - * - * @return The legend of the Y axis of the chart. - */ - public String getyAxis() { - return yAxis; - } - - /** - * Gets the attributes stored in the chart as a List. - * - * @return The attributes list. - */ - public List getAttributes() { - return attributes; - } - - /** - * Writes the initial header and array definition to the JavaScript data file. - * - * @throws PerfCakeException - * When it was not possible to write the data. - */ - private void writeDataFileHeader() throws PerfCakeException { - final StringBuilder dataHeader = new StringBuilder("var "); - dataHeader.append(baseName); - dataHeader.append(" = [ [ "); - boolean first = true; - for (String attr : attributes) { - if (first) { - dataHeader.append("'"); - first = false; - } else { - dataHeader.append(", '"); - } - dataHeader.append(attr); - dataHeader.append("'"); - } - dataHeader.append(" ] ];\n\n"); - Utils.writeFileContent(dataFile, dataHeader.toString()); - } - - /** - * Writes a quick view HTML file that can display the chart during the test run. - * - * @throws PerfCakeException - * When it was not possible to store the quick view file. - */ - private void writeQuickView() throws PerfCakeException { - final Path quickViewFile = Paths.get(target.toString(), "data", baseName + ".html"); - final Properties quickViewProps = new Properties(); - quickViewProps.setProperty("baseName", baseName); - quickViewProps.setProperty("loader", getLoaderLine()); - Utils.copyTemplateFromResource("/charts/quick-view.html", quickViewFile, quickViewProps); - } - - /** - * Writes a description file containing all needed information to draw the chart. - * - * @throws PerfCakeException - * When it was not possible to store the description file. - */ - private void writeDescriptionFile() throws PerfCakeException { - final Path instructionsFile = Paths.get(target.toString(), "data", baseName + ".dat"); - Utils.writeFileContent(instructionsFile, getLoaderLine()); - } - - /** - * Gets the JavaScript instruction line that is used to draw the chart in the result report. - * This is exactly what is stored in the description file too. - * - * @return The JavaScript code to draw the chart. - */ - public String getLoaderLine() { - final StringBuilder line = new StringBuilder(concat ? "drawConcatChart(" : "drawChart("); - line.append(baseName); - line.append(", 'chart_"); - line.append(baseName); - line.append("_div', [0"); - - for (int i = 1; i < attributes.size(); i++) { - line.append(", "); - line.append(i); - } - - line.append("], '"); - line.append(xAxis); - line.append("', '"); - line.append(yAxis); - line.append("', '"); - line.append(name); - line.append("');\n"); - - return line.toString(); - } - - /** - * Gets a JavaScript line to be written to the data file that represents the current Measurement. - * All attributes required by the attributes list of this chart must be present in the measurement for the line to be returned. - * - * @param m - * The current measurement. - * @return The line representing the data in measurement specified by the attributes list of this chart, or null when there was some of - * the attributes missing. - */ - private String getResultLine(final Measurement m) { - StringBuilder sb = new StringBuilder(); - sb.append(baseName); - sb.append(".push(['"); - sb.append(Utils.timeToHMS(m.getTime())); - sb.append("'"); - - for (String attr : attributes) { - if (!attr.equals("Time")) { - sb.append(", "); - Object data = m.get(attr); - - // we do not have all required attributes, return an empty line - if (data == null) { - return ""; - } - - if (data instanceof String) { - sb.append("'"); - sb.append((String) data); - sb.append("'"); - } else { - sb.append(data.toString()); - } - } - } - - sb.append("]);\n"); - - return sb.toString(); - } - - /** - * Appends results to this chart based on the given Measurement. - * - * @param m - * The Measurement to be stored. - * @throws ReportingException - * When it was not possible to write the data. - */ - public void appendResult(final Measurement m) throws ReportingException { - String line = getResultLine(m); - - if (line != null && !"".equals(line)) { - try (FileOutputStream fos = new FileOutputStream(dataFile, true); OutputStreamWriter osw = new OutputStreamWriter(fos, Utils.getDefaultEncoding()); BufferedWriter bw = new BufferedWriter(osw)) { - bw.append(line); - } catch (IOException ioe) { - throw new ReportingException(String.format("Could not append data to the chart file %s.", dataFile.getAbsolutePath()), ioe); - } - } - } - - /** - * Gets the group of the current chart. - * - * @return The group name of this chart. - */ - public String getGroup() { - return group; - } - - /** - * Gets the type of the X axis. It can be either Time, Percents, or Iteration number. - * - * @return The type of the X axis. - */ - public PeriodType getxAxisType() { - return xAxisType; - } - - /** - * Was the chart created as a result of combining multiple other charts? - * - * @return True if and only if the chart was created as a combination of other charts. - */ - public boolean isCombined() { - return concat; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/old/Chart.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/old/Chart.java deleted file mode 100755 index b7fc8b9..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/old/Chart.java +++ /dev/null @@ -1,493 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.reporting.destinations.chart; - -import org.perfcake.PerfCakeConst; -import org.perfcake.PerfCakeException; -import org.perfcake.common.PeriodType; -import org.perfcake.reporting.Measurement; -import org.perfcake.reporting.ReportingException; -import org.perfcake.util.Utils; -import org.perfcake.validation.StringUtil; - -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; - -import java.io.BufferedReader; -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.nio.charset.Charset; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -/** - * Represents a single Google chart data file(s) stored in the file system. - * Charts once read from a description file cannot be further modified and stored again! - * - * @author Martin Večeřa - */ -public class Chart { - - /** - * Prefix of the files of the charts created as a combination of measured results. - */ - protected static final String DATA_ARRAY_PREFIX = "data_array_"; - - /** - * A logger for the class. - */ - private static final Logger log = LogManager.getLogger(Chart.class); - - /** - * File counter for the stored combined chart. - */ - private static int fileCounter = 1; - - /** - * Base of the file name of the chart file. E.g. from '/some/path/data/stats201501272232.js' it is just 'stats201501272232'. - */ - private String baseName; - - /** - * The JavaScript file representing chart data. This is not set for charts created as a combination of existing ones. - */ - private File dataFile; - - /** - * Target path for storing all data files related to this chart. These are the data itself (.js), the description file (.dat), - * and the quick view file (.html). - */ - private Path target; - - /** - * Name of this chart. - */ - private String name; - - /** - * The legend of the X axis of this chart. - */ - private String xAxis; - - /** - * The legend of the Y axis of this chart. - */ - private String yAxis; - - /** - * The type of the X axis. It can display the overall progress of the test in Percents, Time, or Iteration numbers. - */ - private PeriodType xAxisType = PeriodType.TIME; - - /** - * Attributes that should be stored from the Measurement. - */ - private List attributes; - - /** - * The chart's group name. Charts from multiple measurements that have the same group name are later searched for matching attributes. - */ - private String group; - - /** - * Was this chart created as a concatenation of other charts? - */ - private boolean concat = false; - - /** - * Create a new chart based on the information loaded from a description file. - * - * @param baseName - * Base of the data files. - * @param group - * The name of the group the chart belongs to. - * @param attributes - * Attributes stored for the chart. - * @param name - * Name of this chart. - * @param xAxis - * Legend of the X axis. - * @param yAxis - * Legend of the Y axis. - */ - private Chart(final String baseName, final String group, final List attributes, final String name, final String xAxis, final String yAxis) { - this.baseName = baseName; - this.group = group; - this.attributes = attributes; - this.name = name; - this.xAxis = xAxis; - this.yAxis = yAxis; - } - - /** - * Create a new chart instance. - * - * @param target - * Target path where to store the data. - * @param group - * Group of this chart. - * @param attributes - * Attributes to be stored for this chart. - * @param name - * Name of the chart. - * @param xAxis - * Legend of the X axis. - * @param yAxis - * Legend of the Y axis. - * @throws PerfCakeException - * When it was not possible to create necessary data files. - */ - public Chart(final Path target, final String group, final List attributes, final String name, final String xAxis, final String yAxis) throws PerfCakeException { - this.target = target; - this.attributes = attributes; - this.name = name; - this.xAxis = xAxis; - this.yAxis = yAxis; - this.group = group; - - baseName = group + System.getProperty(PerfCakeConst.NICE_TIMESTAMP_PROPERTY); - dataFile = Paths.get(target.toString(), "data", baseName + ".js").toFile(); - - writeDataFileHeader(); - writeDescriptionFile(); - writeQuickView(); - } - - /** - * Get a chart instance based on the given description file. The resulting instance will carry all the needed information but cannot - * be later changed and stored again. - * - * @param descriptionFile - * The description file where to read the chart data from. - * @return A new chart instance based on the information in the description file. - * @throws IOException - * When it was not possible to read the data. - */ - public static Chart fromDescriptionFile(final File descriptionFile) throws IOException { - final String base = descriptionFile.getName().substring(0, descriptionFile.getName().length() - 4); - final String group = base.substring(0, base.length() - 14); - final String loaderEntry = new String(Files.readAllBytes(Paths.get(descriptionFile.toURI()))); - - // drawChart(stats20150124220000, 'chart_stats20150124220000_div', [0, 1, 2], 'Time of test', 'Iterations per second', 'Performance'); - String name = loaderEntry.substring(loaderEntry.lastIndexOf(", ") + 3); - name = name.substring(0, name.lastIndexOf("'")); - - String axises = loaderEntry.substring(loaderEntry.indexOf("], '") + 4, loaderEntry.lastIndexOf("', '")); - String xAxis = axises.substring(0, axises.indexOf("', '")); - String yAxis = axises.substring(axises.indexOf("', '") + 4); - - final File jsFile = new File(descriptionFile.getAbsolutePath().substring(0, descriptionFile.getAbsolutePath().length() - 4) + ".js"); - String firstDataLine = ""; - try (BufferedReader br = Files.newBufferedReader(jsFile.toPath(), Charset.forName(Utils.getDefaultEncoding()));) { - firstDataLine = br.readLine(); - } - - firstDataLine = firstDataLine.substring(firstDataLine.indexOf("[ [ ") + 4); - firstDataLine = firstDataLine.substring(0, firstDataLine.indexOf(" ] ]")); - String[] columnNames = firstDataLine.split(", "); - List columnsList = new ArrayList<>(); - for (String s : columnNames) { - columnsList.add(StringUtil.trim(s, "'")); - } - - return new Chart(base, group, columnsList, name, xAxis, yAxis); - } - - /** - * Creates and saves a new chart as a combination of the given attribute and charts. The result is stored to the given path. - * - * @param target - * The path where to store the resulting chart. - * @param match - * The name of the attribute that all the charts have in common. The resulting chart will display this attributed from all the charts. - * @param charts - * The charts to be combined based on the given attribute. - * @return The resulting chart representing the combination. - * @throws PerfCakeException - * When it was not possible to store the created chart. - */ - public static Chart combineCharts(final Path target, final String match, final List charts) throws PerfCakeException { - String base, baseFile; - Path dataFile; - do { - base = DATA_ARRAY_PREFIX + (fileCounter++); - baseFile = base + ".js"; - dataFile = Paths.get(target.toString(), "data", baseFile); - } while (dataFile.toFile().exists()); - - final List columnNames = new ArrayList<>(); - columnNames.add("Time"); - final StringBuilder baseNames = new StringBuilder(); - final StringBuilder columns = new StringBuilder(); - final StringBuilder lengths = new StringBuilder(); - final StringBuilder quotedNames = new StringBuilder(); - for (Chart chart : charts) { - if (baseNames.length() > 0) { - baseNames.append(", "); - columns.append(", "); - lengths.append(", "); - quotedNames.append(", "); - } - - columnNames.add(chart.getBaseName()); - - baseNames.append(chart.getBaseName()); - columns.append(chart.getAttributes().indexOf(match)); - lengths.append(chart.getBaseName()); - lengths.append(".length"); - quotedNames.append("'"); - quotedNames.append(chart.getName()); - quotedNames.append("'"); - } - - final Properties dataProps = new Properties(); - dataProps.setProperty("baseName", base); - dataProps.setProperty("chartCols", columns.toString()); - dataProps.setProperty("chartLen", lengths.toString()); - dataProps.setProperty("chartsQuoted", quotedNames.toString()); - dataProps.setProperty("charts", baseNames.toString()); - Utils.copyTemplateFromResource("/charts/data-array.js", dataFile, dataProps); - - final Chart result = new Chart(base, charts.get(0).getGroup(), columnNames, "Group: " + charts.get(0).getGroup() + ", Match of axis: " + match, charts.get(0).getxAxis(), charts.get(0).getyAxis()); - result.concat = true; - - return result; - } - - /** - * Gets the base name of the data files of this chart. - * - * @return The base name of the data files of this chart. - */ - public String getBaseName() { - return baseName; - } - - /** - * Gets the name of the chart. - * - * @return The name of the chart. - */ - public String getName() { - return name; - } - - /** - * Gets the legend of the X axis of the chart. - * - * @return The legend of the X axis of the chart. - */ - public String getxAxis() { - return xAxis; - } - - /** - * Gets the legend of the Y axis of the chart. - * - * @return The legend of the Y axis of the chart. - */ - public String getyAxis() { - return yAxis; - } - - /** - * Gets the attributes stored in the chart as a List. - * - * @return The attributes list. - */ - public List getAttributes() { - return attributes; - } - - /** - * Writes the initial header and array definition to the JavaScript data file. - * - * @throws PerfCakeException - * When it was not possible to write the data. - */ - private void writeDataFileHeader() throws PerfCakeException { - final StringBuilder dataHeader = new StringBuilder("var "); - dataHeader.append(baseName); - dataHeader.append(" = [ [ "); - boolean first = true; - for (String attr : attributes) { - if (first) { - dataHeader.append("'"); - first = false; - } else { - dataHeader.append(", '"); - } - dataHeader.append(attr); - dataHeader.append("'"); - } - dataHeader.append(" ] ];\n\n"); - Utils.writeFileContent(dataFile, dataHeader.toString()); - } - - /** - * Writes a quick view HTML file that can display the chart during the test run. - * - * @throws PerfCakeException - * When it was not possible to store the quick view file. - */ - private void writeQuickView() throws PerfCakeException { - final Path quickViewFile = Paths.get(target.toString(), "data", baseName + ".html"); - final Properties quickViewProps = new Properties(); - quickViewProps.setProperty("baseName", baseName); - quickViewProps.setProperty("loader", getLoaderLine()); - Utils.copyTemplateFromResource("/charts/quick-view.html", quickViewFile, quickViewProps); - } - - /** - * Writes a description file containing all needed information to draw the chart. - * - * @throws PerfCakeException - * When it was not possible to store the description file. - */ - private void writeDescriptionFile() throws PerfCakeException { - final Path instructionsFile = Paths.get(target.toString(), "data", baseName + ".dat"); - Utils.writeFileContent(instructionsFile, getLoaderLine()); - } - - /** - * Gets the JavaScript instruction line that is used to draw the chart in the result report. - * This is exactly what is stored in the description file too. - * - * @return The JavaScript code to draw the chart. - */ - public String getLoaderLine() { - final StringBuilder line = new StringBuilder(concat ? "drawConcatChart(" : "drawChart("); - line.append(baseName); - line.append(", 'chart_"); - line.append(baseName); - line.append("_div', [0"); - - for (int i = 1; i < attributes.size(); i++) { - line.append(", "); - line.append(i); - } - - line.append("], '"); - line.append(xAxis); - line.append("', '"); - line.append(yAxis); - line.append("', '"); - line.append(name); - line.append("');\n"); - - return line.toString(); - } - - /** - * Gets a JavaScript line to be written to the data file that represents the current Measurement. - * All attributes required by the attributes list of this chart must be present in the measurement for the line to be returned. - * - * @param m - * The current measurement. - * @return The line representing the data in measurement specified by the attributes list of this chart, or null when there was some of - * the attributes missing. - */ - private String getResultLine(final Measurement m) { - StringBuilder sb = new StringBuilder(); - sb.append(baseName); - sb.append(".push(['"); - sb.append(Utils.timeToHMS(m.getTime())); - sb.append("'"); - - for (String attr : attributes) { - if (!attr.equals("Time")) { - sb.append(", "); - Object data = m.get(attr); - - // we do not have all required attributes, return an empty line - if (data == null) { - return ""; - } - - if (data instanceof String) { - sb.append("'"); - sb.append((String) data); - sb.append("'"); - } else { - sb.append(data.toString()); - } - } - } - - sb.append("]);\n"); - - return sb.toString(); - } - - /** - * Appends results to this chart based on the given Measurement. - * - * @param m - * The Measurement to be stored. - * @throws ReportingException - * When it was not possible to write the data. - */ - public void appendResult(final Measurement m) throws ReportingException { - String line = getResultLine(m); - - if (line != null && !"".equals(line)) { - try (FileOutputStream fos = new FileOutputStream(dataFile, true); OutputStreamWriter osw = new OutputStreamWriter(fos, Utils.getDefaultEncoding()); BufferedWriter bw = new BufferedWriter(osw)) { - bw.append(line); - } catch (IOException ioe) { - throw new ReportingException(String.format("Could not append data to the chart file %s.", dataFile.getAbsolutePath()), ioe); - } - } - } - - /** - * Gets the group of the current chart. - * - * @return The group name of this chart. - */ - public String getGroup() { - return group; - } - - /** - * Gets the type of the X axis. It can be either Time, Percents, or Iteration number. - * - * @return The type of the X axis. - */ - public PeriodType getxAxisType() { - return xAxisType; - } - - /** - * Was the chart created as a result of combining multiple other charts? - * - * @return True if and only if the chart was created as a combination of other charts. - */ - public boolean isCombined() { - return concat; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/pair.info deleted file mode 100755 index f661ff3..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76062/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76062 -comSha:e42bfeb13b49fc79592ff246fd0bf90c052091d4 -parentComSha:ef1463e4e9fe0a637d8ff2a7b1e482f68133a427 -BuggyFilePath:src/main/java/org/perfcake/reporting/destinations/chart/Chart.java -FixedFilePath:src/main/java/org/perfcake/reporting/destinations/chart/Chart.java -StartLineNum:193 -EndLineNum:193 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/comMsg.txt deleted file mode 100755 index c97bd7f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -findbugs issues cleaning, UtilsTest \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/diff.diff deleted file mode 100755 index d7ba266..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/org/perfcake/message/sender/AbstractSocketSender.java b/src/main/java/org/perfcake/message/sender/AbstractSocketSender.java -index 714c6321..f6523b2d 100644 ---- a/src/main/java/org/perfcake/message/sender/AbstractSocketSender.java -+++ b/src/main/java/org/perfcake/message/sender/AbstractSocketSender.java -@@ -24,0 +25 @@ import java.io.InputStreamReader; -+import java.io.OutputStreamWriter; -@@ -32,0 +34 @@ import org.perfcake.reporting.MeasurementUnit; -+import org.perfcake.util.Utils; -@@ -107,2 +109,2 @@ abstract public class AbstractSocketSender extends AbstractSender { -- out = new PrintWriter(socket.getOutputStream(), true); -- in = new BufferedReader(new InputStreamReader(socket.getInputStream())); -+ out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Utils.getDefaultEncoding()), true); -+ in = new BufferedReader(new InputStreamReader(socket.getInputStream(), Utils.getDefaultEncoding())); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/new/AbstractSocketSender.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/new/AbstractSocketSender.java deleted file mode 100755 index f6523b2..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/new/AbstractSocketSender.java +++ /dev/null @@ -1,174 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.message.sender; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Serializable; -import java.net.Socket; -import java.util.Map; - -import org.perfcake.PerfCakeException; -import org.perfcake.message.Message; -import org.perfcake.reporting.MeasurementUnit; -import org.perfcake.util.Utils; -import org.testng.log4testng.Logger; - -/** - * The common ancestor for all senders that are able to send messages through a socket. - * - * @author Martin Večeřa - */ -abstract public class AbstractSocketSender extends AbstractSender { - - /** - * The host of the socket. - */ - protected String host; - - /** - * The port of the socket - */ - protected int port; - - /** - * The socket for sending. - */ - protected Socket socket; - - /** - * A writer for message to be written into the socket. - */ - private PrintWriter out; - - /** - * A reader for response to be received from the socket. - */ - private BufferedReader in; - - /** - * The sender's logger. - */ - private final Logger log = Logger.getLogger(AbstractSocketSender.class); - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#init() - */ - @Override - public void init() throws Exception { - String[] parts = target.split(":", 2); - host = parts[0]; - port = Integer.valueOf(parts[1]); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#close() - */ - @Override - public void close() { - // closed per message - } - - /** - * Opens a socket on the {@link #host} address. - * - * @throws Exception - */ - abstract protected void openSocket() throws Exception; - - /** - * Opens the writer to an outbound socket's stream and the reader to read from inbound socket's stream. - * - * @throws Exception - */ - private void openStreams() throws Exception { - out = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Utils.getDefaultEncoding()), true); - in = new BufferedReader(new InputStreamReader(socket.getInputStream(), Utils.getDefaultEncoding())); - } - - /** - * Closes the socket along with the outbound and inbound streams. - */ - private void closeSocket() { - out.close(); - try { - in.close(); - } catch (IOException e) { - log.warn("Cannot close input stream.", e); - } - try { - socket.close(); - } catch (IOException e) { - log.warn("Cannot close socket.", e); - } - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#preSend(org.perfcake.message.Message, java.util.Map) - */ - @Override - public void preSend(final Message message, final Map properties) throws Exception { - super.preSend(message, properties); - openSocket(); - openStreams(); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#doSend(org.perfcake.message.Message, java.util.Map) - */ - @Override - public Serializable doSend(final Message message, final Map properties, final MeasurementUnit mu) throws Exception { - out.print(message.getPayload().toString()); - - if (out.checkError()) { // flush and check for error - throw new PerfCakeException(String.format("Error writing to a socket at %s:%d.", host, port)); - } - - StringBuilder sb = new StringBuilder(); - while (in.ready()) { - sb.append(in.readLine()); - } - - return sb.toString(); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#postSend(org.perfcake.message.Message) - */ - @Override - public void postSend(final Message message) throws Exception { - super.postSend(message); - closeSocket(); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/old/AbstractSocketSender.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/old/AbstractSocketSender.java deleted file mode 100755 index 714c632..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/old/AbstractSocketSender.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.message.sender; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.io.Serializable; -import java.net.Socket; -import java.util.Map; - -import org.perfcake.PerfCakeException; -import org.perfcake.message.Message; -import org.perfcake.reporting.MeasurementUnit; -import org.testng.log4testng.Logger; - -/** - * The common ancestor for all senders that are able to send messages through a socket. - * - * @author Martin Večeřa - */ -abstract public class AbstractSocketSender extends AbstractSender { - - /** - * The host of the socket. - */ - protected String host; - - /** - * The port of the socket - */ - protected int port; - - /** - * The socket for sending. - */ - protected Socket socket; - - /** - * A writer for message to be written into the socket. - */ - private PrintWriter out; - - /** - * A reader for response to be received from the socket. - */ - private BufferedReader in; - - /** - * The sender's logger. - */ - private final Logger log = Logger.getLogger(AbstractSocketSender.class); - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#init() - */ - @Override - public void init() throws Exception { - String[] parts = target.split(":", 2); - host = parts[0]; - port = Integer.valueOf(parts[1]); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#close() - */ - @Override - public void close() { - // closed per message - } - - /** - * Opens a socket on the {@link #host} address. - * - * @throws Exception - */ - abstract protected void openSocket() throws Exception; - - /** - * Opens the writer to an outbound socket's stream and the reader to read from inbound socket's stream. - * - * @throws Exception - */ - private void openStreams() throws Exception { - out = new PrintWriter(socket.getOutputStream(), true); - in = new BufferedReader(new InputStreamReader(socket.getInputStream())); - } - - /** - * Closes the socket along with the outbound and inbound streams. - */ - private void closeSocket() { - out.close(); - try { - in.close(); - } catch (IOException e) { - log.warn("Cannot close input stream.", e); - } - try { - socket.close(); - } catch (IOException e) { - log.warn("Cannot close socket.", e); - } - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#preSend(org.perfcake.message.Message, java.util.Map) - */ - @Override - public void preSend(final Message message, final Map properties) throws Exception { - super.preSend(message, properties); - openSocket(); - openStreams(); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#doSend(org.perfcake.message.Message, java.util.Map) - */ - @Override - public Serializable doSend(final Message message, final Map properties, final MeasurementUnit mu) throws Exception { - out.print(message.getPayload().toString()); - - if (out.checkError()) { // flush and check for error - throw new PerfCakeException(String.format("Error writing to a socket at %s:%d.", host, port)); - } - - StringBuilder sb = new StringBuilder(); - while (in.ready()) { - sb.append(in.readLine()); - } - - return sb.toString(); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.message.sender.AbstractSender#postSend(org.perfcake.message.Message) - */ - @Override - public void postSend(final Message message) throws Exception { - super.postSend(message); - closeSocket(); - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/pair.info deleted file mode 100755 index 12bb045..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76082/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76082 -comSha:fcc8a9f6f76d554be3c5a5b792f3b6019ae78b5a -parentComSha:691018806eb0762dfee4fb0b1a03efccdc7ce9e1 -BuggyFilePath:src/main/java/org/perfcake/message/sender/AbstractSocketSender.java -FixedFilePath:src/main/java/org/perfcake/message/sender/AbstractSocketSender.java -StartLineNum:107 -EndLineNum:107 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/comMsg.txt deleted file mode 100755 index c97bd7f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -findbugs issues cleaning, UtilsTest \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/diff.diff deleted file mode 100755 index 979bc58..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/main/java/org/perfcake/util/agent/AgentThread.java b/src/main/java/org/perfcake/util/agent/AgentThread.java -index e0b25fa6..eb0e1484 100644 ---- a/src/main/java/org/perfcake/util/agent/AgentThread.java -+++ b/src/main/java/org/perfcake/util/agent/AgentThread.java -@@ -6,0 +7 @@ import java.io.InputStreamReader; -+import java.io.OutputStreamWriter; -@@ -12,0 +14 @@ import java.util.Properties; -+import org.perfcake.util.Utils; -@@ -40 +42 @@ public class AgentThread implements Runnable { -- if (agentArgs != "" && agentArgs != null) { -+ if ("".equals(agentArgs) && agentArgs != null) { -@@ -69,2 +71,2 @@ public class AgentThread implements Runnable { -- BufferedReader br = new BufferedReader(new InputStreamReader(is)); -- PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); -+ BufferedReader br = new BufferedReader(new InputStreamReader(is, Utils.getDefaultEncoding())); -+ PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Utils.getDefaultEncoding()), true); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/new/AgentThread.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/new/AgentThread.java deleted file mode 100755 index eb0e148..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/new/AgentThread.java +++ /dev/null @@ -1,119 +0,0 @@ -package org.perfcake.util.agent; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.Properties; - -import org.perfcake.util.Utils; -import org.perfcake.util.agent.PerfCakeAgent.Memory; - -public class AgentThread implements Runnable { - - private String agentArgs; - - public AgentThread(String agentArgs) { - super(); - this.agentArgs = agentArgs; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - InetAddress host = null; - int port = 8849; // default - ServerSocket ssocket = null; - Socket socket = null; - InputStream is = null; - - try { - // parse agent properties - Properties props = new Properties(); - if ("".equals(agentArgs) && agentArgs != null) { - String[] args = agentArgs.split(","); - for (String arg : args) { - String[] keyValuePair = arg.split("="); - if (keyValuePair.length == 2) { - props.put(keyValuePair[0], keyValuePair[1]); - } else { - err("Invalid agent argument \"" + arg + "\" - ignoring"); - } - } - } - - if (props.get("port") != null) { - port = Integer.valueOf((String) props.get("port")); - } - - if (props.get("hostname") != null) { - host = InetAddress.getByName(props.getProperty("hostname")); - } else { - host = InetAddress.getLocalHost(); - } - - ssocket = new ServerSocket(port, 1, host); - while (true) { - log("Listening at " + ssocket.getInetAddress().getHostAddress() + " on port " + ssocket.getLocalPort()); - socket = ssocket.accept(); - log("Client connected from " + socket.getInetAddress().getHostAddress()); - is = socket.getInputStream(); - String input = null; - BufferedReader br = new BufferedReader(new InputStreamReader(is, Utils.getDefaultEncoding())); - PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Utils.getDefaultEncoding()), true); - while ((input = br.readLine()) != null) { - String response = "Unrecognized command!"; - Runtime rt = Runtime.getRuntime(); - try { - switch (Memory.valueOf(input.toUpperCase())) { - case FREE: - response = String.valueOf(rt.freeMemory()); - break; - case MAX: - response = String.valueOf(rt.maxMemory()); - break; - case TOTAL: - response = String.valueOf(rt.totalMemory()); - break; - case USED: - response = String.valueOf(rt.totalMemory() - rt.freeMemory()); - break; - } - } catch (IllegalArgumentException iae) { - err(iae.getLocalizedMessage()); - } - pw.println(response); - } - log("Client disconnected"); - } - - } catch (Throwable e) { - e.printStackTrace(); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - private static void log(String msg) { - System.out.println(PerfCakeAgent.class.getSimpleName() + " > " + msg); - } - - private static void err(String msg) { - System.err.println(PerfCakeAgent.class.getSimpleName() + " > ERROR: " + msg); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/old/AgentThread.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/old/AgentThread.java deleted file mode 100755 index e0b25fa..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/old/AgentThread.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.perfcake.util.agent; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.net.ServerSocket; -import java.net.Socket; -import java.util.Properties; - -import org.perfcake.util.agent.PerfCakeAgent.Memory; - -public class AgentThread implements Runnable { - - private String agentArgs; - - public AgentThread(String agentArgs) { - super(); - this.agentArgs = agentArgs; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - InetAddress host = null; - int port = 8849; // default - ServerSocket ssocket = null; - Socket socket = null; - InputStream is = null; - - try { - // parse agent properties - Properties props = new Properties(); - if (agentArgs != "" && agentArgs != null) { - String[] args = agentArgs.split(","); - for (String arg : args) { - String[] keyValuePair = arg.split("="); - if (keyValuePair.length == 2) { - props.put(keyValuePair[0], keyValuePair[1]); - } else { - err("Invalid agent argument \"" + arg + "\" - ignoring"); - } - } - } - - if (props.get("port") != null) { - port = Integer.valueOf((String) props.get("port")); - } - - if (props.get("hostname") != null) { - host = InetAddress.getByName(props.getProperty("hostname")); - } else { - host = InetAddress.getLocalHost(); - } - - ssocket = new ServerSocket(port, 1, host); - while (true) { - log("Listening at " + ssocket.getInetAddress().getHostAddress() + " on port " + ssocket.getLocalPort()); - socket = ssocket.accept(); - log("Client connected from " + socket.getInetAddress().getHostAddress()); - is = socket.getInputStream(); - String input = null; - BufferedReader br = new BufferedReader(new InputStreamReader(is)); - PrintWriter pw = new PrintWriter(socket.getOutputStream(), true); - while ((input = br.readLine()) != null) { - String response = "Unrecognized command!"; - Runtime rt = Runtime.getRuntime(); - try { - switch (Memory.valueOf(input.toUpperCase())) { - case FREE: - response = String.valueOf(rt.freeMemory()); - break; - case MAX: - response = String.valueOf(rt.maxMemory()); - break; - case TOTAL: - response = String.valueOf(rt.totalMemory()); - break; - case USED: - response = String.valueOf(rt.totalMemory() - rt.freeMemory()); - break; - } - } catch (IllegalArgumentException iae) { - err(iae.getLocalizedMessage()); - } - pw.println(response); - } - log("Client disconnected"); - } - - } catch (Throwable e) { - e.printStackTrace(); - } finally { - if (is != null) { - try { - is.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - private static void log(String msg) { - System.out.println(PerfCakeAgent.class.getSimpleName() + " > " + msg); - } - - private static void err(String msg) { - System.err.println(PerfCakeAgent.class.getSimpleName() + " > ERROR: " + msg); - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/pair.info deleted file mode 100755 index 21e32d3..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76112/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76112 -comSha:fcc8a9f6f76d554be3c5a5b792f3b6019ae78b5a -parentComSha:691018806eb0762dfee4fb0b1a03efccdc7ce9e1 -BuggyFilePath:src/main/java/org/perfcake/util/agent/AgentThread.java -FixedFilePath:src/main/java/org/perfcake/util/agent/AgentThread.java -StartLineNum:70 -EndLineNum:70 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/comMsg.txt deleted file mode 100755 index c97bd7f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -findbugs issues cleaning, UtilsTest \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/diff.diff deleted file mode 100755 index a2c984c..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/org/perfcake/reporting/reporters/MemoryUsageReporter.java b/src/main/java/org/perfcake/reporting/reporters/MemoryUsageReporter.java -index 61fe4002..d31611c6 100644 ---- a/src/main/java/org/perfcake/reporting/reporters/MemoryUsageReporter.java -+++ b/src/main/java/org/perfcake/reporting/reporters/MemoryUsageReporter.java -@@ -24,0 +25 @@ import java.io.InputStreamReader; -+import java.io.OutputStreamWriter; -@@ -37,0 +39 @@ import org.perfcake.reporting.reporters.accumulators.LastValueAccumulator; -+import org.perfcake.util.Utils; -@@ -133,2 +135,2 @@ public class MemoryUsageReporter extends AbstractReporter { -- requestWriter = new PrintWriter(socket.getOutputStream(), true); -- responseReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); -+ requestWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Utils.getDefaultEncoding()), true); -+ responseReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), Utils.getDefaultEncoding())); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/new/MemoryUsageReporter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/new/MemoryUsageReporter.java deleted file mode 100755 index d31611c..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/new/MemoryUsageReporter.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.reporting.reporters; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.net.Socket; - -import org.apache.log4j.Logger; -import org.perfcake.common.PeriodType; -import org.perfcake.reporting.Measurement; -import org.perfcake.reporting.MeasurementUnit; -import org.perfcake.reporting.Quantity; -import org.perfcake.reporting.ReportingException; -import org.perfcake.reporting.destinations.Destination; -import org.perfcake.reporting.reporters.accumulators.Accumulator; -import org.perfcake.reporting.reporters.accumulators.LastValueAccumulator; -import org.perfcake.util.Utils; -import org.perfcake.util.agent.PerfCakeAgent; -import org.perfcake.util.agent.PerfCakeAgent.Memory; - -/** - * Reporter that is able to get the memory usage information from a remote JVM, - * where {@link PerfCakeAgent} is deployed. It communicates with the {@link PerfCakeAgent} to - * get the information. - * - * @author Pavel Macík - * - */ -public class MemoryUsageReporter extends AbstractReporter { - - private static final long BYTES_IN_MIB = 1_048_576L; - - /** - * The reporter's logger. - */ - private static final Logger log = Logger.getLogger(MemoryUsageReporter.class); - - /** - * Hostname where {@link PerfCakeAgent} is listening on. - */ - private String agentHostname = "localhost"; - - /** - * Port number where {@link PerfCakeAgent} is listening on. - */ - private String agentPort = "8849"; - - /** - * IP address of the {@link PerfCakeAgent}. - */ - private InetAddress host; - - /** - * Socket used to communicate with the {@link PerfCakeAgent}. - */ - private Socket socket; - - /** - * Reader to read response from {@link PerfCakeAgent}. - */ - private BufferedReader responseReader; - - /** - * Writer to send requests to {@link PerfCakeAgent}. - */ - private PrintWriter requestWriter; - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#getAccumulator(java.lang.String, java.lang.Class) - */ - @SuppressWarnings("rawtypes") - @Override - protected Accumulator getAccumulator(final String key, final Class clazz) { - return new LastValueAccumulator(); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#doReset() - */ - @Override - protected void doReset() { - // nop - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#doReport(org.perfcake.nreporting.MeasurementUnit) - */ - @Override - protected void doReport(final MeasurementUnit mu) throws ReportingException { - // nop - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#start() - */ - @Override - public void start() { - super.start(); - try { - host = InetAddress.getByName(agentHostname); - if (log.isDebugEnabled()) { - log.debug("Creating socket " + host + ":" + agentPort + "..."); - } - socket = new Socket(host, Integer.valueOf(agentPort)); - requestWriter = new PrintWriter(new OutputStreamWriter(socket.getOutputStream(), Utils.getDefaultEncoding()), true); - responseReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), Utils.getDefaultEncoding())); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#stop() - */ - @Override - public void stop() { - super.stop(); - try { - socket.close(); - requestWriter.close(); - responseReader.close(); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - @Override - public void publishResult(final PeriodType periodType, final Destination d) throws ReportingException { - try { - Measurement m = newMeasurement(); - m.set("Used", (new Quantity((double) getMemoryUsage(Memory.USED) / BYTES_IN_MIB, "MiB"))); - m.set("Total", (new Quantity((double) getMemoryUsage(Memory.TOTAL) / BYTES_IN_MIB, "MiB"))); - m.set("Max", (new Quantity((double) getMemoryUsage(Memory.MAX) / BYTES_IN_MIB, "MiB"))); - d.report(m); - if (log.isDebugEnabled()) { - log.debug("Reporting: [" + m.toString() + "]"); - } - } catch (IOException ioe) { - throw new ReportingException("Could not publish result", ioe); - } - } - - /** - * Gets the memory usage information from the {@link PerfCakeAgent} the reporter is connected to. - * - * @param type - * {@link Memory} type. - * @return Amount of memory type in bytes. - * @throws IOException - */ - private long getMemoryUsage(final Memory type) throws IOException { - requestWriter.println(type.toString()); - return Long.valueOf(responseReader.readLine()); - } - - /** - * Used to read the value of agentHostname. - * - * @return The agent hostname value. - */ - public String getAgentHostname() { - return agentHostname; - } - - /** - * Used to set the value of agentHostname. - * - * @param agentHostname - * The agent hostname value to set. - */ - public void setAgentHostname(final String agentHostname) { - this.agentHostname = agentHostname; - } - - /** - * Used to read the value of agentPort. - * - * @return The agent port value. - */ - public String getAgentPort() { - return agentPort; - } - - /** - * Used to set the value of agentPort. - * - * @param agentPort - * The agent port value to set. - */ - public void setAgentPort(final String agentPort) { - this.agentPort = agentPort; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/old/MemoryUsageReporter.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/old/MemoryUsageReporter.java deleted file mode 100755 index 61fe400..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/old/MemoryUsageReporter.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.reporting.reporters; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.PrintWriter; -import java.net.InetAddress; -import java.net.Socket; - -import org.apache.log4j.Logger; -import org.perfcake.common.PeriodType; -import org.perfcake.reporting.Measurement; -import org.perfcake.reporting.MeasurementUnit; -import org.perfcake.reporting.Quantity; -import org.perfcake.reporting.ReportingException; -import org.perfcake.reporting.destinations.Destination; -import org.perfcake.reporting.reporters.accumulators.Accumulator; -import org.perfcake.reporting.reporters.accumulators.LastValueAccumulator; -import org.perfcake.util.agent.PerfCakeAgent; -import org.perfcake.util.agent.PerfCakeAgent.Memory; - -/** - * Reporter that is able to get the memory usage information from a remote JVM, - * where {@link PerfCakeAgent} is deployed. It communicates with the {@link PerfCakeAgent} to - * get the information. - * - * @author Pavel Macík - * - */ -public class MemoryUsageReporter extends AbstractReporter { - - private static final long BYTES_IN_MIB = 1_048_576L; - - /** - * The reporter's logger. - */ - private static final Logger log = Logger.getLogger(MemoryUsageReporter.class); - - /** - * Hostname where {@link PerfCakeAgent} is listening on. - */ - private String agentHostname = "localhost"; - - /** - * Port number where {@link PerfCakeAgent} is listening on. - */ - private String agentPort = "8849"; - - /** - * IP address of the {@link PerfCakeAgent}. - */ - private InetAddress host; - - /** - * Socket used to communicate with the {@link PerfCakeAgent}. - */ - private Socket socket; - - /** - * Reader to read response from {@link PerfCakeAgent}. - */ - private BufferedReader responseReader; - - /** - * Writer to send requests to {@link PerfCakeAgent}. - */ - private PrintWriter requestWriter; - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#getAccumulator(java.lang.String, java.lang.Class) - */ - @SuppressWarnings("rawtypes") - @Override - protected Accumulator getAccumulator(final String key, final Class clazz) { - return new LastValueAccumulator(); - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#doReset() - */ - @Override - protected void doReset() { - // nop - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#doReport(org.perfcake.nreporting.MeasurementUnit) - */ - @Override - protected void doReport(final MeasurementUnit mu) throws ReportingException { - // nop - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#start() - */ - @Override - public void start() { - super.start(); - try { - host = InetAddress.getByName(agentHostname); - if (log.isDebugEnabled()) { - log.debug("Creating socket " + host + ":" + agentPort + "..."); - } - socket = new Socket(host, Integer.valueOf(agentPort)); - requestWriter = new PrintWriter(socket.getOutputStream(), true); - responseReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - /* - * (non-Javadoc) - * - * @see org.perfcake.nreporting.reporters.AbstractReporter#stop() - */ - @Override - public void stop() { - super.stop(); - try { - socket.close(); - requestWriter.close(); - responseReader.close(); - } catch (IOException ioe) { - ioe.printStackTrace(); - } - } - - @Override - public void publishResult(final PeriodType periodType, final Destination d) throws ReportingException { - try { - Measurement m = newMeasurement(); - m.set("Used", (new Quantity((double) getMemoryUsage(Memory.USED) / BYTES_IN_MIB, "MiB"))); - m.set("Total", (new Quantity((double) getMemoryUsage(Memory.TOTAL) / BYTES_IN_MIB, "MiB"))); - m.set("Max", (new Quantity((double) getMemoryUsage(Memory.MAX) / BYTES_IN_MIB, "MiB"))); - d.report(m); - if (log.isDebugEnabled()) { - log.debug("Reporting: [" + m.toString() + "]"); - } - } catch (IOException ioe) { - throw new ReportingException("Could not publish result", ioe); - } - } - - /** - * Gets the memory usage information from the {@link PerfCakeAgent} the reporter is connected to. - * - * @param type - * {@link Memory} type. - * @return Amount of memory type in bytes. - * @throws IOException - */ - private long getMemoryUsage(final Memory type) throws IOException { - requestWriter.println(type.toString()); - return Long.valueOf(responseReader.readLine()); - } - - /** - * Used to read the value of agentHostname. - * - * @return The agent hostname value. - */ - public String getAgentHostname() { - return agentHostname; - } - - /** - * Used to set the value of agentHostname. - * - * @param agentHostname - * The agent hostname value to set. - */ - public void setAgentHostname(final String agentHostname) { - this.agentHostname = agentHostname; - } - - /** - * Used to read the value of agentPort. - * - * @return The agent port value. - */ - public String getAgentPort() { - return agentPort; - } - - /** - * Used to set the value of agentPort. - * - * @param agentPort - * The agent port value to set. - */ - public void setAgentPort(final String agentPort) { - this.agentPort = agentPort; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/pair.info deleted file mode 100755 index 8f7a603..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76223/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76223 -comSha:fcc8a9f6f76d554be3c5a5b792f3b6019ae78b5a -parentComSha:691018806eb0762dfee4fb0b1a03efccdc7ce9e1 -BuggyFilePath:src/main/java/org/perfcake/reporting/reporters/MemoryUsageReporter.java -FixedFilePath:src/main/java/org/perfcake/reporting/reporters/MemoryUsageReporter.java -StartLineNum:133 -EndLineNum:133 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/comMsg.txt deleted file mode 100755 index c5ede21..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -various tweaks, fixed findbugs warnings, switched site skin, fixed typos \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/diff.diff deleted file mode 100755 index ff61a5f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/main/java/org/perfcake/validation/RulesValidator.java b/src/main/java/org/perfcake/validation/RulesValidator.java -index 1faf9b47..bf0de347 100644 ---- a/src/main/java/org/perfcake/validation/RulesValidator.java -+++ b/src/main/java/org/perfcake/validation/RulesValidator.java -@@ -26,3 +26,2 @@ import org.w3c.dom.Element; --import java.io.BufferedReader; --import java.io.FileReader; --import java.io.StringReader; -+import java.io.*; -+import java.nio.charset.StandardCharsets; -@@ -107,2 +106 @@ public class RulesValidator implements MessageValidator { -- try (final FileReader fr = new FileReader(validationRuleFile); -- final BufferedReader br = new BufferedReader(fr)) { -+ try (final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(validationRuleFile), StandardCharsets.UTF_8))) { \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/new/RulesValidator.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/new/RulesValidator.java deleted file mode 100755 index bf0de34..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/new/RulesValidator.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.validation; - -import org.apache.log4j.Logger; -import org.perfcake.message.Message; -import org.w3c.dom.Element; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -/** - * Validates the message with the defined Drools rules. There is a custom DSL file making the rules specification easier. - * - * @author Marek Baluch - * @author Martin Večeřa - */ -public class RulesValidator implements MessageValidator { - - /** - * Message property key set on the original message for the validator to denote the original message and its response. - */ - public static final String RULES_ORIGINAL_MESSAGE = "rulesValidator-originalMessage"; - - /** - * A logger for this class. - */ - private static final Logger log = Logger.getLogger(RulesValidator.class); - - /** - * Rules helper that wraps the Drools logic. - */ - private RulesValidatorHelper rulesValidatorHelper; - - @Override - public boolean isValid(final Message originalMessage, final Message response) { - if (rulesValidatorHelper == null) { - log.error("Rules were not properly loaded."); - return false; - } - - final Map unusedAssertions = rulesValidatorHelper.validate(originalMessage, response); - - for (final Entry entry : unusedAssertions.entrySet()) { - if (log.isDebugEnabled()) { - log.debug(String.format("Drools message validation failed with message '%s' and rule '%s'.", response.toString(), entry.getValue())); - } - } - - if (!unusedAssertions.isEmpty()) { - if (log.isInfoEnabled()) { - log.info(String.format("Drools message validation failed with message '%s' - some rules failed, see previous log for more details.", response.toString())); - } - return false; - } - - return true; - } - - /** - * Creates a new {@link org.perfcake.validation.RulesValidatorHelper} based on the provided assertions. - * @param assertionsReader A buffered reader prepared to read the assertions. Each line represents a single assertion. - * @throws Exception When it was not possible to read and process the assertions. - */ - private void processAssertions(BufferedReader assertionsReader) throws Exception { - HashMap assertions = new HashMap<>(); - int lineNo = 0; - String line; - - while ((line = assertionsReader.readLine()) != null) { - line = StringUtil.trim(line); - if (!"".equals(line) && !line.startsWith("#")) { - assertions.put(lineNo, line); - lineNo++; - } - } - - rulesValidatorHelper = new RulesValidatorHelper(assertions); - } - - /** - * Sets the rules file from which the assertions are loaded. - * @param validationRuleFile The file name of the assertions file. - */ - public void setRules(final String validationRuleFile) { - try (final BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(validationRuleFile), StandardCharsets.UTF_8))) { - processAssertions(br); - } catch (final Exception ex) { - log.error("Error creating Drools base message validator.", ex); - } - } - - /** - * Sets the rules based on an XML element holding the assertions. - * @param validationRule The XML element with the assertions. - */ - public void setRules(final Element validationRule) { - try (final BufferedReader br = new BufferedReader(new StringReader(validationRule.getTextContent()))) { - processAssertions(br); - } catch (final Exception ex) { - log.error("Error creating Drools base message validator.", ex); - } - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/old/RulesValidator.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/old/RulesValidator.java deleted file mode 100755 index 1faf9b4..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/old/RulesValidator.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.validation; - -import org.apache.log4j.Logger; -import org.perfcake.message.Message; -import org.w3c.dom.Element; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.StringReader; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -/** - * Validates the message with the defined Drools rules. There is a custom DSL file making the rules specification easier. - * - * @author Marek Baluch - * @author Martin Večeřa - */ -public class RulesValidator implements MessageValidator { - - /** - * Message property key set on the original message for the validator to denote the original message and its response. - */ - public static final String RULES_ORIGINAL_MESSAGE = "rulesValidator-originalMessage"; - - /** - * A logger for this class. - */ - private static final Logger log = Logger.getLogger(RulesValidator.class); - - /** - * Rules helper that wraps the Drools logic. - */ - private RulesValidatorHelper rulesValidatorHelper; - - @Override - public boolean isValid(final Message originalMessage, final Message response) { - if (rulesValidatorHelper == null) { - log.error("Rules were not properly loaded."); - return false; - } - - final Map unusedAssertions = rulesValidatorHelper.validate(originalMessage, response); - - for (final Entry entry : unusedAssertions.entrySet()) { - if (log.isDebugEnabled()) { - log.debug(String.format("Drools message validation failed with message '%s' and rule '%s'.", response.toString(), entry.getValue())); - } - } - - if (!unusedAssertions.isEmpty()) { - if (log.isInfoEnabled()) { - log.info(String.format("Drools message validation failed with message '%s' - some rules failed, see previous log for more details.", response.toString())); - } - return false; - } - - return true; - } - - /** - * Creates a new {@link org.perfcake.validation.RulesValidatorHelper} based on the provided assertions. - * @param assertionsReader A buffered reader prepared to read the assertions. Each line represents a single assertion. - * @throws Exception When it was not possible to read and process the assertions. - */ - private void processAssertions(BufferedReader assertionsReader) throws Exception { - HashMap assertions = new HashMap<>(); - int lineNo = 0; - String line; - - while ((line = assertionsReader.readLine()) != null) { - line = StringUtil.trim(line); - if (!"".equals(line) && !line.startsWith("#")) { - assertions.put(lineNo, line); - lineNo++; - } - } - - rulesValidatorHelper = new RulesValidatorHelper(assertions); - } - - /** - * Sets the rules file from which the assertions are loaded. - * @param validationRuleFile The file name of the assertions file. - */ - public void setRules(final String validationRuleFile) { - try (final FileReader fr = new FileReader(validationRuleFile); - final BufferedReader br = new BufferedReader(fr)) { - processAssertions(br); - } catch (final Exception ex) { - log.error("Error creating Drools base message validator.", ex); - } - } - - /** - * Sets the rules based on an XML element holding the assertions. - * @param validationRule The XML element with the assertions. - */ - public void setRules(final Element validationRule) { - try (final BufferedReader br = new BufferedReader(new StringReader(validationRule.getTextContent()))) { - processAssertions(br); - } catch (final Exception ex) { - log.error("Error creating Drools base message validator.", ex); - } - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/pair.info deleted file mode 100755 index 7201ff9..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76268/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76268 -comSha:f118e3a2834310c9e7c56eaf8a67f30db46a5b03 -parentComSha:fec9bdf7c582604d3f4d5688b957774250520c9b -BuggyFilePath:src/main/java/org/perfcake/validation/RulesValidator.java -FixedFilePath:src/main/java/org/perfcake/validation/RulesValidator.java -StartLineNum:107 -EndLineNum:107 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/comMsg.txt deleted file mode 100755 index c5ede21..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -various tweaks, fixed findbugs warnings, switched site skin, fixed typos \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/diff.diff deleted file mode 100755 index 12571dc..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/org/perfcake/validation/ScriptValidator.java b/src/main/java/org/perfcake/validation/ScriptValidator.java -index a1e0a849..3e428464 100644 ---- a/src/main/java/org/perfcake/validation/ScriptValidator.java -+++ b/src/main/java/org/perfcake/validation/ScriptValidator.java -@@ -27,3 +27,2 @@ import javax.script.*; --import java.io.File; --import java.io.FileReader; --import java.io.IOException; -+import java.io.*; -+import java.nio.charset.StandardCharsets; -@@ -56 +55 @@ public class ScriptValidator implements MessageValidator { -- try (FileReader fr = new FileReader(new File(scriptFile))) { -+ try (Reader fr = new BufferedReader(new InputStreamReader(new FileInputStream(new File(scriptFile)), StandardCharsets.UTF_8))) { \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/new/ScriptValidator.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/new/ScriptValidator.java deleted file mode 100755 index 3e42846..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/new/ScriptValidator.java +++ /dev/null @@ -1,127 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.validation; - -import org.apache.log4j.Logger; -import org.perfcake.message.Message; -import org.w3c.dom.Element; - -import javax.script.*; -import java.io.*; -import java.nio.charset.StandardCharsets; - -/** - * Validates messages using Java Script Engine and the provided script. - * The script engine must be installed in the extensions directory. The original message is passed - * to the script in the 'originalMessage' property and the response is inserted as 'message', both using - * script bindings. Script return value is evaluated for validation success (true = passed, false = failed). - * - * @author Martin Večeřa - */ -public class ScriptValidator implements MessageValidator { - - private String engine; - private String script; - private String scriptFile; - private CompiledScript compiledScript = null; - - private static final Logger log = Logger.getLogger(ScriptValidator.class); - - private CompiledScript getCompiledScript() throws ScriptException, ValidationException { - if (compiledScript == null) { - ScriptEngineManager manager = new ScriptEngineManager(); - ScriptEngine engine = manager.getEngineByName(this.engine); - - if (script != null) { - compiledScript = ((Compilable) engine).compile(script); - } else if (scriptFile != null) { - try (Reader fr = new BufferedReader(new InputStreamReader(new FileInputStream(new File(scriptFile)), StandardCharsets.UTF_8))) { - compiledScript = ((Compilable) engine).compile(fr); - } catch (IOException e) { - throw new ValidationException("Error loading script file: ", e); - } - } else { - throw new ValidationException("No script was set."); - } - } - - return compiledScript; - } - - @Override - public boolean isValid(final Message originalMessage, Message response) { - boolean result = false; - - try { - CompiledScript script = getCompiledScript(); - Bindings b = script.getEngine().createBindings(); - b.put("originalMessage", originalMessage); - b.put("message", response); - b.put("log", log); - Object ret = script.eval(b); - if (ret instanceof Boolean) { - result = (Boolean) ret; - } - } catch (ScriptException | ValidationException e) { - log.warn("Error validating a message: ", e); - result = false; - } - - if (!result) { - log.info(String.format("Script validating failed with the message '%s' using script validator.", response.toString())); - } - return result; - } - - public String getEngine() { - return engine; - } - - public void setEngine(String engine) { - this.compiledScript = null; - this.engine = engine; - } - - public String getScript() { - return script; - } - - public void setScript(String script) { - this.scriptFile = null; - this.compiledScript = null; - this.script = script; - } - - public void setScript(Element script) { - this.scriptFile = null; - this.compiledScript = null; - this.script = script.getTextContent(); - } - - public String getScriptFile() { - return scriptFile; - } - - public void setScriptFile(String scriptFile) { - this.script = null; - this.compiledScript = null; - this.scriptFile = scriptFile; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/old/ScriptValidator.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/old/ScriptValidator.java deleted file mode 100755 index a1e0a84..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/old/ScriptValidator.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.validation; - -import org.apache.log4j.Logger; -import org.perfcake.message.Message; -import org.w3c.dom.Element; - -import javax.script.*; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; - -/** - * Validates messages using Java Script Engine and the provided script. - * The script engine must be installed in the extensions directory. The original message is passed - * to the script in the 'originalMessage' property and the response is inserted as 'message', both using - * script bindings. Script return value is evaluated for validation success (true = passed, false = failed). - * - * @author Martin Večeřa - */ -public class ScriptValidator implements MessageValidator { - - private String engine; - private String script; - private String scriptFile; - private CompiledScript compiledScript = null; - - private static final Logger log = Logger.getLogger(ScriptValidator.class); - - private CompiledScript getCompiledScript() throws ScriptException, ValidationException { - if (compiledScript == null) { - ScriptEngineManager manager = new ScriptEngineManager(); - ScriptEngine engine = manager.getEngineByName(this.engine); - - if (script != null) { - compiledScript = ((Compilable) engine).compile(script); - } else if (scriptFile != null) { - try (FileReader fr = new FileReader(new File(scriptFile))) { - compiledScript = ((Compilable) engine).compile(fr); - } catch (IOException e) { - throw new ValidationException("Error loading script file: ", e); - } - } else { - throw new ValidationException("No script was set."); - } - } - - return compiledScript; - } - - @Override - public boolean isValid(final Message originalMessage, Message response) { - boolean result = false; - - try { - CompiledScript script = getCompiledScript(); - Bindings b = script.getEngine().createBindings(); - b.put("originalMessage", originalMessage); - b.put("message", response); - b.put("log", log); - Object ret = script.eval(b); - if (ret instanceof Boolean) { - result = (Boolean) ret; - } - } catch (ScriptException | ValidationException e) { - log.warn("Error validating a message: ", e); - result = false; - } - - if (!result) { - log.info(String.format("Script validating failed with the message '%s' using script validator.", response.toString())); - } - return result; - } - - public String getEngine() { - return engine; - } - - public void setEngine(String engine) { - this.compiledScript = null; - this.engine = engine; - } - - public String getScript() { - return script; - } - - public void setScript(String script) { - this.scriptFile = null; - this.compiledScript = null; - this.script = script; - } - - public void setScript(Element script) { - this.scriptFile = null; - this.compiledScript = null; - this.script = script.getTextContent(); - } - - public String getScriptFile() { - return scriptFile; - } - - public void setScriptFile(String scriptFile) { - this.script = null; - this.compiledScript = null; - this.scriptFile = scriptFile; - } -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/pair.info deleted file mode 100755 index 560ddaa..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76278/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76278 -comSha:f118e3a2834310c9e7c56eaf8a67f30db46a5b03 -parentComSha:fec9bdf7c582604d3f4d5688b957774250520c9b -BuggyFilePath:src/main/java/org/perfcake/validation/ScriptValidator.java -FixedFilePath:src/main/java/org/perfcake/validation/ScriptValidator.java -StartLineNum:56 -EndLineNum:56 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/comMsg.txt deleted file mode 100755 index c97bd7f..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -findbugs issues cleaning, UtilsTest \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/diff.diff deleted file mode 100755 index ad3132a..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/org/perfcake/validation/RulesBuilder.java b/src/main/java/org/perfcake/validation/RulesBuilder.java -index 083931cd..8dec52eb 100644 ---- a/src/main/java/org/perfcake/validation/RulesBuilder.java -+++ b/src/main/java/org/perfcake/validation/RulesBuilder.java -@@ -31,0 +32 @@ import org.drools.rule.Package; -+import org.perfcake.util.Utils; -@@ -80 +81 @@ public class RulesBuilder { -- final String rule = String.format("rule \"Line %d\"\n dialect \"java\"\n when\n %s\n then\n > rulesUsed.remove(%d);\nend\n", lineNumber, assertion, lineNumber - 1, lineNumber);// rules -+ final String rule = String.format("rule \"Line %d\"%n dialect \"java\"%n when%n %s%n then%n > rulesUsed.remove(%d);%nend%n", lineNumber, assertion, lineNumber - 1, lineNumber);// rules -@@ -94 +95 @@ public class RulesBuilder { -- pBuilder.addPackageFromDrl(new StringReader(sBuilder.toString()), new InputStreamReader(dslis)); -+ pBuilder.addPackageFromDrl(new StringReader(sBuilder.toString()), new InputStreamReader(dslis, Utils.getDefaultEncoding())); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/new/RulesBuilder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/new/RulesBuilder.java deleted file mode 100755 index 8dec52e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/new/RulesBuilder.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.validation; - -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.util.Map; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; -import org.drools.compiler.PackageBuilder; -import org.drools.rule.Package; -import org.perfcake.util.Utils; - -/** - * - * @author Marek Baluch - * @author Lucie Fabriková - */ -public class RulesBuilder { - - static final Logger log = Logger.getLogger(RulesBuilder.class); - - private static final String resourcesDir = "src/main/resources/"; - - /** - * Build scenario assertions into a Drools package. - * - * @param assertions - * User assertions (usually defined in a PerfCake scenario file - * @param dsl - * DSL file on java class-path - * @return compiled Drools package - * @throws Exception - */ - public static Package build(final Map assertions, final String dsl) throws Exception { - System.out.println("BUILDING RULES"); - - if (log.isDebugEnabled()) { - log.debug("Building rules."); - } - - final StringBuilder sBuilder = new StringBuilder(); - sBuilder.append("package org.perfcake.validation\n\n"); - sBuilder.append("global java.util.Map rulesUsed\n"); - sBuilder.append("import java.util.Map\n"); - sBuilder.append("import org.perfcake.message.Message\n"); - sBuilder.append("import org.perfcake.validation.ValidatorUtil\n"); - sBuilder.append("import org.perfcake.validation.ValidatorUtil.MessagePart\n"); - sBuilder.append("import org.perfcake.validation.ValidatorUtil.Operator\n"); - sBuilder.append("import org.perfcake.validation.ValidatorUtil.Occurance\n"); - - // sBuilder.append("expander messageValidator.dsl\n"); - sBuilder.append("expander ").append(dsl).append("\n"); - - for (int i = 0; i < assertions.size(); i++) { - String assertion = assertions.get(i); - assertion = assertion.trim(); - if (assertion.length() > 0 && !assertion.startsWith("#")) { - final int lineNumber = i + 1; - - final String rule = String.format("rule \"Line %d\"%n dialect \"java\"%n when%n %s%n then%n > rulesUsed.remove(%d);%nend%n", lineNumber, assertion, lineNumber - 1, lineNumber);// rules - // numbered - // from 1 - - sBuilder.append(rule); - } - } - if (log.isDebugEnabled()) { - log.debug("Built rules:\n" + sBuilder.toString()); - } - - // InputStream dslis = RulesBuilder.class.getResourceAsStream(dsl); - final InputStream dslis = new FileInputStream(resourcesDir + dsl); - final PackageBuilder pBuilder = new PackageBuilder(); - pBuilder.addPackageFromDrl(new StringReader(sBuilder.toString()), new InputStreamReader(dslis, Utils.getDefaultEncoding())); - - // Check the builder for errors - if (pBuilder.hasErrors()) { - if (log.isEnabledFor(Level.ERROR)) { - log.error(pBuilder.getErrors().toString()); - } - throw new RuntimeException("Unable to compile rules."); - } - - // get the compiled package (which is serializable) - final Package pkg = pBuilder.getPackage(); - return pkg; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/old/RulesBuilder.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/old/RulesBuilder.java deleted file mode 100755 index 083931c..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/old/RulesBuilder.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.validation; - -import java.io.FileInputStream; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.StringReader; -import java.util.Map; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; -import org.drools.compiler.PackageBuilder; -import org.drools.rule.Package; - -/** - * - * @author Marek Baluch - * @author Lucie Fabriková - */ -public class RulesBuilder { - - static final Logger log = Logger.getLogger(RulesBuilder.class); - - private static final String resourcesDir = "src/main/resources/"; - - /** - * Build scenario assertions into a Drools package. - * - * @param assertions - * User assertions (usually defined in a PerfCake scenario file - * @param dsl - * DSL file on java class-path - * @return compiled Drools package - * @throws Exception - */ - public static Package build(final Map assertions, final String dsl) throws Exception { - System.out.println("BUILDING RULES"); - - if (log.isDebugEnabled()) { - log.debug("Building rules."); - } - - final StringBuilder sBuilder = new StringBuilder(); - sBuilder.append("package org.perfcake.validation\n\n"); - sBuilder.append("global java.util.Map rulesUsed\n"); - sBuilder.append("import java.util.Map\n"); - sBuilder.append("import org.perfcake.message.Message\n"); - sBuilder.append("import org.perfcake.validation.ValidatorUtil\n"); - sBuilder.append("import org.perfcake.validation.ValidatorUtil.MessagePart\n"); - sBuilder.append("import org.perfcake.validation.ValidatorUtil.Operator\n"); - sBuilder.append("import org.perfcake.validation.ValidatorUtil.Occurance\n"); - - // sBuilder.append("expander messageValidator.dsl\n"); - sBuilder.append("expander ").append(dsl).append("\n"); - - for (int i = 0; i < assertions.size(); i++) { - String assertion = assertions.get(i); - assertion = assertion.trim(); - if (assertion.length() > 0 && !assertion.startsWith("#")) { - final int lineNumber = i + 1; - - final String rule = String.format("rule \"Line %d\"\n dialect \"java\"\n when\n %s\n then\n > rulesUsed.remove(%d);\nend\n", lineNumber, assertion, lineNumber - 1, lineNumber);// rules - // numbered - // from 1 - - sBuilder.append(rule); - } - } - if (log.isDebugEnabled()) { - log.debug("Built rules:\n" + sBuilder.toString()); - } - - // InputStream dslis = RulesBuilder.class.getResourceAsStream(dsl); - final InputStream dslis = new FileInputStream(resourcesDir + dsl); - final PackageBuilder pBuilder = new PackageBuilder(); - pBuilder.addPackageFromDrl(new StringReader(sBuilder.toString()), new InputStreamReader(dslis)); - - // Check the builder for errors - if (pBuilder.hasErrors()) { - if (log.isEnabledFor(Level.ERROR)) { - log.error(pBuilder.getErrors().toString()); - } - throw new RuntimeException("Unable to compile rules."); - } - - // get the compiled package (which is serializable) - final Package pkg = pBuilder.getPackage(); - return pkg; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/pair.info deleted file mode 100755 index 5d683fd..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76359/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76359 -comSha:fcc8a9f6f76d554be3c5a5b792f3b6019ae78b5a -parentComSha:691018806eb0762dfee4fb0b1a03efccdc7ce9e1 -BuggyFilePath:src/main/java/org/perfcake/validation/RulesBuilder.java -FixedFilePath:src/main/java/org/perfcake/validation/RulesBuilder.java -StartLineNum:94 -EndLineNum:94 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/comMsg.txt deleted file mode 100755 index 7e0af5e..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Partial Findbugs Warnings cleanup [#49] \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/diff.diff deleted file mode 100755 index e8bddd1..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/perfcake/validation/ValidatorUtil.java b/src/main/java/org/perfcake/validation/ValidatorUtil.java -index d8c0d675..a06f3087 100644 ---- a/src/main/java/org/perfcake/validation/ValidatorUtil.java -+++ b/src/main/java/org/perfcake/validation/ValidatorUtil.java -@@ -22,0 +23 @@ import java.io.UnsupportedEncodingException; -+import java.nio.charset.Charset; -@@ -220 +221 @@ public final class ValidatorUtil { -- return new String((byte[]) data); -+ return new String((byte[]) data, Charset.defaultCharset()); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/new/ValidatorUtil.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/new/ValidatorUtil.java deleted file mode 100755 index a06f308..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/new/ValidatorUtil.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.validation; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; -import org.perfcake.message.Message; -import org.perfcake.util.Utils; - -/** - * Utilities used for messages validation. - * - * @author Pavel Macík - * @author Lucie Fabriková - */ -public final class ValidatorUtil { - - /** - * log4j logger. - */ - private static final Logger log = Logger.getLogger(ValidatorUtil.class); - - /** - * Non-public constructor to avoid instantiation. - */ - private ValidatorUtil() { - super(); - } - - /** - * TODO comment values' meaning - * Validation operator applied to message part and validated value. - */ - public enum Operator { - EQUALS, MATCHES, STARTS_WITH, CONTAINS, ENDS_WITH, EXISTS - } - - /** - * TODO comment values' meaning - * Message part that is validated. - */ - public enum MessagePart { - BODY, BODY_PART, PROPERTY, ATTACHMENT, HEADER_MESSAGE_ID, HEADER_TO, HEADER_FROM, HEADER_REPLY_TO, HEADER_FAULT_TO, HEADER_RELATES_TO, HEADER_ACTION - } - - /** - * TODO comment values' meaning - * Message occurance operator. - */ - public enum Occurance { - NONE, AT_LEAST, AT_MOST, EXACTLY - } - - /** - * Validates messages in the list in the interval between from and to borders included. It applies operator on the messages part and - * the valid value. - * - * @param list - * Message list. - * @param from - * Begin of the interval. - * @param to - * End of the interval. - * @param part - * Validated message part. - * @param partValue - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @return A boolean value indicating, if validation of all messages passed - * (true) or not (false). - */ - public static boolean validateMessages(final List list, final int from, final int to, final ValidatorUtil.MessagePart part, final String partValue, final ValidatorUtil.Operator operator, final String value) { - final int count = list.size(); - if (to <= from) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Arguments =" + from + " and =" + to + " are not valid interval borders! should be less than ."); - } - return false; - } else if (from < 0 || count < to) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Arguments =" + from + " and =" + to + " are out of list's bounds. The list contains " + count + " messages."); - } - return false; - } - boolean retVal = true; - for (int i = from; i < to; i++) { - retVal = retVal && validateMessage(list, i, part, partValue, operator, value); - } - return retVal; - } - - /** - * Validates message in the list on specified position. It - * applies operator on the message part and the - * valid value. - * - * @param list - * Message list. - * @param number - * Message position in the list. - * @param part - * Validated message part. - * @param partValue - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @return A boolean value indicating, if validation of the message passed - * (true) or not (false). - */ - public static boolean validateMessage(final List list, final int number, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value) { - final int count = list.size(); - - if (number < 0 || number >= count) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Invalid message position: " + number + " (the list contains " + count + " messages)"); - } - return false; - } else { - return validateMessage((list.get(number)), part, partName, operator, value); - } - } - - // TODO check all the cases, do they make sense? - public static Object getMessagePart(final org.perfcake.message.Message message, final ValidatorUtil.MessagePart part, final String partName) { - switch (part) { - case BODY: - return message.getPayload(); - case PROPERTY: - return message.getProperty(partName); - case HEADER_FROM: - return message.getHeader("from"); - case HEADER_TO: - return message.getHeader("to"); - case HEADER_REPLY_TO: - return message.getHeader("replyTo"); - case HEADER_FAULT_TO: - return message.getHeader("faultTo"); - case HEADER_RELATES_TO: - return message.getHeader("relatesTo"); - case HEADER_ACTION: - return message.getHeader("action"); - case ATTACHMENT: - return null; - case BODY_PART: - return null; - case HEADER_MESSAGE_ID: - return message.getHeader("messageId"); - } - - if (log.isEnabledFor(Level.ERROR)) { - log.error("This argument values combination (" + part.name() + " + " + partName + ") is not valid for message validation. Please consult with documentation for more information."); - } - - return null; - } - - private static boolean validatePart(final String str, final ValidatorUtil.Operator operator, final String value) { - if (str == null) { - return false; - } - - switch (operator) { - case EQUALS: - return str.equals(value); - case MATCHES: - return str.matches(value); - case STARTS_WITH: - return str.startsWith(value); - case CONTAINS: - return str.contains(value); - case ENDS_WITH: - return str.endsWith(value); - case EXISTS: - return true; // now it is evident that the part exists - } - - if (log.isEnabledFor(Level.ERROR)) { - log.error("This argument values combination (" + operator.name() + " + " + value + ") is not valid for message validation. Please consult with documentation for more information."); - } - - return false; - } - - private static String getStringData(final Object data) { - if (data == null) { - return null; - } else { - if (data instanceof byte[]) { - try { - return new String((byte[]) data, Utils.getDefaultEncoding()); - } catch (UnsupportedEncodingException e) { - return new String((byte[]) data, Charset.defaultCharset()); - } - } else { - return data.toString(); - } - } - } - - private static boolean validateData(final Object data, final ValidatorUtil.Operator operator, final String value) { - final String str = getStringData(data); - return validatePart(str, operator, value); - } - - public static boolean validateMessage(final Message message, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value) { - return validateData(getMessagePart(message, part, partName), operator, value); - } - - public static boolean validateMessageInverse(final Message message, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value) { - return !validateMessage(message, part, partName, operator, value); - } - - /** - * Validate that the list contains specified number of valid messages. - * - * @param list - * Message list. - * @param part - * Validated message part. - * @param partName - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @param occurance - * Type of message occurance in the list. - * @param treshold - * Treshold for the occurance metrics. - * @return A boolean value indicating, if validation of the message passed - * (true) or not (false) with actual occurance. - */ - public static boolean validateMessageOccurance(final List list, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value, final ValidatorUtil.Occurance occurance, final int treshold) { - switch (occurance) { - case NONE: - for (int i = 0; i < list.size(); i++) { - if (validateMessage(list, i, part, partName, operator, value)) { - return false; - } - } - return true; - case AT_LEAST: - return countMessages(list, part, partName, operator, value) >= treshold; - case AT_MOST: - return countMessages(list, part, partName, operator, value) <= treshold; - case EXACTLY: - return countMessages(list, part, partName, operator, value) == treshold; - } - - return false; - } - - /** - * Validate that the sublist of the list (between from and to (borders included)) contains specified number of valid messages. - * - * @param list - * Message list. - * @param from - * Begin of the interval. - * @param to - * End of the interval. - * @param part - * Validated message part. - * @param partName - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @param occurance - * Type of message occurance in the list. - * @param treshold - * Treshold for the occurance metrics. - * @return A boolean value indicating, if validation of the message passed - * (true) or not (false) with actual occurance. - */ - public static boolean validateMessageOccuranceOnInterval(final List list, final int from, final int to, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value, final ValidatorUtil.Occurance occurance, final int treshold) { - final int count = list.size(); - if (to <= from) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Arguments =" + from + " and =" + to + " are not valid interval borders! should be less than ."); - } - return false; - } else if (from < 0 || count < to) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Arguments =" + from + " and =" + to + " are out of list's bounds. The list contains " + count + " messages."); - } - return false; - } - final List subList = new ArrayList(); - for (int i = from; i <= to; i++) { - subList.add(list.get(i)); - } - return validateMessageOccurance(subList, part, partName, operator, value, occurance, treshold); - } - - /** - * Count messages in the list that match the criteria (pass the validation).. - * - * @param list - * Message list. - * @param part - * Validated message part. - * @param partName - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @return Number of messages in the list that match the criteria (pass the validation). - * @see #validateMessage(java.util.List, int, org.jboss.soa.esb.qa.perfcake.validation.ValidatorUtil.MessagePart, java.lang.String, org.jboss.soa.esb.qa.perfcake.validation.ValidatorUtil.Operator, - * java.lang.String) - */ - private static int countMessages(final List list, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value) { - int messageCount = 0; - for (int i = 0; i < list.size(); i++) { - if (validateMessage(list, i, part, partName, operator, value)) { - messageCount++; - } - } - return messageCount; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/old/ValidatorUtil.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/old/ValidatorUtil.java deleted file mode 100755 index d8c0d67..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/old/ValidatorUtil.java +++ /dev/null @@ -1,355 +0,0 @@ -/* - * -----------------------------------------------------------------------\ - * PerfCake - *   - * Copyright (C) 2010 - 2013 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.perfcake.validation; - -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; -import org.perfcake.message.Message; -import org.perfcake.util.Utils; - -/** - * Utilities used for messages validation. - * - * @author Pavel Macík - * @author Lucie Fabriková - */ -public final class ValidatorUtil { - - /** - * log4j logger. - */ - private static final Logger log = Logger.getLogger(ValidatorUtil.class); - - /** - * Non-public constructor to avoid instantiation. - */ - private ValidatorUtil() { - super(); - } - - /** - * TODO comment values' meaning - * Validation operator applied to message part and validated value. - */ - public enum Operator { - EQUALS, MATCHES, STARTS_WITH, CONTAINS, ENDS_WITH, EXISTS - } - - /** - * TODO comment values' meaning - * Message part that is validated. - */ - public enum MessagePart { - BODY, BODY_PART, PROPERTY, ATTACHMENT, HEADER_MESSAGE_ID, HEADER_TO, HEADER_FROM, HEADER_REPLY_TO, HEADER_FAULT_TO, HEADER_RELATES_TO, HEADER_ACTION - } - - /** - * TODO comment values' meaning - * Message occurance operator. - */ - public enum Occurance { - NONE, AT_LEAST, AT_MOST, EXACTLY - } - - /** - * Validates messages in the list in the interval between from and to borders included. It applies operator on the messages part and - * the valid value. - * - * @param list - * Message list. - * @param from - * Begin of the interval. - * @param to - * End of the interval. - * @param part - * Validated message part. - * @param partValue - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @return A boolean value indicating, if validation of all messages passed - * (true) or not (false). - */ - public static boolean validateMessages(final List list, final int from, final int to, final ValidatorUtil.MessagePart part, final String partValue, final ValidatorUtil.Operator operator, final String value) { - final int count = list.size(); - if (to <= from) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Arguments =" + from + " and =" + to + " are not valid interval borders! should be less than ."); - } - return false; - } else if (from < 0 || count < to) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Arguments =" + from + " and =" + to + " are out of list's bounds. The list contains " + count + " messages."); - } - return false; - } - boolean retVal = true; - for (int i = from; i < to; i++) { - retVal = retVal && validateMessage(list, i, part, partValue, operator, value); - } - return retVal; - } - - /** - * Validates message in the list on specified position. It - * applies operator on the message part and the - * valid value. - * - * @param list - * Message list. - * @param number - * Message position in the list. - * @param part - * Validated message part. - * @param partValue - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @return A boolean value indicating, if validation of the message passed - * (true) or not (false). - */ - public static boolean validateMessage(final List list, final int number, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value) { - final int count = list.size(); - - if (number < 0 || number >= count) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Invalid message position: " + number + " (the list contains " + count + " messages)"); - } - return false; - } else { - return validateMessage((list.get(number)), part, partName, operator, value); - } - } - - // TODO check all the cases, do they make sense? - public static Object getMessagePart(final org.perfcake.message.Message message, final ValidatorUtil.MessagePart part, final String partName) { - switch (part) { - case BODY: - return message.getPayload(); - case PROPERTY: - return message.getProperty(partName); - case HEADER_FROM: - return message.getHeader("from"); - case HEADER_TO: - return message.getHeader("to"); - case HEADER_REPLY_TO: - return message.getHeader("replyTo"); - case HEADER_FAULT_TO: - return message.getHeader("faultTo"); - case HEADER_RELATES_TO: - return message.getHeader("relatesTo"); - case HEADER_ACTION: - return message.getHeader("action"); - case ATTACHMENT: - return null; - case BODY_PART: - return null; - case HEADER_MESSAGE_ID: - return message.getHeader("messageId"); - } - - if (log.isEnabledFor(Level.ERROR)) { - log.error("This argument values combination (" + part.name() + " + " + partName + ") is not valid for message validation. Please consult with documentation for more information."); - } - - return null; - } - - private static boolean validatePart(final String str, final ValidatorUtil.Operator operator, final String value) { - if (str == null) { - return false; - } - - switch (operator) { - case EQUALS: - return str.equals(value); - case MATCHES: - return str.matches(value); - case STARTS_WITH: - return str.startsWith(value); - case CONTAINS: - return str.contains(value); - case ENDS_WITH: - return str.endsWith(value); - case EXISTS: - return true; // now it is evident that the part exists - } - - if (log.isEnabledFor(Level.ERROR)) { - log.error("This argument values combination (" + operator.name() + " + " + value + ") is not valid for message validation. Please consult with documentation for more information."); - } - - return false; - } - - private static String getStringData(final Object data) { - if (data == null) { - return null; - } else { - if (data instanceof byte[]) { - try { - return new String((byte[]) data, Utils.getDefaultEncoding()); - } catch (UnsupportedEncodingException e) { - return new String((byte[]) data); - } - } else { - return data.toString(); - } - } - } - - private static boolean validateData(final Object data, final ValidatorUtil.Operator operator, final String value) { - final String str = getStringData(data); - return validatePart(str, operator, value); - } - - public static boolean validateMessage(final Message message, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value) { - return validateData(getMessagePart(message, part, partName), operator, value); - } - - public static boolean validateMessageInverse(final Message message, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value) { - return !validateMessage(message, part, partName, operator, value); - } - - /** - * Validate that the list contains specified number of valid messages. - * - * @param list - * Message list. - * @param part - * Validated message part. - * @param partName - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @param occurance - * Type of message occurance in the list. - * @param treshold - * Treshold for the occurance metrics. - * @return A boolean value indicating, if validation of the message passed - * (true) or not (false) with actual occurance. - */ - public static boolean validateMessageOccurance(final List list, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value, final ValidatorUtil.Occurance occurance, final int treshold) { - switch (occurance) { - case NONE: - for (int i = 0; i < list.size(); i++) { - if (validateMessage(list, i, part, partName, operator, value)) { - return false; - } - } - return true; - case AT_LEAST: - return countMessages(list, part, partName, operator, value) >= treshold; - case AT_MOST: - return countMessages(list, part, partName, operator, value) <= treshold; - case EXACTLY: - return countMessages(list, part, partName, operator, value) == treshold; - } - - return false; - } - - /** - * Validate that the sublist of the list (between from and to (borders included)) contains specified number of valid messages. - * - * @param list - * Message list. - * @param from - * Begin of the interval. - * @param to - * End of the interval. - * @param part - * Validated message part. - * @param partName - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @param occurance - * Type of message occurance in the list. - * @param treshold - * Treshold for the occurance metrics. - * @return A boolean value indicating, if validation of the message passed - * (true) or not (false) with actual occurance. - */ - public static boolean validateMessageOccuranceOnInterval(final List list, final int from, final int to, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value, final ValidatorUtil.Occurance occurance, final int treshold) { - final int count = list.size(); - if (to <= from) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Arguments =" + from + " and =" + to + " are not valid interval borders! should be less than ."); - } - return false; - } else if (from < 0 || count < to) { - if (log.isEnabledFor(Level.ERROR)) { - log.error("Arguments =" + from + " and =" + to + " are out of list's bounds. The list contains " + count + " messages."); - } - return false; - } - final List subList = new ArrayList(); - for (int i = from; i <= to; i++) { - subList.add(list.get(i)); - } - return validateMessageOccurance(subList, part, partName, operator, value, occurance, treshold); - } - - /** - * Count messages in the list that match the criteria (pass the validation).. - * - * @param list - * Message list. - * @param part - * Validated message part. - * @param partName - * Actual value of the parametrized message part (e.g. when part is a body part, this value specifies which - * one). If it is not provided, make it null. - * @param operator - * Operator for validation. - * @param value - * Valid value of validated message part. - * @return Number of messages in the list that match the criteria (pass the validation). - * @see #validateMessage(java.util.List, int, org.jboss.soa.esb.qa.perfcake.validation.ValidatorUtil.MessagePart, java.lang.String, org.jboss.soa.esb.qa.perfcake.validation.ValidatorUtil.Operator, - * java.lang.String) - */ - private static int countMessages(final List list, final ValidatorUtil.MessagePart part, final String partName, final ValidatorUtil.Operator operator, final String value) { - int messageCount = 0; - for (int i = 0; i < list.size(); i++) { - if (validateMessage(list, i, part, partName, operator, value)) { - messageCount++; - } - } - return messageCount; - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/pair.info deleted file mode 100755 index b537357..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#76376/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:76376 -comSha:d4d092233d1b7fc61b9e2425dd8d0ede99982bf5 -parentComSha:8529336cef2f748d808b396f0edd6d70bc662f5b -BuggyFilePath:src/main/java/org/perfcake/validation/ValidatorUtil.java -FixedFilePath:src/main/java/org/perfcake/validation/ValidatorUtil.java -StartLineNum:220 -EndLineNum:220 -repoName:PerfCake#PerfCake \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/comMsg.txt deleted file mode 100755 index b74afd0..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixed some major int vs. long bugs in GraphStorage. thanks to findbugs \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/diff.diff deleted file mode 100755 index b13ae01..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/com/graphhopper/util/CmdArgs.java b/src/main/java/com/graphhopper/util/CmdArgs.java -index 778d25d26..a4b22c9d2 100644 ---- a/src/main/java/com/graphhopper/util/CmdArgs.java -+++ b/src/main/java/com/graphhopper/util/CmdArgs.java -@@ -17,0 +18 @@ package com.graphhopper.util; -+import java.io.FileInputStream; -@@ -19,0 +21 @@ import java.io.IOException; -+import java.io.InputStreamReader; -@@ -105 +107 @@ public class CmdArgs { -- Helper.loadProperties(map, new FileReader(fileStr)); -+ Helper.loadProperties(map, new InputStreamReader(new FileInputStream(fileStr), "UTF-8")); \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/new/CmdArgs.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/new/CmdArgs.java deleted file mode 100755 index a4b22c9..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/new/CmdArgs.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright 2012 Peter Karich - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.graphhopper.util; - -import java.io.FileInputStream; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -/** - * Stores command line options in a mapped. The case of the key is ignored. - * - * @author Peter Karich - */ -public class CmdArgs { - - private final Map map; - - public CmdArgs() { - this(new LinkedHashMap(5)); - } - - public CmdArgs(Map map) { - this.map = map; - } - - public CmdArgs put(String key, String str) { - map.put(key.toLowerCase(), str); - return this; - } - - public long getLong(String key, long _default) { - String str = get(key); - if (!Helper.isEmpty(str)) { - try { - return Long.parseLong(str); - } catch (Exception ex) { - } - } - return _default; - } - - public int getInt(String key, int _default) { - String str = get(key); - if (!Helper.isEmpty(str)) { - try { - return Integer.parseInt(str); - } catch (Exception ex) { - } - } - return _default; - } - - public boolean getBool(String key, boolean _default) { - String str = get(key); - if (!Helper.isEmpty(str)) { - try { - return Boolean.parseBoolean(str); - } catch (Exception ex) { - } - } - return _default; - } - - public double getDouble(String key, double _default) { - String str = get(key); - if (!Helper.isEmpty(str)) { - try { - return Double.parseDouble(str); - } catch (Exception ex) { - } - } - return _default; - } - - public String get(String key, String _default) { - String str = get(key); - if (Helper.isEmpty(str)) - return _default; - return str; - } - - String get(String key) { - if (Helper.isEmpty(key)) - return ""; - return map.get(key.toLowerCase()); - } - - public static CmdArgs readFromConfig(String fileStr) throws IOException { - Map map = new LinkedHashMap(); - Helper.loadProperties(map, new InputStreamReader(new FileInputStream(fileStr), "UTF-8")); - CmdArgs args = new CmdArgs(); - args.merge(map); - return args; - } - - public static CmdArgs read(String[] args) { - Map map = new LinkedHashMap(); - for (String arg : args) { - String strs[] = arg.split("\\="); - if (strs.length != 2) - continue; - - String key = strs[0]; - if (key.startsWith("-")) { - key = key.substring(1); - } - if (key.startsWith("-")) { - key = key.substring(1); - } - String value = strs[1]; - map.put(key, value); - } - - return new CmdArgs(map); - } - - public CmdArgs merge(CmdArgs read) { - return merge(read.map); - } - - CmdArgs merge(Map map) { - for (Entry e : map.entrySet()) { - if (Helper.isEmpty(e.getKey())) - continue; - this.map.put(e.getKey().toLowerCase(), e.getValue()); - } - return this; - } - - @Override public String toString() { - return map.toString(); - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/old/CmdArgs.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/old/CmdArgs.java deleted file mode 100755 index 778d25d..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/old/CmdArgs.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright 2012 Peter Karich - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.graphhopper.util; - -import java.io.FileReader; -import java.io.IOException; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -/** - * Stores command line options in a mapped. The case of the key is ignored. - * - * @author Peter Karich - */ -public class CmdArgs { - - private final Map map; - - public CmdArgs() { - this(new LinkedHashMap(5)); - } - - public CmdArgs(Map map) { - this.map = map; - } - - public CmdArgs put(String key, String str) { - map.put(key.toLowerCase(), str); - return this; - } - - public long getLong(String key, long _default) { - String str = get(key); - if (!Helper.isEmpty(str)) { - try { - return Long.parseLong(str); - } catch (Exception ex) { - } - } - return _default; - } - - public int getInt(String key, int _default) { - String str = get(key); - if (!Helper.isEmpty(str)) { - try { - return Integer.parseInt(str); - } catch (Exception ex) { - } - } - return _default; - } - - public boolean getBool(String key, boolean _default) { - String str = get(key); - if (!Helper.isEmpty(str)) { - try { - return Boolean.parseBoolean(str); - } catch (Exception ex) { - } - } - return _default; - } - - public double getDouble(String key, double _default) { - String str = get(key); - if (!Helper.isEmpty(str)) { - try { - return Double.parseDouble(str); - } catch (Exception ex) { - } - } - return _default; - } - - public String get(String key, String _default) { - String str = get(key); - if (Helper.isEmpty(str)) - return _default; - return str; - } - - String get(String key) { - if (Helper.isEmpty(key)) - return ""; - return map.get(key.toLowerCase()); - } - - public static CmdArgs readFromConfig(String fileStr) throws IOException { - Map map = new LinkedHashMap(); - Helper.loadProperties(map, new FileReader(fileStr)); - CmdArgs args = new CmdArgs(); - args.merge(map); - return args; - } - - public static CmdArgs read(String[] args) { - Map map = new LinkedHashMap(); - for (String arg : args) { - String strs[] = arg.split("\\="); - if (strs.length != 2) - continue; - - String key = strs[0]; - if (key.startsWith("-")) { - key = key.substring(1); - } - if (key.startsWith("-")) { - key = key.substring(1); - } - String value = strs[1]; - map.put(key, value); - } - - return new CmdArgs(map); - } - - public CmdArgs merge(CmdArgs read) { - return merge(read.map); - } - - CmdArgs merge(Map map) { - for (Entry e : map.entrySet()) { - if (Helper.isEmpty(e.getKey())) - continue; - this.map.put(e.getKey().toLowerCase(), e.getValue()); - } - return this; - } - - @Override public String toString() { - return map.toString(); - } -} \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/pair.info deleted file mode 100755 index c913307..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#77492/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:77492 -comSha:a2090c9029f14ae72fb37f0921cd29245bcb45c8 -parentComSha:3200cb32b231c905d172414ad6093ad744119842 -BuggyFilePath:src/main/java/com/graphhopper/util/CmdArgs.java -FixedFilePath:src/main/java/com/graphhopper/util/CmdArgs.java -StartLineNum:105 -EndLineNum:105 -repoName:graphhopper#graphhopper \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/comMsg.txt b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/comMsg.txt deleted file mode 100755 index 89265a3..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -FindBugs: DM_DEFAULT_ENCODING \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/diff.diff b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/diff.diff deleted file mode 100755 index 7c21ce5..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/diff.diff +++ /dev/null @@ -1,8 +0,0 @@ -diff --git a/src/main/java/de/is24/deadcode4j/analyzer/JavaFileAnalyzer.java b/src/main/java/de/is24/deadcode4j/analyzer/JavaFileAnalyzer.java -index e6311ed..6653a6c 100644 ---- a/src/main/java/de/is24/deadcode4j/analyzer/JavaFileAnalyzer.java -+++ b/src/main/java/de/is24/deadcode4j/analyzer/JavaFileAnalyzer.java -@@ -62,0 +63 @@ public abstract class JavaFileAnalyzer extends AnalyzerAdapter { -+ @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "The MavenProject does not provide the proper encoding") -@@ -140 +140,0 @@ public abstract class JavaFileAnalyzer extends AnalyzerAdapter { -- @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "The MavenProject does not provide the proper encoding") \ No newline at end of file diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/new/JavaFileAnalyzer.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/new/JavaFileAnalyzer.java deleted file mode 100755 index 6653a6c..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/new/JavaFileAnalyzer.java +++ /dev/null @@ -1,570 +0,0 @@ -package de.is24.deadcode4j.analyzer; - -import com.google.common.base.Optional; -import com.google.common.cache.LoadingCache; -import de.is24.deadcode4j.AnalysisContext; -import de.is24.deadcode4j.analyzer.javassist.ClassPoolAccessor; -import de.is24.guava.NonNullFunction; -import de.is24.guava.SequentialLoadingCache; -import de.is24.javaparser.Nodes; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import japa.parser.JavaParser; -import japa.parser.TokenMgrError; -import japa.parser.ast.CompilationUnit; -import japa.parser.ast.ImportDeclaration; -import japa.parser.ast.Node; -import japa.parser.ast.PackageDeclaration; -import japa.parser.ast.body.BodyDeclaration; -import japa.parser.ast.body.TypeDeclaration; -import javassist.CtClass; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static com.google.common.base.Optional.absent; -import static com.google.common.base.Optional.of; -import static com.google.common.base.Predicates.and; -import static com.google.common.base.Predicates.not; -import static com.google.common.collect.Iterables.getOnlyElement; -import static com.google.common.collect.Lists.newArrayList; -import static de.is24.deadcode4j.Utils.emptyIfNull; -import static de.is24.javassist.CtClasses.*; -import static de.is24.guava.NonNullFunctions.or; -import static de.is24.guava.NonNullFunctions.toFunction; -import static de.is24.javaparser.ImportDeclarations.isAsterisk; -import static de.is24.javaparser.ImportDeclarations.refersTo; -import static de.is24.javaparser.Nodes.getTypeName; -import static de.is24.javaparser.Nodes.prepend; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static org.apache.commons.io.IOUtils.closeQuietly; - -/** - * Serves as a base class with which to analyze java files. - * - * @since 1.6 - */ -public abstract class JavaFileAnalyzer extends AnalyzerAdapter { - - private static final String JAVA_PARSER_KEY = JavaFileAnalyzer.class.getName() + ":JavaParser"; - private static final NonNullFunction>> - JAVA_PARSER_SUPPLIER = - new NonNullFunction>>() { - @Nonnull - @Override - public LoadingCache> apply(@Nonnull final AnalysisContext analysisContext) { - return SequentialLoadingCache.createSingleValueCache(toFunction(new NonNullFunction>() { - @Nonnull - @Override - @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "The MavenProject does not provide the proper encoding") - public Optional apply(@Nonnull File file) { - Reader reader = null; - try { - reader = analysisContext.getModule().getEncoding() != null - ? new InputStreamReader(new FileInputStream(file), - analysisContext.getModule().getEncoding()) - : new FileReader(file); - return of(JavaParser.parse(reader, false)); - } catch (TokenMgrError e) { - throw new RuntimeException("Failed to parse [" + file + "]!", e); - } catch (Exception e) { - throw new RuntimeException("Failed to parse [" + file + "]!", e); - } finally { - closeQuietly(reader); - } - } - })); - } - }; - - private static final String TYPE_RESOLVER_KEY = JavaFileAnalyzer.class.getName() + ":TypeResolver"; - private static final NonNullFunction, Optional>> - TYPE_RESOLVER_SUPPLIER = - new NonNullFunction, Optional>>() { - @Nonnull - @Override - public NonNullFunction, Optional> apply(@Nonnull AnalysisContext analysisContext) { - final ClassPoolAccessor classPoolAccessor = ClassPoolAccessor.classPoolAccessorFor(analysisContext); - return new NonNullFunction, Optional>() { - @Nonnull - @Override - @SuppressWarnings("unchecked") - public Optional apply(@Nonnull Qualifier input) { - return or( - new FullyQualifiedTypeResolver(classPoolAccessor), - new InnerTypeResolver(), - new InheritedTypeResolver(classPoolAccessor), - new ImportedTypeResolver(classPoolAccessor), - new PackageTypeResolver(classPoolAccessor), - new AsteriskImportedTypeResolver(classPoolAccessor), - new JavaLangTypeResolver(classPoolAccessor) - ).apply(input); - } - }; - } - }; - - private static LoadingCache> getJavaFileParser(AnalysisContext analysisContext) { - return analysisContext.getOrCreateCacheEntry(JAVA_PARSER_KEY, JAVA_PARSER_SUPPLIER); - } - - private static NonNullFunction, Optional> getTypeResolver(AnalysisContext analysisContext) { - return analysisContext.getOrCreateCacheEntry(TYPE_RESOLVER_KEY, TYPE_RESOLVER_SUPPLIER); - } - - /** - * Resolves a type reference by means of the given {@code Qualifier}. - * - * @see de.is24.deadcode4j.analyzer.JavaFileAnalyzer.Qualifier - * @since 1.6 - */ - @Nonnull - protected static Optional resolveType(@Nonnull final AnalysisContext analysisContext, @Nonnull Qualifier qualifier) { - Optional resolvedClass = getTypeResolver(analysisContext).apply(qualifier); - if (!qualifier.allowsPartialResolving() && resolvedClass.isPresent()) { - if (!isFullyResolved(resolvedClass.get(), qualifier)) { - return absent(); - } - } - return resolvedClass; - } - - protected static boolean isFullyResolved(@Nonnull String resolvedClass, @Nonnull Qualifier qualifier) { - return resolvedClass.replace('$', '.').endsWith(qualifier.getFullQualifier().replace('$', '.')); - } - - @Override - public final void doAnalysis(@Nonnull AnalysisContext analysisContext, @Nonnull File file) { - if (file.getName().endsWith(".java")) { - CompilationUnit compilationUnit = getJavaFileParser(analysisContext).getUnchecked(file).get(); - logger.debug("Analyzing Java file [{}]...", file); - analyzeCompilationUnit(analysisContext, compilationUnit); - } - } - - /** - * Perform an analysis for the specified java file. - * Results must be reported via the capabilities of the {@link AnalysisContext}. - * - * @since 1.6 - */ - protected abstract void analyzeCompilationUnit(@Nonnull AnalysisContext analysisContext, @Nonnull CompilationUnit compilationUnit); - - /** - * Subclasses of {@code Qualifier} are used to resolve types by providing an environment to analyze. - * - * @see #resolveType(de.is24.deadcode4j.AnalysisContext, de.is24.deadcode4j.analyzer.JavaFileAnalyzer.Qualifier) - * @since 1.6 - */ - protected static abstract class Qualifier { - - @Nonnull - private final T reference; - @Nonnull - private final String name; - @Nonnull - private final String fullQualifier; - @Nullable - private final Qualifier parentQualifier; - @Nullable - private final Qualifier scopeQualifier; - - protected Qualifier(@Nonnull T reference, @Nullable Qualifier parent) { - this.reference = reference; - this.parentQualifier = parent; - this.scopeQualifier = getScopeQualifier(reference); - this.name = getName(reference); - this.fullQualifier = getFullQualifier(reference); - } - - protected Qualifier(@Nonnull T reference) { - this(reference, null); - } - - /** - * Must return the name of the level/scope this qualifier represents. - * - * @since 1.6 - */ - @Nonnull - protected abstract String getName(@Nonnull T reference); - - /** - * Must return the full qualifier name of this level/scope and below. - * - * @since 1.6 - */ - @Nonnull - protected abstract String getFullQualifier(@Nonnull T reference); - - /** - * Must return the qualifier of the level/scope below. - * - * @since 1.6 - */ - @Nullable - protected abstract Qualifier getScopeQualifier(@Nonnull T reference); - - /** - * Indicates if this qualifier can be resolved partially or must be resolved completely. - * - * @since 1.6 - */ - protected abstract boolean allowsPartialResolving(); - - @Nonnull - protected final T getNode() { - return this.reference; - } - - @Nonnull - protected final String getName() { - return this.name; - } - - @Nonnull - protected final String getFullQualifier() { - return fullQualifier; - } - - @Nullable - protected final Qualifier getParentQualifier() { - return this.parentQualifier; - } - - @Nullable - protected final Qualifier getScopeQualifier() { - return this.scopeQualifier; - } - - @Nonnull - protected final Qualifier getFirstQualifier() { - for (Qualifier currentScope = this, nextScope; ; ) { - nextScope = currentScope.getScopeQualifier(); - if (nextScope == null) { - return currentScope; - } - currentScope = nextScope; - } - } - - protected final boolean isSingleQualifier() { - return this == getFirstQualifier(); - } - - @Nonnull - protected final Iterable getTypeCandidates() { - if (!allowsPartialResolving()) { - return Collections.>singleton(this); - } - List> candidates = newArrayList(); - for (Qualifier loopQualifier = this; ; ) { - candidates.add(loopQualifier); - loopQualifier = loopQualifier.getScopeQualifier(); - if (loopQualifier == null) { - return candidates; - } - } - } - - /** - * This hook allows to further analyze an inherited type. - * - * @return the name of the class this qualifier refers to - * @since 1.6 - */ - @Nonnull - protected Optional examineInheritedType(@Nonnull CtClass referencingClazz, - @Nonnull CtClass inheritedClazz) { - return absent(); - } - - } - - private static abstract class RequiresClassPoolAccessor { - @Nonnull - protected final ClassPoolAccessor classPoolAccessor; - - protected RequiresClassPoolAccessor(@Nonnull ClassPoolAccessor classPoolAccessor) { - this.classPoolAccessor = classPoolAccessor; - } - } - - private static abstract class CandidatesResolver extends RequiresClassPoolAccessor - implements NonNullFunction, Optional> { - - protected CandidatesResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - protected Iterable calculatePrefixes(@Nonnull Qualifier topQualifier) { - String prefix = calculatePrefix(topQualifier); - return prefix != null ? singletonList(prefix) : Collections.emptyList(); - } - - @Nullable - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - return null; - } - - protected boolean skipResolvingFor(@Nonnull Qualifier candidate) { - return false; - } - - @Nonnull - @Override - public final Optional apply(@Nonnull Qualifier input) { - for (CharSequence prefix : calculatePrefixes(input)) { - for (Qualifier candidate : input.getTypeCandidates()) { - if (skipResolvingFor(candidate)) { - continue; - } - Optional resolvedClass = classPoolAccessor.resolveClass(prefix + candidate.getFullQualifier()); - if (resolvedClass.isPresent()) { - return resolvedClass; - } - } - } - return absent(); - } - - } - - private static class FullyQualifiedTypeResolver extends CandidatesResolver { - - public FullyQualifiedTypeResolver(ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - return ""; - } - - @Override - protected boolean skipResolvingFor(@Nonnull Qualifier candidate) { - return candidate.isSingleQualifier(); - } - - } - - private static class InnerTypeResolver implements NonNullFunction, Optional> { - - @Nonnull - @Override - public Optional apply(@Nonnull Qualifier typeReference) { - Qualifier firstQualifier = typeReference.getFirstQualifier(); - for (Node loopNode = typeReference.getNode(); ; ) { - Optional reference; - if (TypeDeclaration.class.isInstance(loopNode)) { - TypeDeclaration typeDeclaration = TypeDeclaration.class.cast(loopNode); - reference = resolveInnerReference(firstQualifier, singleton(typeDeclaration)); - if (reference.isPresent()) { - return reference; - } - reference = resolveInnerReference(firstQualifier, typeDeclaration.getMembers()); - if (reference.isPresent()) { - return reference; - } - } else if (CompilationUnit.class.isInstance(loopNode)) { - reference = resolveInnerReference(firstQualifier, CompilationUnit.class.cast(loopNode).getTypes()); - if (reference.isPresent()) - return reference; - } - loopNode = loopNode.getParentNode(); - if (loopNode == null) { - return absent(); - } - } - } - - @Nonnull - private Optional resolveInnerReference( - @Nonnull Qualifier firstQualifier, - @Nullable Iterable bodyDeclarations) { - for (TypeDeclaration typeDeclaration : emptyIfNull(bodyDeclarations).filter(TypeDeclaration.class)) { - if (firstQualifier.getName().equals(typeDeclaration.getName())) { - return of(resolveReferencedType(firstQualifier, typeDeclaration)); - } - } - return absent(); - } - - @Nonnull - private String resolveReferencedType(@Nonnull Qualifier qualifier, @Nonnull TypeDeclaration type) { - Qualifier parentQualifier = qualifier.getParentQualifier(); - if (parentQualifier != null) { - for (TypeDeclaration innerType : emptyIfNull(type.getMembers()).filter(TypeDeclaration.class)) { - if (parentQualifier.getName().equals(innerType.getName())) { - return resolveReferencedType(parentQualifier, innerType); - } - } - } - - return getTypeName(type); - } - - } - - private static class InheritedTypeResolver extends RequiresClassPoolAccessor - implements NonNullFunction, Optional> { - - public InheritedTypeResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - public Optional apply(@Nonnull Qualifier typeReference) { - String typeName = getTypeName(typeReference.getNode()); - CtClass clazz = getCtClass(classPoolAccessor.getClassPool(), typeName); - if (clazz == null) { - return absent(); - } - Qualifier firstQualifier = typeReference.getFirstQualifier(); - for (CtClass declaringClazz : getDeclaringClassesOf(clazz)) { - Optional inheritedType = resolveInheritedType(clazz, declaringClazz, firstQualifier); - if (inheritedType.isPresent()) { - return inheritedType; - } - } - return absent(); - } - - @Nonnull - private Optional resolveInheritedType(@Nonnull CtClass referencingClazz, - @Nonnull CtClass clazz, - @Nonnull Qualifier firstQualifier) { - @SuppressWarnings("unchecked") - Optional result = firstQualifier.examineInheritedType(referencingClazz, clazz); - if (result.isPresent()) { - return result; - } - result = checkNestedClasses(referencingClazz, getSuperclassOf(clazz), firstQualifier); - if (result.isPresent()) { - return result; - } - for (CtClass interfaceClazz : getInterfacesOf(clazz)) { - result = checkNestedClasses(referencingClazz, interfaceClazz, firstQualifier); - if (result.isPresent()) { - return result; - } - } - return absent(); - } - - @Nonnull - private Optional checkNestedClasses(@Nonnull CtClass referencingClazz, - @Nullable CtClass clazz, - @Nonnull Qualifier firstQualifier) { - if (clazz == null || isJavaLangObject(clazz)) { - return absent(); - } - for (CtClass nestedClass : getNestedClassesOf(clazz)) { - if (nestedClass.getName().substring(clazz.getName().length() + 1).equals(firstQualifier.getName())) { - return resolveNestedType(firstQualifier, nestedClass); - } - } - return resolveInheritedType(referencingClazz, clazz, firstQualifier); - } - - private Optional resolveNestedType(Qualifier qualifier, CtClass clazz) { - Qualifier parentQualifier = qualifier.getParentQualifier(); - if (parentQualifier != null) { - for (CtClass nestedClass : getNestedClassesOf(clazz)) { - if (nestedClass.getName().substring(clazz.getName().length() + 1) - .equals(parentQualifier.getName())) { - return resolveNestedType(parentQualifier, nestedClass); - } - } - } - return of(clazz.getName()); - } - - } - - private static class ImportedTypeResolver extends CandidatesResolver { - - public ImportedTypeResolver(ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nullable - @Override - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - String firstQualifier = topQualifier.getFirstQualifier().getName(); - CompilationUnit compilationUnit = Nodes.getCompilationUnit(topQualifier.getNode()); - ImportDeclaration importDeclaration = getOnlyElement(emptyIfNull(compilationUnit.getImports()).filter( - and(not(isAsterisk()), refersTo(firstQualifier))), null); - if (importDeclaration == null) { - return null; - } - StringBuilder buffy = prepend(importDeclaration.getName(), new StringBuilder()); - int beginIndex = buffy.length() - firstQualifier.length(); - return beginIndex == 0 ? "" : - buffy.replace(beginIndex - 1, buffy.length(), importDeclaration.isStatic() ? "$" : ".").toString(); - } - - } - - private static class PackageTypeResolver extends CandidatesResolver { - - public PackageTypeResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - PackageDeclaration aPackage = Nodes.getCompilationUnit(topQualifier.getNode()).getPackage(); - if (aPackage == null) { - return ""; - } - return prepend(aPackage.getName(), new StringBuilder("")).append(".").toString(); - } - - } - - private static class AsteriskImportedTypeResolver extends CandidatesResolver { - - public AsteriskImportedTypeResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - protected Iterable calculatePrefixes(@Nonnull Qualifier topQualifier) { - ArrayList asteriskImports = newArrayList(); - CompilationUnit compilationUnit = Nodes.getCompilationUnit(topQualifier.getNode()); - for (ImportDeclaration importDeclaration : - emptyIfNull(compilationUnit.getImports()).filter(isAsterisk())) { - StringBuilder buffy = prepend(importDeclaration.getName(), new StringBuilder()); - buffy.append(importDeclaration.isStatic() ? '$' : '.'); - asteriskImports.add(buffy.toString()); - } - return asteriskImports; - } - - } - - private static class JavaLangTypeResolver extends CandidatesResolver { - - public JavaLangTypeResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - return "java.lang."; - } - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/old/JavaFileAnalyzer.java b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/old/JavaFileAnalyzer.java deleted file mode 100755 index e6311ed..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/old/JavaFileAnalyzer.java +++ /dev/null @@ -1,570 +0,0 @@ -package de.is24.deadcode4j.analyzer; - -import com.google.common.base.Optional; -import com.google.common.cache.LoadingCache; -import de.is24.deadcode4j.AnalysisContext; -import de.is24.deadcode4j.analyzer.javassist.ClassPoolAccessor; -import de.is24.guava.NonNullFunction; -import de.is24.guava.SequentialLoadingCache; -import de.is24.javaparser.Nodes; -import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; -import japa.parser.JavaParser; -import japa.parser.TokenMgrError; -import japa.parser.ast.CompilationUnit; -import japa.parser.ast.ImportDeclaration; -import japa.parser.ast.Node; -import japa.parser.ast.PackageDeclaration; -import japa.parser.ast.body.BodyDeclaration; -import japa.parser.ast.body.TypeDeclaration; -import javassist.CtClass; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import java.io.*; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import static com.google.common.base.Optional.absent; -import static com.google.common.base.Optional.of; -import static com.google.common.base.Predicates.and; -import static com.google.common.base.Predicates.not; -import static com.google.common.collect.Iterables.getOnlyElement; -import static com.google.common.collect.Lists.newArrayList; -import static de.is24.deadcode4j.Utils.emptyIfNull; -import static de.is24.javassist.CtClasses.*; -import static de.is24.guava.NonNullFunctions.or; -import static de.is24.guava.NonNullFunctions.toFunction; -import static de.is24.javaparser.ImportDeclarations.isAsterisk; -import static de.is24.javaparser.ImportDeclarations.refersTo; -import static de.is24.javaparser.Nodes.getTypeName; -import static de.is24.javaparser.Nodes.prepend; -import static java.util.Collections.singleton; -import static java.util.Collections.singletonList; -import static org.apache.commons.io.IOUtils.closeQuietly; - -/** - * Serves as a base class with which to analyze java files. - * - * @since 1.6 - */ -public abstract class JavaFileAnalyzer extends AnalyzerAdapter { - - private static final String JAVA_PARSER_KEY = JavaFileAnalyzer.class.getName() + ":JavaParser"; - private static final NonNullFunction>> - JAVA_PARSER_SUPPLIER = - new NonNullFunction>>() { - @Nonnull - @Override - public LoadingCache> apply(@Nonnull final AnalysisContext analysisContext) { - return SequentialLoadingCache.createSingleValueCache(toFunction(new NonNullFunction>() { - @Nonnull - @Override - public Optional apply(@Nonnull File file) { - Reader reader = null; - try { - reader = analysisContext.getModule().getEncoding() != null - ? new InputStreamReader(new FileInputStream(file), - analysisContext.getModule().getEncoding()) - : new FileReader(file); - return of(JavaParser.parse(reader, false)); - } catch (TokenMgrError e) { - throw new RuntimeException("Failed to parse [" + file + "]!", e); - } catch (Exception e) { - throw new RuntimeException("Failed to parse [" + file + "]!", e); - } finally { - closeQuietly(reader); - } - } - })); - } - }; - - private static final String TYPE_RESOLVER_KEY = JavaFileAnalyzer.class.getName() + ":TypeResolver"; - private static final NonNullFunction, Optional>> - TYPE_RESOLVER_SUPPLIER = - new NonNullFunction, Optional>>() { - @Nonnull - @Override - public NonNullFunction, Optional> apply(@Nonnull AnalysisContext analysisContext) { - final ClassPoolAccessor classPoolAccessor = ClassPoolAccessor.classPoolAccessorFor(analysisContext); - return new NonNullFunction, Optional>() { - @Nonnull - @Override - @SuppressWarnings("unchecked") - public Optional apply(@Nonnull Qualifier input) { - return or( - new FullyQualifiedTypeResolver(classPoolAccessor), - new InnerTypeResolver(), - new InheritedTypeResolver(classPoolAccessor), - new ImportedTypeResolver(classPoolAccessor), - new PackageTypeResolver(classPoolAccessor), - new AsteriskImportedTypeResolver(classPoolAccessor), - new JavaLangTypeResolver(classPoolAccessor) - ).apply(input); - } - }; - } - }; - - private static LoadingCache> getJavaFileParser(AnalysisContext analysisContext) { - return analysisContext.getOrCreateCacheEntry(JAVA_PARSER_KEY, JAVA_PARSER_SUPPLIER); - } - - private static NonNullFunction, Optional> getTypeResolver(AnalysisContext analysisContext) { - return analysisContext.getOrCreateCacheEntry(TYPE_RESOLVER_KEY, TYPE_RESOLVER_SUPPLIER); - } - - /** - * Resolves a type reference by means of the given {@code Qualifier}. - * - * @see de.is24.deadcode4j.analyzer.JavaFileAnalyzer.Qualifier - * @since 1.6 - */ - @Nonnull - protected static Optional resolveType(@Nonnull final AnalysisContext analysisContext, @Nonnull Qualifier qualifier) { - Optional resolvedClass = getTypeResolver(analysisContext).apply(qualifier); - if (!qualifier.allowsPartialResolving() && resolvedClass.isPresent()) { - if (!isFullyResolved(resolvedClass.get(), qualifier)) { - return absent(); - } - } - return resolvedClass; - } - - protected static boolean isFullyResolved(@Nonnull String resolvedClass, @Nonnull Qualifier qualifier) { - return resolvedClass.replace('$', '.').endsWith(qualifier.getFullQualifier().replace('$', '.')); - } - - @Override - @SuppressFBWarnings(value = "DM_DEFAULT_ENCODING", justification = "The MavenProject does not provide the proper encoding") - public final void doAnalysis(@Nonnull AnalysisContext analysisContext, @Nonnull File file) { - if (file.getName().endsWith(".java")) { - CompilationUnit compilationUnit = getJavaFileParser(analysisContext).getUnchecked(file).get(); - logger.debug("Analyzing Java file [{}]...", file); - analyzeCompilationUnit(analysisContext, compilationUnit); - } - } - - /** - * Perform an analysis for the specified java file. - * Results must be reported via the capabilities of the {@link AnalysisContext}. - * - * @since 1.6 - */ - protected abstract void analyzeCompilationUnit(@Nonnull AnalysisContext analysisContext, @Nonnull CompilationUnit compilationUnit); - - /** - * Subclasses of {@code Qualifier} are used to resolve types by providing an environment to analyze. - * - * @see #resolveType(de.is24.deadcode4j.AnalysisContext, de.is24.deadcode4j.analyzer.JavaFileAnalyzer.Qualifier) - * @since 1.6 - */ - protected static abstract class Qualifier { - - @Nonnull - private final T reference; - @Nonnull - private final String name; - @Nonnull - private final String fullQualifier; - @Nullable - private final Qualifier parentQualifier; - @Nullable - private final Qualifier scopeQualifier; - - protected Qualifier(@Nonnull T reference, @Nullable Qualifier parent) { - this.reference = reference; - this.parentQualifier = parent; - this.scopeQualifier = getScopeQualifier(reference); - this.name = getName(reference); - this.fullQualifier = getFullQualifier(reference); - } - - protected Qualifier(@Nonnull T reference) { - this(reference, null); - } - - /** - * Must return the name of the level/scope this qualifier represents. - * - * @since 1.6 - */ - @Nonnull - protected abstract String getName(@Nonnull T reference); - - /** - * Must return the full qualifier name of this level/scope and below. - * - * @since 1.6 - */ - @Nonnull - protected abstract String getFullQualifier(@Nonnull T reference); - - /** - * Must return the qualifier of the level/scope below. - * - * @since 1.6 - */ - @Nullable - protected abstract Qualifier getScopeQualifier(@Nonnull T reference); - - /** - * Indicates if this qualifier can be resolved partially or must be resolved completely. - * - * @since 1.6 - */ - protected abstract boolean allowsPartialResolving(); - - @Nonnull - protected final T getNode() { - return this.reference; - } - - @Nonnull - protected final String getName() { - return this.name; - } - - @Nonnull - protected final String getFullQualifier() { - return fullQualifier; - } - - @Nullable - protected final Qualifier getParentQualifier() { - return this.parentQualifier; - } - - @Nullable - protected final Qualifier getScopeQualifier() { - return this.scopeQualifier; - } - - @Nonnull - protected final Qualifier getFirstQualifier() { - for (Qualifier currentScope = this, nextScope; ; ) { - nextScope = currentScope.getScopeQualifier(); - if (nextScope == null) { - return currentScope; - } - currentScope = nextScope; - } - } - - protected final boolean isSingleQualifier() { - return this == getFirstQualifier(); - } - - @Nonnull - protected final Iterable getTypeCandidates() { - if (!allowsPartialResolving()) { - return Collections.>singleton(this); - } - List> candidates = newArrayList(); - for (Qualifier loopQualifier = this; ; ) { - candidates.add(loopQualifier); - loopQualifier = loopQualifier.getScopeQualifier(); - if (loopQualifier == null) { - return candidates; - } - } - } - - /** - * This hook allows to further analyze an inherited type. - * - * @return the name of the class this qualifier refers to - * @since 1.6 - */ - @Nonnull - protected Optional examineInheritedType(@Nonnull CtClass referencingClazz, - @Nonnull CtClass inheritedClazz) { - return absent(); - } - - } - - private static abstract class RequiresClassPoolAccessor { - @Nonnull - protected final ClassPoolAccessor classPoolAccessor; - - protected RequiresClassPoolAccessor(@Nonnull ClassPoolAccessor classPoolAccessor) { - this.classPoolAccessor = classPoolAccessor; - } - } - - private static abstract class CandidatesResolver extends RequiresClassPoolAccessor - implements NonNullFunction, Optional> { - - protected CandidatesResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - protected Iterable calculatePrefixes(@Nonnull Qualifier topQualifier) { - String prefix = calculatePrefix(topQualifier); - return prefix != null ? singletonList(prefix) : Collections.emptyList(); - } - - @Nullable - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - return null; - } - - protected boolean skipResolvingFor(@Nonnull Qualifier candidate) { - return false; - } - - @Nonnull - @Override - public final Optional apply(@Nonnull Qualifier input) { - for (CharSequence prefix : calculatePrefixes(input)) { - for (Qualifier candidate : input.getTypeCandidates()) { - if (skipResolvingFor(candidate)) { - continue; - } - Optional resolvedClass = classPoolAccessor.resolveClass(prefix + candidate.getFullQualifier()); - if (resolvedClass.isPresent()) { - return resolvedClass; - } - } - } - return absent(); - } - - } - - private static class FullyQualifiedTypeResolver extends CandidatesResolver { - - public FullyQualifiedTypeResolver(ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - return ""; - } - - @Override - protected boolean skipResolvingFor(@Nonnull Qualifier candidate) { - return candidate.isSingleQualifier(); - } - - } - - private static class InnerTypeResolver implements NonNullFunction, Optional> { - - @Nonnull - @Override - public Optional apply(@Nonnull Qualifier typeReference) { - Qualifier firstQualifier = typeReference.getFirstQualifier(); - for (Node loopNode = typeReference.getNode(); ; ) { - Optional reference; - if (TypeDeclaration.class.isInstance(loopNode)) { - TypeDeclaration typeDeclaration = TypeDeclaration.class.cast(loopNode); - reference = resolveInnerReference(firstQualifier, singleton(typeDeclaration)); - if (reference.isPresent()) { - return reference; - } - reference = resolveInnerReference(firstQualifier, typeDeclaration.getMembers()); - if (reference.isPresent()) { - return reference; - } - } else if (CompilationUnit.class.isInstance(loopNode)) { - reference = resolveInnerReference(firstQualifier, CompilationUnit.class.cast(loopNode).getTypes()); - if (reference.isPresent()) - return reference; - } - loopNode = loopNode.getParentNode(); - if (loopNode == null) { - return absent(); - } - } - } - - @Nonnull - private Optional resolveInnerReference( - @Nonnull Qualifier firstQualifier, - @Nullable Iterable bodyDeclarations) { - for (TypeDeclaration typeDeclaration : emptyIfNull(bodyDeclarations).filter(TypeDeclaration.class)) { - if (firstQualifier.getName().equals(typeDeclaration.getName())) { - return of(resolveReferencedType(firstQualifier, typeDeclaration)); - } - } - return absent(); - } - - @Nonnull - private String resolveReferencedType(@Nonnull Qualifier qualifier, @Nonnull TypeDeclaration type) { - Qualifier parentQualifier = qualifier.getParentQualifier(); - if (parentQualifier != null) { - for (TypeDeclaration innerType : emptyIfNull(type.getMembers()).filter(TypeDeclaration.class)) { - if (parentQualifier.getName().equals(innerType.getName())) { - return resolveReferencedType(parentQualifier, innerType); - } - } - } - - return getTypeName(type); - } - - } - - private static class InheritedTypeResolver extends RequiresClassPoolAccessor - implements NonNullFunction, Optional> { - - public InheritedTypeResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - public Optional apply(@Nonnull Qualifier typeReference) { - String typeName = getTypeName(typeReference.getNode()); - CtClass clazz = getCtClass(classPoolAccessor.getClassPool(), typeName); - if (clazz == null) { - return absent(); - } - Qualifier firstQualifier = typeReference.getFirstQualifier(); - for (CtClass declaringClazz : getDeclaringClassesOf(clazz)) { - Optional inheritedType = resolveInheritedType(clazz, declaringClazz, firstQualifier); - if (inheritedType.isPresent()) { - return inheritedType; - } - } - return absent(); - } - - @Nonnull - private Optional resolveInheritedType(@Nonnull CtClass referencingClazz, - @Nonnull CtClass clazz, - @Nonnull Qualifier firstQualifier) { - @SuppressWarnings("unchecked") - Optional result = firstQualifier.examineInheritedType(referencingClazz, clazz); - if (result.isPresent()) { - return result; - } - result = checkNestedClasses(referencingClazz, getSuperclassOf(clazz), firstQualifier); - if (result.isPresent()) { - return result; - } - for (CtClass interfaceClazz : getInterfacesOf(clazz)) { - result = checkNestedClasses(referencingClazz, interfaceClazz, firstQualifier); - if (result.isPresent()) { - return result; - } - } - return absent(); - } - - @Nonnull - private Optional checkNestedClasses(@Nonnull CtClass referencingClazz, - @Nullable CtClass clazz, - @Nonnull Qualifier firstQualifier) { - if (clazz == null || isJavaLangObject(clazz)) { - return absent(); - } - for (CtClass nestedClass : getNestedClassesOf(clazz)) { - if (nestedClass.getName().substring(clazz.getName().length() + 1).equals(firstQualifier.getName())) { - return resolveNestedType(firstQualifier, nestedClass); - } - } - return resolveInheritedType(referencingClazz, clazz, firstQualifier); - } - - private Optional resolveNestedType(Qualifier qualifier, CtClass clazz) { - Qualifier parentQualifier = qualifier.getParentQualifier(); - if (parentQualifier != null) { - for (CtClass nestedClass : getNestedClassesOf(clazz)) { - if (nestedClass.getName().substring(clazz.getName().length() + 1) - .equals(parentQualifier.getName())) { - return resolveNestedType(parentQualifier, nestedClass); - } - } - } - return of(clazz.getName()); - } - - } - - private static class ImportedTypeResolver extends CandidatesResolver { - - public ImportedTypeResolver(ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nullable - @Override - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - String firstQualifier = topQualifier.getFirstQualifier().getName(); - CompilationUnit compilationUnit = Nodes.getCompilationUnit(topQualifier.getNode()); - ImportDeclaration importDeclaration = getOnlyElement(emptyIfNull(compilationUnit.getImports()).filter( - and(not(isAsterisk()), refersTo(firstQualifier))), null); - if (importDeclaration == null) { - return null; - } - StringBuilder buffy = prepend(importDeclaration.getName(), new StringBuilder()); - int beginIndex = buffy.length() - firstQualifier.length(); - return beginIndex == 0 ? "" : - buffy.replace(beginIndex - 1, buffy.length(), importDeclaration.isStatic() ? "$" : ".").toString(); - } - - } - - private static class PackageTypeResolver extends CandidatesResolver { - - public PackageTypeResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - PackageDeclaration aPackage = Nodes.getCompilationUnit(topQualifier.getNode()).getPackage(); - if (aPackage == null) { - return ""; - } - return prepend(aPackage.getName(), new StringBuilder("")).append(".").toString(); - } - - } - - private static class AsteriskImportedTypeResolver extends CandidatesResolver { - - public AsteriskImportedTypeResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - protected Iterable calculatePrefixes(@Nonnull Qualifier topQualifier) { - ArrayList asteriskImports = newArrayList(); - CompilationUnit compilationUnit = Nodes.getCompilationUnit(topQualifier.getNode()); - for (ImportDeclaration importDeclaration : - emptyIfNull(compilationUnit.getImports()).filter(isAsterisk())) { - StringBuilder buffy = prepend(importDeclaration.getName(), new StringBuilder()); - buffy.append(importDeclaration.isStatic() ? '$' : '.'); - asteriskImports.add(buffy.toString()); - } - return asteriskImports; - } - - } - - private static class JavaLangTypeResolver extends CandidatesResolver { - - public JavaLangTypeResolver(@Nonnull ClassPoolAccessor classPoolAccessor) { - super(classPoolAccessor); - } - - @Nonnull - @Override - protected String calculatePrefix(@Nonnull Qualifier topQualifier) { - return "java.lang."; - } - - } - -} diff --git a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/pair.info b/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/pair.info deleted file mode 100755 index 64d9884..0000000 --- a/All/FindBugs-DM_DEFAULT_ENCODING/FBViolation#86830/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:86830 -comSha:9f5ef558f07ead0e2dd09aa6223dd8d67994e0a4 -parentComSha:77b32064b6034ea6097d05bd043d947fec53e161 -BuggyFilePath:src/main/java/de/is24/deadcode4j/analyzer/JavaFileAnalyzer.java -FixedFilePath:src/main/java/de/is24/deadcode4j/analyzer/JavaFileAnalyzer.java -StartLineNum:66 -EndLineNum:66 -repoName:ImmobilienScout24#deadcode4j \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/comMsg.txt deleted file mode 100755 index 8f20277..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Declaration redundancy \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/diff.diff deleted file mode 100755 index 7356875..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/net/slipcor/pvparena/core/StringParser.java b/src/net/slipcor/pvparena/core/StringParser.java -index 93d4dcf3..40e52002 100644 ---- a/src/net/slipcor/pvparena/core/StringParser.java -+++ b/src/net/slipcor/pvparena/core/StringParser.java -@@ -35 +35 @@ public final class StringParser { -- public static final Debug DEBUG = new Debug(17); -+ private static final Debug DEBUG = new Debug(17); -@@ -40 +40 @@ public final class StringParser { -- public static Set positive = new HashSet(Arrays.asList( -+ public static final Set positive = new HashSet(Arrays.asList( -@@ -42 +42 @@ public final class StringParser { -- public static Set negative = new HashSet(Arrays.asList( -+ public static final Set negative = new HashSet(Arrays.asList( -@@ -587 +587 @@ public final class StringParser { -- public static String getWoolEnumFromChatColorEnum(final String color) { -+ private static String getWoolEnumFromChatColorEnum(final String color) { \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/new/StringParser.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/new/StringParser.java deleted file mode 100755 index 40e5200..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/new/StringParser.java +++ /dev/null @@ -1,720 +0,0 @@ -package net.slipcor.pvparena.core; - -import net.slipcor.pvparena.PVPArena; -import org.bukkit.ChatColor; -import org.bukkit.Color; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.*; -import org.bukkit.material.Dye; -import org.bukkit.material.Wool; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import java.util.*; - -/** - *

- * String Parser class
- * 
- *

- * provides methods to parse Objects to String and back - * - * @author slipcor - * @version v0.10.2 - */ - -public final class StringParser { - private static final String SAFE_BREAK = ""; - private static final String SAFE_PAGE_BREAK = ""; - private static final String SAFE_LORE_BREAK = ""; - - private static final Debug DEBUG = new Debug(17); - - private StringParser() { - } - - public static final Set positive = new HashSet(Arrays.asList( - "yes", "on", "true", "1")); - public static final Set negative = new HashSet(Arrays.asList( - "no", "off", "false", "0")); - - private static String codeCharacters(final String string, final boolean forward) { - final HashMap findReplace = new HashMap(); - String result = string; - if (forward) { - findReplace.put(":", "<>"); - findReplace.put("~", "<>"); - findReplace.put("|", "<>"); - findReplace.put(",", "<>"); - findReplace.put(ChatColor.COLOR_CHAR + "", "&"); - } else { - findReplace.put("<>", ":"); - findReplace.put("<>", "~"); - findReplace.put("<>", "|"); - findReplace.put("<>", ","); - result = ChatColor.translateAlternateColorCodes('&', result); - result = ChatColor.translateAlternateColorCodes('?', result); - } - - for (String s : findReplace.keySet()) { - result = result.replace(s, findReplace.get(s)); - } - - return result; - } - - public static String colorize(final String string) { - return ChatColor.translateAlternateColorCodes('&', string) - .replace("&&", "&").replace("%%&%%", "&"); - } - - public static String[] colorize(final List stringList) { - final String[] result = new String[stringList.size()]; - - for (int i = 0; i < stringList.size(); i++) { - result[i] = colorize(stringList.get(i)); - } - return result; - } - - /** - * color an integer if bigger than 0 - * - * @param timed the integer to color - * @return a colored string - */ - public static String colorVar(final int timed) { - return colorVar(String.valueOf(timed), timed > 0); - } - - /** - * color a boolean based on value - * - * @param value the boolean to color - * @return a colored string - */ - public static String colorVar(final boolean value) { - return colorVar(String.valueOf(value), value); - } - - public static String colorVar(final double value) { - return colorVar(String.valueOf(value), value > 0); - } - - /** - * color a string if set - * - * @param string the string to color - * @return a colored string - */ - public static String colorVar(final String string) { - if (string == null || string.equals("") || string.equals("none")) { - return colorVar("null", false); - } - return colorVar(string, true); - } - - /** - * color a string based on a given boolean - * - * @param string the string to color - * @param value true:green, false:red - * @return a colored string - */ - public static String colorVar(final String string, final boolean value) { - return (value ? ChatColor.GREEN.toString() : ChatColor.RED.toString()) + string - + ChatColor.WHITE; - } - - /** - * calculate a WOOL byte from a color enum - * - * @param color the string to parse - * @return the color short - */ - public static byte getColorDataFromENUM(final String color) { - - String wool = getWoolEnumFromChatColorEnum(color); - if (wool == null) { - wool = color; - } - /* - * DyeColor supports: WHITE, ORANGE, MAGENTA, LIGHT_BLUE, YELLOW, LIME, - * PINK, GRAY, SILVER, CYAN, PURPLE, BLUE, BROWN, GREEN, RED, BLACK; - */ - - for (DyeColor dc : DyeColor.values()) { - if (dc.name().equalsIgnoreCase(wool)) { - return (byte) (15 - dc.getDyeData()); - } - } - PVPArena.instance.getLogger().warning("unknown color enum: " + wool); - - return (byte) 0; - } - - public static ChatColor getChatColorFromWoolEnum(final String color) { - return ChatColor.valueOf(parseDyeColorToChatColor(color, true)); - } - - /** - * construct an itemstack out of a string - * - * @param string the formatted string: [itemid/name][~[dmg]]~[data]:[amount] - * @return the itemstack - */ - public static ItemStack getItemStackFromString(final String string) { - DEBUG.i("parsing itemstack string: " + string); - - // [itemid/name]~[dmg]|[enchantmentID]~level:[amount] - - - short dmg; - String data; - int amount = 1; - Material mat; - - String desc = null; - - String[] temp = string.split(":"); - - String prefix = null; - - for (String s : PVPArena.instance.getConfig().getStringList("materialprefixes")) { - if (string.startsWith(prefix+":")) { - prefix = s; - temp = string.substring(prefix.length()).split(":"); - } - } - - if (temp.length > 1) { - try { - amount = Integer.parseInt(temp[1]); - } catch (NumberFormatException e) { - PVPArena.instance.getLogger().severe("Material error. Maybe add " + temp[0] + " to materialprefixes?"); - return new ItemStack(Material.AIR); - } - if (temp.length > 2) { - desc = temp[2]; - } - } - - final Map enchants = new HashMap(); - if (temp[0].contains("|")) { - DEBUG.i("trying to add enchantment"); - final String[] temp2 = temp[0].split("\\|"); - DEBUG.i("temp2 length: " + temp2.length); - temp[0] = temp2[0]; - - DEBUG.i("correcting item temp to " + temp[0]); - - for (int i = 1; i < temp2.length; i++) { - - final String strEnch = temp2[i]; - if (strEnch.contains("~")) { - final String[] arrEnch = strEnch.split("~"); - final Enchantment ench = Enchantment.getById(Integer - .parseInt(arrEnch[0])); - final Integer enchLevel = Integer.parseInt(arrEnch[1]); - DEBUG.i("adding enchantment " + ench.getName() + " lvl " - + enchLevel); - enchants.put(ench, enchLevel); - } - } - } - - temp = temp[0].split("~"); - - mat = parseMat(prefix==null?temp[0]:prefix+":"+temp[0]); - if (mat != null) { - if (temp.length == 1) { - // [itemid/name]:[amount] - - final ItemStack itemStack = new ItemStack(mat, amount); - for (Enchantment e : enchants.keySet()) { - DEBUG.i("processing enchantment " + e.getName()); - itemStack.addUnsafeEnchantment(e, enchants.get(e)); - } - - if (desc != null) { - ItemMeta meta = itemStack.getItemMeta(); - meta.setDisplayName(codeCharacters(desc, false)); - itemStack.setItemMeta(meta); - } - - return itemStack; - } - dmg = Short.parseShort(temp[1]); - if (temp.length == 2) { - // [itemid/name]~[dmg]:[amount] - final ItemStack itemStack = new ItemStack(mat, amount, dmg); - for (Enchantment e : enchants.keySet()) { - itemStack.addUnsafeEnchantment(e, enchants.get(e)); - } - - if (desc != null) { - ItemMeta meta = itemStack.getItemMeta(); - meta.setDisplayName(codeCharacters(desc, false)); - itemStack.setItemMeta(meta); - } - - return itemStack; - } - // string: POTION~0~INVISIBILITYx0x300~Duration 15 seconds.:2:Stealth - - // ---> split(":"); - - // temp[0] = POTION~0~INVISIBILITYx0x300~Duration 15 seconds. - // temp[1] = 2 - // temp[2] = Stealth - - // ---> split("~"); - - // temp[0] = POTION - // temp[1] = 0 - // temp[2] = INVISIBILITYx0x300 - // temp[3] = Duration 15 seconds. - - final int location; - - if (temp.length > 3 && temp[3].contains(SAFE_LORE_BREAK)) { - location = 3; - } else { - location = 2; - } - - final String[] dataSplit = temp[location].split(SAFE_LORE_BREAK); - data = dataSplit[0]; - if (temp[2].contains(SAFE_BREAK)) { - if (mat == Material.POTION) { - data = temp[2]; - } else { - data = temp[2].split(SAFE_BREAK)[0]; - } - } - - final String lore = dataSplit.length > 1 ? dataSplit[1] : null; - - if (temp.length >= 3) { - // [itemid/name]~[dmg]~[data]:[amount] - final ItemStack itemStack = new ItemStack(mat, amount, dmg); - - - if (desc != null) { - ItemMeta meta = itemStack.getItemMeta(); - meta.setDisplayName(codeCharacters(desc, false)); - itemStack.setItemMeta(meta); - } - - if (mat == Material.INK_SACK) { - try { - itemStack.setData(new Dye(Byte.parseByte(data))); - } catch (Exception e) { - DEBUG.i( - "invalid dye data: " + data); - return itemStack; - } - } else if (mat == Material.WOOL) { - try { - itemStack.setData(new Wool(Byte.parseByte(data))); - } catch (Exception e) { - PVPArena.instance.getLogger().warning( - "invalid wool data: " + data); - return itemStack; - } - } else if (mat == Material.WRITTEN_BOOK - || mat == Material.BOOK_AND_QUILL) { - final BookMeta bookMeta = (BookMeta) itemStack.getItemMeta(); - try { - final String[] outer = data.split(SAFE_BREAK); - bookMeta.setAuthor(codeCharacters(outer[0], false)); - bookMeta.setTitle(codeCharacters(outer[1], false)); - final List pages = new ArrayList(); - final String[] inner = codeCharacters(outer[2], false).split( - SAFE_PAGE_BREAK); - Collections.addAll(pages, inner); - bookMeta.setPages(pages); - itemStack.setItemMeta(bookMeta); - } catch (Exception e) { - PVPArena.instance.getLogger().warning( - "invalid book data: " + data); - return itemStack; - } - } else if (itemStack.getType().name().startsWith("LEATHER_")) { - try { - final LeatherArmorMeta leatherMeta = (LeatherArmorMeta) itemStack - .getItemMeta(); - leatherMeta.setColor(Color.fromRGB(Integer.parseInt(data))); - itemStack.setItemMeta(leatherMeta); - } catch (Exception e) { - DEBUG.i( - "invalid leather data: " + data); - return itemStack; - } - } else if (itemStack.getType() == Material.SKULL_ITEM) { - try { - final SkullMeta skullMeta = (SkullMeta) itemStack.getItemMeta(); - skullMeta.setOwner(data); - itemStack.setItemMeta(skullMeta); - } catch (Exception e) { - PVPArena.instance.getLogger().warning( - "invalid skull data: " + data); - return itemStack; - } - } else if (itemStack.getType() == Material.POTION) { - // data = NAMEx1x100NAMEx2x100 - try { - final PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta(); - - String[] defs = data.split(SAFE_BREAK); - - for (String def : defs) { - String[] vals = def.split("x"); - potionMeta.addCustomEffect( - new PotionEffect( - PotionEffectType.getByName(vals[0]), - Integer.parseInt(vals[2]), - Integer.parseInt(vals[1])), true); - } - - if (lore != null - && !(mat == Material.WRITTEN_BOOK || mat == Material.BOOK_AND_QUILL)) { - final List lLore = new ArrayList(); - for (String line : lore.split(SAFE_BREAK)) { - lLore.add(codeCharacters(line, false)); - } - potionMeta.setLore(lLore); - } - - itemStack.setItemMeta(potionMeta); - } catch (Exception e) { - PVPArena.instance.getLogger().warning( - "invalid potion data: " + data); - return itemStack; - } - } else { - DEBUG.i("data not available for: " + mat.name()); - } - - if (lore != null - && !(mat == Material.WRITTEN_BOOK || mat == Material.BOOK_AND_QUILL)) { - final List lLore = new ArrayList(); - for (String line : lore.split(SAFE_BREAK)) { - lLore.add(codeCharacters(line, false)); - } - final ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setLore(lLore); - itemStack.setItemMeta(itemMeta); - } - - for (Enchantment e : enchants.keySet()) { - itemStack.addUnsafeEnchantment(e, enchants.get(e)); - } - - return itemStack; - } - } - return null; - } - - public static ItemStack[] getItemStacksFromString(final String string) { - if (string.equals("none")) { - return new ItemStack[0]; - } - - final String[] args = string.split(","); - - ItemStack[] result = new ItemStack[args.length]; - - int pos = 0; - - for (String s : args) { - result[pos++] = getItemStackFromString(s); - } - - return result; - } - - public static String getStringFromItemStacks(final ItemStack[] isItems) { - if (isItems == null) { - return "AIR"; - } - final String[] split = new String[isItems.length]; - - int pos = 0; - - for (ItemStack is : isItems) { - split[pos++] = getStringFromItemStack(is); - } - - return joinArray(trimAir(split), ","); - } - - private static String[] trimAir(final String[] sArray) { - final List list = new ArrayList(); - for (String item : sArray) { - if (item.equals("AIR")) { - continue; - } - list.add(item); - } - - if (list.size() < 1) { - return new String[]{"AIR"}; - } - - String[] result = new String[list.size()]; - int pos = 0; - for (String item : list) { - result[pos++] = item; - } - - return result; - } - - public static String getStringFromItemStack(final ItemStack itemStack) { - if (itemStack == null || itemStack.getType().equals(Material.AIR)) { - return "AIR"; - } - final StringBuilder temp = new StringBuilder(itemStack.getType().name()); - boolean durability = false; - if (itemStack.getDurability() != 0) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - if (itemStack.getType() == Material.INK_SACK || itemStack.getType() == Material.WOOL) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - temp.append('~'); - temp.append(String.valueOf(itemStack.getData().getData())); - } else if (itemStack.getType() == Material.WRITTEN_BOOK - || itemStack.getType() == Material.BOOK_AND_QUILL) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - final BookMeta bookMeta = (BookMeta) itemStack.getItemMeta(); - if (bookMeta != null && (bookMeta.getAuthor() != null) && (bookMeta.getTitle() != null) - && (bookMeta.getPages() != null)) { - temp.append('~'); - temp.append(codeCharacters(bookMeta.getAuthor(), true)); - temp.append(SAFE_BREAK); - temp.append(codeCharacters(bookMeta.getTitle(), true)); - temp.append(SAFE_BREAK); - temp.append(codeCharacters( - joinArray(bookMeta.getPages().toArray(), - SAFE_PAGE_BREAK), true)); - - } - } else if (itemStack.getType().name().startsWith("LEATHER_")) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - final LeatherArmorMeta leatherMeta = (LeatherArmorMeta) itemStack.getItemMeta(); - temp.append('~'); - temp.append(leatherMeta.getColor().asRGB()); - } else if (itemStack.getType() == Material.SKULL_ITEM) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - final SkullMeta skullMeta = (SkullMeta) itemStack.getItemMeta(); - temp.append('~'); - temp.append(skullMeta.getOwner()); - } else if (itemStack.getType() == Material.POTION) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - final PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta(); - temp.append('~'); - for (PotionEffect pe : potionMeta.getCustomEffects()) { - temp.append(pe.getType().getName()).append("x").append(pe.getAmplifier()).append("x").append(pe.getDuration()); - temp.append(SAFE_BREAK); - } - } - - if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasLore()) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - - temp.append('~'); - temp.append(SAFE_LORE_BREAK); - temp.append(codeCharacters( - joinArray(itemStack.getItemMeta().getLore() - .toArray(), SAFE_BREAK), true)); - } - final Map enchants = itemStack.getEnchantments(); - - if (enchants != null && !enchants.isEmpty()) { - for (Enchantment e : enchants.keySet()) { - temp.append('|'); - temp.append(String.valueOf(e.getId())); - temp.append('~'); - temp.append(enchants.get(e)); - } - } - - if (itemStack.getAmount() > 1 || itemStack.getItemMeta().hasDisplayName()) { - temp.append(':'); - temp.append(itemStack.getAmount()); - } - - if (itemStack.getItemMeta().hasDisplayName()) { - temp.append(':'); - temp.append(codeCharacters(itemStack.getItemMeta().getDisplayName(), true)); - } - - return temp.toString().replace(ChatColor.COLOR_CHAR, '&'); - } - - private static String getWoolEnumFromChatColorEnum(final String color) { - return parseDyeColorToChatColor(color, false); - } - - public static String joinArray(final Object[] array, final String glue) { - final StringBuilder result = new StringBuilder(""); - for (Object o : array) { - result.append(glue); - result.append(String.valueOf(o)); - } - if (result.length() <= glue.length()) { - return result.toString(); - } - return result.substring(glue.length()); - } - - public static String joinList(final List set, final String glue) { - final StringBuilder result = new StringBuilder(""); - for (Object o : set) { - result.append(glue); - result.append(String.valueOf(o)); - } - if (result.length() <= glue.length()) { - return result.toString(); - } - return result.substring(glue.length()); - } - - public static String joinSet(final Set set, final String glue) { - final StringBuilder result = new StringBuilder(""); - for (Object o : set) { - result.append(glue); - result.append(String.valueOf(o)); - } - if (result.length() <= glue.length()) { - return result.toString(); - } - return result.substring(glue.length()); - } - - private static String parseDyeColorToChatColor(final String color, final boolean forward) { - - /** - * wool colors: ORANGE, MAGENTA, LIGHT_BLUE, LIME, PINK, GRAY, SILVER, - * PURPLE, BLUE, GREEN, RED, CYAN; - * - * chat colors: GOLD, LIGHT_PURPLE, BLUE, GREEN, RED, DARK_GRAY, GRAY, - * DARK_PURPLE, DARK_BLUE, DARK_GREEN, DARK_RED, DARK_AQUA - * - * - * - * both colors (ignore): WHITE, YELLOW, BLACK - * - * colors not being able to parse: - * - * chat-AQUA, wool-brown - */ - final String[] wool = new String[]{"ORANGE", "MAGENTA", "LIGHT_BLUE", - "LIME", "PINK", "GRAY", "SILVER", "PURPLE", "BLUE", - "GREEN", "RED", "CYAN"}; - final String[] chat = new String[]{"GOLD", "LIGHT_PURPLE", "BLUE", - "GREEN", "RED", "DARK_GRAY", "GRAY", "DARK_PURPLE", "DARK_BLUE", - "DARK_GREEN", "DARK_RED", "DARK_AQUA"}; - - if (forward) { - for (int i = 0; i < wool.length; i++) { - if (color.equals(wool[i])) { - return chat[i]; - } - } - } else { - - for (int i = 0; i < chat.length; i++) { - if (color.equals(chat[i])) { - return wool[i]; - } - } - } - - return color; - } - - /** - * retrieve a material from a string - * - * @param string the string to parse - * @return the material - */ - private static Material parseMat(final String string) { - DEBUG.i("parsing material: " + string); - Material mat; - try { - mat = Material.getMaterial(Integer.parseInt(string)); - if (mat == null) { - mat = Material.getMaterial(string); - } - } catch (Exception e) { - mat = Material.getMaterial(string); - } - if (mat == null) { - PVPArena.instance.getLogger().warning( - "unrecognized material: " + string); - } - return mat; - } - - public static String[] shiftArrayBy(final String[] args, final int offset) { - final String[] newArgs = new String[args.length - offset]; - System.arraycopy(args, offset, newArgs, 0, args.length - offset); - return newArgs; - } - - public static String[] unShiftArrayBy(final String[] args, final int offset) { - final String[] newArgs = new String[args.length + offset]; - System.arraycopy(args, 0, newArgs, 1, args.length); - return newArgs; - } - - public static BlockFace parseToBlockFace(final String string) { - if (string.startsWith("o") || string.startsWith("i")) { - // out or in are just the same thing, reference to self with positive/negative values - return BlockFace.SELF; - } - BlockFace[] faces = new BlockFace[]{ - BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, - BlockFace.UP, BlockFace.DOWN}; - for (BlockFace face : faces) { - if (face.name().startsWith(string.toUpperCase())) { - return face; - } - } - return null; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/old/StringParser.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/old/StringParser.java deleted file mode 100755 index 93d4dcf..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/old/StringParser.java +++ /dev/null @@ -1,720 +0,0 @@ -package net.slipcor.pvparena.core; - -import net.slipcor.pvparena.PVPArena; -import org.bukkit.ChatColor; -import org.bukkit.Color; -import org.bukkit.DyeColor; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.*; -import org.bukkit.material.Dye; -import org.bukkit.material.Wool; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import java.util.*; - -/** - *

- * String Parser class
- * 
- *

- * provides methods to parse Objects to String and back - * - * @author slipcor - * @version v0.10.2 - */ - -public final class StringParser { - private static final String SAFE_BREAK = ""; - private static final String SAFE_PAGE_BREAK = ""; - private static final String SAFE_LORE_BREAK = ""; - - public static final Debug DEBUG = new Debug(17); - - private StringParser() { - } - - public static Set positive = new HashSet(Arrays.asList( - "yes", "on", "true", "1")); - public static Set negative = new HashSet(Arrays.asList( - "no", "off", "false", "0")); - - private static String codeCharacters(final String string, final boolean forward) { - final HashMap findReplace = new HashMap(); - String result = string; - if (forward) { - findReplace.put(":", "<>"); - findReplace.put("~", "<>"); - findReplace.put("|", "<>"); - findReplace.put(",", "<>"); - findReplace.put(ChatColor.COLOR_CHAR + "", "&"); - } else { - findReplace.put("<>", ":"); - findReplace.put("<>", "~"); - findReplace.put("<>", "|"); - findReplace.put("<>", ","); - result = ChatColor.translateAlternateColorCodes('&', result); - result = ChatColor.translateAlternateColorCodes('?', result); - } - - for (String s : findReplace.keySet()) { - result = result.replace(s, findReplace.get(s)); - } - - return result; - } - - public static String colorize(final String string) { - return ChatColor.translateAlternateColorCodes('&', string) - .replace("&&", "&").replace("%%&%%", "&"); - } - - public static String[] colorize(final List stringList) { - final String[] result = new String[stringList.size()]; - - for (int i = 0; i < stringList.size(); i++) { - result[i] = colorize(stringList.get(i)); - } - return result; - } - - /** - * color an integer if bigger than 0 - * - * @param timed the integer to color - * @return a colored string - */ - public static String colorVar(final int timed) { - return colorVar(String.valueOf(timed), timed > 0); - } - - /** - * color a boolean based on value - * - * @param value the boolean to color - * @return a colored string - */ - public static String colorVar(final boolean value) { - return colorVar(String.valueOf(value), value); - } - - public static String colorVar(final double value) { - return colorVar(String.valueOf(value), value > 0); - } - - /** - * color a string if set - * - * @param string the string to color - * @return a colored string - */ - public static String colorVar(final String string) { - if (string == null || string.equals("") || string.equals("none")) { - return colorVar("null", false); - } - return colorVar(string, true); - } - - /** - * color a string based on a given boolean - * - * @param string the string to color - * @param value true:green, false:red - * @return a colored string - */ - public static String colorVar(final String string, final boolean value) { - return (value ? ChatColor.GREEN.toString() : ChatColor.RED.toString()) + string - + ChatColor.WHITE; - } - - /** - * calculate a WOOL byte from a color enum - * - * @param color the string to parse - * @return the color short - */ - public static byte getColorDataFromENUM(final String color) { - - String wool = getWoolEnumFromChatColorEnum(color); - if (wool == null) { - wool = color; - } - /* - * DyeColor supports: WHITE, ORANGE, MAGENTA, LIGHT_BLUE, YELLOW, LIME, - * PINK, GRAY, SILVER, CYAN, PURPLE, BLUE, BROWN, GREEN, RED, BLACK; - */ - - for (DyeColor dc : DyeColor.values()) { - if (dc.name().equalsIgnoreCase(wool)) { - return (byte) (15 - dc.getDyeData()); - } - } - PVPArena.instance.getLogger().warning("unknown color enum: " + wool); - - return (byte) 0; - } - - public static ChatColor getChatColorFromWoolEnum(final String color) { - return ChatColor.valueOf(parseDyeColorToChatColor(color, true)); - } - - /** - * construct an itemstack out of a string - * - * @param string the formatted string: [itemid/name][~[dmg]]~[data]:[amount] - * @return the itemstack - */ - public static ItemStack getItemStackFromString(final String string) { - DEBUG.i("parsing itemstack string: " + string); - - // [itemid/name]~[dmg]|[enchantmentID]~level:[amount] - - - short dmg; - String data; - int amount = 1; - Material mat; - - String desc = null; - - String[] temp = string.split(":"); - - String prefix = null; - - for (String s : PVPArena.instance.getConfig().getStringList("materialprefixes")) { - if (string.startsWith(prefix+":")) { - prefix = s; - temp = string.substring(prefix.length()).split(":"); - } - } - - if (temp.length > 1) { - try { - amount = Integer.parseInt(temp[1]); - } catch (NumberFormatException e) { - PVPArena.instance.getLogger().severe("Material error. Maybe add " + temp[0] + " to materialprefixes?"); - return new ItemStack(Material.AIR); - } - if (temp.length > 2) { - desc = temp[2]; - } - } - - final Map enchants = new HashMap(); - if (temp[0].contains("|")) { - DEBUG.i("trying to add enchantment"); - final String[] temp2 = temp[0].split("\\|"); - DEBUG.i("temp2 length: " + temp2.length); - temp[0] = temp2[0]; - - DEBUG.i("correcting item temp to " + temp[0]); - - for (int i = 1; i < temp2.length; i++) { - - final String strEnch = temp2[i]; - if (strEnch.contains("~")) { - final String[] arrEnch = strEnch.split("~"); - final Enchantment ench = Enchantment.getById(Integer - .parseInt(arrEnch[0])); - final Integer enchLevel = Integer.parseInt(arrEnch[1]); - DEBUG.i("adding enchantment " + ench.getName() + " lvl " - + enchLevel); - enchants.put(ench, enchLevel); - } - } - } - - temp = temp[0].split("~"); - - mat = parseMat(prefix==null?temp[0]:prefix+":"+temp[0]); - if (mat != null) { - if (temp.length == 1) { - // [itemid/name]:[amount] - - final ItemStack itemStack = new ItemStack(mat, amount); - for (Enchantment e : enchants.keySet()) { - DEBUG.i("processing enchantment " + e.getName()); - itemStack.addUnsafeEnchantment(e, enchants.get(e)); - } - - if (desc != null) { - ItemMeta meta = itemStack.getItemMeta(); - meta.setDisplayName(codeCharacters(desc, false)); - itemStack.setItemMeta(meta); - } - - return itemStack; - } - dmg = Short.parseShort(temp[1]); - if (temp.length == 2) { - // [itemid/name]~[dmg]:[amount] - final ItemStack itemStack = new ItemStack(mat, amount, dmg); - for (Enchantment e : enchants.keySet()) { - itemStack.addUnsafeEnchantment(e, enchants.get(e)); - } - - if (desc != null) { - ItemMeta meta = itemStack.getItemMeta(); - meta.setDisplayName(codeCharacters(desc, false)); - itemStack.setItemMeta(meta); - } - - return itemStack; - } - // string: POTION~0~INVISIBILITYx0x300~Duration 15 seconds.:2:Stealth - - // ---> split(":"); - - // temp[0] = POTION~0~INVISIBILITYx0x300~Duration 15 seconds. - // temp[1] = 2 - // temp[2] = Stealth - - // ---> split("~"); - - // temp[0] = POTION - // temp[1] = 0 - // temp[2] = INVISIBILITYx0x300 - // temp[3] = Duration 15 seconds. - - final int location; - - if (temp.length > 3 && temp[3].contains(SAFE_LORE_BREAK)) { - location = 3; - } else { - location = 2; - } - - final String[] dataSplit = temp[location].split(SAFE_LORE_BREAK); - data = dataSplit[0]; - if (temp[2].contains(SAFE_BREAK)) { - if (mat == Material.POTION) { - data = temp[2]; - } else { - data = temp[2].split(SAFE_BREAK)[0]; - } - } - - final String lore = dataSplit.length > 1 ? dataSplit[1] : null; - - if (temp.length >= 3) { - // [itemid/name]~[dmg]~[data]:[amount] - final ItemStack itemStack = new ItemStack(mat, amount, dmg); - - - if (desc != null) { - ItemMeta meta = itemStack.getItemMeta(); - meta.setDisplayName(codeCharacters(desc, false)); - itemStack.setItemMeta(meta); - } - - if (mat == Material.INK_SACK) { - try { - itemStack.setData(new Dye(Byte.parseByte(data))); - } catch (Exception e) { - DEBUG.i( - "invalid dye data: " + data); - return itemStack; - } - } else if (mat == Material.WOOL) { - try { - itemStack.setData(new Wool(Byte.parseByte(data))); - } catch (Exception e) { - PVPArena.instance.getLogger().warning( - "invalid wool data: " + data); - return itemStack; - } - } else if (mat == Material.WRITTEN_BOOK - || mat == Material.BOOK_AND_QUILL) { - final BookMeta bookMeta = (BookMeta) itemStack.getItemMeta(); - try { - final String[] outer = data.split(SAFE_BREAK); - bookMeta.setAuthor(codeCharacters(outer[0], false)); - bookMeta.setTitle(codeCharacters(outer[1], false)); - final List pages = new ArrayList(); - final String[] inner = codeCharacters(outer[2], false).split( - SAFE_PAGE_BREAK); - Collections.addAll(pages, inner); - bookMeta.setPages(pages); - itemStack.setItemMeta(bookMeta); - } catch (Exception e) { - PVPArena.instance.getLogger().warning( - "invalid book data: " + data); - return itemStack; - } - } else if (itemStack.getType().name().startsWith("LEATHER_")) { - try { - final LeatherArmorMeta leatherMeta = (LeatherArmorMeta) itemStack - .getItemMeta(); - leatherMeta.setColor(Color.fromRGB(Integer.parseInt(data))); - itemStack.setItemMeta(leatherMeta); - } catch (Exception e) { - DEBUG.i( - "invalid leather data: " + data); - return itemStack; - } - } else if (itemStack.getType() == Material.SKULL_ITEM) { - try { - final SkullMeta skullMeta = (SkullMeta) itemStack.getItemMeta(); - skullMeta.setOwner(data); - itemStack.setItemMeta(skullMeta); - } catch (Exception e) { - PVPArena.instance.getLogger().warning( - "invalid skull data: " + data); - return itemStack; - } - } else if (itemStack.getType() == Material.POTION) { - // data = NAMEx1x100NAMEx2x100 - try { - final PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta(); - - String[] defs = data.split(SAFE_BREAK); - - for (String def : defs) { - String[] vals = def.split("x"); - potionMeta.addCustomEffect( - new PotionEffect( - PotionEffectType.getByName(vals[0]), - Integer.parseInt(vals[2]), - Integer.parseInt(vals[1])), true); - } - - if (lore != null - && !(mat == Material.WRITTEN_BOOK || mat == Material.BOOK_AND_QUILL)) { - final List lLore = new ArrayList(); - for (String line : lore.split(SAFE_BREAK)) { - lLore.add(codeCharacters(line, false)); - } - potionMeta.setLore(lLore); - } - - itemStack.setItemMeta(potionMeta); - } catch (Exception e) { - PVPArena.instance.getLogger().warning( - "invalid potion data: " + data); - return itemStack; - } - } else { - DEBUG.i("data not available for: " + mat.name()); - } - - if (lore != null - && !(mat == Material.WRITTEN_BOOK || mat == Material.BOOK_AND_QUILL)) { - final List lLore = new ArrayList(); - for (String line : lore.split(SAFE_BREAK)) { - lLore.add(codeCharacters(line, false)); - } - final ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setLore(lLore); - itemStack.setItemMeta(itemMeta); - } - - for (Enchantment e : enchants.keySet()) { - itemStack.addUnsafeEnchantment(e, enchants.get(e)); - } - - return itemStack; - } - } - return null; - } - - public static ItemStack[] getItemStacksFromString(final String string) { - if (string.equals("none")) { - return new ItemStack[0]; - } - - final String[] args = string.split(","); - - ItemStack[] result = new ItemStack[args.length]; - - int pos = 0; - - for (String s : args) { - result[pos++] = getItemStackFromString(s); - } - - return result; - } - - public static String getStringFromItemStacks(final ItemStack[] isItems) { - if (isItems == null) { - return "AIR"; - } - final String[] split = new String[isItems.length]; - - int pos = 0; - - for (ItemStack is : isItems) { - split[pos++] = getStringFromItemStack(is); - } - - return joinArray(trimAir(split), ","); - } - - private static String[] trimAir(final String[] sArray) { - final List list = new ArrayList(); - for (String item : sArray) { - if (item.equals("AIR")) { - continue; - } - list.add(item); - } - - if (list.size() < 1) { - return new String[]{"AIR"}; - } - - String[] result = new String[list.size()]; - int pos = 0; - for (String item : list) { - result[pos++] = item; - } - - return result; - } - - public static String getStringFromItemStack(final ItemStack itemStack) { - if (itemStack == null || itemStack.getType().equals(Material.AIR)) { - return "AIR"; - } - final StringBuilder temp = new StringBuilder(itemStack.getType().name()); - boolean durability = false; - if (itemStack.getDurability() != 0) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - if (itemStack.getType() == Material.INK_SACK || itemStack.getType() == Material.WOOL) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - temp.append('~'); - temp.append(String.valueOf(itemStack.getData().getData())); - } else if (itemStack.getType() == Material.WRITTEN_BOOK - || itemStack.getType() == Material.BOOK_AND_QUILL) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - final BookMeta bookMeta = (BookMeta) itemStack.getItemMeta(); - if (bookMeta != null && (bookMeta.getAuthor() != null) && (bookMeta.getTitle() != null) - && (bookMeta.getPages() != null)) { - temp.append('~'); - temp.append(codeCharacters(bookMeta.getAuthor(), true)); - temp.append(SAFE_BREAK); - temp.append(codeCharacters(bookMeta.getTitle(), true)); - temp.append(SAFE_BREAK); - temp.append(codeCharacters( - joinArray(bookMeta.getPages().toArray(), - SAFE_PAGE_BREAK), true)); - - } - } else if (itemStack.getType().name().startsWith("LEATHER_")) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - final LeatherArmorMeta leatherMeta = (LeatherArmorMeta) itemStack.getItemMeta(); - temp.append('~'); - temp.append(leatherMeta.getColor().asRGB()); - } else if (itemStack.getType() == Material.SKULL_ITEM) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - final SkullMeta skullMeta = (SkullMeta) itemStack.getItemMeta(); - temp.append('~'); - temp.append(skullMeta.getOwner()); - } else if (itemStack.getType() == Material.POTION) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - final PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta(); - temp.append('~'); - for (PotionEffect pe : potionMeta.getCustomEffects()) { - temp.append(pe.getType().getName()).append("x").append(pe.getAmplifier()).append("x").append(pe.getDuration()); - temp.append(SAFE_BREAK); - } - } - - if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasLore()) { - if (!durability) { - temp.append('~'); - temp.append(String.valueOf(itemStack.getDurability())); - durability = true; - } - - temp.append('~'); - temp.append(SAFE_LORE_BREAK); - temp.append(codeCharacters( - joinArray(itemStack.getItemMeta().getLore() - .toArray(), SAFE_BREAK), true)); - } - final Map enchants = itemStack.getEnchantments(); - - if (enchants != null && !enchants.isEmpty()) { - for (Enchantment e : enchants.keySet()) { - temp.append('|'); - temp.append(String.valueOf(e.getId())); - temp.append('~'); - temp.append(enchants.get(e)); - } - } - - if (itemStack.getAmount() > 1 || itemStack.getItemMeta().hasDisplayName()) { - temp.append(':'); - temp.append(itemStack.getAmount()); - } - - if (itemStack.getItemMeta().hasDisplayName()) { - temp.append(':'); - temp.append(codeCharacters(itemStack.getItemMeta().getDisplayName(), true)); - } - - return temp.toString().replace(ChatColor.COLOR_CHAR, '&'); - } - - public static String getWoolEnumFromChatColorEnum(final String color) { - return parseDyeColorToChatColor(color, false); - } - - public static String joinArray(final Object[] array, final String glue) { - final StringBuilder result = new StringBuilder(""); - for (Object o : array) { - result.append(glue); - result.append(String.valueOf(o)); - } - if (result.length() <= glue.length()) { - return result.toString(); - } - return result.substring(glue.length()); - } - - public static String joinList(final List set, final String glue) { - final StringBuilder result = new StringBuilder(""); - for (Object o : set) { - result.append(glue); - result.append(String.valueOf(o)); - } - if (result.length() <= glue.length()) { - return result.toString(); - } - return result.substring(glue.length()); - } - - public static String joinSet(final Set set, final String glue) { - final StringBuilder result = new StringBuilder(""); - for (Object o : set) { - result.append(glue); - result.append(String.valueOf(o)); - } - if (result.length() <= glue.length()) { - return result.toString(); - } - return result.substring(glue.length()); - } - - private static String parseDyeColorToChatColor(final String color, final boolean forward) { - - /** - * wool colors: ORANGE, MAGENTA, LIGHT_BLUE, LIME, PINK, GRAY, SILVER, - * PURPLE, BLUE, GREEN, RED, CYAN; - * - * chat colors: GOLD, LIGHT_PURPLE, BLUE, GREEN, RED, DARK_GRAY, GRAY, - * DARK_PURPLE, DARK_BLUE, DARK_GREEN, DARK_RED, DARK_AQUA - * - * - * - * both colors (ignore): WHITE, YELLOW, BLACK - * - * colors not being able to parse: - * - * chat-AQUA, wool-brown - */ - final String[] wool = new String[]{"ORANGE", "MAGENTA", "LIGHT_BLUE", - "LIME", "PINK", "GRAY", "SILVER", "PURPLE", "BLUE", - "GREEN", "RED", "CYAN"}; - final String[] chat = new String[]{"GOLD", "LIGHT_PURPLE", "BLUE", - "GREEN", "RED", "DARK_GRAY", "GRAY", "DARK_PURPLE", "DARK_BLUE", - "DARK_GREEN", "DARK_RED", "DARK_AQUA"}; - - if (forward) { - for (int i = 0; i < wool.length; i++) { - if (color.equals(wool[i])) { - return chat[i]; - } - } - } else { - - for (int i = 0; i < chat.length; i++) { - if (color.equals(chat[i])) { - return wool[i]; - } - } - } - - return color; - } - - /** - * retrieve a material from a string - * - * @param string the string to parse - * @return the material - */ - private static Material parseMat(final String string) { - DEBUG.i("parsing material: " + string); - Material mat; - try { - mat = Material.getMaterial(Integer.parseInt(string)); - if (mat == null) { - mat = Material.getMaterial(string); - } - } catch (Exception e) { - mat = Material.getMaterial(string); - } - if (mat == null) { - PVPArena.instance.getLogger().warning( - "unrecognized material: " + string); - } - return mat; - } - - public static String[] shiftArrayBy(final String[] args, final int offset) { - final String[] newArgs = new String[args.length - offset]; - System.arraycopy(args, offset, newArgs, 0, args.length - offset); - return newArgs; - } - - public static String[] unShiftArrayBy(final String[] args, final int offset) { - final String[] newArgs = new String[args.length + offset]; - System.arraycopy(args, 0, newArgs, 1, args.length); - return newArgs; - } - - public static BlockFace parseToBlockFace(final String string) { - if (string.startsWith("o") || string.startsWith("i")) { - // out or in are just the same thing, reference to self with positive/negative values - return BlockFace.SELF; - } - BlockFace[] faces = new BlockFace[]{ - BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST, - BlockFace.UP, BlockFace.DOWN}; - for (BlockFace face : faces) { - if (face.name().startsWith(string.toUpperCase())) { - return face; - } - } - return null; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/pair.info deleted file mode 100755 index cd90454..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#10328/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:10328 -comSha:82db803fad264e008c6fc17e9a7b95527505616e -parentComSha:5e4277b6ca35071da3e9df92c84d081d4119a176 -BuggyFilePath:src/net/slipcor/pvparena/core/StringParser.java -FixedFilePath:src/net/slipcor/pvparena/core/StringParser.java -StartLineNum:40 -EndLineNum:40 -repoName:slipcor#pvparena \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/comMsg.txt deleted file mode 100755 index b10192f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Converting java.logging to slf4j in structure gui, #155 \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/diff.diff deleted file mode 100755 index cb9fa0f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/diff.diff +++ /dev/null @@ -1,19 +0,0 @@ -diff --git a/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlignmentCalc.java b/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlignmentCalc.java -index 6c812344f..55dac677b 100644 ---- a/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlignmentCalc.java -+++ b/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlignmentCalc.java -@@ -26,2 +25,0 @@ package org.biojava.bio.structure.gui.util; --import java.util.logging.Logger; -- -@@ -33,0 +32,2 @@ import org.biojava.bio.structure.align.pairwise.AlternativeAlignment; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; -@@ -48 +48 @@ public class AlignmentCalc implements Runnable { -- public static Logger logger = Logger.getLogger("org.biojava"); -+ private static final Logger logger = LoggerFactory.getLogger(AlignmentCalc.class); -@@ -85 +85 @@ public class AlignmentCalc implements Runnable { -- aligner.setDebug(true); -+ -@@ -89 +89 @@ public class AlignmentCalc implements Runnable { -- logger.warning(e.getMessage()); -+ logger.warn(e.getMessage()); \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/new/AlignmentCalc.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/new/AlignmentCalc.java deleted file mode 100755 index 55dac67..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/new/AlignmentCalc.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on Jul 16, 2006 - * - */ -package org.biojava.bio.structure.gui.util; - - -import org.biojava.bio.structure.Structure; -import org.biojava.bio.structure.StructureException; -import org.biojava.bio.structure.align.ClusterAltAligs; -import org.biojava.bio.structure.align.StructurePairAligner; -import org.biojava.bio.structure.align.gui.AlignmentGui; -import org.biojava.bio.structure.align.pairwise.AlternativeAlignment; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - - -/** A class that obtains two structures via DAS and aligns them - * This is done in a separate thread. - * It is possible to register Event listeners to get notification of when the download has finished. - * - * @author Andreas Prlic - * @since 1.7 - * @version %I% %G% - */ -public class AlignmentCalc implements Runnable { - - - private static final Logger logger = LoggerFactory.getLogger(AlignmentCalc.class); - - boolean interrupted = false; - - String pdb1; - String pdb2; - String chain1; - String chain2; - - Structure structure1; - Structure structure2; - - AlignmentGui parent; - - - /** requests an alignment of pdb1 vs pdb 2. - * Chain 1 and chain2 are optional. - * If they are empty strings, they are ignored - * @param parent the alignment gui frame that interacts with this class - * @param s1 structure 1 - * @param s2 structure 2 - */ - public AlignmentCalc(AlignmentGui parent, Structure s1, Structure s2 ) { - - this.parent= parent; - - structure1 = s1; - structure2 = s2; - - } - - public void run() { - - // both structure have been downloaded, now calculate the alignment ... - - - StructurePairAligner aligner = new StructurePairAligner(); - - try { - aligner.align(structure1,structure2); - } catch (StructureException e){ - logger.warn(e.getMessage()); - - } - - - - AlternativeAlignment[] aligs = aligner.getAlignments(); - //cluster similar results together - ClusterAltAligs.cluster(aligs); - showAlignment(aligner,aligs); - - //logger.info("done!"); - - parent.notifyCalcFinished(); - - } - - - - private void showAlignment(StructurePairAligner alignment, AlternativeAlignment[] aligs) { - AlternativeAlignmentFrame frame = new AlternativeAlignmentFrame(structure1, structure2); - frame.setStructurePairAligner(alignment); - frame.setAlternativeAlignments(aligs); - frame.pack(); - frame.setVisible(true); - - - - } - - /** stops what is currently happening and does not continue - * - * - */ - public void interrupt() { - interrupted = true; - } - - public void cleanup() { - - parent.notifyCalcFinished(); - - parent=null; - // cleanup... - - structure1 = null; - structure2 = null; - - } - - - -} - - - - diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/old/AlignmentCalc.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/old/AlignmentCalc.java deleted file mode 100755 index 6c81234..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/old/AlignmentCalc.java +++ /dev/null @@ -1,145 +0,0 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on Jul 16, 2006 - * - */ -package org.biojava.bio.structure.gui.util; - - -import java.util.logging.Logger; - -import org.biojava.bio.structure.Structure; -import org.biojava.bio.structure.StructureException; -import org.biojava.bio.structure.align.ClusterAltAligs; -import org.biojava.bio.structure.align.StructurePairAligner; -import org.biojava.bio.structure.align.gui.AlignmentGui; -import org.biojava.bio.structure.align.pairwise.AlternativeAlignment; - - - -/** A class that obtains two structures via DAS and aligns them - * This is done in a separate thread. - * It is possible to register Event listeners to get notification of when the download has finished. - * - * @author Andreas Prlic - * @since 1.7 - * @version %I% %G% - */ -public class AlignmentCalc implements Runnable { - - - public static Logger logger = Logger.getLogger("org.biojava"); - - boolean interrupted = false; - - String pdb1; - String pdb2; - String chain1; - String chain2; - - Structure structure1; - Structure structure2; - - AlignmentGui parent; - - - /** requests an alignment of pdb1 vs pdb 2. - * Chain 1 and chain2 are optional. - * If they are empty strings, they are ignored - * @param parent the alignment gui frame that interacts with this class - * @param s1 structure 1 - * @param s2 structure 2 - */ - public AlignmentCalc(AlignmentGui parent, Structure s1, Structure s2 ) { - - this.parent= parent; - - structure1 = s1; - structure2 = s2; - - } - - public void run() { - - // both structure have been downloaded, now calculate the alignment ... - - - StructurePairAligner aligner = new StructurePairAligner(); - aligner.setDebug(true); - try { - aligner.align(structure1,structure2); - } catch (StructureException e){ - logger.warning(e.getMessage()); - - } - - - - AlternativeAlignment[] aligs = aligner.getAlignments(); - //cluster similar results together - ClusterAltAligs.cluster(aligs); - showAlignment(aligner,aligs); - - //logger.info("done!"); - - parent.notifyCalcFinished(); - - } - - - - private void showAlignment(StructurePairAligner alignment, AlternativeAlignment[] aligs) { - AlternativeAlignmentFrame frame = new AlternativeAlignmentFrame(structure1, structure2); - frame.setStructurePairAligner(alignment); - frame.setAlternativeAlignments(aligs); - frame.pack(); - frame.setVisible(true); - - - - } - - /** stops what is currently happening and does not continue - * - * - */ - public void interrupt() { - interrupted = true; - } - - public void cleanup() { - - parent.notifyCalcFinished(); - - parent=null; - // cleanup... - - structure1 = null; - structure2 = null; - - } - - - -} - - - - diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/pair.info deleted file mode 100755 index 34374e5..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#105/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:105 -comSha:2fbb1721a2c703b17615d3754459382533958236 -parentComSha:ae6868b5bccb59e943f0b16b2d1379d842614134 -BuggyFilePath:biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlignmentCalc.java -FixedFilePath:biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlignmentCalc.java -StartLineNum:48 -EndLineNum:48 -repoName:biojava#biojava \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/comMsg.txt deleted file mode 100755 index b10192f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Converting java.logging to slf4j in structure gui, #155 \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/diff.diff deleted file mode 100755 index c34c643..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlternativeAlignmentFrame.java b/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlternativeAlignmentFrame.java -index 95b29eb42..d2f95d576 100644 ---- a/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlternativeAlignmentFrame.java -+++ b/biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlternativeAlignmentFrame.java -@@ -33 +33 @@ import java.util.List; --import java.util.logging.Logger; -+ -@@ -53,0 +54,2 @@ import org.biojava.bio.structure.gui.SequenceDisplay; -+import org.slf4j.Logger; -+import org.slf4j.LoggerFactory; -@@ -67,2 +69,2 @@ extends JFrame{ -- -- public static Logger logger = Logger.getLogger("org.biojava"); -+ -+ private static final Logger logger = LoggerFactory.getLogger(AlternativeAlignmentFrame.class); -@@ -230,2 +231,0 @@ extends JFrame{ -- n.setNmr(true); -- \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/new/AlternativeAlignmentFrame.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/new/AlternativeAlignmentFrame.java deleted file mode 100755 index d2f95d5..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/new/AlternativeAlignmentFrame.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on Jul 16, 2006 - * - */ -package org.biojava.bio.structure.gui.util; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.text.MessageFormat; -import java.util.List; - -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.table.TableCellRenderer; - -import org.biojava.bio.structure.Atom; -import org.biojava.bio.structure.AtomImpl; -import org.biojava.bio.structure.Calc; -import org.biojava.bio.structure.Chain; -import org.biojava.bio.structure.Structure; -import org.biojava.bio.structure.StructureImpl; -import org.biojava.bio.structure.align.StructurePairAligner; -import org.biojava.bio.structure.align.pairwise.AlternativeAlignment; -import org.biojava.bio.structure.gui.events.JmolAlignedPositionListener; -import org.biojava.bio.structure.jama.Matrix; -import org.biojava.bio.structure.gui.BiojavaJmol; -import org.biojava.bio.structure.gui.ScaleableMatrixPanel; -import org.biojava.bio.structure.gui.SequenceDisplay; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - - -/** a frame showing the alternative alignments, which are the result of a structure superimposition - * - * @author Andreas Prlic - * @since 1.7 - * @version %I% %G% - */ -public class AlternativeAlignmentFrame -extends JFrame{ - - private static final long serialVersionUID=0l; - - - private static final Logger logger = LoggerFactory.getLogger(AlternativeAlignmentFrame.class); - - private static String[] columnNames = new String[]{"#","eqr","score", "rms", "gaps","cluster", "show distance matrix","show alignment"}; - - AlternativeAlignment[] aligs; - JPanel panel; - - Structure structure1; - Structure structure2; - StructurePairAligner structurePairAligner; - - public AlternativeAlignmentFrame(Structure s1, Structure s2) { - super(); - panel = new JPanel(); - panel.setPreferredSize(new Dimension(800,400)); - this.getContentPane().add(panel); - - - structure1 = s1; - structure2 = s2; - String pdb1 = s1.getPDBCode(); - String pdb2 = s2.getPDBCode(); - - String t = "Alternative Alignments"; - Object[] args = {pdb1,pdb2}; - - String title = MessageFormat.format(t,args); - this.setTitle(title); - } - - public void setStructurePairAligner(StructurePairAligner aligner){ - this.structurePairAligner = aligner; - } - - public void setAlternativeAlignments(AlternativeAlignment[] aligs) { - this.aligs = aligs; - panel.removeAll(); - - //Box vBox = Box.createVerticalBox(); - //panel.add(vBox); - - Object[][] data = getDataFromAligs(aligs); - JTableDataButtonModel model = new JTableDataButtonModel(data, columnNames); - JTable table = new JTable(model); - - - TableCellRenderer defaultRenderer = table.getDefaultRenderer(JButton.class); - - JButtonTableCellRenderer myRenderer = new JButtonTableCellRenderer(defaultRenderer); - - table.setDefaultRenderer(JButton.class, myRenderer); - - table.addMouseListener(new JTableMouseButtonListener(table)); - - JScrollPane scrollPane = new JScrollPane(table); - scrollPane.setPreferredSize(new Dimension(800,400)); - //vBox.add(e); - panel.add(scrollPane); - - - } - - private Object[][] getDataFromAligs(AlternativeAlignment[] aligs){ - - - Object[][] data = new Object[aligs.length][columnNames.length]; - - for ( int i=0;i< aligs.length;i++){ - AlternativeAlignment alig = aligs[i]; - - data[i][0] = new Integer(i+1); - data[i][1] = new Integer(alig.getEqr()); - data[i][2] = new Double(alig.getScore()); - data[i][3] = new Double(alig.getRmsd()); - data[i][4] = new Integer(alig.getGaps()); - data[i][5] = new Integer(alig.getCluster()); - JButton maxb = new JButton("Distance Matrix"); - maxb.addMouseListener(new MatrixMouseListener(this,i)); - - data[i][6] = maxb; - - - //Action action1 = new MyButtonAction(t,this,i); - JButton but = new JButton("Show in Jmol"); - but.addMouseListener(new MyButtonMouseListener(this,i)); - data[i][7] = but; - - - } - return data; - } - - public void showDistanceMatrix(int position){ - if ( position > aligs.length){ - return; - } - AlternativeAlignment alig = aligs[position]; - logger.info("display distance matrix for alternative alignment " + (position +1)); - - ScaleableMatrixPanel smp = new ScaleableMatrixPanel(); - JFrame frame = new JFrame(); - frame.setTitle("Alt. Alig [" + position+"] - Distance Matrix & path"); - - frame.addWindowListener(new WindowAdapter(){ - public void windowClosing(WindowEvent e){ - JFrame f = (JFrame) e.getSource(); - f.setVisible(false); - f.dispose(); - } - - - - }); - - smp.setMatrix(alig.getDistanceMatrix()); - smp.setAlternativeAligs(new AlternativeAlignment[]{alig}); - - frame.getContentPane().add(smp); - - frame.pack(); - frame.setVisible(true); - - } - - public void showAlternative(int position){ - if ( position > aligs.length){ - return; - } - AlternativeAlignment alig = aligs[position]; - logger.info("display alternative alignment " + (position +1)); - - // create the structure alignment object and tell the listeners ... - - -// Matrix m1 = Matrix.identity(3,3); - Matrix m2 = alig.getRotationMatrix(); - - String pdb1 = structure1.getPDBCode(); - String pdb2 = structure2.getPDBCode(); - - - Atom shift1 = new AtomImpl(); - shift1.setCoords(new double[]{0,0,1}); - Atom shift2 = alig.getShift(); - - Structure s3 = (Structure)structure2.clone(); - - Calc.rotate(s3,m2); - Calc.shift(s3,shift2); - - BiojavaJmol jmol = new BiojavaJmol(); - jmol.setTitle(pdb1 + " vs. " + pdb2); - - Structure n = new StructureImpl(); - - List chains1 = structure1.getChains(); - - n.addModel(chains1); - - List chains3 = s3.getChains(); - n.addModel(chains3); - - jmol.setStructure(n); - String[] cmds = createRasmolScripts(alig); - jmol.evalString("model 0 ; select * ; wireframe off ; spacefill off; backbone 0.3;"); - jmol.evalString(cmds[0]); - jmol.evalString(cmds[1]); - - JFrame frame = new JFrame("Sequences for AlternativeAlignment ["+position+"]"); - - SequenceDisplay seqdisp; - seqdisp = new SequenceDisplay(structurePairAligner); - seqdisp.setStructure1(structure1); - seqdisp.setStructure2(structure2); - - seqdisp.setAlternativeAlignment(alig); - - frame.getContentPane().add(seqdisp); - - frame.pack(); - frame.setVisible(true); - frame.addWindowListener(new WindowAdapter(){ - public void windowClosing(WindowEvent e){ - JFrame f = (JFrame) e.getSource(); - f.setVisible(false); - f.dispose(); - } - - - - }); - - seqdisp.updateDisplay(); - - JmolAlignedPositionListener jmolBridge = new JmolAlignedPositionListener(jmol,structurePairAligner); - jmolBridge.setStructure1(structure1); - jmolBridge.setStructure2(s3); - - seqdisp.addAlignmentPositionListener(jmolBridge); - - } - - - - private String[] createRasmolScripts(AlternativeAlignment alig){ - String[] scripts = new String[2]; - - Color col1 = Color.red; - Color col2 = Color.blue; - - Color chaincol1 = new Color(col1.getRed()/2,col1.getGreen()/2,col1.getBlue()/2); - Color chaincol2 = new Color(col2.getRed()/2,col2.getGreen()/2,col2.getBlue()/2); - - - - String cmd1 = ""; - String cmd2 = ""; - - cmd1 += "select */"+1+"; "; - cmd1 += " color [" +chaincol1.getRed()+","+chaincol1.getGreen() +","+chaincol1.getBlue() +"];"; - - cmd2 += "select */"+2+"; "; - cmd2 += " color [" +chaincol2.getRed()+","+chaincol2.getGreen() +","+chaincol2.getBlue() +"];"; - - cmd1 += "select "; - cmd2 += "select "; - - String[] pdb1s = alig.getPDBresnum1(); - String[] pdb2s = alig.getPDBresnum2(); - - - for ( int i =0 ; i< pdb1s.length;i++){ - - String p1 = pdb1s[i]; - String p2 = pdb2s[i]; - - cmd1 += p1 +"/1"; - cmd2 += p2 +"/2"; - - if ( i <= pdb1s.length -2){ - cmd1 += ","; - cmd2 += ","; - } - } - - cmd1 += "; color [" +col1.getRed()+","+col1.getGreen() +","+col1.getBlue() +"];"; - cmd1 += " backbone 0.6;"; - - cmd2 += "; color [" +col2.getRed()+","+col2.getGreen() +","+col2.getBlue() +"];"; - cmd2 += " backbone 0.6;"; - - //System.out.println(cmd1); - scripts[0] = cmd1; - scripts[1] = cmd2; - - return scripts; - } - - - - -} - -class MyButtonMouseListener implements MouseListener{ - AlternativeAlignmentFrame parent; - int pos; - public MyButtonMouseListener(AlternativeAlignmentFrame parent, int position){ - - this.parent = parent; - this.pos = position; - } - - - - public void mouseClicked(MouseEvent arg0) { - - - } - - public void mousePressed(MouseEvent arg0) { - - } - - public void mouseReleased(MouseEvent arg0) { - parent.showAlternative(pos); - - } - - public void mouseEntered(MouseEvent arg0) { - - } - - public void mouseExited(MouseEvent arg0) { - - } - -} - -class MatrixMouseListener implements MouseListener{ - AlternativeAlignmentFrame parent; - int pos; - public MatrixMouseListener( AlternativeAlignmentFrame parent, int position){ - - this.parent = parent; - this.pos = position; - } - - public void mouseClicked(MouseEvent arg0) {} - public void mousePressed(MouseEvent arg0) {} - - public void mouseReleased(MouseEvent arg0) { - parent.showDistanceMatrix(pos); - - } - - - public void mouseEntered(MouseEvent arg0) { } - - public void mouseExited(MouseEvent arg0) {} - -} - diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/old/AlternativeAlignmentFrame.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/old/AlternativeAlignmentFrame.java deleted file mode 100755 index 95b29eb..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/old/AlternativeAlignmentFrame.java +++ /dev/null @@ -1,391 +0,0 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on Jul 16, 2006 - * - */ -package org.biojava.bio.structure.gui.util; - -import java.awt.Color; -import java.awt.Dimension; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.text.MessageFormat; -import java.util.List; -import java.util.logging.Logger; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.table.TableCellRenderer; - -import org.biojava.bio.structure.Atom; -import org.biojava.bio.structure.AtomImpl; -import org.biojava.bio.structure.Calc; -import org.biojava.bio.structure.Chain; -import org.biojava.bio.structure.Structure; -import org.biojava.bio.structure.StructureImpl; -import org.biojava.bio.structure.align.StructurePairAligner; -import org.biojava.bio.structure.align.pairwise.AlternativeAlignment; -import org.biojava.bio.structure.gui.events.JmolAlignedPositionListener; -import org.biojava.bio.structure.jama.Matrix; -import org.biojava.bio.structure.gui.BiojavaJmol; -import org.biojava.bio.structure.gui.ScaleableMatrixPanel; -import org.biojava.bio.structure.gui.SequenceDisplay; - - -/** a frame showing the alternative alignments, which are the result of a structure superimposition - * - * @author Andreas Prlic - * @since 1.7 - * @version %I% %G% - */ -public class AlternativeAlignmentFrame -extends JFrame{ - - private static final long serialVersionUID=0l; - - - public static Logger logger = Logger.getLogger("org.biojava"); - - private static String[] columnNames = new String[]{"#","eqr","score", "rms", "gaps","cluster", "show distance matrix","show alignment"}; - - AlternativeAlignment[] aligs; - JPanel panel; - - Structure structure1; - Structure structure2; - StructurePairAligner structurePairAligner; - - public AlternativeAlignmentFrame(Structure s1, Structure s2) { - super(); - panel = new JPanel(); - panel.setPreferredSize(new Dimension(800,400)); - this.getContentPane().add(panel); - - - structure1 = s1; - structure2 = s2; - String pdb1 = s1.getPDBCode(); - String pdb2 = s2.getPDBCode(); - - String t = "Alternative Alignments"; - Object[] args = {pdb1,pdb2}; - - String title = MessageFormat.format(t,args); - this.setTitle(title); - } - - public void setStructurePairAligner(StructurePairAligner aligner){ - this.structurePairAligner = aligner; - } - - public void setAlternativeAlignments(AlternativeAlignment[] aligs) { - this.aligs = aligs; - panel.removeAll(); - - //Box vBox = Box.createVerticalBox(); - //panel.add(vBox); - - Object[][] data = getDataFromAligs(aligs); - JTableDataButtonModel model = new JTableDataButtonModel(data, columnNames); - JTable table = new JTable(model); - - - TableCellRenderer defaultRenderer = table.getDefaultRenderer(JButton.class); - - JButtonTableCellRenderer myRenderer = new JButtonTableCellRenderer(defaultRenderer); - - table.setDefaultRenderer(JButton.class, myRenderer); - - table.addMouseListener(new JTableMouseButtonListener(table)); - - JScrollPane scrollPane = new JScrollPane(table); - scrollPane.setPreferredSize(new Dimension(800,400)); - //vBox.add(e); - panel.add(scrollPane); - - - } - - private Object[][] getDataFromAligs(AlternativeAlignment[] aligs){ - - - Object[][] data = new Object[aligs.length][columnNames.length]; - - for ( int i=0;i< aligs.length;i++){ - AlternativeAlignment alig = aligs[i]; - - data[i][0] = new Integer(i+1); - data[i][1] = new Integer(alig.getEqr()); - data[i][2] = new Double(alig.getScore()); - data[i][3] = new Double(alig.getRmsd()); - data[i][4] = new Integer(alig.getGaps()); - data[i][5] = new Integer(alig.getCluster()); - JButton maxb = new JButton("Distance Matrix"); - maxb.addMouseListener(new MatrixMouseListener(this,i)); - - data[i][6] = maxb; - - - //Action action1 = new MyButtonAction(t,this,i); - JButton but = new JButton("Show in Jmol"); - but.addMouseListener(new MyButtonMouseListener(this,i)); - data[i][7] = but; - - - } - return data; - } - - public void showDistanceMatrix(int position){ - if ( position > aligs.length){ - return; - } - AlternativeAlignment alig = aligs[position]; - logger.info("display distance matrix for alternative alignment " + (position +1)); - - ScaleableMatrixPanel smp = new ScaleableMatrixPanel(); - JFrame frame = new JFrame(); - frame.setTitle("Alt. Alig [" + position+"] - Distance Matrix & path"); - - frame.addWindowListener(new WindowAdapter(){ - public void windowClosing(WindowEvent e){ - JFrame f = (JFrame) e.getSource(); - f.setVisible(false); - f.dispose(); - } - - - - }); - - smp.setMatrix(alig.getDistanceMatrix()); - smp.setAlternativeAligs(new AlternativeAlignment[]{alig}); - - frame.getContentPane().add(smp); - - frame.pack(); - frame.setVisible(true); - - } - - public void showAlternative(int position){ - if ( position > aligs.length){ - return; - } - AlternativeAlignment alig = aligs[position]; - logger.info("display alternative alignment " + (position +1)); - - // create the structure alignment object and tell the listeners ... - - -// Matrix m1 = Matrix.identity(3,3); - Matrix m2 = alig.getRotationMatrix(); - - String pdb1 = structure1.getPDBCode(); - String pdb2 = structure2.getPDBCode(); - - - Atom shift1 = new AtomImpl(); - shift1.setCoords(new double[]{0,0,1}); - Atom shift2 = alig.getShift(); - - Structure s3 = (Structure)structure2.clone(); - - Calc.rotate(s3,m2); - Calc.shift(s3,shift2); - - BiojavaJmol jmol = new BiojavaJmol(); - jmol.setTitle(pdb1 + " vs. " + pdb2); - - Structure n = new StructureImpl(); - - List chains1 = structure1.getChains(); - - n.addModel(chains1); - - List chains3 = s3.getChains(); - n.addModel(chains3); - - n.setNmr(true); - - jmol.setStructure(n); - String[] cmds = createRasmolScripts(alig); - jmol.evalString("model 0 ; select * ; wireframe off ; spacefill off; backbone 0.3;"); - jmol.evalString(cmds[0]); - jmol.evalString(cmds[1]); - - JFrame frame = new JFrame("Sequences for AlternativeAlignment ["+position+"]"); - - SequenceDisplay seqdisp; - seqdisp = new SequenceDisplay(structurePairAligner); - seqdisp.setStructure1(structure1); - seqdisp.setStructure2(structure2); - - seqdisp.setAlternativeAlignment(alig); - - frame.getContentPane().add(seqdisp); - - frame.pack(); - frame.setVisible(true); - frame.addWindowListener(new WindowAdapter(){ - public void windowClosing(WindowEvent e){ - JFrame f = (JFrame) e.getSource(); - f.setVisible(false); - f.dispose(); - } - - - - }); - - seqdisp.updateDisplay(); - - JmolAlignedPositionListener jmolBridge = new JmolAlignedPositionListener(jmol,structurePairAligner); - jmolBridge.setStructure1(structure1); - jmolBridge.setStructure2(s3); - - seqdisp.addAlignmentPositionListener(jmolBridge); - - } - - - - private String[] createRasmolScripts(AlternativeAlignment alig){ - String[] scripts = new String[2]; - - Color col1 = Color.red; - Color col2 = Color.blue; - - Color chaincol1 = new Color(col1.getRed()/2,col1.getGreen()/2,col1.getBlue()/2); - Color chaincol2 = new Color(col2.getRed()/2,col2.getGreen()/2,col2.getBlue()/2); - - - - String cmd1 = ""; - String cmd2 = ""; - - cmd1 += "select */"+1+"; "; - cmd1 += " color [" +chaincol1.getRed()+","+chaincol1.getGreen() +","+chaincol1.getBlue() +"];"; - - cmd2 += "select */"+2+"; "; - cmd2 += " color [" +chaincol2.getRed()+","+chaincol2.getGreen() +","+chaincol2.getBlue() +"];"; - - cmd1 += "select "; - cmd2 += "select "; - - String[] pdb1s = alig.getPDBresnum1(); - String[] pdb2s = alig.getPDBresnum2(); - - - for ( int i =0 ; i< pdb1s.length;i++){ - - String p1 = pdb1s[i]; - String p2 = pdb2s[i]; - - cmd1 += p1 +"/1"; - cmd2 += p2 +"/2"; - - if ( i <= pdb1s.length -2){ - cmd1 += ","; - cmd2 += ","; - } - } - - cmd1 += "; color [" +col1.getRed()+","+col1.getGreen() +","+col1.getBlue() +"];"; - cmd1 += " backbone 0.6;"; - - cmd2 += "; color [" +col2.getRed()+","+col2.getGreen() +","+col2.getBlue() +"];"; - cmd2 += " backbone 0.6;"; - - //System.out.println(cmd1); - scripts[0] = cmd1; - scripts[1] = cmd2; - - return scripts; - } - - - - -} - -class MyButtonMouseListener implements MouseListener{ - AlternativeAlignmentFrame parent; - int pos; - public MyButtonMouseListener(AlternativeAlignmentFrame parent, int position){ - - this.parent = parent; - this.pos = position; - } - - - - public void mouseClicked(MouseEvent arg0) { - - - } - - public void mousePressed(MouseEvent arg0) { - - } - - public void mouseReleased(MouseEvent arg0) { - parent.showAlternative(pos); - - } - - public void mouseEntered(MouseEvent arg0) { - - } - - public void mouseExited(MouseEvent arg0) { - - } - -} - -class MatrixMouseListener implements MouseListener{ - AlternativeAlignmentFrame parent; - int pos; - public MatrixMouseListener( AlternativeAlignmentFrame parent, int position){ - - this.parent = parent; - this.pos = position; - } - - public void mouseClicked(MouseEvent arg0) {} - public void mousePressed(MouseEvent arg0) {} - - public void mouseReleased(MouseEvent arg0) { - parent.showDistanceMatrix(pos); - - } - - - public void mouseEntered(MouseEvent arg0) { } - - public void mouseExited(MouseEvent arg0) {} - -} - diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/pair.info deleted file mode 100755 index 88755bc..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#154/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:154 -comSha:2fbb1721a2c703b17615d3754459382533958236 -parentComSha:ae6868b5bccb59e943f0b16b2d1379d842614134 -BuggyFilePath:biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlternativeAlignmentFrame.java -FixedFilePath:biojava3-structure-gui/src/main/java/org/biojava/bio/structure/gui/util/AlternativeAlignmentFrame.java -StartLineNum:68 -EndLineNum:68 -repoName:biojava#biojava \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/comMsg.txt deleted file mode 100755 index 3e5386f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed improper names and changed API to more current naming schemes. Bumped version for API change. \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/diff.diff deleted file mode 100755 index 28ef13c..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/californium/src/main/java/ch/ethz/inf/vs/californium/coap/CoAP.java b/californium/src/main/java/ch/ethz/inf/vs/californium/coap/CoAP.java -index e6e03854..e17a63e8 100644 ---- a/californium/src/main/java/ch/ethz/inf/vs/californium/coap/CoAP.java -+++ b/californium/src/main/java/ch/ethz/inf/vs/californium/coap/CoAP.java -@@ -16,2 +16,4 @@ public class CoAP { -- public static String COAP_URI_SCHEME = "coap"; -- public static String COAP_SECURE_URI_SCHEME = "coaps"; -+ public static final int VERSION = 0x01; -+ -+ public static final String COAP_URI_SCHEME = "coap"; -+ public static final String COAP_SECURE_URI_SCHEME = "coaps"; \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/new/CoAP.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/new/CoAP.java deleted file mode 100755 index e17a63e..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/new/CoAP.java +++ /dev/null @@ -1,312 +0,0 @@ -package ch.ethz.inf.vs.californium.coap; - -/** - * CoAP defines several constants. - *

    - *
  • Message types: CON, NON, ACK, RST
  • - *
  • Request codes: GET, POST, PUT, DELETE
  • - *
  • Response codes
  • - *
  • Option numbers
  • - *
  • Message format
  • - *
- * @see MediaTypeRegistry - */ -public class CoAP { - - public static final int VERSION = 0x01; - - public static final String COAP_URI_SCHEME = "coap"; - public static final String COAP_SECURE_URI_SCHEME = "coaps"; - - private CoAP() { - // prevent initialization - } - - /** - * CoAP defines four types of messages: Confirmable, Non-confirmable, - * Acknowledgment, Reset;. - */ - public enum Type { - - /** The Confirmable. */ - CON(0), - - /** The Non-confirmable. */ - NON(1), - - /** The Acknowledgment */ - ACK(2), - - /** The Reject. */ - RST(3); - - /** The integer value of a message type. */ - public final int value; - - /** - * Instantiates a new type with the specified integer value. - * - * @param value the integer value - */ - Type(int value) { - this.value = value; - } - - /** - * Converts an integer into its corresponding message type. - * - * @param value the integer value - * @return the message type - * @throws IllegalArgumentException if the integer value is unrecognized - */ - public static Type valueOf(int value) { - switch (value) { - case 0: return CON; - case 1: return NON; - case 2: return ACK; - case 3: return RST; - default: throw new IllegalArgumentException("Unknown CoAP type "+value); - } - } - } - - /** - * The enumeration of request codes: GET, POST; PUT and DELETE. - */ - public enum Code { - - /** The GET code. */ - GET(1), - - /** The POST code. */ - POST(2), - - /** The PUT code. */ - PUT(3), - - /** The DELETE code. */ - DELETE(4); - - /** The code value. */ - public final int value; - - /** - * Instantiates a new code with the specified code value. - * - * @param value the integer value of the code - */ - Code(int value) { - this.value = value; - } - - /** - * Converts the specified integer value to a request code. - * - * @param value the integer value - * @return the request code - * @throws IllegalArgumentException if the integer value is unrecognized - */ - public static Code valueOf(int value) { - switch (value) { - case 1: return GET; - case 2: return POST; - case 3: return PUT; - case 4: return DELETE; - default: throw new IllegalArgumentException("Unknwon CoAP request code "+value); - } - } - } - - /** - * The enumeration of response codes - */ - public enum ResponseCode { - - // Success - CREATED(65), - DELETED(66), - VALID(67), - CHANGED(68), - CONTENT(69), - CONTINUE(95), - - // Client error - BAD_REQUEST(128), - UNAUTHORIZED(129), - BAD_OPTION(130), - FORBIDDEN(131), - NOT_FOUND(132), - METHOD_NOT_ALLOWED(133), - NOT_ACCEPTABLE(134), - REQUEST_ENTITY_INCOMPLETE(136), - PRECONDITION_FAILED(140), - REQUEST_ENTITY_TOO_LARGE(141), - UNSUPPORTED_CONTENT_FORMAT(143), - - // Server error - INTERNAL_SERVER_ERROR(160), - NOT_IMPLEMENTED(161), - BAD_GATEWAY(162), - SERVICE_UNAVAILABLE(163), - GATEWAY_TIMEOUT(164), - PROXY_NOT_SUPPORTED(165); - - /** The code value. */ - public final int value; - - /** - * Instantiates a new response code with the specified integer value. - * - * @param value the integer value - */ - private ResponseCode(int value) { - this.value = value; - } - - /** - * Converts the specified integer value to a response code. - * - * @param value the value - * @return the response code - * @throws IllegalArgumentException if integer value is not recognized - */ - public static ResponseCode valueOf(int value) { - switch (value) { - case 65: return CREATED; - case 66: return DELETED; - case 67: return VALID; - case 68: return CHANGED; - case 69: return CONTENT; - case 128: return BAD_REQUEST; - case 129: return UNAUTHORIZED; - case 130: return BAD_OPTION; - case 131: return FORBIDDEN; - case 132: return NOT_FOUND; - case 133: return METHOD_NOT_ALLOWED; - case 134: return NOT_ACCEPTABLE; - case 136: return REQUEST_ENTITY_INCOMPLETE; - case 140: return PRECONDITION_FAILED; - case 141: return REQUEST_ENTITY_TOO_LARGE; - case 143: return UNSUPPORTED_CONTENT_FORMAT; - case 160: return INTERNAL_SERVER_ERROR; - case 161: return NOT_IMPLEMENTED; - case 162: return BAD_GATEWAY; - case 163: return SERVICE_UNAVAILABLE; - case 164: return GATEWAY_TIMEOUT; - case 165: return PROXY_NOT_SUPPORTED; - default: // Make an extensive search - for (ResponseCode code:ResponseCode.values()) - if (code.value == value) return code; - throw new IllegalArgumentException("Unknown CoAP response code "+value); - } - } - - public String toString() { - return String.format("%d.%02d", this.value/32, this.value%32); - } - - public static boolean isSuccess(ResponseCode code) { - return 65 <= code.value && code.value <= 127; - } - - public static boolean isClientError(ResponseCode code) { - return BAD_REQUEST.value <= code.value && code.value < INTERNAL_SERVER_ERROR.value; - } - - public static boolean isServerError(ResponseCode code) { - return INTERNAL_SERVER_ERROR.value <= code.value; - } - } - - /** - * CoAP Option Number Registry. - */ - public static class OptionRegistry { - - // draft-ietf-core-coap-14 - public static final int RESERVED_0 = 0; - public static final int IF_MATCH = 1; - public static final int URI_HOST = 3; - public static final int ETAG = 4; - public static final int IF_NONE_MATCH = 5; - public static final int URI_PORT = 7; - public static final int LOCATION_PATH = 8; - public static final int URI_PATH = 11; - public static final int CONTENT_FORMAT = 12; - public static final int MAX_AGE = 14; - public static final int URI_QUERY = 15; - public static final int ACCEPT = 17; - public static final int LOCATION_QUERY = 20; - public static final int PROXY_URI = 35; - public static final int PROXY_SCHEME = 39; - public static final int RESERVED_1 = 128; - public static final int RESERVED_2 = 132; - public static final int RESERVED_3 = 136; - public static final int RESERVED_4 = 140; - - // draft-ietf-core-observe-08 - public static final int OBSERVE = 6; - - // draft-ietf-core-block-10 - public static final int BLOCK2 = 23; - public static final int BLOCK1 = 27; - public static final int SIZE = 28; - - /** - * Option Number Registry default values. - */ - public static class Default { - - /** The default MAX_AGE. */ - public static final long MAX_AGE = 60L; - } - } - - /** - * CoAP message format. - */ - public class MessageFormat { - - /** number of bits used for the encoding of the CoAP version field. */ - public static final int VERSION_BITS = 2; - - /** number of bits used for the encoding of the message type field. */ - public static final int TYPE_BITS = 2; - - /** number of bits used for the encoding of the token length field. */ - public static final int TOKEN_LENGTH_BITS = 4; - - /** number of bits used for the encoding of the request method/response code field. */ - public static final int CODE_BITS = 8; - - /** number of bits used for the encoding of the message ID. */ - public static final int MESSAGE_ID_BITS = 16; - - /** number of bits used for the encoding of the option delta field. */ - public static final int OPTION_DELTA_BITS = 4; - - /** number of bits used for the encoding of the option delta field. */ - public static final int OPTION_LENGTH_BITS = 4; - - /** One byte which indicates indicates the end of options and the start of the payload. */ - public static final byte PAYLOAD_MARKER = (byte) 0xFF; - - /** CoAP version supported by this Californium version. */ - public static final int VERSION = 1; - - /** The code value of an empty message. */ - public static final int EMPTY_CODE = 0; - - /** The lowest value of a request code. */ - public static final int REQUEST_CODE_LOWER_BOUND = 1; - - /** The highest value of a request code. */ - public static final int REQUEST_CODE_UPPER_BOUNT = 31; - - /** The lowest value of a response code. */ - public static final int RESPONSE_CODE_LOWER_BOUND = 64; - - /** The highest value of a response code. */ - public static final int RESPONSE_CODE_UPPER_BOUND = 191; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/old/CoAP.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/old/CoAP.java deleted file mode 100755 index e6e0385..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/old/CoAP.java +++ /dev/null @@ -1,310 +0,0 @@ -package ch.ethz.inf.vs.californium.coap; - -/** - * CoAP defines several constants. - *
    - *
  • Message types: CON, NON, ACK, RST
  • - *
  • Request codes: GET, POST, PUT, DELETE
  • - *
  • Response codes
  • - *
  • Option numbers
  • - *
  • Message format
  • - *
- * @see MediaTypeRegistry - */ -public class CoAP { - - public static String COAP_URI_SCHEME = "coap"; - public static String COAP_SECURE_URI_SCHEME = "coaps"; - - private CoAP() { - // prevent initialization - } - - /** - * CoAP defines four types of messages: Confirmable, Non-confirmable, - * Acknowledgment, Reset;. - */ - public enum Type { - - /** The Confirmable. */ - CON(0), - - /** The Non-confirmable. */ - NON(1), - - /** The Acknowledgment */ - ACK(2), - - /** The Reject. */ - RST(3); - - /** The integer value of a message type. */ - public final int value; - - /** - * Instantiates a new type with the specified integer value. - * - * @param value the integer value - */ - Type(int value) { - this.value = value; - } - - /** - * Converts an integer into its corresponding message type. - * - * @param value the integer value - * @return the message type - * @throws IllegalArgumentException if the integer value is unrecognized - */ - public static Type valueOf(int value) { - switch (value) { - case 0: return CON; - case 1: return NON; - case 2: return ACK; - case 3: return RST; - default: throw new IllegalArgumentException("Unknown CoAP type "+value); - } - } - } - - /** - * The enumeration of request codes: GET, POST; PUT and DELETE. - */ - public enum Code { - - /** The GET code. */ - GET(1), - - /** The POST code. */ - POST(2), - - /** The PUT code. */ - PUT(3), - - /** The DELETE code. */ - DELETE(4); - - /** The code value. */ - public final int value; - - /** - * Instantiates a new code with the specified code value. - * - * @param value the integer value of the code - */ - Code(int value) { - this.value = value; - } - - /** - * Converts the specified integer value to a request code. - * - * @param value the integer value - * @return the request code - * @throws IllegalArgumentException if the integer value is unrecognized - */ - public static Code valueOf(int value) { - switch (value) { - case 1: return GET; - case 2: return POST; - case 3: return PUT; - case 4: return DELETE; - default: throw new IllegalArgumentException("Unknwon CoAP request code "+value); - } - } - } - - /** - * The enumeration of response codes - */ - public enum ResponseCode { - - // Success - CREATED(65), - DELETED(66), - VALID(67), - CHANGED(68), - CONTENT(69), - CONTINUE(95), - - // Client error - BAD_REQUEST(128), - UNAUTHORIZED(129), - BAD_OPTION(130), - FORBIDDEN(131), - NOT_FOUND(132), - METHOD_NOT_ALLOWED(133), - NOT_ACCEPTABLE(134), - REQUEST_ENTITY_INCOMPLETE(136), - PRECONDITION_FAILED(140), - REQUEST_ENTITY_TOO_LARGE(141), - UNSUPPORTED_CONTENT_FORMAT(143), - - // Server error - INTERNAL_SERVER_ERROR(160), - NOT_IMPLEMENTED(161), - BAD_GATEWAY(162), - SERVICE_UNAVAILABLE(163), - GATEWAY_TIMEOUT(164), - PROXY_NOT_SUPPORTED(165); - - /** The code value. */ - public final int value; - - /** - * Instantiates a new response code with the specified integer value. - * - * @param value the integer value - */ - private ResponseCode(int value) { - this.value = value; - } - - /** - * Converts the specified integer value to a response code. - * - * @param value the value - * @return the response code - * @throws IllegalArgumentException if integer value is not recognized - */ - public static ResponseCode valueOf(int value) { - switch (value) { - case 65: return CREATED; - case 66: return DELETED; - case 67: return VALID; - case 68: return CHANGED; - case 69: return CONTENT; - case 128: return BAD_REQUEST; - case 129: return UNAUTHORIZED; - case 130: return BAD_OPTION; - case 131: return FORBIDDEN; - case 132: return NOT_FOUND; - case 133: return METHOD_NOT_ALLOWED; - case 134: return NOT_ACCEPTABLE; - case 136: return REQUEST_ENTITY_INCOMPLETE; - case 140: return PRECONDITION_FAILED; - case 141: return REQUEST_ENTITY_TOO_LARGE; - case 143: return UNSUPPORTED_CONTENT_FORMAT; - case 160: return INTERNAL_SERVER_ERROR; - case 161: return NOT_IMPLEMENTED; - case 162: return BAD_GATEWAY; - case 163: return SERVICE_UNAVAILABLE; - case 164: return GATEWAY_TIMEOUT; - case 165: return PROXY_NOT_SUPPORTED; - default: // Make an extensive search - for (ResponseCode code:ResponseCode.values()) - if (code.value == value) return code; - throw new IllegalArgumentException("Unknown CoAP response code "+value); - } - } - - public String toString() { - return String.format("%d.%02d", this.value/32, this.value%32); - } - - public static boolean isSuccess(ResponseCode code) { - return 65 <= code.value && code.value <= 127; - } - - public static boolean isClientError(ResponseCode code) { - return BAD_REQUEST.value <= code.value && code.value < INTERNAL_SERVER_ERROR.value; - } - - public static boolean isServerError(ResponseCode code) { - return INTERNAL_SERVER_ERROR.value <= code.value; - } - } - - /** - * CoAP Option Number Registry. - */ - public static class OptionRegistry { - - // draft-ietf-core-coap-14 - public static final int RESERVED_0 = 0; - public static final int IF_MATCH = 1; - public static final int URI_HOST = 3; - public static final int ETAG = 4; - public static final int IF_NONE_MATCH = 5; - public static final int URI_PORT = 7; - public static final int LOCATION_PATH = 8; - public static final int URI_PATH = 11; - public static final int CONTENT_FORMAT = 12; - public static final int MAX_AGE = 14; - public static final int URI_QUERY = 15; - public static final int ACCEPT = 17; - public static final int LOCATION_QUERY = 20; - public static final int PROXY_URI = 35; - public static final int PROXY_SCHEME = 39; - public static final int RESERVED_1 = 128; - public static final int RESERVED_2 = 132; - public static final int RESERVED_3 = 136; - public static final int RESERVED_4 = 140; - - // draft-ietf-core-observe-08 - public static final int OBSERVE = 6; - - // draft-ietf-core-block-10 - public static final int BLOCK2 = 23; - public static final int BLOCK1 = 27; - public static final int SIZE = 28; - - /** - * Option Number Registry default values. - */ - public static class Default { - - /** The default MAX_AGE. */ - public static final long MAX_AGE = 60L; - } - } - - /** - * CoAP message format. - */ - public class MessageFormat { - - /** number of bits used for the encoding of the CoAP version field. */ - public static final int VERSION_BITS = 2; - - /** number of bits used for the encoding of the message type field. */ - public static final int TYPE_BITS = 2; - - /** number of bits used for the encoding of the token length field. */ - public static final int TOKEN_LENGTH_BITS = 4; - - /** number of bits used for the encoding of the request method/response code field. */ - public static final int CODE_BITS = 8; - - /** number of bits used for the encoding of the message ID. */ - public static final int MESSAGE_ID_BITS = 16; - - /** number of bits used for the encoding of the option delta field. */ - public static final int OPTION_DELTA_BITS = 4; - - /** number of bits used for the encoding of the option delta field. */ - public static final int OPTION_LENGTH_BITS = 4; - - /** One byte which indicates indicates the end of options and the start of the payload. */ - public static final byte PAYLOAD_MARKER = (byte) 0xFF; - - /** CoAP version supported by this Californium version. */ - public static final int VERSION = 1; - - /** The code value of an empty message. */ - public static final int EMPTY_CODE = 0; - - /** The lowest value of a request code. */ - public static final int REQUEST_CODE_LOWER_BOUND = 1; - - /** The highest value of a request code. */ - public static final int REQUEST_CODE_UPPER_BOUNT = 31; - - /** The lowest value of a response code. */ - public static final int RESPONSE_CODE_LOWER_BOUND = 64; - - /** The highest value of a response code. */ - public static final int RESPONSE_CODE_UPPER_BOUND = 191; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/pair.info deleted file mode 100755 index 40dca92..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#24564/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:24564 -comSha:84768e062302f47b6ca1df4eeec75050a58f3f63 -parentComSha:6d199bf0fc18b43607523213ba534dbd61ddbbab -BuggyFilePath:californium/src/main/java/ch/ethz/inf/vs/californium/coap/CoAP.java -FixedFilePath:californium/src/main/java/ch/ethz/inf/vs/californium/coap/CoAP.java -StartLineNum:16 -EndLineNum:16 -repoName:mkovatsc#Californium \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/comMsg.txt deleted file mode 100755 index 10475d1..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -merging with version 3.2.1 \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/diff.diff deleted file mode 100755 index 59ccf0f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/choco-solver/src/main/java/solver/constraints/nary/automata/FA/FiniteAutomaton.java b/choco-solver/src/main/java/solver/constraints/nary/automata/FA/FiniteAutomaton.java -index b54a8fcd7..b6abf9f3f 100644 ---- a/choco-solver/src/main/java/solver/constraints/nary/automata/FA/FiniteAutomaton.java -+++ b/choco-solver/src/main/java/solver/constraints/nary/automata/FA/FiniteAutomaton.java -@@ -2 +2 @@ -- * Copyright (c) 1999-2010, Ecole des Mines de Nantes -+ * Copyright (c) 1999-2014, Ecole des Mines de Nantes -@@ -54,2 +54,2 @@ public class FiniteAutomaton implements IAutomaton { -- protected static TIntIntHashMap charFromIntMap = new TIntIntHashMap(); -- protected static TIntIntHashMap intFromCharMap = new TIntIntHashMap(); -+ protected final static TIntIntHashMap charFromIntMap = new TIntIntHashMap(); -+ protected final static TIntIntHashMap intFromCharMap = new TIntIntHashMap(); -@@ -425 +425 @@ public class FiniteAutomaton implements IAutomaton { -- StringBuffer b = new StringBuffer(); -+ StringBuilder b = new StringBuilder(); \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/new/FiniteAutomaton.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/new/FiniteAutomaton.java deleted file mode 100755 index b6abf9f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/new/FiniteAutomaton.java +++ /dev/null @@ -1,708 +0,0 @@ -/** - * Copyright (c) 1999-2014, Ecole des Mines de Nantes - * All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Ecole des Mines de Nantes nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package solver.constraints.nary.automata.FA; - -import dk.brics.automaton.*; -import gnu.trove.iterator.TIntIterator; -import gnu.trove.list.array.TIntArrayList; -import gnu.trove.map.hash.TIntIntHashMap; -import gnu.trove.map.hash.TObjectIntHashMap; -import gnu.trove.set.hash.TIntHashSet; -import org.slf4j.LoggerFactory; -import util.tools.StringUtils; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.*; - -/** - * Created by IntelliJ IDEA. - * User: julien - * Date: Mar 15, 2010 - * Time: 12:53:23 PM - */ -public class FiniteAutomaton implements IAutomaton { - - - protected final static TIntIntHashMap charFromIntMap = new TIntIntHashMap(); - protected final static TIntIntHashMap intFromCharMap = new TIntIntHashMap(); - - public static org.slf4j.Logger LOGGER = LoggerFactory.getLogger("solver"); - - - static { - int delta = 0; - for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; i++) { - while ((char) (i + delta) == '"' || (char) (i + delta) == '{' || (char) (i + delta) == '}' || (char) (i + delta) == '<' || - (char) (i + delta) == '>' || (char) (i + delta) == '[' || (char) (i + delta) == ']' || - (char) (i + delta) == '(' || (char) (i + delta) == ')') delta++; - charFromIntMap.put(i, i + delta); - intFromCharMap.put(i + delta, i); - } - - } - - public static int getIntFromChar(char c) { - return intFromCharMap.get(c); - } - - public static char getCharFromInt(int i) { - return (char) charFromIntMap.get(i); - } - - - protected Automaton representedBy; - - protected TObjectIntHashMap stateToIndex; - protected ArrayList states; - protected TIntHashSet alphabet; - protected int nbStates; - - - public FiniteAutomaton() { - this.representedBy = new Automaton(); - this.stateToIndex = new TObjectIntHashMap(); - this.states = new ArrayList(); - - this.alphabet = new TIntHashSet(); - - } - - public FiniteAutomaton(String regexp) { - this(); - String correct = StringUtils.toCharExp(regexp); - this.representedBy = new RegExp(correct).toAutomaton(); - for (State s : representedBy.getStates()) { - for (Transition t : s.getTransitions()) { - for (char c = t.getMin(); c <= t.getMax(); c++) { - alphabet.add(getIntFromChar(c)); - } - } - } - syncStates(); - } - - public FiniteAutomaton(FiniteAutomaton other) { - perfectCopy(other); - } - - private void perfectCopy(FiniteAutomaton other) { - this.representedBy = new Automaton(); - this.states = new ArrayList(); - this.stateToIndex = new TObjectIntHashMap(); - this.alphabet = new TIntHashSet(); - this.nbStates = other.nbStates; - for (int i = 0; i < other.nbStates; i++) { - State s = new State(); - this.states.add(s); - this.stateToIndex.put(s, i); - if (other.isFinal(i)) - s.setAccept(true); - if (other.getInitialState() == i) - this.representedBy.setInitialState(s); - } - List transitions = other.getTransitions(); - for (int[] t : transitions) { - this.addTransition(t[0], t[1], t[2]); - } - - } - - private FiniteAutomaton(Automaton a, TIntHashSet alphabet) { - this(); - fill(a, alphabet); - - } - - - public static int max(TIntHashSet hs) { - int max = Integer.MIN_VALUE; - for (TIntIterator it = hs.iterator(); it.hasNext(); ) { - int n = it.next(); - if (n > max) - max = n; - } - return max; - } - - private static int min(TIntHashSet hs) { - int min = Integer.MAX_VALUE; - for (TIntIterator it = hs.iterator(); it.hasNext(); ) { - int n = it.next(); - if (n < min) - min = n; - } - return min; - } - - public void fill(Automaton a, TIntHashSet alphabet) { - - int max = max(alphabet); - int min = min(alphabet); - - - this.setDeterministic(a.isDeterministic()); - - HashMap m = new HashMap(); - Set states = a.getStates(); - for (State s : states) { - this.addState(); - State ns = this.states.get(this.states.size() - 1); - m.put(s, ns); - - } - for (State s : states) { - State p = m.get(s); - int source = stateToIndex.get(p); - p.setAccept(s.isAccept()); - if (a.getInitialState().equals(s)) - representedBy.setInitialState(p); - for (Transition t : s.getTransitions()) { - int tmin = getIntFromChar(t.getMin()); - int tmax = getIntFromChar(t.getMax()); - State dest = m.get(t.getDest()); - int desti = stateToIndex.get(dest); - int minmax = Math.min(max, tmax); - for (int i = Math.max(min, tmin); i <= minmax; i++) { - if (alphabet.contains(i)) - this.addTransition(source, desti, i); - } - } - - } - } - - public int getNbStates() { - return nbStates; - } - - public int getNbSymbols() { - return alphabet.size(); - } - - public int addState() { - int idx = states.size(); - State s = new State(); - states.add(s); - stateToIndex.put(s, idx); - nbStates++; - return idx; - } - - - public void removeSymbolFromAutomaton(int symbol) { - char c = getCharFromInt(symbol); - ArrayList triples = new ArrayList(); - for (int i = 0; i < states.size(); i++) { - State s = states.get(i); - for (Transition t : s.getTransitions()) { - - if (t.getMin() <= c && t.getMax() >= c) { - triples.add(new Triple(i, stateToIndex.get(t.getDest()), symbol)); - } - } - for (Triple t : triples) { - this.deleteTransition(t.a, t.b, t.c); - } - triples.clear(); - } - alphabet.remove(symbol); - //this.representedBy.reduce(); - // this.syncStates(); - } - - public void addTransition(int source, int destination, int... symbols) { - for (int symbol : symbols) { - try { - checkState(source, destination); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to addTransition : " + e); - } - alphabet.add(symbol); - State s = states.get(source); - State d = states.get(destination); - s.addTransition(new Transition(getCharFromInt(symbol), d)); - } - } - - public void deleteTransition(int source, int destination, int symbol) { - try { - checkState(source, destination); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to delete transition : " + e); - } - State s = states.get(source); - State d = states.get(destination); - Set transitions = s.getTransitions(); - Set nTrans = new HashSet(); - char c = getCharFromInt(symbol); - Iterator it = transitions.iterator(); - for (; it.hasNext(); ) { - Transition t = it.next(); - if (t.getDest().equals(d) && t.getMin() <= c && t.getMax() >= c) { - it.remove(); - - if (t.getMin() == c && c < t.getMax()) { - nTrans.add(new Transition((char) (c + 1), t.getMax(), d)); - } else if (t.getMin() > c && c == t.getMax()) { - nTrans.add(new Transition(t.getMin(), (char) (c - 1), d)); - } else if (t.getMin() < c && c < t.getMax()) { - nTrans.add(new Transition(t.getMin(), (char) (c - 1), d)); - nTrans.add(new Transition((char) (c + 1), t.getMax(), d)); - } - } - } - transitions.addAll(nTrans); - } - - private void checkState(int... state) throws StateNotInAutomatonException { - int sz = states.size(); - for (int s : state) - if (s >= sz) { - throw new StateNotInAutomatonException(s); - } - } - - public int delta(int source, int symbol) throws NonDeterministicOperationException { - if (!representedBy.isDeterministic()) { - throw new NonDeterministicOperationException(); - } - try { - checkState(source); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to perform delta lookup, state not in automaton : " + e); - } - State s = states.get(source); - State d = s.step(getCharFromInt(symbol)); - if (d != null) { - return stateToIndex.get(d); - } else - return -1; - - } - - private HashSet nexts = new HashSet(); - - public void delta(int source, int symbol, TIntHashSet states) { - try { - checkState(source); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable perform delta lookup, state not in automaton : " + e); - } - State s = this.states.get(source); - nexts.clear(); - s.step(getCharFromInt(symbol), nexts); - for (State to : nexts) { - states.add(stateToIndex.get(to)); - } - } - - - public TIntArrayList getOutSymbols(int source) { - try { - checkState(source); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to get outgoing transition, state not in automaton : " + e); - } - TIntHashSet set = new TIntHashSet(); - State s = states.get(source); - for (Transition t : s.getTransitions()) { - for (char c = t.getMin(); c <= t.getMax(); c++) { - set.add(getIntFromChar(c)); - } - } - return new TIntArrayList(set.toArray()); - - } - - private TIntHashSet tmpSet = new TIntHashSet(); - - public int[] getOutSymbolsArray(int source) { - try { - checkState(source); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to get outgoing transition, state not in automaton : " + e); - } - tmpSet.clear(); - State s = states.get(source); - for (Transition t : s.getTransitions()) { - for (char c = t.getMin(); c <= t.getMax(); c++) { - tmpSet.add(getIntFromChar(c)); - } - } - return tmpSet.toArray(); - - } - - public void addToAlphabet(int a) { - alphabet.add(a); - } - - public void removeFromAlphabet(int a) { - alphabet.remove(a); - } - - public int getInitialState() { - State s = representedBy.getInitialState(); - if (s == null) - return -1; - else - return stateToIndex.get(s); - } - - public boolean isFinal(int state) { - try { - checkState(state); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to check if this state is final : " + e); - } - return states.get(state).isAccept(); - } - - public void setInitialState(int state) { - try { - checkState(state); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to set initial state, state is not in automaton : " + e); - } - representedBy.setInitialState(states.get(state)); - } - - public void setFinal(int state) { - try { - checkState(state); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to set final state, state is not in automaton : " + e); - } - states.get(state).setAccept(true); - } - - public void setFinal(int... states) { - for (int s : states) setFinal(s); - } - - public void setNonFinal(int state) { - try { - checkState(state); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to set non final state, state is not in automaton : " + e); - } - states.get(state).setAccept(false); - } - - public void setNonFInal(int... states) { - for (int s : states) setNonFinal(s); - } - - public boolean run(int[] word) { - StringBuilder b = new StringBuilder(); - for (int i : word) { - char c = getCharFromInt(i); - b.append(c); - } - return representedBy.run(b.toString()); - } - - public Automaton makeBricsAutomaton() { - return representedBy.clone(); - } - - public IAutomaton repeat() { - return new FiniteAutomaton(this.representedBy.repeat(), alphabet); - } - - public IAutomaton repeat(int min) { - return new FiniteAutomaton(this.representedBy.repeat(min), alphabet); - } - - public IAutomaton repeat(int min, int max) { - return new FiniteAutomaton(this.representedBy.repeat(min, max), alphabet); - } - - public void minimize() { - this.representedBy.minimize(); - syncStates(); - } - - private void syncStates() { - this.alphabet.clear(); - this.states.clear(); - this.stateToIndex.clear(); - int idx = 0; - for (State s : representedBy.getStates()) { - states.add(s); - stateToIndex.put(s, idx++); - for (Transition t : s.getTransitions()) { - for (char c = t.getMin(); c <= t.getMax(); c++) { - alphabet.add(getIntFromChar(c)); - } - } - } - nbStates = states.size(); - } - - public void reduce() { - this.representedBy.reduce(); - syncStates(); - } - - public void removeDeadTransitions() { - this.representedBy.removeDeadTransitions(); - syncStates(); - } - - public FiniteAutomaton union(FiniteAutomaton otherI) { - FiniteAutomaton other = (FiniteAutomaton) otherI; - Automaton union = this.representedBy.union(other.representedBy); - TIntHashSet alphabet = new TIntHashSet(this.alphabet.toArray()); - alphabet.addAll(other.alphabet.toArray()); - return new FiniteAutomaton(union, alphabet); - - } - - public FiniteAutomaton intersection(IAutomaton otherI) { - FiniteAutomaton other = (FiniteAutomaton) otherI; - Automaton inter = this.representedBy.intersection(other.representedBy); - TIntHashSet alphabet = new TIntHashSet(); - for (int a : this.alphabet.toArray()) { - if (other.alphabet.contains(a)) - alphabet.add(a); - } - return new FiniteAutomaton(inter, alphabet); - } - - public FiniteAutomaton complement(TIntHashSet alphabet) { - Automaton comp = this.representedBy.complement(); - return new FiniteAutomaton(comp, alphabet); - } - - public FiniteAutomaton complement() { - return complement(alphabet); - } - - - public FiniteAutomaton concatenate(FiniteAutomaton otherI) { - FiniteAutomaton other = (FiniteAutomaton) otherI; - Automaton conc = this.representedBy.concatenate(other.representedBy); - TIntHashSet alphabet = new TIntHashSet(this.alphabet.toArray()); - alphabet.addAll(other.alphabet.toArray()); - return new FiniteAutomaton(conc, alphabet); - } - - public void addEpsilon(int source, int destination) { - try { - checkState(source, destination); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to add epsilon transition, a state is not in the automaton : " + e); - - } - State s = states.get(source); - State d = states.get(destination); - - - ArrayList pairs = new ArrayList(); - pairs.add(new StatePair(s, d)); - this.representedBy.addEpsilons(pairs); - } - - public boolean isDeterministic() { - return this.representedBy.isDeterministic(); - } - - public void setDeterministic(boolean deterministic) { - this.representedBy.setDeterministic(deterministic); - } - - public TIntHashSet getFinalStates() { - TIntHashSet finals = new TIntHashSet(); - for (int i = 0; i < states.size(); i++) { - if (states.get(i).isAccept()) - finals.add(i); - } - return finals; - } - - - public void toDotty(String f) { - String s = this.toDot(); - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(new File(f))); - bw.write(s); - bw.close(); - } catch (IOException e) { - System.err.println("Unable to write dotty file " + f); - } - } - - public String toDot() { - StringBuilder b = new StringBuilder("digraph Automaton {\n"); - b.append(" rankdir = LR;\n"); - Set states = this.representedBy.getStates(); - // setStateNumbers(states); - for (State s : states) { - int idx = stateToIndex.get(s); - b.append(" ").append(idx); - if (s.isAccept()) - b.append(" [shape=doublecircle];\n"); - else - b.append(" [shape=circle];\n"); - if (s == this.representedBy.getInitialState()) { - b.append(" initial [shape=plaintext,label=\"\"];\n"); - b.append(" initial -> ").append(idx).append("\n"); - } - for (Transition t : s.getTransitions()) { - b.append(" ").append(idx); - appendDot(t, b); - } - } - return b.append("}\n").toString(); - } - - private void appendDot(Transition t, StringBuilder b) { - int destIdx = stateToIndex.get(t.getDest()); - - b.append(" -> ").append(destIdx).append(" [label=\""); - b.append("{"); - b.append(getIntFromChar(t.getMin())); - if (t.getMin() != t.getMax()) { - for (char c = (char) (t.getMin() + 1); c <= t.getMax(); c++) { - b.append(","); - b.append(getIntFromChar(c)); - } - } - b.append("}"); - b.append("\"]\n"); - } - - public TIntHashSet getAlphabet() { - return alphabet; - } - - public List getTransitions() { - List transitions = new ArrayList(); - for (int i = 0; i < states.size(); i++) { - State s = states.get(i); - for (Transition t : s.getTransitions()) { - int dest = stateToIndex.get(t.getDest()); - for (char c = t.getMin(); c <= t.getMax(); c++) { - int symbol = getIntFromChar(c); - transitions.add(new int[]{i, dest, symbol}); - } - } - } - return transitions; - } - - - public List getTransitions(int state) { - List transitions = new ArrayList(); - for (Transition t : states.get(state).getTransitions()) { - int dest = stateToIndex.get(t.getDest()); - for (char c = t.getMin(); c <= t.getMax(); c++) { - int symbol = getIntFromChar(c); - transitions.add(new int[]{state, dest, symbol}); - } - } - return transitions; - } - - public ArrayList _removeSymbolFromAutomaton(int alpha) { - char c = getCharFromInt(alpha); - TIntHashSet setOfRemoved = new TIntHashSet(); - ArrayList triples = new ArrayList(); - for (int i = 0; i < states.size(); i++) { - State s = states.get(i); - for (Transition t : s.getTransitions()) { - - if (t.getMin() <= c && t.getMax() >= c) { - triples.add(new Triple(i, stateToIndex.get(t.getDest()), alpha)); - setOfRemoved.add(i); - } - } - for (Triple t : triples) { - this.deleteTransition(t.a, t.b, t.c); - } - triples.clear(); - - } - alphabet.remove(alpha); - // this.removeDeadTransitions(); - ArrayList couple = new ArrayList(); - for (int i = 0; i < states.size(); i++) { - State s = states.get(i); - for (Transition t : s.getTransitions()) { - int dest = stateToIndex.get(t.getDest()); - if (setOfRemoved.contains(dest)) { - for (char d = t.getMin(); d <= t.getMax(); d++) - couple.add(new int[]{i, getIntFromChar(d)}); - } - - } - - - } - return couple; - - - //this.representedBy.reduce(); - // this.syncStates(); - - - } - - public FiniteAutomaton clone() throws CloneNotSupportedException { - FiniteAutomaton auto = (FiniteAutomaton) super.clone(); - auto.representedBy = new Automaton(); - auto.states = new ArrayList(); - auto.stateToIndex = new TObjectIntHashMap(); - auto.alphabet = new TIntHashSet(); - auto.nbStates = this.nbStates; - for (int i = 0; i < this.nbStates; i++) { - State s = new State(); - auto.states.add(s); - auto.stateToIndex.put(s, i); - if (this.isFinal(i)) - s.setAccept(true); - if (this.getInitialState() == i) - auto.representedBy.setInitialState(s); - } - List transitions = this.getTransitions(); - for (int[] t : transitions) { - auto.addTransition(t[0], t[1], t[2]); - } - return auto; - } - - - @Override - public String toString() { - return representedBy.toString(); - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/old/FiniteAutomaton.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/old/FiniteAutomaton.java deleted file mode 100755 index b54a8fc..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/old/FiniteAutomaton.java +++ /dev/null @@ -1,708 +0,0 @@ -/** - * Copyright (c) 1999-2010, Ecole des Mines de Nantes - * All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the Ecole des Mines de Nantes nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package solver.constraints.nary.automata.FA; - -import dk.brics.automaton.*; -import gnu.trove.iterator.TIntIterator; -import gnu.trove.list.array.TIntArrayList; -import gnu.trove.map.hash.TIntIntHashMap; -import gnu.trove.map.hash.TObjectIntHashMap; -import gnu.trove.set.hash.TIntHashSet; -import org.slf4j.LoggerFactory; -import util.tools.StringUtils; - -import java.io.BufferedWriter; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.util.*; - -/** - * Created by IntelliJ IDEA. - * User: julien - * Date: Mar 15, 2010 - * Time: 12:53:23 PM - */ -public class FiniteAutomaton implements IAutomaton { - - - protected static TIntIntHashMap charFromIntMap = new TIntIntHashMap(); - protected static TIntIntHashMap intFromCharMap = new TIntIntHashMap(); - - public static org.slf4j.Logger LOGGER = LoggerFactory.getLogger("solver"); - - - static { - int delta = 0; - for (int i = Character.MIN_VALUE; i <= Character.MAX_VALUE; i++) { - while ((char) (i + delta) == '"' || (char) (i + delta) == '{' || (char) (i + delta) == '}' || (char) (i + delta) == '<' || - (char) (i + delta) == '>' || (char) (i + delta) == '[' || (char) (i + delta) == ']' || - (char) (i + delta) == '(' || (char) (i + delta) == ')') delta++; - charFromIntMap.put(i, i + delta); - intFromCharMap.put(i + delta, i); - } - - } - - public static int getIntFromChar(char c) { - return intFromCharMap.get(c); - } - - public static char getCharFromInt(int i) { - return (char) charFromIntMap.get(i); - } - - - protected Automaton representedBy; - - protected TObjectIntHashMap stateToIndex; - protected ArrayList states; - protected TIntHashSet alphabet; - protected int nbStates; - - - public FiniteAutomaton() { - this.representedBy = new Automaton(); - this.stateToIndex = new TObjectIntHashMap(); - this.states = new ArrayList(); - - this.alphabet = new TIntHashSet(); - - } - - public FiniteAutomaton(String regexp) { - this(); - String correct = StringUtils.toCharExp(regexp); - this.representedBy = new RegExp(correct).toAutomaton(); - for (State s : representedBy.getStates()) { - for (Transition t : s.getTransitions()) { - for (char c = t.getMin(); c <= t.getMax(); c++) { - alphabet.add(getIntFromChar(c)); - } - } - } - syncStates(); - } - - public FiniteAutomaton(FiniteAutomaton other) { - perfectCopy(other); - } - - private void perfectCopy(FiniteAutomaton other) { - this.representedBy = new Automaton(); - this.states = new ArrayList(); - this.stateToIndex = new TObjectIntHashMap(); - this.alphabet = new TIntHashSet(); - this.nbStates = other.nbStates; - for (int i = 0; i < other.nbStates; i++) { - State s = new State(); - this.states.add(s); - this.stateToIndex.put(s, i); - if (other.isFinal(i)) - s.setAccept(true); - if (other.getInitialState() == i) - this.representedBy.setInitialState(s); - } - List transitions = other.getTransitions(); - for (int[] t : transitions) { - this.addTransition(t[0], t[1], t[2]); - } - - } - - private FiniteAutomaton(Automaton a, TIntHashSet alphabet) { - this(); - fill(a, alphabet); - - } - - - public static int max(TIntHashSet hs) { - int max = Integer.MIN_VALUE; - for (TIntIterator it = hs.iterator(); it.hasNext(); ) { - int n = it.next(); - if (n > max) - max = n; - } - return max; - } - - private static int min(TIntHashSet hs) { - int min = Integer.MAX_VALUE; - for (TIntIterator it = hs.iterator(); it.hasNext(); ) { - int n = it.next(); - if (n < min) - min = n; - } - return min; - } - - public void fill(Automaton a, TIntHashSet alphabet) { - - int max = max(alphabet); - int min = min(alphabet); - - - this.setDeterministic(a.isDeterministic()); - - HashMap m = new HashMap(); - Set states = a.getStates(); - for (State s : states) { - this.addState(); - State ns = this.states.get(this.states.size() - 1); - m.put(s, ns); - - } - for (State s : states) { - State p = m.get(s); - int source = stateToIndex.get(p); - p.setAccept(s.isAccept()); - if (a.getInitialState().equals(s)) - representedBy.setInitialState(p); - for (Transition t : s.getTransitions()) { - int tmin = getIntFromChar(t.getMin()); - int tmax = getIntFromChar(t.getMax()); - State dest = m.get(t.getDest()); - int desti = stateToIndex.get(dest); - int minmax = Math.min(max, tmax); - for (int i = Math.max(min, tmin); i <= minmax; i++) { - if (alphabet.contains(i)) - this.addTransition(source, desti, i); - } - } - - } - } - - public int getNbStates() { - return nbStates; - } - - public int getNbSymbols() { - return alphabet.size(); - } - - public int addState() { - int idx = states.size(); - State s = new State(); - states.add(s); - stateToIndex.put(s, idx); - nbStates++; - return idx; - } - - - public void removeSymbolFromAutomaton(int symbol) { - char c = getCharFromInt(symbol); - ArrayList triples = new ArrayList(); - for (int i = 0; i < states.size(); i++) { - State s = states.get(i); - for (Transition t : s.getTransitions()) { - - if (t.getMin() <= c && t.getMax() >= c) { - triples.add(new Triple(i, stateToIndex.get(t.getDest()), symbol)); - } - } - for (Triple t : triples) { - this.deleteTransition(t.a, t.b, t.c); - } - triples.clear(); - } - alphabet.remove(symbol); - //this.representedBy.reduce(); - // this.syncStates(); - } - - public void addTransition(int source, int destination, int... symbols) { - for (int symbol : symbols) { - try { - checkState(source, destination); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to addTransition : " + e); - } - alphabet.add(symbol); - State s = states.get(source); - State d = states.get(destination); - s.addTransition(new Transition(getCharFromInt(symbol), d)); - } - } - - public void deleteTransition(int source, int destination, int symbol) { - try { - checkState(source, destination); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to delete transition : " + e); - } - State s = states.get(source); - State d = states.get(destination); - Set transitions = s.getTransitions(); - Set nTrans = new HashSet(); - char c = getCharFromInt(symbol); - Iterator it = transitions.iterator(); - for (; it.hasNext(); ) { - Transition t = it.next(); - if (t.getDest().equals(d) && t.getMin() <= c && t.getMax() >= c) { - it.remove(); - - if (t.getMin() == c && c < t.getMax()) { - nTrans.add(new Transition((char) (c + 1), t.getMax(), d)); - } else if (t.getMin() > c && c == t.getMax()) { - nTrans.add(new Transition(t.getMin(), (char) (c - 1), d)); - } else if (t.getMin() < c && c < t.getMax()) { - nTrans.add(new Transition(t.getMin(), (char) (c - 1), d)); - nTrans.add(new Transition((char) (c + 1), t.getMax(), d)); - } - } - } - transitions.addAll(nTrans); - } - - private void checkState(int... state) throws StateNotInAutomatonException { - int sz = states.size(); - for (int s : state) - if (s >= sz) { - throw new StateNotInAutomatonException(s); - } - } - - public int delta(int source, int symbol) throws NonDeterministicOperationException { - if (!representedBy.isDeterministic()) { - throw new NonDeterministicOperationException(); - } - try { - checkState(source); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to perform delta lookup, state not in automaton : " + e); - } - State s = states.get(source); - State d = s.step(getCharFromInt(symbol)); - if (d != null) { - return stateToIndex.get(d); - } else - return -1; - - } - - private HashSet nexts = new HashSet(); - - public void delta(int source, int symbol, TIntHashSet states) { - try { - checkState(source); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable perform delta lookup, state not in automaton : " + e); - } - State s = this.states.get(source); - nexts.clear(); - s.step(getCharFromInt(symbol), nexts); - for (State to : nexts) { - states.add(stateToIndex.get(to)); - } - } - - - public TIntArrayList getOutSymbols(int source) { - try { - checkState(source); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to get outgoing transition, state not in automaton : " + e); - } - TIntHashSet set = new TIntHashSet(); - State s = states.get(source); - for (Transition t : s.getTransitions()) { - for (char c = t.getMin(); c <= t.getMax(); c++) { - set.add(getIntFromChar(c)); - } - } - return new TIntArrayList(set.toArray()); - - } - - private TIntHashSet tmpSet = new TIntHashSet(); - - public int[] getOutSymbolsArray(int source) { - try { - checkState(source); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to get outgoing transition, state not in automaton : " + e); - } - tmpSet.clear(); - State s = states.get(source); - for (Transition t : s.getTransitions()) { - for (char c = t.getMin(); c <= t.getMax(); c++) { - tmpSet.add(getIntFromChar(c)); - } - } - return tmpSet.toArray(); - - } - - public void addToAlphabet(int a) { - alphabet.add(a); - } - - public void removeFromAlphabet(int a) { - alphabet.remove(a); - } - - public int getInitialState() { - State s = representedBy.getInitialState(); - if (s == null) - return -1; - else - return stateToIndex.get(s); - } - - public boolean isFinal(int state) { - try { - checkState(state); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to check if this state is final : " + e); - } - return states.get(state).isAccept(); - } - - public void setInitialState(int state) { - try { - checkState(state); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to set initial state, state is not in automaton : " + e); - } - representedBy.setInitialState(states.get(state)); - } - - public void setFinal(int state) { - try { - checkState(state); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to set final state, state is not in automaton : " + e); - } - states.get(state).setAccept(true); - } - - public void setFinal(int... states) { - for (int s : states) setFinal(s); - } - - public void setNonFinal(int state) { - try { - checkState(state); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to set non final state, state is not in automaton : " + e); - } - states.get(state).setAccept(false); - } - - public void setNonFInal(int... states) { - for (int s : states) setNonFinal(s); - } - - public boolean run(int[] word) { - StringBuffer b = new StringBuffer(); - for (int i : word) { - char c = getCharFromInt(i); - b.append(c); - } - return representedBy.run(b.toString()); - } - - public Automaton makeBricsAutomaton() { - return representedBy.clone(); - } - - public IAutomaton repeat() { - return new FiniteAutomaton(this.representedBy.repeat(), alphabet); - } - - public IAutomaton repeat(int min) { - return new FiniteAutomaton(this.representedBy.repeat(min), alphabet); - } - - public IAutomaton repeat(int min, int max) { - return new FiniteAutomaton(this.representedBy.repeat(min, max), alphabet); - } - - public void minimize() { - this.representedBy.minimize(); - syncStates(); - } - - private void syncStates() { - this.alphabet.clear(); - this.states.clear(); - this.stateToIndex.clear(); - int idx = 0; - for (State s : representedBy.getStates()) { - states.add(s); - stateToIndex.put(s, idx++); - for (Transition t : s.getTransitions()) { - for (char c = t.getMin(); c <= t.getMax(); c++) { - alphabet.add(getIntFromChar(c)); - } - } - } - nbStates = states.size(); - } - - public void reduce() { - this.representedBy.reduce(); - syncStates(); - } - - public void removeDeadTransitions() { - this.representedBy.removeDeadTransitions(); - syncStates(); - } - - public FiniteAutomaton union(FiniteAutomaton otherI) { - FiniteAutomaton other = (FiniteAutomaton) otherI; - Automaton union = this.representedBy.union(other.representedBy); - TIntHashSet alphabet = new TIntHashSet(this.alphabet.toArray()); - alphabet.addAll(other.alphabet.toArray()); - return new FiniteAutomaton(union, alphabet); - - } - - public FiniteAutomaton intersection(IAutomaton otherI) { - FiniteAutomaton other = (FiniteAutomaton) otherI; - Automaton inter = this.representedBy.intersection(other.representedBy); - TIntHashSet alphabet = new TIntHashSet(); - for (int a : this.alphabet.toArray()) { - if (other.alphabet.contains(a)) - alphabet.add(a); - } - return new FiniteAutomaton(inter, alphabet); - } - - public FiniteAutomaton complement(TIntHashSet alphabet) { - Automaton comp = this.representedBy.complement(); - return new FiniteAutomaton(comp, alphabet); - } - - public FiniteAutomaton complement() { - return complement(alphabet); - } - - - public FiniteAutomaton concatenate(FiniteAutomaton otherI) { - FiniteAutomaton other = (FiniteAutomaton) otherI; - Automaton conc = this.representedBy.concatenate(other.representedBy); - TIntHashSet alphabet = new TIntHashSet(this.alphabet.toArray()); - alphabet.addAll(other.alphabet.toArray()); - return new FiniteAutomaton(conc, alphabet); - } - - public void addEpsilon(int source, int destination) { - try { - checkState(source, destination); - } catch (StateNotInAutomatonException e) { - LOGGER.warn("Unable to add epsilon transition, a state is not in the automaton : " + e); - - } - State s = states.get(source); - State d = states.get(destination); - - - ArrayList pairs = new ArrayList(); - pairs.add(new StatePair(s, d)); - this.representedBy.addEpsilons(pairs); - } - - public boolean isDeterministic() { - return this.representedBy.isDeterministic(); - } - - public void setDeterministic(boolean deterministic) { - this.representedBy.setDeterministic(deterministic); - } - - public TIntHashSet getFinalStates() { - TIntHashSet finals = new TIntHashSet(); - for (int i = 0; i < states.size(); i++) { - if (states.get(i).isAccept()) - finals.add(i); - } - return finals; - } - - - public void toDotty(String f) { - String s = this.toDot(); - try { - BufferedWriter bw = new BufferedWriter(new FileWriter(new File(f))); - bw.write(s); - bw.close(); - } catch (IOException e) { - System.err.println("Unable to write dotty file " + f); - } - } - - public String toDot() { - StringBuilder b = new StringBuilder("digraph Automaton {\n"); - b.append(" rankdir = LR;\n"); - Set states = this.representedBy.getStates(); - // setStateNumbers(states); - for (State s : states) { - int idx = stateToIndex.get(s); - b.append(" ").append(idx); - if (s.isAccept()) - b.append(" [shape=doublecircle];\n"); - else - b.append(" [shape=circle];\n"); - if (s == this.representedBy.getInitialState()) { - b.append(" initial [shape=plaintext,label=\"\"];\n"); - b.append(" initial -> ").append(idx).append("\n"); - } - for (Transition t : s.getTransitions()) { - b.append(" ").append(idx); - appendDot(t, b); - } - } - return b.append("}\n").toString(); - } - - private void appendDot(Transition t, StringBuilder b) { - int destIdx = stateToIndex.get(t.getDest()); - - b.append(" -> ").append(destIdx).append(" [label=\""); - b.append("{"); - b.append(getIntFromChar(t.getMin())); - if (t.getMin() != t.getMax()) { - for (char c = (char) (t.getMin() + 1); c <= t.getMax(); c++) { - b.append(","); - b.append(getIntFromChar(c)); - } - } - b.append("}"); - b.append("\"]\n"); - } - - public TIntHashSet getAlphabet() { - return alphabet; - } - - public List getTransitions() { - List transitions = new ArrayList(); - for (int i = 0; i < states.size(); i++) { - State s = states.get(i); - for (Transition t : s.getTransitions()) { - int dest = stateToIndex.get(t.getDest()); - for (char c = t.getMin(); c <= t.getMax(); c++) { - int symbol = getIntFromChar(c); - transitions.add(new int[]{i, dest, symbol}); - } - } - } - return transitions; - } - - - public List getTransitions(int state) { - List transitions = new ArrayList(); - for (Transition t : states.get(state).getTransitions()) { - int dest = stateToIndex.get(t.getDest()); - for (char c = t.getMin(); c <= t.getMax(); c++) { - int symbol = getIntFromChar(c); - transitions.add(new int[]{state, dest, symbol}); - } - } - return transitions; - } - - public ArrayList _removeSymbolFromAutomaton(int alpha) { - char c = getCharFromInt(alpha); - TIntHashSet setOfRemoved = new TIntHashSet(); - ArrayList triples = new ArrayList(); - for (int i = 0; i < states.size(); i++) { - State s = states.get(i); - for (Transition t : s.getTransitions()) { - - if (t.getMin() <= c && t.getMax() >= c) { - triples.add(new Triple(i, stateToIndex.get(t.getDest()), alpha)); - setOfRemoved.add(i); - } - } - for (Triple t : triples) { - this.deleteTransition(t.a, t.b, t.c); - } - triples.clear(); - - } - alphabet.remove(alpha); - // this.removeDeadTransitions(); - ArrayList couple = new ArrayList(); - for (int i = 0; i < states.size(); i++) { - State s = states.get(i); - for (Transition t : s.getTransitions()) { - int dest = stateToIndex.get(t.getDest()); - if (setOfRemoved.contains(dest)) { - for (char d = t.getMin(); d <= t.getMax(); d++) - couple.add(new int[]{i, getIntFromChar(d)}); - } - - } - - - } - return couple; - - - //this.representedBy.reduce(); - // this.syncStates(); - - - } - - public FiniteAutomaton clone() throws CloneNotSupportedException { - FiniteAutomaton auto = (FiniteAutomaton) super.clone(); - auto.representedBy = new Automaton(); - auto.states = new ArrayList(); - auto.stateToIndex = new TObjectIntHashMap(); - auto.alphabet = new TIntHashSet(); - auto.nbStates = this.nbStates; - for (int i = 0; i < this.nbStates; i++) { - State s = new State(); - auto.states.add(s); - auto.stateToIndex.put(s, i); - if (this.isFinal(i)) - s.setAccept(true); - if (this.getInitialState() == i) - auto.representedBy.setInitialState(s); - } - List transitions = this.getTransitions(); - for (int[] t : transitions) { - auto.addTransition(t[0], t[1], t[2]); - } - return auto; - } - - - @Override - public String toString() { - return representedBy.toString(); - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/pair.info deleted file mode 100755 index ab4140e..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#28661/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:28661 -comSha:d92c1f718d4d12b5a5650ddc011dd9d0e68210a8 -parentComSha:245dc32449eebb5cdbb6df2bc39819d7faa68375 -BuggyFilePath:choco-solver/src/main/java/solver/constraints/nary/automata/FA/FiniteAutomaton.java -FixedFilePath:choco-solver/src/main/java/solver/constraints/nary/automata/FA/FiniteAutomaton.java -StartLineNum:55 -EndLineNum:55 -repoName:chocoteam#choco3 \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/comMsg.txt deleted file mode 100755 index 6642cb8..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Finalized some fields, removed redundant code, various other fixes \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/diff.diff deleted file mode 100755 index a6da60c..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/fr/xephi/authme/security/PasswordSecurity.java b/src/main/java/fr/xephi/authme/security/PasswordSecurity.java -index 723026d9..571c83fb 100644 ---- a/src/main/java/fr/xephi/authme/security/PasswordSecurity.java -+++ b/src/main/java/fr/xephi/authme/security/PasswordSecurity.java -@@ -21,2 +21,2 @@ public class PasswordSecurity { -- public static HashMap userSalt = new HashMap<>(); -- private static SecureRandom rnd = new SecureRandom(); -+ public static final HashMap userSalt = new HashMap<>(); -+ private static final SecureRandom rnd = new SecureRandom(); -@@ -194 +194 @@ public class PasswordSecurity { -- String hash, String playerName) throws NoSuchAlgorithmException { -+ String hash, String playerName) { \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/new/PasswordSecurity.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/new/PasswordSecurity.java deleted file mode 100755 index 571c83f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/new/PasswordSecurity.java +++ /dev/null @@ -1,215 +0,0 @@ -package fr.xephi.authme.security; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.events.PasswordEncryptionEvent; -import fr.xephi.authme.security.crypts.BCRYPT; -import fr.xephi.authme.security.crypts.EncryptionMethod; -import fr.xephi.authme.settings.Settings; -import org.bukkit.Bukkit; - -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.HashMap; - -/** - */ -public class PasswordSecurity { - - public static final HashMap userSalt = new HashMap<>(); - private static final SecureRandom rnd = new SecureRandom(); - - /** - * Method createSalt. - * - * @param length int - * - * @return String * @throws NoSuchAlgorithmException - */ - public static String createSalt(int length) - throws NoSuchAlgorithmException { - byte[] msg = new byte[40]; - rnd.nextBytes(msg); - MessageDigest sha1 = MessageDigest.getInstance("SHA1"); - sha1.reset(); - byte[] digest = sha1.digest(msg); - return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)).substring(0, length); - } - - /** - * Method getHash. - * - * @param alg HashAlgorithm - * @param password String - * @param playerName String - * - * @return String * @throws NoSuchAlgorithmException - */ - public static String getHash(HashAlgorithm alg, String password, - String playerName) throws NoSuchAlgorithmException { - EncryptionMethod method; - try { - if (alg != HashAlgorithm.CUSTOM) - method = (EncryptionMethod) alg.getclasse().newInstance(); - else method = null; - } catch (InstantiationException | IllegalAccessException e) { - throw new NoSuchAlgorithmException("Problem with this hash algorithm"); - } - String salt = ""; - switch (alg) { - case SHA256: - salt = createSalt(16); - break; - case MD5VB: - salt = createSalt(16); - break; - case XAUTH: - salt = createSalt(12); - break; - case MYBB: - salt = createSalt(8); - userSalt.put(playerName, salt); - break; - case IPB3: - salt = createSalt(5); - userSalt.put(playerName, salt); - break; - case PHPFUSION: - salt = createSalt(12); - userSalt.put(playerName, salt); - break; - case SALTED2MD5: - salt = createSalt(Settings.saltLength); - userSalt.put(playerName, salt); - break; - case JOOMLA: - salt = createSalt(32); - userSalt.put(playerName, salt); - break; - case BCRYPT: - salt = BCRYPT.gensalt(Settings.bCryptLog2Rounds); - userSalt.put(playerName, salt); - break; - case WBB3: - salt = createSalt(40); - userSalt.put(playerName, salt); - break; - case WBB4: - salt = BCRYPT.gensalt(8); - userSalt.put(playerName, salt); - break; - case PBKDF2DJANGO: - case PBKDF2: - salt = createSalt(12); - userSalt.put(playerName, salt); - break; - case SMF: - return method.getHash(password, null, playerName); - case PHPBB: - salt = createSalt(16); - userSalt.put(playerName, salt); - break; - case BCRYPT2Y: - salt = createSalt(16); - userSalt.put(playerName, salt); - break; - case SALTEDSHA512: - salt = createSalt(32); - userSalt.put(playerName, salt); - break; - case MD5: - case SHA1: - case WHIRLPOOL: - case PLAINTEXT: - case XENFORO: - case SHA512: - case ROYALAUTH: - case CRAZYCRYPT1: - case DOUBLEMD5: - case WORDPRESS: - case CUSTOM: - break; - default: - throw new NoSuchAlgorithmException("Unknown hash algorithm"); - } - PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName); - Bukkit.getPluginManager().callEvent(event); - method = event.getMethod(); - if (method == null) - throw new NoSuchAlgorithmException("Unknown hash algorithm"); - return method.getHash(password, salt, playerName); - } - - /** - * Method comparePasswordWithHash. - * - * @param password String - * @param hash String - * @param playerName String - * - * @return boolean * @throws NoSuchAlgorithmException - */ - public static boolean comparePasswordWithHash(String password, String hash, - String playerName) throws NoSuchAlgorithmException { - HashAlgorithm algorithm = Settings.getPasswordHash; - EncryptionMethod method; - try { - if (algorithm != HashAlgorithm.CUSTOM) - method = (EncryptionMethod) algorithm.getclasse().newInstance(); - else - method = null; - - PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName); - Bukkit.getPluginManager().callEvent(event); - method = event.getMethod(); - - if (method == null) - throw new NoSuchAlgorithmException("Unknown hash algorithm"); - - if (method.comparePassword(hash, password, playerName)) - return true; - - if (Settings.supportOldPassword) { - if (compareWithAllEncryptionMethod(password, hash, playerName)) - return true; - } - } catch (InstantiationException | IllegalAccessException e) { - throw new NoSuchAlgorithmException("Problem with this hash algorithm"); - } - return false; - } - - /** - * Method compareWithAllEncryptionMethod. - * - * @param password String - * @param hash String - * @param playerName String - * - * @return boolean * @throws NoSuchAlgorithmException - */ - private static boolean compareWithAllEncryptionMethod(String password, - String hash, String playerName) { - for (HashAlgorithm algo : HashAlgorithm.values()) { - if (algo != HashAlgorithm.CUSTOM) { - try { - EncryptionMethod method = (EncryptionMethod) algo.getclasse().newInstance(); - if (method.comparePassword(hash, password, playerName)) { - PlayerAuth nAuth = AuthMe.getInstance().database.getAuth(playerName); - if (nAuth != null) { - nAuth.setHash(getHash(Settings.getPasswordHash, password, playerName)); - nAuth.setSalt(userSalt.containsKey(playerName) ? userSalt.get(playerName) : ""); - AuthMe.getInstance().database.updatePassword(nAuth); - AuthMe.getInstance().database.updateSalt(nAuth); - } - return true; - } - } catch (Exception ignored) { - } - } - } - return false; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/old/PasswordSecurity.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/old/PasswordSecurity.java deleted file mode 100755 index 723026d..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/old/PasswordSecurity.java +++ /dev/null @@ -1,215 +0,0 @@ -package fr.xephi.authme.security; - -import fr.xephi.authme.AuthMe; -import fr.xephi.authme.cache.auth.PlayerAuth; -import fr.xephi.authme.events.PasswordEncryptionEvent; -import fr.xephi.authme.security.crypts.BCRYPT; -import fr.xephi.authme.security.crypts.EncryptionMethod; -import fr.xephi.authme.settings.Settings; -import org.bukkit.Bukkit; - -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.HashMap; - -/** - */ -public class PasswordSecurity { - - public static HashMap userSalt = new HashMap<>(); - private static SecureRandom rnd = new SecureRandom(); - - /** - * Method createSalt. - * - * @param length int - * - * @return String * @throws NoSuchAlgorithmException - */ - public static String createSalt(int length) - throws NoSuchAlgorithmException { - byte[] msg = new byte[40]; - rnd.nextBytes(msg); - MessageDigest sha1 = MessageDigest.getInstance("SHA1"); - sha1.reset(); - byte[] digest = sha1.digest(msg); - return String.format("%0" + (digest.length << 1) + "x", new BigInteger(1, digest)).substring(0, length); - } - - /** - * Method getHash. - * - * @param alg HashAlgorithm - * @param password String - * @param playerName String - * - * @return String * @throws NoSuchAlgorithmException - */ - public static String getHash(HashAlgorithm alg, String password, - String playerName) throws NoSuchAlgorithmException { - EncryptionMethod method; - try { - if (alg != HashAlgorithm.CUSTOM) - method = (EncryptionMethod) alg.getclasse().newInstance(); - else method = null; - } catch (InstantiationException | IllegalAccessException e) { - throw new NoSuchAlgorithmException("Problem with this hash algorithm"); - } - String salt = ""; - switch (alg) { - case SHA256: - salt = createSalt(16); - break; - case MD5VB: - salt = createSalt(16); - break; - case XAUTH: - salt = createSalt(12); - break; - case MYBB: - salt = createSalt(8); - userSalt.put(playerName, salt); - break; - case IPB3: - salt = createSalt(5); - userSalt.put(playerName, salt); - break; - case PHPFUSION: - salt = createSalt(12); - userSalt.put(playerName, salt); - break; - case SALTED2MD5: - salt = createSalt(Settings.saltLength); - userSalt.put(playerName, salt); - break; - case JOOMLA: - salt = createSalt(32); - userSalt.put(playerName, salt); - break; - case BCRYPT: - salt = BCRYPT.gensalt(Settings.bCryptLog2Rounds); - userSalt.put(playerName, salt); - break; - case WBB3: - salt = createSalt(40); - userSalt.put(playerName, salt); - break; - case WBB4: - salt = BCRYPT.gensalt(8); - userSalt.put(playerName, salt); - break; - case PBKDF2DJANGO: - case PBKDF2: - salt = createSalt(12); - userSalt.put(playerName, salt); - break; - case SMF: - return method.getHash(password, null, playerName); - case PHPBB: - salt = createSalt(16); - userSalt.put(playerName, salt); - break; - case BCRYPT2Y: - salt = createSalt(16); - userSalt.put(playerName, salt); - break; - case SALTEDSHA512: - salt = createSalt(32); - userSalt.put(playerName, salt); - break; - case MD5: - case SHA1: - case WHIRLPOOL: - case PLAINTEXT: - case XENFORO: - case SHA512: - case ROYALAUTH: - case CRAZYCRYPT1: - case DOUBLEMD5: - case WORDPRESS: - case CUSTOM: - break; - default: - throw new NoSuchAlgorithmException("Unknown hash algorithm"); - } - PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName); - Bukkit.getPluginManager().callEvent(event); - method = event.getMethod(); - if (method == null) - throw new NoSuchAlgorithmException("Unknown hash algorithm"); - return method.getHash(password, salt, playerName); - } - - /** - * Method comparePasswordWithHash. - * - * @param password String - * @param hash String - * @param playerName String - * - * @return boolean * @throws NoSuchAlgorithmException - */ - public static boolean comparePasswordWithHash(String password, String hash, - String playerName) throws NoSuchAlgorithmException { - HashAlgorithm algorithm = Settings.getPasswordHash; - EncryptionMethod method; - try { - if (algorithm != HashAlgorithm.CUSTOM) - method = (EncryptionMethod) algorithm.getclasse().newInstance(); - else - method = null; - - PasswordEncryptionEvent event = new PasswordEncryptionEvent(method, playerName); - Bukkit.getPluginManager().callEvent(event); - method = event.getMethod(); - - if (method == null) - throw new NoSuchAlgorithmException("Unknown hash algorithm"); - - if (method.comparePassword(hash, password, playerName)) - return true; - - if (Settings.supportOldPassword) { - if (compareWithAllEncryptionMethod(password, hash, playerName)) - return true; - } - } catch (InstantiationException | IllegalAccessException e) { - throw new NoSuchAlgorithmException("Problem with this hash algorithm"); - } - return false; - } - - /** - * Method compareWithAllEncryptionMethod. - * - * @param password String - * @param hash String - * @param playerName String - * - * @return boolean * @throws NoSuchAlgorithmException - */ - private static boolean compareWithAllEncryptionMethod(String password, - String hash, String playerName) throws NoSuchAlgorithmException { - for (HashAlgorithm algo : HashAlgorithm.values()) { - if (algo != HashAlgorithm.CUSTOM) { - try { - EncryptionMethod method = (EncryptionMethod) algo.getclasse().newInstance(); - if (method.comparePassword(hash, password, playerName)) { - PlayerAuth nAuth = AuthMe.getInstance().database.getAuth(playerName); - if (nAuth != null) { - nAuth.setHash(getHash(Settings.getPasswordHash, password, playerName)); - nAuth.setSalt(userSalt.containsKey(playerName) ? userSalt.get(playerName) : ""); - AuthMe.getInstance().database.updatePassword(nAuth); - AuthMe.getInstance().database.updateSalt(nAuth); - } - return true; - } - } catch (Exception ignored) { - } - } - } - return false; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/pair.info deleted file mode 100755 index 4b6751c..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#41575/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:41575 -comSha:82bf0f45ca7637de9206205721da874c627e3eee -parentComSha:83e5d726af570d8d90e3baee4760656d88bea096 -BuggyFilePath:src/main/java/fr/xephi/authme/security/PasswordSecurity.java -FixedFilePath:src/main/java/fr/xephi/authme/security/PasswordSecurity.java -StartLineNum:21 -EndLineNum:21 -repoName:Xephi#AuthMeReloaded \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/comMsg.txt deleted file mode 100755 index 5aeee8d..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix some code warnings \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/diff.diff deleted file mode 100755 index 5307cfa..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/main/java/org/mapdb/HTreeMap.java b/src/main/java/org/mapdb/HTreeMap.java -index b6fb08d9..9c43db85 100644 ---- a/src/main/java/org/mapdb/HTreeMap.java -+++ b/src/main/java/org/mapdb/HTreeMap.java -@@ -844,3 +844,2 @@ public class HTreeMap extends AbstractMap implements ConcurrentMap it = iterator(); -- while (it.hasNext()) { -- result += hasher.hashCode(it.next()); -+ for (K k : this) { -+ result += hasher.hashCode(k); -@@ -893 +892 @@ public class HTreeMap extends AbstractMap implements ConcurrentMap> _entrySet = new AbstractSet>(){ -+ private final Set> _entrySet = new AbstractSet>(){ -@@ -1263 +1262 @@ public class HTreeMap extends AbstractMap implements ConcurrentMap - * This map uses full 32bit hash from beginning, There is no initial load factor and rehash. - * Technically it is not hash table, but hash tree with nodes expanding when they become full. - *

- * This map is suitable for number of records 1e9 and over. - * Larger number of records will increase hash collisions and performance - * will degrade linearly with number of records (separate chaining). - *

- * Concurrent scalability is achieved by splitting HashMap into 16 segments, each with separate lock. - * Very similar to ConcurrentHashMap - * - * @author Jan Kotek - */ -@SuppressWarnings({ "unchecked", "rawtypes" }) -public class HTreeMap extends AbstractMap implements ConcurrentMap, Bind.MapWithModificationListener { - - - protected static final int BUCKET_OVERFLOW = 4; - - protected static final int DIV8 = 3; - protected static final int MOD8 = 0x7; - - /** is this a Map or Set? if false, entries do not have values, only keys are allowed*/ - protected final boolean hasValues; - - /** - * Salt added to hash before rehashing, so it is harder to trigger hash collision attack. - */ - protected final int hashSalt; - - protected final Atomic.Long counter; - - protected final Serializer keySerializer; - protected final Serializer valueSerializer; - protected final Hasher hasher; - - protected final Engine engine; - - protected final boolean expireFlag; - protected final long expireTimeStart; - protected final long expire; - protected final boolean expireAccessFlag; - protected final long expireAccess; - protected final long expireMaxSize; - protected final long expireStoreSize; - protected final boolean expireMaxSizeFlag; - - protected final long[] expireHeads; - protected final long[] expireTails; - - protected final Fun.Function1 valueCreator; - - protected final CountDownLatch closeLatch = new CountDownLatch(2); - - protected final Runnable closeListener = new Runnable() { - @Override public void run() { - if(closeLatch.getCount()>1){ - closeLatch.countDown(); - } - - try { - closeLatch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - - - HTreeMap.this.engine.closeListenerUnregister(HTreeMap.this.closeListener); - } - }; - - - /** node which holds key-value pair */ - protected static final class LinkedNode{ - - public final long next; - public final long expireLinkNodeRecid; - - public final K key; - public final V value; - - public LinkedNode(final long next, long expireLinkNodeRecid, final K key, final V value ){ - this.key = key; - this.expireLinkNodeRecid = expireLinkNodeRecid; - this.value = value; - this.next = next; - } - } - - - - protected final Serializer> LN_SERIALIZER = new Serializer>() { - @Override - public void serialize(DataOutput out, LinkedNode value) throws IOException { - DataOutput2.packLong(out, value.next); - if(expireFlag) - DataOutput2.packLong(out, value.expireLinkNodeRecid); - keySerializer.serialize(out,value.key); - if(hasValues) - valueSerializer.serialize(out,value.value); - } - - @Override - public LinkedNode deserialize(DataInput in, int available) throws IOException { - assert(available!=0); - return new LinkedNode( - DataInput2.unpackLong(in), - expireFlag?DataInput2.unpackLong(in):0L, - keySerializer.deserialize(in,-1), - hasValues? valueSerializer.deserialize(in,-1) : (V) BTreeMap.EMPTY - ); - } - - @Override - public int fixedSize() { - return -1; - } - - }; - - - protected static final SerializerDIR_SERIALIZER = new Serializer() { - @Override - public void serialize(DataOutput out, long[][] value) throws IOException { - assert(value.length==16); - - //first write mask which indicate subarray nullability - int nulls = 0; - for(int i = 0;i<16;i++){ - if(value[i]!=null){ - for(long l:value[i]){ - if(l!=0){ - nulls |= 1<>>1; - } - - return ret; - } - - @Override - public int fixedSize() { - return -1; - } - - }; - - /** list of segments, this is immutable*/ - protected final long[] segmentRecids; - - protected final ReentrantReadWriteLock[] segmentLocks = new ReentrantReadWriteLock[16]; - { - for(int i=0;i< 16;i++) segmentLocks[i]=new ReentrantReadWriteLock(CC.FAIR_LOCKS); - } - - - - - /** - * Opens HTreeMap - */ - public HTreeMap(Engine engine, long counterRecid, int hashSalt, long[] segmentRecids, - Serializer keySerializer, Serializer valueSerializer, - long expireTimeStart, long expire, long expireAccess, long expireMaxSize, long expireStoreSize, - long[] expireHeads, long[] expireTails, Fun.Function1 valueCreator, - Hasher hasher, boolean disableLocks) { - if(counterRecid<0) throw new IllegalArgumentException(); - if(engine==null) throw new NullPointerException(); - if(segmentRecids==null) throw new NullPointerException(); - if(keySerializer==null) throw new NullPointerException(); - - SerializerBase.assertSerializable(keySerializer); - this.hasValues = valueSerializer!=null; - if(hasValues) { - SerializerBase.assertSerializable(valueSerializer); - } - - - if(segmentRecids.length!=16) throw new IllegalArgumentException(); - - this.engine = engine; - this.hashSalt = hashSalt; - this.segmentRecids = Arrays.copyOf(segmentRecids,16); - this.keySerializer = keySerializer; - this.valueSerializer = valueSerializer; - this.hasher = hasher!=null ? hasher : Hasher.BASIC; - if(expire==0 && expireAccess!=0){ - expire = expireAccess; - } - if(expireMaxSize!=0 && counterRecid==0){ - throw new IllegalArgumentException("expireMaxSize must have counter enabled"); - } - - - this.expireFlag = expire !=0L || expireAccess!=0L || expireMaxSize!=0 || expireStoreSize!=0; - this.expire = expire; - this.expireTimeStart = expireTimeStart; - this.expireAccessFlag = expireAccess !=0L || expireMaxSize!=0 || expireStoreSize!=0; - this.expireAccess = expireAccess; - this.expireHeads = expireHeads==null? null : Arrays.copyOf(expireHeads,16); - this.expireTails = expireTails==null? null : Arrays.copyOf(expireTails,16); - this.expireMaxSizeFlag = expireMaxSize!=0; - this.expireMaxSize = expireMaxSize; - this.expireStoreSize = expireStoreSize; - this.valueCreator = valueCreator; - - if(counterRecid!=0){ - this.counter = new Atomic.Long(engine,counterRecid); - Bind.size(this,counter); - }else{ - this.counter = null; - } - - if(expireFlag){ - Thread t = new Thread(new ExpireRunnable(this),"HTreeMap expirator"); - t.setDaemon(true); - t.start(); - - engine.closeListenerRegister(closeListener); - } - - } - - - - protected static long[] preallocateSegments(Engine engine){ - //prealocate segmentRecids, so we dont have to lock on those latter - long[] ret = new long[16]; - for(int i=0;i<16;i++) - ret[i] = engine.put(new long[16][], DIR_SERIALIZER); - return ret; - } - - - - @Override - public boolean containsKey(final Object o){ - return getPeek(o)!=null; - } - - @Override - public int size() { - long size = sizeLong(); - if(size>Integer.MAX_VALUE) return Integer.MAX_VALUE; - return (int) size; - } - - - @Override - public long sizeLong() { - if(counter!=null) - return counter.get(); - - - long counter = 0; - - //search tree, until we find first non null - for(int i=0;i<16;i++){ - try{ - segmentLocks[i].readLock().lock(); - - final long dirRecid = segmentRecids[i]; - counter+=recursiveDirCount(dirRecid); - }finally { - segmentLocks[i].readLock().unlock(); - } - } - - - return counter; - } - - private long recursiveDirCount(final long dirRecid) { - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - long counter = 0; - for(long[] subdir:dir){ - if(subdir == null) continue; - for(long recid:subdir){ - if(recid == 0) continue; - if((recid&1)==0){ - //reference to another subdir - recid = recid>>>1; - counter += recursiveDirCount(recid); - }else{ - //reference to linked list, count it - recid = recid>>>1; - while(recid!=0){ - LinkedNode n = engine.get(recid, LN_SERIALIZER); - if(n!=null){ - counter++; - recid = n.next; - }else{ - recid = 0; - } - } - } - } - } - return counter; - } - - @Override - public boolean isEmpty() { - //search tree, until we find first non null - for(int i=0;i<16;i++){ - try{ - segmentLocks[i].readLock().lock(); - - long dirRecid = segmentRecids[i]; - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - for(long[] d:dir){ - if(d!=null) return false; - } - - }finally { - segmentLocks[i].readLock().unlock(); - } - } - - return true; - } - - - - @Override - public V get(final Object o){ - if(o==null) return null; - final int h = hash(o); - final int segment = h >>>28; - - final Lock lock = expireAccessFlag ? segmentLocks[segment].writeLock() : segmentLocks[segment].readLock(); - lock.lock(); - LinkedNode ln; - try{ - ln = getInner(o, h, segment); - if(ln==null) return null; - if(expireAccessFlag) expireLinkBump(segment,ln.expireLinkNodeRecid,true); - }finally { - lock.unlock(); - } - if(valueCreator==null|| ln.value!=null) return ln.value; - - V value = valueCreator.run((K) o); - V prevVal = putIfAbsent((K) o,value); - if(prevVal!=null) return prevVal; - return value; - } - - - /** - * Return given value, without updating cache statistics if `expireAccess()` is true - * It also does not use `valueCreator` if value is not found (always returns null if not found) - * - * @param key key to lookup - * @return value associated with key or null - */ - public V getPeek(final Object key){ - if(key==null) return null; - final int h = hash(key); - final int segment = h >>>28; - - final Lock lock = segmentLocks[segment].readLock(); - lock.lock(); - - try{ - LinkedNode ln = getInner(key, h, segment); - if(ln==null) return null; - return ln.value; - }finally { - lock.unlock(); - } - - } - - protected LinkedNode getInner(Object o, int h, int segment) { - long recid = segmentRecids[segment]; - for(int level=3;level>=0;level--){ - long[][] dir = engine.get(recid, DIR_SERIALIZER); - if(dir == null) return null; - int slot = (h>>>(level*7 )) & 0x7F; - assert(slot<128); - if(dir[slot>>>DIV8]==null) return null; - recid = dir[slot>>>DIV8][slot&MOD8]; - if(recid == 0) return null; - if((recid&1)!=0){ //last bite indicates if referenced record is LinkedNode - recid = recid>>>1; - while(true){ - LinkedNode ln = engine.get(recid, LN_SERIALIZER); - if(ln == null) return null; - if(hasher.equals(ln.key, (K) o)){ - assert(hash(ln.key)==h); - return ln; - } - if(ln.next==0) return null; - recid = ln.next; - } - } - - recid = recid>>>1; - } - - return null; - } - - @Override - public V put(final K key, final V value){ - if (key == null) - throw new IllegalArgumentException("null key"); - - if (value == null) - throw new IllegalArgumentException("null value"); - - final int h = hash(key); - final int segment = h >>>28; - segmentLocks[segment].writeLock().lock(); - try{ - - return putInner(key, value, h, segment); - - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - private V putInner(K key, V value, int h, int segment) { - long dirRecid = segmentRecids[segment]; - - int level = 3; - while(true){ - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - final int slot = (h>>>(7*level )) & 0x7F; - assert(slot<=127); - - if(dir == null ){ - //create new dir - dir = new long[16][]; - } - - if(dir[slot>>>DIV8] == null){ - dir = Arrays.copyOf(dir, 16); - dir[slot>>>DIV8] = new long[8]; - } - - int counter = 0; - long recid = dir[slot>>>DIV8][slot&MOD8]; - - if(recid!=0){ - if((recid&1) == 0){ - dirRecid = recid>>>1; - level--; - continue; - } - recid = recid>>>1; - - //traverse linked list, try to replace previous value - LinkedNode ln = engine.get(recid, LN_SERIALIZER); - - while(ln!=null){ - if(hasher.equals(ln.key,key)){ - //found, replace value at this node - V oldVal = ln.value; - ln = new LinkedNode(ln.next, ln.expireLinkNodeRecid, ln.key, value); - engine.update(recid, ln, LN_SERIALIZER); - if(expireFlag) expireLinkBump(segment,ln.expireLinkNodeRecid,false); - notify(key, oldVal, value); - return oldVal; - } - recid = ln.next; - ln = recid==0? null : engine.get(recid, LN_SERIALIZER); - counter++; - } - //key was not found at linked list, so just append it to beginning - } - - - //check if linked list has overflow and needs to be expanded to new dir level - if(counter>=BUCKET_OVERFLOW && level>=1){ - long[][] nextDir = new long[16][]; - - { - final long expireNodeRecid = expireFlag? engine.preallocate():0L; - final LinkedNode node = new LinkedNode(0, expireNodeRecid, key, value); - final long newRecid = engine.put(node, LN_SERIALIZER); - //add newly inserted record - int pos =(h >>>(7*(level-1) )) & 0x7F; - nextDir[pos>>>DIV8] = new long[8]; - nextDir[pos>>>DIV8][pos&MOD8] = ( newRecid<<1) | 1; - if(expireFlag) expireLinkAdd(segment,expireNodeRecid,newRecid,h); - } - - - //redistribute linked bucket into new dir - long nodeRecid = dir[slot>>>DIV8][slot&MOD8]>>>1; - while(nodeRecid!=0){ - LinkedNode n = engine.get(nodeRecid, LN_SERIALIZER); - final long nextRecid = n.next; - int pos = (hash(n.key) >>>(7*(level -1) )) & 0x7F; - if(nextDir[pos>>>DIV8]==null) nextDir[pos>>>DIV8] = new long[8]; - n = new LinkedNode(nextDir[pos>>>DIV8][pos&MOD8]>>>1, n.expireLinkNodeRecid, n.key, n.value); - nextDir[pos>>>DIV8][pos&MOD8] = (nodeRecid<<1) | 1; - engine.update(nodeRecid, n, LN_SERIALIZER); - nodeRecid = nextRecid; - } - - //insert nextDir and update parent dir - long nextDirRecid = engine.put(nextDir, DIR_SERIALIZER); - int parentPos = (h>>>(7*level )) & 0x7F; - dir = Arrays.copyOf(dir,16); - dir[parentPos>>>DIV8] = Arrays.copyOf(dir[parentPos>>>DIV8],8); - dir[parentPos>>>DIV8][parentPos&MOD8] = (nextDirRecid<<1) | 0; - engine.update(dirRecid, dir, DIR_SERIALIZER); - notify(key, null, value); - return null; - }else{ - // record does not exist in linked list, so create new one - recid = dir[slot>>>DIV8][slot&MOD8]>>>1; - final long expireNodeRecid = expireFlag? engine.put(ExpireLinkNode.EMPTY, ExpireLinkNode.SERIALIZER):0L; - - final long newRecid = engine.put(new LinkedNode(recid, expireNodeRecid, key, value), LN_SERIALIZER); - dir = Arrays.copyOf(dir,16); - dir[slot>>>DIV8] = Arrays.copyOf(dir[slot>>>DIV8],8); - dir[slot>>>DIV8][slot&MOD8] = (newRecid<<1) | 1; - engine.update(dirRecid, dir, DIR_SERIALIZER); - if(expireFlag) expireLinkAdd(segment,expireNodeRecid, newRecid,h); - notify(key, null, value); - return null; - } - } - } - - - @Override - public V remove(Object key){ - - final int h = hash(key); - final int segment = h >>>28; - segmentLocks[segment].writeLock().lock(); - try{ - return removeInternal(key, segment, h, true); - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - - protected V removeInternal(Object key, int segment, int h, boolean removeExpire){ - final long[] dirRecids = new long[4]; - int level = 3; - dirRecids[level] = segmentRecids[segment]; - - assert(segment==h>>>28); - - while(true){ - long[][] dir = engine.get(dirRecids[level], DIR_SERIALIZER); - final int slot = (h>>>(7*level )) & 0x7F; - assert(slot<=127); - - if(dir == null ){ - //create new dir - dir = new long[16][]; - } - - if(dir[slot>>>DIV8] == null){ - dir = Arrays.copyOf(dir,16); - dir[slot>>>DIV8] = new long[8]; - } - -// int counter = 0; - long recid = dir[slot>>>DIV8][slot&MOD8]; - - if(recid!=0){ - if((recid&1) == 0){ - level--; - dirRecids[level] = recid>>>1; - continue; - } - recid = recid>>>1; - - //traverse linked list, try to remove node - LinkedNode ln = engine.get(recid, LN_SERIALIZER); - LinkedNode prevLn = null; - long prevRecid = 0; - while(ln!=null){ - if(hasher.equals(ln.key, (K) key)){ - //remove from linkedList - if(prevLn == null ){ - //referenced directly from dir - if(ln.next==0){ - recursiveDirDelete(h, level, dirRecids, dir, slot); - - - }else{ - dir=Arrays.copyOf(dir,16); - dir[slot>>>DIV8] = Arrays.copyOf(dir[slot>>>DIV8],8); - dir[slot>>>DIV8][slot&MOD8] = (ln.next<<1)|1; - engine.update(dirRecids[level], dir, DIR_SERIALIZER); - } - - }else{ - //referenced from LinkedNode - prevLn = new LinkedNode(ln.next, prevLn.expireLinkNodeRecid,prevLn.key, prevLn.value); - engine.update(prevRecid, prevLn, LN_SERIALIZER); - } - //found, remove this node - assert(hash(ln.key)==h); - engine.delete(recid, LN_SERIALIZER); - if(removeExpire && expireFlag) expireLinkRemove(segment, ln.expireLinkNodeRecid); - notify((K) key, ln.value, null); - return ln.value; - } - prevRecid = recid; - prevLn = ln; - recid = ln.next; - ln = recid==0? null : engine.get(recid, LN_SERIALIZER); -// counter++; - } - //key was not found at linked list, so it does not exist - return null; - } - //recid is 0, so entry does not exist - return null; - - } - } - - - private void recursiveDirDelete(int h, int level, long[] dirRecids, long[][] dir, int slot) { - //was only item in linked list, so try to collapse the dir - dir=Arrays.copyOf(dir,16); - dir[slot>>>DIV8] = Arrays.copyOf(dir[slot>>>DIV8],8); - dir[slot>>>DIV8][slot&MOD8] = 0; - //one record was zeroed out, check if subarray can be collapsed to null - boolean allZero = true; - for(long l:dir[slot>>>DIV8]){ - if(l!=0){ - allZero = false; - break; - } - } - if(allZero){ - dir[slot>>>DIV8] = null; - } - allZero = true; - for(long[] l:dir){ - if(l!=null){ - allZero = false; - break; - } - } - - if(allZero){ - //delete from parent dir - if(level==3){ - //parent is segment, recid of this dir can not be modified, so just update to null - engine.update(dirRecids[level], new long[16][], DIR_SERIALIZER); - }else{ - engine.delete(dirRecids[level], DIR_SERIALIZER); - - final long[][] parentDir = engine.get(dirRecids[level + 1], DIR_SERIALIZER); - final int parentPos = (h >>> (7 * (level + 1))) & 0x7F; - recursiveDirDelete(h,level+1,dirRecids, parentDir, parentPos); - //parentDir[parentPos>>>DIV8][parentPos&MOD8] = 0; - //engine.update(dirRecids[level + 1],parentDir,DIR_SERIALIZER); - - } - }else{ - engine.update(dirRecids[level], dir, DIR_SERIALIZER); - } - } - - @Override - public void clear() { - for(int i = 0; i<16;i++) try{ - segmentLocks[i].writeLock().lock(); - - final long dirRecid = segmentRecids[i]; - recursiveDirClear(dirRecid); - - //set dir to null, as segment recid is immutable - engine.update(dirRecid, new long[16][], DIR_SERIALIZER); - - if(expireFlag) - while(expireLinkRemoveLast(i)!=null){} //TODO speedup remove all - - }finally { - segmentLocks[i].writeLock().unlock(); - } - } - - private void recursiveDirClear(final long dirRecid) { - final long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - if(dir == null) return; - for(long[] subdir:dir){ - if(subdir==null) continue; - for(long recid:subdir){ - if(recid == 0) continue; - if((recid&1)==0){ - //another dir - recid = recid>>>1; - //recursively remove dir - recursiveDirClear(recid); - engine.delete(recid, DIR_SERIALIZER); - }else{ - //linked list to delete - recid = recid>>>1; - while(recid!=0){ - LinkedNode n = engine.get(recid, LN_SERIALIZER); - engine.delete(recid,LN_SERIALIZER); - notify((K)n.key, (V)n.value , null); - recid = n.next; - } - } - - } - } - } - - - @Override - public boolean containsValue(Object value) { - for (V v : values()) { - if (v.equals(value)) return true; - } - return false; - } - - - - protected class KeySet extends AbstractSet { - - @Override - public int size() { - return HTreeMap.this.size(); - } - - @Override - public boolean isEmpty() { - return HTreeMap.this.isEmpty(); - } - - @Override - public boolean contains(Object o) { - return HTreeMap.this.containsKey(o); - } - - @Override - public Iterator iterator() { - return new KeyIterator(); - } - - @Override - public boolean add(K k) { - if(HTreeMap.this.hasValues) - throw new UnsupportedOperationException(); - else - return HTreeMap.this.put(k, (V) BTreeMap.EMPTY) == null; - } - - @Override - public boolean remove(Object o) { -// if(o instanceof Entry){ -// Entry e = (Entry) o; -// return HTreeMap.this.remove(((Entry) o).getKey(),((Entry) o).getValue()); -// } - return HTreeMap.this.remove(o)!=null; - - } - - - @Override - public void clear() { - HTreeMap.this.clear(); - } - - public HTreeMap parent(){ - return HTreeMap.this; - } - - @Override - public int hashCode() { - int result = 0; - for (K k : this) { - result += hasher.hashCode(k); - } - return result; - - } - } - - - - private final Set _keySet = new KeySet(); - - @Override - public Set keySet() { - return _keySet; - } - - private final Collection _values = new AbstractCollection(){ - - @Override - public int size() { - return HTreeMap.this.size(); - } - - @Override - public boolean isEmpty() { - return HTreeMap.this.isEmpty(); - } - - @Override - public boolean contains(Object o) { - return HTreeMap.this.containsValue(o); - } - - - - @Override - public Iterator iterator() { - return new ValueIterator(); - } - - }; - - @Override - public Collection values() { - return _values; - } - - private final Set> _entrySet = new AbstractSet>(){ - - @Override - public int size() { - return HTreeMap.this.size(); - } - - @Override - public boolean isEmpty() { - return HTreeMap.this.isEmpty(); - } - - @Override - public boolean contains(Object o) { - if(o instanceof Entry){ - Entry e = (Entry) o; - Object val = HTreeMap.this.get(e.getKey()); - return val!=null && val.equals(e.getValue()); - }else - return false; - } - - @Override - public Iterator> iterator() { - return new EntryIterator(); - } - - - @Override - public boolean add(Entry kvEntry) { - K key = kvEntry.getKey(); - V value = kvEntry.getValue(); - if(key==null || value == null) throw new NullPointerException(); - HTreeMap.this.put(key, value); - return true; - } - - @Override - public boolean remove(Object o) { - if(o instanceof Entry){ - Entry e = (Entry) o; - Object key = e.getKey(); - if(key == null) return false; - return HTreeMap.this.remove(key, e.getValue()); - } - return false; - } - - - @Override - public void clear() { - HTreeMap.this.clear(); - } - }; - - @Override - public Set> entrySet() { - return _entrySet; - } - - - protected int hash(final Object key) { - int h = hasher.hashCode((K) key) ^ hashSalt; - h ^= (h >>> 20) ^ (h >>> 12); - return h ^ (h >>> 7) ^ (h >>> 4); - } - - - abstract class HashIterator{ - - protected LinkedNode[] currentLinkedList; - protected int currentLinkedListPos = 0; - - private K lastReturnedKey = null; - - private int lastSegment = 0; - - HashIterator(){ - currentLinkedList = findNextLinkedNode(0); - } - - public void remove() { - final K keyToRemove = lastReturnedKey; - if (lastReturnedKey == null) - throw new IllegalStateException(); - - lastReturnedKey = null; - HTreeMap.this.remove(keyToRemove); - } - - public boolean hasNext(){ - return currentLinkedList!=null && currentLinkedListPos>>28; - - //two phases, first find old item and increase hash - try{ - segmentLocks[segment].readLock().lock(); - - long dirRecid = segmentRecids[segment]; - int level = 3; - //dive into tree, finding last hash position - while(true){ - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - int pos = (lastHash>>>(7 * level)) & 0x7F; - - //check if we need to expand deeper - if(dir[pos>>>DIV8]==null || dir[pos>>>DIV8][pos&MOD8]==0 || (dir[pos>>>DIV8][pos&MOD8]&1)==1) { - //increase hash by 1 - if(level!=0){ - lastHash = ((lastHash>>>(7 * level)) + 1) << (7*level); //should use mask and XOR - }else - lastHash +=1; - if(lastHash==0){ - return null; - } - break; - } - - //reference is dir, move to next level - dirRecid = dir[pos>>>DIV8][pos&MOD8]>>>1; - level--; - } - - }finally { - segmentLocks[segment].readLock().unlock(); - } - return findNextLinkedNode(lastHash); - - - } - - private LinkedNode[] findNextLinkedNode(int hash) { - //second phase, start search from increased hash to find next items - for(int segment = Math.max(hash >>>28, lastSegment); segment<16;segment++){ - final Lock lock = expireAccessFlag ? segmentLocks[segment].writeLock() :segmentLocks[segment].readLock() ; - lock.lock(); - try{ - lastSegment = Math.max(segment,lastSegment); - long dirRecid = segmentRecids[segment]; - LinkedNode ret[] = findNextLinkedNodeRecur(dirRecid, hash, 3); - if(ret!=null) for(LinkedNode ln:ret){ - assert hash(ln.key)>>>28==segment; - } - //System.out.println(Arrays.asList(ret)); - if(ret !=null){ - if(expireAccessFlag){ - for(LinkedNode ln:ret) expireLinkBump(segment,ln.expireLinkNodeRecid,true); - } - return ret; - } - hash = 0; - }finally { - lock.unlock(); - } - } - - return null; - } - - private LinkedNode[] findNextLinkedNodeRecur(long dirRecid, int newHash, int level){ - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - if(dir == null) return null; - int pos = (newHash>>>(level*7)) & 0x7F; - boolean first = true; - while(pos<128){ - if(dir[pos>>>DIV8]!=null){ - long recid = dir[pos>>>DIV8][pos&MOD8]; - if(recid!=0){ - if((recid&1) == 1){ - recid = recid>>1; - //found linked list, load it into array and return - LinkedNode[] array = new LinkedNode[1]; - int arrayPos = 0; - while(recid!=0){ - LinkedNode ln = engine.get(recid, LN_SERIALIZER); - if(ln==null){ - recid = 0; - continue; - } - //increase array size if needed - if(arrayPos == array.length) - array = Arrays.copyOf(array, array.length+1); - array[arrayPos++] = ln; - recid = ln.next; - } - return array; - }else{ - //found another dir, continue dive - recid = recid>>1; - LinkedNode[] ret = findNextLinkedNodeRecur(recid, first ? newHash : 0, level - 1); - if(ret != null) return ret; - } - } - } - first = false; - pos++; - } - return null; - } - } - - class KeyIterator extends HashIterator implements Iterator{ - - @Override - public K next() { - if(currentLinkedList == null) - throw new NoSuchElementException(); - K key = (K) currentLinkedList[currentLinkedListPos].key; - moveToNext(); - return key; - } - } - - class ValueIterator extends HashIterator implements Iterator{ - - @Override - public V next() { - if(currentLinkedList == null) - throw new NoSuchElementException(); - V value = (V) currentLinkedList[currentLinkedListPos].value; - moveToNext(); - return value; - } - } - - class EntryIterator extends HashIterator implements Iterator>{ - - @Override - public Entry next() { - if(currentLinkedList == null) - throw new NoSuchElementException(); - K key = (K) currentLinkedList[currentLinkedListPos].key; - moveToNext(); - return new Entry2(key); - } - } - - class Entry2 implements Entry{ - - private final K key; - - Entry2(K key) { - this.key = key; - } - - @Override - public K getKey() { - return key; - } - - @Override - public V getValue() { - return HTreeMap.this.get(key); - } - - @Override - public V setValue(V value) { - return HTreeMap.this.put(key,value); - } - - @Override - public boolean equals(Object o) { - return (o instanceof Entry) && hasher.equals(key, (K) ((Entry) o).getKey()); - } - - @Override - public int hashCode() { - final V value = HTreeMap.this.get(key); - return (key == null ? 0 : hasher.hashCode(key)) ^ - (value == null ? 0 : value.hashCode()); - } - } - - - @Override - public V putIfAbsent(K key, V value) { - if(key==null||value==null) throw new NullPointerException(); - - final int h = HTreeMap.this.hash(key); - final int segment = h >>>28; - try{ - segmentLocks[segment].writeLock().lock(); - - LinkedNode ln = HTreeMap.this.getInner(key,h,segment); - if (ln==null) - return put(key, value); - else - return ln.value; - - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - @Override - public boolean remove(Object key, Object value) { - if(key==null||value==null) throw new NullPointerException(); - final int h = HTreeMap.this.hash(key); - final int segment = h >>>28; - try{ - segmentLocks[segment].writeLock().lock(); - - LinkedNode otherVal = getInner(key, h, segment); - if (otherVal!=null && otherVal.value.equals(value)) { - removeInternal(key, segment, h, true); - return true; - }else - return false; - - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - @Override - public boolean replace(K key, V oldValue, V newValue) { - if(key==null||oldValue==null||newValue==null) throw new NullPointerException(); - final int h = HTreeMap.this.hash(key); - final int segment = h >>>28; - try{ - segmentLocks[segment].writeLock().lock(); - - LinkedNode ln = getInner(key, h,segment); - if (ln!=null && ln.value.equals(oldValue)) { - putInner(key, newValue,h,segment); - return true; - } else - return false; - - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - @Override - public V replace(K key, V value) { - if(key==null||value==null) throw new NullPointerException(); - final int h = HTreeMap.this.hash(key); - final int segment = h >>>28; - try{ - segmentLocks[segment].writeLock().lock(); - - if (getInner(key,h,segment)!=null) - return putInner(key, value,h,segment); - else - return null; - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - - - protected static final class ExpireLinkNode{ - - public final static ExpireLinkNode EMPTY = new ExpireLinkNode(0,0,0,0,0); - - public static final Serializer SERIALIZER = new Serializer() { - @Override - public void serialize(DataOutput out, ExpireLinkNode value) throws IOException { - if(value == EMPTY) return; - DataOutput2.packLong(out,value.prev); - DataOutput2.packLong(out,value.next); - DataOutput2.packLong(out,value.keyRecid); - DataOutput2.packLong(out,value.time); - out.writeInt(value.hash); - } - - @Override - public ExpireLinkNode deserialize(DataInput in, int available) throws IOException { - if(available==0) return EMPTY; - return new ExpireLinkNode( - DataInput2.unpackLong(in),DataInput2.unpackLong(in),DataInput2.unpackLong(in),DataInput2.unpackLong(in), - in.readInt() - ); - } - - @Override - public int fixedSize() { - return -1; - } - - }; - - public final long prev; - public final long next; - public final long keyRecid; - public final long time; - public final int hash; - - public ExpireLinkNode(long prev, long next, long keyRecid, long time, int hash) { - this.prev = prev; - this.next = next; - this.keyRecid = keyRecid; - this.time = time; - this.hash = hash; - } - - public ExpireLinkNode copyNext(long next2) { - return new ExpireLinkNode(prev,next2, keyRecid,time,hash); - } - - public ExpireLinkNode copyPrev(long prev2) { - return new ExpireLinkNode(prev2,next, keyRecid,time,hash); - } - - public ExpireLinkNode copyTime(long time2) { - return new ExpireLinkNode(prev,next,keyRecid,time2,hash); - } - - } - - - - protected void expireLinkAdd(int segment, long expireNodeRecid, long keyRecid, int hash){ - assert(segmentLocks[segment].writeLock().isHeldByCurrentThread()); - assert(expireNodeRecid>0); - assert(keyRecid>0); - - long time = expire==0 ? 0: expire+System.currentTimeMillis()-expireTimeStart; - long head = engine.get(expireHeads[segment],Serializer.LONG); - if(head == 0){ - //insert new - ExpireLinkNode n = new ExpireLinkNode(0,0,keyRecid,time,hash); - engine.update(expireNodeRecid, n, ExpireLinkNode.SERIALIZER); - engine.update(expireHeads[segment],expireNodeRecid,Serializer.LONG); - engine.update(expireTails[segment],expireNodeRecid,Serializer.LONG); - }else{ - //insert new head - ExpireLinkNode n = new ExpireLinkNode(head,0,keyRecid,time,hash); - engine.update(expireNodeRecid, n, ExpireLinkNode.SERIALIZER); - - //update old head to have new head as next - ExpireLinkNode oldHead = engine.get(head,ExpireLinkNode.SERIALIZER); - oldHead=oldHead.copyNext(expireNodeRecid); - engine.update(head,oldHead,ExpireLinkNode.SERIALIZER); - - //and update head - engine.update(expireHeads[segment],expireNodeRecid,Serializer.LONG); - } - } - - protected void expireLinkBump(int segment, long nodeRecid, boolean access){ - assert(segmentLocks[segment].writeLock().isHeldByCurrentThread()); - - ExpireLinkNode n = engine.get(nodeRecid,ExpireLinkNode.SERIALIZER); - long newTime = - access? - (expireAccess==0?0 : expireAccess+System.currentTimeMillis()-expireTimeStart): - (expire==0?0 : expire+System.currentTimeMillis()-expireTimeStart); - - //TODO optimize bellow, but what if there is only size limit? - //if(n.time>newTime) return; // older time greater than new one, do not update - - if(n.next==0){ - //already head, so just update time - n = n.copyTime(newTime); - engine.update(nodeRecid,n,ExpireLinkNode.SERIALIZER); - }else{ - //update prev so it points to next - if(n.prev!=0){ - //not a tail - ExpireLinkNode prev = engine.get(n.prev,ExpireLinkNode.SERIALIZER); - prev=prev.copyNext(n.next); - engine.update(n.prev, prev, ExpireLinkNode.SERIALIZER); - }else{ - //yes tail, so just update it to point to next - engine.update(expireTails[segment],n.next,Serializer.LONG); - } - - //update next so it points to prev - ExpireLinkNode next = engine.get(n.next, ExpireLinkNode.SERIALIZER); - next=next.copyPrev(n.prev); - engine.update(n.next,next,ExpireLinkNode.SERIALIZER); - - //TODO optimize if oldHead==next - - //now insert node as new head - long oldHeadRecid = engine.get(expireHeads[segment],Serializer.LONG); - ExpireLinkNode oldHead = engine.get(oldHeadRecid, ExpireLinkNode.SERIALIZER); - oldHead = oldHead.copyNext(nodeRecid); - engine.update(oldHeadRecid,oldHead,ExpireLinkNode.SERIALIZER); - engine.update(expireHeads[segment],nodeRecid,Serializer.LONG); - - n = new ExpireLinkNode(oldHeadRecid,0, n.keyRecid, newTime, n.hash); - engine.update(nodeRecid,n,ExpireLinkNode.SERIALIZER); - } - } - - protected ExpireLinkNode expireLinkRemoveLast(int segment){ - assert(segmentLocks[segment].writeLock().isHeldByCurrentThread()); - - long tail = engine.get(expireTails[segment],Serializer.LONG); - if(tail==0) return null; - - ExpireLinkNode n = engine.get(tail,ExpireLinkNode.SERIALIZER); - if(n.next==0){ - //update tail and head - engine.update(expireHeads[segment],0L,Serializer.LONG); - engine.update(expireTails[segment],0L,Serializer.LONG); - }else{ - //point tail to next record - engine.update(expireTails[segment],n.next,Serializer.LONG); - //update next record to have zero prev - ExpireLinkNode next = engine.get(n.next,ExpireLinkNode.SERIALIZER); - next=next.copyPrev(0L); - engine.update(n.next, next, ExpireLinkNode.SERIALIZER); - } - - engine.delete(tail,ExpireLinkNode.SERIALIZER); - return n; - } - - - protected ExpireLinkNode expireLinkRemove(int segment, long nodeRecid){ - assert(segmentLocks[segment].writeLock().isHeldByCurrentThread()); - - ExpireLinkNode n = engine.get(nodeRecid,ExpireLinkNode.SERIALIZER); - engine.delete(nodeRecid,ExpireLinkNode.SERIALIZER); - if(n.next == 0 && n.prev==0){ - engine.update(expireHeads[segment],0L,Serializer.LONG); - engine.update(expireTails[segment],0L,Serializer.LONG); - }else if (n.next == 0) { - ExpireLinkNode prev = engine.get(n.prev,ExpireLinkNode.SERIALIZER); - prev=prev.copyNext(0); - engine.update(n.prev,prev,ExpireLinkNode.SERIALIZER); - engine.update(expireHeads[segment],n.prev,Serializer.LONG); - }else if (n.prev == 0) { - ExpireLinkNode next = engine.get(n.next,ExpireLinkNode.SERIALIZER); - next=next.copyPrev(0); - engine.update(n.next,next,ExpireLinkNode.SERIALIZER); - engine.update(expireTails[segment],n.next,Serializer.LONG); - }else{ - ExpireLinkNode next = engine.get(n.next,ExpireLinkNode.SERIALIZER); - next=next.copyPrev(n.prev); - engine.update(n.next,next,ExpireLinkNode.SERIALIZER); - - ExpireLinkNode prev = engine.get(n.prev,ExpireLinkNode.SERIALIZER); - prev=prev.copyNext(n.next); - engine.update(n.prev,prev,ExpireLinkNode.SERIALIZER); - } - - return n; - } - - /** - * Returns maximal (newest) expiration timestamp - */ - public long getMaxExpireTime(){ - if(!expireFlag) return 0; - long ret = 0; - for(int segment = 0;segment<16;segment++){ - segmentLocks[segment].readLock().lock(); - try{ - long head = engine.get(expireHeads[segment],Serializer.LONG); - if(head == 0) continue; - ExpireLinkNode ln = engine.get(head, ExpireLinkNode.SERIALIZER); - if(ln==null || ln.time==0) continue; - ret = Math.max(ret, ln.time+expireTimeStart); - }finally{ - segmentLocks[segment].readLock().unlock(); - } - } - return ret; - } - - /** - * Returns minimal (oldest) expiration timestamp - */ - public long getMinExpireTime(){ - if(!expireFlag) return 0; - long ret = Long.MAX_VALUE; - for(int segment = 0;segment<16;segment++){ - segmentLocks[segment].readLock().lock(); - try{ - long tail = engine.get(expireTails[segment],Serializer.LONG); - if(tail == 0) continue; - ExpireLinkNode ln = engine.get(tail, ExpireLinkNode.SERIALIZER); - if(ln==null || ln.time==0) continue; - ret = Math.min(ret, ln.time+expireTimeStart); - }finally{ - segmentLocks[segment].readLock().unlock(); - } - } - if(ret == Long.MAX_VALUE) ret =0; - return ret; - } - - protected static class ExpireRunnable implements Runnable{ - - //use weak referece to prevent memory leak - final WeakReference mapRef; - - public ExpireRunnable(HTreeMap map) { - this.mapRef = new WeakReference(map); - } - - @Override - public void run() { - boolean pause = false; - try { - while(true) { - - if (pause) { - Thread.sleep(1000); - } - - - HTreeMap map = mapRef.get(); - if (map == null || map.engine.isClosed() || map.closeLatch.getCount()<2) - return; - - //TODO what if store gets closed while working on this? - map.expirePurge(); - - if (map.engine.isClosed() || map.closeLatch.getCount()<2) - return; - - pause = ((!map.expireMaxSizeFlag || map.size() < map.expireMaxSize) - && (map.expireStoreSize == 0L || - Store.forEngine(map.engine).getCurrSize() - Store.forEngine(map.engine).getFreeSize() < map.expireStoreSize)); - - } - - }catch(Throwable e){ - //TODO exception handling - e.printStackTrace(); - //Utils.LOG.log(Level.SEVERE, "HTreeMap expirator failed", e); - }finally { - HTreeMap m = mapRef.get(); - if (m != null) - m.closeLatch.countDown(); - mapRef.clear(); - } - } - - } - - - protected void expirePurge(){ - if(!expireFlag) return; - - long removePerSegment = 0; - if(expireMaxSizeFlag){ - long size = counter.get(); - if(size>expireMaxSize){ - removePerSegment=1+(size-expireMaxSize)/16; - } - } - - - if(expireStoreSize!=0 && removePerSegment==0){ - Store store = Store.forEngine(engine); - if(expireStoreSize>>28 == seg); - - final boolean remove = ++counter < removePerSegment || - ((expire!=0 || expireAccess!=0) && n.time+expireTimeStart ln = engine.get(n.keyRecid,LN_SERIALIZER); - removeInternal(ln.key,seg, n.hash, false); - }else{ - break; - } - last=n; - recid=n.next; - } - // patch linked list - if(last ==null ){ - //no items removed - return; - }else if(recid == 0){ - //all items were taken, so zero items - engine.update(expireTails[seg],0L, Serializer.LONG); - engine.update(expireHeads[seg],0L, Serializer.LONG); - }else{ - //update tail to point to next item - engine.update(expireTails[seg],recid, Serializer.LONG); - //and update next item to point to tail - n = engine.get(recid, ExpireLinkNode.SERIALIZER); - n = n.copyPrev(0); - engine.update(recid,n,ExpireLinkNode.SERIALIZER); - } -// expireCheckSegment(seg); - }finally{ - segmentLocks[seg].writeLock().unlock(); - } - } - - - protected void expireCheckSegment(int segment){ - long current = engine.get(expireTails[segment],Serializer.LONG); - if(current==0){ - if(engine.get(expireHeads[segment],Serializer.LONG)!=0) - throw new AssertionError("head not 0"); - return; - } - - long prev = 0; - while(current!=0){ - ExpireLinkNode curr = engine.get(current,ExpireLinkNode.SERIALIZER); - assert(curr.prev==prev):"wrong prev "+curr.prev +" - "+prev; - prev= current; - current = curr.next; - } - if(engine.get(expireHeads[segment],Serializer.LONG)!=prev) - throw new AssertionError("wrong head"); - - } - - /** - * Make readonly snapshot view of current Map. Snapshot is immutable and not affected by modifications made by other threads. - * Useful if you need consistent view on Map. - *

- * Maintaining snapshot have some overhead, underlying Engine is closed after Map view is GCed. - * Please make sure to release reference to this Map view, so snapshot view can be garbage collected. - * - * @return snapshot - */ - public Map snapshot(){ - Engine snapshot = TxEngine.createSnapshotFor(engine); - return new HTreeMap(snapshot, counter==null?0:counter.recid, - hashSalt, segmentRecids, keySerializer, valueSerializer,0L,0L,0L,0L,0L,null,null, null, null, false); - } - - - protected final Object modListenersLock = new Object(); - protected Bind.MapListener[] modListeners = new Bind.MapListener[0]; - - @Override - public void addModificationListener(Bind.MapListener listener) { - synchronized (modListenersLock){ - Bind.MapListener[] modListeners2 = - Arrays.copyOf(modListeners,modListeners.length+1); - modListeners2[modListeners2.length-1] = listener; - modListeners = modListeners2; - } - - } - - @Override - public void removeModificationListener(Bind.MapListener listener) { - synchronized (modListenersLock){ - for(int i=0;i>>28].isWriteLockedByCurrentThread()); - Bind.MapListener[] modListeners2 = modListeners; - for(Bind.MapListener listener:modListeners2){ - if(listener!=null) - listener.update(key, oldValue, newValue); - } - } - - /** - * Closes underlying storage and releases all resources. - * Used mostly with temporary collections where engine is not accessible. - */ - public void close(){ - engine.close(); - } - - public Engine getEngine(){ - return engine; - } - -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/old/HTreeMap.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/old/HTreeMap.java deleted file mode 100755 index b6fb08d..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/old/HTreeMap.java +++ /dev/null @@ -1,1702 +0,0 @@ -/* - * Copyright (c) 2012 Jan Kotek - * - * 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.mapdb; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.lang.ref.WeakReference; -import java.util.*; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -/** - * Thread safe concurrent HashMap - *

- * This map uses full 32bit hash from beginning, There is no initial load factor and rehash. - * Technically it is not hash table, but hash tree with nodes expanding when they become full. - *

- * This map is suitable for number of records 1e9 and over. - * Larger number of records will increase hash collisions and performance - * will degrade linearly with number of records (separate chaining). - *

- * Concurrent scalability is achieved by splitting HashMap into 16 segments, each with separate lock. - * Very similar to ConcurrentHashMap - * - * @author Jan Kotek - */ -@SuppressWarnings({ "unchecked", "rawtypes" }) -public class HTreeMap extends AbstractMap implements ConcurrentMap, Bind.MapWithModificationListener { - - - protected static final int BUCKET_OVERFLOW = 4; - - protected static final int DIV8 = 3; - protected static final int MOD8 = 0x7; - - /** is this a Map or Set? if false, entries do not have values, only keys are allowed*/ - protected final boolean hasValues; - - /** - * Salt added to hash before rehashing, so it is harder to trigger hash collision attack. - */ - protected final int hashSalt; - - protected final Atomic.Long counter; - - protected final Serializer keySerializer; - protected final Serializer valueSerializer; - protected final Hasher hasher; - - protected final Engine engine; - - protected final boolean expireFlag; - protected final long expireTimeStart; - protected final long expire; - protected final boolean expireAccessFlag; - protected final long expireAccess; - protected final long expireMaxSize; - protected final long expireStoreSize; - protected final boolean expireMaxSizeFlag; - - protected final long[] expireHeads; - protected final long[] expireTails; - - protected final Fun.Function1 valueCreator; - - protected final CountDownLatch closeLatch = new CountDownLatch(2); - - protected final Runnable closeListener = new Runnable() { - @Override public void run() { - if(closeLatch.getCount()>1){ - closeLatch.countDown(); - } - - try { - closeLatch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - - - HTreeMap.this.engine.closeListenerUnregister(HTreeMap.this.closeListener); - } - }; - - - /** node which holds key-value pair */ - protected static final class LinkedNode{ - - public final long next; - public final long expireLinkNodeRecid; - - public final K key; - public final V value; - - public LinkedNode(final long next, long expireLinkNodeRecid, final K key, final V value ){ - this.key = key; - this.expireLinkNodeRecid = expireLinkNodeRecid; - this.value = value; - this.next = next; - } - } - - - - protected final Serializer> LN_SERIALIZER = new Serializer>() { - @Override - public void serialize(DataOutput out, LinkedNode value) throws IOException { - DataOutput2.packLong(out, value.next); - if(expireFlag) - DataOutput2.packLong(out, value.expireLinkNodeRecid); - keySerializer.serialize(out,value.key); - if(hasValues) - valueSerializer.serialize(out,value.value); - } - - @Override - public LinkedNode deserialize(DataInput in, int available) throws IOException { - assert(available!=0); - return new LinkedNode( - DataInput2.unpackLong(in), - expireFlag?DataInput2.unpackLong(in):0L, - keySerializer.deserialize(in,-1), - hasValues? valueSerializer.deserialize(in,-1) : (V) BTreeMap.EMPTY - ); - } - - @Override - public int fixedSize() { - return -1; - } - - }; - - - protected static final SerializerDIR_SERIALIZER = new Serializer() { - @Override - public void serialize(DataOutput out, long[][] value) throws IOException { - assert(value.length==16); - - //first write mask which indicate subarray nullability - int nulls = 0; - for(int i = 0;i<16;i++){ - if(value[i]!=null){ - for(long l:value[i]){ - if(l!=0){ - nulls |= 1<>>1; - } - - return ret; - } - - @Override - public int fixedSize() { - return -1; - } - - }; - - /** list of segments, this is immutable*/ - protected final long[] segmentRecids; - - protected final ReentrantReadWriteLock[] segmentLocks = new ReentrantReadWriteLock[16]; - { - for(int i=0;i< 16;i++) segmentLocks[i]=new ReentrantReadWriteLock(CC.FAIR_LOCKS); - } - - - - - /** - * Opens HTreeMap - */ - public HTreeMap(Engine engine, long counterRecid, int hashSalt, long[] segmentRecids, - Serializer keySerializer, Serializer valueSerializer, - long expireTimeStart, long expire, long expireAccess, long expireMaxSize, long expireStoreSize, - long[] expireHeads, long[] expireTails, Fun.Function1 valueCreator, - Hasher hasher, boolean disableLocks) { - if(counterRecid<0) throw new IllegalArgumentException(); - if(engine==null) throw new NullPointerException(); - if(segmentRecids==null) throw new NullPointerException(); - if(keySerializer==null) throw new NullPointerException(); - - SerializerBase.assertSerializable(keySerializer); - this.hasValues = valueSerializer!=null; - if(hasValues) { - SerializerBase.assertSerializable(valueSerializer); - } - - - if(segmentRecids.length!=16) throw new IllegalArgumentException(); - - this.engine = engine; - this.hashSalt = hashSalt; - this.segmentRecids = Arrays.copyOf(segmentRecids,16); - this.keySerializer = keySerializer; - this.valueSerializer = valueSerializer; - this.hasher = hasher!=null ? hasher : Hasher.BASIC; - if(expire==0 && expireAccess!=0){ - expire = expireAccess; - } - if(expireMaxSize!=0 && counterRecid==0){ - throw new IllegalArgumentException("expireMaxSize must have counter enabled"); - } - - - this.expireFlag = expire !=0L || expireAccess!=0L || expireMaxSize!=0 || expireStoreSize!=0; - this.expire = expire; - this.expireTimeStart = expireTimeStart; - this.expireAccessFlag = expireAccess !=0L || expireMaxSize!=0 || expireStoreSize!=0; - this.expireAccess = expireAccess; - this.expireHeads = expireHeads==null? null : Arrays.copyOf(expireHeads,16); - this.expireTails = expireTails==null? null : Arrays.copyOf(expireTails,16); - this.expireMaxSizeFlag = expireMaxSize!=0; - this.expireMaxSize = expireMaxSize; - this.expireStoreSize = expireStoreSize; - this.valueCreator = valueCreator; - - if(counterRecid!=0){ - this.counter = new Atomic.Long(engine,counterRecid); - Bind.size(this,counter); - }else{ - this.counter = null; - } - - if(expireFlag){ - Thread t = new Thread(new ExpireRunnable(this),"HTreeMap expirator"); - t.setDaemon(true); - t.start(); - - engine.closeListenerRegister(closeListener); - } - - } - - - - protected static long[] preallocateSegments(Engine engine){ - //prealocate segmentRecids, so we dont have to lock on those latter - long[] ret = new long[16]; - for(int i=0;i<16;i++) - ret[i] = engine.put(new long[16][], DIR_SERIALIZER); - return ret; - } - - - - @Override - public boolean containsKey(final Object o){ - return getPeek(o)!=null; - } - - @Override - public int size() { - long size = sizeLong(); - if(size>Integer.MAX_VALUE) return Integer.MAX_VALUE; - return (int) size; - } - - - @Override - public long sizeLong() { - if(counter!=null) - return counter.get(); - - - long counter = 0; - - //search tree, until we find first non null - for(int i=0;i<16;i++){ - try{ - segmentLocks[i].readLock().lock(); - - final long dirRecid = segmentRecids[i]; - counter+=recursiveDirCount(dirRecid); - }finally { - segmentLocks[i].readLock().unlock(); - } - } - - - return counter; - } - - private long recursiveDirCount(final long dirRecid) { - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - long counter = 0; - for(long[] subdir:dir){ - if(subdir == null) continue; - for(long recid:subdir){ - if(recid == 0) continue; - if((recid&1)==0){ - //reference to another subdir - recid = recid>>>1; - counter += recursiveDirCount(recid); - }else{ - //reference to linked list, count it - recid = recid>>>1; - while(recid!=0){ - LinkedNode n = engine.get(recid, LN_SERIALIZER); - if(n!=null){ - counter++; - recid = n.next; - }else{ - recid = 0; - } - } - } - } - } - return counter; - } - - @Override - public boolean isEmpty() { - //search tree, until we find first non null - for(int i=0;i<16;i++){ - try{ - segmentLocks[i].readLock().lock(); - - long dirRecid = segmentRecids[i]; - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - for(long[] d:dir){ - if(d!=null) return false; - } - - }finally { - segmentLocks[i].readLock().unlock(); - } - } - - return true; - } - - - - @Override - public V get(final Object o){ - if(o==null) return null; - final int h = hash(o); - final int segment = h >>>28; - - final Lock lock = expireAccessFlag ? segmentLocks[segment].writeLock() : segmentLocks[segment].readLock(); - lock.lock(); - LinkedNode ln; - try{ - ln = getInner(o, h, segment); - if(ln==null) return null; - if(expireAccessFlag) expireLinkBump(segment,ln.expireLinkNodeRecid,true); - }finally { - lock.unlock(); - } - if(valueCreator==null|| ln.value!=null) return ln.value; - - V value = valueCreator.run((K) o); - V prevVal = putIfAbsent((K) o,value); - if(prevVal!=null) return prevVal; - return value; - } - - - /** - * Return given value, without updating cache statistics if `expireAccess()` is true - * It also does not use `valueCreator` if value is not found (always returns null if not found) - * - * @param key key to lookup - * @return value associated with key or null - */ - public V getPeek(final Object key){ - if(key==null) return null; - final int h = hash(key); - final int segment = h >>>28; - - final Lock lock = segmentLocks[segment].readLock(); - lock.lock(); - - try{ - LinkedNode ln = getInner(key, h, segment); - if(ln==null) return null; - return ln.value; - }finally { - lock.unlock(); - } - - } - - protected LinkedNode getInner(Object o, int h, int segment) { - long recid = segmentRecids[segment]; - for(int level=3;level>=0;level--){ - long[][] dir = engine.get(recid, DIR_SERIALIZER); - if(dir == null) return null; - int slot = (h>>>(level*7 )) & 0x7F; - assert(slot<128); - if(dir[slot>>>DIV8]==null) return null; - recid = dir[slot>>>DIV8][slot&MOD8]; - if(recid == 0) return null; - if((recid&1)!=0){ //last bite indicates if referenced record is LinkedNode - recid = recid>>>1; - while(true){ - LinkedNode ln = engine.get(recid, LN_SERIALIZER); - if(ln == null) return null; - if(hasher.equals(ln.key, (K) o)){ - assert(hash(ln.key)==h); - return ln; - } - if(ln.next==0) return null; - recid = ln.next; - } - } - - recid = recid>>>1; - } - - return null; - } - - @Override - public V put(final K key, final V value){ - if (key == null) - throw new IllegalArgumentException("null key"); - - if (value == null) - throw new IllegalArgumentException("null value"); - - final int h = hash(key); - final int segment = h >>>28; - segmentLocks[segment].writeLock().lock(); - try{ - - return putInner(key, value, h, segment); - - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - private V putInner(K key, V value, int h, int segment) { - long dirRecid = segmentRecids[segment]; - - int level = 3; - while(true){ - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - final int slot = (h>>>(7*level )) & 0x7F; - assert(slot<=127); - - if(dir == null ){ - //create new dir - dir = new long[16][]; - } - - if(dir[slot>>>DIV8] == null){ - dir = Arrays.copyOf(dir, 16); - dir[slot>>>DIV8] = new long[8]; - } - - int counter = 0; - long recid = dir[slot>>>DIV8][slot&MOD8]; - - if(recid!=0){ - if((recid&1) == 0){ - dirRecid = recid>>>1; - level--; - continue; - } - recid = recid>>>1; - - //traverse linked list, try to replace previous value - LinkedNode ln = engine.get(recid, LN_SERIALIZER); - - while(ln!=null){ - if(hasher.equals(ln.key,key)){ - //found, replace value at this node - V oldVal = ln.value; - ln = new LinkedNode(ln.next, ln.expireLinkNodeRecid, ln.key, value); - engine.update(recid, ln, LN_SERIALIZER); - if(expireFlag) expireLinkBump(segment,ln.expireLinkNodeRecid,false); - notify(key, oldVal, value); - return oldVal; - } - recid = ln.next; - ln = recid==0? null : engine.get(recid, LN_SERIALIZER); - counter++; - } - //key was not found at linked list, so just append it to beginning - } - - - //check if linked list has overflow and needs to be expanded to new dir level - if(counter>=BUCKET_OVERFLOW && level>=1){ - long[][] nextDir = new long[16][]; - - { - final long expireNodeRecid = expireFlag? engine.preallocate():0L; - final LinkedNode node = new LinkedNode(0, expireNodeRecid, key, value); - final long newRecid = engine.put(node, LN_SERIALIZER); - //add newly inserted record - int pos =(h >>>(7*(level-1) )) & 0x7F; - nextDir[pos>>>DIV8] = new long[8]; - nextDir[pos>>>DIV8][pos&MOD8] = ( newRecid<<1) | 1; - if(expireFlag) expireLinkAdd(segment,expireNodeRecid,newRecid,h); - } - - - //redistribute linked bucket into new dir - long nodeRecid = dir[slot>>>DIV8][slot&MOD8]>>>1; - while(nodeRecid!=0){ - LinkedNode n = engine.get(nodeRecid, LN_SERIALIZER); - final long nextRecid = n.next; - int pos = (hash(n.key) >>>(7*(level -1) )) & 0x7F; - if(nextDir[pos>>>DIV8]==null) nextDir[pos>>>DIV8] = new long[8]; - n = new LinkedNode(nextDir[pos>>>DIV8][pos&MOD8]>>>1, n.expireLinkNodeRecid, n.key, n.value); - nextDir[pos>>>DIV8][pos&MOD8] = (nodeRecid<<1) | 1; - engine.update(nodeRecid, n, LN_SERIALIZER); - nodeRecid = nextRecid; - } - - //insert nextDir and update parent dir - long nextDirRecid = engine.put(nextDir, DIR_SERIALIZER); - int parentPos = (h>>>(7*level )) & 0x7F; - dir = Arrays.copyOf(dir,16); - dir[parentPos>>>DIV8] = Arrays.copyOf(dir[parentPos>>>DIV8],8); - dir[parentPos>>>DIV8][parentPos&MOD8] = (nextDirRecid<<1) | 0; - engine.update(dirRecid, dir, DIR_SERIALIZER); - notify(key, null, value); - return null; - }else{ - // record does not exist in linked list, so create new one - recid = dir[slot>>>DIV8][slot&MOD8]>>>1; - final long expireNodeRecid = expireFlag? engine.put(ExpireLinkNode.EMPTY, ExpireLinkNode.SERIALIZER):0L; - - final long newRecid = engine.put(new LinkedNode(recid, expireNodeRecid, key, value), LN_SERIALIZER); - dir = Arrays.copyOf(dir,16); - dir[slot>>>DIV8] = Arrays.copyOf(dir[slot>>>DIV8],8); - dir[slot>>>DIV8][slot&MOD8] = (newRecid<<1) | 1; - engine.update(dirRecid, dir, DIR_SERIALIZER); - if(expireFlag) expireLinkAdd(segment,expireNodeRecid, newRecid,h); - notify(key, null, value); - return null; - } - } - } - - - @Override - public V remove(Object key){ - - final int h = hash(key); - final int segment = h >>>28; - segmentLocks[segment].writeLock().lock(); - try{ - return removeInternal(key, segment, h, true); - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - - protected V removeInternal(Object key, int segment, int h, boolean removeExpire){ - final long[] dirRecids = new long[4]; - int level = 3; - dirRecids[level] = segmentRecids[segment]; - - assert(segment==h>>>28); - - while(true){ - long[][] dir = engine.get(dirRecids[level], DIR_SERIALIZER); - final int slot = (h>>>(7*level )) & 0x7F; - assert(slot<=127); - - if(dir == null ){ - //create new dir - dir = new long[16][]; - } - - if(dir[slot>>>DIV8] == null){ - dir = Arrays.copyOf(dir,16); - dir[slot>>>DIV8] = new long[8]; - } - -// int counter = 0; - long recid = dir[slot>>>DIV8][slot&MOD8]; - - if(recid!=0){ - if((recid&1) == 0){ - level--; - dirRecids[level] = recid>>>1; - continue; - } - recid = recid>>>1; - - //traverse linked list, try to remove node - LinkedNode ln = engine.get(recid, LN_SERIALIZER); - LinkedNode prevLn = null; - long prevRecid = 0; - while(ln!=null){ - if(hasher.equals(ln.key, (K) key)){ - //remove from linkedList - if(prevLn == null ){ - //referenced directly from dir - if(ln.next==0){ - recursiveDirDelete(h, level, dirRecids, dir, slot); - - - }else{ - dir=Arrays.copyOf(dir,16); - dir[slot>>>DIV8] = Arrays.copyOf(dir[slot>>>DIV8],8); - dir[slot>>>DIV8][slot&MOD8] = (ln.next<<1)|1; - engine.update(dirRecids[level], dir, DIR_SERIALIZER); - } - - }else{ - //referenced from LinkedNode - prevLn = new LinkedNode(ln.next, prevLn.expireLinkNodeRecid,prevLn.key, prevLn.value); - engine.update(prevRecid, prevLn, LN_SERIALIZER); - } - //found, remove this node - assert(hash(ln.key)==h); - engine.delete(recid, LN_SERIALIZER); - if(removeExpire && expireFlag) expireLinkRemove(segment, ln.expireLinkNodeRecid); - notify((K) key, ln.value, null); - return ln.value; - } - prevRecid = recid; - prevLn = ln; - recid = ln.next; - ln = recid==0? null : engine.get(recid, LN_SERIALIZER); -// counter++; - } - //key was not found at linked list, so it does not exist - return null; - } - //recid is 0, so entry does not exist - return null; - - } - } - - - private void recursiveDirDelete(int h, int level, long[] dirRecids, long[][] dir, int slot) { - //was only item in linked list, so try to collapse the dir - dir=Arrays.copyOf(dir,16); - dir[slot>>>DIV8] = Arrays.copyOf(dir[slot>>>DIV8],8); - dir[slot>>>DIV8][slot&MOD8] = 0; - //one record was zeroed out, check if subarray can be collapsed to null - boolean allZero = true; - for(long l:dir[slot>>>DIV8]){ - if(l!=0){ - allZero = false; - break; - } - } - if(allZero){ - dir[slot>>>DIV8] = null; - } - allZero = true; - for(long[] l:dir){ - if(l!=null){ - allZero = false; - break; - } - } - - if(allZero){ - //delete from parent dir - if(level==3){ - //parent is segment, recid of this dir can not be modified, so just update to null - engine.update(dirRecids[level], new long[16][], DIR_SERIALIZER); - }else{ - engine.delete(dirRecids[level], DIR_SERIALIZER); - - final long[][] parentDir = engine.get(dirRecids[level + 1], DIR_SERIALIZER); - final int parentPos = (h >>> (7 * (level + 1))) & 0x7F; - recursiveDirDelete(h,level+1,dirRecids, parentDir, parentPos); - //parentDir[parentPos>>>DIV8][parentPos&MOD8] = 0; - //engine.update(dirRecids[level + 1],parentDir,DIR_SERIALIZER); - - } - }else{ - engine.update(dirRecids[level], dir, DIR_SERIALIZER); - } - } - - @Override - public void clear() { - for(int i = 0; i<16;i++) try{ - segmentLocks[i].writeLock().lock(); - - final long dirRecid = segmentRecids[i]; - recursiveDirClear(dirRecid); - - //set dir to null, as segment recid is immutable - engine.update(dirRecid, new long[16][], DIR_SERIALIZER); - - if(expireFlag) - while(expireLinkRemoveLast(i)!=null){} //TODO speedup remove all - - }finally { - segmentLocks[i].writeLock().unlock(); - } - } - - private void recursiveDirClear(final long dirRecid) { - final long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - if(dir == null) return; - for(long[] subdir:dir){ - if(subdir==null) continue; - for(long recid:subdir){ - if(recid == 0) continue; - if((recid&1)==0){ - //another dir - recid = recid>>>1; - //recursively remove dir - recursiveDirClear(recid); - engine.delete(recid, DIR_SERIALIZER); - }else{ - //linked list to delete - recid = recid>>>1; - while(recid!=0){ - LinkedNode n = engine.get(recid, LN_SERIALIZER); - engine.delete(recid,LN_SERIALIZER); - notify((K)n.key, (V)n.value , null); - recid = n.next; - } - } - - } - } - } - - - @Override - public boolean containsValue(Object value) { - for (V v : values()) { - if (v.equals(value)) return true; - } - return false; - } - - - - protected class KeySet extends AbstractSet { - - @Override - public int size() { - return HTreeMap.this.size(); - } - - @Override - public boolean isEmpty() { - return HTreeMap.this.isEmpty(); - } - - @Override - public boolean contains(Object o) { - return HTreeMap.this.containsKey(o); - } - - @Override - public Iterator iterator() { - return new KeyIterator(); - } - - @Override - public boolean add(K k) { - if(HTreeMap.this.hasValues) - throw new UnsupportedOperationException(); - else - return HTreeMap.this.put(k, (V) BTreeMap.EMPTY) == null; - } - - @Override - public boolean remove(Object o) { -// if(o instanceof Entry){ -// Entry e = (Entry) o; -// return HTreeMap.this.remove(((Entry) o).getKey(),((Entry) o).getValue()); -// } - return HTreeMap.this.remove(o)!=null; - - } - - - @Override - public void clear() { - HTreeMap.this.clear(); - } - - public HTreeMap parent(){ - return HTreeMap.this; - } - - @Override - public int hashCode() { - int result = 0; - Iterator it = iterator(); - while (it.hasNext()) { - result += hasher.hashCode(it.next()); - } - return result; - - } - } - - - - private final Set _keySet = new KeySet(); - - @Override - public Set keySet() { - return _keySet; - } - - private final Collection _values = new AbstractCollection(){ - - @Override - public int size() { - return HTreeMap.this.size(); - } - - @Override - public boolean isEmpty() { - return HTreeMap.this.isEmpty(); - } - - @Override - public boolean contains(Object o) { - return HTreeMap.this.containsValue(o); - } - - - - @Override - public Iterator iterator() { - return new ValueIterator(); - } - - }; - - @Override - public Collection values() { - return _values; - } - - private Set> _entrySet = new AbstractSet>(){ - - @Override - public int size() { - return HTreeMap.this.size(); - } - - @Override - public boolean isEmpty() { - return HTreeMap.this.isEmpty(); - } - - @Override - public boolean contains(Object o) { - if(o instanceof Entry){ - Entry e = (Entry) o; - Object val = HTreeMap.this.get(e.getKey()); - return val!=null && val.equals(e.getValue()); - }else - return false; - } - - @Override - public Iterator> iterator() { - return new EntryIterator(); - } - - - @Override - public boolean add(Entry kvEntry) { - K key = kvEntry.getKey(); - V value = kvEntry.getValue(); - if(key==null || value == null) throw new NullPointerException(); - HTreeMap.this.put(key, value); - return true; - } - - @Override - public boolean remove(Object o) { - if(o instanceof Entry){ - Entry e = (Entry) o; - Object key = e.getKey(); - if(key == null) return false; - return HTreeMap.this.remove(key, e.getValue()); - } - return false; - } - - - @Override - public void clear() { - HTreeMap.this.clear(); - } - }; - - @Override - public Set> entrySet() { - return _entrySet; - } - - - protected int hash(final Object key) { - int h = hasher.hashCode((K) key) ^ hashSalt; - h ^= (h >>> 20) ^ (h >>> 12); - return h ^ (h >>> 7) ^ (h >>> 4); - } - - - abstract class HashIterator{ - - protected LinkedNode[] currentLinkedList; - protected int currentLinkedListPos = 0; - - private K lastReturnedKey = null; - - private int lastSegment = 0; - - HashIterator(){ - currentLinkedList = findNextLinkedNode(0); - } - - public void remove() { - final K keyToRemove = lastReturnedKey; - if (lastReturnedKey == null) - throw new IllegalStateException(); - - lastReturnedKey = null; - HTreeMap.this.remove(keyToRemove); - } - - public boolean hasNext(){ - return currentLinkedList!=null && currentLinkedListPos>>28; - - //two phases, first find old item and increase hash - try{ - segmentLocks[segment].readLock().lock(); - - long dirRecid = segmentRecids[segment]; - int level = 3; - //dive into tree, finding last hash position - while(true){ - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - int pos = (lastHash>>>(7 * level)) & 0x7F; - - //check if we need to expand deeper - if(dir[pos>>>DIV8]==null || dir[pos>>>DIV8][pos&MOD8]==0 || (dir[pos>>>DIV8][pos&MOD8]&1)==1) { - //increase hash by 1 - if(level!=0){ - lastHash = ((lastHash>>>(7 * level)) + 1) << (7*level); //should use mask and XOR - }else - lastHash +=1; - if(lastHash==0){ - return null; - } - break; - } - - //reference is dir, move to next level - dirRecid = dir[pos>>>DIV8][pos&MOD8]>>>1; - level--; - } - - }finally { - segmentLocks[segment].readLock().unlock(); - } - return findNextLinkedNode(lastHash); - - - } - - private LinkedNode[] findNextLinkedNode(int hash) { - //second phase, start search from increased hash to find next items - for(int segment = Math.max(hash >>>28, lastSegment); segment<16;segment++){ - final Lock lock = expireAccessFlag ? segmentLocks[segment].writeLock() :segmentLocks[segment].readLock() ; - lock.lock(); - try{ - lastSegment = Math.max(segment,lastSegment); - long dirRecid = segmentRecids[segment]; - LinkedNode ret[] = findNextLinkedNodeRecur(dirRecid, hash, 3); - if(ret!=null) for(LinkedNode ln:ret){ - assert hash(ln.key)>>>28==segment; - } - //System.out.println(Arrays.asList(ret)); - if(ret !=null){ - if(expireAccessFlag){ - for(LinkedNode ln:ret) expireLinkBump(segment,ln.expireLinkNodeRecid,true); - } - return ret; - } - hash = 0; - }finally { - lock.unlock(); - } - } - - return null; - } - - private LinkedNode[] findNextLinkedNodeRecur(long dirRecid, int newHash, int level){ - long[][] dir = engine.get(dirRecid, DIR_SERIALIZER); - if(dir == null) return null; - int pos = (newHash>>>(level*7)) & 0x7F; - boolean first = true; - while(pos<128){ - if(dir[pos>>>DIV8]!=null){ - long recid = dir[pos>>>DIV8][pos&MOD8]; - if(recid!=0){ - if((recid&1) == 1){ - recid = recid>>1; - //found linked list, load it into array and return - LinkedNode[] array = new LinkedNode[1]; - int arrayPos = 0; - while(recid!=0){ - LinkedNode ln = engine.get(recid, LN_SERIALIZER); - if(ln==null){ - recid = 0; - continue; - } - //increase array size if needed - if(arrayPos == array.length) - array = Arrays.copyOf(array, array.length+1); - array[arrayPos++] = ln; - recid = ln.next; - } - return array; - }else{ - //found another dir, continue dive - recid = recid>>1; - LinkedNode[] ret = findNextLinkedNodeRecur(recid, first ? newHash : 0, level - 1); - if(ret != null) return ret; - } - } - } - first = false; - pos++; - } - return null; - } - } - - class KeyIterator extends HashIterator implements Iterator{ - - @Override - public K next() { - if(currentLinkedList == null) - throw new NoSuchElementException(); - K key = (K) currentLinkedList[currentLinkedListPos].key; - moveToNext(); - return key; - } - } - - class ValueIterator extends HashIterator implements Iterator{ - - @Override - public V next() { - if(currentLinkedList == null) - throw new NoSuchElementException(); - V value = (V) currentLinkedList[currentLinkedListPos].value; - moveToNext(); - return value; - } - } - - class EntryIterator extends HashIterator implements Iterator>{ - - @Override - public Entry next() { - if(currentLinkedList == null) - throw new NoSuchElementException(); - K key = (K) currentLinkedList[currentLinkedListPos].key; - moveToNext(); - return new Entry2(key); - } - } - - class Entry2 implements Entry{ - - private final K key; - - Entry2(K key) { - this.key = key; - } - - @Override - public K getKey() { - return key; - } - - @Override - public V getValue() { - return HTreeMap.this.get(key); - } - - @Override - public V setValue(V value) { - return HTreeMap.this.put(key,value); - } - - @Override - public boolean equals(Object o) { - return (o instanceof Entry) && hasher.equals(key, (K) ((Entry) o).getKey()); - } - - @Override - public int hashCode() { - final V value = HTreeMap.this.get(key); - return (key == null ? 0 : hasher.hashCode(key)) ^ - (value == null ? 0 : value.hashCode()); - } - } - - - @Override - public V putIfAbsent(K key, V value) { - if(key==null||value==null) throw new NullPointerException(); - - final int h = HTreeMap.this.hash(key); - final int segment = h >>>28; - try{ - segmentLocks[segment].writeLock().lock(); - - LinkedNode ln = HTreeMap.this.getInner(key,h,segment); - if (ln==null) - return put(key, value); - else - return ln.value; - - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - @Override - public boolean remove(Object key, Object value) { - if(key==null||value==null) throw new NullPointerException(); - final int h = HTreeMap.this.hash(key); - final int segment = h >>>28; - try{ - segmentLocks[segment].writeLock().lock(); - - LinkedNode otherVal = getInner(key, h, segment); - if (otherVal!=null && otherVal.value.equals(value)) { - removeInternal(key, segment, h, true); - return true; - }else - return false; - - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - @Override - public boolean replace(K key, V oldValue, V newValue) { - if(key==null||oldValue==null||newValue==null) throw new NullPointerException(); - final int h = HTreeMap.this.hash(key); - final int segment = h >>>28; - try{ - segmentLocks[segment].writeLock().lock(); - - LinkedNode ln = getInner(key, h,segment); - if (ln!=null && ln.value.equals(oldValue)) { - putInner(key, newValue,h,segment); - return true; - } else - return false; - - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - @Override - public V replace(K key, V value) { - if(key==null||value==null) throw new NullPointerException(); - final int h = HTreeMap.this.hash(key); - final int segment = h >>>28; - try{ - segmentLocks[segment].writeLock().lock(); - - if (getInner(key,h,segment)!=null) - return putInner(key, value,h,segment); - else - return null; - }finally { - segmentLocks[segment].writeLock().unlock(); - } - } - - - - protected static final class ExpireLinkNode{ - - public static ExpireLinkNode EMPTY = new ExpireLinkNode(0,0,0,0,0); - - public static final Serializer SERIALIZER = new Serializer() { - @Override - public void serialize(DataOutput out, ExpireLinkNode value) throws IOException { - if(value == EMPTY) return; - DataOutput2.packLong(out,value.prev); - DataOutput2.packLong(out,value.next); - DataOutput2.packLong(out,value.keyRecid); - DataOutput2.packLong(out,value.time); - out.writeInt(value.hash); - } - - @Override - public ExpireLinkNode deserialize(DataInput in, int available) throws IOException { - if(available==0) return EMPTY; - return new ExpireLinkNode( - DataInput2.unpackLong(in),DataInput2.unpackLong(in),DataInput2.unpackLong(in),DataInput2.unpackLong(in), - in.readInt() - ); - } - - @Override - public int fixedSize() { - return -1; - } - - }; - - public final long prev; - public final long next; - public final long keyRecid; - public final long time; - public final int hash; - - public ExpireLinkNode(long prev, long next, long keyRecid, long time, int hash) { - this.prev = prev; - this.next = next; - this.keyRecid = keyRecid; - this.time = time; - this.hash = hash; - } - - public ExpireLinkNode copyNext(long next2) { - return new ExpireLinkNode(prev,next2, keyRecid,time,hash); - } - - public ExpireLinkNode copyPrev(long prev2) { - return new ExpireLinkNode(prev2,next, keyRecid,time,hash); - } - - public ExpireLinkNode copyTime(long time2) { - return new ExpireLinkNode(prev,next,keyRecid,time2,hash); - } - - } - - - - protected void expireLinkAdd(int segment, long expireNodeRecid, long keyRecid, int hash){ - assert(segmentLocks[segment].writeLock().isHeldByCurrentThread()); - assert(expireNodeRecid>0); - assert(keyRecid>0); - - long time = expire==0 ? 0: expire+System.currentTimeMillis()-expireTimeStart; - long head = engine.get(expireHeads[segment],Serializer.LONG); - if(head == 0){ - //insert new - ExpireLinkNode n = new ExpireLinkNode(0,0,keyRecid,time,hash); - engine.update(expireNodeRecid, n, ExpireLinkNode.SERIALIZER); - engine.update(expireHeads[segment],expireNodeRecid,Serializer.LONG); - engine.update(expireTails[segment],expireNodeRecid,Serializer.LONG); - }else{ - //insert new head - ExpireLinkNode n = new ExpireLinkNode(head,0,keyRecid,time,hash); - engine.update(expireNodeRecid, n, ExpireLinkNode.SERIALIZER); - - //update old head to have new head as next - ExpireLinkNode oldHead = engine.get(head,ExpireLinkNode.SERIALIZER); - oldHead=oldHead.copyNext(expireNodeRecid); - engine.update(head,oldHead,ExpireLinkNode.SERIALIZER); - - //and update head - engine.update(expireHeads[segment],expireNodeRecid,Serializer.LONG); - } - } - - protected void expireLinkBump(int segment, long nodeRecid, boolean access){ - assert(segmentLocks[segment].writeLock().isHeldByCurrentThread()); - - ExpireLinkNode n = engine.get(nodeRecid,ExpireLinkNode.SERIALIZER); - long newTime = - access? - (expireAccess==0?0 : expireAccess+System.currentTimeMillis()-expireTimeStart): - (expire==0?0 : expire+System.currentTimeMillis()-expireTimeStart); - - //TODO optimize bellow, but what if there is only size limit? - //if(n.time>newTime) return; // older time greater than new one, do not update - - if(n.next==0){ - //already head, so just update time - n = n.copyTime(newTime); - engine.update(nodeRecid,n,ExpireLinkNode.SERIALIZER); - }else{ - //update prev so it points to next - if(n.prev!=0){ - //not a tail - ExpireLinkNode prev = engine.get(n.prev,ExpireLinkNode.SERIALIZER); - prev=prev.copyNext(n.next); - engine.update(n.prev, prev, ExpireLinkNode.SERIALIZER); - }else{ - //yes tail, so just update it to point to next - engine.update(expireTails[segment],n.next,Serializer.LONG); - } - - //update next so it points to prev - ExpireLinkNode next = engine.get(n.next, ExpireLinkNode.SERIALIZER); - next=next.copyPrev(n.prev); - engine.update(n.next,next,ExpireLinkNode.SERIALIZER); - - //TODO optimize if oldHead==next - - //now insert node as new head - long oldHeadRecid = engine.get(expireHeads[segment],Serializer.LONG); - ExpireLinkNode oldHead = engine.get(oldHeadRecid, ExpireLinkNode.SERIALIZER); - oldHead = oldHead.copyNext(nodeRecid); - engine.update(oldHeadRecid,oldHead,ExpireLinkNode.SERIALIZER); - engine.update(expireHeads[segment],nodeRecid,Serializer.LONG); - - n = new ExpireLinkNode(oldHeadRecid,0, n.keyRecid, newTime, n.hash); - engine.update(nodeRecid,n,ExpireLinkNode.SERIALIZER); - } - } - - protected ExpireLinkNode expireLinkRemoveLast(int segment){ - assert(segmentLocks[segment].writeLock().isHeldByCurrentThread()); - - long tail = engine.get(expireTails[segment],Serializer.LONG); - if(tail==0) return null; - - ExpireLinkNode n = engine.get(tail,ExpireLinkNode.SERIALIZER); - if(n.next==0){ - //update tail and head - engine.update(expireHeads[segment],0L,Serializer.LONG); - engine.update(expireTails[segment],0L,Serializer.LONG); - }else{ - //point tail to next record - engine.update(expireTails[segment],n.next,Serializer.LONG); - //update next record to have zero prev - ExpireLinkNode next = engine.get(n.next,ExpireLinkNode.SERIALIZER); - next=next.copyPrev(0L); - engine.update(n.next, next, ExpireLinkNode.SERIALIZER); - } - - engine.delete(tail,ExpireLinkNode.SERIALIZER); - return n; - } - - - protected ExpireLinkNode expireLinkRemove(int segment, long nodeRecid){ - assert(segmentLocks[segment].writeLock().isHeldByCurrentThread()); - - ExpireLinkNode n = engine.get(nodeRecid,ExpireLinkNode.SERIALIZER); - engine.delete(nodeRecid,ExpireLinkNode.SERIALIZER); - if(n.next == 0 && n.prev==0){ - engine.update(expireHeads[segment],0L,Serializer.LONG); - engine.update(expireTails[segment],0L,Serializer.LONG); - }else if (n.next == 0) { - ExpireLinkNode prev = engine.get(n.prev,ExpireLinkNode.SERIALIZER); - prev=prev.copyNext(0); - engine.update(n.prev,prev,ExpireLinkNode.SERIALIZER); - engine.update(expireHeads[segment],n.prev,Serializer.LONG); - }else if (n.prev == 0) { - ExpireLinkNode next = engine.get(n.next,ExpireLinkNode.SERIALIZER); - next=next.copyPrev(0); - engine.update(n.next,next,ExpireLinkNode.SERIALIZER); - engine.update(expireTails[segment],n.next,Serializer.LONG); - }else{ - ExpireLinkNode next = engine.get(n.next,ExpireLinkNode.SERIALIZER); - next=next.copyPrev(n.prev); - engine.update(n.next,next,ExpireLinkNode.SERIALIZER); - - ExpireLinkNode prev = engine.get(n.prev,ExpireLinkNode.SERIALIZER); - prev=prev.copyNext(n.next); - engine.update(n.prev,prev,ExpireLinkNode.SERIALIZER); - } - - return n; - } - - /** - * Returns maximal (newest) expiration timestamp - */ - public long getMaxExpireTime(){ - if(!expireFlag) return 0; - long ret = 0; - for(int segment = 0;segment<16;segment++){ - segmentLocks[segment].readLock().lock(); - try{ - long head = engine.get(expireHeads[segment],Serializer.LONG); - if(head == 0) continue; - ExpireLinkNode ln = engine.get(head, ExpireLinkNode.SERIALIZER); - if(ln==null || ln.time==0) continue; - ret = Math.max(ret, ln.time+expireTimeStart); - }finally{ - segmentLocks[segment].readLock().unlock(); - } - } - return ret; - } - - /** - * Returns minimal (oldest) expiration timestamp - */ - public long getMinExpireTime(){ - if(!expireFlag) return 0; - long ret = Long.MAX_VALUE; - for(int segment = 0;segment<16;segment++){ - segmentLocks[segment].readLock().lock(); - try{ - long tail = engine.get(expireTails[segment],Serializer.LONG); - if(tail == 0) continue; - ExpireLinkNode ln = engine.get(tail, ExpireLinkNode.SERIALIZER); - if(ln==null || ln.time==0) continue; - ret = Math.min(ret, ln.time+expireTimeStart); - }finally{ - segmentLocks[segment].readLock().unlock(); - } - } - if(ret == Long.MAX_VALUE) ret =0; - return ret; - } - - protected static class ExpireRunnable implements Runnable{ - - //use weak referece to prevent memory leak - final WeakReference mapRef; - - public ExpireRunnable(HTreeMap map) { - this.mapRef = new WeakReference(map); - } - - @Override - public void run() { - boolean pause = false; - try { - while(true) { - - if (pause) { - Thread.sleep(1000); - } - - - HTreeMap map = mapRef.get(); - if (map == null || map.engine.isClosed() || map.closeLatch.getCount()<2) - return; - - //TODO what if store gets closed while working on this? - map.expirePurge(); - - if (map.engine.isClosed() || map.closeLatch.getCount()<2) - return; - - pause = ((!map.expireMaxSizeFlag || map.size() < map.expireMaxSize) - && (map.expireStoreSize == 0L || - Store.forEngine(map.engine).getCurrSize() - Store.forEngine(map.engine).getFreeSize() < map.expireStoreSize)); - - } - - }catch(Throwable e){ - //TODO exception handling - e.printStackTrace(); - //Utils.LOG.log(Level.SEVERE, "HTreeMap expirator failed", e); - }finally { - HTreeMap m = mapRef.get(); - if (m != null) - m.closeLatch.countDown(); - mapRef.clear(); - } - } - - } - - - protected void expirePurge(){ - if(!expireFlag) return; - - long removePerSegment = 0; - if(expireMaxSizeFlag){ - long size = counter.get(); - if(size>expireMaxSize){ - removePerSegment=1+(size-expireMaxSize)/16; - } - } - - - if(expireStoreSize!=0 && removePerSegment==0){ - Store store = Store.forEngine(engine); - if(expireStoreSize>>28 == seg); - - final boolean remove = ++counter < removePerSegment || - ((expire!=0 || expireAccess!=0) && n.time+expireTimeStart ln = engine.get(n.keyRecid,LN_SERIALIZER); - removeInternal(ln.key,seg, n.hash, false); - }else{ - break; - } - last=n; - recid=n.next; - } - // patch linked list - if(last ==null ){ - //no items removed - return; - }else if(recid == 0){ - //all items were taken, so zero items - engine.update(expireTails[seg],0L, Serializer.LONG); - engine.update(expireHeads[seg],0L, Serializer.LONG); - }else{ - //update tail to point to next item - engine.update(expireTails[seg],recid, Serializer.LONG); - //and update next item to point to tail - n = engine.get(recid, ExpireLinkNode.SERIALIZER); - n = n.copyPrev(0); - engine.update(recid,n,ExpireLinkNode.SERIALIZER); - } -// expireCheckSegment(seg); - }finally{ - segmentLocks[seg].writeLock().unlock(); - } - } - - - protected void expireCheckSegment(int segment){ - long current = engine.get(expireTails[segment],Serializer.LONG); - if(current==0){ - if(engine.get(expireHeads[segment],Serializer.LONG)!=0) - throw new AssertionError("head not 0"); - return; - } - - long prev = 0; - while(current!=0){ - ExpireLinkNode curr = engine.get(current,ExpireLinkNode.SERIALIZER); - assert(curr.prev==prev):"wrong prev "+curr.prev +" - "+prev; - prev= current; - current = curr.next; - } - if(engine.get(expireHeads[segment],Serializer.LONG)!=prev) - throw new AssertionError("wrong head"); - - } - - /** - * Make readonly snapshot view of current Map. Snapshot is immutable and not affected by modifications made by other threads. - * Useful if you need consistent view on Map. - *

- * Maintaining snapshot have some overhead, underlying Engine is closed after Map view is GCed. - * Please make sure to release reference to this Map view, so snapshot view can be garbage collected. - * - * @return snapshot - */ - public Map snapshot(){ - Engine snapshot = TxEngine.createSnapshotFor(engine); - return new HTreeMap(snapshot, counter==null?0:counter.recid, - hashSalt, segmentRecids, keySerializer, valueSerializer,0L,0L,0L,0L,0L,null,null, null, null, false); - } - - - protected final Object modListenersLock = new Object(); - protected Bind.MapListener[] modListeners = new Bind.MapListener[0]; - - @Override - public void addModificationListener(Bind.MapListener listener) { - synchronized (modListenersLock){ - Bind.MapListener[] modListeners2 = - Arrays.copyOf(modListeners,modListeners.length+1); - modListeners2[modListeners2.length-1] = listener; - modListeners = modListeners2; - } - - } - - @Override - public void removeModificationListener(Bind.MapListener listener) { - synchronized (modListenersLock){ - for(int i=0;i>>28].isWriteLockedByCurrentThread()); - Bind.MapListener[] modListeners2 = modListeners; - for(Bind.MapListener listener:modListeners2){ - if(listener!=null) - listener.update(key, oldValue, newValue); - } - } - - /** - * Closes underlying storage and releases all resources. - * Used mostly with temporary collections where engine is not accessible. - */ - public void close(){ - engine.close(); - } - - public Engine getEngine(){ - return engine; - } - -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/pair.info deleted file mode 100755 index 3fd9e83..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#4804/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:4804 -comSha:167b296b78ce830988083acc859dad7f39ce7fe6 -parentComSha:75efe20e0b2b22cf769e5630e511c2ccfd2df089 -BuggyFilePath:src/main/java/org/mapdb/HTreeMap.java -FixedFilePath:src/main/java/org/mapdb/HTreeMap.java -StartLineNum:1263 -EndLineNum:1263 -repoName:jankotek#MapDB \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/comMsg.txt deleted file mode 100755 index 5c0f15f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Bereinigung Findbugs-Warnings \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/diff.diff deleted file mode 100755 index fa879c3..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java b/src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -index fa67239..13fcc29 100644 ---- a/src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -+++ b/src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -@@ -16,4 +16,4 @@ public class CheckDrittpersonIdentischMitElternteilCommand implements Command { -- public static String ERROR_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson ist identisch mit Mutter. Setze Mutter als Rechnungsempfängerin."; -- public static String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson und Mutter scheinen identisch zu sein. Setze Mutter als Rechnungsempfängerin oder präzisiere Mutter."; -- public static String ERROR_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson ist identisch mit Vater. Setze Vater als Rechnungsempfänger."; -- public static String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson und Vater scheinen identisch zu sein. Setze Vater als Rechnungsempfänger oder präzisiere Vater."; -+ public static final String ERROR_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson ist identisch mit Mutter. Setze Mutter als Rechnungsempfängerin."; -+ public static final String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson und Mutter scheinen identisch zu sein. Setze Mutter als Rechnungsempfängerin oder präzisiere Mutter."; -+ public static final String ERROR_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson ist identisch mit Vater. Setze Vater als Rechnungsempfänger."; -+ public static final String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson und Vater scheinen identisch zu sein. Setze Vater als Rechnungsempfänger oder präzisiere Vater."; \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/new/CheckDrittpersonIdentischMitElternteilCommand.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/new/CheckDrittpersonIdentischMitElternteilCommand.java deleted file mode 100755 index 13fcc29..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/new/CheckDrittpersonIdentischMitElternteilCommand.java +++ /dev/null @@ -1,83 +0,0 @@ -package ch.metzenthin.svm.domain.commands; - -import ch.metzenthin.svm.domain.model.AngehoerigerModel; -import ch.metzenthin.svm.persistence.entities.Angehoeriger; - -/** - * @author Martin Schraner - */ -public class CheckDrittpersonIdentischMitElternteilCommand implements Command { - - private Angehoeriger mutter; - private Angehoeriger vater; - private Angehoeriger rechnungsempfaengerDrittperson; - private boolean isDrittpersonRechungsempfaenger; - - public static final String ERROR_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson ist identisch mit Mutter. Setze Mutter als Rechnungsempfängerin."; - public static final String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson und Mutter scheinen identisch zu sein. Setze Mutter als Rechnungsempfängerin oder präzisiere Mutter."; - public static final String ERROR_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson ist identisch mit Vater. Setze Vater als Rechnungsempfänger."; - public static final String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson und Vater scheinen identisch zu sein. Setze Vater als Rechnungsempfänger oder präzisiere Vater."; - - // output - private boolean identical; - private String errorDrittpersonIdentischMitElternteil; - - public CheckDrittpersonIdentischMitElternteilCommand(AngehoerigerModel mutterModel, AngehoerigerModel vaterModel, AngehoerigerModel rechnungsempfaengerDrittpersonModel) { - mutter = mutterModel.getAngehoeriger(); - if (mutter != null) { - mutter.setAdresse(mutterModel.getAdresse()); - } - vater = vaterModel.getAngehoeriger(); - if (vater != null) { - vater.setAdresse(vaterModel.getAdresse()); - } - rechnungsempfaengerDrittperson = rechnungsempfaengerDrittpersonModel.getAngehoeriger(); - if (rechnungsempfaengerDrittperson != null) { - rechnungsempfaengerDrittperson.setAdresse(rechnungsempfaengerDrittpersonModel.getAdresse()); - } - isDrittpersonRechungsempfaenger = rechnungsempfaengerDrittpersonModel.isRechnungsempfaenger(); - } - - @Override - public void execute() { - - if (rechnungsempfaengerDrittperson == null || rechnungsempfaengerDrittperson.isEmpty() || !isDrittpersonRechungsempfaenger) { - identical = false; - errorDrittpersonIdentischMitElternteil = ""; - } - - else if (mutter.isIdenticalWith(rechnungsempfaengerDrittperson)) { - identical = true; - errorDrittpersonIdentischMitElternteil = ERROR_IDENTISCH_MIT_MUTTER; - } - - else if (mutter.isPartOf(rechnungsempfaengerDrittperson)) { - identical = true; - errorDrittpersonIdentischMitElternteil = ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER; - } - - else if (vater.isIdenticalWith(rechnungsempfaengerDrittperson)) { - identical = true; - errorDrittpersonIdentischMitElternteil = ERROR_IDENTISCH_MIT_VATER; - } - - else if (vater.isPartOf(rechnungsempfaengerDrittperson)) { - identical = true; - errorDrittpersonIdentischMitElternteil = ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER; - } - - else { - identical = false; - errorDrittpersonIdentischMitElternteil = ""; - } - - } - - public boolean isIdentical() { - return identical; - } - - public String getErrorDrittpersonIdentischMitElternteil() { - return errorDrittpersonIdentischMitElternteil; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/old/CheckDrittpersonIdentischMitElternteilCommand.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/old/CheckDrittpersonIdentischMitElternteilCommand.java deleted file mode 100755 index fa67239..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/old/CheckDrittpersonIdentischMitElternteilCommand.java +++ /dev/null @@ -1,83 +0,0 @@ -package ch.metzenthin.svm.domain.commands; - -import ch.metzenthin.svm.domain.model.AngehoerigerModel; -import ch.metzenthin.svm.persistence.entities.Angehoeriger; - -/** - * @author Martin Schraner - */ -public class CheckDrittpersonIdentischMitElternteilCommand implements Command { - - private Angehoeriger mutter; - private Angehoeriger vater; - private Angehoeriger rechnungsempfaengerDrittperson; - private boolean isDrittpersonRechungsempfaenger; - - public static String ERROR_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson ist identisch mit Mutter. Setze Mutter als Rechnungsempfängerin."; - public static String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson und Mutter scheinen identisch zu sein. Setze Mutter als Rechnungsempfängerin oder präzisiere Mutter."; - public static String ERROR_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson ist identisch mit Vater. Setze Vater als Rechnungsempfänger."; - public static String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson und Vater scheinen identisch zu sein. Setze Vater als Rechnungsempfänger oder präzisiere Vater."; - - // output - private boolean identical; - private String errorDrittpersonIdentischMitElternteil; - - public CheckDrittpersonIdentischMitElternteilCommand(AngehoerigerModel mutterModel, AngehoerigerModel vaterModel, AngehoerigerModel rechnungsempfaengerDrittpersonModel) { - mutter = mutterModel.getAngehoeriger(); - if (mutter != null) { - mutter.setAdresse(mutterModel.getAdresse()); - } - vater = vaterModel.getAngehoeriger(); - if (vater != null) { - vater.setAdresse(vaterModel.getAdresse()); - } - rechnungsempfaengerDrittperson = rechnungsempfaengerDrittpersonModel.getAngehoeriger(); - if (rechnungsempfaengerDrittperson != null) { - rechnungsempfaengerDrittperson.setAdresse(rechnungsempfaengerDrittpersonModel.getAdresse()); - } - isDrittpersonRechungsempfaenger = rechnungsempfaengerDrittpersonModel.isRechnungsempfaenger(); - } - - @Override - public void execute() { - - if (rechnungsempfaengerDrittperson == null || rechnungsempfaengerDrittperson.isEmpty() || !isDrittpersonRechungsempfaenger) { - identical = false; - errorDrittpersonIdentischMitElternteil = ""; - } - - else if (mutter.isIdenticalWith(rechnungsempfaengerDrittperson)) { - identical = true; - errorDrittpersonIdentischMitElternteil = ERROR_IDENTISCH_MIT_MUTTER; - } - - else if (mutter.isPartOf(rechnungsempfaengerDrittperson)) { - identical = true; - errorDrittpersonIdentischMitElternteil = ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER; - } - - else if (vater.isIdenticalWith(rechnungsempfaengerDrittperson)) { - identical = true; - errorDrittpersonIdentischMitElternteil = ERROR_IDENTISCH_MIT_VATER; - } - - else if (vater.isPartOf(rechnungsempfaengerDrittperson)) { - identical = true; - errorDrittpersonIdentischMitElternteil = ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER; - } - - else { - identical = false; - errorDrittpersonIdentischMitElternteil = ""; - } - - } - - public boolean isIdentical() { - return identical; - } - - public String getErrorDrittpersonIdentischMitElternteil() { - return errorDrittpersonIdentischMitElternteil; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/pair.info deleted file mode 100755 index e002928..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49684/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:49684 -comSha:ca075210d54e8879d5a5f1cad23b29e2a05141f0 -parentComSha:b33d8870ce4b6ce01197bf0f344a05c62ef7477a -BuggyFilePath:src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -FixedFilePath:src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -StartLineNum:16 -EndLineNum:16 -repoName:marschraner#svm \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/comMsg.txt deleted file mode 100755 index 5c0f15f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Bereinigung Findbugs-Warnings \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/diff.diff deleted file mode 100755 index 1dcf4ae..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java b/src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -index 63153f2..fd8128a 100644 ---- a/src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -+++ b/src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -@@ -14,4 +14,4 @@ public class CheckDrittpersonIdentischMitElternteilCommand implements Command { -- public static String ERROR_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson ist identisch mit Mutter. Setze Mutter als Rechnungsempfängerin."; -- public static String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson und Mutter scheinen identisch zu sein. Setze Mutter als Rechnungsempfängerin und/oder korrigiere Mutter."; -- public static String ERROR_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson ist identisch mit Vater. Setze Vater als Rechnungsempfänger."; -- public static String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson und Vater scheinen identisch zu sein. Setze Vater als Rechnungsempfänger und/oder korrigiere Vater."; -+ public static final String ERROR_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson ist identisch mit Mutter. Setze Mutter als Rechnungsempfängerin."; -+ public static final String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson und Mutter scheinen identisch zu sein. Setze Mutter als Rechnungsempfängerin und/oder korrigiere Mutter."; -+ public static final String ERROR_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson ist identisch mit Vater. Setze Vater als Rechnungsempfänger."; -+ public static final String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson und Vater scheinen identisch zu sein. Setze Vater als Rechnungsempfänger und/oder korrigiere Vater."; \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/new/CheckDrittpersonIdentischMitElternteilCommand.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/new/CheckDrittpersonIdentischMitElternteilCommand.java deleted file mode 100755 index fd8128a..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/new/CheckDrittpersonIdentischMitElternteilCommand.java +++ /dev/null @@ -1,71 +0,0 @@ -package ch.metzenthin.svm.domain.commands; - -import ch.metzenthin.svm.persistence.entities.Angehoeriger; - -/** - * @author Martin Schraner - */ -public class CheckDrittpersonIdentischMitElternteilCommand implements Command { - - private Angehoeriger mutter; - private Angehoeriger vater; - private Angehoeriger rechnungsempfaengerDrittperson; - - public static final String ERROR_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson ist identisch mit Mutter. Setze Mutter als Rechnungsempfängerin."; - public static final String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson und Mutter scheinen identisch zu sein. Setze Mutter als Rechnungsempfängerin und/oder korrigiere Mutter."; - public static final String ERROR_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson ist identisch mit Vater. Setze Vater als Rechnungsempfänger."; - public static final String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson und Vater scheinen identisch zu sein. Setze Vater als Rechnungsempfänger und/oder korrigiere Vater."; - - // output - private boolean identical; - private String errorMessage; - - public CheckDrittpersonIdentischMitElternteilCommand(Angehoeriger mutter, Angehoeriger vater, Angehoeriger rechnungsempfaengerDrittperson) { - this.mutter = mutter; - this.vater = vater; - this.rechnungsempfaengerDrittperson = rechnungsempfaengerDrittperson; - } - - @Override - public void execute() { - - if (rechnungsempfaengerDrittperson == null || rechnungsempfaengerDrittperson.isEmpty()) { - identical = false; - errorMessage = ""; - } - - else if (mutter != null && mutter.getVorname() != null && !mutter.getVorname().trim().isEmpty() && mutter.isIdenticalWith(rechnungsempfaengerDrittperson)) { - identical = true; - errorMessage = ERROR_IDENTISCH_MIT_MUTTER; - } - - else if (mutter != null && mutter.getVorname() != null && !mutter.getVorname().trim().isEmpty() && mutter.isPartOf(rechnungsempfaengerDrittperson)) { - identical = true; - errorMessage = ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER; - } - - else if (vater != null && vater.getVorname() != null && !vater.getVorname().trim().isEmpty() && vater.isIdenticalWith(rechnungsempfaengerDrittperson)) { - identical = true; - errorMessage = ERROR_IDENTISCH_MIT_VATER; - } - - else if (vater != null && vater.getVorname() != null && !vater.getVorname().trim().isEmpty() && vater.isPartOf(rechnungsempfaengerDrittperson)) { - identical = true; - errorMessage = ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER; - } - - else { - identical = false; - errorMessage = ""; - } - - } - - public boolean isIdentical() { - return identical; - } - - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/old/CheckDrittpersonIdentischMitElternteilCommand.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/old/CheckDrittpersonIdentischMitElternteilCommand.java deleted file mode 100755 index 63153f2..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/old/CheckDrittpersonIdentischMitElternteilCommand.java +++ /dev/null @@ -1,71 +0,0 @@ -package ch.metzenthin.svm.domain.commands; - -import ch.metzenthin.svm.persistence.entities.Angehoeriger; - -/** - * @author Martin Schraner - */ -public class CheckDrittpersonIdentischMitElternteilCommand implements Command { - - private Angehoeriger mutter; - private Angehoeriger vater; - private Angehoeriger rechnungsempfaengerDrittperson; - - public static String ERROR_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson ist identisch mit Mutter. Setze Mutter als Rechnungsempfängerin."; - public static String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER = "Rechnungsempfänger Drittperson und Mutter scheinen identisch zu sein. Setze Mutter als Rechnungsempfängerin und/oder korrigiere Mutter."; - public static String ERROR_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson ist identisch mit Vater. Setze Vater als Rechnungsempfänger."; - public static String ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER = "Rechnungsempfänger Drittperson und Vater scheinen identisch zu sein. Setze Vater als Rechnungsempfänger und/oder korrigiere Vater."; - - // output - private boolean identical; - private String errorMessage; - - public CheckDrittpersonIdentischMitElternteilCommand(Angehoeriger mutter, Angehoeriger vater, Angehoeriger rechnungsempfaengerDrittperson) { - this.mutter = mutter; - this.vater = vater; - this.rechnungsempfaengerDrittperson = rechnungsempfaengerDrittperson; - } - - @Override - public void execute() { - - if (rechnungsempfaengerDrittperson == null || rechnungsempfaengerDrittperson.isEmpty()) { - identical = false; - errorMessage = ""; - } - - else if (mutter != null && mutter.getVorname() != null && !mutter.getVorname().trim().isEmpty() && mutter.isIdenticalWith(rechnungsempfaengerDrittperson)) { - identical = true; - errorMessage = ERROR_IDENTISCH_MIT_MUTTER; - } - - else if (mutter != null && mutter.getVorname() != null && !mutter.getVorname().trim().isEmpty() && mutter.isPartOf(rechnungsempfaengerDrittperson)) { - identical = true; - errorMessage = ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_MUTTER; - } - - else if (vater != null && vater.getVorname() != null && !vater.getVorname().trim().isEmpty() && vater.isIdenticalWith(rechnungsempfaengerDrittperson)) { - identical = true; - errorMessage = ERROR_IDENTISCH_MIT_VATER; - } - - else if (vater != null && vater.getVorname() != null && !vater.getVorname().trim().isEmpty() && vater.isPartOf(rechnungsempfaengerDrittperson)) { - identical = true; - errorMessage = ERROR_WAHRSCHEINLICH_IDENTISCH_MIT_VATER; - } - - else { - identical = false; - errorMessage = ""; - } - - } - - public boolean isIdentical() { - return identical; - } - - public String getErrorMessage() { - return errorMessage; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/pair.info deleted file mode 100755 index 977b62e..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49754/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:49754 -comSha:ce21a62fce3c30fbb1af1338c19f00fea4cf0d6b -parentComSha:615be59f878863018e4a356fc2e1bd2147baf7ec -BuggyFilePath:src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -FixedFilePath:src/main/java/ch/metzenthin/svm/domain/commands/CheckDrittpersonIdentischMitElternteilCommand.java -StartLineNum:15 -EndLineNum:15 -repoName:marschraner#svm \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/comMsg.txt deleted file mode 100755 index c8e3d2c..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Jenkin-Bugs behoben \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/diff.diff deleted file mode 100755 index 3b12d7d..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/ch/metzenthin/svm/persistence/entities/Lektionsgebuehren.java b/src/main/java/ch/metzenthin/svm/persistence/entities/Lektionsgebuehren.java -index f53a54a..8d52490 100644 ---- a/src/main/java/ch/metzenthin/svm/persistence/entities/Lektionsgebuehren.java -+++ b/src/main/java/ch/metzenthin/svm/persistence/entities/Lektionsgebuehren.java -@@ -14,2 +14,2 @@ public class Lektionsgebuehren implements Comparable { -- public static int MAX_KINDER = 6; -- public static int MIN_ANZAHL_TAGE_SECHS_JAHRES_RABATT = 2125; // 5 Jahre und 10 Monate -+ public static final int MAX_KINDER = 6; -+ public static final int MIN_ANZAHL_TAGE_SECHS_JAHRES_RABATT = 2125; // 5 Jahre und 10 Monate \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/new/Lektionsgebuehren.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/new/Lektionsgebuehren.java deleted file mode 100755 index 8d52490..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/new/Lektionsgebuehren.java +++ /dev/null @@ -1,130 +0,0 @@ -package ch.metzenthin.svm.persistence.entities; - -import javax.persistence.*; -import java.math.BigDecimal; -import java.sql.Timestamp; - -/** - * @author Martin Schraner - */ -@Entity -@Table(name="Lektionsgebuehren") -public class Lektionsgebuehren implements Comparable { - - public static final int MAX_KINDER = 6; - public static final int MIN_ANZAHL_TAGE_SECHS_JAHRES_RABATT = 2125; // 5 Jahre und 10 Monate - - @Id - @Column(name = "lektionslaenge") - private Integer lektionslaenge; - - @Version - @Column(name = "last_updated") - private Timestamp version; - - @Column(name = "betrag_1_kind", nullable = false) - private BigDecimal betrag1Kind; - - @Column(name = "betrag_2_kinder", nullable = false) - private BigDecimal betrag2Kinder; - - @Column(name = "betrag_3_kinder", nullable = false) - private BigDecimal betrag3Kinder; - - @Column(name = "betrag_4_kinder", nullable = false) - private BigDecimal betrag4Kinder; - - @Column(name = "betrag_5_kinder", nullable = false) - private BigDecimal betrag5Kinder; - - @Column(name = "betrag_6_kinder", nullable = false) - private BigDecimal betrag6Kinder; - - public Lektionsgebuehren() { - } - - public Lektionsgebuehren(Integer lektionslaenge, BigDecimal betrag1Kind, BigDecimal betrag2Kinder, BigDecimal betrag3Kinder, BigDecimal betrag4Kinder, BigDecimal betrag5Kinder, BigDecimal betrag6Kinder) { - this.lektionslaenge = lektionslaenge; - this.betrag1Kind = betrag1Kind; - this.betrag2Kinder = betrag2Kinder; - this.betrag3Kinder = betrag3Kinder; - this.betrag4Kinder = betrag4Kinder; - this.betrag5Kinder = betrag5Kinder; - this.betrag6Kinder = betrag6Kinder; - } - - public boolean isIdenticalWith(Lektionsgebuehren otherLektionsgebuehren) { - return otherLektionsgebuehren != null - && (lektionslaenge.equals(otherLektionsgebuehren.lektionslaenge)); - } - - public void copyAttributesFrom(Lektionsgebuehren otherLektionslaengen) { - this.betrag1Kind = otherLektionslaengen.betrag1Kind; - this.betrag2Kinder = otherLektionslaengen.betrag2Kinder; - this.betrag3Kinder = otherLektionslaengen.betrag3Kinder; - this.betrag4Kinder = otherLektionslaengen.betrag4Kinder; - this.betrag5Kinder = otherLektionslaengen.betrag5Kinder; - this.betrag6Kinder = otherLektionslaengen.betrag6Kinder; - } - - @Override - public int compareTo(Lektionsgebuehren otherLektionsgebuehren) { - return lektionslaenge.compareTo(otherLektionsgebuehren.getLektionslaenge()); - } - - public Integer getLektionslaenge() { - return lektionslaenge; - } - - public void setLektionslaenge(Integer lektionslaenge) { - this.lektionslaenge = lektionslaenge; - } - - public BigDecimal getBetrag1Kind() { - return betrag1Kind; - } - - public void setBetrag1Kind(BigDecimal betrag1Kind) { - this.betrag1Kind = betrag1Kind; - } - - public BigDecimal getBetrag2Kinder() { - return betrag2Kinder; - } - - public void setBetrag2Kinder(BigDecimal betrag2Kinder) { - this.betrag2Kinder = betrag2Kinder; - } - - public BigDecimal getBetrag3Kinder() { - return betrag3Kinder; - } - - public void setBetrag3Kinder(BigDecimal betrag3Kinder) { - this.betrag3Kinder = betrag3Kinder; - } - - public BigDecimal getBetrag4Kinder() { - return betrag4Kinder; - } - - public void setBetrag4Kinder(BigDecimal betrag4Kinder) { - this.betrag4Kinder = betrag4Kinder; - } - - public BigDecimal getBetrag5Kinder() { - return betrag5Kinder; - } - - public void setBetrag5Kinder(BigDecimal betrag5Kinder) { - this.betrag5Kinder = betrag5Kinder; - } - - public BigDecimal getBetrag6Kinder() { - return betrag6Kinder; - } - - public void setBetrag6Kinder(BigDecimal betrag6Kinder) { - this.betrag6Kinder = betrag6Kinder; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/old/Lektionsgebuehren.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/old/Lektionsgebuehren.java deleted file mode 100755 index f53a54a..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/old/Lektionsgebuehren.java +++ /dev/null @@ -1,130 +0,0 @@ -package ch.metzenthin.svm.persistence.entities; - -import javax.persistence.*; -import java.math.BigDecimal; -import java.sql.Timestamp; - -/** - * @author Martin Schraner - */ -@Entity -@Table(name="Lektionsgebuehren") -public class Lektionsgebuehren implements Comparable { - - public static int MAX_KINDER = 6; - public static int MIN_ANZAHL_TAGE_SECHS_JAHRES_RABATT = 2125; // 5 Jahre und 10 Monate - - @Id - @Column(name = "lektionslaenge") - private Integer lektionslaenge; - - @Version - @Column(name = "last_updated") - private Timestamp version; - - @Column(name = "betrag_1_kind", nullable = false) - private BigDecimal betrag1Kind; - - @Column(name = "betrag_2_kinder", nullable = false) - private BigDecimal betrag2Kinder; - - @Column(name = "betrag_3_kinder", nullable = false) - private BigDecimal betrag3Kinder; - - @Column(name = "betrag_4_kinder", nullable = false) - private BigDecimal betrag4Kinder; - - @Column(name = "betrag_5_kinder", nullable = false) - private BigDecimal betrag5Kinder; - - @Column(name = "betrag_6_kinder", nullable = false) - private BigDecimal betrag6Kinder; - - public Lektionsgebuehren() { - } - - public Lektionsgebuehren(Integer lektionslaenge, BigDecimal betrag1Kind, BigDecimal betrag2Kinder, BigDecimal betrag3Kinder, BigDecimal betrag4Kinder, BigDecimal betrag5Kinder, BigDecimal betrag6Kinder) { - this.lektionslaenge = lektionslaenge; - this.betrag1Kind = betrag1Kind; - this.betrag2Kinder = betrag2Kinder; - this.betrag3Kinder = betrag3Kinder; - this.betrag4Kinder = betrag4Kinder; - this.betrag5Kinder = betrag5Kinder; - this.betrag6Kinder = betrag6Kinder; - } - - public boolean isIdenticalWith(Lektionsgebuehren otherLektionsgebuehren) { - return otherLektionsgebuehren != null - && (lektionslaenge.equals(otherLektionsgebuehren.lektionslaenge)); - } - - public void copyAttributesFrom(Lektionsgebuehren otherLektionslaengen) { - this.betrag1Kind = otherLektionslaengen.betrag1Kind; - this.betrag2Kinder = otherLektionslaengen.betrag2Kinder; - this.betrag3Kinder = otherLektionslaengen.betrag3Kinder; - this.betrag4Kinder = otherLektionslaengen.betrag4Kinder; - this.betrag5Kinder = otherLektionslaengen.betrag5Kinder; - this.betrag6Kinder = otherLektionslaengen.betrag6Kinder; - } - - @Override - public int compareTo(Lektionsgebuehren otherLektionsgebuehren) { - return lektionslaenge.compareTo(otherLektionsgebuehren.getLektionslaenge()); - } - - public Integer getLektionslaenge() { - return lektionslaenge; - } - - public void setLektionslaenge(Integer lektionslaenge) { - this.lektionslaenge = lektionslaenge; - } - - public BigDecimal getBetrag1Kind() { - return betrag1Kind; - } - - public void setBetrag1Kind(BigDecimal betrag1Kind) { - this.betrag1Kind = betrag1Kind; - } - - public BigDecimal getBetrag2Kinder() { - return betrag2Kinder; - } - - public void setBetrag2Kinder(BigDecimal betrag2Kinder) { - this.betrag2Kinder = betrag2Kinder; - } - - public BigDecimal getBetrag3Kinder() { - return betrag3Kinder; - } - - public void setBetrag3Kinder(BigDecimal betrag3Kinder) { - this.betrag3Kinder = betrag3Kinder; - } - - public BigDecimal getBetrag4Kinder() { - return betrag4Kinder; - } - - public void setBetrag4Kinder(BigDecimal betrag4Kinder) { - this.betrag4Kinder = betrag4Kinder; - } - - public BigDecimal getBetrag5Kinder() { - return betrag5Kinder; - } - - public void setBetrag5Kinder(BigDecimal betrag5Kinder) { - this.betrag5Kinder = betrag5Kinder; - } - - public BigDecimal getBetrag6Kinder() { - return betrag6Kinder; - } - - public void setBetrag6Kinder(BigDecimal betrag6Kinder) { - this.betrag6Kinder = betrag6Kinder; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/pair.info deleted file mode 100755 index 6d17ced..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49775/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:49775 -comSha:cc2d290957ef455bcd6eba3753bf48f2ce6c1fe1 -parentComSha:c702f681925afb2181cd9b518ea90700aa3e3ce8 -BuggyFilePath:src/main/java/ch/metzenthin/svm/persistence/entities/Lektionsgebuehren.java -FixedFilePath:src/main/java/ch/metzenthin/svm/persistence/entities/Lektionsgebuehren.java -StartLineNum:14 -EndLineNum:14 -repoName:marschraner#svm \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/comMsg.txt deleted file mode 100755 index 56c8246..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Korrekturen Findbugs-Warnungen \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/diff.diff deleted file mode 100755 index 0434291..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/ch/metzenthin/svm/common/utils/SvmProperties.java b/src/main/java/ch/metzenthin/svm/common/utils/SvmProperties.java -index 1f86c1b..26298fa 100644 ---- a/src/main/java/ch/metzenthin/svm/common/utils/SvmProperties.java -+++ b/src/main/java/ch/metzenthin/svm/common/utils/SvmProperties.java -@@ -15,4 +15,4 @@ public class SvmProperties { -- public static String SVM_PROPERTIES_FILE_NAME = System.getProperty("user.home") + File.separator + ".svm"; -- public static String KEY_TEMPLATES_DIRECTORY = "templates_directory"; -- public static String KEY_DEFAULT_OUTPUT_DIRECTORY = "default_output_directory"; -- public static String KEY_ABSENZENLISTE_TEMPLATE = "absenzenlisten_template"; -+ public static final String SVM_PROPERTIES_FILE_NAME = System.getProperty("user.home") + File.separator + ".svm"; -+ public static final String KEY_TEMPLATES_DIRECTORY = "templates_directory"; -+ public static final String KEY_DEFAULT_OUTPUT_DIRECTORY = "default_output_directory"; -+ public static final String KEY_ABSENZENLISTE_TEMPLATE = "absenzenlisten_template"; \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/new/SvmProperties.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/new/SvmProperties.java deleted file mode 100755 index 26298fa..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/new/SvmProperties.java +++ /dev/null @@ -1,61 +0,0 @@ -package ch.metzenthin.svm.common.utils; - -import java.io.*; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Properties; -import java.util.TreeSet; - - -/** - * @author Martin Schraner - */ -public class SvmProperties { - - public static final String SVM_PROPERTIES_FILE_NAME = System.getProperty("user.home") + File.separator + ".svm"; - public static final String KEY_TEMPLATES_DIRECTORY = "templates_directory"; - public static final String KEY_DEFAULT_OUTPUT_DIRECTORY = "default_output_directory"; - public static final String KEY_ABSENZENLISTE_TEMPLATE = "absenzenlisten_template"; - - public static void createSvmPropertiesFileDefault() { - - Properties prop = new Properties() { - // Alphabetische statt zufällige Sortierung der Properties-Einträge - @Override - public synchronized Enumeration keys() { - return Collections.enumeration(new TreeSet<>(super.keySet())); - } - }; - - OutputStream propertiesFile; - File f = new File(SVM_PROPERTIES_FILE_NAME); - if (!f.exists()) { - try { - propertiesFile = new FileOutputStream(SVM_PROPERTIES_FILE_NAME); - - // set the properties value - prop.setProperty(KEY_TEMPLATES_DIRECTORY, System.getProperty("user.dir") + File.separator + "Listen-Templates"); - prop.setProperty(KEY_DEFAULT_OUTPUT_DIRECTORY, System.getProperty("user.home") + File.separator + "Desktop"); - prop.setProperty(KEY_ABSENZENLISTE_TEMPLATE, "" + File.separator + "Semester_" + File.separator + "Absenzenliste-Template___.docx"); - prop.store(propertiesFile, null); - - propertiesFile.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - public static Properties getSvmProperties() { - Properties prop = new Properties(); - InputStream propertiesFile; - try { - propertiesFile = new FileInputStream(SVM_PROPERTIES_FILE_NAME); - prop.load(propertiesFile); - propertiesFile.close(); - } catch (IOException ex) { - throw new RuntimeException(); - } - return prop; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/old/SvmProperties.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/old/SvmProperties.java deleted file mode 100755 index 1f86c1b..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/old/SvmProperties.java +++ /dev/null @@ -1,61 +0,0 @@ -package ch.metzenthin.svm.common.utils; - -import java.io.*; -import java.util.Collections; -import java.util.Enumeration; -import java.util.Properties; -import java.util.TreeSet; - - -/** - * @author Martin Schraner - */ -public class SvmProperties { - - public static String SVM_PROPERTIES_FILE_NAME = System.getProperty("user.home") + File.separator + ".svm"; - public static String KEY_TEMPLATES_DIRECTORY = "templates_directory"; - public static String KEY_DEFAULT_OUTPUT_DIRECTORY = "default_output_directory"; - public static String KEY_ABSENZENLISTE_TEMPLATE = "absenzenlisten_template"; - - public static void createSvmPropertiesFileDefault() { - - Properties prop = new Properties() { - // Alphabetische statt zufällige Sortierung der Properties-Einträge - @Override - public synchronized Enumeration keys() { - return Collections.enumeration(new TreeSet<>(super.keySet())); - } - }; - - OutputStream propertiesFile; - File f = new File(SVM_PROPERTIES_FILE_NAME); - if (!f.exists()) { - try { - propertiesFile = new FileOutputStream(SVM_PROPERTIES_FILE_NAME); - - // set the properties value - prop.setProperty(KEY_TEMPLATES_DIRECTORY, System.getProperty("user.dir") + File.separator + "Listen-Templates"); - prop.setProperty(KEY_DEFAULT_OUTPUT_DIRECTORY, System.getProperty("user.home") + File.separator + "Desktop"); - prop.setProperty(KEY_ABSENZENLISTE_TEMPLATE, "" + File.separator + "Semester_" + File.separator + "Absenzenliste-Template___.docx"); - prop.store(propertiesFile, null); - - propertiesFile.close(); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - } - - public static Properties getSvmProperties() { - Properties prop = new Properties(); - InputStream propertiesFile; - try { - propertiesFile = new FileInputStream(SVM_PROPERTIES_FILE_NAME); - prop.load(propertiesFile); - propertiesFile.close(); - } catch (IOException ex) { - throw new RuntimeException(); - } - return prop; - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/pair.info deleted file mode 100755 index 9320e61..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49805/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:49805 -comSha:6fa32cd4c13b970ab3d7f950b43635b667300523 -parentComSha:b56497192e2af8845af2aae017f2485aa14b9702 -BuggyFilePath:src/main/java/ch/metzenthin/svm/common/utils/SvmProperties.java -FixedFilePath:src/main/java/ch/metzenthin/svm/common/utils/SvmProperties.java -StartLineNum:18 -EndLineNum:18 -repoName:marschraner#svm \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/comMsg.txt deleted file mode 100755 index 3c5a04b..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix FindBugs Warnings \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/diff.diff deleted file mode 100755 index 41e5e3a..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/ch/metzenthin/svm/dataTypes/Schuljahre.java b/src/main/java/ch/metzenthin/svm/dataTypes/Schuljahre.java -index 9c06417..d79464c 100644 ---- a/src/main/java/ch/metzenthin/svm/dataTypes/Schuljahre.java -+++ b/src/main/java/ch/metzenthin/svm/dataTypes/Schuljahre.java -@@ -8,2 +8,2 @@ public class Schuljahre { -- public static int SCHULJAHR_VALID_MIN = 2000; -- public static int SCHULJAHR_VALID_MAX = 2049; -+ public final static int SCHULJAHR_VALID_MIN = 2000; -+ public final static int SCHULJAHR_VALID_MAX = 2049; \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/new/Schuljahre.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/new/Schuljahre.java deleted file mode 100755 index d79464c..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/new/Schuljahre.java +++ /dev/null @@ -1,27 +0,0 @@ -package ch.metzenthin.svm.dataTypes; - -/** - * @author Martin Schraner - */ -public class Schuljahre { - - public final static int SCHULJAHR_VALID_MIN = 2000; - public final static int SCHULJAHR_VALID_MAX = 2049; - - public String[] getSchuljahre() { - String[] schuljahre = new String[SCHULJAHR_VALID_MAX - SCHULJAHR_VALID_MIN + 1]; - for (int i = 0; i < SCHULJAHR_VALID_MAX - SCHULJAHR_VALID_MIN; i++) { - int schuljahr1 = SCHULJAHR_VALID_MIN + i; - int schuljahr2 = schuljahr1 + 1; - schuljahre[i] = schuljahr1 + "/" + schuljahr2; - } - return schuljahre; - } - - public static String getPreviousSchuljahr(String schuljahr) { - int schuljahr1 = Integer.parseInt(schuljahr.substring(0, 4)) - 1; - int schuljahr2 = Integer.parseInt(schuljahr.substring(5, 9)) - 1; - return schuljahr1 + "/" + schuljahr2; - } - -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/old/Schuljahre.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/old/Schuljahre.java deleted file mode 100755 index 9c06417..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/old/Schuljahre.java +++ /dev/null @@ -1,27 +0,0 @@ -package ch.metzenthin.svm.dataTypes; - -/** - * @author Martin Schraner - */ -public class Schuljahre { - - public static int SCHULJAHR_VALID_MIN = 2000; - public static int SCHULJAHR_VALID_MAX = 2049; - - public String[] getSchuljahre() { - String[] schuljahre = new String[SCHULJAHR_VALID_MAX - SCHULJAHR_VALID_MIN + 1]; - for (int i = 0; i < SCHULJAHR_VALID_MAX - SCHULJAHR_VALID_MIN; i++) { - int schuljahr1 = SCHULJAHR_VALID_MIN + i; - int schuljahr2 = schuljahr1 + 1; - schuljahre[i] = schuljahr1 + "/" + schuljahr2; - } - return schuljahre; - } - - public static String getPreviousSchuljahr(String schuljahr) { - int schuljahr1 = Integer.parseInt(schuljahr.substring(0, 4)) - 1; - int schuljahr2 = Integer.parseInt(schuljahr.substring(5, 9)) - 1; - return schuljahr1 + "/" + schuljahr2; - } - -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/pair.info deleted file mode 100755 index 0e8d012..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#49835/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:49835 -comSha:18358c8ffb57fcaa923bbb0339f50ae4aae36e44 -parentComSha:ab95dcff5dcaca38352994434821089dad7469dd -BuggyFilePath:src/main/java/ch/metzenthin/svm/dataTypes/Schuljahre.java -FixedFilePath:src/main/java/ch/metzenthin/svm/dataTypes/Schuljahre.java -StartLineNum:8 -EndLineNum:8 -repoName:marschraner#svm \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/comMsg.txt deleted file mode 100755 index a3dd108..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/comMsg.txt +++ /dev/null @@ -1,4 +0,0 @@ -- constants should be final - - -git-svn-id: https://svn.apache.org/repos/asf/incubator/vxquery/trunk/vxquery@885616 13f79535-47bb-0310-9956-ffa450edef68 \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/diff.diff deleted file mode 100755 index 1d28f84..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/org/apache/vxquery/datamodel/atomic/IntegerValue.java b/src/main/java/org/apache/vxquery/datamodel/atomic/IntegerValue.java -index 20187ade..0c7f77ec 100644 ---- a/src/main/java/org/apache/vxquery/datamodel/atomic/IntegerValue.java -+++ b/src/main/java/org/apache/vxquery/datamodel/atomic/IntegerValue.java -@@ -27,2 +27,2 @@ public class IntegerValue extends NumericValue { -- public static IntegerValue ZERO = new IntegerValue(BigInteger.ZERO); -- public static IntegerValue ONE = new IntegerValue(BigInteger.ONE); -+ public static final IntegerValue ZERO = new IntegerValue(BigInteger.ZERO); -+ public static final IntegerValue ONE = new IntegerValue(BigInteger.ONE); \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/new/IntegerValue.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/new/IntegerValue.java deleted file mode 100755 index 0c7f77e..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/new/IntegerValue.java +++ /dev/null @@ -1,82 +0,0 @@ -/* -* 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.vxquery.datamodel.atomic; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import org.apache.vxquery.types.AtomicType; -import org.apache.vxquery.types.BuiltinTypeRegistry; - -public class IntegerValue extends NumericValue { - - public static final IntegerValue ZERO = new IntegerValue(BigInteger.ZERO); - public static final IntegerValue ONE = new IntegerValue(BigInteger.ONE); - - IntegerValue(BigInteger value) { - super(value, BuiltinTypeRegistry.XS_INTEGER); - } - - public IntegerValue(BigInteger value, AtomicType type) { - super(value, type); - } - - @Override - public int sign() { - return ((BigInteger) value).signum(); - } - - @Override - public NumericValue negate() { - return new IntegerValue(((BigInteger) value).negate()); - } - - @Override - public NumericValue ceiling() { - return this; - } - - @Override - public NumericValue floor() { - return this; - } - - @Override - public NumericValue round() { - return this; - } - - @Override - public NumericValue roundHalfToEven(IntegerValue precision) { - return this; - } - - @Override - public BigInteger getIntegerValue() { - return (BigInteger) value; - } - - @Override - public BigDecimal getDecimalValue() { - return new BigDecimal((BigInteger) value); - } - - @Override - public String toString() { - return "[INTEGER_VALUE " + value + "]"; - } -} \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/old/IntegerValue.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/old/IntegerValue.java deleted file mode 100755 index 20187ad..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/old/IntegerValue.java +++ /dev/null @@ -1,82 +0,0 @@ -/* -* 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.vxquery.datamodel.atomic; - -import java.math.BigDecimal; -import java.math.BigInteger; - -import org.apache.vxquery.types.AtomicType; -import org.apache.vxquery.types.BuiltinTypeRegistry; - -public class IntegerValue extends NumericValue { - - public static IntegerValue ZERO = new IntegerValue(BigInteger.ZERO); - public static IntegerValue ONE = new IntegerValue(BigInteger.ONE); - - IntegerValue(BigInteger value) { - super(value, BuiltinTypeRegistry.XS_INTEGER); - } - - public IntegerValue(BigInteger value, AtomicType type) { - super(value, type); - } - - @Override - public int sign() { - return ((BigInteger) value).signum(); - } - - @Override - public NumericValue negate() { - return new IntegerValue(((BigInteger) value).negate()); - } - - @Override - public NumericValue ceiling() { - return this; - } - - @Override - public NumericValue floor() { - return this; - } - - @Override - public NumericValue round() { - return this; - } - - @Override - public NumericValue roundHalfToEven(IntegerValue precision) { - return this; - } - - @Override - public BigInteger getIntegerValue() { - return (BigInteger) value; - } - - @Override - public BigDecimal getDecimalValue() { - return new BigDecimal((BigInteger) value); - } - - @Override - public String toString() { - return "[INTEGER_VALUE " + value + "]"; - } -} \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/pair.info deleted file mode 100755 index 61cea37..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#55464/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:55464 -comSha:1324ead1f346c116123ab7666e0337e1b52185fd -parentComSha:4640d33882fd8110b987589441afc13f2bbaa54f -BuggyFilePath:src/main/java/org/apache/vxquery/datamodel/atomic/IntegerValue.java -FixedFilePath:src/main/java/org/apache/vxquery/datamodel/atomic/IntegerValue.java -StartLineNum:27 -EndLineNum:27 -repoName:apache#vxquery \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/comMsg.txt deleted file mode 100755 index e5534c8..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Entity updates - added preSnapshot() method and some chunk update stuff - -Signed-off-by: Raphfrk \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/diff.diff deleted file mode 100755 index 621d2df..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/src/main/java/org/getspout/api/geo/cuboid/Chunk.java b/src/main/java/org/getspout/api/geo/cuboid/Chunk.java -index 945165c3c..142a09931 100644 ---- a/src/main/java/org/getspout/api/geo/cuboid/Chunk.java -+++ b/src/main/java/org/getspout/api/geo/cuboid/Chunk.java -@@ -15 +15 @@ public abstract class Chunk extends Cube implements BlockAccess { -- public static int CHUNK_SIZE = 16; -+ public final static int CHUNK_SIZE = 16; -@@ -20 +20 @@ public abstract class Chunk extends Cube implements BlockAccess { -- public static int CHUNK_SIZE_BITS = 4; -+ public final static int CHUNK_SIZE_BITS = 4; -@@ -27 +27 @@ public abstract class Chunk extends Cube implements BlockAccess { -- * Performs the nessecary tasks to unload this chunk from the world. -+ * Performs the necessary tasks to unload this chunk from the world. -@@ -31,0 +32 @@ public abstract class Chunk extends Cube implements BlockAccess { -+ \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/new/Chunk.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/new/Chunk.java deleted file mode 100755 index 142a099..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/new/Chunk.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.getspout.api.geo.cuboid; - -import org.getspout.api.geo.BlockAccess; -import org.getspout.api.geo.World; -import org.getspout.api.geo.discrete.Point; - -/** - * Represents a cube containing 16x16x16 Blocks - */ -public abstract class Chunk extends Cube implements BlockAccess { - - /** - * Internal size of a side of a chunk - */ - public final static int CHUNK_SIZE = 16; - - /** - * Number of bits on the side of a chunk - */ - public final static int CHUNK_SIZE_BITS = 4; - - public Chunk(World world, float x, float y, float z) { - super(new Point(world, x, y, z), CHUNK_SIZE); - } - - /** - * Performs the necessary tasks to unload this chunk from the world. - * - * @param save whether the chunk data should be saved. - */ - public abstract void unload(boolean save); - -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/old/Chunk.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/old/Chunk.java deleted file mode 100755 index 945165c..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/old/Chunk.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.getspout.api.geo.cuboid; - -import org.getspout.api.geo.BlockAccess; -import org.getspout.api.geo.World; -import org.getspout.api.geo.discrete.Point; - -/** - * Represents a cube containing 16x16x16 Blocks - */ -public abstract class Chunk extends Cube implements BlockAccess { - - /** - * Internal size of a side of a chunk - */ - public static int CHUNK_SIZE = 16; - - /** - * Number of bits on the side of a chunk - */ - public static int CHUNK_SIZE_BITS = 4; - - public Chunk(World world, float x, float y, float z) { - super(new Point(world, x, y, z), CHUNK_SIZE); - } - - /** - * Performs the nessecary tasks to unload this chunk from the world. - * - * @param save whether the chunk data should be saved. - */ - public abstract void unload(boolean save); -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/pair.info deleted file mode 100755 index 680c2db..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#82531/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:82531 -comSha:b2caaabbd868204d7dce286bbc7a177e642cbfc8 -parentComSha:9b44afd555452a77094100f19920cad4e8d757e7 -BuggyFilePath:src/main/java/org/getspout/api/geo/cuboid/Chunk.java -FixedFilePath:src/main/java/org/getspout/api/geo/cuboid/Chunk.java -StartLineNum:15 -EndLineNum:15 -repoName:SpoutDev#Spout \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/comMsg.txt b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/comMsg.txt deleted file mode 100755 index 98d9deb..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -sorted a few necessary and unnecessary finals \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/diff.diff b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/diff.diff deleted file mode 100755 index f13abb9..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/diff.diff +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/oboformat/src/main/java/org/obolibrary/obo2owl/OWLAPIOwl2Obo.java b/oboformat/src/main/java/org/obolibrary/obo2owl/OWLAPIOwl2Obo.java -index 22fd4a2e4..a252802e6 100644 ---- a/oboformat/src/main/java/org/obolibrary/obo2owl/OWLAPIOwl2Obo.java -+++ b/oboformat/src/main/java/org/obolibrary/obo2owl/OWLAPIOwl2Obo.java -@@ -17 +16,0 @@ import java.util.Set; --import java.util.Vector; -@@ -101 +100,2 @@ public class OWLAPIOwl2Obo { -- private static Logger LOG = LoggerFactory.getLogger(OWLAPIOwl2Obo.class); -+ private static final Logger LOG = LoggerFactory -+ .getLogger(OWLAPIOwl2Obo.class); -@@ -135 +135 @@ public class OWLAPIOwl2Obo { -- public static Map annotationPropertyMap = initAnnotationPropertyMap(); -+ public static final Map annotationPropertyMap = initAnnotationPropertyMap(); -@@ -1519 +1519,2 @@ public class OWLAPIOwl2Obo { -- } else if (!f.getClauses(OboFormatTag.TAG_INTERSECTION_OF).isEmpty()) { -+ } else if (!f.getClauses(OboFormatTag.TAG_INTERSECTION_OF) -+ .isEmpty()) { \ No newline at end of file diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/new/OWLAPIOwl2Obo.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/new/OWLAPIOwl2Obo.java deleted file mode 100755 index a252802..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/new/OWLAPIOwl2Obo.java +++ /dev/null @@ -1,2389 +0,0 @@ -package org.obolibrary.obo2owl; - -import static org.semanticweb.owlapi.model.parameters.Imports.INCLUDED; -import static org.semanticweb.owlapi.search.Searcher.annotations; -import static org.semanticweb.owlapi.util.OWLAPIPreconditions.verifyNotNull; - -import java.io.UnsupportedEncodingException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import org.obolibrary.obo2owl.Obo2OWLConstants.Obo2OWLVocabulary; -import org.obolibrary.obo2owl.OwlStringTools.OwlStringException; -import org.obolibrary.oboformat.model.Clause; -import org.obolibrary.oboformat.model.Frame; -import org.obolibrary.oboformat.model.Frame.FrameType; -import org.obolibrary.oboformat.model.OBODoc; -import org.obolibrary.oboformat.model.QualifierValue; -import org.obolibrary.oboformat.model.Xref; -import org.obolibrary.oboformat.parser.OBOFormatConstants; -import org.obolibrary.oboformat.parser.OBOFormatConstants.OboFormatTag; -import org.semanticweb.owlapi.model.AxiomType; -import org.semanticweb.owlapi.model.IRI; -import org.semanticweb.owlapi.model.OWLAnnotation; -import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; -import org.semanticweb.owlapi.model.OWLAnnotationProperty; -import org.semanticweb.owlapi.model.OWLAnnotationValue; -import org.semanticweb.owlapi.model.OWLAsymmetricObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLAxiom; -import org.semanticweb.owlapi.model.OWLClass; -import org.semanticweb.owlapi.model.OWLClassAssertionAxiom; -import org.semanticweb.owlapi.model.OWLClassExpression; -import org.semanticweb.owlapi.model.OWLDataFactory; -import org.semanticweb.owlapi.model.OWLDatatype; -import org.semanticweb.owlapi.model.OWLDeclarationAxiom; -import org.semanticweb.owlapi.model.OWLDisjointClassesAxiom; -import org.semanticweb.owlapi.model.OWLDisjointObjectPropertiesAxiom; -import org.semanticweb.owlapi.model.OWLEntity; -import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom; -import org.semanticweb.owlapi.model.OWLEquivalentObjectPropertiesAxiom; -import org.semanticweb.owlapi.model.OWLFunctionalObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLInverseFunctionalObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLInverseObjectPropertiesAxiom; -import org.semanticweb.owlapi.model.OWLLiteral; -import org.semanticweb.owlapi.model.OWLNamedIndividual; -import org.semanticweb.owlapi.model.OWLNamedObject; -import org.semanticweb.owlapi.model.OWLNaryPropertyAxiom; -import org.semanticweb.owlapi.model.OWLObject; -import org.semanticweb.owlapi.model.OWLObjectAllValuesFrom; -import org.semanticweb.owlapi.model.OWLObjectCardinalityRestriction; -import org.semanticweb.owlapi.model.OWLObjectComplementOf; -import org.semanticweb.owlapi.model.OWLObjectExactCardinality; -import org.semanticweb.owlapi.model.OWLObjectIntersectionOf; -import org.semanticweb.owlapi.model.OWLObjectMaxCardinality; -import org.semanticweb.owlapi.model.OWLObjectMinCardinality; -import org.semanticweb.owlapi.model.OWLObjectProperty; -import org.semanticweb.owlapi.model.OWLObjectPropertyDomainAxiom; -import org.semanticweb.owlapi.model.OWLObjectPropertyExpression; -import org.semanticweb.owlapi.model.OWLObjectPropertyRangeAxiom; -import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom; -import org.semanticweb.owlapi.model.OWLObjectUnionOf; -import org.semanticweb.owlapi.model.OWLOntology; -import org.semanticweb.owlapi.model.OWLOntologyManager; -import org.semanticweb.owlapi.model.OWLQuantifiedObjectRestriction; -import org.semanticweb.owlapi.model.OWLReflexiveObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLSubAnnotationPropertyOfAxiom; -import org.semanticweb.owlapi.model.OWLSubClassOfAxiom; -import org.semanticweb.owlapi.model.OWLSubObjectPropertyOfAxiom; -import org.semanticweb.owlapi.model.OWLSubPropertyChainOfAxiom; -import org.semanticweb.owlapi.model.OWLSymmetricObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLTransitiveObjectPropertyAxiom; -import org.semanticweb.owlapi.search.Filters; -import org.semanticweb.owlapi.vocab.Namespaces; -import org.semanticweb.owlapi.vocab.OWL2Datatype; -import org.semanticweb.owlapi.vocab.OWLRDFVocabulary; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Optional; - -/** - * The Class OWLAPIOwl2Obo. - */ -public class OWLAPIOwl2Obo { - - /** - * The log. - */ - private static final Logger LOG = LoggerFactory - .getLogger(OWLAPIOwl2Obo.class); - private static final String IRI_CLASS_SYNONYMTYPEDEF = Obo2OWLConstants.DEFAULT_IRI_PREFIX - + "IAO_synonymtypedef"; - private static final String IRI_CLASS_SUBSETDEF = Obo2OWLConstants.DEFAULT_IRI_PREFIX - + "IAO_subsetdef"; - /** - * The manager. - */ - @Nonnull - protected OWLOntologyManager manager; - /** - * The owl ontology. - */ - protected OWLOntology owlOntology; - /** - * The fac. - */ - protected OWLDataFactory fac; - /** - * The obodoc. - */ - protected OBODoc obodoc; - /** - * The untranslatable axioms. - */ - protected Set untranslatableAxioms; - /** - * The id space map. - */ - protected Map idSpaceMap; - /** - * The annotation property map. - */ - @Nonnull - public static final Map annotationPropertyMap = initAnnotationPropertyMap(); - /** - * The ap to declare. - */ - protected Set apToDeclare; - /** - * The ontology id. - */ - protected String ontologyId; - /** - * The strict conversion. - */ - protected boolean strictConversion; - /** - * The discard untranslatable. - */ - protected boolean discardUntranslatable = false; - /** - * mute untranslatable axiom warnings - */ - private boolean muteUntranslatableAxioms = false; - - /** - * Inits the. - */ - protected void init() { - idSpaceMap = new HashMap(); - // legacy: - idSpaceMap.put("http://www.obofoundry.org/ro/ro.owl#", "OBO_REL"); - untranslatableAxioms = new HashSet(); - fac = manager.getOWLDataFactory(); - apToDeclare = new HashSet(); - } - - /** - * Instantiates a new oWLAPI owl2 obo. - * - * @param translationManager - * the translation manager - */ - public OWLAPIOwl2Obo(@Nonnull OWLOntologyManager translationManager) { - manager = translationManager; - init(); - } - - /** - * Inits the annotation property map. - * - * @return the hash map - */ - @Nonnull - protected static HashMap initAnnotationPropertyMap() { - HashMap map = new HashMap(); - for (String key : OWLAPIObo2Owl.annotationPropertyMap.keySet()) { - IRI propIRI = OWLAPIObo2Owl.annotationPropertyMap.get(key); - map.put(propIRI.toString(), key); - } - return map; - } - - /** - * Sets the strict conversion. - * - * @param b - * the new strict conversion - */ - public void setStrictConversion(boolean b) { - strictConversion = b; - } - - /** - * Gets the strict conversion. - * - * @return the strict conversion - */ - public boolean getStrictConversion() { - return strictConversion; - } - - /** - * Checks if is discard untranslatable. - * - * @return the discardUntranslatable - */ - public boolean isDiscardUntranslatable() { - return discardUntranslatable; - } - - /** - * Sets the discard untranslatable. - * - * @param discardUntranslatable - * the discardUntranslatable to set - */ - public void setDiscardUntranslatable(boolean discardUntranslatable) { - this.discardUntranslatable = discardUntranslatable; - } - - /** - * Gets the manager. - * - * @return the manager - */ - public OWLOntologyManager getManager() { - return manager; - } - - /** - * Sets the manager. - * - * @param manager - * the new manager - */ - public void setManager(@Nonnull OWLOntologyManager manager) { - this.manager = manager; - } - - /** - * Gets the obodoc. - * - * @return the obodoc - */ - @Nonnull - public OBODoc getObodoc() { - return verifyNotNull(obodoc); - } - - /** - * Sets the obodoc. - * - * @param obodoc - * the new obodoc - */ - public void setObodoc(@Nonnull OBODoc obodoc) { - this.obodoc = obodoc; - } - - /** - * Convert. - * - * @param ont - * the ont - * @return the oBO doc - */ - @Nonnull - public OBODoc convert(@Nonnull OWLOntology ont) { - owlOntology = ont; - ontologyId = getOntologyId(ont); - init(); - return tr(); - } - - @Nonnull - protected OWLOntology getOWLOntology() { - return verifyNotNull(owlOntology); - } - - /** - * Gets the untranslatable axioms. - * - * @return the untranslatableAxioms - */ - public Collection getUntranslatableAxioms() { - return untranslatableAxioms; - } - - /** - * Tr. - * - * @return the oBO doc - */ - @Nonnull - protected OBODoc tr() { - setObodoc(new OBODoc()); - preProcess(); - tr(getOWLOntology()); - for (OWLAxiom ax : getOWLOntology().getAxioms()) { - if (ax instanceof OWLDeclarationAxiom) { - tr((OWLDeclarationAxiom) ax); - } else if (ax instanceof OWLSubClassOfAxiom) { - tr((OWLSubClassOfAxiom) ax); - } else if (ax instanceof OWLDisjointClassesAxiom) { - tr((OWLDisjointClassesAxiom) ax); - } else if (ax instanceof OWLEquivalentClassesAxiom) { - tr((OWLEquivalentClassesAxiom) ax); - } else if (ax instanceof OWLClassAssertionAxiom) { - tr((OWLClassAssertionAxiom) ax); - } else if (ax instanceof OWLEquivalentObjectPropertiesAxiom) { - tr((OWLEquivalentObjectPropertiesAxiom) ax); - } else if (ax instanceof OWLSubAnnotationPropertyOfAxiom) { - tr((OWLSubAnnotationPropertyOfAxiom) ax); - } else if (ax instanceof OWLSubObjectPropertyOfAxiom) { - tr((OWLSubObjectPropertyOfAxiom) ax); - } else if (ax instanceof OWLObjectPropertyRangeAxiom) { - tr((OWLObjectPropertyRangeAxiom) ax); - } else if (ax instanceof OWLFunctionalObjectPropertyAxiom) { - tr((OWLFunctionalObjectPropertyAxiom) ax); - } else if (ax instanceof OWLSymmetricObjectPropertyAxiom) { - tr((OWLSymmetricObjectPropertyAxiom) ax); - } else if (ax instanceof OWLAsymmetricObjectPropertyAxiom) { - tr((OWLAsymmetricObjectPropertyAxiom) ax); - } else if (ax instanceof OWLObjectPropertyDomainAxiom) { - tr((OWLObjectPropertyDomainAxiom) ax); - } else if (ax instanceof OWLInverseFunctionalObjectPropertyAxiom) { - tr((OWLInverseFunctionalObjectPropertyAxiom) ax); - } else if (ax instanceof OWLInverseObjectPropertiesAxiom) { - tr((OWLInverseObjectPropertiesAxiom) ax); - } else if (ax instanceof OWLDisjointObjectPropertiesAxiom) { - tr((OWLDisjointObjectPropertiesAxiom) ax); - } else if (ax instanceof OWLReflexiveObjectPropertyAxiom) { - tr((OWLReflexiveObjectPropertyAxiom) ax); - } else if (ax instanceof OWLTransitiveObjectPropertyAxiom) { - tr((OWLTransitiveObjectPropertyAxiom) ax); - } else if (ax instanceof OWLSubPropertyChainOfAxiom) { - tr((OWLSubPropertyChainOfAxiom) ax); - } else { - if (!(ax instanceof OWLAnnotationAssertionAxiom)) { - error(ax, false); - } else { - // we presume this has been processed - } - } - } - if (untranslatableAxioms.isEmpty() == false - && discardUntranslatable == false) { - try { - String axiomString = OwlStringTools.translate( - untranslatableAxioms, manager); - if (axiomString != null) { - Frame headerFrame = getObodoc().getHeaderFrame(); - if (headerFrame == null) { - headerFrame = new Frame(FrameType.HEADER); - getObodoc().setHeaderFrame(headerFrame); - } - headerFrame.addClause(new Clause( - OboFormatTag.TAG_OWL_AXIOMS, axiomString)); - } - } catch (OwlStringException e) { - throw new RuntimeException(e); - } - } - return getObodoc(); - } - - /** - * Pre process. - */ - @SuppressWarnings("null") - protected void preProcess() { - // converse of postProcess in obo2owl - String viewRel = null; - for (OWLAnnotation ann : getOWLOntology().getAnnotations()) { - if (ann.getProperty() - .getIRI() - .equals(Obo2OWLVocabulary.IRI_OIO_LogicalDefinitionViewRelation - .getIRI())) { - OWLAnnotationValue v = ann.getValue(); - if (v instanceof OWLLiteral) { - viewRel = ((OWLLiteral) v).getLiteral(); - } else { - viewRel = getIdentifier((IRI) v); - } - break; - } - } - if (viewRel != null) { - // OWLObjectProperty vp = fac.getOWLObjectProperty(pIRI); - Set rmAxioms = new HashSet(); - Set newAxioms = new HashSet(); - for (OWLEquivalentClassesAxiom eca : getOWLOntology().getAxioms( - AxiomType.EQUIVALENT_CLASSES)) { - int numNamed = 0; - Set xs = new HashSet(); - for (OWLClassExpression x : eca.getClassExpressions()) { - if (x instanceof OWLClass) { - xs.add(x); - numNamed++; - continue; - } else if (x instanceof OWLObjectSomeValuesFrom) { - OWLObjectProperty p = (OWLObjectProperty) ((OWLObjectSomeValuesFrom) x) - .getProperty(); - if (this.getIdentifier(p).equals(viewRel) == false) { - LOG.error("Expected: {} got: {} in {}", viewRel, p, - eca); - } - xs.add(((OWLObjectSomeValuesFrom) x).getFiller()); - } else { - LOG.error("Unexpected: {}", eca); - } - } - if (numNamed == 1) { - rmAxioms.add(eca); - newAxioms.add(fac.getOWLEquivalentClassesAxiom(xs)); - } else { - LOG.error("ECA did not fit expected pattern: {}", eca); - } - } - manager.removeAxioms(getOWLOntology(), rmAxioms); - manager.addAxioms(getOWLOntology(), newAxioms); - } - } - - protected void add(@Nullable Frame f) { - if (f != null) { - try { - getObodoc().addFrame(f); - } catch (Exception ex) { - LOG.error(ex.getMessage(), ex); - } - } - } - - /** - * Tr object property. - * - * @param prop - * the prop - * @param tag - * the tag - * @param value - * the value - * @param annotations - * the annotations - * @return true, if successful - */ - @SuppressWarnings("null") - protected boolean trObjectProperty(@Nullable OWLObjectProperty prop, - @Nullable String tag, @Nullable String value, - @Nonnull Set annotations) { - if (prop == null || value == null) { - return false; - } - Frame f = getTypedefFrame(prop); - Clause clause; - if (OboFormatTag.TAG_ID.getTag().equals(tag)) { - clause = f.getClause(tag); - if (tag != null) { - clause.setValue(value); - } else { - clause = new Clause(tag, value); - f.addClause(clause); - } - } else { - clause = new Clause(tag, value); - f.addClause(clause); - } - addQualifiers(clause, annotations); - return true; - } - - /** - * Tr object property. - * - * @param prop - * the prop - * @param tag - * the tag - * @param value - * the value - * @param annotations - * the annotations - * @return true, if successful - */ - protected boolean trObjectProperty(@Nullable OWLObjectProperty prop, - String tag, @Nullable Boolean value, - @Nonnull Set annotations) { - if (prop == null || value == null) { - return false; - } - Frame f = getTypedefFrame(prop); - Clause clause = new Clause(tag); - clause.addValue(value); - f.addClause(clause); - addQualifiers(clause, annotations); - return true; - } - - /** - * Tr nary property axiom. - * - * @param ax - * the ax - * @param tag - * the tag - */ - protected void trNaryPropertyAxiom( - @Nonnull OWLNaryPropertyAxiom ax, - String tag) { - Set set = ax.getProperties(); - if (set.size() > 1) { - boolean first = true; - OWLObjectProperty prop = null; - String disjointFrom = null; - for (OWLObjectPropertyExpression ex : set) { - if (ex.isBottomEntity() || ex.isTopEntity()) { - error(tag - + " using Top or Bottom entities are not supported in OBO.", - ax, false); - return; - } - if (first) { - first = false; - if (ex instanceof OWLObjectProperty) { - prop = (OWLObjectProperty) ex; - } - } else { - disjointFrom = this.getIdentifier(ex); // getIdentifier(ex); - } - } - if (trObjectProperty(prop, tag, disjointFrom, ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLSubPropertyChainOfAxiom ax) { - OWLObjectPropertyExpression pEx = ax.getSuperProperty(); - if (pEx.isAnonymous()) { - error(ax, false); - return; - } - OWLObjectProperty p = pEx.asOWLObjectProperty(); - Frame f = getTypedefFrame(p); - if (p.isBottomEntity() || p.isTopEntity()) { - error("Property chains using Top or Bottom entities are not supported in OBO.", - ax, false); - return; - } - List list = ax.getPropertyChain(); - if (list.size() != 2) { - error(ax, false); - return; - } - OWLObjectPropertyExpression exp1 = list.get(0); - OWLObjectPropertyExpression exp2 = list.get(1); - if (exp1.isBottomEntity() || exp1.isTopEntity() - || exp2.isBottomEntity() || exp2.isTopEntity()) { - error("Property chains using Top or Bottom entities are not supported in OBO.", - ax, false); - return; - } - String rel1 = getIdentifier(exp1); - String rel2 = getIdentifier(exp2); - if (rel1 == null || rel2 == null) { - error(ax, false); - return; - } - Clause clause; - // set of unprocessed annotations - Set unprocessedAnnotations = new HashSet( - ax.getAnnotations()); - if (rel1.equals(f.getId())) { - clause = new Clause(OboFormatTag.TAG_TRANSITIVE_OVER, rel2); - } else { - OboFormatTag tag = OboFormatTag.TAG_HOLDS_OVER_CHAIN; - for (OWLAnnotation ann : ax.getAnnotations()) { - if (OWLAPIObo2Owl.IRI_PROP_isReversiblePropertyChain.equals(ann - .getProperty().getIRI().toString())) { - tag = OboFormatTag.TAG_EQUIVALENT_TO_CHAIN; - // remove annotation from unprocessed set. - unprocessedAnnotations.remove(ann); - break; - } - } - clause = new Clause(tag); - clause.addValue(rel1); - clause.addValue(rel2); - } - f.addClause(clause); - addQualifiers(clause, unprocessedAnnotations); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLEquivalentObjectPropertiesAxiom ax) { - trNaryPropertyAxiom(ax, OboFormatTag.TAG_EQUIVALENT_TO.getTag()); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLTransitiveObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_TRANSITIVE.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLDisjointObjectPropertiesAxiom ax) { - trNaryPropertyAxiom(ax, OboFormatTag.TAG_DISJOINT_FROM.getTag()); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLReflexiveObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_REFLEXIVE.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLInverseFunctionalObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_INVERSE_FUNCTIONAL.getTag(), - Boolean.TRUE, ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLInverseObjectPropertiesAxiom ax) { - OWLObjectPropertyExpression prop1 = ax.getFirstProperty(); - OWLObjectPropertyExpression prop2 = ax.getSecondProperty(); - if (prop1 instanceof OWLObjectProperty - && prop2 instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop1, - OboFormatTag.TAG_INVERSE_OF.getTag(), - this.getIdentifier(prop2), ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLObjectPropertyDomainAxiom ax) { - OWLClassExpression domain = ax.getDomain(); - OWLObjectPropertyExpression propEx = ax.getProperty(); - if (propEx.isAnonymous()) { - error(ax, true); - return; - } - OWLObjectProperty prop = propEx.asOWLObjectProperty(); - if (domain.isBottomEntity() || domain.isTopEntity()) { - // at least get the type def frame - getTypedefFrame(prop); - // now throw the error - error("domains using top or bottom entities are not translatable to OBO.", - ax, false); - return; - } - String range = this.getIdentifier(domain); - if (range != null) { - if (trObjectProperty(prop, OboFormatTag.TAG_DOMAIN.getTag(), range, - ax.getAnnotations())) { - return; - } else { - error("trObjectProperty failed for " + prop, ax, true); - } - } else { - error("no range translatable for " + ax, false); - } - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLAsymmetricObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_ASYMMETRIC.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLSymmetricObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_SYMMETRIC.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLFunctionalObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_FUNCTIONAL.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLObjectPropertyRangeAxiom ax) { - OWLClassExpression owlRange = ax.getRange(); - OWLObjectPropertyExpression propEx = ax.getProperty(); - if (propEx.isAnonymous()) { - error(ax, false); - } - OWLObjectProperty prop = propEx.asOWLObjectProperty(); - if (owlRange.isBottomEntity() || owlRange.isTopEntity()) { - // at least create the property frame - getTypedefFrame(prop); - // error message - error("ranges using top or bottom entities are not translatable to OBO.", - ax, false); - return; - } - String range = this.getIdentifier(owlRange); // getIdentifier(ax.getRange()); - if (range != null) { - if (trObjectProperty(prop, OboFormatTag.TAG_RANGE.getTag(), range, - ax.getAnnotations())) { - return; - } - } - error(ax, false); - } - - @SuppressWarnings("null") - protected void tr(@Nonnull OWLSubObjectPropertyOfAxiom ax) { - OWLObjectPropertyExpression sup = ax.getSuperProperty(); - OWLObjectPropertyExpression sub = ax.getSubProperty(); - if (sub.isBottomEntity() || sub.isTopEntity() || sup.isBottomEntity() - || sub.isTopEntity()) { - error("SubProperties using Top or Bottom entites are not supported in OBO.", - false); - return; - } - if (sub instanceof OWLObjectProperty - && sup instanceof OWLObjectProperty) { - String supId = this.getIdentifier(sup); - if (supId.startsWith("owl:")) { - return; - } - Frame f = getTypedefFrame((OWLObjectProperty) sub); - Clause clause = new Clause(OboFormatTag.TAG_IS_A, supId); - f.addClause(clause); - addQualifiers(clause, ax.getAnnotations()); - } else { - error(ax, true); - } - } - - @SuppressWarnings("null") - protected void tr(@Nonnull OWLSubAnnotationPropertyOfAxiom ax) { - OWLAnnotationProperty sup = ax.getSuperProperty(); - OWLAnnotationProperty sub = ax.getSubProperty(); - if (sub.isBottomEntity() || sub.isTopEntity() || sup.isBottomEntity() - || sub.isTopEntity()) { - error("SubAnnotationProperties using Top or Bottom entites are not supported in OBO.", - false); - return; - } - String _tag = owlObjectToTag(sup); - if (OboFormatTag.TAG_SYNONYMTYPEDEF.getTag().equals(_tag)) { - String name = ""; - String scope = null; - for (OWLAnnotationAssertionAxiom axiom : getOWLOntology() - .getAnnotationAssertionAxioms(sub.getIRI())) { - String tg = owlObjectToTag(axiom.getProperty()); - if (OboFormatTag.TAG_NAME.getTag().equals(tg)) { - name = ((OWLLiteral) axiom.getValue()).getLiteral(); - } else if (OboFormatTag.TAG_SCOPE.getTag().equals(tg)) { - scope = owlObjectToTag(axiom.getValue()); - } - } - Frame hf = getObodoc().getHeaderFrame(); - Clause clause = new Clause(OboFormatTag.TAG_SYNONYMTYPEDEF); - clause.addValue(this.getIdentifier(sub)); - clause.addValue(name); - if (scope != null) { - clause.addValue(scope); - } - addQualifiers(clause, ax.getAnnotations()); - if (!hf.getClauses().contains(clause)) { - hf.addClause(clause); - } else { - LOG.error("duplicate clause: {} in header", clause); - } - return; - } else if (OboFormatTag.TAG_SUBSETDEF.getTag().equals(_tag)) { - String comment = ""; - for (OWLAnnotationAssertionAxiom axiom : getOWLOntology() - .getAnnotationAssertionAxioms(sub.getIRI())) { - String tg = owlObjectToTag(axiom.getProperty()); - if (OboFormatTag.TAG_COMMENT.getTag().equals(tg)) { - comment = ((OWLLiteral) axiom.getValue()).getLiteral(); - break; - } - } - Frame hf = getObodoc().getHeaderFrame(); - Clause clause = new Clause(OboFormatTag.TAG_SUBSETDEF); - clause.addValue(this.getIdentifier(sub)); - clause.addValue(comment); - if (!hf.getClauses().contains(clause)) { - hf.addClause(clause); - } else { - LOG.error("duplicate clause: {} in header", clause); - } - addQualifiers(clause, ax.getAnnotations()); - return; - } - if (sub instanceof OWLObjectProperty - && sup instanceof OWLObjectProperty) { - String supId = this.getIdentifier(sup); // getIdentifier(sup); - if (supId.startsWith("owl:")) { - return; - } - Frame f = getTypedefFrame(sub); - Clause clause = new Clause(OboFormatTag.TAG_IS_A, supId); - f.addClause(clause); - addQualifiers(clause, ax.getAnnotations()); - } else { - error(ax, true); - } - } - - /** - * The absoulte url pattern. - */ - protected Pattern absoulteURLPattern = Pattern.compile("<\\s*http.*?>"); - - /** - * Tr. - * - * @param aanAx - * the aan ax - * @param frame - * the frame - */ - protected void tr(@Nonnull OWLAnnotationAssertionAxiom aanAx, - @Nonnull Frame frame) { - boolean success = tr(aanAx.getProperty(), aanAx.getValue(), - aanAx.getAnnotations(), frame); - if (!success) { - untranslatableAxioms.add(aanAx); - } - } - - /** - * Tr. - * - * @param prop - * the prop - * @param annVal - * the ann val - * @param qualifiers - * the qualifiers - * @param frame - * the frame - * @return true, if successful - */ - @SuppressWarnings("null") - protected boolean tr(OWLAnnotationProperty prop, - @Nonnull OWLAnnotationValue annVal, - @Nonnull Set qualifiers, @Nonnull Frame frame) { - String tagString = owlObjectToTag(prop); - OboFormatTag tag = null; - if (tagString != null) { - tag = OBOFormatConstants.getTag(tagString); - } - if (tag == null) { - // annotation property does not correspond to a mapping to a tag in - // the OBO syntax - - // use the property_value tag - return trGenericPropertyValue(prop, annVal, qualifiers, frame); - } - String value = getValue(annVal, tagString); - if (tagString == null) { - Clause clause = new Clause(OboFormatTag.TAG_PROPERTY_VALUE); - String propId = this.getIdentifier(prop); - addQualifiers(clause, qualifiers); - if (propId.equals("shorthand") == false) { - clause.addValue(propId); - clause.addValue(value); - // TODO - xsd types - frame.addClause(clause); - } - } else if (!value.trim().isEmpty()) { - if (tag == OboFormatTag.TAG_ID) { - if (frame.getId().equals(value) == false) { - warn("Conflicting id definitions: 1) " + frame.getId() - + " 2)" + value); - return false; - } - return true; - } - Clause clause = new Clause(tag); - if (tag == OboFormatTag.TAG_DATE) { - try { - clause.addValue(OBOFormatConstants.headerDateFormat.get() - .parseObject(value)); - } catch (ParseException e) { - error("Could not parse date string: " + value, true); - return false; - } - } else { - clause.addValue(value); - } - Set unprocessedQualifiers = new HashSet( - qualifiers); - if (tag == OboFormatTag.TAG_DEF) { - for (OWLAnnotation aan : qualifiers) { - String propId = owlObjectToTag(aan.getProperty()); - if ("xref".equals(propId)) { - OWLAnnotationValue v = aan.getValue(); - String xrefValue; - if (v instanceof IRI) { - xrefValue = ((IRI) v).toString(); - } else { - xrefValue = ((OWLLiteral) v).getLiteral(); - } - Xref xref = new Xref(xrefValue); - clause.addXref(xref); - unprocessedQualifiers.remove(aan); - } - } - } else if (tag == OboFormatTag.TAG_XREF) { - Xref xref = new Xref(value); - for (OWLAnnotation annotation : qualifiers) { - if (fac.getRDFSLabel().equals(annotation.getProperty())) { - OWLAnnotationValue owlAnnotationValue = annotation - .getValue(); - if (owlAnnotationValue instanceof OWLLiteral) { - unprocessedQualifiers.remove(annotation); - String xrefAnnotation = ((OWLLiteral) owlAnnotationValue) - .getLiteral(); - xrefAnnotation = xrefAnnotation.trim(); - if (!xrefAnnotation.isEmpty()) { - xref.setAnnotation(xrefAnnotation); - } - } - } - } - clause.setValue(xref); - } else if (tag == OboFormatTag.TAG_EXACT - || tag == OboFormatTag.TAG_NARROW - || tag == OboFormatTag.TAG_BROAD - || tag == OboFormatTag.TAG_RELATED) { - handleSynonym(qualifiers, tag.getTag(), clause, - unprocessedQualifiers); - } else if (tag == OboFormatTag.TAG_SYNONYM) { - // This should never happen. - // All synonyms need to be qualified with a type. - String synonymType = null; - handleSynonym(qualifiers, synonymType, clause, - unprocessedQualifiers); - } - addQualifiers(clause, unprocessedQualifiers); - // before adding the clause check for redundant clauses - boolean redundant = false; - for (Clause frameClause : frame.getClauses()) { - if (clause.equals(frameClause)) { - redundant = handleDuplicateClause(frame, frameClause); - } - } - if (!redundant) { - frame.addClause(clause); - } - } else { - return false; - } - return true; - } - - /** - * Handle synonym. - * - * @param qualifiers - * the qualifiers - * @param scope - * the scope - * @param clause - * the clause - * @param unprocessedQualifiers - * the unprocessed qualifiers - */ - protected void handleSynonym(@Nonnull Set qualifiers, - @Nullable String scope, @Nonnull Clause clause, - @Nonnull Set unprocessedQualifiers) { - clause.setTag(OboFormatTag.TAG_SYNONYM.getTag()); - String type = null; - clause.setXrefs(new ArrayList()); - for (OWLAnnotation aan : qualifiers) { - String propId = owlObjectToTag(aan.getProperty()); - if (OboFormatTag.TAG_XREF.getTag().equals(propId)) { - OWLAnnotationValue v = aan.getValue(); - String xrefValue; - if (v instanceof IRI) { - xrefValue = ((IRI) v).toString(); - } else { - xrefValue = ((OWLLiteral) v).getLiteral(); - } - Xref xref = new Xref(xrefValue); - clause.addXref(xref); - unprocessedQualifiers.remove(aan); - } else if (OboFormatTag.TAG_HAS_SYNONYM_TYPE.getTag() - .equals(propId)) { - type = getIdentifier(aan.getValue()); - unprocessedQualifiers.remove(aan); - } - } - if (scope != null) { - clause.addValue(scope); - if (type != null) { - clause.addValue(type); - } - } - } - - /** - * Handle a duplicate clause in a frame during translation. - * - * @param frame - * the frame - * @param clause - * the clause - * @return true if the clause is to be marked as redundant and will not be - * added to the - */ - protected boolean - handleDuplicateClause(@Nonnull Frame frame, Clause clause) { - // default is to report it via the logger and remove it. - LOG.error("Duplicate clause '{}' generated in frame: {}", clause, - frame.getId()); - return true; - } - - /** - * Tr generic property value. - * - * @param prop - * the prop - * @param annVal - * the ann val - * @param qualifiers - * the qualifiers - * @param frame - * the frame - * @return true, if successful - */ - @SuppressWarnings("null") - protected boolean trGenericPropertyValue(OWLAnnotationProperty prop, - OWLAnnotationValue annVal, @Nonnull Set qualifiers, - @Nonnull Frame frame) { - // no built-in obo tag for this: use the generic property_value tag - Clause clause = new Clause(OboFormatTag.TAG_PROPERTY_VALUE.getTag()); - String propId = this.getIdentifier(prop); - addQualifiers(clause, qualifiers); - if (propId.equals("shorthand") == false) { - clause.addValue(propId); - if (annVal instanceof OWLLiteral) { - OWLLiteral owlLiteral = (OWLLiteral) annVal; - clause.addValue(owlLiteral.getLiteral()); - OWLDatatype datatype = owlLiteral.getDatatype(); - IRI dataTypeIri = datatype.getIRI(); - if (!OWL2Datatype.isBuiltIn(dataTypeIri)) { - error("Untranslatable axiom due to unknown data type: " - + annVal, true); - return false; - } - if (Namespaces.XSD.inNamespace(dataTypeIri)) { - clause.addValue("xsd:" + dataTypeIri.getFragment()); - } else if (dataTypeIri.isPlainLiteral()) { - clause.addValue("xsd:string"); - } else { - clause.addValue(dataTypeIri.toString()); - } - } else if (annVal instanceof IRI) { - clause.addValue(getIdentifier((IRI) annVal)); - } - frame.addClause(clause); - } - return true; - } - - /** - * Gets the value. - * - * @param annVal - * the ann val - * @param tag - * the tag - * @return the value - */ - @SuppressWarnings("null") - @Nullable - protected String getValue(@Nonnull OWLAnnotationValue annVal, String tag) { - String value = annVal.toString(); - if (annVal instanceof OWLLiteral) { - value = ((OWLLiteral) annVal).getLiteral(); - } else if (annVal instanceof IRI) { - value = getIdentifier((IRI) annVal); - } - if (OboFormatTag.TAG_EXPAND_EXPRESSION_TO.getTag().equals(tag)) { - Matcher matcher = absoulteURLPattern.matcher(value); - while (matcher.find()) { - String m = matcher.group(); - m = m.replace("<", ""); - m = m.replace(">", ""); - int i = m.lastIndexOf("/"); - m = m.substring(i + 1); - value = value.replace(matcher.group(), m); - } - } - return value; - } - - /** - * Adds the qualifiers. - * - * @param c - * the c - * @param qualifiers - * the qualifiers - */ - protected void addQualifiers(@Nonnull Clause c, - @Nonnull Set qualifiers) { - for (OWLAnnotation ann : qualifiers) { - String prop = owlObjectToTag(ann.getProperty()); - if (prop == null) { - prop = ann.getProperty().getIRI().toString(); - } - if (prop.equals("gci_relation") || prop.equals("gci_filler") - || prop.equals("cardinality") - || prop.equals("minCardinality") - || prop.equals("maxCardinality") || prop.equals("all_some") - || prop.equals("all_only")) { - continue; - } - String value = ann.getValue().toString(); - if (ann.getValue() instanceof OWLLiteral) { - value = ((OWLLiteral) ann.getValue()).getLiteral(); - } else if (ann.getValue() instanceof IRI) { - value = getIdentifier((IRI) ann.getValue()); - } - QualifierValue qv = new QualifierValue(prop, value); - c.addQualifierValue(qv); - } - } - - /** - * E.g. http://purl.obolibrary.org/obo/go.owl to "go"
- * if does not match this pattern, then retain original IRI - * - * @param ontology - * the ontology - * @return The OBO ID of the ontology - */ - @SuppressWarnings("null") - public static String getOntologyId(@Nonnull OWLOntology ontology) { - return getOntologyId(ontology.getOntologyID().getOntologyIRI().get()); - } - - /** - * Gets the ontology id. - * - * @param iriObj - * the iri obj - * @return the ontology id - */ - public static String getOntologyId(@Nonnull IRI iriObj) { - // String id = getIdentifier(ontology.getOntologyID().getOntologyIRI()); - String iri = iriObj.toString(); - String id; - if (iri.startsWith("http://purl.obolibrary.org/obo/")) { - id = iri.replace("http://purl.obolibrary.org/obo/", ""); - if (id.endsWith(".owl")) { - id = id.replaceFirst(".owl$", ""); - } - } else { - id = iri; - } - // int index = iri.lastIndexOf("/"); - // id = iri.substring(index+1); - // index = id.lastIndexOf(".owl"); - // if(index>0){ - // id = id.substring(0, index); - // } - return id; - } - - /** - * Gets the data version. - * - * @param ontology - * the ontology - * @return the data version - */ - @Nullable - public static String getDataVersion(@Nonnull OWLOntology ontology) { - String oid = getOntologyId(ontology); - Optional v = ontology.getOntologyID().getVersionIRI(); - if (v.isPresent()) { - String vs = v.get().toString() - .replace("http://purl.obolibrary.org/obo/", ""); - vs = vs.replaceFirst(oid + "/", ""); - vs = vs.replace("/" + oid + ".owl", ""); - return vs; - } - return null; - } - - /** - * Tr. - * - * @param ontology - * the ontology - */ - protected void tr(@Nonnull OWLOntology ontology) { - Frame f = new Frame(FrameType.HEADER); - getObodoc().setHeaderFrame(f); - for (IRI iri : ontology.getDirectImportsDocuments()) { - Clause c = new Clause(OboFormatTag.TAG_IMPORT.getTag()); - // c.setValue(getOntologyId(iri)); - c.setValue(iri.toString()); - f.addClause(c); - } - String id = getOntologyId(ontology); - Clause c = new Clause(OboFormatTag.TAG_ONTOLOGY.getTag()); - c.setValue(id); - f.addClause(c); - String vid = getDataVersion(ontology); - if (vid != null) { - Clause c2 = new Clause(OboFormatTag.TAG_DATA_VERSION.getTag()); - c2.setValue(vid); - f.addClause(c2); - } - for (OWLAnnotation ann : ontology.getAnnotations()) { - OWLAnnotationProperty property = ann.getProperty(); - String tagString = owlObjectToTag(property); - if (OboFormatTag.TAG_COMMENT.getTag().equals(tagString)) { - property = fac.getOWLAnnotationProperty(OWLAPIObo2Owl - .trTagToIRI(OboFormatTag.TAG_REMARK.getTag())); - } - tr(property, ann.getValue(), ann.getAnnotations(), f); - } - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLEquivalentClassesAxiom ax) { - /* - * Assumption: the underlying data structure is a set The order is not - * guaranteed to be preserved. - */ - Set expressions = ax.getClassExpressions(); - // handle expression list with size other than two elements as error - if (expressions.size() != 2) { - error(ax, false); - return; - } - Iterator it = expressions.iterator(); - OWLClassExpression ce1 = it.next(); - OWLClassExpression ce2 = it.next(); - if (ce1.isBottomEntity() || ce1.isTopEntity() || ce2.isBottomEntity() - || ce2.isTopEntity()) { - error("Equivalent classes axioms using Top or Bottom entities are not supported in OBO.", - ax, false); - return; - } - if (ce1 instanceof OWLClass == false) { - // check whether ce2 is the actual OWLEntity - if (ce2 instanceof OWLClass) { - // three way exchange - OWLClassExpression temp = ce2; - ce2 = ce1; - ce1 = temp; - } else { - // this might happen for some GCI axioms, which are not - // expressible in OBO - error("GCI axioms are not expressible in OBO.", ax, false); - return; - } - } - Frame f = getTermFrame(ce1.asOWLClass()); - if (f == null) { - error(ax, false); - return; - } - boolean isUntranslateable = false; - List equivalenceAxiomClauses = new ArrayList(); - String cls2 = this.getIdentifier(ce2); - if (cls2 != null) { - Clause c = new Clause(OboFormatTag.TAG_EQUIVALENT_TO.getTag()); - c.setValue(cls2); - f.addClause(c); - addQualifiers(c, ax.getAnnotations()); - } else if (ce2 instanceof OWLObjectUnionOf) { - List list2 = ((OWLObjectUnionOf) ce2) - .getOperandsAsList(); - for (OWLClassExpression oce : list2) { - String id = this.getIdentifier(oce); - if (id == null) { - isUntranslateable = true; - error(ax, true); - return; - } - Clause c = new Clause(OboFormatTag.TAG_UNION_OF.getTag()); - c.setValue(id); - equivalenceAxiomClauses.add(c); - addQualifiers(c, ax.getAnnotations()); - } - } else if (ce2 instanceof OWLObjectIntersectionOf) { - List list2 = ((OWLObjectIntersectionOf) ce2) - .getOperandsAsList(); - for (OWLClassExpression ce : list2) { - String r = null; - cls2 = this.getIdentifier(ce); - Integer exact = null; // cardinality - Integer min = null; // minCardinality - Integer max = null; // maxCardinality - Boolean allSome = null; // all_some - Boolean allOnly = null; // all_only - if (ce instanceof OWLObjectSomeValuesFrom) { - OWLObjectSomeValuesFrom ristriction = (OWLObjectSomeValuesFrom) ce; - r = this.getIdentifier(ristriction.getProperty()); - cls2 = this.getIdentifier(ristriction.getFiller()); - } else if (ce instanceof OWLObjectExactCardinality) { - OWLObjectExactCardinality card = (OWLObjectExactCardinality) ce; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - exact = card.getCardinality(); - } else if (ce instanceof OWLObjectMinCardinality) { - OWLObjectMinCardinality card = (OWLObjectMinCardinality) ce; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - min = card.getCardinality(); - } else if (ce instanceof OWLObjectMaxCardinality) { - OWLObjectMaxCardinality card = (OWLObjectMaxCardinality) ce; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - max = card.getCardinality(); - } else if (ce instanceof OWLObjectAllValuesFrom) { - OWLObjectAllValuesFrom all = (OWLObjectAllValuesFrom) ce; - OWLClassExpression filler = all.getFiller(); - if (filler instanceof OWLClass) { - r = this.getIdentifier(all.getProperty()); - cls2 = this.getIdentifier(filler); - allOnly = Boolean.TRUE; - } else if (filler instanceof OWLObjectComplementOf) { - OWLObjectComplementOf restriction = (OWLObjectComplementOf) filler; - r = this.getIdentifier(all.getProperty()); - cls2 = this.getIdentifier(restriction.getOperand()); - exact = 0; - } - } else if (ce instanceof OWLObjectIntersectionOf) { - // either a min-max or a some-all combination - Set operands = ((OWLObjectIntersectionOf) ce) - .getOperands(); - if (operands.size() == 2) { - for (OWLClassExpression operand : operands) { - if (operand instanceof OWLObjectMinCardinality) { - OWLObjectMinCardinality card = (OWLObjectMinCardinality) operand; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - min = card.getCardinality(); - } else if (operand instanceof OWLObjectMaxCardinality) { - OWLObjectMaxCardinality card = (OWLObjectMaxCardinality) operand; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - max = card.getCardinality(); - } else if (operand instanceof OWLObjectAllValuesFrom) { - OWLObjectAllValuesFrom all = (OWLObjectAllValuesFrom) operand; - r = this.getIdentifier(all.getProperty()); - cls2 = this.getIdentifier(all.getFiller()); - allOnly = Boolean.TRUE; - } else if (operand instanceof OWLObjectSomeValuesFrom) { - OWLObjectSomeValuesFrom all = (OWLObjectSomeValuesFrom) operand; - r = this.getIdentifier(all.getProperty()); - cls2 = this.getIdentifier(all.getFiller()); - allSome = Boolean.TRUE; - } - } - } - } - if (cls2 != null) { - Clause c = new Clause( - OboFormatTag.TAG_INTERSECTION_OF.getTag()); - if (r != null) { - c.addValue(r); - } - c.addValue(cls2); - equivalenceAxiomClauses.add(c); - if (exact != null) { - c.addQualifierValue(new QualifierValue("cardinality", - exact.toString())); - } - if (min != null) { - c.addQualifierValue(new QualifierValue( - "minCardinality", min.toString())); - } - if (max != null) { - c.addQualifierValue(new QualifierValue( - "maxCardinality", max.toString())); - } - if (allSome != null) { - c.addQualifierValue(new QualifierValue("all_some", - allSome.toString())); - } - if (allOnly != null) { - c.addQualifierValue(new QualifierValue("all_only", - allOnly.toString())); - } - addQualifiers(c, ax.getAnnotations()); - } else if (!f.getClauses(OboFormatTag.TAG_INTERSECTION_OF) - .isEmpty()) { - error("The axiom is not translated (maximimum one IntersectionOf EquivalenceAxiom)", - ax, false); - } else { - isUntranslateable = true; - error(ax, false); - } - } - } else { - isUntranslateable = true; - error(ax, false); - } - // Only add clauses if the *entire* equivalence axiom can be translated - if (!isUntranslateable) { - for (Clause c : equivalenceAxiomClauses) { - f.addClause(c); - } - } - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLDisjointClassesAxiom ax) { - // use set, the OWL-API does not provide an order - Set set = ax.getClassExpressions(); - if (set.size() != 2) { - error("Expected two classes in a disjoin classes axiom.", ax, false); - } - Iterator it = set.iterator(); - OWLClassExpression ce1 = it.next(); - OWLClassExpression ce2 = it.next(); - if (ce1.isBottomEntity() || ce1.isTopEntity() || ce2.isBottomEntity() - || ce2.isTopEntity()) { - error("Disjoint classes axiom using Top or Bottom entities are not supported.", - ax, false); - } - String cls2 = this.getIdentifier(ce2); - if (cls2 == null) { - error(ax, true); - return; - } - if (ce1.isAnonymous()) { - error(ax, false); - return; - } - OWLClass cls1 = ce1.asOWLClass(); - Frame f = getTermFrame(cls1); - Clause c = new Clause(OboFormatTag.TAG_DISJOINT_FROM.getTag()); - c.setValue(cls2); - f.addClause(c); - addQualifiers(c, ax.getAnnotations()); - } - - /** - * Tr. - * - * @param axiom - * the axiom - */ - protected void tr(@Nonnull OWLDeclarationAxiom axiom) { - OWLEntity entity = axiom.getEntity(); - if (entity.isBottomEntity() || entity.isTopEntity()) { - return; - } - Collection set = getOWLOntology() - .filterAxioms(Filters.annotations, entity.getIRI(), INCLUDED); - if (set.isEmpty()) { - return; - } - Frame f = null; - if (entity instanceof OWLClass) { - f = getTermFrame(entity.asOWLClass()); - } else if (entity instanceof OWLObjectProperty) { - f = getTypedefFrame(entity.asOWLObjectProperty()); - } else if (entity instanceof OWLAnnotationProperty) { - for (OWLAxiom a : set) { - OWLAnnotationAssertionAxiom ax = (OWLAnnotationAssertionAxiom) a; - OWLAnnotationProperty prop = ax.getProperty(); - String tag = owlObjectToTag(prop); - if (OboFormatTag.TAG_IS_METADATA_TAG.getTag().equals(tag)) { - f = getTypedefFrame(entity); - break; - } - } - } - if (f != null) { - for (OWLAnnotationAssertionAxiom a : set) { - assert a != null; - tr(a, f); - } - add(f); - return; - } - } - - /** - * Gets the identifier. - * - * @param obj - * the obj - * @return the identifier - */ - @Nullable - public String getIdentifier(OWLObject obj) { - try { - return getIdentifierFromObject(obj, getOWLOntology()); - } catch (UntranslatableAxiomException e) { - error(e.getMessage(), true); - } - return null; - } - - /** - * @return true if untranslatable axioms should not be logged - */ - public boolean isMuteUntranslatableAxioms() { - return muteUntranslatableAxioms; - } - - /** - * @param muteUntranslatableAxioms - * true disables logging - */ - public void setMuteUntranslatableAxioms(boolean muteUntranslatableAxioms) { - this.muteUntranslatableAxioms = muteUntranslatableAxioms; - } - - /** - * The Class UntranslatableAxiomException. - */ - public static class UntranslatableAxiomException extends Exception { - - // generated - private static final long serialVersionUID = 40000L; - - /** - * Instantiates a new untranslatable axiom exception. - * - * @param message - * the message - * @param cause - * the cause - */ - public UntranslatableAxiomException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Instantiates a new untranslatable axiom exception. - * - * @param message - * the message - */ - public UntranslatableAxiomException(String message) { - super(message); - } - } - - /** - * Retrieve the identifier for a given {@link OWLObject}. This methods uses - * also shorthand hints to resolve the identifier. Should the translation - * process encounter a problem or not find an identifier the defaultValue is - * returned. - * - * @param obj - * the {@link OWLObject} to resolve - * @param ont - * the target ontology - * @param defaultValue - * the value to return in case of an error or no id - * @return identifier or the default value - */ - @Nonnull - public static String getIdentifierFromObject(@Nonnull OWLObject obj, - @Nonnull OWLOntology ont, @Nonnull String defaultValue) { - String id = defaultValue; - try { - id = getIdentifierFromObject(obj, ont); - if (id == null) { - id = defaultValue; - } - } catch (UntranslatableAxiomException e) { - LOG.error(e.getMessage(), e); - } - return id; - } - - /** - * Retrieve the identifier for a given {@link OWLObject}. This methods uses - * also shorthand hints to resolve the identifier. Should the translation - * process encounter an unexpected axiom an - * - * @param obj - * the {@link OWLObject} to resolve - * @param ont - * the target ontology - * @return identifier or null - * @throws UntranslatableAxiomException - * the untranslatable axiom exception - * {@link UntranslatableAxiomException} is thrown. - */ - @SuppressWarnings("null") - @Nullable - public static String getIdentifierFromObject(OWLObject obj, - @Nonnull OWLOntology ont) throws UntranslatableAxiomException { - if (obj instanceof OWLObjectProperty - || obj instanceof OWLAnnotationProperty) { - OWLEntity entity = (OWLEntity) obj; - Collection filterAxioms = ont.filterAxioms( - Filters.annotations, entity.getIRI(), INCLUDED); - for (OWLAxiom a : filterAxioms) { - OWLAnnotationAssertionAxiom ax = (OWLAnnotationAssertionAxiom) a; - String propId = getIdentifierFromObject(ax.getProperty() - .getIRI(), ont); - // see BFOROXrefTest - // 5.9.3. Special Rules for Relations - if (propId.equals("shorthand")) { - OWLAnnotationValue value = ax.getValue(); - if (value instanceof OWLLiteral) { - return ((OWLLiteral) value).getLiteral(); - } - throw new UntranslatableAxiomException( - "Untranslatable axiom, expected literal value, but was: " - + value + " in axiom: " + ax); - } - } - } - if (obj instanceof OWLEntity) { - return getIdentifier(((OWLEntity) obj).getIRI()); - } - if (obj instanceof IRI) { - return getIdentifier((IRI) obj); - } - return null; - } - - /** - * See table 5.9.2. Translation of identifiers - * - * @param iriId - * the iri id - * @return obo identifier or null - */ - @Nullable - public static String getIdentifier(@Nullable IRI iriId) { - if (iriId == null) { - return null; - } - String iri = iriId.toString(); - // canonical IRIs - // if (iri.startsWith("http://purl.obolibrary.org/obo/")) { - // String canonicalId = iri.replace("http://purl.obolibrary.org/obo/", - // ""); - // } - int indexSlash = iri.lastIndexOf("/"); - String id = null; - if (indexSlash > -1) { - id = iri.substring(indexSlash + 1); - } else { - id = iri; - } - String[] s = id.split("#_"); - // table 5.9.2 row 2 - NonCanonical-Prefixed-ID - if (s.length > 1) { - return s[0] + ":" + s[1]; - } - // row 3 - Unprefixed-ID - s = id.split("#"); - if (s.length > 1) { - // prefixURI = prefixURI + s[0] + "#"; - // if(!(s[1].contains("#") || s[1].contains("_"))){ - String prefix = ""; - if ("owl".equals(s[0]) || "rdf".equals(s[0]) || "rdfs".equals(s[0])) { - prefix = s[0] + ":"; - } - // TODO: the following implements behavior in current spec, but this - // leads to undesirable results - // else if (baseOntology != null) { - // String oid = getOntologyId(baseOntology); // OBO-style ID - // if (oid.equals(s[0])) - // prefix = ""; - // else { - // return iri; - // } - // //prefix = s[0]; - // } - return prefix + s[1]; - } - // row 1 - Canonical-Prefixed-ID - s = id.split("_"); - if (s.length == 2 && !id.contains("#") && !s[1].contains("_")) { - String localId; - try { - localId = java.net.URLDecoder.decode(s[1], "UTF-8"); - return s[0] + ":" + localId; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException( - "UTF-8 not supported, JRE corrupted?", e); - } - } - if (s.length > 2 && !id.contains("#")) { - if (s[s.length - 1].replaceAll("[0-9]", "").isEmpty()) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < s.length; i++) { - if (i > 0) { - if (i == s.length - 1) { - sb.append(":"); - } else { - sb.append("_"); - } - } - sb.append(s[i]); - } - return sb.toString(); - } - } - return iri; - } - - /** - * Owl object to tag. - * - * @param obj - * the obj - * @return the string - */ - @Nullable - public static String owlObjectToTag(OWLObject obj) { - IRI iriObj = null; - if (obj instanceof OWLNamedObject) { - iriObj = ((OWLNamedObject) obj).getIRI(); - } else if (obj instanceof IRI) { - iriObj = (IRI) obj; - } - if (iriObj == null) { - return null; - } - String iri = iriObj.toString(); - String tag = annotationPropertyMap.get(iri); - if (tag == null) { - // hardcoded values for legacy annotation properties: (TEMPORARY) - if (iri.startsWith(Obo2OWLConstants.DEFAULT_IRI_PREFIX + "IAO_")) { - String legacyId = iri.replace( - Obo2OWLConstants.DEFAULT_IRI_PREFIX, ""); - if (legacyId.equals("IAO_xref")) { - return OboFormatTag.TAG_XREF.getTag(); - } - if (legacyId.equals("IAO_id")) { - return OboFormatTag.TAG_ID.getTag(); - } - if (legacyId.equals("IAO_namespace")) { - return OboFormatTag.TAG_NAMESPACE.getTag(); - } - } - String prefix = Obo2OWLConstants.OIOVOCAB_IRI_PREFIX; - if (iri.startsWith(prefix)) { - tag = iri.substring(prefix.length()); - } - } - return tag; - } - - /** - * Gets the term frame. - * - * @param entity - * the entity - * @return the term frame - */ - protected Frame getTermFrame(@Nonnull OWLClass entity) { - String id = getIdentifier(entity.getIRI()); - Frame f = getObodoc().getTermFrame(id); - if (f == null) { - f = new Frame(FrameType.TERM); - f.setId(id); - f.addClause(new Clause(OboFormatTag.TAG_ID, id)); - add(f); - } - return f; - } - - /** - * Gets the typedef frame. - * - * @param entity - * the entity - * @return the typedef frame - */ - protected Frame getTypedefFrame(OWLEntity entity) { - String id = this.getIdentifier(entity); - Frame f = getObodoc().getTypedefFrame(id); - if (f == null) { - f = new Frame(FrameType.TYPEDEF); - f.setId(id); - f.addClause(new Clause(OboFormatTag.TAG_ID, id)); - add(f); - } - return f; - } - - /** - * Tr. - * - * @param ax - * the ax - */ - @SuppressWarnings("null") - protected void tr(@Nonnull OWLClassAssertionAxiom ax) { - OWLObject cls = ax.getClassExpression(); - if (!(cls instanceof OWLClass)) { - return; - } - String clsIRI = ((OWLClass) cls).getIRI().toString(); - if (IRI_CLASS_SYNONYMTYPEDEF.equals(clsIRI)) { - Frame f = getObodoc().getHeaderFrame(); - Clause c = new Clause(OboFormatTag.TAG_SYNONYMTYPEDEF.getTag()); - OWLNamedIndividual indv = (OWLNamedIndividual) ax.getIndividual(); - String indvId = this.getIdentifier(indv); - // TODO: full specify this in the spec document. - // we may want to allow full IDs for subsets in future. - // here we would have a convention that an unprefixed - // subsetdef/synonymtypedef - // gets placed in a temp ID space, and only this id space is - // stripped - indvId = indvId.replaceFirst(".*:", ""); - c.addValue(indvId); - c.addValue(indvId); - String nameValue = ""; - String scopeValue = null; - for (OWLAnnotation ann : annotations(getOWLOntology() - .getAnnotationAssertionAxioms(indv.getIRI()))) { - String propId = ann.getProperty().getIRI().toString(); - String value = ((OWLLiteral) ann.getValue()).getLiteral(); - if (OWLRDFVocabulary.RDFS_LABEL.getIRI().toString() - .equals(propId)) { - nameValue = "\"" + value + "\""; - } else { - scopeValue = value; - } - } - c.addValue(nameValue); - if (scopeValue != null) { - c.addValue(scopeValue); - } - f.addClause(c); - } else if (IRI_CLASS_SUBSETDEF.equals(clsIRI)) { - Frame f = getObodoc().getHeaderFrame(); - Clause c = new Clause(OboFormatTag.TAG_SUBSETDEF.getTag()); - OWLNamedIndividual indv = (OWLNamedIndividual) ax.getIndividual(); - String indvId = this.getIdentifier(indv); - // TODO: full specify this in the spec document. - // we may want to allow full IDs for subsets in future. - // here we would have a convention that an unprefixed - // subsetdef/synonymtypedef - // gets placed in a temp ID space, and only this id space is - // stripped - indvId = indvId.replaceFirst(".*:", ""); - c.addValue(indvId); - String nameValue = ""; - for (OWLAnnotation ann : annotations(getOWLOntology() - .getAnnotationAssertionAxioms(indv.getIRI()))) { - String propId = ann.getProperty().getIRI().toString(); - String value = ((OWLLiteral) ann.getValue()).getLiteral(); - if (OWLRDFVocabulary.RDFS_LABEL.getIRI().toString() - .equals(propId)) { - nameValue = "\"" + value + "\""; - } - } - c.addValue(nameValue); - f.addClause(c); - } else { - // TODO: individual - } - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLSubClassOfAxiom ax) { - OWLClassExpression sub = ax.getSubClass(); - OWLClassExpression sup = ax.getSuperClass(); - Set qvs = new HashSet(); - if (sub.isOWLNothing() || sub.isTopEntity() || sup.isTopEntity() - || sup.isOWLNothing()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - // 5.2.2 - if (sub instanceof OWLObjectIntersectionOf) { - Set xs = ((OWLObjectIntersectionOf) sub) - .getOperands(); - // obo-format is limited to very restricted GCIs - the LHS of the - // axiom - // must correspond to ObjectIntersectionOf(cls - // ObjectSomeValuesFrom(p filler)) - if (xs.size() == 2) { - OWLClass c = null; - OWLObjectSomeValuesFrom r = null; - OWLObjectProperty p = null; - OWLClass filler = null; - for (OWLClassExpression x : xs) { - if (x instanceof OWLClass) { - c = (OWLClass) x; - } - if (x instanceof OWLObjectSomeValuesFrom) { - r = (OWLObjectSomeValuesFrom) x; - if (r.getProperty() instanceof OWLObjectProperty) { - if (r.getFiller() instanceof OWLClass) { - p = (OWLObjectProperty) r.getProperty(); - filler = (OWLClass) r.getFiller(); - } - } - } - } - if (c != null && p != null && filler != null) { - sub = c; - qvs.add(new QualifierValue("gci_relation", getIdentifier(p))); - qvs.add(new QualifierValue("gci_filler", - getIdentifier(filler))); - } - } - } - if (sub instanceof OWLClass) { - Frame f = getTermFrame((OWLClass) sub); - if (sup instanceof OWLClass) { - Clause c = new Clause(OboFormatTag.TAG_IS_A.getTag()); - c.setValue(this.getIdentifier(sup)); - c.setQualifierValues(qvs); - f.addClause(c); - addQualifiers(c, ax.getAnnotations()); - } else if (sup instanceof OWLQuantifiedObjectRestriction) { - // OWLObjectSomeValuesFrom - // OWLObjectAllValuesFrom - OWLQuantifiedObjectRestriction r = (OWLQuantifiedObjectRestriction) sup; - OWLClassExpression filler = r.getFiller(); - if (filler.isBottomEntity() || filler.isTopEntity()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - String fillerId = this.getIdentifier(filler); - if (fillerId == null) { - error(ax, true); - return; - } - f.addClause(createRelationshipClauseWithRestrictions(r, - fillerId, qvs, ax)); - } else if (sup instanceof OWLObjectCardinalityRestriction) { - // OWLObjectExactCardinality - // OWLObjectMinCardinality - // OWLObjectMaxCardinality - OWLObjectCardinalityRestriction cardinality = (OWLObjectCardinalityRestriction) sup; - OWLClassExpression filler = cardinality.getFiller(); - if (filler.isBottomEntity() || filler.isTopEntity()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - String fillerId = this.getIdentifier(filler); - if (fillerId == null) { - error(ax, true); - return; - } - f.addClause(createRelationshipClauseWithCardinality( - cardinality, fillerId, qvs, ax)); - } else if (sup instanceof OWLObjectIntersectionOf) { - OWLObjectIntersectionOf i = (OWLObjectIntersectionOf) sup; - List clauses = new ArrayList(); - for (OWLClassExpression operand : i.getOperands()) { - if (operand instanceof OWLQuantifiedObjectRestriction) { - OWLQuantifiedObjectRestriction restriction = (OWLQuantifiedObjectRestriction) operand; - OWLClassExpression filler = restriction.getFiller(); - if (filler.isBottomEntity() || filler.isTopEntity()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - String fillerId = this.getIdentifier(filler); - if (fillerId == null) { - error(ax, true); - return; - } - clauses.add(createRelationshipClauseWithRestrictions( - restriction, fillerId, - new HashSet(qvs), ax)); - } else if (operand instanceof OWLObjectCardinalityRestriction) { - OWLObjectCardinalityRestriction restriction = (OWLObjectCardinalityRestriction) operand; - OWLClassExpression filler = restriction.getFiller(); - if (filler.isBottomEntity() || filler.isTopEntity()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - String fillerId = this.getIdentifier(filler); - if (fillerId == null) { - error(ax, true); - return; - } - clauses.add(createRelationshipClauseWithCardinality( - restriction, fillerId, - new HashSet(qvs), ax)); - } else { - error(ax, true); - return; - } - } - if (clauses.isEmpty()) { - error(ax, true); - return; - } - clauses = normalizeRelationshipClauses(clauses); - for (Clause clause : clauses) { - f.addClause(clause); - } - } else { - error(ax, true); - return; - } - } else { - error(ax, true); - return; - } - } - - /** - * Creates the relationship clause with restrictions. - * - * @param r - * the r - * @param fillerId - * the filler id - * @param qvs - * the qvs - * @param ax - * the ax - * @return the clause - */ - @Nonnull - protected Clause createRelationshipClauseWithRestrictions( - @Nonnull OWLQuantifiedObjectRestriction r, String fillerId, - @Nonnull Set qvs, @Nonnull OWLSubClassOfAxiom ax) { - Clause c = new Clause(OboFormatTag.TAG_RELATIONSHIP.getTag()); - c.addValue(this.getIdentifier(r.getProperty())); - c.addValue(fillerId); - c.setQualifierValues(qvs); - addQualifiers(c, ax.getAnnotations()); - return c; - } - - /** - * Creates the relationship clause with cardinality. - * - * @param restriction - * the restriction - * @param fillerId - * the filler id - * @param qvs - * the qvs - * @param ax - * the ax - * @return the clause - */ - @Nonnull - protected Clause createRelationshipClauseWithCardinality( - @Nonnull OWLObjectCardinalityRestriction restriction, - String fillerId, @Nonnull Set qvs, - @Nonnull OWLSubClassOfAxiom ax) { - Clause c = new Clause(OboFormatTag.TAG_RELATIONSHIP.getTag()); - c.addValue(this.getIdentifier(restriction.getProperty())); - c.addValue(fillerId); - c.setQualifierValues(qvs); - String q = "cardinality"; - if (restriction instanceof OWLObjectMinCardinality) { - q = "minCardinality"; - } else if (restriction instanceof OWLObjectMaxCardinality) { - q = "maxCardinality"; - } - c.addQualifierValue(new QualifierValue(q, Integer.toString(restriction - .getCardinality()))); - addQualifiers(c, ax.getAnnotations()); - return c; - } - - /** - * Join clauses and its {@link QualifierValue} which have the same - * relationship type and target. Try to resolve conflicts for multiple - * statements. E.g., min=2 and min=3 is resolved to min=2, or max=2 and - * max=4 is resolved to max=4. It will not merge conflicting exact - * cardinality statements. TODO How to merge "all_some", and "all_only"? - * - * @param clauses - * the clauses - * @return normalized list of {@link Clause} - */ - @Nonnull - public static List normalizeRelationshipClauses( - @Nonnull List clauses) { - List normalized = new ArrayList(); - while (!clauses.isEmpty()) { - Clause target = clauses.remove(0); - assert target != null; - List similar = findSimilarClauses(clauses, target); - normalized.add(target); - mergeSimilarIntoTarget(target, similar); - } - return normalized; - } - - /** - * Find similar clauses. - * - * @param clauses - * the clauses - * @param target - * the target - * @return the list - */ - @SuppressWarnings("null") - @Nonnull - static List findSimilarClauses(@Nonnull List clauses, - @Nonnull Clause target) { - String targetTag = target.getTag(); - Object targetValue = target.getValue(); - Object targetValue2 = target.getValue2(); - List similar = new ArrayList(); - Iterator iterator = clauses.iterator(); - while (iterator.hasNext()) { - Clause current = iterator.next(); - Object currentValue = current.getValue(); - Object currentValue2 = current.getValue2(); - if (targetTag.equals(current.getTag()) - && targetValue.equals(currentValue)) { - if (targetValue2 == null) { - if (currentValue2 == null) { - similar.add(current); - iterator.remove(); - } - } else if (targetValue2.equals(currentValue2)) { - similar.add(current); - iterator.remove(); - } - } - } - return similar; - } - - /** - * Merge similar into target. - * - * @param target - * the target - * @param similar - * the similar - */ - static void mergeSimilarIntoTarget(@Nonnull Clause target, - @Nonnull List similar) { - if (similar.isEmpty()) { - return; - } - Collection targetQVs = target.getQualifierValues(); - for (Clause current : similar) { - Collection newQVs = current.getQualifierValues(); - for (QualifierValue newQV : newQVs) { - String newQualifier = newQV.getQualifier(); - // if min or max cardinality check for possible merges - if ("minCardinality".equals(newQualifier) - || "maxCardinality".equals(newQualifier)) { - QualifierValue match = findMatchingQualifierValue(newQV, - targetQVs); - if (match != null) { - mergeQualifierValues(match, newQV); - } else { - target.addQualifierValue(newQV); - } - } else { - target.addQualifierValue(newQV); - } - } - } - } - - /** - * Find matching qualifier value. - * - * @param query - * the query - * @param list - * the list - * @return the qualifier value - */ - @Nullable - static QualifierValue findMatchingQualifierValue( - @Nonnull QualifierValue query, - @Nonnull Collection list) { - String queryQualifier = query.getQualifier(); - for (QualifierValue qv : list) { - if (queryQualifier.equals(qv.getQualifier())) { - return qv; - } - } - return null; - } - - /** - * Merge qualifier values. - * - * @param target - * the target - * @param newQV - * the new qv - */ - static void mergeQualifierValues(@Nonnull QualifierValue target, - @Nonnull QualifierValue newQV) { - // do nothing, if they are equal - if (!target.getValue().equals(newQV.getValue())) { - if ("minCardinality".equals(target.getQualifier())) { - // try to merge, parse as integers - int currentValue = Integer.parseInt(target.getValue() - .toString()); - int newValue = Integer.parseInt(newQV.getValue().toString()); - int mergedValue = Math.min(currentValue, newValue); - target.setValue(Integer.toString(mergedValue)); - } else if ("maxCardinality".equals(target.getQualifier())) { - // try to merge, parse as integers - int currentValue = Integer.parseInt(target.getValue() - .toString()); - int newValue = Integer.parseInt(newQV.getValue().toString()); - int mergedValue = Math.max(currentValue, newValue); - target.setValue(Integer.toString(mergedValue)); - } - } - } - - protected void - error(String message, OWLAxiom ax, boolean shouldLogComplaint) { - untranslatableAxioms.add(ax); - error(message + ax, shouldLogComplaint); - } - - protected void error(OWLAxiom ax, boolean shouldLogComplaint) { - untranslatableAxioms.add(ax); - error("the axiom is not translated : " + ax, shouldLogComplaint); - } - - protected void error(String message, boolean shouldLogComplaint) { - if (strictConversion) { - throw new RuntimeException("The conversion is halted: " + message); - } else { - if (!muteUntranslatableAxioms && shouldLogComplaint) { - LOG.error("MASKING ERROR «{}»", message, new Exception()); - } - } - } - - protected void warn(String message) { - if (strictConversion) { - throw new RuntimeException("The conversion is halted: " + message); - } else { - LOG.warn("MASKING ERROR «{}»", message); - } - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/old/OWLAPIOwl2Obo.java b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/old/OWLAPIOwl2Obo.java deleted file mode 100755 index 22fd4a2..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/old/OWLAPIOwl2Obo.java +++ /dev/null @@ -1,2388 +0,0 @@ -package org.obolibrary.obo2owl; - -import static org.semanticweb.owlapi.model.parameters.Imports.INCLUDED; -import static org.semanticweb.owlapi.search.Searcher.annotations; -import static org.semanticweb.owlapi.util.OWLAPIPreconditions.verifyNotNull; - -import java.io.UnsupportedEncodingException; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.Vector; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - -import org.obolibrary.obo2owl.Obo2OWLConstants.Obo2OWLVocabulary; -import org.obolibrary.obo2owl.OwlStringTools.OwlStringException; -import org.obolibrary.oboformat.model.Clause; -import org.obolibrary.oboformat.model.Frame; -import org.obolibrary.oboformat.model.Frame.FrameType; -import org.obolibrary.oboformat.model.OBODoc; -import org.obolibrary.oboformat.model.QualifierValue; -import org.obolibrary.oboformat.model.Xref; -import org.obolibrary.oboformat.parser.OBOFormatConstants; -import org.obolibrary.oboformat.parser.OBOFormatConstants.OboFormatTag; -import org.semanticweb.owlapi.model.AxiomType; -import org.semanticweb.owlapi.model.IRI; -import org.semanticweb.owlapi.model.OWLAnnotation; -import org.semanticweb.owlapi.model.OWLAnnotationAssertionAxiom; -import org.semanticweb.owlapi.model.OWLAnnotationProperty; -import org.semanticweb.owlapi.model.OWLAnnotationValue; -import org.semanticweb.owlapi.model.OWLAsymmetricObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLAxiom; -import org.semanticweb.owlapi.model.OWLClass; -import org.semanticweb.owlapi.model.OWLClassAssertionAxiom; -import org.semanticweb.owlapi.model.OWLClassExpression; -import org.semanticweb.owlapi.model.OWLDataFactory; -import org.semanticweb.owlapi.model.OWLDatatype; -import org.semanticweb.owlapi.model.OWLDeclarationAxiom; -import org.semanticweb.owlapi.model.OWLDisjointClassesAxiom; -import org.semanticweb.owlapi.model.OWLDisjointObjectPropertiesAxiom; -import org.semanticweb.owlapi.model.OWLEntity; -import org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom; -import org.semanticweb.owlapi.model.OWLEquivalentObjectPropertiesAxiom; -import org.semanticweb.owlapi.model.OWLFunctionalObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLInverseFunctionalObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLInverseObjectPropertiesAxiom; -import org.semanticweb.owlapi.model.OWLLiteral; -import org.semanticweb.owlapi.model.OWLNamedIndividual; -import org.semanticweb.owlapi.model.OWLNamedObject; -import org.semanticweb.owlapi.model.OWLNaryPropertyAxiom; -import org.semanticweb.owlapi.model.OWLObject; -import org.semanticweb.owlapi.model.OWLObjectAllValuesFrom; -import org.semanticweb.owlapi.model.OWLObjectCardinalityRestriction; -import org.semanticweb.owlapi.model.OWLObjectComplementOf; -import org.semanticweb.owlapi.model.OWLObjectExactCardinality; -import org.semanticweb.owlapi.model.OWLObjectIntersectionOf; -import org.semanticweb.owlapi.model.OWLObjectMaxCardinality; -import org.semanticweb.owlapi.model.OWLObjectMinCardinality; -import org.semanticweb.owlapi.model.OWLObjectProperty; -import org.semanticweb.owlapi.model.OWLObjectPropertyDomainAxiom; -import org.semanticweb.owlapi.model.OWLObjectPropertyExpression; -import org.semanticweb.owlapi.model.OWLObjectPropertyRangeAxiom; -import org.semanticweb.owlapi.model.OWLObjectSomeValuesFrom; -import org.semanticweb.owlapi.model.OWLObjectUnionOf; -import org.semanticweb.owlapi.model.OWLOntology; -import org.semanticweb.owlapi.model.OWLOntologyManager; -import org.semanticweb.owlapi.model.OWLQuantifiedObjectRestriction; -import org.semanticweb.owlapi.model.OWLReflexiveObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLSubAnnotationPropertyOfAxiom; -import org.semanticweb.owlapi.model.OWLSubClassOfAxiom; -import org.semanticweb.owlapi.model.OWLSubObjectPropertyOfAxiom; -import org.semanticweb.owlapi.model.OWLSubPropertyChainOfAxiom; -import org.semanticweb.owlapi.model.OWLSymmetricObjectPropertyAxiom; -import org.semanticweb.owlapi.model.OWLTransitiveObjectPropertyAxiom; -import org.semanticweb.owlapi.search.Filters; -import org.semanticweb.owlapi.vocab.Namespaces; -import org.semanticweb.owlapi.vocab.OWL2Datatype; -import org.semanticweb.owlapi.vocab.OWLRDFVocabulary; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.base.Optional; - -/** - * The Class OWLAPIOwl2Obo. - */ -public class OWLAPIOwl2Obo { - - /** - * The log. - */ - private static Logger LOG = LoggerFactory.getLogger(OWLAPIOwl2Obo.class); - private static final String IRI_CLASS_SYNONYMTYPEDEF = Obo2OWLConstants.DEFAULT_IRI_PREFIX - + "IAO_synonymtypedef"; - private static final String IRI_CLASS_SUBSETDEF = Obo2OWLConstants.DEFAULT_IRI_PREFIX - + "IAO_subsetdef"; - /** - * The manager. - */ - @Nonnull - protected OWLOntologyManager manager; - /** - * The owl ontology. - */ - protected OWLOntology owlOntology; - /** - * The fac. - */ - protected OWLDataFactory fac; - /** - * The obodoc. - */ - protected OBODoc obodoc; - /** - * The untranslatable axioms. - */ - protected Set untranslatableAxioms; - /** - * The id space map. - */ - protected Map idSpaceMap; - /** - * The annotation property map. - */ - @Nonnull - public static Map annotationPropertyMap = initAnnotationPropertyMap(); - /** - * The ap to declare. - */ - protected Set apToDeclare; - /** - * The ontology id. - */ - protected String ontologyId; - /** - * The strict conversion. - */ - protected boolean strictConversion; - /** - * The discard untranslatable. - */ - protected boolean discardUntranslatable = false; - /** - * mute untranslatable axiom warnings - */ - private boolean muteUntranslatableAxioms = false; - - /** - * Inits the. - */ - protected void init() { - idSpaceMap = new HashMap(); - // legacy: - idSpaceMap.put("http://www.obofoundry.org/ro/ro.owl#", "OBO_REL"); - untranslatableAxioms = new HashSet(); - fac = manager.getOWLDataFactory(); - apToDeclare = new HashSet(); - } - - /** - * Instantiates a new oWLAPI owl2 obo. - * - * @param translationManager - * the translation manager - */ - public OWLAPIOwl2Obo(@Nonnull OWLOntologyManager translationManager) { - manager = translationManager; - init(); - } - - /** - * Inits the annotation property map. - * - * @return the hash map - */ - @Nonnull - protected static HashMap initAnnotationPropertyMap() { - HashMap map = new HashMap(); - for (String key : OWLAPIObo2Owl.annotationPropertyMap.keySet()) { - IRI propIRI = OWLAPIObo2Owl.annotationPropertyMap.get(key); - map.put(propIRI.toString(), key); - } - return map; - } - - /** - * Sets the strict conversion. - * - * @param b - * the new strict conversion - */ - public void setStrictConversion(boolean b) { - strictConversion = b; - } - - /** - * Gets the strict conversion. - * - * @return the strict conversion - */ - public boolean getStrictConversion() { - return strictConversion; - } - - /** - * Checks if is discard untranslatable. - * - * @return the discardUntranslatable - */ - public boolean isDiscardUntranslatable() { - return discardUntranslatable; - } - - /** - * Sets the discard untranslatable. - * - * @param discardUntranslatable - * the discardUntranslatable to set - */ - public void setDiscardUntranslatable(boolean discardUntranslatable) { - this.discardUntranslatable = discardUntranslatable; - } - - /** - * Gets the manager. - * - * @return the manager - */ - public OWLOntologyManager getManager() { - return manager; - } - - /** - * Sets the manager. - * - * @param manager - * the new manager - */ - public void setManager(@Nonnull OWLOntologyManager manager) { - this.manager = manager; - } - - /** - * Gets the obodoc. - * - * @return the obodoc - */ - @Nonnull - public OBODoc getObodoc() { - return verifyNotNull(obodoc); - } - - /** - * Sets the obodoc. - * - * @param obodoc - * the new obodoc - */ - public void setObodoc(@Nonnull OBODoc obodoc) { - this.obodoc = obodoc; - } - - /** - * Convert. - * - * @param ont - * the ont - * @return the oBO doc - */ - @Nonnull - public OBODoc convert(@Nonnull OWLOntology ont) { - owlOntology = ont; - ontologyId = getOntologyId(ont); - init(); - return tr(); - } - - @Nonnull - protected OWLOntology getOWLOntology() { - return verifyNotNull(owlOntology); - } - - /** - * Gets the untranslatable axioms. - * - * @return the untranslatableAxioms - */ - public Collection getUntranslatableAxioms() { - return untranslatableAxioms; - } - - /** - * Tr. - * - * @return the oBO doc - */ - @Nonnull - protected OBODoc tr() { - setObodoc(new OBODoc()); - preProcess(); - tr(getOWLOntology()); - for (OWLAxiom ax : getOWLOntology().getAxioms()) { - if (ax instanceof OWLDeclarationAxiom) { - tr((OWLDeclarationAxiom) ax); - } else if (ax instanceof OWLSubClassOfAxiom) { - tr((OWLSubClassOfAxiom) ax); - } else if (ax instanceof OWLDisjointClassesAxiom) { - tr((OWLDisjointClassesAxiom) ax); - } else if (ax instanceof OWLEquivalentClassesAxiom) { - tr((OWLEquivalentClassesAxiom) ax); - } else if (ax instanceof OWLClassAssertionAxiom) { - tr((OWLClassAssertionAxiom) ax); - } else if (ax instanceof OWLEquivalentObjectPropertiesAxiom) { - tr((OWLEquivalentObjectPropertiesAxiom) ax); - } else if (ax instanceof OWLSubAnnotationPropertyOfAxiom) { - tr((OWLSubAnnotationPropertyOfAxiom) ax); - } else if (ax instanceof OWLSubObjectPropertyOfAxiom) { - tr((OWLSubObjectPropertyOfAxiom) ax); - } else if (ax instanceof OWLObjectPropertyRangeAxiom) { - tr((OWLObjectPropertyRangeAxiom) ax); - } else if (ax instanceof OWLFunctionalObjectPropertyAxiom) { - tr((OWLFunctionalObjectPropertyAxiom) ax); - } else if (ax instanceof OWLSymmetricObjectPropertyAxiom) { - tr((OWLSymmetricObjectPropertyAxiom) ax); - } else if (ax instanceof OWLAsymmetricObjectPropertyAxiom) { - tr((OWLAsymmetricObjectPropertyAxiom) ax); - } else if (ax instanceof OWLObjectPropertyDomainAxiom) { - tr((OWLObjectPropertyDomainAxiom) ax); - } else if (ax instanceof OWLInverseFunctionalObjectPropertyAxiom) { - tr((OWLInverseFunctionalObjectPropertyAxiom) ax); - } else if (ax instanceof OWLInverseObjectPropertiesAxiom) { - tr((OWLInverseObjectPropertiesAxiom) ax); - } else if (ax instanceof OWLDisjointObjectPropertiesAxiom) { - tr((OWLDisjointObjectPropertiesAxiom) ax); - } else if (ax instanceof OWLReflexiveObjectPropertyAxiom) { - tr((OWLReflexiveObjectPropertyAxiom) ax); - } else if (ax instanceof OWLTransitiveObjectPropertyAxiom) { - tr((OWLTransitiveObjectPropertyAxiom) ax); - } else if (ax instanceof OWLSubPropertyChainOfAxiom) { - tr((OWLSubPropertyChainOfAxiom) ax); - } else { - if (!(ax instanceof OWLAnnotationAssertionAxiom)) { - error(ax, false); - } else { - // we presume this has been processed - } - } - } - if (untranslatableAxioms.isEmpty() == false - && discardUntranslatable == false) { - try { - String axiomString = OwlStringTools.translate( - untranslatableAxioms, manager); - if (axiomString != null) { - Frame headerFrame = getObodoc().getHeaderFrame(); - if (headerFrame == null) { - headerFrame = new Frame(FrameType.HEADER); - getObodoc().setHeaderFrame(headerFrame); - } - headerFrame.addClause(new Clause( - OboFormatTag.TAG_OWL_AXIOMS, axiomString)); - } - } catch (OwlStringException e) { - throw new RuntimeException(e); - } - } - return getObodoc(); - } - - /** - * Pre process. - */ - @SuppressWarnings("null") - protected void preProcess() { - // converse of postProcess in obo2owl - String viewRel = null; - for (OWLAnnotation ann : getOWLOntology().getAnnotations()) { - if (ann.getProperty() - .getIRI() - .equals(Obo2OWLVocabulary.IRI_OIO_LogicalDefinitionViewRelation - .getIRI())) { - OWLAnnotationValue v = ann.getValue(); - if (v instanceof OWLLiteral) { - viewRel = ((OWLLiteral) v).getLiteral(); - } else { - viewRel = getIdentifier((IRI) v); - } - break; - } - } - if (viewRel != null) { - // OWLObjectProperty vp = fac.getOWLObjectProperty(pIRI); - Set rmAxioms = new HashSet(); - Set newAxioms = new HashSet(); - for (OWLEquivalentClassesAxiom eca : getOWLOntology().getAxioms( - AxiomType.EQUIVALENT_CLASSES)) { - int numNamed = 0; - Set xs = new HashSet(); - for (OWLClassExpression x : eca.getClassExpressions()) { - if (x instanceof OWLClass) { - xs.add(x); - numNamed++; - continue; - } else if (x instanceof OWLObjectSomeValuesFrom) { - OWLObjectProperty p = (OWLObjectProperty) ((OWLObjectSomeValuesFrom) x) - .getProperty(); - if (this.getIdentifier(p).equals(viewRel) == false) { - LOG.error("Expected: {} got: {} in {}", viewRel, p, - eca); - } - xs.add(((OWLObjectSomeValuesFrom) x).getFiller()); - } else { - LOG.error("Unexpected: {}", eca); - } - } - if (numNamed == 1) { - rmAxioms.add(eca); - newAxioms.add(fac.getOWLEquivalentClassesAxiom(xs)); - } else { - LOG.error("ECA did not fit expected pattern: {}", eca); - } - } - manager.removeAxioms(getOWLOntology(), rmAxioms); - manager.addAxioms(getOWLOntology(), newAxioms); - } - } - - protected void add(@Nullable Frame f) { - if (f != null) { - try { - getObodoc().addFrame(f); - } catch (Exception ex) { - LOG.error(ex.getMessage(), ex); - } - } - } - - /** - * Tr object property. - * - * @param prop - * the prop - * @param tag - * the tag - * @param value - * the value - * @param annotations - * the annotations - * @return true, if successful - */ - @SuppressWarnings("null") - protected boolean trObjectProperty(@Nullable OWLObjectProperty prop, - @Nullable String tag, @Nullable String value, - @Nonnull Set annotations) { - if (prop == null || value == null) { - return false; - } - Frame f = getTypedefFrame(prop); - Clause clause; - if (OboFormatTag.TAG_ID.getTag().equals(tag)) { - clause = f.getClause(tag); - if (tag != null) { - clause.setValue(value); - } else { - clause = new Clause(tag, value); - f.addClause(clause); - } - } else { - clause = new Clause(tag, value); - f.addClause(clause); - } - addQualifiers(clause, annotations); - return true; - } - - /** - * Tr object property. - * - * @param prop - * the prop - * @param tag - * the tag - * @param value - * the value - * @param annotations - * the annotations - * @return true, if successful - */ - protected boolean trObjectProperty(@Nullable OWLObjectProperty prop, - String tag, @Nullable Boolean value, - @Nonnull Set annotations) { - if (prop == null || value == null) { - return false; - } - Frame f = getTypedefFrame(prop); - Clause clause = new Clause(tag); - clause.addValue(value); - f.addClause(clause); - addQualifiers(clause, annotations); - return true; - } - - /** - * Tr nary property axiom. - * - * @param ax - * the ax - * @param tag - * the tag - */ - protected void trNaryPropertyAxiom( - @Nonnull OWLNaryPropertyAxiom ax, - String tag) { - Set set = ax.getProperties(); - if (set.size() > 1) { - boolean first = true; - OWLObjectProperty prop = null; - String disjointFrom = null; - for (OWLObjectPropertyExpression ex : set) { - if (ex.isBottomEntity() || ex.isTopEntity()) { - error(tag - + " using Top or Bottom entities are not supported in OBO.", - ax, false); - return; - } - if (first) { - first = false; - if (ex instanceof OWLObjectProperty) { - prop = (OWLObjectProperty) ex; - } - } else { - disjointFrom = this.getIdentifier(ex); // getIdentifier(ex); - } - } - if (trObjectProperty(prop, tag, disjointFrom, ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLSubPropertyChainOfAxiom ax) { - OWLObjectPropertyExpression pEx = ax.getSuperProperty(); - if (pEx.isAnonymous()) { - error(ax, false); - return; - } - OWLObjectProperty p = pEx.asOWLObjectProperty(); - Frame f = getTypedefFrame(p); - if (p.isBottomEntity() || p.isTopEntity()) { - error("Property chains using Top or Bottom entities are not supported in OBO.", - ax, false); - return; - } - List list = ax.getPropertyChain(); - if (list.size() != 2) { - error(ax, false); - return; - } - OWLObjectPropertyExpression exp1 = list.get(0); - OWLObjectPropertyExpression exp2 = list.get(1); - if (exp1.isBottomEntity() || exp1.isTopEntity() - || exp2.isBottomEntity() || exp2.isTopEntity()) { - error("Property chains using Top or Bottom entities are not supported in OBO.", - ax, false); - return; - } - String rel1 = getIdentifier(exp1); - String rel2 = getIdentifier(exp2); - if (rel1 == null || rel2 == null) { - error(ax, false); - return; - } - Clause clause; - // set of unprocessed annotations - Set unprocessedAnnotations = new HashSet( - ax.getAnnotations()); - if (rel1.equals(f.getId())) { - clause = new Clause(OboFormatTag.TAG_TRANSITIVE_OVER, rel2); - } else { - OboFormatTag tag = OboFormatTag.TAG_HOLDS_OVER_CHAIN; - for (OWLAnnotation ann : ax.getAnnotations()) { - if (OWLAPIObo2Owl.IRI_PROP_isReversiblePropertyChain.equals(ann - .getProperty().getIRI().toString())) { - tag = OboFormatTag.TAG_EQUIVALENT_TO_CHAIN; - // remove annotation from unprocessed set. - unprocessedAnnotations.remove(ann); - break; - } - } - clause = new Clause(tag); - clause.addValue(rel1); - clause.addValue(rel2); - } - f.addClause(clause); - addQualifiers(clause, unprocessedAnnotations); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLEquivalentObjectPropertiesAxiom ax) { - trNaryPropertyAxiom(ax, OboFormatTag.TAG_EQUIVALENT_TO.getTag()); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLTransitiveObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_TRANSITIVE.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLDisjointObjectPropertiesAxiom ax) { - trNaryPropertyAxiom(ax, OboFormatTag.TAG_DISJOINT_FROM.getTag()); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLReflexiveObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_REFLEXIVE.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLInverseFunctionalObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_INVERSE_FUNCTIONAL.getTag(), - Boolean.TRUE, ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLInverseObjectPropertiesAxiom ax) { - OWLObjectPropertyExpression prop1 = ax.getFirstProperty(); - OWLObjectPropertyExpression prop2 = ax.getSecondProperty(); - if (prop1 instanceof OWLObjectProperty - && prop2 instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop1, - OboFormatTag.TAG_INVERSE_OF.getTag(), - this.getIdentifier(prop2), ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLObjectPropertyDomainAxiom ax) { - OWLClassExpression domain = ax.getDomain(); - OWLObjectPropertyExpression propEx = ax.getProperty(); - if (propEx.isAnonymous()) { - error(ax, true); - return; - } - OWLObjectProperty prop = propEx.asOWLObjectProperty(); - if (domain.isBottomEntity() || domain.isTopEntity()) { - // at least get the type def frame - getTypedefFrame(prop); - // now throw the error - error("domains using top or bottom entities are not translatable to OBO.", - ax, false); - return; - } - String range = this.getIdentifier(domain); - if (range != null) { - if (trObjectProperty(prop, OboFormatTag.TAG_DOMAIN.getTag(), range, - ax.getAnnotations())) { - return; - } else { - error("trObjectProperty failed for " + prop, ax, true); - } - } else { - error("no range translatable for " + ax, false); - } - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLAsymmetricObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_ASYMMETRIC.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLSymmetricObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_SYMMETRIC.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLFunctionalObjectPropertyAxiom ax) { - OWLObjectPropertyExpression prop = ax.getProperty(); - if (prop instanceof OWLObjectProperty) { - if (trObjectProperty((OWLObjectProperty) prop, - OboFormatTag.TAG_IS_FUNCTIONAL.getTag(), Boolean.TRUE, - ax.getAnnotations())) { - return; - } - } - error(ax, true); - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLObjectPropertyRangeAxiom ax) { - OWLClassExpression owlRange = ax.getRange(); - OWLObjectPropertyExpression propEx = ax.getProperty(); - if (propEx.isAnonymous()) { - error(ax, false); - } - OWLObjectProperty prop = propEx.asOWLObjectProperty(); - if (owlRange.isBottomEntity() || owlRange.isTopEntity()) { - // at least create the property frame - getTypedefFrame(prop); - // error message - error("ranges using top or bottom entities are not translatable to OBO.", - ax, false); - return; - } - String range = this.getIdentifier(owlRange); // getIdentifier(ax.getRange()); - if (range != null) { - if (trObjectProperty(prop, OboFormatTag.TAG_RANGE.getTag(), range, - ax.getAnnotations())) { - return; - } - } - error(ax, false); - } - - @SuppressWarnings("null") - protected void tr(@Nonnull OWLSubObjectPropertyOfAxiom ax) { - OWLObjectPropertyExpression sup = ax.getSuperProperty(); - OWLObjectPropertyExpression sub = ax.getSubProperty(); - if (sub.isBottomEntity() || sub.isTopEntity() || sup.isBottomEntity() - || sub.isTopEntity()) { - error("SubProperties using Top or Bottom entites are not supported in OBO.", - false); - return; - } - if (sub instanceof OWLObjectProperty - && sup instanceof OWLObjectProperty) { - String supId = this.getIdentifier(sup); - if (supId.startsWith("owl:")) { - return; - } - Frame f = getTypedefFrame((OWLObjectProperty) sub); - Clause clause = new Clause(OboFormatTag.TAG_IS_A, supId); - f.addClause(clause); - addQualifiers(clause, ax.getAnnotations()); - } else { - error(ax, true); - } - } - - @SuppressWarnings("null") - protected void tr(@Nonnull OWLSubAnnotationPropertyOfAxiom ax) { - OWLAnnotationProperty sup = ax.getSuperProperty(); - OWLAnnotationProperty sub = ax.getSubProperty(); - if (sub.isBottomEntity() || sub.isTopEntity() || sup.isBottomEntity() - || sub.isTopEntity()) { - error("SubAnnotationProperties using Top or Bottom entites are not supported in OBO.", - false); - return; - } - String _tag = owlObjectToTag(sup); - if (OboFormatTag.TAG_SYNONYMTYPEDEF.getTag().equals(_tag)) { - String name = ""; - String scope = null; - for (OWLAnnotationAssertionAxiom axiom : getOWLOntology() - .getAnnotationAssertionAxioms(sub.getIRI())) { - String tg = owlObjectToTag(axiom.getProperty()); - if (OboFormatTag.TAG_NAME.getTag().equals(tg)) { - name = ((OWLLiteral) axiom.getValue()).getLiteral(); - } else if (OboFormatTag.TAG_SCOPE.getTag().equals(tg)) { - scope = owlObjectToTag(axiom.getValue()); - } - } - Frame hf = getObodoc().getHeaderFrame(); - Clause clause = new Clause(OboFormatTag.TAG_SYNONYMTYPEDEF); - clause.addValue(this.getIdentifier(sub)); - clause.addValue(name); - if (scope != null) { - clause.addValue(scope); - } - addQualifiers(clause, ax.getAnnotations()); - if (!hf.getClauses().contains(clause)) { - hf.addClause(clause); - } else { - LOG.error("duplicate clause: {} in header", clause); - } - return; - } else if (OboFormatTag.TAG_SUBSETDEF.getTag().equals(_tag)) { - String comment = ""; - for (OWLAnnotationAssertionAxiom axiom : getOWLOntology() - .getAnnotationAssertionAxioms(sub.getIRI())) { - String tg = owlObjectToTag(axiom.getProperty()); - if (OboFormatTag.TAG_COMMENT.getTag().equals(tg)) { - comment = ((OWLLiteral) axiom.getValue()).getLiteral(); - break; - } - } - Frame hf = getObodoc().getHeaderFrame(); - Clause clause = new Clause(OboFormatTag.TAG_SUBSETDEF); - clause.addValue(this.getIdentifier(sub)); - clause.addValue(comment); - if (!hf.getClauses().contains(clause)) { - hf.addClause(clause); - } else { - LOG.error("duplicate clause: {} in header", clause); - } - addQualifiers(clause, ax.getAnnotations()); - return; - } - if (sub instanceof OWLObjectProperty - && sup instanceof OWLObjectProperty) { - String supId = this.getIdentifier(sup); // getIdentifier(sup); - if (supId.startsWith("owl:")) { - return; - } - Frame f = getTypedefFrame(sub); - Clause clause = new Clause(OboFormatTag.TAG_IS_A, supId); - f.addClause(clause); - addQualifiers(clause, ax.getAnnotations()); - } else { - error(ax, true); - } - } - - /** - * The absoulte url pattern. - */ - protected Pattern absoulteURLPattern = Pattern.compile("<\\s*http.*?>"); - - /** - * Tr. - * - * @param aanAx - * the aan ax - * @param frame - * the frame - */ - protected void tr(@Nonnull OWLAnnotationAssertionAxiom aanAx, - @Nonnull Frame frame) { - boolean success = tr(aanAx.getProperty(), aanAx.getValue(), - aanAx.getAnnotations(), frame); - if (!success) { - untranslatableAxioms.add(aanAx); - } - } - - /** - * Tr. - * - * @param prop - * the prop - * @param annVal - * the ann val - * @param qualifiers - * the qualifiers - * @param frame - * the frame - * @return true, if successful - */ - @SuppressWarnings("null") - protected boolean tr(OWLAnnotationProperty prop, - @Nonnull OWLAnnotationValue annVal, - @Nonnull Set qualifiers, @Nonnull Frame frame) { - String tagString = owlObjectToTag(prop); - OboFormatTag tag = null; - if (tagString != null) { - tag = OBOFormatConstants.getTag(tagString); - } - if (tag == null) { - // annotation property does not correspond to a mapping to a tag in - // the OBO syntax - - // use the property_value tag - return trGenericPropertyValue(prop, annVal, qualifiers, frame); - } - String value = getValue(annVal, tagString); - if (tagString == null) { - Clause clause = new Clause(OboFormatTag.TAG_PROPERTY_VALUE); - String propId = this.getIdentifier(prop); - addQualifiers(clause, qualifiers); - if (propId.equals("shorthand") == false) { - clause.addValue(propId); - clause.addValue(value); - // TODO - xsd types - frame.addClause(clause); - } - } else if (!value.trim().isEmpty()) { - if (tag == OboFormatTag.TAG_ID) { - if (frame.getId().equals(value) == false) { - warn("Conflicting id definitions: 1) " + frame.getId() - + " 2)" + value); - return false; - } - return true; - } - Clause clause = new Clause(tag); - if (tag == OboFormatTag.TAG_DATE) { - try { - clause.addValue(OBOFormatConstants.headerDateFormat.get() - .parseObject(value)); - } catch (ParseException e) { - error("Could not parse date string: " + value, true); - return false; - } - } else { - clause.addValue(value); - } - Set unprocessedQualifiers = new HashSet( - qualifiers); - if (tag == OboFormatTag.TAG_DEF) { - for (OWLAnnotation aan : qualifiers) { - String propId = owlObjectToTag(aan.getProperty()); - if ("xref".equals(propId)) { - OWLAnnotationValue v = aan.getValue(); - String xrefValue; - if (v instanceof IRI) { - xrefValue = ((IRI) v).toString(); - } else { - xrefValue = ((OWLLiteral) v).getLiteral(); - } - Xref xref = new Xref(xrefValue); - clause.addXref(xref); - unprocessedQualifiers.remove(aan); - } - } - } else if (tag == OboFormatTag.TAG_XREF) { - Xref xref = new Xref(value); - for (OWLAnnotation annotation : qualifiers) { - if (fac.getRDFSLabel().equals(annotation.getProperty())) { - OWLAnnotationValue owlAnnotationValue = annotation - .getValue(); - if (owlAnnotationValue instanceof OWLLiteral) { - unprocessedQualifiers.remove(annotation); - String xrefAnnotation = ((OWLLiteral) owlAnnotationValue) - .getLiteral(); - xrefAnnotation = xrefAnnotation.trim(); - if (!xrefAnnotation.isEmpty()) { - xref.setAnnotation(xrefAnnotation); - } - } - } - } - clause.setValue(xref); - } else if (tag == OboFormatTag.TAG_EXACT - || tag == OboFormatTag.TAG_NARROW - || tag == OboFormatTag.TAG_BROAD - || tag == OboFormatTag.TAG_RELATED) { - handleSynonym(qualifiers, tag.getTag(), clause, - unprocessedQualifiers); - } else if (tag == OboFormatTag.TAG_SYNONYM) { - // This should never happen. - // All synonyms need to be qualified with a type. - String synonymType = null; - handleSynonym(qualifiers, synonymType, clause, - unprocessedQualifiers); - } - addQualifiers(clause, unprocessedQualifiers); - // before adding the clause check for redundant clauses - boolean redundant = false; - for (Clause frameClause : frame.getClauses()) { - if (clause.equals(frameClause)) { - redundant = handleDuplicateClause(frame, frameClause); - } - } - if (!redundant) { - frame.addClause(clause); - } - } else { - return false; - } - return true; - } - - /** - * Handle synonym. - * - * @param qualifiers - * the qualifiers - * @param scope - * the scope - * @param clause - * the clause - * @param unprocessedQualifiers - * the unprocessed qualifiers - */ - protected void handleSynonym(@Nonnull Set qualifiers, - @Nullable String scope, @Nonnull Clause clause, - @Nonnull Set unprocessedQualifiers) { - clause.setTag(OboFormatTag.TAG_SYNONYM.getTag()); - String type = null; - clause.setXrefs(new ArrayList()); - for (OWLAnnotation aan : qualifiers) { - String propId = owlObjectToTag(aan.getProperty()); - if (OboFormatTag.TAG_XREF.getTag().equals(propId)) { - OWLAnnotationValue v = aan.getValue(); - String xrefValue; - if (v instanceof IRI) { - xrefValue = ((IRI) v).toString(); - } else { - xrefValue = ((OWLLiteral) v).getLiteral(); - } - Xref xref = new Xref(xrefValue); - clause.addXref(xref); - unprocessedQualifiers.remove(aan); - } else if (OboFormatTag.TAG_HAS_SYNONYM_TYPE.getTag() - .equals(propId)) { - type = getIdentifier(aan.getValue()); - unprocessedQualifiers.remove(aan); - } - } - if (scope != null) { - clause.addValue(scope); - if (type != null) { - clause.addValue(type); - } - } - } - - /** - * Handle a duplicate clause in a frame during translation. - * - * @param frame - * the frame - * @param clause - * the clause - * @return true if the clause is to be marked as redundant and will not be - * added to the - */ - protected boolean - handleDuplicateClause(@Nonnull Frame frame, Clause clause) { - // default is to report it via the logger and remove it. - LOG.error("Duplicate clause '{}' generated in frame: {}", clause, - frame.getId()); - return true; - } - - /** - * Tr generic property value. - * - * @param prop - * the prop - * @param annVal - * the ann val - * @param qualifiers - * the qualifiers - * @param frame - * the frame - * @return true, if successful - */ - @SuppressWarnings("null") - protected boolean trGenericPropertyValue(OWLAnnotationProperty prop, - OWLAnnotationValue annVal, @Nonnull Set qualifiers, - @Nonnull Frame frame) { - // no built-in obo tag for this: use the generic property_value tag - Clause clause = new Clause(OboFormatTag.TAG_PROPERTY_VALUE.getTag()); - String propId = this.getIdentifier(prop); - addQualifiers(clause, qualifiers); - if (propId.equals("shorthand") == false) { - clause.addValue(propId); - if (annVal instanceof OWLLiteral) { - OWLLiteral owlLiteral = (OWLLiteral) annVal; - clause.addValue(owlLiteral.getLiteral()); - OWLDatatype datatype = owlLiteral.getDatatype(); - IRI dataTypeIri = datatype.getIRI(); - if (!OWL2Datatype.isBuiltIn(dataTypeIri)) { - error("Untranslatable axiom due to unknown data type: " - + annVal, true); - return false; - } - if (Namespaces.XSD.inNamespace(dataTypeIri)) { - clause.addValue("xsd:" + dataTypeIri.getFragment()); - } else if (dataTypeIri.isPlainLiteral()) { - clause.addValue("xsd:string"); - } else { - clause.addValue(dataTypeIri.toString()); - } - } else if (annVal instanceof IRI) { - clause.addValue(getIdentifier((IRI) annVal)); - } - frame.addClause(clause); - } - return true; - } - - /** - * Gets the value. - * - * @param annVal - * the ann val - * @param tag - * the tag - * @return the value - */ - @SuppressWarnings("null") - @Nullable - protected String getValue(@Nonnull OWLAnnotationValue annVal, String tag) { - String value = annVal.toString(); - if (annVal instanceof OWLLiteral) { - value = ((OWLLiteral) annVal).getLiteral(); - } else if (annVal instanceof IRI) { - value = getIdentifier((IRI) annVal); - } - if (OboFormatTag.TAG_EXPAND_EXPRESSION_TO.getTag().equals(tag)) { - Matcher matcher = absoulteURLPattern.matcher(value); - while (matcher.find()) { - String m = matcher.group(); - m = m.replace("<", ""); - m = m.replace(">", ""); - int i = m.lastIndexOf("/"); - m = m.substring(i + 1); - value = value.replace(matcher.group(), m); - } - } - return value; - } - - /** - * Adds the qualifiers. - * - * @param c - * the c - * @param qualifiers - * the qualifiers - */ - protected void addQualifiers(@Nonnull Clause c, - @Nonnull Set qualifiers) { - for (OWLAnnotation ann : qualifiers) { - String prop = owlObjectToTag(ann.getProperty()); - if (prop == null) { - prop = ann.getProperty().getIRI().toString(); - } - if (prop.equals("gci_relation") || prop.equals("gci_filler") - || prop.equals("cardinality") - || prop.equals("minCardinality") - || prop.equals("maxCardinality") || prop.equals("all_some") - || prop.equals("all_only")) { - continue; - } - String value = ann.getValue().toString(); - if (ann.getValue() instanceof OWLLiteral) { - value = ((OWLLiteral) ann.getValue()).getLiteral(); - } else if (ann.getValue() instanceof IRI) { - value = getIdentifier((IRI) ann.getValue()); - } - QualifierValue qv = new QualifierValue(prop, value); - c.addQualifierValue(qv); - } - } - - /** - * E.g. http://purl.obolibrary.org/obo/go.owl to "go"
- * if does not match this pattern, then retain original IRI - * - * @param ontology - * the ontology - * @return The OBO ID of the ontology - */ - @SuppressWarnings("null") - public static String getOntologyId(@Nonnull OWLOntology ontology) { - return getOntologyId(ontology.getOntologyID().getOntologyIRI().get()); - } - - /** - * Gets the ontology id. - * - * @param iriObj - * the iri obj - * @return the ontology id - */ - public static String getOntologyId(@Nonnull IRI iriObj) { - // String id = getIdentifier(ontology.getOntologyID().getOntologyIRI()); - String iri = iriObj.toString(); - String id; - if (iri.startsWith("http://purl.obolibrary.org/obo/")) { - id = iri.replace("http://purl.obolibrary.org/obo/", ""); - if (id.endsWith(".owl")) { - id = id.replaceFirst(".owl$", ""); - } - } else { - id = iri; - } - // int index = iri.lastIndexOf("/"); - // id = iri.substring(index+1); - // index = id.lastIndexOf(".owl"); - // if(index>0){ - // id = id.substring(0, index); - // } - return id; - } - - /** - * Gets the data version. - * - * @param ontology - * the ontology - * @return the data version - */ - @Nullable - public static String getDataVersion(@Nonnull OWLOntology ontology) { - String oid = getOntologyId(ontology); - Optional v = ontology.getOntologyID().getVersionIRI(); - if (v.isPresent()) { - String vs = v.get().toString() - .replace("http://purl.obolibrary.org/obo/", ""); - vs = vs.replaceFirst(oid + "/", ""); - vs = vs.replace("/" + oid + ".owl", ""); - return vs; - } - return null; - } - - /** - * Tr. - * - * @param ontology - * the ontology - */ - protected void tr(@Nonnull OWLOntology ontology) { - Frame f = new Frame(FrameType.HEADER); - getObodoc().setHeaderFrame(f); - for (IRI iri : ontology.getDirectImportsDocuments()) { - Clause c = new Clause(OboFormatTag.TAG_IMPORT.getTag()); - // c.setValue(getOntologyId(iri)); - c.setValue(iri.toString()); - f.addClause(c); - } - String id = getOntologyId(ontology); - Clause c = new Clause(OboFormatTag.TAG_ONTOLOGY.getTag()); - c.setValue(id); - f.addClause(c); - String vid = getDataVersion(ontology); - if (vid != null) { - Clause c2 = new Clause(OboFormatTag.TAG_DATA_VERSION.getTag()); - c2.setValue(vid); - f.addClause(c2); - } - for (OWLAnnotation ann : ontology.getAnnotations()) { - OWLAnnotationProperty property = ann.getProperty(); - String tagString = owlObjectToTag(property); - if (OboFormatTag.TAG_COMMENT.getTag().equals(tagString)) { - property = fac.getOWLAnnotationProperty(OWLAPIObo2Owl - .trTagToIRI(OboFormatTag.TAG_REMARK.getTag())); - } - tr(property, ann.getValue(), ann.getAnnotations(), f); - } - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLEquivalentClassesAxiom ax) { - /* - * Assumption: the underlying data structure is a set The order is not - * guaranteed to be preserved. - */ - Set expressions = ax.getClassExpressions(); - // handle expression list with size other than two elements as error - if (expressions.size() != 2) { - error(ax, false); - return; - } - Iterator it = expressions.iterator(); - OWLClassExpression ce1 = it.next(); - OWLClassExpression ce2 = it.next(); - if (ce1.isBottomEntity() || ce1.isTopEntity() || ce2.isBottomEntity() - || ce2.isTopEntity()) { - error("Equivalent classes axioms using Top or Bottom entities are not supported in OBO.", - ax, false); - return; - } - if (ce1 instanceof OWLClass == false) { - // check whether ce2 is the actual OWLEntity - if (ce2 instanceof OWLClass) { - // three way exchange - OWLClassExpression temp = ce2; - ce2 = ce1; - ce1 = temp; - } else { - // this might happen for some GCI axioms, which are not - // expressible in OBO - error("GCI axioms are not expressible in OBO.", ax, false); - return; - } - } - Frame f = getTermFrame(ce1.asOWLClass()); - if (f == null) { - error(ax, false); - return; - } - boolean isUntranslateable = false; - List equivalenceAxiomClauses = new ArrayList(); - String cls2 = this.getIdentifier(ce2); - if (cls2 != null) { - Clause c = new Clause(OboFormatTag.TAG_EQUIVALENT_TO.getTag()); - c.setValue(cls2); - f.addClause(c); - addQualifiers(c, ax.getAnnotations()); - } else if (ce2 instanceof OWLObjectUnionOf) { - List list2 = ((OWLObjectUnionOf) ce2) - .getOperandsAsList(); - for (OWLClassExpression oce : list2) { - String id = this.getIdentifier(oce); - if (id == null) { - isUntranslateable = true; - error(ax, true); - return; - } - Clause c = new Clause(OboFormatTag.TAG_UNION_OF.getTag()); - c.setValue(id); - equivalenceAxiomClauses.add(c); - addQualifiers(c, ax.getAnnotations()); - } - } else if (ce2 instanceof OWLObjectIntersectionOf) { - List list2 = ((OWLObjectIntersectionOf) ce2) - .getOperandsAsList(); - for (OWLClassExpression ce : list2) { - String r = null; - cls2 = this.getIdentifier(ce); - Integer exact = null; // cardinality - Integer min = null; // minCardinality - Integer max = null; // maxCardinality - Boolean allSome = null; // all_some - Boolean allOnly = null; // all_only - if (ce instanceof OWLObjectSomeValuesFrom) { - OWLObjectSomeValuesFrom ristriction = (OWLObjectSomeValuesFrom) ce; - r = this.getIdentifier(ristriction.getProperty()); - cls2 = this.getIdentifier(ristriction.getFiller()); - } else if (ce instanceof OWLObjectExactCardinality) { - OWLObjectExactCardinality card = (OWLObjectExactCardinality) ce; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - exact = card.getCardinality(); - } else if (ce instanceof OWLObjectMinCardinality) { - OWLObjectMinCardinality card = (OWLObjectMinCardinality) ce; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - min = card.getCardinality(); - } else if (ce instanceof OWLObjectMaxCardinality) { - OWLObjectMaxCardinality card = (OWLObjectMaxCardinality) ce; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - max = card.getCardinality(); - } else if (ce instanceof OWLObjectAllValuesFrom) { - OWLObjectAllValuesFrom all = (OWLObjectAllValuesFrom) ce; - OWLClassExpression filler = all.getFiller(); - if (filler instanceof OWLClass) { - r = this.getIdentifier(all.getProperty()); - cls2 = this.getIdentifier(filler); - allOnly = Boolean.TRUE; - } else if (filler instanceof OWLObjectComplementOf) { - OWLObjectComplementOf restriction = (OWLObjectComplementOf) filler; - r = this.getIdentifier(all.getProperty()); - cls2 = this.getIdentifier(restriction.getOperand()); - exact = 0; - } - } else if (ce instanceof OWLObjectIntersectionOf) { - // either a min-max or a some-all combination - Set operands = ((OWLObjectIntersectionOf) ce) - .getOperands(); - if (operands.size() == 2) { - for (OWLClassExpression operand : operands) { - if (operand instanceof OWLObjectMinCardinality) { - OWLObjectMinCardinality card = (OWLObjectMinCardinality) operand; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - min = card.getCardinality(); - } else if (operand instanceof OWLObjectMaxCardinality) { - OWLObjectMaxCardinality card = (OWLObjectMaxCardinality) operand; - r = this.getIdentifier(card.getProperty()); - cls2 = this.getIdentifier(card.getFiller()); - max = card.getCardinality(); - } else if (operand instanceof OWLObjectAllValuesFrom) { - OWLObjectAllValuesFrom all = (OWLObjectAllValuesFrom) operand; - r = this.getIdentifier(all.getProperty()); - cls2 = this.getIdentifier(all.getFiller()); - allOnly = Boolean.TRUE; - } else if (operand instanceof OWLObjectSomeValuesFrom) { - OWLObjectSomeValuesFrom all = (OWLObjectSomeValuesFrom) operand; - r = this.getIdentifier(all.getProperty()); - cls2 = this.getIdentifier(all.getFiller()); - allSome = Boolean.TRUE; - } - } - } - } - if (cls2 != null) { - Clause c = new Clause( - OboFormatTag.TAG_INTERSECTION_OF.getTag()); - if (r != null) { - c.addValue(r); - } - c.addValue(cls2); - equivalenceAxiomClauses.add(c); - if (exact != null) { - c.addQualifierValue(new QualifierValue("cardinality", - exact.toString())); - } - if (min != null) { - c.addQualifierValue(new QualifierValue( - "minCardinality", min.toString())); - } - if (max != null) { - c.addQualifierValue(new QualifierValue( - "maxCardinality", max.toString())); - } - if (allSome != null) { - c.addQualifierValue(new QualifierValue("all_some", - allSome.toString())); - } - if (allOnly != null) { - c.addQualifierValue(new QualifierValue("all_only", - allOnly.toString())); - } - addQualifiers(c, ax.getAnnotations()); - } else if (!f.getClauses(OboFormatTag.TAG_INTERSECTION_OF).isEmpty()) { - error("The axiom is not translated (maximimum one IntersectionOf EquivalenceAxiom)", - ax, false); - } else { - isUntranslateable = true; - error(ax, false); - } - } - } else { - isUntranslateable = true; - error(ax, false); - } - // Only add clauses if the *entire* equivalence axiom can be translated - if (!isUntranslateable) { - for (Clause c : equivalenceAxiomClauses) { - f.addClause(c); - } - } - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLDisjointClassesAxiom ax) { - // use set, the OWL-API does not provide an order - Set set = ax.getClassExpressions(); - if (set.size() != 2) { - error("Expected two classes in a disjoin classes axiom.", ax, false); - } - Iterator it = set.iterator(); - OWLClassExpression ce1 = it.next(); - OWLClassExpression ce2 = it.next(); - if (ce1.isBottomEntity() || ce1.isTopEntity() || ce2.isBottomEntity() - || ce2.isTopEntity()) { - error("Disjoint classes axiom using Top or Bottom entities are not supported.", - ax, false); - } - String cls2 = this.getIdentifier(ce2); - if (cls2 == null) { - error(ax, true); - return; - } - if (ce1.isAnonymous()) { - error(ax, false); - return; - } - OWLClass cls1 = ce1.asOWLClass(); - Frame f = getTermFrame(cls1); - Clause c = new Clause(OboFormatTag.TAG_DISJOINT_FROM.getTag()); - c.setValue(cls2); - f.addClause(c); - addQualifiers(c, ax.getAnnotations()); - } - - /** - * Tr. - * - * @param axiom - * the axiom - */ - protected void tr(@Nonnull OWLDeclarationAxiom axiom) { - OWLEntity entity = axiom.getEntity(); - if (entity.isBottomEntity() || entity.isTopEntity()) { - return; - } - Collection set = getOWLOntology() - .filterAxioms(Filters.annotations, entity.getIRI(), INCLUDED); - if (set.isEmpty()) { - return; - } - Frame f = null; - if (entity instanceof OWLClass) { - f = getTermFrame(entity.asOWLClass()); - } else if (entity instanceof OWLObjectProperty) { - f = getTypedefFrame(entity.asOWLObjectProperty()); - } else if (entity instanceof OWLAnnotationProperty) { - for (OWLAxiom a : set) { - OWLAnnotationAssertionAxiom ax = (OWLAnnotationAssertionAxiom) a; - OWLAnnotationProperty prop = ax.getProperty(); - String tag = owlObjectToTag(prop); - if (OboFormatTag.TAG_IS_METADATA_TAG.getTag().equals(tag)) { - f = getTypedefFrame(entity); - break; - } - } - } - if (f != null) { - for (OWLAnnotationAssertionAxiom a : set) { - assert a != null; - tr(a, f); - } - add(f); - return; - } - } - - /** - * Gets the identifier. - * - * @param obj - * the obj - * @return the identifier - */ - @Nullable - public String getIdentifier(OWLObject obj) { - try { - return getIdentifierFromObject(obj, getOWLOntology()); - } catch (UntranslatableAxiomException e) { - error(e.getMessage(), true); - } - return null; - } - - /** - * @return true if untranslatable axioms should not be logged - */ - public boolean isMuteUntranslatableAxioms() { - return muteUntranslatableAxioms; - } - - /** - * @param muteUntranslatableAxioms - * true disables logging - */ - public void setMuteUntranslatableAxioms(boolean muteUntranslatableAxioms) { - this.muteUntranslatableAxioms = muteUntranslatableAxioms; - } - - /** - * The Class UntranslatableAxiomException. - */ - public static class UntranslatableAxiomException extends Exception { - - // generated - private static final long serialVersionUID = 40000L; - - /** - * Instantiates a new untranslatable axiom exception. - * - * @param message - * the message - * @param cause - * the cause - */ - public UntranslatableAxiomException(String message, Throwable cause) { - super(message, cause); - } - - /** - * Instantiates a new untranslatable axiom exception. - * - * @param message - * the message - */ - public UntranslatableAxiomException(String message) { - super(message); - } - } - - /** - * Retrieve the identifier for a given {@link OWLObject}. This methods uses - * also shorthand hints to resolve the identifier. Should the translation - * process encounter a problem or not find an identifier the defaultValue is - * returned. - * - * @param obj - * the {@link OWLObject} to resolve - * @param ont - * the target ontology - * @param defaultValue - * the value to return in case of an error or no id - * @return identifier or the default value - */ - @Nonnull - public static String getIdentifierFromObject(@Nonnull OWLObject obj, - @Nonnull OWLOntology ont, @Nonnull String defaultValue) { - String id = defaultValue; - try { - id = getIdentifierFromObject(obj, ont); - if (id == null) { - id = defaultValue; - } - } catch (UntranslatableAxiomException e) { - LOG.error(e.getMessage(), e); - } - return id; - } - - /** - * Retrieve the identifier for a given {@link OWLObject}. This methods uses - * also shorthand hints to resolve the identifier. Should the translation - * process encounter an unexpected axiom an - * - * @param obj - * the {@link OWLObject} to resolve - * @param ont - * the target ontology - * @return identifier or null - * @throws UntranslatableAxiomException - * the untranslatable axiom exception - * {@link UntranslatableAxiomException} is thrown. - */ - @SuppressWarnings("null") - @Nullable - public static String getIdentifierFromObject(OWLObject obj, - @Nonnull OWLOntology ont) throws UntranslatableAxiomException { - if (obj instanceof OWLObjectProperty - || obj instanceof OWLAnnotationProperty) { - OWLEntity entity = (OWLEntity) obj; - Collection filterAxioms = ont.filterAxioms( - Filters.annotations, entity.getIRI(), INCLUDED); - for (OWLAxiom a : filterAxioms) { - OWLAnnotationAssertionAxiom ax = (OWLAnnotationAssertionAxiom) a; - String propId = getIdentifierFromObject(ax.getProperty() - .getIRI(), ont); - // see BFOROXrefTest - // 5.9.3. Special Rules for Relations - if (propId.equals("shorthand")) { - OWLAnnotationValue value = ax.getValue(); - if (value instanceof OWLLiteral) { - return ((OWLLiteral) value).getLiteral(); - } - throw new UntranslatableAxiomException( - "Untranslatable axiom, expected literal value, but was: " - + value + " in axiom: " + ax); - } - } - } - if (obj instanceof OWLEntity) { - return getIdentifier(((OWLEntity) obj).getIRI()); - } - if (obj instanceof IRI) { - return getIdentifier((IRI) obj); - } - return null; - } - - /** - * See table 5.9.2. Translation of identifiers - * - * @param iriId - * the iri id - * @return obo identifier or null - */ - @Nullable - public static String getIdentifier(@Nullable IRI iriId) { - if (iriId == null) { - return null; - } - String iri = iriId.toString(); - // canonical IRIs - // if (iri.startsWith("http://purl.obolibrary.org/obo/")) { - // String canonicalId = iri.replace("http://purl.obolibrary.org/obo/", - // ""); - // } - int indexSlash = iri.lastIndexOf("/"); - String id = null; - if (indexSlash > -1) { - id = iri.substring(indexSlash + 1); - } else { - id = iri; - } - String[] s = id.split("#_"); - // table 5.9.2 row 2 - NonCanonical-Prefixed-ID - if (s.length > 1) { - return s[0] + ":" + s[1]; - } - // row 3 - Unprefixed-ID - s = id.split("#"); - if (s.length > 1) { - // prefixURI = prefixURI + s[0] + "#"; - // if(!(s[1].contains("#") || s[1].contains("_"))){ - String prefix = ""; - if ("owl".equals(s[0]) || "rdf".equals(s[0]) || "rdfs".equals(s[0])) { - prefix = s[0] + ":"; - } - // TODO: the following implements behavior in current spec, but this - // leads to undesirable results - // else if (baseOntology != null) { - // String oid = getOntologyId(baseOntology); // OBO-style ID - // if (oid.equals(s[0])) - // prefix = ""; - // else { - // return iri; - // } - // //prefix = s[0]; - // } - return prefix + s[1]; - } - // row 1 - Canonical-Prefixed-ID - s = id.split("_"); - if (s.length == 2 && !id.contains("#") && !s[1].contains("_")) { - String localId; - try { - localId = java.net.URLDecoder.decode(s[1], "UTF-8"); - return s[0] + ":" + localId; - } catch (UnsupportedEncodingException e) { - throw new RuntimeException( - "UTF-8 not supported, JRE corrupted?", e); - } - } - if (s.length > 2 && !id.contains("#")) { - if (s[s.length - 1].replaceAll("[0-9]", "").isEmpty()) { - StringBuffer sb = new StringBuffer(); - for (int i = 0; i < s.length; i++) { - if (i > 0) { - if (i == s.length - 1) { - sb.append(":"); - } else { - sb.append("_"); - } - } - sb.append(s[i]); - } - return sb.toString(); - } - } - return iri; - } - - /** - * Owl object to tag. - * - * @param obj - * the obj - * @return the string - */ - @Nullable - public static String owlObjectToTag(OWLObject obj) { - IRI iriObj = null; - if (obj instanceof OWLNamedObject) { - iriObj = ((OWLNamedObject) obj).getIRI(); - } else if (obj instanceof IRI) { - iriObj = (IRI) obj; - } - if (iriObj == null) { - return null; - } - String iri = iriObj.toString(); - String tag = annotationPropertyMap.get(iri); - if (tag == null) { - // hardcoded values for legacy annotation properties: (TEMPORARY) - if (iri.startsWith(Obo2OWLConstants.DEFAULT_IRI_PREFIX + "IAO_")) { - String legacyId = iri.replace( - Obo2OWLConstants.DEFAULT_IRI_PREFIX, ""); - if (legacyId.equals("IAO_xref")) { - return OboFormatTag.TAG_XREF.getTag(); - } - if (legacyId.equals("IAO_id")) { - return OboFormatTag.TAG_ID.getTag(); - } - if (legacyId.equals("IAO_namespace")) { - return OboFormatTag.TAG_NAMESPACE.getTag(); - } - } - String prefix = Obo2OWLConstants.OIOVOCAB_IRI_PREFIX; - if (iri.startsWith(prefix)) { - tag = iri.substring(prefix.length()); - } - } - return tag; - } - - /** - * Gets the term frame. - * - * @param entity - * the entity - * @return the term frame - */ - protected Frame getTermFrame(@Nonnull OWLClass entity) { - String id = getIdentifier(entity.getIRI()); - Frame f = getObodoc().getTermFrame(id); - if (f == null) { - f = new Frame(FrameType.TERM); - f.setId(id); - f.addClause(new Clause(OboFormatTag.TAG_ID, id)); - add(f); - } - return f; - } - - /** - * Gets the typedef frame. - * - * @param entity - * the entity - * @return the typedef frame - */ - protected Frame getTypedefFrame(OWLEntity entity) { - String id = this.getIdentifier(entity); - Frame f = getObodoc().getTypedefFrame(id); - if (f == null) { - f = new Frame(FrameType.TYPEDEF); - f.setId(id); - f.addClause(new Clause(OboFormatTag.TAG_ID, id)); - add(f); - } - return f; - } - - /** - * Tr. - * - * @param ax - * the ax - */ - @SuppressWarnings("null") - protected void tr(@Nonnull OWLClassAssertionAxiom ax) { - OWLObject cls = ax.getClassExpression(); - if (!(cls instanceof OWLClass)) { - return; - } - String clsIRI = ((OWLClass) cls).getIRI().toString(); - if (IRI_CLASS_SYNONYMTYPEDEF.equals(clsIRI)) { - Frame f = getObodoc().getHeaderFrame(); - Clause c = new Clause(OboFormatTag.TAG_SYNONYMTYPEDEF.getTag()); - OWLNamedIndividual indv = (OWLNamedIndividual) ax.getIndividual(); - String indvId = this.getIdentifier(indv); - // TODO: full specify this in the spec document. - // we may want to allow full IDs for subsets in future. - // here we would have a convention that an unprefixed - // subsetdef/synonymtypedef - // gets placed in a temp ID space, and only this id space is - // stripped - indvId = indvId.replaceFirst(".*:", ""); - c.addValue(indvId); - c.addValue(indvId); - String nameValue = ""; - String scopeValue = null; - for (OWLAnnotation ann : annotations(getOWLOntology() - .getAnnotationAssertionAxioms(indv.getIRI()))) { - String propId = ann.getProperty().getIRI().toString(); - String value = ((OWLLiteral) ann.getValue()).getLiteral(); - if (OWLRDFVocabulary.RDFS_LABEL.getIRI().toString() - .equals(propId)) { - nameValue = "\"" + value + "\""; - } else { - scopeValue = value; - } - } - c.addValue(nameValue); - if (scopeValue != null) { - c.addValue(scopeValue); - } - f.addClause(c); - } else if (IRI_CLASS_SUBSETDEF.equals(clsIRI)) { - Frame f = getObodoc().getHeaderFrame(); - Clause c = new Clause(OboFormatTag.TAG_SUBSETDEF.getTag()); - OWLNamedIndividual indv = (OWLNamedIndividual) ax.getIndividual(); - String indvId = this.getIdentifier(indv); - // TODO: full specify this in the spec document. - // we may want to allow full IDs for subsets in future. - // here we would have a convention that an unprefixed - // subsetdef/synonymtypedef - // gets placed in a temp ID space, and only this id space is - // stripped - indvId = indvId.replaceFirst(".*:", ""); - c.addValue(indvId); - String nameValue = ""; - for (OWLAnnotation ann : annotations(getOWLOntology() - .getAnnotationAssertionAxioms(indv.getIRI()))) { - String propId = ann.getProperty().getIRI().toString(); - String value = ((OWLLiteral) ann.getValue()).getLiteral(); - if (OWLRDFVocabulary.RDFS_LABEL.getIRI().toString() - .equals(propId)) { - nameValue = "\"" + value + "\""; - } - } - c.addValue(nameValue); - f.addClause(c); - } else { - // TODO: individual - } - } - - /** - * Tr. - * - * @param ax - * the ax - */ - protected void tr(@Nonnull OWLSubClassOfAxiom ax) { - OWLClassExpression sub = ax.getSubClass(); - OWLClassExpression sup = ax.getSuperClass(); - Set qvs = new HashSet(); - if (sub.isOWLNothing() || sub.isTopEntity() || sup.isTopEntity() - || sup.isOWLNothing()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - // 5.2.2 - if (sub instanceof OWLObjectIntersectionOf) { - Set xs = ((OWLObjectIntersectionOf) sub) - .getOperands(); - // obo-format is limited to very restricted GCIs - the LHS of the - // axiom - // must correspond to ObjectIntersectionOf(cls - // ObjectSomeValuesFrom(p filler)) - if (xs.size() == 2) { - OWLClass c = null; - OWLObjectSomeValuesFrom r = null; - OWLObjectProperty p = null; - OWLClass filler = null; - for (OWLClassExpression x : xs) { - if (x instanceof OWLClass) { - c = (OWLClass) x; - } - if (x instanceof OWLObjectSomeValuesFrom) { - r = (OWLObjectSomeValuesFrom) x; - if (r.getProperty() instanceof OWLObjectProperty) { - if (r.getFiller() instanceof OWLClass) { - p = (OWLObjectProperty) r.getProperty(); - filler = (OWLClass) r.getFiller(); - } - } - } - } - if (c != null && p != null && filler != null) { - sub = c; - qvs.add(new QualifierValue("gci_relation", getIdentifier(p))); - qvs.add(new QualifierValue("gci_filler", - getIdentifier(filler))); - } - } - } - if (sub instanceof OWLClass) { - Frame f = getTermFrame((OWLClass) sub); - if (sup instanceof OWLClass) { - Clause c = new Clause(OboFormatTag.TAG_IS_A.getTag()); - c.setValue(this.getIdentifier(sup)); - c.setQualifierValues(qvs); - f.addClause(c); - addQualifiers(c, ax.getAnnotations()); - } else if (sup instanceof OWLQuantifiedObjectRestriction) { - // OWLObjectSomeValuesFrom - // OWLObjectAllValuesFrom - OWLQuantifiedObjectRestriction r = (OWLQuantifiedObjectRestriction) sup; - OWLClassExpression filler = r.getFiller(); - if (filler.isBottomEntity() || filler.isTopEntity()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - String fillerId = this.getIdentifier(filler); - if (fillerId == null) { - error(ax, true); - return; - } - f.addClause(createRelationshipClauseWithRestrictions(r, - fillerId, qvs, ax)); - } else if (sup instanceof OWLObjectCardinalityRestriction) { - // OWLObjectExactCardinality - // OWLObjectMinCardinality - // OWLObjectMaxCardinality - OWLObjectCardinalityRestriction cardinality = (OWLObjectCardinalityRestriction) sup; - OWLClassExpression filler = cardinality.getFiller(); - if (filler.isBottomEntity() || filler.isTopEntity()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - String fillerId = this.getIdentifier(filler); - if (fillerId == null) { - error(ax, true); - return; - } - f.addClause(createRelationshipClauseWithCardinality( - cardinality, fillerId, qvs, ax)); - } else if (sup instanceof OWLObjectIntersectionOf) { - OWLObjectIntersectionOf i = (OWLObjectIntersectionOf) sup; - List clauses = new ArrayList(); - for (OWLClassExpression operand : i.getOperands()) { - if (operand instanceof OWLQuantifiedObjectRestriction) { - OWLQuantifiedObjectRestriction restriction = (OWLQuantifiedObjectRestriction) operand; - OWLClassExpression filler = restriction.getFiller(); - if (filler.isBottomEntity() || filler.isTopEntity()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - String fillerId = this.getIdentifier(filler); - if (fillerId == null) { - error(ax, true); - return; - } - clauses.add(createRelationshipClauseWithRestrictions( - restriction, fillerId, - new HashSet(qvs), ax)); - } else if (operand instanceof OWLObjectCardinalityRestriction) { - OWLObjectCardinalityRestriction restriction = (OWLObjectCardinalityRestriction) operand; - OWLClassExpression filler = restriction.getFiller(); - if (filler.isBottomEntity() || filler.isTopEntity()) { - error("Assertions using owl:Thing or owl:Nothing are not translateable OBO", - ax, false); - return; - } - String fillerId = this.getIdentifier(filler); - if (fillerId == null) { - error(ax, true); - return; - } - clauses.add(createRelationshipClauseWithCardinality( - restriction, fillerId, - new HashSet(qvs), ax)); - } else { - error(ax, true); - return; - } - } - if (clauses.isEmpty()) { - error(ax, true); - return; - } - clauses = normalizeRelationshipClauses(clauses); - for (Clause clause : clauses) { - f.addClause(clause); - } - } else { - error(ax, true); - return; - } - } else { - error(ax, true); - return; - } - } - - /** - * Creates the relationship clause with restrictions. - * - * @param r - * the r - * @param fillerId - * the filler id - * @param qvs - * the qvs - * @param ax - * the ax - * @return the clause - */ - @Nonnull - protected Clause createRelationshipClauseWithRestrictions( - @Nonnull OWLQuantifiedObjectRestriction r, String fillerId, - @Nonnull Set qvs, @Nonnull OWLSubClassOfAxiom ax) { - Clause c = new Clause(OboFormatTag.TAG_RELATIONSHIP.getTag()); - c.addValue(this.getIdentifier(r.getProperty())); - c.addValue(fillerId); - c.setQualifierValues(qvs); - addQualifiers(c, ax.getAnnotations()); - return c; - } - - /** - * Creates the relationship clause with cardinality. - * - * @param restriction - * the restriction - * @param fillerId - * the filler id - * @param qvs - * the qvs - * @param ax - * the ax - * @return the clause - */ - @Nonnull - protected Clause createRelationshipClauseWithCardinality( - @Nonnull OWLObjectCardinalityRestriction restriction, - String fillerId, @Nonnull Set qvs, - @Nonnull OWLSubClassOfAxiom ax) { - Clause c = new Clause(OboFormatTag.TAG_RELATIONSHIP.getTag()); - c.addValue(this.getIdentifier(restriction.getProperty())); - c.addValue(fillerId); - c.setQualifierValues(qvs); - String q = "cardinality"; - if (restriction instanceof OWLObjectMinCardinality) { - q = "minCardinality"; - } else if (restriction instanceof OWLObjectMaxCardinality) { - q = "maxCardinality"; - } - c.addQualifierValue(new QualifierValue(q, Integer.toString(restriction - .getCardinality()))); - addQualifiers(c, ax.getAnnotations()); - return c; - } - - /** - * Join clauses and its {@link QualifierValue} which have the same - * relationship type and target. Try to resolve conflicts for multiple - * statements. E.g., min=2 and min=3 is resolved to min=2, or max=2 and - * max=4 is resolved to max=4. It will not merge conflicting exact - * cardinality statements. TODO How to merge "all_some", and "all_only"? - * - * @param clauses - * the clauses - * @return normalized list of {@link Clause} - */ - @Nonnull - public static List normalizeRelationshipClauses( - @Nonnull List clauses) { - List normalized = new ArrayList(); - while (!clauses.isEmpty()) { - Clause target = clauses.remove(0); - assert target != null; - List similar = findSimilarClauses(clauses, target); - normalized.add(target); - mergeSimilarIntoTarget(target, similar); - } - return normalized; - } - - /** - * Find similar clauses. - * - * @param clauses - * the clauses - * @param target - * the target - * @return the list - */ - @SuppressWarnings("null") - @Nonnull - static List findSimilarClauses(@Nonnull List clauses, - @Nonnull Clause target) { - String targetTag = target.getTag(); - Object targetValue = target.getValue(); - Object targetValue2 = target.getValue2(); - List similar = new ArrayList(); - Iterator iterator = clauses.iterator(); - while (iterator.hasNext()) { - Clause current = iterator.next(); - Object currentValue = current.getValue(); - Object currentValue2 = current.getValue2(); - if (targetTag.equals(current.getTag()) - && targetValue.equals(currentValue)) { - if (targetValue2 == null) { - if (currentValue2 == null) { - similar.add(current); - iterator.remove(); - } - } else if (targetValue2.equals(currentValue2)) { - similar.add(current); - iterator.remove(); - } - } - } - return similar; - } - - /** - * Merge similar into target. - * - * @param target - * the target - * @param similar - * the similar - */ - static void mergeSimilarIntoTarget(@Nonnull Clause target, - @Nonnull List similar) { - if (similar.isEmpty()) { - return; - } - Collection targetQVs = target.getQualifierValues(); - for (Clause current : similar) { - Collection newQVs = current.getQualifierValues(); - for (QualifierValue newQV : newQVs) { - String newQualifier = newQV.getQualifier(); - // if min or max cardinality check for possible merges - if ("minCardinality".equals(newQualifier) - || "maxCardinality".equals(newQualifier)) { - QualifierValue match = findMatchingQualifierValue(newQV, - targetQVs); - if (match != null) { - mergeQualifierValues(match, newQV); - } else { - target.addQualifierValue(newQV); - } - } else { - target.addQualifierValue(newQV); - } - } - } - } - - /** - * Find matching qualifier value. - * - * @param query - * the query - * @param list - * the list - * @return the qualifier value - */ - @Nullable - static QualifierValue findMatchingQualifierValue( - @Nonnull QualifierValue query, - @Nonnull Collection list) { - String queryQualifier = query.getQualifier(); - for (QualifierValue qv : list) { - if (queryQualifier.equals(qv.getQualifier())) { - return qv; - } - } - return null; - } - - /** - * Merge qualifier values. - * - * @param target - * the target - * @param newQV - * the new qv - */ - static void mergeQualifierValues(@Nonnull QualifierValue target, - @Nonnull QualifierValue newQV) { - // do nothing, if they are equal - if (!target.getValue().equals(newQV.getValue())) { - if ("minCardinality".equals(target.getQualifier())) { - // try to merge, parse as integers - int currentValue = Integer.parseInt(target.getValue() - .toString()); - int newValue = Integer.parseInt(newQV.getValue().toString()); - int mergedValue = Math.min(currentValue, newValue); - target.setValue(Integer.toString(mergedValue)); - } else if ("maxCardinality".equals(target.getQualifier())) { - // try to merge, parse as integers - int currentValue = Integer.parseInt(target.getValue() - .toString()); - int newValue = Integer.parseInt(newQV.getValue().toString()); - int mergedValue = Math.max(currentValue, newValue); - target.setValue(Integer.toString(mergedValue)); - } - } - } - - protected void - error(String message, OWLAxiom ax, boolean shouldLogComplaint) { - untranslatableAxioms.add(ax); - error(message + ax, shouldLogComplaint); - } - - protected void error(OWLAxiom ax, boolean shouldLogComplaint) { - untranslatableAxioms.add(ax); - error("the axiom is not translated : " + ax, shouldLogComplaint); - } - - protected void error(String message, boolean shouldLogComplaint) { - if (strictConversion) { - throw new RuntimeException("The conversion is halted: " + message); - } else { - if (!muteUntranslatableAxioms && shouldLogComplaint) { - LOG.error("MASKING ERROR «{}»", message, new Exception()); - } - } - } - - protected void warn(String message) { - if (strictConversion) { - throw new RuntimeException("The conversion is halted: " + message); - } else { - LOG.warn("MASKING ERROR «{}»", message); - } - } -} diff --git a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/pair.info b/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/pair.info deleted file mode 100755 index 5d41a6f..0000000 --- a/All/FindBugs-MS_SHOULD_BE_FINAL/FBViolation#86207/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:86207 -comSha:b20fe9c5856d4e22410b4cdbb3d475ed753b0ded -parentComSha:0b2270deea5b872274f9a2277e6a554287f7a443 -BuggyFilePath:oboformat/src/main/java/org/obolibrary/obo2owl/OWLAPIOwl2Obo.java -FixedFilePath:oboformat/src/main/java/org/obolibrary/obo2owl/OWLAPIOwl2Obo.java -StartLineNum:135 -EndLineNum:135 -repoName:owlcs#owlapi \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/comMsg.txt deleted file mode 100755 index b27ed61..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -fixing all javadoc warnings in biojava-structure - -git-svn-id: http://code.open-bio.org/repos/biojava/biojava-live/trunk@9149 7c6358e6-4a41-0410-a743-a5b2a554c398 \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/diff.diff deleted file mode 100755 index ada2db8..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/biojava3-structure/src/main/java/org/biojava/bio/structure/align/helper/AligMatEl.java b/biojava3-structure/src/main/java/org/biojava/bio/structure/align/helper/AligMatEl.java -index ca0e31f4..623fa5aa 100644 ---- a/biojava3-structure/src/main/java/org/biojava/bio/structure/align/helper/AligMatEl.java -+++ b/biojava3-structure/src/main/java/org/biojava/bio/structure/align/helper/AligMatEl.java -@@ -30 +30,5 @@ extends IndexPair{ -- int value; -+ /** -+ * -+ */ -+ private static final long serialVersionUID = -4040926588803887471L; -+ int value; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/new/AligMatEl.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/new/AligMatEl.java deleted file mode 100755 index 623fa5a..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/new/AligMatEl.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on Mar 1, 2006 - * - */ -package org.biojava.bio.structure.align.helper; - -public class AligMatEl -extends IndexPair{ - - - - /** - * - */ - private static final long serialVersionUID = -4040926588803887471L; - int value; - int contig; - - - public AligMatEl(){ - super(); - value = -1; - contig = -1; - } - - public int getContig() { - return contig; - } - public void setContig(int contig) { - this.contig = contig; - } - - public int getValue() { - return value; - } - public void setValue(int value) { - this.value = value; - } - - public String toString(){ - String ret = "AligMatEl val:" + value + " contig:" + contig + - " trackrow:" + getRow() + " trackcol:" + getCol(); - return ret; - } - - } - - - - diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/old/AligMatEl.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/old/AligMatEl.java deleted file mode 100755 index ca0e31f..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/old/AligMatEl.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on Mar 1, 2006 - * - */ -package org.biojava.bio.structure.align.helper; - -public class AligMatEl -extends IndexPair{ - - - - int value; - int contig; - - - public AligMatEl(){ - super(); - value = -1; - contig = -1; - } - - public int getContig() { - return contig; - } - public void setContig(int contig) { - this.contig = contig; - } - - public int getValue() { - return value; - } - public void setValue(int value) { - this.value = value; - } - - public String toString(){ - String ret = "AligMatEl val:" + value + " contig:" + contig + - " trackrow:" + getRow() + " trackcol:" + getCol(); - return ret; - } - - } - - - - diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/pair.info deleted file mode 100755 index 19a856d..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#23472/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:23472 -comSha:e91970915a55169c443adb5ee05e25f428370fe7 -parentComSha:5e0c811dc56984abb6c1b4134a975797a00dc0ca -BuggyFilePath:biojava3-structure/src/main/java/org/biojava/bio/structure/align/helper/AligMatEl.java -FixedFilePath:biojava3-structure/src/main/java/org/biojava/bio/structure/align/helper/AligMatEl.java -StartLineNum:35 -EndLineNum:57 -repoName:JolantaWojcik#biojavaOwn \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/comMsg.txt deleted file mode 100755 index 7a1ea70..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/comMsg.txt +++ /dev/null @@ -1,4 +0,0 @@ -Merge branch 'master' of github.com:thinkaurelius/faunus - -Conflicts: - src/main/java/com/thinkaurelius/faunus/mapreduce/FaunusCompiler.java \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/diff.diff deleted file mode 100755 index 21071d2..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/main/java/com/thinkaurelius/faunus/hdfs/OnlyGraphFilter.java b/src/main/java/com/thinkaurelius/faunus/hdfs/NoSideEffectFilter.java -index 7e851a7df..48cd222e5 100644 ---- a/src/main/java/com/thinkaurelius/faunus/hdfs/OnlyGraphFilter.java -+++ b/src/main/java/com/thinkaurelius/faunus/hdfs/NoSideEffectFilter.java -@@ -8,2 +7,0 @@ import org.apache.hadoop.fs.PathFilter; --import java.io.Serializable; -- -@@ -13 +11 @@ import java.io.Serializable; --public class OnlyGraphFilter implements PathFilter, Serializable { -+public class NoSideEffectFilter implements PathFilter { -@@ -15 +13 @@ public class OnlyGraphFilter implements PathFilter, Serializable { -- public OnlyGraphFilter() { -+ public NoSideEffectFilter() { -@@ -23 +21 @@ public class OnlyGraphFilter implements PathFilter, Serializable { -- return path.getName().contains(Tokens.GRAPH) || path.getName().contains(Tokens.PART); -+ return !path.getName().startsWith(Tokens.SIDEEFFECT); \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/new/NoSideEffectFilter.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/new/NoSideEffectFilter.java deleted file mode 100755 index 48cd222..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/new/NoSideEffectFilter.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.thinkaurelius.faunus.hdfs; - -import com.thinkaurelius.faunus.Tokens; -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.fs.PathFilter; - -/** - * @author Marko A. Rodriguez (http://markorodriguez.com) - */ -public class NoSideEffectFilter implements PathFilter { - - public NoSideEffectFilter() { - } - - public boolean accept(Path path) { - try { - if (!path.getFileSystem(new Configuration()).isFile(path)) - return true; - else - return !path.getName().startsWith(Tokens.SIDEEFFECT); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/old/OnlyGraphFilter.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/old/OnlyGraphFilter.java deleted file mode 100755 index 7e851a7..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/old/OnlyGraphFilter.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.thinkaurelius.faunus.hdfs; - -import com.thinkaurelius.faunus.Tokens; -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.fs.PathFilter; - -import java.io.Serializable; - -/** - * @author Marko A. Rodriguez (http://markorodriguez.com) - */ -public class OnlyGraphFilter implements PathFilter, Serializable { - - public OnlyGraphFilter() { - } - - public boolean accept(Path path) { - try { - if (!path.getFileSystem(new Configuration()).isFile(path)) - return true; - else - return path.getName().contains(Tokens.GRAPH) || path.getName().contains(Tokens.PART); - } catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/pair.info deleted file mode 100755 index 3dfbe5c..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#34106/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:34106 -comSha:730e9f00111d680ab9dacbf21f6539ddda889800 -parentComSha:b696b7cdce310270a372820fcef6014c0dafdb7b -BuggyFilePath:src/main/java/com/thinkaurelius/faunus/hdfs/OnlyGraphFilter.java -FixedFilePath:src/main/java/com/thinkaurelius/faunus/hdfs/NoSideEffectFilter.java -StartLineNum:15 -EndLineNum:25 -repoName:thinkaurelius#titan \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/comMsg.txt deleted file mode 100755 index 9e6bcea..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -removed ConfigURLFactory from the fields, so it doesn't need to be serialized \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/diff.diff deleted file mode 100755 index 94db55b..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/org/aeonbits/owner/ConfigURLFactory.java b/src/main/java/org/aeonbits/owner/ConfigURLFactory.java -index 2f36e7f..0c6a46c 100644 ---- a/src/main/java/org/aeonbits/owner/ConfigURLFactory.java -+++ b/src/main/java/org/aeonbits/owner/ConfigURLFactory.java -@@ -11 +10,0 @@ package org.aeonbits.owner; --import java.io.Serializable; -@@ -18 +17 @@ import java.net.URL; --class ConfigURLFactory implements Serializable { -+class ConfigURLFactory { -@@ -20 +19 @@ class ConfigURLFactory implements Serializable { -- private transient final ClassLoader classLoader; -+ private final transient ClassLoader classLoader; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/new/ConfigURLFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/new/ConfigURLFactory.java deleted file mode 100755 index 0c6a46c..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/new/ConfigURLFactory.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) 2013, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.net.MalformedURLException; -import java.net.URL; - -/** - * @author Luigi R. Viggiano - */ -class ConfigURLFactory { - private static final String CLASSPATH_PROTOCOL = "classpath:"; - private final transient ClassLoader classLoader; - private final VariablesExpander expander; - - ConfigURLFactory(ClassLoader classLoader, VariablesExpander expander) { - this.classLoader = classLoader; - this.expander = expander; - } - - URL newURL(String spec) throws MalformedURLException { - String expanded = expand(spec); - URL url; - if (expanded.startsWith(CLASSPATH_PROTOCOL)) { - String path = expanded.substring(CLASSPATH_PROTOCOL.length()); - url = classLoader.getResource(path); - if (url == null) - return null; - } else { - url = new URL(expanded); - } - return new URL(url.getProtocol(), url.getHost(), url.getPort(), expand(url.getPath())); - } - - private String expand(String path) { - return expander.expand(path); - } - - String toClasspathURLSpec(String name) { - return CLASSPATH_PROTOCOL + name.replace('.', '/'); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/old/ConfigURLFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/old/ConfigURLFactory.java deleted file mode 100755 index 2f36e7f..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/old/ConfigURLFactory.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2013, Luigi R. Viggiano - * All rights reserved. - * - * This software is distributable under the BSD license. - * See the terms of the BSD license in the documentation provided with this software. - */ - -package org.aeonbits.owner; - -import java.io.Serializable; -import java.net.MalformedURLException; -import java.net.URL; - -/** - * @author Luigi R. Viggiano - */ -class ConfigURLFactory implements Serializable { - private static final String CLASSPATH_PROTOCOL = "classpath:"; - private transient final ClassLoader classLoader; - private final VariablesExpander expander; - - ConfigURLFactory(ClassLoader classLoader, VariablesExpander expander) { - this.classLoader = classLoader; - this.expander = expander; - } - - URL newURL(String spec) throws MalformedURLException { - String expanded = expand(spec); - URL url; - if (expanded.startsWith(CLASSPATH_PROTOCOL)) { - String path = expanded.substring(CLASSPATH_PROTOCOL.length()); - url = classLoader.getResource(path); - if (url == null) - return null; - } else { - url = new URL(expanded); - } - return new URL(url.getProtocol(), url.getHost(), url.getPort(), expand(url.getPath())); - } - - private String expand(String path) { - return expander.expand(path); - } - - String toClasspathURLSpec(String name) { - return CLASSPATH_PROTOCOL + name.replace('.', '/'); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/pair.info deleted file mode 100755 index 51d59bf..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#37103/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:37103 -comSha:2f4caecf311a5464306a20772d6179d35fd4263c -parentComSha:2e1390f301dcbdb997f4725ba09f0a28071b9ceb -BuggyFilePath:src/main/java/org/aeonbits/owner/ConfigURLFactory.java -FixedFilePath:src/main/java/org/aeonbits/owner/ConfigURLFactory.java -StartLineNum:23 -EndLineNum:47 -repoName:lviggiano#owner \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/comMsg.txt deleted file mode 100755 index 865fa37..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Bye bye ActivityExecution \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/diff.diff deleted file mode 100755 index e6f6de6..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/diff.diff +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ServiceTaskDelegateExpressionActivityBehavior.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ServiceTaskDelegateExpressionActivityBehavior.java -index 29743a6c8..40b8f0953 100644 ---- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ServiceTaskDelegateExpressionActivityBehavior.java -+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ServiceTaskDelegateExpressionActivityBehavior.java -@@ -18,0 +19 @@ import org.activiti.engine.delegate.BpmnError; -+import org.activiti.engine.delegate.DelegateExecution; -@@ -28 +28,0 @@ import org.activiti.engine.impl.delegate.ActivityBehaviorInvocation; --import org.activiti.engine.impl.delegate.ActivityExecution; -@@ -41,0 +42,2 @@ public class ServiceTaskDelegateExpressionActivityBehavior extends TaskActivityB -+ private static final long serialVersionUID = 1L; -+ -@@ -53 +55 @@ public class ServiceTaskDelegateExpressionActivityBehavior extends TaskActivityB -- public void trigger(ActivityExecution execution, String signalName, Object signalData) { -+ public void trigger(DelegateExecution execution, String signalName, Object signalData) { -@@ -61 +63 @@ public class ServiceTaskDelegateExpressionActivityBehavior extends TaskActivityB -- public void execute(ActivityExecution execution) { -+ public void execute(DelegateExecution execution) { \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/new/ServiceTaskDelegateExpressionActivityBehavior.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/new/ServiceTaskDelegateExpressionActivityBehavior.java deleted file mode 100755 index 40b8f09..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/new/ServiceTaskDelegateExpressionActivityBehavior.java +++ /dev/null @@ -1,113 +0,0 @@ -/* 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.activiti.engine.impl.bpmn.behavior; - -import java.util.List; - -import org.activiti.engine.ActivitiIllegalArgumentException; -import org.activiti.engine.delegate.BpmnError; -import org.activiti.engine.delegate.DelegateExecution; -import org.activiti.engine.delegate.Expression; -import org.activiti.engine.delegate.JavaDelegate; -import org.activiti.engine.impl.bpmn.helper.ClassDelegate; -import org.activiti.engine.impl.bpmn.helper.ErrorPropagation; -import org.activiti.engine.impl.bpmn.helper.SkipExpressionUtil; -import org.activiti.engine.impl.bpmn.parser.FieldDeclaration; -import org.activiti.engine.impl.context.Context; -import org.activiti.engine.impl.delegate.ActivityBehavior; -import org.activiti.engine.impl.delegate.ActivityBehaviorInvocation; -import org.activiti.engine.impl.delegate.TriggerableActivityBehavior; -import org.activiti.engine.impl.delegate.invocation.JavaDelegateInvocation; - -/** - * {@link ActivityBehavior} used when 'delegateExpression' is used for a serviceTask. - * - * @author Joram Barrez - * @author Josh Long - * @author Slawomir Wojtasiak (Patch for ACT-1159) - * @author Falko Menge - */ -public class ServiceTaskDelegateExpressionActivityBehavior extends TaskActivityBehavior { - - private static final long serialVersionUID = 1L; - - protected Expression expression; - protected Expression skipExpression; - private final List fieldDeclarations; - - public ServiceTaskDelegateExpressionActivityBehavior(Expression expression, Expression skipExpression, List fieldDeclarations) { - this.expression = expression; - this.skipExpression = skipExpression; - this.fieldDeclarations = fieldDeclarations; - } - - @Override - public void trigger(DelegateExecution execution, String signalName, Object signalData) { - Object delegate = expression.getValue(execution); - if (delegate instanceof TriggerableActivityBehavior) { - ClassDelegate.applyFieldDeclaration(fieldDeclarations, delegate); - ((TriggerableActivityBehavior) delegate).trigger(execution, signalName, signalData); - } - } - - public void execute(DelegateExecution execution) { - - try { - boolean isSkipExpressionEnabled = SkipExpressionUtil.isSkipExpressionEnabled(execution, skipExpression); - if (!isSkipExpressionEnabled || (isSkipExpressionEnabled && !SkipExpressionUtil.shouldSkipFlowElement(execution, skipExpression))) { - - // Note: we can't cache the result of the expression, because the - // execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}' - Object delegate = expression.getValue(execution); - ClassDelegate.applyFieldDeclaration(fieldDeclarations, delegate); - - if (delegate instanceof ActivityBehavior) { - - if (delegate instanceof AbstractBpmnActivityBehavior) { - ((AbstractBpmnActivityBehavior) delegate).setMultiInstanceActivityBehavior(getMultiInstanceActivityBehavior()); - } - - Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(new ActivityBehaviorInvocation((ActivityBehavior) delegate, execution)); - - } else if (delegate instanceof JavaDelegate) { - Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(new JavaDelegateInvocation((JavaDelegate) delegate, execution)); - leave(execution); - - } else { - throw new ActivitiIllegalArgumentException("Delegate expression " + expression + " did neither resolve to an implementation of " + ActivityBehavior.class + " nor " + JavaDelegate.class); - } - } else { - leave(execution); - } - } catch (Exception exc) { - - Throwable cause = exc; - BpmnError error = null; - while (cause != null) { - if (cause instanceof BpmnError) { - error = (BpmnError) cause; - break; - } - cause = cause.getCause(); - } - - if (error != null) { - ErrorPropagation.propagateError(error, execution); - } else { - throw new RuntimeException(exc); - } - - } - } - -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/old/ServiceTaskDelegateExpressionActivityBehavior.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/old/ServiceTaskDelegateExpressionActivityBehavior.java deleted file mode 100755 index 29743a6..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/old/ServiceTaskDelegateExpressionActivityBehavior.java +++ /dev/null @@ -1,111 +0,0 @@ -/* 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.activiti.engine.impl.bpmn.behavior; - -import java.util.List; - -import org.activiti.engine.ActivitiIllegalArgumentException; -import org.activiti.engine.delegate.BpmnError; -import org.activiti.engine.delegate.Expression; -import org.activiti.engine.delegate.JavaDelegate; -import org.activiti.engine.impl.bpmn.helper.ClassDelegate; -import org.activiti.engine.impl.bpmn.helper.ErrorPropagation; -import org.activiti.engine.impl.bpmn.helper.SkipExpressionUtil; -import org.activiti.engine.impl.bpmn.parser.FieldDeclaration; -import org.activiti.engine.impl.context.Context; -import org.activiti.engine.impl.delegate.ActivityBehavior; -import org.activiti.engine.impl.delegate.ActivityBehaviorInvocation; -import org.activiti.engine.impl.delegate.ActivityExecution; -import org.activiti.engine.impl.delegate.TriggerableActivityBehavior; -import org.activiti.engine.impl.delegate.invocation.JavaDelegateInvocation; - -/** - * {@link ActivityBehavior} used when 'delegateExpression' is used for a serviceTask. - * - * @author Joram Barrez - * @author Josh Long - * @author Slawomir Wojtasiak (Patch for ACT-1159) - * @author Falko Menge - */ -public class ServiceTaskDelegateExpressionActivityBehavior extends TaskActivityBehavior { - - protected Expression expression; - protected Expression skipExpression; - private final List fieldDeclarations; - - public ServiceTaskDelegateExpressionActivityBehavior(Expression expression, Expression skipExpression, List fieldDeclarations) { - this.expression = expression; - this.skipExpression = skipExpression; - this.fieldDeclarations = fieldDeclarations; - } - - @Override - public void trigger(ActivityExecution execution, String signalName, Object signalData) { - Object delegate = expression.getValue(execution); - if (delegate instanceof TriggerableActivityBehavior) { - ClassDelegate.applyFieldDeclaration(fieldDeclarations, delegate); - ((TriggerableActivityBehavior) delegate).trigger(execution, signalName, signalData); - } - } - - public void execute(ActivityExecution execution) { - - try { - boolean isSkipExpressionEnabled = SkipExpressionUtil.isSkipExpressionEnabled(execution, skipExpression); - if (!isSkipExpressionEnabled || (isSkipExpressionEnabled && !SkipExpressionUtil.shouldSkipFlowElement(execution, skipExpression))) { - - // Note: we can't cache the result of the expression, because the - // execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}' - Object delegate = expression.getValue(execution); - ClassDelegate.applyFieldDeclaration(fieldDeclarations, delegate); - - if (delegate instanceof ActivityBehavior) { - - if (delegate instanceof AbstractBpmnActivityBehavior) { - ((AbstractBpmnActivityBehavior) delegate).setMultiInstanceActivityBehavior(getMultiInstanceActivityBehavior()); - } - - Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(new ActivityBehaviorInvocation((ActivityBehavior) delegate, execution)); - - } else if (delegate instanceof JavaDelegate) { - Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(new JavaDelegateInvocation((JavaDelegate) delegate, execution)); - leave(execution); - - } else { - throw new ActivitiIllegalArgumentException("Delegate expression " + expression + " did neither resolve to an implementation of " + ActivityBehavior.class + " nor " + JavaDelegate.class); - } - } else { - leave(execution); - } - } catch (Exception exc) { - - Throwable cause = exc; - BpmnError error = null; - while (cause != null) { - if (cause instanceof BpmnError) { - error = (BpmnError) cause; - break; - } - cause = cause.getCause(); - } - - if (error != null) { - ErrorPropagation.propagateError(error, execution); - } else { - throw new RuntimeException(exc); - } - - } - } - -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/pair.info deleted file mode 100755 index edb3824..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#6158/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:6158 -comSha:19fad051eb349eee9abd570bd44c86c8473c4983 -parentComSha:cac16864b12d60478e0318b0ec58994cab5112dc -BuggyFilePath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ServiceTaskDelegateExpressionActivityBehavior.java -FixedFilePath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ServiceTaskDelegateExpressionActivityBehavior.java -StartLineNum:46 -EndLineNum:109 -repoName:Activiti#Activiti \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/comMsg.txt deleted file mode 100755 index 865fa37..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Bye bye ActivityExecution \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/diff.diff deleted file mode 100755 index 27c7f92..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/EventBasedGatewayActivityBehavior.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/EventBasedGatewayActivityBehavior.java -index 0ea342963..fdc75107e 100644 ---- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/EventBasedGatewayActivityBehavior.java -+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/EventBasedGatewayActivityBehavior.java -@@ -16 +16 @@ package org.activiti.engine.impl.bpmn.behavior; --import org.activiti.engine.impl.delegate.ActivityExecution; -+import org.activiti.engine.delegate.DelegateExecution; -@@ -22,0 +23,2 @@ public class EventBasedGatewayActivityBehavior extends FlowNodeActivityBehavior -+ -+ private static final long serialVersionUID = 1L; -@@ -25 +27 @@ public class EventBasedGatewayActivityBehavior extends FlowNodeActivityBehavior -- public void execute(ActivityExecution execution) { -+ public void execute(DelegateExecution execution) { \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/new/EventBasedGatewayActivityBehavior.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/new/EventBasedGatewayActivityBehavior.java deleted file mode 100755 index fdc7510..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/new/EventBasedGatewayActivityBehavior.java +++ /dev/null @@ -1,35 +0,0 @@ -/* 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.activiti.engine.impl.bpmn.behavior; - -import org.activiti.engine.delegate.DelegateExecution; - -/** - * @author Daniel Meyer - * @author Joram Barrez - */ -public class EventBasedGatewayActivityBehavior extends FlowNodeActivityBehavior { - - private static final long serialVersionUID = 1L; - - @Override - public void execute(DelegateExecution execution) { - - // The event based gateway simply leaves directly, in the default BPMN 2.0 way - // (taking all sequence flow in parallel) - leave(execution); - - } - -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/old/EventBasedGatewayActivityBehavior.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/old/EventBasedGatewayActivityBehavior.java deleted file mode 100755 index 0ea3429..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/old/EventBasedGatewayActivityBehavior.java +++ /dev/null @@ -1,33 +0,0 @@ -/* 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.activiti.engine.impl.bpmn.behavior; - -import org.activiti.engine.impl.delegate.ActivityExecution; - -/** - * @author Daniel Meyer - * @author Joram Barrez - */ -public class EventBasedGatewayActivityBehavior extends FlowNodeActivityBehavior { - - @Override - public void execute(ActivityExecution execution) { - - // The event based gateway simply leaves directly, in the default BPMN 2.0 way - // (taking all sequence flow in parallel) - leave(execution); - - } - -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/pair.info deleted file mode 100755 index 60a9cef..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7357/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:7357 -comSha:19fad051eb349eee9abd570bd44c86c8473c4983 -parentComSha:cac16864b12d60478e0318b0ec58994cab5112dc -BuggyFilePath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/EventBasedGatewayActivityBehavior.java -FixedFilePath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/EventBasedGatewayActivityBehavior.java -StartLineNum:22 -EndLineNum:31 -repoName:Activiti#Activiti \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/comMsg.txt deleted file mode 100755 index 865fa37..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Bye bye ActivityExecution \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/diff.diff deleted file mode 100755 index 0153513..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ShellActivityBehavior.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ShellActivityBehavior.java -index 8ae2688d8..2f5175b07 100644 ---- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ShellActivityBehavior.java -+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ShellActivityBehavior.java -@@ -18 +17,0 @@ import org.activiti.engine.delegate.Expression; --import org.activiti.engine.impl.delegate.ActivityExecution; -@@ -21,0 +21,2 @@ public class ShellActivityBehavior extends AbstractBpmnActivityBehavior { -+ private static final long serialVersionUID = 1L; -+ -@@ -49 +50 @@ public class ShellActivityBehavior extends AbstractBpmnActivityBehavior { -- private void readFields(ActivityExecution execution) { -+ private void readFields(DelegateExecution execution) { -@@ -70 +71 @@ public class ShellActivityBehavior extends AbstractBpmnActivityBehavior { -- public void execute(ActivityExecution execution) { -+ public void execute(DelegateExecution execution) { \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/new/ShellActivityBehavior.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/new/ShellActivityBehavior.java deleted file mode 100755 index 2f5175b..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/new/ShellActivityBehavior.java +++ /dev/null @@ -1,154 +0,0 @@ -package org.activiti.engine.impl.bpmn.behavior; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.activiti.engine.ActivitiException; -import org.activiti.engine.delegate.DelegateExecution; -import org.activiti.engine.delegate.Expression; - -public class ShellActivityBehavior extends AbstractBpmnActivityBehavior { - - private static final long serialVersionUID = 1L; - - protected Expression command; - protected Expression wait; - protected Expression arg1; - protected Expression arg2; - protected Expression arg3; - protected Expression arg4; - protected Expression arg5; - protected Expression outputVariable; - protected Expression errorCodeVariable; - protected Expression redirectError; - protected Expression cleanEnv; - protected Expression directory; - - String commandStr; - String arg1Str; - String arg2Str; - String arg3Str; - String arg4Str; - String arg5Str; - String waitStr; - String resultVariableStr; - String errorCodeVariableStr; - Boolean waitFlag; - Boolean redirectErrorFlag; - Boolean cleanEnvBoolean; - String directoryStr; - - private void readFields(DelegateExecution execution) { - commandStr = getStringFromField(command, execution); - arg1Str = getStringFromField(arg1, execution); - arg2Str = getStringFromField(arg2, execution); - arg3Str = getStringFromField(arg3, execution); - arg4Str = getStringFromField(arg4, execution); - arg5Str = getStringFromField(arg5, execution); - waitStr = getStringFromField(wait, execution); - resultVariableStr = getStringFromField(outputVariable, execution); - errorCodeVariableStr = getStringFromField(errorCodeVariable, execution); - - String redirectErrorStr = getStringFromField(redirectError, execution); - String cleanEnvStr = getStringFromField(cleanEnv, execution); - - waitFlag = waitStr == null || waitStr.equals("true"); - redirectErrorFlag = redirectErrorStr != null && redirectErrorStr.equals("true"); - cleanEnvBoolean = cleanEnvStr != null && cleanEnvStr.equals("true"); - directoryStr = getStringFromField(directory, execution); - - } - - public void execute(DelegateExecution execution) { - - readFields(execution); - - List argList = new ArrayList(); - argList.add(commandStr); - - if (arg1Str != null) - argList.add(arg1Str); - if (arg2Str != null) - argList.add(arg2Str); - if (arg3Str != null) - argList.add(arg3Str); - if (arg4Str != null) - argList.add(arg4Str); - if (arg5Str != null) - argList.add(arg5Str); - - ProcessBuilder processBuilder = new ProcessBuilder(argList); - - try { - processBuilder.redirectErrorStream(redirectErrorFlag); - if (cleanEnvBoolean) { - Map env = processBuilder.environment(); - env.clear(); - } - if (directoryStr != null && directoryStr.length() > 0) - processBuilder.directory(new File(directoryStr)); - - Process process = processBuilder.start(); - - if (waitFlag) { - int errorCode = process.waitFor(); - - if (resultVariableStr != null) { - String result = convertStreamToStr(process.getInputStream()); - execution.setVariable(resultVariableStr, result); - } - - if (errorCodeVariableStr != null) { - execution.setVariable(errorCodeVariableStr, Integer.toString(errorCode)); - - } - - } - } catch (Exception e) { - throw new ActivitiException("Could not execute shell command ", e); - } - - leave(execution); - } - - public static String convertStreamToStr(InputStream is) throws IOException { - - if (is != null) { - Writer writer = new StringWriter(); - - char[] buffer = new char[1024]; - try { - Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); - int n; - while ((n = reader.read(buffer)) != -1) { - writer.write(buffer, 0, n); - } - } finally { - is.close(); - } - return writer.toString(); - } else { - return ""; - } - } - - protected String getStringFromField(Expression expression, DelegateExecution execution) { - if (expression != null) { - Object value = expression.getValue(execution); - if (value != null) { - return value.toString(); - } - } - return null; - } - -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/old/ShellActivityBehavior.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/old/ShellActivityBehavior.java deleted file mode 100755 index 8ae2688..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/old/ShellActivityBehavior.java +++ /dev/null @@ -1,153 +0,0 @@ -package org.activiti.engine.impl.bpmn.behavior; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.activiti.engine.ActivitiException; -import org.activiti.engine.delegate.DelegateExecution; -import org.activiti.engine.delegate.Expression; -import org.activiti.engine.impl.delegate.ActivityExecution; - -public class ShellActivityBehavior extends AbstractBpmnActivityBehavior { - - protected Expression command; - protected Expression wait; - protected Expression arg1; - protected Expression arg2; - protected Expression arg3; - protected Expression arg4; - protected Expression arg5; - protected Expression outputVariable; - protected Expression errorCodeVariable; - protected Expression redirectError; - protected Expression cleanEnv; - protected Expression directory; - - String commandStr; - String arg1Str; - String arg2Str; - String arg3Str; - String arg4Str; - String arg5Str; - String waitStr; - String resultVariableStr; - String errorCodeVariableStr; - Boolean waitFlag; - Boolean redirectErrorFlag; - Boolean cleanEnvBoolean; - String directoryStr; - - private void readFields(ActivityExecution execution) { - commandStr = getStringFromField(command, execution); - arg1Str = getStringFromField(arg1, execution); - arg2Str = getStringFromField(arg2, execution); - arg3Str = getStringFromField(arg3, execution); - arg4Str = getStringFromField(arg4, execution); - arg5Str = getStringFromField(arg5, execution); - waitStr = getStringFromField(wait, execution); - resultVariableStr = getStringFromField(outputVariable, execution); - errorCodeVariableStr = getStringFromField(errorCodeVariable, execution); - - String redirectErrorStr = getStringFromField(redirectError, execution); - String cleanEnvStr = getStringFromField(cleanEnv, execution); - - waitFlag = waitStr == null || waitStr.equals("true"); - redirectErrorFlag = redirectErrorStr != null && redirectErrorStr.equals("true"); - cleanEnvBoolean = cleanEnvStr != null && cleanEnvStr.equals("true"); - directoryStr = getStringFromField(directory, execution); - - } - - public void execute(ActivityExecution execution) { - - readFields(execution); - - List argList = new ArrayList(); - argList.add(commandStr); - - if (arg1Str != null) - argList.add(arg1Str); - if (arg2Str != null) - argList.add(arg2Str); - if (arg3Str != null) - argList.add(arg3Str); - if (arg4Str != null) - argList.add(arg4Str); - if (arg5Str != null) - argList.add(arg5Str); - - ProcessBuilder processBuilder = new ProcessBuilder(argList); - - try { - processBuilder.redirectErrorStream(redirectErrorFlag); - if (cleanEnvBoolean) { - Map env = processBuilder.environment(); - env.clear(); - } - if (directoryStr != null && directoryStr.length() > 0) - processBuilder.directory(new File(directoryStr)); - - Process process = processBuilder.start(); - - if (waitFlag) { - int errorCode = process.waitFor(); - - if (resultVariableStr != null) { - String result = convertStreamToStr(process.getInputStream()); - execution.setVariable(resultVariableStr, result); - } - - if (errorCodeVariableStr != null) { - execution.setVariable(errorCodeVariableStr, Integer.toString(errorCode)); - - } - - } - } catch (Exception e) { - throw new ActivitiException("Could not execute shell command ", e); - } - - leave(execution); - } - - public static String convertStreamToStr(InputStream is) throws IOException { - - if (is != null) { - Writer writer = new StringWriter(); - - char[] buffer = new char[1024]; - try { - Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); - int n; - while ((n = reader.read(buffer)) != -1) { - writer.write(buffer, 0, n); - } - } finally { - is.close(); - } - return writer.toString(); - } else { - return ""; - } - } - - protected String getStringFromField(Expression expression, DelegateExecution execution) { - if (expression != null) { - Object value = expression.getValue(execution); - if (value != null) { - return value.toString(); - } - } - return null; - } - -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/pair.info deleted file mode 100755 index caf46d6..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#7712/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:7712 -comSha:19fad051eb349eee9abd570bd44c86c8473c4983 -parentComSha:cac16864b12d60478e0318b0ec58994cab5112dc -BuggyFilePath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ShellActivityBehavior.java -FixedFilePath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/ShellActivityBehavior.java -StartLineNum:20 -EndLineNum:150 -repoName:Activiti#Activiti \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/comMsg.txt deleted file mode 100755 index f208997..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Declaring a serializable UID \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/diff.diff deleted file mode 100755 index 19931e7..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/diff.diff +++ /dev/null @@ -1,8 +0,0 @@ -diff --git a/src/main/java/org/getspout/api/inventory/Inventory.java b/src/main/java/org/getspout/api/inventory/Inventory.java -index f75f48bf5..c64a89bd9 100644 ---- a/src/main/java/org/getspout/api/inventory/Inventory.java -+++ b/src/main/java/org/getspout/api/inventory/Inventory.java -@@ -7 +7,2 @@ public class Inventory implements Serializable { -- ItemStack[] contents; -+ private static final long serialVersionUID = 0L; -+ private ItemStack[] contents; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/new/Inventory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/new/Inventory.java deleted file mode 100755 index c64a89b..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/new/Inventory.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.getspout.api.inventory; - -import java.io.Serializable; - -public class Inventory implements Serializable { - - private static final long serialVersionUID = 0L; - private ItemStack[] contents; - - public Inventory(int size) { - contents = new ItemStack[size]; - } - - public ItemStack[] getContents() { - return contents; - } - - public ItemStack getItem(int slot) { - return contents[slot]; - } - - public void setItem(ItemStack item, int slot) { - contents[slot] = item; - } - - public boolean addItem(ItemStack item) { - for (int i = 0; i < contents.length; i++) { - if (contents[i] == null) { - contents[i] = item; - return true; - } - } - return false; - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/old/Inventory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/old/Inventory.java deleted file mode 100755 index f75f48b..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/old/Inventory.java +++ /dev/null @@ -1,34 +0,0 @@ -package org.getspout.api.inventory; - -import java.io.Serializable; - -public class Inventory implements Serializable { - - ItemStack[] contents; - - public Inventory(int size) { - contents = new ItemStack[size]; - } - - public ItemStack[] getContents() { - return contents; - } - - public ItemStack getItem(int slot) { - return contents[slot]; - } - - public void setItem(ItemStack item, int slot) { - contents[slot] = item; - } - - public boolean addItem(ItemStack item) { - for (int i = 0; i < contents.length; i++) { - if (contents[i] == null) { - contents[i] = item; - return true; - } - } - return false; - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/pair.info deleted file mode 100755 index 9b1c6c8..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#82546/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:82546 -comSha:035cd992a98c1e4e715b3ca0e5a238a192c14e2d -parentComSha:3bec589ae854528b4156102d2e5287246549b990 -BuggyFilePath:src/main/java/org/getspout/api/inventory/Inventory.java -FixedFilePath:src/main/java/org/getspout/api/inventory/Inventory.java -StartLineNum:9 -EndLineNum:32 -repoName:SpoutDev#Spout \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/comMsg.txt deleted file mode 100755 index f886d49..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -warnings removed, javadoc added \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/diff.diff deleted file mode 100755 index 99d8a8a..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/parsers/src/main/java/org/coode/owlapi/latex/LatexAxiomsListOntologyFormat.java b/parsers/src/main/java/org/coode/owlapi/latex/LatexAxiomsListOntologyFormat.java -index a2b9cd76c..323859aef 100644 ---- a/parsers/src/main/java/org/coode/owlapi/latex/LatexAxiomsListOntologyFormat.java -+++ b/parsers/src/main/java/org/coode/owlapi/latex/LatexAxiomsListOntologyFormat.java -@@ -50,5 +50 @@ public class LatexAxiomsListOntologyFormat extends OWLOntologyFormat { -- -- @SuppressWarnings("javadoc") -- public LatexAxiomsListOntologyFormat() { -- } -- -+ private static final long serialVersionUID = 30405L; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/new/LatexAxiomsListOntologyFormat.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/new/LatexAxiomsListOntologyFormat.java deleted file mode 100755 index 323859a..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/new/LatexAxiomsListOntologyFormat.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * This file is part of the OWL API. - * - * The contents of this file are subject to the LGPL License, Version 3.0. - * - * Copyright (C) 2011, The University of Manchester - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see http://www.gnu.org/licenses/. - * - * - * Alternatively, the contents of this file may be used under the terms of the Apache License, Version 2.0 - * in which case, the provisions of the Apache License Version 2.0 are applicable instead of those above. - * - * Copyright 2011, University of Manchester - * - * 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.coode.owlapi.latex; - -import org.semanticweb.owlapi.model.OWLOntologyFormat; - - -/** - * Author: Matthew Horridge
The University Of Manchester
Information Management Group
Date: - * 03-Aug-2008

- */ -public class LatexAxiomsListOntologyFormat extends OWLOntologyFormat { - private static final long serialVersionUID = 30405L; - - @Override - public String toString() { - return "Latex Axiom List"; - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/old/LatexAxiomsListOntologyFormat.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/old/LatexAxiomsListOntologyFormat.java deleted file mode 100755 index a2b9cd7..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/old/LatexAxiomsListOntologyFormat.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * This file is part of the OWL API. - * - * The contents of this file are subject to the LGPL License, Version 3.0. - * - * Copyright (C) 2011, The University of Manchester - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see http://www.gnu.org/licenses/. - * - * - * Alternatively, the contents of this file may be used under the terms of the Apache License, Version 2.0 - * in which case, the provisions of the Apache License Version 2.0 are applicable instead of those above. - * - * Copyright 2011, University of Manchester - * - * 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.coode.owlapi.latex; - -import org.semanticweb.owlapi.model.OWLOntologyFormat; - - -/** - * Author: Matthew Horridge
The University Of Manchester
Information Management Group
Date: - * 03-Aug-2008

- */ -public class LatexAxiomsListOntologyFormat extends OWLOntologyFormat { - - @SuppressWarnings("javadoc") - public LatexAxiomsListOntologyFormat() { - } - - - @Override - public String toString() { - return "Latex Axiom List"; - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/pair.info deleted file mode 100755 index b3262c0..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85462/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:85462 -comSha:edbdc77d7ce316275194a74367f413c19fe4f7c5 -parentComSha:e7634ef62b5aabbdfe23ab53a2e2652256644be5 -BuggyFilePath:parsers/src/main/java/org/coode/owlapi/latex/LatexAxiomsListOntologyFormat.java -FixedFilePath:parsers/src/main/java/org/coode/owlapi/latex/LatexAxiomsListOntologyFormat.java -StartLineNum:52 -EndLineNum:58 -repoName:owlcs#owlapi \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/comMsg.txt deleted file mode 100755 index b622295..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -javadoc warnings removed \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/diff.diff deleted file mode 100755 index 06cf17b..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/rio/src/main/java/org/semanticweb/owlapi/formats/TrixOntologyFormatFactory.java b/rio/src/main/java/org/semanticweb/owlapi/formats/TrixOntologyFormatFactory.java -index f4f12a579..f682e1c55 100644 ---- a/rio/src/main/java/org/semanticweb/owlapi/formats/TrixOntologyFormatFactory.java -+++ b/rio/src/main/java/org/semanticweb/owlapi/formats/TrixOntologyFormatFactory.java -@@ -17,3 +17 @@ public class TrixOntologyFormatFactory extends -- public TrixOntologyFormatFactory() { -- super(); -- } -+ private static final long serialVersionUID = 40000L; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/new/TrixOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/new/TrixOntologyFormatFactory.java deleted file mode 100755 index f682e1c..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/new/TrixOntologyFormatFactory.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class TrixOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - private static final long serialVersionUID = 40000L; - - @Override - public RioRDFOntologyFormat createFormat() { - return new TrixOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/old/TrixOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/old/TrixOntologyFormatFactory.java deleted file mode 100755 index f4f12a5..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/old/TrixOntologyFormatFactory.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class TrixOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - public TrixOntologyFormatFactory() { - super(); - } - - @Override - public RioRDFOntologyFormat createFormat() { - return new TrixOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/pair.info deleted file mode 100755 index 666cc93..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85604/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:85604 -comSha:8c0ef92ae5eee1e1f6f3329b9eb81acd4b855769 -parentComSha:206a4c1dbe5906d21bf530afa26a5d1b8327c139 -BuggyFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/TrixOntologyFormatFactory.java -FixedFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/TrixOntologyFormatFactory.java -StartLineNum:12 -EndLineNum:23 -repoName:owlcs#owlapi \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/comMsg.txt deleted file mode 100755 index b622295..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -javadoc warnings removed \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/diff.diff deleted file mode 100755 index 40e048f..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/rio/src/main/java/org/semanticweb/owlapi/formats/TrigOntologyFormatFactory.java b/rio/src/main/java/org/semanticweb/owlapi/formats/TrigOntologyFormatFactory.java -index 4e0445a13..f42bbb7e6 100644 ---- a/rio/src/main/java/org/semanticweb/owlapi/formats/TrigOntologyFormatFactory.java -+++ b/rio/src/main/java/org/semanticweb/owlapi/formats/TrigOntologyFormatFactory.java -@@ -17,3 +17 @@ public class TrigOntologyFormatFactory extends -- public TrigOntologyFormatFactory() { -- super(); -- } -+ private static final long serialVersionUID = 40000L; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/new/TrigOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/new/TrigOntologyFormatFactory.java deleted file mode 100755 index f42bbb7..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/new/TrigOntologyFormatFactory.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class TrigOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - private static final long serialVersionUID = 40000L; - - @Override - public RioRDFOntologyFormat createFormat() { - return new TrigOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/old/TrigOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/old/TrigOntologyFormatFactory.java deleted file mode 100755 index 4e0445a..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/old/TrigOntologyFormatFactory.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class TrigOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - public TrigOntologyFormatFactory() { - super(); - } - - @Override - public RioRDFOntologyFormat createFormat() { - return new TrigOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/pair.info deleted file mode 100755 index 3f9e305..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85616/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:85616 -comSha:8c0ef92ae5eee1e1f6f3329b9eb81acd4b855769 -parentComSha:206a4c1dbe5906d21bf530afa26a5d1b8327c139 -BuggyFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/TrigOntologyFormatFactory.java -FixedFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/TrigOntologyFormatFactory.java -StartLineNum:12 -EndLineNum:23 -repoName:owlcs#owlapi \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/comMsg.txt deleted file mode 100755 index b622295..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -javadoc warnings removed \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/diff.diff deleted file mode 100755 index 3e17d02..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/rio/src/main/java/org/semanticweb/owlapi/formats/RDFXMLOntologyFormatFactory.java b/rio/src/main/java/org/semanticweb/owlapi/formats/RDFXMLOntologyFormatFactory.java -index 4ab96d89d..8070beaeb 100644 ---- a/rio/src/main/java/org/semanticweb/owlapi/formats/RDFXMLOntologyFormatFactory.java -+++ b/rio/src/main/java/org/semanticweb/owlapi/formats/RDFXMLOntologyFormatFactory.java -@@ -17,3 +17 @@ public class RDFXMLOntologyFormatFactory extends -- public RDFXMLOntologyFormatFactory() { -- super(); -- } -+ private static final long serialVersionUID = 40000L; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/new/RDFXMLOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/new/RDFXMLOntologyFormatFactory.java deleted file mode 100755 index 8070bea..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/new/RDFXMLOntologyFormatFactory.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.openrdf.rio.RDFFormat; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(org.semanticweb.owlapi.model.OWLOntologyFormatFactory.class) -public class RDFXMLOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - private static final long serialVersionUID = 40000L; - - @Override - public RioRDFXMLOntologyFormat createFormat() { - return new RioRDFXMLOntologyFormat(RDFFormat.RDFXML); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/old/RDFXMLOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/old/RDFXMLOntologyFormatFactory.java deleted file mode 100755 index 4ab96d8..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/old/RDFXMLOntologyFormatFactory.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.openrdf.rio.RDFFormat; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(org.semanticweb.owlapi.model.OWLOntologyFormatFactory.class) -public class RDFXMLOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - public RDFXMLOntologyFormatFactory() { - super(); - } - - @Override - public RioRDFXMLOntologyFormat createFormat() { - return new RioRDFXMLOntologyFormat(RDFFormat.RDFXML); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/pair.info deleted file mode 100755 index e41a051..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85743/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:85743 -comSha:8c0ef92ae5eee1e1f6f3329b9eb81acd4b855769 -parentComSha:206a4c1dbe5906d21bf530afa26a5d1b8327c139 -BuggyFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/RDFXMLOntologyFormatFactory.java -FixedFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/RDFXMLOntologyFormatFactory.java -StartLineNum:12 -EndLineNum:23 -repoName:owlcs#owlapi \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/comMsg.txt deleted file mode 100755 index b622295..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -javadoc warnings removed \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/diff.diff deleted file mode 100755 index 23f1bb1..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/rio/src/main/java/org/semanticweb/owlapi/formats/BinaryRdfOntologyFormatFactory.java b/rio/src/main/java/org/semanticweb/owlapi/formats/BinaryRdfOntologyFormatFactory.java -index 54602faaa..d9183b72f 100644 ---- a/rio/src/main/java/org/semanticweb/owlapi/formats/BinaryRdfOntologyFormatFactory.java -+++ b/rio/src/main/java/org/semanticweb/owlapi/formats/BinaryRdfOntologyFormatFactory.java -@@ -17,3 +17 @@ public class BinaryRdfOntologyFormatFactory extends -- public BinaryRdfOntologyFormatFactory() { -- super(); -- } -+ private static final long serialVersionUID = 40000L; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/new/BinaryRdfOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/new/BinaryRdfOntologyFormatFactory.java deleted file mode 100755 index d9183b7..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/new/BinaryRdfOntologyFormatFactory.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class BinaryRdfOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - private static final long serialVersionUID = 40000L; - - @Override - public RioRDFOntologyFormat createFormat() { - return new BinaryRdfOntologyFormat(); - } - - @Override - public boolean isTextual() { - return false; - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/old/BinaryRdfOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/old/BinaryRdfOntologyFormatFactory.java deleted file mode 100755 index 54602fa..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/old/BinaryRdfOntologyFormatFactory.java +++ /dev/null @@ -1,30 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class BinaryRdfOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - public BinaryRdfOntologyFormatFactory() { - super(); - } - - @Override - public RioRDFOntologyFormat createFormat() { - return new BinaryRdfOntologyFormat(); - } - - @Override - public boolean isTextual() { - return false; - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/pair.info deleted file mode 100755 index 4631174..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#85858/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:85858 -comSha:8c0ef92ae5eee1e1f6f3329b9eb81acd4b855769 -parentComSha:206a4c1dbe5906d21bf530afa26a5d1b8327c139 -BuggyFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/BinaryRdfOntologyFormatFactory.java -FixedFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/BinaryRdfOntologyFormatFactory.java -StartLineNum:12 -EndLineNum:28 -repoName:owlcs#owlapi \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/comMsg.txt deleted file mode 100755 index b622295..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -javadoc warnings removed \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/diff.diff deleted file mode 100755 index e02a6fa..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/rio/src/main/java/org/semanticweb/owlapi/formats/TurtleOntologyFormatFactory.java b/rio/src/main/java/org/semanticweb/owlapi/formats/TurtleOntologyFormatFactory.java -index cd9c27153..7a0610aca 100644 ---- a/rio/src/main/java/org/semanticweb/owlapi/formats/TurtleOntologyFormatFactory.java -+++ b/rio/src/main/java/org/semanticweb/owlapi/formats/TurtleOntologyFormatFactory.java -@@ -16,3 +16 @@ public class TurtleOntologyFormatFactory extends -- public TurtleOntologyFormatFactory() { -- super(); -- } -+ private static final long serialVersionUID = 40000L; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/new/TurtleOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/new/TurtleOntologyFormatFactory.java deleted file mode 100755 index 7a0610a..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/new/TurtleOntologyFormatFactory.java +++ /dev/null @@ -1,22 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(org.semanticweb.owlapi.model.OWLOntologyFormatFactory.class) -public class TurtleOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - private static final long serialVersionUID = 40000L; - - @Override - public RioRDFOntologyFormat createFormat() { - return new RioTurtleOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/old/TurtleOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/old/TurtleOntologyFormatFactory.java deleted file mode 100755 index cd9c271..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/old/TurtleOntologyFormatFactory.java +++ /dev/null @@ -1,24 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(org.semanticweb.owlapi.model.OWLOntologyFormatFactory.class) -public class TurtleOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - public TurtleOntologyFormatFactory() { - super(); - } - - @Override - public RioRDFOntologyFormat createFormat() { - return new RioTurtleOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/pair.info deleted file mode 100755 index 7ea8710..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86013/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:86013 -comSha:8c0ef92ae5eee1e1f6f3329b9eb81acd4b855769 -parentComSha:206a4c1dbe5906d21bf530afa26a5d1b8327c139 -BuggyFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/TurtleOntologyFormatFactory.java -FixedFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/TurtleOntologyFormatFactory.java -StartLineNum:11 -EndLineNum:22 -repoName:owlcs#owlapi \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/comMsg.txt deleted file mode 100755 index b622295..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -javadoc warnings removed \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/diff.diff deleted file mode 100755 index 002c2e2..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/rio/src/main/java/org/semanticweb/owlapi/formats/NTriplesOntologyFormatFactory.java b/rio/src/main/java/org/semanticweb/owlapi/formats/NTriplesOntologyFormatFactory.java -index 1ac0c9f04..72b6cbffa 100644 ---- a/rio/src/main/java/org/semanticweb/owlapi/formats/NTriplesOntologyFormatFactory.java -+++ b/rio/src/main/java/org/semanticweb/owlapi/formats/NTriplesOntologyFormatFactory.java -@@ -17,3 +17 @@ public class NTriplesOntologyFormatFactory extends -- public NTriplesOntologyFormatFactory() { -- super(); -- } -+ private static final long serialVersionUID = 40000L; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/new/NTriplesOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/new/NTriplesOntologyFormatFactory.java deleted file mode 100755 index 72b6cbf..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/new/NTriplesOntologyFormatFactory.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class NTriplesOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - private static final long serialVersionUID = 40000L; - - @Override - public RioRDFOntologyFormat createFormat() { - return new NTriplesOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/old/NTriplesOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/old/NTriplesOntologyFormatFactory.java deleted file mode 100755 index 1ac0c9f..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/old/NTriplesOntologyFormatFactory.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class NTriplesOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - public NTriplesOntologyFormatFactory() { - super(); - } - - @Override - public RioRDFOntologyFormat createFormat() { - return new NTriplesOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/pair.info deleted file mode 100755 index fd97bcb..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86018/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:86018 -comSha:8c0ef92ae5eee1e1f6f3329b9eb81acd4b855769 -parentComSha:206a4c1dbe5906d21bf530afa26a5d1b8327c139 -BuggyFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/NTriplesOntologyFormatFactory.java -FixedFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/NTriplesOntologyFormatFactory.java -StartLineNum:12 -EndLineNum:23 -repoName:owlcs#owlapi \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/comMsg.txt deleted file mode 100755 index 2cccf31..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Event test fix \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/diff.diff deleted file mode 100755 index efd2526..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/NoneEndEventActivityBehavior.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/NoneEndEventActivityBehavior.java -index e7e37b3be..e0d28fde5 100644 ---- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/NoneEndEventActivityBehavior.java -+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/NoneEndEventActivityBehavior.java -@@ -22,0 +23,2 @@ public class NoneEndEventActivityBehavior extends FlowNodeActivityBehavior { -+ private static final long serialVersionUID = 1L; -+ -@@ -24 +26 @@ public class NoneEndEventActivityBehavior extends FlowNodeActivityBehavior { -- Context.getAgenda().planEndExecutionOperation(execution); -+ Context.getAgenda().planTakeOutgoingSequenceFlowsOperation(execution); \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/new/NoneEndEventActivityBehavior.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/new/NoneEndEventActivityBehavior.java deleted file mode 100755 index e0d28fd..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/new/NoneEndEventActivityBehavior.java +++ /dev/null @@ -1,29 +0,0 @@ -/* 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.activiti.engine.impl.bpmn.behavior; - -import org.activiti.engine.impl.context.Context; -import org.activiti.engine.impl.pvm.delegate.ActivityExecution; - -/** - * @author Joram Barrez - */ -public class NoneEndEventActivityBehavior extends FlowNodeActivityBehavior { - - private static final long serialVersionUID = 1L; - - public void execute(ActivityExecution execution) { - Context.getAgenda().planTakeOutgoingSequenceFlowsOperation(execution); - } - -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/old/NoneEndEventActivityBehavior.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/old/NoneEndEventActivityBehavior.java deleted file mode 100755 index e7e37b3..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/old/NoneEndEventActivityBehavior.java +++ /dev/null @@ -1,27 +0,0 @@ -/* 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.activiti.engine.impl.bpmn.behavior; - -import org.activiti.engine.impl.context.Context; -import org.activiti.engine.impl.pvm.delegate.ActivityExecution; - -/** - * @author Joram Barrez - */ -public class NoneEndEventActivityBehavior extends FlowNodeActivityBehavior { - - public void execute(ActivityExecution execution) { - Context.getAgenda().planEndExecutionOperation(execution); - } - -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/pair.info deleted file mode 100755 index f8c4e82..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#8623/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:8623 -comSha:ba5734051dbfcc266ea7770172361fc6a2d5a8bd -parentComSha:4538c2757100bd3e355d31c6441bc9188d6554b3 -BuggyFilePath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/NoneEndEventActivityBehavior.java -FixedFilePath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/bpmn/behavior/NoneEndEventActivityBehavior.java -StartLineNum:21 -EndLineNum:25 -repoName:Activiti#Activiti \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/comMsg.txt b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/comMsg.txt deleted file mode 100755 index b622295..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -javadoc warnings removed \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/diff.diff b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/diff.diff deleted file mode 100755 index 660ea3c..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/rio/src/main/java/org/semanticweb/owlapi/formats/NQuadsOntologyFormatFactory.java b/rio/src/main/java/org/semanticweb/owlapi/formats/NQuadsOntologyFormatFactory.java -index 06a974fdd..50c6f9c16 100644 ---- a/rio/src/main/java/org/semanticweb/owlapi/formats/NQuadsOntologyFormatFactory.java -+++ b/rio/src/main/java/org/semanticweb/owlapi/formats/NQuadsOntologyFormatFactory.java -@@ -17,3 +17 @@ public class NQuadsOntologyFormatFactory extends -- public NQuadsOntologyFormatFactory() { -- super(); -- } -+ private static final long serialVersionUID = 40000L; \ No newline at end of file diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/new/NQuadsOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/new/NQuadsOntologyFormatFactory.java deleted file mode 100755 index 50c6f9c..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/new/NQuadsOntologyFormatFactory.java +++ /dev/null @@ -1,23 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class NQuadsOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - private static final long serialVersionUID = 40000L; - - @Override - public RioRDFOntologyFormat createFormat() { - return new NQuadsOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/old/NQuadsOntologyFormatFactory.java b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/old/NQuadsOntologyFormatFactory.java deleted file mode 100755 index 06a974f..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/old/NQuadsOntologyFormatFactory.java +++ /dev/null @@ -1,25 +0,0 @@ -/** - * - */ -package org.semanticweb.owlapi.formats; - -import org.kohsuke.MetaInfServices; -import org.semanticweb.owlapi.model.OWLOntologyFormatFactory; - -/** - * @author Peter Ansell p_ansell@yahoo.com - */ -@MetaInfServices(OWLOntologyFormatFactory.class) -public class NQuadsOntologyFormatFactory extends - AbstractRioRDFOntologyFormatFactory implements - RioRDFOntologyFormatFactory { - - public NQuadsOntologyFormatFactory() { - super(); - } - - @Override - public RioRDFOntologyFormat createFormat() { - return new NQuadsOntologyFormat(); - } -} diff --git a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/pair.info b/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/pair.info deleted file mode 100755 index a660cfb..0000000 --- a/All/FindBugs-SE_NO_SERIALVERSIONID/FBViolation#86348/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:86348 -comSha:8c0ef92ae5eee1e1f6f3329b9eb81acd4b855769 -parentComSha:206a4c1dbe5906d21bf530afa26a5d1b8327c139 -BuggyFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/NQuadsOntologyFormatFactory.java -FixedFilePath:rio/src/main/java/org/semanticweb/owlapi/formats/NQuadsOntologyFormatFactory.java -StartLineNum:12 -EndLineNum:23 -repoName:owlcs#owlapi \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/comMsg.txt b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/comMsg.txt deleted file mode 100755 index f3d505f..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -First imple of replacing Ack{Receiver,Sender}Window with Table (https://issues.jboss.org/browse/JGRP-1419) \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/diff.diff b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/diff.diff deleted file mode 100755 index 0e4cead..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/diff.diff +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/src/org/jgroups/protocols/UNICAST2.java b/src/org/jgroups/protocols/UNICAST2.java -index b21383958..094e3c3b9 100644 ---- a/src/org/jgroups/protocols/UNICAST2.java -+++ b/src/org/jgroups/protocols/UNICAST2.java -@@ -401 +400,0 @@ public class UNICAST2 extends Protocol implements AgeOutCache.Handler
{ -- removeAllConnections(); -@@ -402,0 +402 @@ public class UNICAST2 extends Protocol implements AgeOutCache.Handler
{ -+ removeAllConnections(); -@@ -1167 +1167 @@ public class UNICAST2 extends Protocol implements AgeOutCache.Handler
{ -- Table sent_msgs; -+ final Table sent_msgs; -@@ -1171 +1170,0 @@ public class UNICAST2 extends Protocol implements AgeOutCache.Handler
{ -- final Lock lock=new ReentrantLock(); -@@ -1188,2 +1187 @@ public class UNICAST2 extends Protocol implements AgeOutCache.Handler
{ -- sb.append("send_conn_id=" + send_conn_id); -- sb.append(" (" + age() + " ms old)"); -+ sb.append("send_conn_id=" + send_conn_id).append(" (" + age() + " ms old)"); \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/new/UNICAST2.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/new/UNICAST2.java deleted file mode 100755 index 094e3c3..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/new/UNICAST2.java +++ /dev/null @@ -1,1274 +0,0 @@ -package org.jgroups.protocols; - -import org.jgroups.*; -import org.jgroups.annotations.MBean; -import org.jgroups.annotations.ManagedAttribute; -import org.jgroups.annotations.ManagedOperation; -import org.jgroups.annotations.Property; -import org.jgroups.conf.PropertyConverters; -import org.jgroups.stack.*; -import org.jgroups.util.*; - -import java.io.DataInput; -import java.io.DataOutput; -import java.util.*; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - - -/** - * Reliable unicast layer. Implemented with negative acks. Every sender keeps its messages in an AckSenderWindow. A - * receiver stores incoming messages in a NakReceiverWindow, and asks the sender for retransmission if a gap is - * detected. Every now and then (stable_interval), a timer task sends a STABLE message to all senders, including the - * highest received and delivered seqnos. A sender purges messages lower than highest delivered and asks the STABLE - * sender for messages it might have missed (smaller than highest received). A STABLE message can also be sent when - * a receiver has received more than max_bytes from a given sender.

- * The advantage of this protocol over {@link org.jgroups.protocols.UNICAST} is that it doesn't send acks for every - * message. Instead, it sends 'acks' after receiving max_bytes and/ or periodically (stable_interval). - * @author Bela Ban - */ -@MBean(description="Reliable unicast layer") -public class UNICAST2 extends Protocol implements AgeOutCache.Handler

{ - public static final long DEFAULT_FIRST_SEQNO=Global.DEFAULT_FIRST_UNICAST_SEQNO; - - - /* ------------------------------------------ Properties ------------------------------------------ */ - @Deprecated - private int[] timeout= {400, 800, 1600, 3200}; // for NakSenderWindow: max time to wait for missing acks - - /** - * The first value (in milliseconds) to use in the exponential backoff - * retransmission mechanism. Only enabled if the value is > 0 - */ - @Deprecated - @Property(description="The first value (in milliseconds) to use in the exponential backoff. Enabled if greater than 0", - deprecatedMessage="Not used anymore") - private int exponential_backoff=300; - - - @Property(description="Max number of messages to be removed from a NakReceiverWindow. This property might " + - "get removed anytime, so don't use it !") - private int max_msg_batch_size=50000; - - @Property(description="Max number of bytes before a stability message is sent to the sender") - protected long max_bytes=10000000; - - @Property(description="Max number of milliseconds before a stability message is sent to the sender(s)") - protected long stable_interval=60000L; - - @Property(description="Max number of STABLE messages sent for the same highest_received seqno. A value < 1 is invalid") - protected int max_stable_msgs=5; - - @Property(description="Number of rows of the matrix in the retransmission table (only for experts)",writable=false) - int xmit_table_num_rows=5; - - @Property(description="Number of elements of a row of the matrix in the retransmission table (only for experts). " + - "The capacity of the matrix is xmit_table_num_rows * xmit_table_msgs_per_row",writable=false) - int xmit_table_msgs_per_row=10000; - - @Property(description="Resize factor of the matrix in the retransmission table (only for experts)",writable=false) - double xmit_table_resize_factor=1.2; - - @Property(description="Number of milliseconds after which the matrix in the retransmission table " + - "is compacted (only for experts)",writable=false) - long xmit_table_max_compaction_time=10 * 60 * 1000; - - @Deprecated - @Property(description="If enabled, the removal of a message from the retransmission table causes an " + - "automatic purge (only for experts)",writable=false, deprecatedMessage="not used anymore") - boolean xmit_table_automatic_purging=true; - - @Property(description="Whether to use the old retransmitter which retransmits individual messages or the new one " + - "which uses ranges of retransmitted messages. Default is true. Note that this property will be removed in 3.0; " + - "it is only used to switch back to the old (and proven) retransmitter mechanism if issues occur") - private boolean use_range_based_retransmitter=true; - - @Property(description="Time (in milliseconds) after which an idle incoming or outgoing connection is closed. The " + - "connection will get re-established when used again. 0 disables connection reaping") - protected long conn_expiry_timeout=60000; - - @Property(description="Interval (in milliseconds) at which missing messages (from all retransmit buffers) " + - "are retransmitted") - protected long xmit_interval=1000; - /* --------------------------------------------- JMX ---------------------------------------------- */ - - - private long num_msgs_sent=0, num_msgs_received=0; - - - /* --------------------------------------------- Fields ------------------------------------------------ */ - - private final ConcurrentMap send_table=Util.createConcurrentMap(); - private final ConcurrentMap recv_table=Util.createConcurrentMap(); - - /** RetransmitTask running every xmit_interval ms */ - protected Future xmit_task; - - protected final ReentrantLock recv_table_lock=new ReentrantLock(); - - private volatile List
members=new ArrayList
(11); - - private Address local_addr=null; - - private TimeScheduler timer=null; // used for retransmissions (passed to AckSenderWindow) - - private boolean started=false; - - protected volatile boolean running=false; - - private short last_conn_id=0; - - protected long max_retransmit_time=60 * 1000L; - - private AgeOutCache
cache=null; - - private Future stable_task_future=null; // bcasts periodic STABLE message (added to timer below) - - protected Future connection_reaper; // closes idle connections - - - - public int[] getTimeout() {return timeout;} - - @Property(name="timeout",converter=PropertyConverters.IntegerArray.class, - description="list of timeouts", deprecatedMessage="not used anymore") - public void setTimeout(int[] val) { - if(val != null) - timeout=val; - } - - public void setMaxMessageBatchSize(int size) { - if(size >= 1) - max_msg_batch_size=size; - } - - @ManagedAttribute - public String getLocalAddress() {return local_addr != null? local_addr.toString() : "null";} - - @ManagedAttribute - public String getMembers() {return members.toString();} - - - @ManagedAttribute(description="Returns the number of outgoing (send) connections") - public int getNumSendConnections() { - return send_table.size(); - } - - @ManagedAttribute(description="Returns the number of incoming (receive) connections") - public int getNumReceiveConnections() { - return recv_table.size(); - } - - @ManagedAttribute(description="Returns the total number of outgoing (send) and incoming (receive) connections") - public int getNumConnections() { - return getNumReceiveConnections() + getNumSendConnections(); - } - - @ManagedOperation - public String printConnections() { - StringBuilder sb=new StringBuilder(); - if(!send_table.isEmpty()) { - sb.append("send connections:\n"); - for(Map.Entry entry: send_table.entrySet()) { - sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); - } - } - - if(!recv_table.isEmpty()) { - sb.append("\nreceive connections:\n"); - for(Map.Entry entry: recv_table.entrySet()) { - sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); - } - } - return sb.toString(); - } - - @ManagedAttribute(description="Whether the ConnectionReaper task is running") - public boolean isConnectionReaperRunning() {return connection_reaper != null && !connection_reaper.isDone();} - - - @ManagedAttribute - public long getNumMessagesSent() { - return num_msgs_sent; - } - - @ManagedAttribute - public long getNumMessagesReceived() { - return num_msgs_received; - } - - @ManagedAttribute(description="Total number of undelivered messages in all receive windows") - public long getXmitTableUndeliveredMessages() { - long retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.size(); - } - return retval; - } - - @ManagedAttribute(description="Total number of missing messages in all receive windows") - public long getXmitTableMissingMessages() { - long retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumMissing(); - } - return retval; - } - - @ManagedAttribute(description="Number of compactions in all (receive and send) windows") - public int getXmitTableNumCompactions() { - int retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumCompactions(); - } - for(SenderEntry entry: send_table.values()) { - if(entry.sent_msgs != null) - retval+=entry.sent_msgs.getNumCompactions(); - } - return retval; - } - - @ManagedAttribute(description="Number of moves in all (receive and send) windows") - public int getXmitTableNumMoves() { - int retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumMoves(); - } - for(SenderEntry entry: send_table.values()) { - if(entry.sent_msgs != null) - retval+=entry.sent_msgs.getNumMoves(); - } - return retval; - } - - @ManagedAttribute(description="Number of resizes in all (receive and send) windows") - public int getXmitTableNumResizes() { - int retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumResizes(); - } - for(SenderEntry entry: send_table.values()) { - if(entry.sent_msgs != null) - retval+=entry.sent_msgs.getNumResizes(); - } - return retval; - } - - @ManagedAttribute(description="Number of purges in all (receive and send) windows") - public int getXmitTableNumPurges() { - int retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumPurges(); - } - for(SenderEntry entry: send_table.values()) { - if(entry.sent_msgs != null) - retval+=entry.sent_msgs.getNumPurges(); - } - return retval; - } - - @ManagedOperation(description="Prints the contents of the receive windows for all members") - public String printReceiveWindowMessages() { - StringBuilder ret=new StringBuilder(local_addr + ":\n"); - for(Map.Entry entry: recv_table.entrySet()) { - Address addr=entry.getKey(); - Table buf=entry.getValue().received_msgs; - ret.append(addr).append(": ").append(buf.toString()).append('\n'); - } - return ret.toString(); - } - - @ManagedOperation(description="Prints the contents of the send windows for all members") - public String printSendWindowMessages() { - StringBuilder ret=new StringBuilder(local_addr + ":\n"); - for(Map.Entry entry: send_table.entrySet()) { - Address addr=entry.getKey(); - Table buf=entry.getValue().sent_msgs; - ret.append(addr).append(": ").append(buf.toString()).append('\n'); - } - return ret.toString(); - } - - - - @ManagedAttribute(description="Number of retransmit requests received") - protected final AtomicLong xmit_reqs_received=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit requests sent") - protected final AtomicLong xmit_reqs_sent=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit responses sent") - protected final AtomicLong xmit_rsps_sent=new AtomicLong(0); - - @ManagedAttribute(description="Is the retransmit task running") - public boolean isXmitTaskRunning() {return xmit_task != null && !xmit_task.isDone();} - - public long getMaxRetransmitTime() { - return max_retransmit_time; - } - - @Property(description="Max number of milliseconds we try to retransmit a message to any given member. After that, " + - "the connection is removed. Any new connection to that member will start with seqno #1 again. 0 disables this") - public void setMaxRetransmitTime(long max_retransmit_time) { - this.max_retransmit_time=max_retransmit_time; - if(cache != null && max_retransmit_time > 0) - cache.setTimeout(max_retransmit_time); - } - - @ManagedAttribute - public int getAgeOutCacheSize() { - return cache != null? cache.size() : 0; - } - - @ManagedOperation - public String printAgeOutCache() { - return cache != null? cache.toString() : "n/a"; - } - - public AgeOutCache
getAgeOutCache() { - return cache; - } - - - - public void resetStats() { - num_msgs_sent=num_msgs_received=0; - xmit_reqs_received.set(0); - xmit_reqs_sent.set(0); - xmit_rsps_sent.set(0); - } - - - public Map dumpStats() { - Map m=super.dumpStats(); - m.put("num_msgs_sent", num_msgs_sent); - m.put("num_msgs_received", num_msgs_received); - return m; - } - - - public TimeScheduler getTimer() { - return timer; - } - - /** - * Only used for unit tests, don't use ! - * @param timer - */ - public void setTimer(TimeScheduler timer) { - this.timer=timer; - } - - public void init() throws Exception { - super.init(); - if(max_stable_msgs < 1) - throw new IllegalArgumentException("max_stable_msgs ( " + max_stable_msgs + ") must be > 0"); - if(max_bytes <= 0) - throw new IllegalArgumentException("max_bytes has to be > 0"); - } - - public void start() throws Exception { - timer=getTransport().getTimer(); - if(timer == null) - throw new Exception("timer is null"); - if(max_retransmit_time > 0) - cache=new AgeOutCache
(timer, max_retransmit_time, this); - started=true; - running=true; - if(stable_interval > 0) - startStableTask(); - if(conn_expiry_timeout > 0) - startConnectionReaper(); - startRetransmitTask(); - } - - public void stop() { - started=false; - running=false; - stopStableTask(); - stopConnectionReaper(); - stopRetransmitTask(); - removeAllConnections(); - } - - - public Object up(Event evt) { - Message msg; - Address dst, src; - Unicast2Header hdr; - - switch(evt.getType()) { - - case Event.MSG: - msg=(Message)evt.getArg(); - dst=msg.getDest(); - - if(dst == null || msg.isFlagSet(Message.NO_RELIABILITY)) // only handle unicast messages - break; // pass up - - // changed from removeHeader(): we cannot remove the header because if we do loopback=true at the - // transport level, we will not have the header on retransmit ! (bela Aug 22 2006) - hdr=(Unicast2Header)msg.getHeader(this.id); - if(hdr == null) - break; - src=msg.getSrc(); - switch(hdr.type) { - case Unicast2Header.DATA: // received regular message - handleDataReceived(src, hdr.seqno, hdr.conn_id, hdr.first, msg, evt); - return null; // we pass the deliverable message up in handleDataReceived() - case Unicast2Header.XMIT_REQ: // received ACK for previously sent message - handleXmitRequest(src, (SeqnoList)msg.getObject()); - break; - case Unicast2Header.SEND_FIRST_SEQNO: - handleResendingOfFirstMessage(src, hdr.seqno); - break; - case Unicast2Header.STABLE: - stable(msg.getSrc(), hdr.conn_id, hdr.seqno, hdr.high_seqno); - break; - default: - log.error("UnicastHeader type " + hdr.type + " not known !"); - break; - } - return null; - } - - return up_prot.up(evt); // Pass up to the layer above us - } - - - - public Object down(Event evt) { - switch (evt.getType()) { - - case Event.MSG: // Add UnicastHeader, add to AckSenderWindow and pass down - Message msg=(Message)evt.getArg(); - Address dst=msg.getDest(); - - /* only handle unicast messages */ - if (dst == null || msg.isFlagSet(Message.NO_RELIABILITY)) - break; - - if(!started) { - if(log.isTraceEnabled()) - log.trace("discarded message as start() has not yet been called, message: " + msg); - return null; - } - - SenderEntry entry=send_table.get(dst); - if(entry == null) { - entry=new SenderEntry(getNewConnectionId()); - SenderEntry existing=send_table.putIfAbsent(dst, entry); - if(existing != null) - entry=existing; - else { - if(log.isTraceEnabled()) - log.trace(local_addr + ": created connection to " + dst + " (conn_id=" + entry.send_conn_id + ")"); - if(cache != null && !members.contains(dst)) - cache.add(dst); - } - } - - short send_conn_id=entry.send_conn_id; - long seqno=entry.sent_msgs_seqno.getAndIncrement(); - long sleep=10; - while(running) { - try { - msg.putHeader(this.id, Unicast2Header.createDataHeader(seqno,send_conn_id,seqno == DEFAULT_FIRST_SEQNO)); - entry.sent_msgs.add(seqno,msg); // add *including* UnicastHeader, adds to retransmitter - if(conn_expiry_timeout > 0) - entry.update(); - break; - } - catch(Throwable t) { - if(!running) - break; - if(log.isWarnEnabled()) - log.warn("failed sending message", t); - Util.sleep(sleep); - sleep=Math.min(5000, sleep*2); - } - } - - if(log.isTraceEnabled()) { - StringBuilder sb=new StringBuilder(); - sb.append(local_addr).append(" --> DATA(").append(dst).append(": #").append(seqno). - append(", conn_id=").append(send_conn_id); - if(seqno == DEFAULT_FIRST_SEQNO) sb.append(", first"); - sb.append(')'); - log.trace(sb); - } - - try { - down_prot.down(evt); - num_msgs_sent++; - } - catch(Throwable t) { - log.warn("failed sending the message", t); - } - return null; // we already passed the msg down - - case Event.VIEW_CHANGE: // remove connections to peers that are not members anymore ! - View view=(View)evt.getArg(); - List
new_members=view.getMembers(); - Set
non_members=new HashSet
(send_table.keySet()); - non_members.addAll(recv_table.keySet()); - - members=new_members; - non_members.removeAll(new_members); - if(cache != null) - cache.removeAll(new_members); - - if(!non_members.isEmpty()) { - if(log.isTraceEnabled()) - log.trace("removing non members " + non_members); - for(Address non_mbr: non_members) - removeConnection(non_mbr); - } - break; - - case Event.SET_LOCAL_ADDRESS: - local_addr=(Address)evt.getArg(); - break; - } - - return down_prot.down(evt); // Pass on to the layer below us - } - - /** - * Purge all messages in window for local_addr, which are <= low. Check if the window's highest received message is - * > high: if true, retransmit all messages from high - win.high to sender - * @param sender - * @param hd Highest delivered seqno - * @param hr Highest received seqno - */ - protected void stable(Address sender, short conn_id, long hd, long hr) { - SenderEntry entry=send_table.get(sender); - Table win=entry != null? entry.sent_msgs : null; - if(win == null) - return; - - if(log.isTraceEnabled()) - log.trace(new StringBuilder().append(local_addr).append(" <-- STABLE(").append(sender) - .append(": ").append(hd).append("-") - .append(hr).append(", conn_id=" + conn_id) +")"); - - if(entry.send_conn_id != conn_id) { - log.warn(local_addr + ": my conn_id (" + entry.send_conn_id + - ") != received conn_id (" + conn_id + "); discarding STABLE message !"); - return; - } - - win.purge(hd,true); - long win_hr=win.getHighestReceived(); - if(win_hr > hr) { - for(long seqno=hr; seqno <= win_hr; seqno++) { - Message msg=win.get(seqno); // destination is still the same (the member which sent the STABLE message) - if(msg != null) - down_prot.down(new Event(Event.MSG, msg)); - } - } - } - - @ManagedOperation(description="Sends a STABLE message to all senders. This causes message purging and potential" + - " retransmissions from senders") - public void sendStableMessages() { - for(Map.Entry entry: recv_table.entrySet()) { - Address dest=entry.getKey(); - ReceiverEntry val=entry.getValue(); - Table win=val != null? val.received_msgs : null; - if(win != null) { - long[] tmp=win.getDigest(); - long low=tmp[0], high=tmp[1]; - - if(val.last_highest == high) { - if(val.num_stable_msgs >= max_stable_msgs) { - continue; - } - else - val.num_stable_msgs++; - } - else { - val.last_highest=high; - val.num_stable_msgs=1; - } - sendStableMessage(dest, val.recv_conn_id, low, high); - } - } - } - - protected void sendStableMessage(Address dest, short conn_id, long hd, long hr) { - Message stable_msg=new Message(dest, null, null); - Unicast2Header hdr=Unicast2Header.createStableHeader(conn_id, hd, hr); - stable_msg.putHeader(this.id, hdr); - stable_msg.setFlag(Message.OOB); - if(log.isTraceEnabled()) { - StringBuilder sb=new StringBuilder(); - sb.append(local_addr).append(" --> STABLE(").append(dest).append(": ") - .append(hd).append("-").append(hr).append(", conn_id=").append(conn_id).append(")"); - log.trace(sb.toString()); - } - down_prot.down(new Event(Event.MSG, stable_msg)); - } - - - private void startStableTask() { - if(stable_task_future == null || stable_task_future.isDone()) { - final Runnable stable_task=new Runnable() { - public void run() { - try { - sendStableMessages(); - } - catch(Throwable t) { - log.error("sending of STABLE messages failed", t); - } - } - }; - stable_task_future=timer.scheduleWithFixedDelay(stable_task, stable_interval, stable_interval, TimeUnit.MILLISECONDS); - if(log.isTraceEnabled()) - log.trace("stable task started"); - } - } - - - private void stopStableTask() { - if(stable_task_future != null) { - stable_task_future.cancel(false); - stable_task_future=null; - } - } - - protected synchronized void startConnectionReaper() { - if(connection_reaper == null || connection_reaper.isDone()) - connection_reaper=timer.scheduleWithFixedDelay(new ConnectionReaper(), conn_expiry_timeout, conn_expiry_timeout, TimeUnit.MILLISECONDS); - } - - protected synchronized void stopConnectionReaper() { - if(connection_reaper != null) - connection_reaper.cancel(false); - } - - /** - * Removes and resets from connection table (which is already locked). Returns true if member was found, otherwise - * false. This method is public only so it can be invoked by unit testing, but should not otherwise be used ! - */ - public void removeConnection(Address mbr) { - removeSendConnection(mbr); - removeReceiveConnection(mbr); - } - - public void removeSendConnection(Address mbr) { - send_table.remove(mbr); - } - - public void removeReceiveConnection(Address mbr) { - ReceiverEntry entry2=recv_table.remove(mbr); - if(entry2 != null) { - Table win=entry2.received_msgs; - if(win != null) - sendStableMessage(mbr, entry2.recv_conn_id, win.getHighestDelivered(), win.getHighestReceived()); - entry2.reset(); - } - } - - - /** - * This method is public only so it can be invoked by unit testing, but should not otherwise be used ! - */ - @ManagedOperation(description="Trashes all connections to other nodes. This is only used for testing") - public void removeAllConnections() { - send_table.clear(); - sendStableMessages(); - for(ReceiverEntry entry2: recv_table.values()) - entry2.reset(); - recv_table.clear(); - } - - - public void retransmit(SeqnoList missing, Address sender) { - Unicast2Header hdr=Unicast2Header.createXmitReqHeader(); - Message retransmit_msg=new Message(sender, null, missing); - retransmit_msg.setFlag(Message.OOB); - if(log.isTraceEnabled()) - log.trace(local_addr + ": sending XMIT_REQ (" + missing + ") to " + sender); - retransmit_msg.putHeader(this.id, hdr); - down_prot.down(new Event(Event.MSG,retransmit_msg)); - xmit_reqs_sent.addAndGet(missing.size()); - } - - - /** - * Called by AgeOutCache, to removed expired connections - * @param key - */ - public void expired(Address key) { - if(key != null) { - if(log.isDebugEnabled()) - log.debug("removing connection to " + key + " because it expired"); - removeConnection(key); - } - } - - - - /** - * Check whether the hashmap contains an entry e for sender (create if not). If - * e.received_msgs is null and first is true: create a new AckReceiverWindow(seqno) and - * add message. Set e.received_msgs to the new window. Else just add the message. - */ - protected void handleDataReceived(Address sender, long seqno, short conn_id, boolean first, Message msg, Event evt) { - if(log.isTraceEnabled()) { - StringBuilder sb=new StringBuilder(); - sb.append(local_addr).append(" <-- DATA(").append(sender).append(": #").append(seqno); - if(conn_id != 0) sb.append(", conn_id=").append(conn_id); - if(first) sb.append(", first"); - sb.append(')'); - log.trace(sb); - } - - ReceiverEntry entry=getReceiverEntry(sender, seqno, first, conn_id); - if(entry == null) - return; - if(conn_expiry_timeout > 0) - entry.update(); - Table win=entry.received_msgs; - boolean added=win.add(seqno, msg); // win is guaranteed to be non-null if we get here - num_msgs_received++; - - if(added) { - int len=msg.getLength(); - if(len > 0 && entry.incrementStable(len)) - sendStableMessage(sender, entry.recv_conn_id, win.getHighestDelivered(), win.getHighestReceived()); - } - - // An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering ! - // http://jira.jboss.com/jira/browse/JGRP-377 - if(msg.isFlagSet(Message.OOB) && added) { - try { - up_prot.up(evt); - } - catch(Throwable t) { - log.error("couldn't deliver OOB message " + msg, t); - } - } - - final AtomicBoolean processing=win.getProcessing(); - if(!processing.compareAndSet(false, true)) { - return; - } - - // Try to remove as many messages as possible and pass them up. - // Prevents concurrent passing up of messages by different threads (http://jira.jboss.com/jira/browse/JGRP-198); - // this is all the more important once we have a concurrent stack (http://jira.jboss.com/jira/browse/JGRP-181), - // where lots of threads can come up to this point concurrently, but only 1 is allowed to pass at a time - // We *can* deliver messages from *different* senders concurrently, e.g. reception of P1, Q1, P2, Q2 can result in - // delivery of P1, Q1, Q2, P2: FIFO (implemented by UNICAST) says messages need to be delivered only in the - // order in which they were sent by their senders - boolean released_processing=false; - try { - while(true) { - List msgs=win.removeMany(processing, true, max_msg_batch_size); // remove my own messages - if(msgs == null || msgs.isEmpty()) { - released_processing=true; - return; - } - - for(Message m: msgs) { - // discard OOB msg: it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-377) - if(m.isFlagSet(Message.OOB)) - continue; - try { - up_prot.up(new Event(Event.MSG, m)); - } - catch(Throwable t) { - log.error("couldn't deliver message " + m, t); - } - } - } - } - finally { - // processing is always set in win.remove(processing) above and never here ! This code is just a - // 2nd line of defense should there be an exception before win.remove(processing) sets processing - if(!released_processing) - processing.set(false); - } - } - - - protected ReceiverEntry getReceiverEntry(Address sender, long seqno, boolean first, short conn_id) { - ReceiverEntry entry=recv_table.get(sender); - if(entry != null && entry.recv_conn_id == conn_id) - return entry; - - recv_table_lock.lock(); - try { - entry=recv_table.get(sender); - if(first) { - if(entry == null) { - entry=getOrCreateReceiverEntry(sender, seqno, conn_id); - } - else { // entry != null && win != null - if(conn_id != entry.recv_conn_id) { - if(log.isTraceEnabled()) - log.trace(local_addr + ": conn_id=" + conn_id + " != " + entry.recv_conn_id + "; resetting receiver window"); - - recv_table.remove(sender); - entry=getOrCreateReceiverEntry(sender, seqno, conn_id); - } - else { - ; - } - } - } - else { // entry == null && win == null OR entry != null && win == null OR entry != null && win != null - if(entry == null || entry.recv_conn_id != conn_id) { - recv_table_lock.unlock(); - sendRequestForFirstSeqno(sender, seqno); // drops the message and returns (see below) - return null; - } - } - return entry; - } - finally { - if(recv_table_lock.isHeldByCurrentThread()) - recv_table_lock.unlock(); - } - } - - - private ReceiverEntry getOrCreateReceiverEntry(Address sender, long seqno, short conn_id) { - Table table=new Table(xmit_table_num_rows, xmit_table_msgs_per_row, seqno-1, - xmit_table_resize_factor, xmit_table_max_compaction_time); - ReceiverEntry entry=new ReceiverEntry(table, conn_id); - ReceiverEntry entry2=recv_table.putIfAbsent(sender, entry); - if(entry2 != null) - return entry2; - if(log.isTraceEnabled()) - log.trace(local_addr + ": created receiver window for " + sender + " at seqno=#" + seqno + " for conn-id=" + conn_id); - return entry; - } - - - private void handleXmitRequest(Address sender, SeqnoList missing) { - if(log.isTraceEnabled()) - log.trace(new StringBuilder().append(local_addr).append(" <-- XMIT(").append(sender). - append(": #").append(missing).append(')')); - - SenderEntry entry=send_table.get(sender); - xmit_reqs_received.addAndGet(missing.size()); - Table win=entry != null? entry.sent_msgs : null; - if(win != null) { - for(long seqno: missing) { - Message msg=win.get(seqno); - if(msg == null) { - if(log.isWarnEnabled() && !local_addr.equals(sender)) { - StringBuilder sb=new StringBuilder(); - sb.append("(requester=").append(sender).append(", local_addr=").append(this.local_addr); - sb.append(") message ").append(sender).append("::").append(seqno); - sb.append(" not found in retransmission table of ").append(sender).append(":\n").append(win); - log.warn(sb.toString()); - } - continue; - } - - down_prot.down(new Event(Event.MSG, msg)); - xmit_rsps_sent.incrementAndGet(); - } - } - } - - - /** - * We need to resend our first message with our conn_id - * @param sender - * @param seqno Resend the non null messages in the range [lowest .. seqno] - */ - private void handleResendingOfFirstMessage(Address sender, long seqno) { - if(log.isTraceEnabled()) - log.trace(local_addr + " <-- SEND_FIRST_SEQNO(" + sender + "," + seqno + ")"); - SenderEntry entry=send_table.get(sender); - Table win=entry != null? entry.sent_msgs : null; - if(win == null) { - if(log.isErrorEnabled()) - log.error(local_addr + ": sender window for " + sender + " not found"); - return; - } - - boolean first_sent=false; - for(long i=win.getLow() +1; i <= seqno; i++) { - Message rsp=win.get(i); - if(rsp == null) - continue; - if(first_sent) { - down_prot.down(new Event(Event.MSG, rsp)); - } - else { - first_sent=true; - // We need to copy the UnicastHeader and put it back into the message because Message.copy() doesn't copy - // the headers and therefore we'd modify the original message in the sender retransmission window - // (https://jira.jboss.org/jira/browse/JGRP-965) - Message copy=rsp.copy(); - Unicast2Header hdr=(Unicast2Header)copy.getHeader(this.id); - Unicast2Header newhdr=hdr.copy(); - newhdr.first=true; - copy.putHeader(this.id, newhdr); - down_prot.down(new Event(Event.MSG, copy)); - } - } - } - - protected void startRetransmitTask() { - if(xmit_task == null || xmit_task.isDone()) - xmit_task=timer.scheduleWithFixedDelay(new RetransmitTask(), 0, xmit_interval, TimeUnit.MILLISECONDS); - } - - protected void stopRetransmitTask() { - if(xmit_task != null) { - xmit_task.cancel(true); - xmit_task=null; - } - } - - - - private synchronized short getNewConnectionId() { - short retval=last_conn_id; - if(last_conn_id >= Short.MAX_VALUE || last_conn_id < 0) - last_conn_id=0; - else - last_conn_id++; - return retval; - } - - private void sendRequestForFirstSeqno(Address dest, long seqno_received) { - Message msg=new Message(dest); - msg.setFlag(Message.OOB); - Unicast2Header hdr=Unicast2Header.createSendFirstSeqnoHeader(seqno_received); - msg.putHeader(this.id, hdr); - if(log.isTraceEnabled()) - log.trace(local_addr + " --> SEND_FIRST_SEQNO(" + dest + "," + seqno_received + ")"); - down_prot.down(new Event(Event.MSG, msg)); - } - - @ManagedOperation(description="Closes connections that have been idle for more than conn_expiry_timeout ms") - public void reapIdleConnections() { - if(conn_expiry_timeout <= 0) - return; - - // remove expired connections from send_table - for(Map.Entry entry: send_table.entrySet()) { - SenderEntry val=entry.getValue(); - long age=val.age(); - if(age >= conn_expiry_timeout) { - removeSendConnection(entry.getKey()); - if(log.isDebugEnabled()) - log.debug(local_addr + ": removed expired connection for " + entry.getKey() + - " (" + age + " ms old) from send_table"); - } - } - - // remove expired connections from recv_table - for(Map.Entry entry: recv_table.entrySet()) { - ReceiverEntry val=entry.getValue(); - long age=val.age(); - if(age >= conn_expiry_timeout) { - removeReceiveConnection(entry.getKey()); - if(log.isDebugEnabled()) - log.debug(local_addr + ": removed expired connection for " + entry.getKey() + - " (" + age + " ms old) from recv_table"); - } - } - } - - - /** - * The following types and fields are serialized: - *
-     * | DATA | seqno | conn_id | first |
-     * | ACK  | seqno |
-     * | SEND_FIRST_SEQNO | seqno |
-     * 
- */ - public static class Unicast2Header extends Header { - public static final byte DATA = 0; - public static final byte XMIT_REQ = 1; - public static final byte SEND_FIRST_SEQNO = 2; - public static final byte STABLE = 3; - - byte type; - long seqno; // DATA and STABLE - long high_seqno; // STABLE - short conn_id; // DATA, STABLE - boolean first; // DATA - - - public Unicast2Header() {} // used for externalization - - public static Unicast2Header createDataHeader(long seqno, short conn_id, boolean first) { - return new Unicast2Header(DATA, seqno, 0L, conn_id, first); - } - - public static Unicast2Header createXmitReqHeader() { - return new Unicast2Header(XMIT_REQ); - } - - public static Unicast2Header createStableHeader(short conn_id, long low, long high) { - if(low > high) - throw new IllegalArgumentException("low (" + low + ") needs to be <= high (" + high + ")"); - Unicast2Header retval=new Unicast2Header(STABLE, low); - retval.high_seqno=high; - retval.conn_id=conn_id; - return retval; - } - - public static Unicast2Header createSendFirstSeqnoHeader(long seqno_received) { - return new Unicast2Header(SEND_FIRST_SEQNO, seqno_received); - } - - private Unicast2Header(byte type) { - this.type=type; - } - - private Unicast2Header(byte type, long seqno) { - this.type=type; - this.seqno=seqno; - } - - private Unicast2Header(byte type, long seqno, long high, short conn_id, boolean first) { - this.type=type; - this.seqno=seqno; - this.high_seqno=high; - this.conn_id=conn_id; - this.first=first; - } - - public byte getType() { - return type; - } - - public long getSeqno() { - return seqno; - } - - public long getHighSeqno() { - return high_seqno; - } - - public short getConnId() { - return conn_id; - } - - - public boolean isFirst() { - return first; - } - - public String toString() { - StringBuilder sb=new StringBuilder(); - sb.append(type2Str(type)).append(", seqno=").append(seqno); - if(conn_id != 0) sb.append(", conn_id=").append(conn_id); - if(first) sb.append(", first"); - return sb.toString(); - } - - public static String type2Str(byte t) { - switch(t) { - case DATA: return "DATA"; - case XMIT_REQ: return "XMIT_REQ"; - case SEND_FIRST_SEQNO: return "SEND_FIRST_SEQNO"; - case STABLE: return "STABLE"; - default: return ""; - } - } - - public final int size() { - int retval=Global.BYTE_SIZE; // type - switch(type) { - case DATA: - retval+=Util.size(seqno) // seqno - + Global.SHORT_SIZE // conn_id - + Global.BYTE_SIZE; // first - break; - case XMIT_REQ: - break; - case STABLE: - retval+=Util.size(seqno, high_seqno) + Global.SHORT_SIZE; // conn_id - break; - case SEND_FIRST_SEQNO: - retval+=Util.size(seqno); - break; - } - return retval; - } - - public Unicast2Header copy() { - return new Unicast2Header(type, seqno, high_seqno, conn_id, first); - } - - - - public void writeTo(DataOutput out) throws Exception { - out.writeByte(type); - switch(type) { - case DATA: - Util.writeLong(seqno, out); - out.writeShort(conn_id); - out.writeBoolean(first); - break; - case XMIT_REQ: - break; - case STABLE: - Util.writeLongSequence(seqno, high_seqno, out); - out.writeShort(conn_id); - break; - case SEND_FIRST_SEQNO: - Util.writeLong(seqno, out); - break; - } - } - - public void readFrom(DataInput in) throws Exception { - type=in.readByte(); - switch(type) { - case DATA: - seqno=Util.readLong(in); - conn_id=in.readShort(); - first=in.readBoolean(); - break; - case XMIT_REQ: - break; - case STABLE: - long[] seqnos=Util.readLongSequence(in); - seqno=seqnos[0]; - high_seqno=seqnos[1]; - conn_id=in.readShort(); - break; - case SEND_FIRST_SEQNO: - seqno=Util.readLong(in); - break; - } - } - } - - - - private final class SenderEntry { - // stores (and retransmits) msgs sent by us to a given peer - final Table sent_msgs; - final AtomicLong sent_msgs_seqno=new AtomicLong(DEFAULT_FIRST_SEQNO); // seqno for msgs sent by us - final short send_conn_id; - private final AtomicLong timestamp=new AtomicLong(0); - - public SenderEntry(short send_conn_id) { - this.send_conn_id=send_conn_id; - this.sent_msgs=new Table(xmit_table_num_rows, xmit_table_msgs_per_row, 0, - xmit_table_resize_factor, xmit_table_max_compaction_time); - update(); - } - - - void update() {timestamp.set(System.currentTimeMillis());} - long age() {return System.currentTimeMillis() - timestamp.longValue();} - - public String toString() { - StringBuilder sb=new StringBuilder(); - if(sent_msgs != null) - sb.append(sent_msgs).append(", "); - sb.append("send_conn_id=" + send_conn_id).append(" (" + age() + " ms old)"); - return sb.toString(); - } - } - - protected final class ReceiverEntry { - private final Table received_msgs; // stores all msgs rcvd by a certain peer in seqno-order - private final short recv_conn_id; - private int received_bytes=0; - private final AtomicLong timestamp=new AtomicLong(0); - private final Lock lock=new ReentrantLock(); - - private long last_highest=-1; - private int num_stable_msgs=0; - - - - public ReceiverEntry(Table received_msgs, short recv_conn_id) { - this.received_msgs=received_msgs; - this.recv_conn_id=recv_conn_id; - update(); - } - - /** Adds len bytes, if max_bytes is exceeded, the value is reset and true returned, else false */ - boolean incrementStable(int len) { - lock.lock(); - try { - if(received_bytes+len >= max_bytes) { - received_bytes=0; - return true; - } - received_bytes+=len; - return false; - } - finally { - lock.unlock(); - } - } - - void reset() { - received_bytes=0; - last_highest=-1; - num_stable_msgs=0; - } - - void update() {timestamp.set(System.currentTimeMillis());} - long age() {return System.currentTimeMillis() - timestamp.longValue();} - - public String toString() { - StringBuilder sb=new StringBuilder(); - if(received_msgs != null) - sb.append(received_msgs).append(", "); - sb.append("recv_conn_id=" + recv_conn_id); - sb.append(" (" + age() + " ms old)"); - return sb.toString(); - } - } - - - protected class ConnectionReaper implements Runnable { - public void run() { - reapIdleConnections(); - } - } - - /** - * Retransmitter task which periodically (every xmit_interval ms) looks at all the retransmit tables and - * sends retransmit request to all members from which we have missing messages - */ - protected class RetransmitTask implements Runnable { - - public void run() { - for(Map.Entry entry: recv_table.entrySet()) { - Address target=entry.getKey(); // target to send retransmit requests to - ReceiverEntry val=entry.getValue(); - Table buf=val != null? val.received_msgs : null; - if(buf != null && buf.getNumMissing() > 0) { - SeqnoList missing=buf.getMissing(); - if(missing != null) - retransmit(missing, target); - } - } - } - } - - - -} \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/old/UNICAST2.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/old/UNICAST2.java deleted file mode 100755 index b213839..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/old/UNICAST2.java +++ /dev/null @@ -1,1276 +0,0 @@ -package org.jgroups.protocols; - -import org.jgroups.*; -import org.jgroups.annotations.MBean; -import org.jgroups.annotations.ManagedAttribute; -import org.jgroups.annotations.ManagedOperation; -import org.jgroups.annotations.Property; -import org.jgroups.conf.PropertyConverters; -import org.jgroups.stack.*; -import org.jgroups.util.*; - -import java.io.DataInput; -import java.io.DataOutput; -import java.util.*; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - - -/** - * Reliable unicast layer. Implemented with negative acks. Every sender keeps its messages in an AckSenderWindow. A - * receiver stores incoming messages in a NakReceiverWindow, and asks the sender for retransmission if a gap is - * detected. Every now and then (stable_interval), a timer task sends a STABLE message to all senders, including the - * highest received and delivered seqnos. A sender purges messages lower than highest delivered and asks the STABLE - * sender for messages it might have missed (smaller than highest received). A STABLE message can also be sent when - * a receiver has received more than max_bytes from a given sender.

- * The advantage of this protocol over {@link org.jgroups.protocols.UNICAST} is that it doesn't send acks for every - * message. Instead, it sends 'acks' after receiving max_bytes and/ or periodically (stable_interval). - * @author Bela Ban - */ -@MBean(description="Reliable unicast layer") -public class UNICAST2 extends Protocol implements AgeOutCache.Handler

{ - public static final long DEFAULT_FIRST_SEQNO=Global.DEFAULT_FIRST_UNICAST_SEQNO; - - - /* ------------------------------------------ Properties ------------------------------------------ */ - @Deprecated - private int[] timeout= {400, 800, 1600, 3200}; // for NakSenderWindow: max time to wait for missing acks - - /** - * The first value (in milliseconds) to use in the exponential backoff - * retransmission mechanism. Only enabled if the value is > 0 - */ - @Deprecated - @Property(description="The first value (in milliseconds) to use in the exponential backoff. Enabled if greater than 0", - deprecatedMessage="Not used anymore") - private int exponential_backoff=300; - - - @Property(description="Max number of messages to be removed from a NakReceiverWindow. This property might " + - "get removed anytime, so don't use it !") - private int max_msg_batch_size=50000; - - @Property(description="Max number of bytes before a stability message is sent to the sender") - protected long max_bytes=10000000; - - @Property(description="Max number of milliseconds before a stability message is sent to the sender(s)") - protected long stable_interval=60000L; - - @Property(description="Max number of STABLE messages sent for the same highest_received seqno. A value < 1 is invalid") - protected int max_stable_msgs=5; - - @Property(description="Number of rows of the matrix in the retransmission table (only for experts)",writable=false) - int xmit_table_num_rows=5; - - @Property(description="Number of elements of a row of the matrix in the retransmission table (only for experts). " + - "The capacity of the matrix is xmit_table_num_rows * xmit_table_msgs_per_row",writable=false) - int xmit_table_msgs_per_row=10000; - - @Property(description="Resize factor of the matrix in the retransmission table (only for experts)",writable=false) - double xmit_table_resize_factor=1.2; - - @Property(description="Number of milliseconds after which the matrix in the retransmission table " + - "is compacted (only for experts)",writable=false) - long xmit_table_max_compaction_time=10 * 60 * 1000; - - @Deprecated - @Property(description="If enabled, the removal of a message from the retransmission table causes an " + - "automatic purge (only for experts)",writable=false, deprecatedMessage="not used anymore") - boolean xmit_table_automatic_purging=true; - - @Property(description="Whether to use the old retransmitter which retransmits individual messages or the new one " + - "which uses ranges of retransmitted messages. Default is true. Note that this property will be removed in 3.0; " + - "it is only used to switch back to the old (and proven) retransmitter mechanism if issues occur") - private boolean use_range_based_retransmitter=true; - - @Property(description="Time (in milliseconds) after which an idle incoming or outgoing connection is closed. The " + - "connection will get re-established when used again. 0 disables connection reaping") - protected long conn_expiry_timeout=60000; - - @Property(description="Interval (in milliseconds) at which missing messages (from all retransmit buffers) " + - "are retransmitted") - protected long xmit_interval=1000; - /* --------------------------------------------- JMX ---------------------------------------------- */ - - - private long num_msgs_sent=0, num_msgs_received=0; - - - /* --------------------------------------------- Fields ------------------------------------------------ */ - - private final ConcurrentMap send_table=Util.createConcurrentMap(); - private final ConcurrentMap recv_table=Util.createConcurrentMap(); - - /** RetransmitTask running every xmit_interval ms */ - protected Future xmit_task; - - protected final ReentrantLock recv_table_lock=new ReentrantLock(); - - private volatile List
members=new ArrayList
(11); - - private Address local_addr=null; - - private TimeScheduler timer=null; // used for retransmissions (passed to AckSenderWindow) - - private boolean started=false; - - protected volatile boolean running=false; - - private short last_conn_id=0; - - protected long max_retransmit_time=60 * 1000L; - - private AgeOutCache
cache=null; - - private Future stable_task_future=null; // bcasts periodic STABLE message (added to timer below) - - protected Future connection_reaper; // closes idle connections - - - - public int[] getTimeout() {return timeout;} - - @Property(name="timeout",converter=PropertyConverters.IntegerArray.class, - description="list of timeouts", deprecatedMessage="not used anymore") - public void setTimeout(int[] val) { - if(val != null) - timeout=val; - } - - public void setMaxMessageBatchSize(int size) { - if(size >= 1) - max_msg_batch_size=size; - } - - @ManagedAttribute - public String getLocalAddress() {return local_addr != null? local_addr.toString() : "null";} - - @ManagedAttribute - public String getMembers() {return members.toString();} - - - @ManagedAttribute(description="Returns the number of outgoing (send) connections") - public int getNumSendConnections() { - return send_table.size(); - } - - @ManagedAttribute(description="Returns the number of incoming (receive) connections") - public int getNumReceiveConnections() { - return recv_table.size(); - } - - @ManagedAttribute(description="Returns the total number of outgoing (send) and incoming (receive) connections") - public int getNumConnections() { - return getNumReceiveConnections() + getNumSendConnections(); - } - - @ManagedOperation - public String printConnections() { - StringBuilder sb=new StringBuilder(); - if(!send_table.isEmpty()) { - sb.append("send connections:\n"); - for(Map.Entry entry: send_table.entrySet()) { - sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); - } - } - - if(!recv_table.isEmpty()) { - sb.append("\nreceive connections:\n"); - for(Map.Entry entry: recv_table.entrySet()) { - sb.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); - } - } - return sb.toString(); - } - - @ManagedAttribute(description="Whether the ConnectionReaper task is running") - public boolean isConnectionReaperRunning() {return connection_reaper != null && !connection_reaper.isDone();} - - - @ManagedAttribute - public long getNumMessagesSent() { - return num_msgs_sent; - } - - @ManagedAttribute - public long getNumMessagesReceived() { - return num_msgs_received; - } - - @ManagedAttribute(description="Total number of undelivered messages in all receive windows") - public long getXmitTableUndeliveredMessages() { - long retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.size(); - } - return retval; - } - - @ManagedAttribute(description="Total number of missing messages in all receive windows") - public long getXmitTableMissingMessages() { - long retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumMissing(); - } - return retval; - } - - @ManagedAttribute(description="Number of compactions in all (receive and send) windows") - public int getXmitTableNumCompactions() { - int retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumCompactions(); - } - for(SenderEntry entry: send_table.values()) { - if(entry.sent_msgs != null) - retval+=entry.sent_msgs.getNumCompactions(); - } - return retval; - } - - @ManagedAttribute(description="Number of moves in all (receive and send) windows") - public int getXmitTableNumMoves() { - int retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumMoves(); - } - for(SenderEntry entry: send_table.values()) { - if(entry.sent_msgs != null) - retval+=entry.sent_msgs.getNumMoves(); - } - return retval; - } - - @ManagedAttribute(description="Number of resizes in all (receive and send) windows") - public int getXmitTableNumResizes() { - int retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumResizes(); - } - for(SenderEntry entry: send_table.values()) { - if(entry.sent_msgs != null) - retval+=entry.sent_msgs.getNumResizes(); - } - return retval; - } - - @ManagedAttribute(description="Number of purges in all (receive and send) windows") - public int getXmitTableNumPurges() { - int retval=0; - for(ReceiverEntry entry: recv_table.values()) { - if(entry.received_msgs != null) - retval+=entry.received_msgs.getNumPurges(); - } - for(SenderEntry entry: send_table.values()) { - if(entry.sent_msgs != null) - retval+=entry.sent_msgs.getNumPurges(); - } - return retval; - } - - @ManagedOperation(description="Prints the contents of the receive windows for all members") - public String printReceiveWindowMessages() { - StringBuilder ret=new StringBuilder(local_addr + ":\n"); - for(Map.Entry entry: recv_table.entrySet()) { - Address addr=entry.getKey(); - Table buf=entry.getValue().received_msgs; - ret.append(addr).append(": ").append(buf.toString()).append('\n'); - } - return ret.toString(); - } - - @ManagedOperation(description="Prints the contents of the send windows for all members") - public String printSendWindowMessages() { - StringBuilder ret=new StringBuilder(local_addr + ":\n"); - for(Map.Entry entry: send_table.entrySet()) { - Address addr=entry.getKey(); - Table buf=entry.getValue().sent_msgs; - ret.append(addr).append(": ").append(buf.toString()).append('\n'); - } - return ret.toString(); - } - - - - @ManagedAttribute(description="Number of retransmit requests received") - protected final AtomicLong xmit_reqs_received=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit requests sent") - protected final AtomicLong xmit_reqs_sent=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit responses sent") - protected final AtomicLong xmit_rsps_sent=new AtomicLong(0); - - @ManagedAttribute(description="Is the retransmit task running") - public boolean isXmitTaskRunning() {return xmit_task != null && !xmit_task.isDone();} - - public long getMaxRetransmitTime() { - return max_retransmit_time; - } - - @Property(description="Max number of milliseconds we try to retransmit a message to any given member. After that, " + - "the connection is removed. Any new connection to that member will start with seqno #1 again. 0 disables this") - public void setMaxRetransmitTime(long max_retransmit_time) { - this.max_retransmit_time=max_retransmit_time; - if(cache != null && max_retransmit_time > 0) - cache.setTimeout(max_retransmit_time); - } - - @ManagedAttribute - public int getAgeOutCacheSize() { - return cache != null? cache.size() : 0; - } - - @ManagedOperation - public String printAgeOutCache() { - return cache != null? cache.toString() : "n/a"; - } - - public AgeOutCache
getAgeOutCache() { - return cache; - } - - - - public void resetStats() { - num_msgs_sent=num_msgs_received=0; - xmit_reqs_received.set(0); - xmit_reqs_sent.set(0); - xmit_rsps_sent.set(0); - } - - - public Map dumpStats() { - Map m=super.dumpStats(); - m.put("num_msgs_sent", num_msgs_sent); - m.put("num_msgs_received", num_msgs_received); - return m; - } - - - public TimeScheduler getTimer() { - return timer; - } - - /** - * Only used for unit tests, don't use ! - * @param timer - */ - public void setTimer(TimeScheduler timer) { - this.timer=timer; - } - - public void init() throws Exception { - super.init(); - if(max_stable_msgs < 1) - throw new IllegalArgumentException("max_stable_msgs ( " + max_stable_msgs + ") must be > 0"); - if(max_bytes <= 0) - throw new IllegalArgumentException("max_bytes has to be > 0"); - } - - public void start() throws Exception { - timer=getTransport().getTimer(); - if(timer == null) - throw new Exception("timer is null"); - if(max_retransmit_time > 0) - cache=new AgeOutCache
(timer, max_retransmit_time, this); - started=true; - running=true; - if(stable_interval > 0) - startStableTask(); - if(conn_expiry_timeout > 0) - startConnectionReaper(); - startRetransmitTask(); - } - - public void stop() { - started=false; - running=false; - stopStableTask(); - stopConnectionReaper(); - removeAllConnections(); - stopRetransmitTask(); - } - - - public Object up(Event evt) { - Message msg; - Address dst, src; - Unicast2Header hdr; - - switch(evt.getType()) { - - case Event.MSG: - msg=(Message)evt.getArg(); - dst=msg.getDest(); - - if(dst == null || msg.isFlagSet(Message.NO_RELIABILITY)) // only handle unicast messages - break; // pass up - - // changed from removeHeader(): we cannot remove the header because if we do loopback=true at the - // transport level, we will not have the header on retransmit ! (bela Aug 22 2006) - hdr=(Unicast2Header)msg.getHeader(this.id); - if(hdr == null) - break; - src=msg.getSrc(); - switch(hdr.type) { - case Unicast2Header.DATA: // received regular message - handleDataReceived(src, hdr.seqno, hdr.conn_id, hdr.first, msg, evt); - return null; // we pass the deliverable message up in handleDataReceived() - case Unicast2Header.XMIT_REQ: // received ACK for previously sent message - handleXmitRequest(src, (SeqnoList)msg.getObject()); - break; - case Unicast2Header.SEND_FIRST_SEQNO: - handleResendingOfFirstMessage(src, hdr.seqno); - break; - case Unicast2Header.STABLE: - stable(msg.getSrc(), hdr.conn_id, hdr.seqno, hdr.high_seqno); - break; - default: - log.error("UnicastHeader type " + hdr.type + " not known !"); - break; - } - return null; - } - - return up_prot.up(evt); // Pass up to the layer above us - } - - - - public Object down(Event evt) { - switch (evt.getType()) { - - case Event.MSG: // Add UnicastHeader, add to AckSenderWindow and pass down - Message msg=(Message)evt.getArg(); - Address dst=msg.getDest(); - - /* only handle unicast messages */ - if (dst == null || msg.isFlagSet(Message.NO_RELIABILITY)) - break; - - if(!started) { - if(log.isTraceEnabled()) - log.trace("discarded message as start() has not yet been called, message: " + msg); - return null; - } - - SenderEntry entry=send_table.get(dst); - if(entry == null) { - entry=new SenderEntry(getNewConnectionId()); - SenderEntry existing=send_table.putIfAbsent(dst, entry); - if(existing != null) - entry=existing; - else { - if(log.isTraceEnabled()) - log.trace(local_addr + ": created connection to " + dst + " (conn_id=" + entry.send_conn_id + ")"); - if(cache != null && !members.contains(dst)) - cache.add(dst); - } - } - - short send_conn_id=entry.send_conn_id; - long seqno=entry.sent_msgs_seqno.getAndIncrement(); - long sleep=10; - while(running) { - try { - msg.putHeader(this.id, Unicast2Header.createDataHeader(seqno,send_conn_id,seqno == DEFAULT_FIRST_SEQNO)); - entry.sent_msgs.add(seqno,msg); // add *including* UnicastHeader, adds to retransmitter - if(conn_expiry_timeout > 0) - entry.update(); - break; - } - catch(Throwable t) { - if(!running) - break; - if(log.isWarnEnabled()) - log.warn("failed sending message", t); - Util.sleep(sleep); - sleep=Math.min(5000, sleep*2); - } - } - - if(log.isTraceEnabled()) { - StringBuilder sb=new StringBuilder(); - sb.append(local_addr).append(" --> DATA(").append(dst).append(": #").append(seqno). - append(", conn_id=").append(send_conn_id); - if(seqno == DEFAULT_FIRST_SEQNO) sb.append(", first"); - sb.append(')'); - log.trace(sb); - } - - try { - down_prot.down(evt); - num_msgs_sent++; - } - catch(Throwable t) { - log.warn("failed sending the message", t); - } - return null; // we already passed the msg down - - case Event.VIEW_CHANGE: // remove connections to peers that are not members anymore ! - View view=(View)evt.getArg(); - List
new_members=view.getMembers(); - Set
non_members=new HashSet
(send_table.keySet()); - non_members.addAll(recv_table.keySet()); - - members=new_members; - non_members.removeAll(new_members); - if(cache != null) - cache.removeAll(new_members); - - if(!non_members.isEmpty()) { - if(log.isTraceEnabled()) - log.trace("removing non members " + non_members); - for(Address non_mbr: non_members) - removeConnection(non_mbr); - } - break; - - case Event.SET_LOCAL_ADDRESS: - local_addr=(Address)evt.getArg(); - break; - } - - return down_prot.down(evt); // Pass on to the layer below us - } - - /** - * Purge all messages in window for local_addr, which are <= low. Check if the window's highest received message is - * > high: if true, retransmit all messages from high - win.high to sender - * @param sender - * @param hd Highest delivered seqno - * @param hr Highest received seqno - */ - protected void stable(Address sender, short conn_id, long hd, long hr) { - SenderEntry entry=send_table.get(sender); - Table win=entry != null? entry.sent_msgs : null; - if(win == null) - return; - - if(log.isTraceEnabled()) - log.trace(new StringBuilder().append(local_addr).append(" <-- STABLE(").append(sender) - .append(": ").append(hd).append("-") - .append(hr).append(", conn_id=" + conn_id) +")"); - - if(entry.send_conn_id != conn_id) { - log.warn(local_addr + ": my conn_id (" + entry.send_conn_id + - ") != received conn_id (" + conn_id + "); discarding STABLE message !"); - return; - } - - win.purge(hd,true); - long win_hr=win.getHighestReceived(); - if(win_hr > hr) { - for(long seqno=hr; seqno <= win_hr; seqno++) { - Message msg=win.get(seqno); // destination is still the same (the member which sent the STABLE message) - if(msg != null) - down_prot.down(new Event(Event.MSG, msg)); - } - } - } - - @ManagedOperation(description="Sends a STABLE message to all senders. This causes message purging and potential" + - " retransmissions from senders") - public void sendStableMessages() { - for(Map.Entry entry: recv_table.entrySet()) { - Address dest=entry.getKey(); - ReceiverEntry val=entry.getValue(); - Table win=val != null? val.received_msgs : null; - if(win != null) { - long[] tmp=win.getDigest(); - long low=tmp[0], high=tmp[1]; - - if(val.last_highest == high) { - if(val.num_stable_msgs >= max_stable_msgs) { - continue; - } - else - val.num_stable_msgs++; - } - else { - val.last_highest=high; - val.num_stable_msgs=1; - } - sendStableMessage(dest, val.recv_conn_id, low, high); - } - } - } - - protected void sendStableMessage(Address dest, short conn_id, long hd, long hr) { - Message stable_msg=new Message(dest, null, null); - Unicast2Header hdr=Unicast2Header.createStableHeader(conn_id, hd, hr); - stable_msg.putHeader(this.id, hdr); - stable_msg.setFlag(Message.OOB); - if(log.isTraceEnabled()) { - StringBuilder sb=new StringBuilder(); - sb.append(local_addr).append(" --> STABLE(").append(dest).append(": ") - .append(hd).append("-").append(hr).append(", conn_id=").append(conn_id).append(")"); - log.trace(sb.toString()); - } - down_prot.down(new Event(Event.MSG, stable_msg)); - } - - - private void startStableTask() { - if(stable_task_future == null || stable_task_future.isDone()) { - final Runnable stable_task=new Runnable() { - public void run() { - try { - sendStableMessages(); - } - catch(Throwable t) { - log.error("sending of STABLE messages failed", t); - } - } - }; - stable_task_future=timer.scheduleWithFixedDelay(stable_task, stable_interval, stable_interval, TimeUnit.MILLISECONDS); - if(log.isTraceEnabled()) - log.trace("stable task started"); - } - } - - - private void stopStableTask() { - if(stable_task_future != null) { - stable_task_future.cancel(false); - stable_task_future=null; - } - } - - protected synchronized void startConnectionReaper() { - if(connection_reaper == null || connection_reaper.isDone()) - connection_reaper=timer.scheduleWithFixedDelay(new ConnectionReaper(), conn_expiry_timeout, conn_expiry_timeout, TimeUnit.MILLISECONDS); - } - - protected synchronized void stopConnectionReaper() { - if(connection_reaper != null) - connection_reaper.cancel(false); - } - - /** - * Removes and resets from connection table (which is already locked). Returns true if member was found, otherwise - * false. This method is public only so it can be invoked by unit testing, but should not otherwise be used ! - */ - public void removeConnection(Address mbr) { - removeSendConnection(mbr); - removeReceiveConnection(mbr); - } - - public void removeSendConnection(Address mbr) { - send_table.remove(mbr); - } - - public void removeReceiveConnection(Address mbr) { - ReceiverEntry entry2=recv_table.remove(mbr); - if(entry2 != null) { - Table win=entry2.received_msgs; - if(win != null) - sendStableMessage(mbr, entry2.recv_conn_id, win.getHighestDelivered(), win.getHighestReceived()); - entry2.reset(); - } - } - - - /** - * This method is public only so it can be invoked by unit testing, but should not otherwise be used ! - */ - @ManagedOperation(description="Trashes all connections to other nodes. This is only used for testing") - public void removeAllConnections() { - send_table.clear(); - sendStableMessages(); - for(ReceiverEntry entry2: recv_table.values()) - entry2.reset(); - recv_table.clear(); - } - - - public void retransmit(SeqnoList missing, Address sender) { - Unicast2Header hdr=Unicast2Header.createXmitReqHeader(); - Message retransmit_msg=new Message(sender, null, missing); - retransmit_msg.setFlag(Message.OOB); - if(log.isTraceEnabled()) - log.trace(local_addr + ": sending XMIT_REQ (" + missing + ") to " + sender); - retransmit_msg.putHeader(this.id, hdr); - down_prot.down(new Event(Event.MSG,retransmit_msg)); - xmit_reqs_sent.addAndGet(missing.size()); - } - - - /** - * Called by AgeOutCache, to removed expired connections - * @param key - */ - public void expired(Address key) { - if(key != null) { - if(log.isDebugEnabled()) - log.debug("removing connection to " + key + " because it expired"); - removeConnection(key); - } - } - - - - /** - * Check whether the hashmap contains an entry e for sender (create if not). If - * e.received_msgs is null and first is true: create a new AckReceiverWindow(seqno) and - * add message. Set e.received_msgs to the new window. Else just add the message. - */ - protected void handleDataReceived(Address sender, long seqno, short conn_id, boolean first, Message msg, Event evt) { - if(log.isTraceEnabled()) { - StringBuilder sb=new StringBuilder(); - sb.append(local_addr).append(" <-- DATA(").append(sender).append(": #").append(seqno); - if(conn_id != 0) sb.append(", conn_id=").append(conn_id); - if(first) sb.append(", first"); - sb.append(')'); - log.trace(sb); - } - - ReceiverEntry entry=getReceiverEntry(sender, seqno, first, conn_id); - if(entry == null) - return; - if(conn_expiry_timeout > 0) - entry.update(); - Table win=entry.received_msgs; - boolean added=win.add(seqno, msg); // win is guaranteed to be non-null if we get here - num_msgs_received++; - - if(added) { - int len=msg.getLength(); - if(len > 0 && entry.incrementStable(len)) - sendStableMessage(sender, entry.recv_conn_id, win.getHighestDelivered(), win.getHighestReceived()); - } - - // An OOB message is passed up immediately. Later, when remove() is called, we discard it. This affects ordering ! - // http://jira.jboss.com/jira/browse/JGRP-377 - if(msg.isFlagSet(Message.OOB) && added) { - try { - up_prot.up(evt); - } - catch(Throwable t) { - log.error("couldn't deliver OOB message " + msg, t); - } - } - - final AtomicBoolean processing=win.getProcessing(); - if(!processing.compareAndSet(false, true)) { - return; - } - - // Try to remove as many messages as possible and pass them up. - // Prevents concurrent passing up of messages by different threads (http://jira.jboss.com/jira/browse/JGRP-198); - // this is all the more important once we have a concurrent stack (http://jira.jboss.com/jira/browse/JGRP-181), - // where lots of threads can come up to this point concurrently, but only 1 is allowed to pass at a time - // We *can* deliver messages from *different* senders concurrently, e.g. reception of P1, Q1, P2, Q2 can result in - // delivery of P1, Q1, Q2, P2: FIFO (implemented by UNICAST) says messages need to be delivered only in the - // order in which they were sent by their senders - boolean released_processing=false; - try { - while(true) { - List msgs=win.removeMany(processing, true, max_msg_batch_size); // remove my own messages - if(msgs == null || msgs.isEmpty()) { - released_processing=true; - return; - } - - for(Message m: msgs) { - // discard OOB msg: it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-377) - if(m.isFlagSet(Message.OOB)) - continue; - try { - up_prot.up(new Event(Event.MSG, m)); - } - catch(Throwable t) { - log.error("couldn't deliver message " + m, t); - } - } - } - } - finally { - // processing is always set in win.remove(processing) above and never here ! This code is just a - // 2nd line of defense should there be an exception before win.remove(processing) sets processing - if(!released_processing) - processing.set(false); - } - } - - - protected ReceiverEntry getReceiverEntry(Address sender, long seqno, boolean first, short conn_id) { - ReceiverEntry entry=recv_table.get(sender); - if(entry != null && entry.recv_conn_id == conn_id) - return entry; - - recv_table_lock.lock(); - try { - entry=recv_table.get(sender); - if(first) { - if(entry == null) { - entry=getOrCreateReceiverEntry(sender, seqno, conn_id); - } - else { // entry != null && win != null - if(conn_id != entry.recv_conn_id) { - if(log.isTraceEnabled()) - log.trace(local_addr + ": conn_id=" + conn_id + " != " + entry.recv_conn_id + "; resetting receiver window"); - - recv_table.remove(sender); - entry=getOrCreateReceiverEntry(sender, seqno, conn_id); - } - else { - ; - } - } - } - else { // entry == null && win == null OR entry != null && win == null OR entry != null && win != null - if(entry == null || entry.recv_conn_id != conn_id) { - recv_table_lock.unlock(); - sendRequestForFirstSeqno(sender, seqno); // drops the message and returns (see below) - return null; - } - } - return entry; - } - finally { - if(recv_table_lock.isHeldByCurrentThread()) - recv_table_lock.unlock(); - } - } - - - private ReceiverEntry getOrCreateReceiverEntry(Address sender, long seqno, short conn_id) { - Table table=new Table(xmit_table_num_rows, xmit_table_msgs_per_row, seqno-1, - xmit_table_resize_factor, xmit_table_max_compaction_time); - ReceiverEntry entry=new ReceiverEntry(table, conn_id); - ReceiverEntry entry2=recv_table.putIfAbsent(sender, entry); - if(entry2 != null) - return entry2; - if(log.isTraceEnabled()) - log.trace(local_addr + ": created receiver window for " + sender + " at seqno=#" + seqno + " for conn-id=" + conn_id); - return entry; - } - - - private void handleXmitRequest(Address sender, SeqnoList missing) { - if(log.isTraceEnabled()) - log.trace(new StringBuilder().append(local_addr).append(" <-- XMIT(").append(sender). - append(": #").append(missing).append(')')); - - SenderEntry entry=send_table.get(sender); - xmit_reqs_received.addAndGet(missing.size()); - Table win=entry != null? entry.sent_msgs : null; - if(win != null) { - for(long seqno: missing) { - Message msg=win.get(seqno); - if(msg == null) { - if(log.isWarnEnabled() && !local_addr.equals(sender)) { - StringBuilder sb=new StringBuilder(); - sb.append("(requester=").append(sender).append(", local_addr=").append(this.local_addr); - sb.append(") message ").append(sender).append("::").append(seqno); - sb.append(" not found in retransmission table of ").append(sender).append(":\n").append(win); - log.warn(sb.toString()); - } - continue; - } - - down_prot.down(new Event(Event.MSG, msg)); - xmit_rsps_sent.incrementAndGet(); - } - } - } - - - /** - * We need to resend our first message with our conn_id - * @param sender - * @param seqno Resend the non null messages in the range [lowest .. seqno] - */ - private void handleResendingOfFirstMessage(Address sender, long seqno) { - if(log.isTraceEnabled()) - log.trace(local_addr + " <-- SEND_FIRST_SEQNO(" + sender + "," + seqno + ")"); - SenderEntry entry=send_table.get(sender); - Table win=entry != null? entry.sent_msgs : null; - if(win == null) { - if(log.isErrorEnabled()) - log.error(local_addr + ": sender window for " + sender + " not found"); - return; - } - - boolean first_sent=false; - for(long i=win.getLow() +1; i <= seqno; i++) { - Message rsp=win.get(i); - if(rsp == null) - continue; - if(first_sent) { - down_prot.down(new Event(Event.MSG, rsp)); - } - else { - first_sent=true; - // We need to copy the UnicastHeader and put it back into the message because Message.copy() doesn't copy - // the headers and therefore we'd modify the original message in the sender retransmission window - // (https://jira.jboss.org/jira/browse/JGRP-965) - Message copy=rsp.copy(); - Unicast2Header hdr=(Unicast2Header)copy.getHeader(this.id); - Unicast2Header newhdr=hdr.copy(); - newhdr.first=true; - copy.putHeader(this.id, newhdr); - down_prot.down(new Event(Event.MSG, copy)); - } - } - } - - protected void startRetransmitTask() { - if(xmit_task == null || xmit_task.isDone()) - xmit_task=timer.scheduleWithFixedDelay(new RetransmitTask(), 0, xmit_interval, TimeUnit.MILLISECONDS); - } - - protected void stopRetransmitTask() { - if(xmit_task != null) { - xmit_task.cancel(true); - xmit_task=null; - } - } - - - - private synchronized short getNewConnectionId() { - short retval=last_conn_id; - if(last_conn_id >= Short.MAX_VALUE || last_conn_id < 0) - last_conn_id=0; - else - last_conn_id++; - return retval; - } - - private void sendRequestForFirstSeqno(Address dest, long seqno_received) { - Message msg=new Message(dest); - msg.setFlag(Message.OOB); - Unicast2Header hdr=Unicast2Header.createSendFirstSeqnoHeader(seqno_received); - msg.putHeader(this.id, hdr); - if(log.isTraceEnabled()) - log.trace(local_addr + " --> SEND_FIRST_SEQNO(" + dest + "," + seqno_received + ")"); - down_prot.down(new Event(Event.MSG, msg)); - } - - @ManagedOperation(description="Closes connections that have been idle for more than conn_expiry_timeout ms") - public void reapIdleConnections() { - if(conn_expiry_timeout <= 0) - return; - - // remove expired connections from send_table - for(Map.Entry entry: send_table.entrySet()) { - SenderEntry val=entry.getValue(); - long age=val.age(); - if(age >= conn_expiry_timeout) { - removeSendConnection(entry.getKey()); - if(log.isDebugEnabled()) - log.debug(local_addr + ": removed expired connection for " + entry.getKey() + - " (" + age + " ms old) from send_table"); - } - } - - // remove expired connections from recv_table - for(Map.Entry entry: recv_table.entrySet()) { - ReceiverEntry val=entry.getValue(); - long age=val.age(); - if(age >= conn_expiry_timeout) { - removeReceiveConnection(entry.getKey()); - if(log.isDebugEnabled()) - log.debug(local_addr + ": removed expired connection for " + entry.getKey() + - " (" + age + " ms old) from recv_table"); - } - } - } - - - /** - * The following types and fields are serialized: - *
-     * | DATA | seqno | conn_id | first |
-     * | ACK  | seqno |
-     * | SEND_FIRST_SEQNO | seqno |
-     * 
- */ - public static class Unicast2Header extends Header { - public static final byte DATA = 0; - public static final byte XMIT_REQ = 1; - public static final byte SEND_FIRST_SEQNO = 2; - public static final byte STABLE = 3; - - byte type; - long seqno; // DATA and STABLE - long high_seqno; // STABLE - short conn_id; // DATA, STABLE - boolean first; // DATA - - - public Unicast2Header() {} // used for externalization - - public static Unicast2Header createDataHeader(long seqno, short conn_id, boolean first) { - return new Unicast2Header(DATA, seqno, 0L, conn_id, first); - } - - public static Unicast2Header createXmitReqHeader() { - return new Unicast2Header(XMIT_REQ); - } - - public static Unicast2Header createStableHeader(short conn_id, long low, long high) { - if(low > high) - throw new IllegalArgumentException("low (" + low + ") needs to be <= high (" + high + ")"); - Unicast2Header retval=new Unicast2Header(STABLE, low); - retval.high_seqno=high; - retval.conn_id=conn_id; - return retval; - } - - public static Unicast2Header createSendFirstSeqnoHeader(long seqno_received) { - return new Unicast2Header(SEND_FIRST_SEQNO, seqno_received); - } - - private Unicast2Header(byte type) { - this.type=type; - } - - private Unicast2Header(byte type, long seqno) { - this.type=type; - this.seqno=seqno; - } - - private Unicast2Header(byte type, long seqno, long high, short conn_id, boolean first) { - this.type=type; - this.seqno=seqno; - this.high_seqno=high; - this.conn_id=conn_id; - this.first=first; - } - - public byte getType() { - return type; - } - - public long getSeqno() { - return seqno; - } - - public long getHighSeqno() { - return high_seqno; - } - - public short getConnId() { - return conn_id; - } - - - public boolean isFirst() { - return first; - } - - public String toString() { - StringBuilder sb=new StringBuilder(); - sb.append(type2Str(type)).append(", seqno=").append(seqno); - if(conn_id != 0) sb.append(", conn_id=").append(conn_id); - if(first) sb.append(", first"); - return sb.toString(); - } - - public static String type2Str(byte t) { - switch(t) { - case DATA: return "DATA"; - case XMIT_REQ: return "XMIT_REQ"; - case SEND_FIRST_SEQNO: return "SEND_FIRST_SEQNO"; - case STABLE: return "STABLE"; - default: return ""; - } - } - - public final int size() { - int retval=Global.BYTE_SIZE; // type - switch(type) { - case DATA: - retval+=Util.size(seqno) // seqno - + Global.SHORT_SIZE // conn_id - + Global.BYTE_SIZE; // first - break; - case XMIT_REQ: - break; - case STABLE: - retval+=Util.size(seqno, high_seqno) + Global.SHORT_SIZE; // conn_id - break; - case SEND_FIRST_SEQNO: - retval+=Util.size(seqno); - break; - } - return retval; - } - - public Unicast2Header copy() { - return new Unicast2Header(type, seqno, high_seqno, conn_id, first); - } - - - - public void writeTo(DataOutput out) throws Exception { - out.writeByte(type); - switch(type) { - case DATA: - Util.writeLong(seqno, out); - out.writeShort(conn_id); - out.writeBoolean(first); - break; - case XMIT_REQ: - break; - case STABLE: - Util.writeLongSequence(seqno, high_seqno, out); - out.writeShort(conn_id); - break; - case SEND_FIRST_SEQNO: - Util.writeLong(seqno, out); - break; - } - } - - public void readFrom(DataInput in) throws Exception { - type=in.readByte(); - switch(type) { - case DATA: - seqno=Util.readLong(in); - conn_id=in.readShort(); - first=in.readBoolean(); - break; - case XMIT_REQ: - break; - case STABLE: - long[] seqnos=Util.readLongSequence(in); - seqno=seqnos[0]; - high_seqno=seqnos[1]; - conn_id=in.readShort(); - break; - case SEND_FIRST_SEQNO: - seqno=Util.readLong(in); - break; - } - } - } - - - - private final class SenderEntry { - // stores (and retransmits) msgs sent by us to a given peer - Table sent_msgs; - final AtomicLong sent_msgs_seqno=new AtomicLong(DEFAULT_FIRST_SEQNO); // seqno for msgs sent by us - final short send_conn_id; - private final AtomicLong timestamp=new AtomicLong(0); - final Lock lock=new ReentrantLock(); - - public SenderEntry(short send_conn_id) { - this.send_conn_id=send_conn_id; - this.sent_msgs=new Table(xmit_table_num_rows, xmit_table_msgs_per_row, 0, - xmit_table_resize_factor, xmit_table_max_compaction_time); - update(); - } - - - void update() {timestamp.set(System.currentTimeMillis());} - long age() {return System.currentTimeMillis() - timestamp.longValue();} - - public String toString() { - StringBuilder sb=new StringBuilder(); - if(sent_msgs != null) - sb.append(sent_msgs).append(", "); - sb.append("send_conn_id=" + send_conn_id); - sb.append(" (" + age() + " ms old)"); - return sb.toString(); - } - } - - protected final class ReceiverEntry { - private final Table received_msgs; // stores all msgs rcvd by a certain peer in seqno-order - private final short recv_conn_id; - private int received_bytes=0; - private final AtomicLong timestamp=new AtomicLong(0); - private final Lock lock=new ReentrantLock(); - - private long last_highest=-1; - private int num_stable_msgs=0; - - - - public ReceiverEntry(Table received_msgs, short recv_conn_id) { - this.received_msgs=received_msgs; - this.recv_conn_id=recv_conn_id; - update(); - } - - /** Adds len bytes, if max_bytes is exceeded, the value is reset and true returned, else false */ - boolean incrementStable(int len) { - lock.lock(); - try { - if(received_bytes+len >= max_bytes) { - received_bytes=0; - return true; - } - received_bytes+=len; - return false; - } - finally { - lock.unlock(); - } - } - - void reset() { - received_bytes=0; - last_highest=-1; - num_stable_msgs=0; - } - - void update() {timestamp.set(System.currentTimeMillis());} - long age() {return System.currentTimeMillis() - timestamp.longValue();} - - public String toString() { - StringBuilder sb=new StringBuilder(); - if(received_msgs != null) - sb.append(received_msgs).append(", "); - sb.append("recv_conn_id=" + recv_conn_id); - sb.append(" (" + age() + " ms old)"); - return sb.toString(); - } - } - - - protected class ConnectionReaper implements Runnable { - public void run() { - reapIdleConnections(); - } - } - - /** - * Retransmitter task which periodically (every xmit_interval ms) looks at all the retransmit tables and - * sends retransmit request to all members from which we have missing messages - */ - protected class RetransmitTask implements Runnable { - - public void run() { - for(Map.Entry entry: recv_table.entrySet()) { - Address target=entry.getKey(); // target to send retransmit requests to - ReceiverEntry val=entry.getValue(); - Table buf=val != null? val.received_msgs : null; - if(buf != null && buf.getNumMissing() > 0) { - SeqnoList missing=buf.getMissing(); - if(missing != null) - retransmit(missing, target); - } - } - } - } - - - -} \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/pair.info b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/pair.info deleted file mode 100755 index d13a1f1..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#16081/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:16081 -comSha:5b3d862fcdbab64153bb1eb0ca7e7b7ffcb2e1e3 -parentComSha:74c5f042db503f5f035bd6946b2bedd8bbcf02eb -BuggyFilePath:src/org/jgroups/protocols/UNICAST2.java -FixedFilePath:src/org/jgroups/protocols/UNICAST2.java -StartLineNum:1171 -EndLineNum:1171 -repoName:belaban#JGroups \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/comMsg.txt b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/comMsg.txt deleted file mode 100755 index e6dcd87..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -cleanup tests and make the work better on multiple plattforms \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/diff.diff b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/diff.diff deleted file mode 100755 index 32dae67..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/test/java/org/jboss/aesh/console/masking/ConsoleMaskingTest.java b/src/test/java/org/jboss/aesh/console/masking/ConsoleMaskingTest.java -index 0a687744..f6b8fdbe 100644 ---- a/src/test/java/org/jboss/aesh/console/masking/ConsoleMaskingTest.java -+++ b/src/test/java/org/jboss/aesh/console/masking/ConsoleMaskingTest.java -@@ -10,0 +11 @@ import org.jboss.aesh.console.BaseConsoleTest; -+import org.jboss.aesh.console.Config; -@@ -30,2 +30,0 @@ public class ConsoleMaskingTest extends BaseConsoleTest { -- private boolean didFail = false; -- -@@ -40 +39 @@ public class ConsoleMaskingTest extends BaseConsoleTest { -- console.setPrompt(new Prompt("", new Character('\u0000'))); -+ console.setPrompt(new Prompt("", '\u0000')); -@@ -51 +50,2 @@ public class ConsoleMaskingTest extends BaseConsoleTest { -- outputStream.write(("\n").getBytes()); -+ outputStream.write((Config.getLineSeparator()).getBytes()); -+ outputStream.flush(); \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/new/ConsoleMaskingTest.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/new/ConsoleMaskingTest.java deleted file mode 100755 index f6b8fdb..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/new/ConsoleMaskingTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2012 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Eclipse Public License version 1.0, available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.jboss.aesh.console.masking; - -import org.jboss.aesh.console.AeshConsoleCallback; -import org.jboss.aesh.console.BaseConsoleTest; -import org.jboss.aesh.console.Config; -import org.jboss.aesh.console.Console; -import org.jboss.aesh.console.ConsoleOperation; -import org.jboss.aesh.console.Prompt; -import org.jboss.aesh.edit.KeyOperation; -import org.jboss.aesh.edit.actions.Operation; -import org.jboss.aesh.terminal.Key; -import org.junit.Test; - -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; - -import static org.junit.Assert.*; - -/** - * @author Ståle W. Pedersen - */ -public class ConsoleMaskingTest extends BaseConsoleTest { - - @Test - public void masking() throws IOException, InterruptedException { - PipedOutputStream outputStream = new PipedOutputStream(); - PipedInputStream pipedInputStream = new PipedInputStream(outputStream); - - KeyOperation deletePrevChar = new KeyOperation(Key.CTRL_H, Operation.DELETE_PREV_CHAR); - - Console console = getTestConsole(pipedInputStream); - console.setPrompt(new Prompt("", '\u0000')); - console.setConsoleCallback(new AeshConsoleCallback() { - @Override - public int execute(ConsoleOperation output) { - assertEquals("mypasswor", output.getBuffer()); - return 0; - } - }); - console.start(); - outputStream.write(("mypassword").getBytes()); - outputStream.write(deletePrevChar.getFirstValue()); - outputStream.write((Config.getLineSeparator()).getBytes()); - outputStream.flush(); - - Thread.sleep(100); - - console.stop(); - } - -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/old/ConsoleMaskingTest.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/old/ConsoleMaskingTest.java deleted file mode 100755 index 0a68774..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/old/ConsoleMaskingTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2012 Red Hat, Inc. and/or its affiliates. - * - * Licensed under the Eclipse Public License version 1.0, available at - * http://www.eclipse.org/legal/epl-v10.html - */ -package org.jboss.aesh.console.masking; - -import org.jboss.aesh.console.AeshConsoleCallback; -import org.jboss.aesh.console.BaseConsoleTest; -import org.jboss.aesh.console.Console; -import org.jboss.aesh.console.ConsoleOperation; -import org.jboss.aesh.console.Prompt; -import org.jboss.aesh.edit.KeyOperation; -import org.jboss.aesh.edit.actions.Operation; -import org.jboss.aesh.terminal.Key; -import org.junit.Test; - -import java.io.IOException; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; - -import static org.junit.Assert.*; - -/** - * @author Ståle W. Pedersen - */ -public class ConsoleMaskingTest extends BaseConsoleTest { - - private boolean didFail = false; - - @Test - public void masking() throws IOException, InterruptedException { - PipedOutputStream outputStream = new PipedOutputStream(); - PipedInputStream pipedInputStream = new PipedInputStream(outputStream); - - KeyOperation deletePrevChar = new KeyOperation(Key.CTRL_H, Operation.DELETE_PREV_CHAR); - - Console console = getTestConsole(pipedInputStream); - console.setPrompt(new Prompt("", new Character('\u0000'))); - console.setConsoleCallback(new AeshConsoleCallback() { - @Override - public int execute(ConsoleOperation output) { - assertEquals("mypasswor", output.getBuffer()); - return 0; - } - }); - console.start(); - outputStream.write(("mypassword").getBytes()); - outputStream.write(deletePrevChar.getFirstValue()); - outputStream.write(("\n").getBytes()); - - Thread.sleep(100); - - console.stop(); - } - -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/pair.info b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/pair.info deleted file mode 100755 index 9e167c0..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#19961/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:19961 -comSha:95cadf56a8a37b4fb378b838412dbf6d8d871099 -parentComSha:96cf17dd1e360381c9b00490e6dae331f3f9ac29 -BuggyFilePath:src/test/java/org/jboss/aesh/console/masking/ConsoleMaskingTest.java -FixedFilePath:src/test/java/org/jboss/aesh/console/masking/ConsoleMaskingTest.java -StartLineNum:30 -EndLineNum:30 -repoName:aeshell#aesh \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/comMsg.txt b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/comMsg.txt deleted file mode 100755 index e3be327..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/comMsg.txt +++ /dev/null @@ -1,4 +0,0 @@ -removed eclipse warnings, unused fields. Made inner classes static where possible. - - -git-svn-id: http://google-gson.googlecode.com/svn/trunk/gson@1234 2534bb62-2c4b-0410-85e8-b5006b95c4ae \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/diff.diff b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/diff.diff deleted file mode 100755 index 0c36924..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java b/src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java -index c1c9705b..0b95445a 100644 ---- a/src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java -+++ b/src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java -@@ -60,3 +60 @@ public final class CollectionTypeAdapterFactory implements TypeAdapterFactory { -- private final class Adapter extends TypeAdapter> { -- private final Gson context; -- private final Type elementType; -+ private static final class Adapter extends TypeAdapter> { -@@ -69,2 +66,0 @@ public final class CollectionTypeAdapterFactory implements TypeAdapterFactory { -- this.context = context; -- this.elementType = elementType; \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/new/CollectionTypeAdapterFactory.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/new/CollectionTypeAdapterFactory.java deleted file mode 100755 index 0b95445..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/new/CollectionTypeAdapterFactory.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.gson.internal.bind; - -import com.google.gson.Gson; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.internal.$Gson$Types; -import com.google.gson.internal.ConstructorConstructor; -import com.google.gson.internal.ObjectConstructor; -import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.Collection; - -/** - * Adapt a homogeneous collection of objects. - */ -public final class CollectionTypeAdapterFactory implements TypeAdapterFactory { - private final ConstructorConstructor constructorConstructor; - - public CollectionTypeAdapterFactory(ConstructorConstructor constructorConstructor) { - this.constructorConstructor = constructorConstructor; - } - - public TypeAdapter create(Gson gson, TypeToken typeToken) { - Type type = typeToken.getType(); - - Class rawType = typeToken.getRawType(); - if (!Collection.class.isAssignableFrom(rawType)) { - return null; - } - - Type elementType = $Gson$Types.getCollectionElementType(type, rawType); - TypeAdapter elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType)); - ObjectConstructor constructor = constructorConstructor.get(typeToken); - - @SuppressWarnings({"unchecked", "rawtypes"}) // create() doesn't define a type parameter - TypeAdapter result = new Adapter(gson, elementType, elementTypeAdapter, constructor); - return result; - } - - private static final class Adapter extends TypeAdapter> { - private final TypeAdapter elementTypeAdapter; - private final ObjectConstructor> constructor; - - public Adapter(Gson context, Type elementType, - TypeAdapter elementTypeAdapter, - ObjectConstructor> constructor) { - this.elementTypeAdapter = - new TypeAdapterRuntimeTypeWrapper(context, elementTypeAdapter, elementType); - this.constructor = constructor; - } - - public Collection read(JsonReader in) throws IOException { - if (in.peek() == JsonToken.NULL) { - in.nextNull(); - return null; - } - - Collection collection = constructor.construct(); - in.beginArray(); - while (in.hasNext()) { - E instance = elementTypeAdapter.read(in); - collection.add(instance); - } - in.endArray(); - return collection; - } - - public void write(JsonWriter out, Collection collection) throws IOException { - if (collection == null) { - out.nullValue(); - return; - } - - out.beginArray(); - for (E element : collection) { - elementTypeAdapter.write(out, element); - } - out.endArray(); - } - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/old/CollectionTypeAdapterFactory.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/old/CollectionTypeAdapterFactory.java deleted file mode 100755 index c1c9705..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/old/CollectionTypeAdapterFactory.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.google.gson.internal.bind; - -import com.google.gson.Gson; -import com.google.gson.TypeAdapter; -import com.google.gson.TypeAdapterFactory; -import com.google.gson.internal.$Gson$Types; -import com.google.gson.internal.ConstructorConstructor; -import com.google.gson.internal.ObjectConstructor; -import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonToken; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.lang.reflect.Type; -import java.util.Collection; - -/** - * Adapt a homogeneous collection of objects. - */ -public final class CollectionTypeAdapterFactory implements TypeAdapterFactory { - private final ConstructorConstructor constructorConstructor; - - public CollectionTypeAdapterFactory(ConstructorConstructor constructorConstructor) { - this.constructorConstructor = constructorConstructor; - } - - public TypeAdapter create(Gson gson, TypeToken typeToken) { - Type type = typeToken.getType(); - - Class rawType = typeToken.getRawType(); - if (!Collection.class.isAssignableFrom(rawType)) { - return null; - } - - Type elementType = $Gson$Types.getCollectionElementType(type, rawType); - TypeAdapter elementTypeAdapter = gson.getAdapter(TypeToken.get(elementType)); - ObjectConstructor constructor = constructorConstructor.get(typeToken); - - @SuppressWarnings({"unchecked", "rawtypes"}) // create() doesn't define a type parameter - TypeAdapter result = new Adapter(gson, elementType, elementTypeAdapter, constructor); - return result; - } - - private final class Adapter extends TypeAdapter> { - private final Gson context; - private final Type elementType; - private final TypeAdapter elementTypeAdapter; - private final ObjectConstructor> constructor; - - public Adapter(Gson context, Type elementType, - TypeAdapter elementTypeAdapter, - ObjectConstructor> constructor) { - this.context = context; - this.elementType = elementType; - this.elementTypeAdapter = - new TypeAdapterRuntimeTypeWrapper(context, elementTypeAdapter, elementType); - this.constructor = constructor; - } - - public Collection read(JsonReader in) throws IOException { - if (in.peek() == JsonToken.NULL) { - in.nextNull(); - return null; - } - - Collection collection = constructor.construct(); - in.beginArray(); - while (in.hasNext()) { - E instance = elementTypeAdapter.read(in); - collection.add(instance); - } - in.endArray(); - return collection; - } - - public void write(JsonWriter out, Collection collection) throws IOException { - if (collection == null) { - out.nullValue(); - return; - } - - out.beginArray(); - for (E element : collection) { - elementTypeAdapter.write(out, element); - } - out.endArray(); - } - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/pair.info b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/pair.info deleted file mode 100755 index 8684691..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2427/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:2427 -comSha:983fc6412f48ac496cbee8101c5525cb67237dd5 -parentComSha:0e8569a72610885780ffcaa9adfeeee8f9ef2362 -BuggyFilePath:src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java -FixedFilePath:src/main/java/com/google/gson/internal/bind/CollectionTypeAdapterFactory.java -StartLineNum:70 -EndLineNum:70 -repoName:TeamExodus#external_gson \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/comMsg.txt b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/comMsg.txt deleted file mode 100755 index 0e956c6..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -Delete dead code found by coverage - -git-svn-id: http://google-gson.googlecode.com/svn/trunk/gson@988 2534bb62-2c4b-0410-85e8-b5006b95c4ae \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/diff.diff b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/diff.diff deleted file mode 100755 index b7920d7..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/com/google/gson/GsonToMiniGsonTypeAdapterFactory.java b/src/main/java/com/google/gson/GsonToMiniGsonTypeAdapterFactory.java -index 1b700027..086619f2 100644 ---- a/src/main/java/com/google/gson/GsonToMiniGsonTypeAdapterFactory.java -+++ b/src/main/java/com/google/gson/GsonToMiniGsonTypeAdapterFactory.java -@@ -33 +32,0 @@ final class GsonToMiniGsonTypeAdapterFactory implements TypeAdapter.Factory { -- private final boolean serializeNulls; -@@ -37,2 +36 @@ final class GsonToMiniGsonTypeAdapterFactory implements TypeAdapter.Factory { -- ParameterizedTypeHandlerMap> deserializers, -- boolean serializeNulls) { -+ ParameterizedTypeHandlerMap> deserializers) { -@@ -41 +38,0 @@ final class GsonToMiniGsonTypeAdapterFactory implements TypeAdapter.Factory { -- this.serializeNulls = serializeNulls; \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/new/GsonToMiniGsonTypeAdapterFactory.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/new/GsonToMiniGsonTypeAdapterFactory.java deleted file mode 100755 index 086619f..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/new/GsonToMiniGsonTypeAdapterFactory.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.gson; - -import com.google.gson.internal.ParameterizedTypeHandlerMap; -import com.google.gson.internal.Streams; -import com.google.gson.internal.bind.MiniGson; -import com.google.gson.internal.bind.TypeAdapter; -import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.lang.reflect.Type; - -final class GsonToMiniGsonTypeAdapterFactory implements TypeAdapter.Factory { - private final ParameterizedTypeHandlerMap> serializers; - private final ParameterizedTypeHandlerMap> deserializers; - private final JsonDeserializationContext deserializationContext; - private final JsonSerializationContext serializationContext; - - public GsonToMiniGsonTypeAdapterFactory(final Gson gson, - ParameterizedTypeHandlerMap> serializers, - ParameterizedTypeHandlerMap> deserializers) { - this.serializers = serializers; - this.deserializers = deserializers; - - this.deserializationContext = new JsonDeserializationContext() { - public T deserialize(JsonElement json, Type typeOfT) throws JsonParseException { - return gson.fromJson(json, typeOfT); - } - }; - - this.serializationContext = new JsonSerializationContext() { - public JsonElement serialize(Object src) { - return gson.toJsonTree(src); - } - public JsonElement serialize(Object src, Type typeOfSrc) { - return gson.toJsonTree(src, typeOfSrc); - } - }; - } - - public TypeAdapter create(final MiniGson context, final TypeToken typeToken) { - final Type type = typeToken.getType(); - - @SuppressWarnings("unchecked") // guaranteed to match typeOfT - final JsonSerializer serializer - = (JsonSerializer) serializers.getHandlerFor(type, false); - @SuppressWarnings("unchecked") // guaranteed to match typeOfT - final JsonDeserializer deserializer - = (JsonDeserializer) deserializers.getHandlerFor(type, false); - - if (serializer == null && deserializer == null) { - return null; - } - - return new TypeAdapter() { - /** - * The delegate is lazily created because it may not be needed, and - * creating it may fail. - */ - private TypeAdapter delegate; - - @Override public T read(JsonReader reader) throws IOException { - if (deserializer == null) { - return delegate().read(reader); - } - JsonElement value = Streams.parse(reader); - if (value.isJsonNull()) { - return null; - } - return deserializer.deserialize(value, type, deserializationContext); - } - - @Override public void write(JsonWriter writer, T value) throws IOException { - if (serializer == null) { - delegate().write(writer, value); - return; - } - if (value == null) { - writer.nullValue(); - return; - } - JsonElement element = serializer.serialize(value, type, serializationContext); - Streams.write(element, writer); - } - - private TypeAdapter delegate() { - TypeAdapter d = delegate; - return d != null - ? d - : (delegate = context.getNextAdapter(GsonToMiniGsonTypeAdapterFactory.this, typeToken)); - } - }; - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/old/GsonToMiniGsonTypeAdapterFactory.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/old/GsonToMiniGsonTypeAdapterFactory.java deleted file mode 100755 index 1b70002..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/old/GsonToMiniGsonTypeAdapterFactory.java +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright (C) 2011 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.google.gson; - -import com.google.gson.internal.ParameterizedTypeHandlerMap; -import com.google.gson.internal.Streams; -import com.google.gson.internal.bind.MiniGson; -import com.google.gson.internal.bind.TypeAdapter; -import com.google.gson.reflect.TypeToken; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import java.io.IOException; -import java.lang.reflect.Type; - -final class GsonToMiniGsonTypeAdapterFactory implements TypeAdapter.Factory { - private final ParameterizedTypeHandlerMap> serializers; - private final ParameterizedTypeHandlerMap> deserializers; - private final JsonDeserializationContext deserializationContext; - private final JsonSerializationContext serializationContext; - private final boolean serializeNulls; - - public GsonToMiniGsonTypeAdapterFactory(final Gson gson, - ParameterizedTypeHandlerMap> serializers, - ParameterizedTypeHandlerMap> deserializers, - boolean serializeNulls) { - this.serializers = serializers; - this.deserializers = deserializers; - this.serializeNulls = serializeNulls; - - this.deserializationContext = new JsonDeserializationContext() { - public T deserialize(JsonElement json, Type typeOfT) throws JsonParseException { - return gson.fromJson(json, typeOfT); - } - }; - - this.serializationContext = new JsonSerializationContext() { - public JsonElement serialize(Object src) { - return gson.toJsonTree(src); - } - public JsonElement serialize(Object src, Type typeOfSrc) { - return gson.toJsonTree(src, typeOfSrc); - } - }; - } - - public TypeAdapter create(final MiniGson context, final TypeToken typeToken) { - final Type type = typeToken.getType(); - - @SuppressWarnings("unchecked") // guaranteed to match typeOfT - final JsonSerializer serializer - = (JsonSerializer) serializers.getHandlerFor(type, false); - @SuppressWarnings("unchecked") // guaranteed to match typeOfT - final JsonDeserializer deserializer - = (JsonDeserializer) deserializers.getHandlerFor(type, false); - - if (serializer == null && deserializer == null) { - return null; - } - - return new TypeAdapter() { - /** - * The delegate is lazily created because it may not be needed, and - * creating it may fail. - */ - private TypeAdapter delegate; - - @Override public T read(JsonReader reader) throws IOException { - if (deserializer == null) { - return delegate().read(reader); - } - JsonElement value = Streams.parse(reader); - if (value.isJsonNull()) { - return null; - } - return deserializer.deserialize(value, type, deserializationContext); - } - - @Override public void write(JsonWriter writer, T value) throws IOException { - if (serializer == null) { - delegate().write(writer, value); - return; - } - if (value == null) { - writer.nullValue(); - return; - } - JsonElement element = serializer.serialize(value, type, serializationContext); - Streams.write(element, writer); - } - - private TypeAdapter delegate() { - TypeAdapter d = delegate; - return d != null - ? d - : (delegate = context.getNextAdapter(GsonToMiniGsonTypeAdapterFactory.this, typeToken)); - } - }; - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/pair.info b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/pair.info deleted file mode 100755 index befb0b8..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#2462/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:2462 -comSha:e8c4c83e27d714f8e89d3916a439a254b3ce3ccf -parentComSha:979696a0c332f77b54697f923050b1789df8d317 -BuggyFilePath:src/main/java/com/google/gson/GsonToMiniGsonTypeAdapterFactory.java -FixedFilePath:src/main/java/com/google/gson/GsonToMiniGsonTypeAdapterFactory.java -StartLineNum:41 -EndLineNum:41 -repoName:TeamExodus#external_gson \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/comMsg.txt b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/comMsg.txt deleted file mode 100755 index 30f5e54..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Update of the player chunk management to the current state of the v1.7.x branches \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/diff.diff b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/diff.diff deleted file mode 100755 index 8f2b2d9..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/de/minetick/packetbuilder/PacketBuilderThreadPool.java b/src/main/java/de/minetick/packetbuilder/PacketBuilderThreadPool.java -index 3329e831..40ef29b0 100644 ---- a/src/main/java/de/minetick/packetbuilder/PacketBuilderThreadPool.java -+++ b/src/main/java/de/minetick/packetbuilder/PacketBuilderThreadPool.java -@@ -17 +16,0 @@ public class PacketBuilderThreadPool implements Observer { -- private boolean adjustCacheSizes = false; -@@ -75 +74,3 @@ public class PacketBuilderThreadPool implements Observer { -- pool.shutdown(); -+ if(pool != null) { -+ pool.shutdown(); -+ } \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/new/PacketBuilderThreadPool.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/new/PacketBuilderThreadPool.java deleted file mode 100755 index 40ef29b..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/new/PacketBuilderThreadPool.java +++ /dev/null @@ -1,106 +0,0 @@ -package de.minetick.packetbuilder; - -import java.util.ArrayDeque; -import java.util.Observable; -import java.util.Observer; - - -public class PacketBuilderThreadPool implements Observer { - - private boolean active; - private ArrayDeque availableThreads; - private ArrayDeque allThreads; - private ArrayDeque waitingJobs; - private Object jobLock = new Object(); - private static PacketBuilderThreadPool pool; - private static int targetPoolSize; - - public PacketBuilderThreadPool(int poolsize) { - poolsize = Math.max(1, poolsize); - targetPoolSize = poolsize; - this.availableThreads = new ArrayDeque(); - this.allThreads = new ArrayDeque(); - this.waitingJobs = new ArrayDeque(); - for(int i = 0; i < poolsize; i++) { - PacketBuilderThread thread = new PacketBuilderThread(); - thread.addObserver(this); - this.availableThreads.add(thread); - this.allThreads.add(thread); - } - pool = this; - this.active = true; - } - - public static void addJobStatic(PacketBuilderJobInterface job) { - if(pool != null) { - pool.addJob(job); - } - } - - public void addJob(PacketBuilderJobInterface job) { - if(this.active) { - synchronized(this.jobLock) { - if(this.availableThreads.isEmpty()) { - this.waitingJobs.add(job); - } else { - PacketBuilderThread thread = this.availableThreads.poll(); - thread.addJob(job); - } - } - } - } - - @Override - public void update(Observable observable, Object obj) { - if(observable instanceof PacketBuilderThread) { - PacketBuilderThread thread = (PacketBuilderThread)observable; - synchronized(this.jobLock) { - if(this.active && targetPoolSize >= this.allThreads.size()) { - if(!this.waitingJobs.isEmpty()) { - thread.fastAddJob(this.waitingJobs.poll()); - } else { - this.availableThreads.add(thread); - } - } else { - thread.deleteObserver(this); - thread.shutdown(); - this.allThreads.remove(thread); - } - } - } - } - - public static void shutdownStatic() { - if(pool != null) { - pool.shutdown(); - } - } - - private void shutdown() { - this.active = false; - synchronized(this.jobLock) { - for(PacketBuilderThread thread : this.allThreads) { - thread.deleteObserver(this); - thread.shutdown(); - } - this.allThreads.clear(); - this.availableThreads.clear(); - } - } - - public static void adjustPoolSize(int size) { - if(size >= 1 && pool != null) { - targetPoolSize = size; - if(pool.allThreads.size() < targetPoolSize) { - synchronized(pool.jobLock) { - while(pool.allThreads.size() < targetPoolSize) { - PacketBuilderThread thread = new PacketBuilderThread(); - thread.addObserver(pool); - pool.availableThreads.add(thread); - pool.allThreads.add(thread); - } - } - } - } - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/old/PacketBuilderThreadPool.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/old/PacketBuilderThreadPool.java deleted file mode 100755 index 3329e83..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/old/PacketBuilderThreadPool.java +++ /dev/null @@ -1,105 +0,0 @@ -package de.minetick.packetbuilder; - -import java.util.ArrayDeque; -import java.util.Observable; -import java.util.Observer; - - -public class PacketBuilderThreadPool implements Observer { - - private boolean active; - private ArrayDeque availableThreads; - private ArrayDeque allThreads; - private ArrayDeque waitingJobs; - private Object jobLock = new Object(); - private static PacketBuilderThreadPool pool; - private static int targetPoolSize; - private boolean adjustCacheSizes = false; - - public PacketBuilderThreadPool(int poolsize) { - poolsize = Math.max(1, poolsize); - targetPoolSize = poolsize; - this.availableThreads = new ArrayDeque(); - this.allThreads = new ArrayDeque(); - this.waitingJobs = new ArrayDeque(); - for(int i = 0; i < poolsize; i++) { - PacketBuilderThread thread = new PacketBuilderThread(); - thread.addObserver(this); - this.availableThreads.add(thread); - this.allThreads.add(thread); - } - pool = this; - this.active = true; - } - - public static void addJobStatic(PacketBuilderJobInterface job) { - if(pool != null) { - pool.addJob(job); - } - } - - public void addJob(PacketBuilderJobInterface job) { - if(this.active) { - synchronized(this.jobLock) { - if(this.availableThreads.isEmpty()) { - this.waitingJobs.add(job); - } else { - PacketBuilderThread thread = this.availableThreads.poll(); - thread.addJob(job); - } - } - } - } - - @Override - public void update(Observable observable, Object obj) { - if(observable instanceof PacketBuilderThread) { - PacketBuilderThread thread = (PacketBuilderThread)observable; - synchronized(this.jobLock) { - if(this.active && targetPoolSize >= this.allThreads.size()) { - if(!this.waitingJobs.isEmpty()) { - thread.fastAddJob(this.waitingJobs.poll()); - } else { - this.availableThreads.add(thread); - } - } else { - thread.deleteObserver(this); - thread.shutdown(); - this.allThreads.remove(thread); - } - } - } - } - - public static void shutdownStatic() { - pool.shutdown(); - } - - private void shutdown() { - this.active = false; - synchronized(this.jobLock) { - for(PacketBuilderThread thread : this.allThreads) { - thread.deleteObserver(this); - thread.shutdown(); - } - this.allThreads.clear(); - this.availableThreads.clear(); - } - } - - public static void adjustPoolSize(int size) { - if(size >= 1 && pool != null) { - targetPoolSize = size; - if(pool.allThreads.size() < targetPoolSize) { - synchronized(pool.jobLock) { - while(pool.allThreads.size() < targetPoolSize) { - PacketBuilderThread thread = new PacketBuilderThread(); - thread.addObserver(pool); - pool.availableThreads.add(thread); - pool.allThreads.add(thread); - } - } - } - } - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/pair.info b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/pair.info deleted file mode 100755 index 6877a17..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#49422/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:49422 -comSha:5d01a79e681df90876473d6a16cfcbcb2383f52a -parentComSha:422b95deb7065b1d04fe520ba3ab84d8273eae8d -BuggyFilePath:src/main/java/de/minetick/packetbuilder/PacketBuilderThreadPool.java -FixedFilePath:src/main/java/de/minetick/packetbuilder/PacketBuilderThreadPool.java -StartLineNum:17 -EndLineNum:17 -repoName:Poweruser#MinetickMod \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/comMsg.txt b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/comMsg.txt deleted file mode 100755 index 5011b5a..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -added some defaults - -git-svn-id: https://mp4parser.googlecode.com/svn/trunk/isoparser@745 7decde4b-c250-0410-a0da-51896bc88be6 \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/diff.diff b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/diff.diff deleted file mode 100755 index 0a1e261..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/com/googlecode/mp4parser/authoring/TrackMetaData.java b/src/main/java/com/googlecode/mp4parser/authoring/TrackMetaData.java -index 288dc27a..c2623095 100644 ---- a/src/main/java/com/googlecode/mp4parser/authoring/TrackMetaData.java -+++ b/src/main/java/com/googlecode/mp4parser/authoring/TrackMetaData.java -@@ -26,2 +26,2 @@ public class TrackMetaData implements Cloneable { -- private Date modificationTime; -- private Date creationTime; -+ private Date modificationTime = new Date(); -+ private Date creationTime = new Date(); -@@ -33 +32,0 @@ public class TrackMetaData implements Cloneable { -- private double startTime = 0; \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/new/TrackMetaData.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/new/TrackMetaData.java deleted file mode 100755 index c262309..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/new/TrackMetaData.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright 2012 Sebastian Annies, Hamburg - * - * Licensed under the Apache License, Version 2.0 (the License); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.googlecode.mp4parser.authoring; - -import java.util.Date; - -/** - * - */ -public class TrackMetaData implements Cloneable { - private String language; - private long timescale; - private Date modificationTime = new Date(); - private Date creationTime = new Date(); - private double width; - private double height; - private float volume; - private long trackId = 1; // zero is not allowed - private int group = 0; - - - /** - * specifies the front-to-back ordering of video tracks; tracks with lower - * numbers are closer to the viewer. 0 is the normal value, and -1 would be - * in front of track 0, and so on. - */ - int layer; - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public long getTimescale() { - return timescale; - } - - public void setTimescale(long timescale) { - this.timescale = timescale; - } - - public Date getModificationTime() { - return modificationTime; - } - - public void setModificationTime(Date modificationTime) { - this.modificationTime = modificationTime; - } - - public Date getCreationTime() { - return creationTime; - } - - public void setCreationTime(Date creationTime) { - this.creationTime = creationTime; - } - - public double getWidth() { - return width; - } - - public void setWidth(double width) { - this.width = width; - } - - public double getHeight() { - return height; - } - - public void setHeight(double height) { - this.height = height; - } - - public long getTrackId() { - return trackId; - } - - public void setTrackId(long trackId) { - this.trackId = trackId; - } - - public int getLayer() { - return layer; - } - - public void setLayer(int layer) { - this.layer = layer; - } - - public float getVolume() { - return volume; - } - - public void setVolume(float volume) { - this.volume = volume; - } - - public int getGroup() { - return group; - } - - public void setGroup(int group) { - this.group = group; - } - - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - return null; - } - } - -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/old/TrackMetaData.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/old/TrackMetaData.java deleted file mode 100755 index 288dc27..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/old/TrackMetaData.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2012 Sebastian Annies, Hamburg - * - * Licensed under the Apache License, Version 2.0 (the License); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an AS IS BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.googlecode.mp4parser.authoring; - -import java.util.Date; - -/** - * - */ -public class TrackMetaData implements Cloneable { - private String language; - private long timescale; - private Date modificationTime; - private Date creationTime; - private double width; - private double height; - private float volume; - private long trackId = 1; // zero is not allowed - private int group = 0; - private double startTime = 0; - - - /** - * specifies the front-to-back ordering of video tracks; tracks with lower - * numbers are closer to the viewer. 0 is the normal value, and -1 would be - * in front of track 0, and so on. - */ - int layer; - - public String getLanguage() { - return language; - } - - public void setLanguage(String language) { - this.language = language; - } - - public long getTimescale() { - return timescale; - } - - public void setTimescale(long timescale) { - this.timescale = timescale; - } - - public Date getModificationTime() { - return modificationTime; - } - - public void setModificationTime(Date modificationTime) { - this.modificationTime = modificationTime; - } - - public Date getCreationTime() { - return creationTime; - } - - public void setCreationTime(Date creationTime) { - this.creationTime = creationTime; - } - - public double getWidth() { - return width; - } - - public void setWidth(double width) { - this.width = width; - } - - public double getHeight() { - return height; - } - - public void setHeight(double height) { - this.height = height; - } - - public long getTrackId() { - return trackId; - } - - public void setTrackId(long trackId) { - this.trackId = trackId; - } - - public int getLayer() { - return layer; - } - - public void setLayer(int layer) { - this.layer = layer; - } - - public float getVolume() { - return volume; - } - - public void setVolume(float volume) { - this.volume = volume; - } - - public int getGroup() { - return group; - } - - public void setGroup(int group) { - this.group = group; - } - - public Object clone() { - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - return null; - } - } - -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/pair.info b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/pair.info deleted file mode 100755 index 70d5092..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#67135/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:67135 -comSha:537e085c89a4391ea54b7cd2a530364e5a5297c3 -parentComSha:11e638dac1efe7635697e51b8ccc582bbb5f31b9 -BuggyFilePath:src/main/java/com/googlecode/mp4parser/authoring/TrackMetaData.java -FixedFilePath:src/main/java/com/googlecode/mp4parser/authoring/TrackMetaData.java -StartLineNum:33 -EndLineNum:33 -repoName:sannies#mp4parser \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/comMsg.txt b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/comMsg.txt deleted file mode 100755 index b74afd0..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixed some major int vs. long bugs in GraphStorage. thanks to findbugs \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/diff.diff b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/diff.diff deleted file mode 100755 index 9ed59fc..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/com/graphhopper/storage/Location2IDPreciseIndex.java b/src/main/java/com/graphhopper/storage/Location2IDPreciseIndex.java -index 9d519ba3d..640fb60c7 100644 ---- a/src/main/java/com/graphhopper/storage/Location2IDPreciseIndex.java -+++ b/src/main/java/com/graphhopper/storage/Location2IDPreciseIndex.java -@@ -25,0 +26 @@ import com.graphhopper.util.EdgeIterator; -+import com.graphhopper.util.NumHelper; -@@ -52 +52,0 @@ public class Location2IDPreciseIndex implements Location2IDIndex { -- private Logger logger = LoggerFactory.getLogger(getClass()); -@@ -199 +199,2 @@ public class Location2IDPreciseIndex implements Location2IDIndex { -- if (tryLon == tmpLon && tryLat == tmpLat || tryLon == connLon && tryLat == connLat) -+ if (NumHelper.equals(tryLon, tmpLon) && NumHelper.equals(tryLat, tmpLat) -+ || NumHelper.equals(tryLon, connLon) && NumHelper.equals(tryLat, connLat)) \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/new/Location2IDPreciseIndex.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/new/Location2IDPreciseIndex.java deleted file mode 100755 index 640fb60..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/new/Location2IDPreciseIndex.java +++ /dev/null @@ -1,410 +0,0 @@ -/* - * Copyright 2012 Peter Karich - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.graphhopper.storage; - -import com.graphhopper.coll.MyBitSet; -import com.graphhopper.coll.MyBitSetImpl; -import com.graphhopper.coll.MyTBitSet; -import com.graphhopper.geohash.KeyAlgo; -import com.graphhopper.geohash.LinearKeyAlgo; -import com.graphhopper.util.DistanceCalc; -import com.graphhopper.util.DistanceCosProjection; -import com.graphhopper.util.EdgeIterator; -import com.graphhopper.util.NumHelper; -import com.graphhopper.util.StopWatch; -import com.graphhopper.util.XFirstSearch; -import com.graphhopper.util.shapes.BBox; -import gnu.trove.list.array.TIntArrayList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Faster and more precise index compared to Location2IDQuadtree. - * - * 1. use an array organized as quadtree. I.e. you can devide your area into tiles, and per tile you - * have an array entry. - * - * TODO 1 Omit this for now to make querying faster and implementation simpler: 2. now in a - * preprocessing step you need to find out which subgraphs are necessary to reach all nodes in one - * tiles. - * - * 3. querying on point A=(lat,lon) converting this to the tile number. Then you'll get all - * necessary subgraphs. Now you'll need to calculate nearest neighbor of the nodes/edges to your - * point A using euclidean geometry (which should be fine as long as they are not too far away which - * is the case for nearest neighbor). - * - * @author Peter Karich - */ -public class Location2IDPreciseIndex implements Location2IDIndex { - - private static final String LIST_NAME = "loc2idIndex"; - private ListOfArrays index; - private Graph g; - private DistanceCalc calc = new DistanceCalc(); - private KeyAlgo algo; - private double latWidth, lonWidth; - private int latSizeI, lonSizeI; - private boolean calcEdgeDistance = true; - - public Location2IDPreciseIndex(Graph g, Directory dir) { - this.g = g; - index = new ListOfArrays(dir, LIST_NAME); - } - - /** - * Loads the index from disc if exists. Make sure you are using the identical graph which was - * used while flusing this index. - * - * @return if loading from file was successfully. - */ - public boolean loadExisting() { - if (index.loadExisting()) { - latSizeI = index.getHeader(0); - lonSizeI = index.getHeader(1); - calcEdgeDistance = index.getHeader(2) == 1; - int checksum = index.getHeader(3); - if (checksum != g.getNodes()) - throw new IllegalStateException("index was created from a different graph with " - + checksum + ". Current nodes:" + g.getNodes()); - prepareAlgo(); - return true; - } - return false; - } - - /** - * Applies only if called before prepareIndex - */ - public Location2IDIndex setCalcEdgeDistance(boolean calcEdgeDist) { - calcEdgeDistance = calcEdgeDist; - return this; - } - - @Override - public Location2IDIndex setPrecision(boolean approxDist) { - if (approxDist) - calc = new DistanceCosProjection(); - else - calc = new DistanceCalc(); - return this; - } - - DistanceCalc getCalc() { - return calc; - } - - public InMemConstructionIndex prepareInMemoryIndex(int capacity) { - prepareBounds(capacity); - prepareAlgo(); - InMemConstructionIndex hi = new InMemConstructionIndex(); - hi.initBuffer(latSizeI, lonSizeI); - hi.initIndex(); - hi.compact(); - return hi; - } - - @Override - public Location2IDIndex prepareIndex(int capacity) { - InMemConstructionIndex hi = prepareInMemoryIndex(capacity); - index.createNew(latSizeI * lonSizeI); - hi.fill(index); - hi.initEmptySlots(index); - return this; - } - - private void prepareBounds(int size) { - latSizeI = lonSizeI = (int) Math.sqrt(size); - - // Same number of entries for x and y otherwise we would need an adapted spatialkey algo. - // Accordingly the width of a tile is different for x and y! - if (latSizeI * lonSizeI < size) - lonSizeI++; - } - - protected KeyAlgo createKeyAlgo(int latS, int lonS) { - return new LinearKeyAlgo(latS, lonS); - } - - private void prepareAlgo() { - BBox b = g.getBounds(); - algo = createKeyAlgo(latSizeI, lonSizeI).setInitialBounds(b.minLon, b.maxLon, b.minLat, b.maxLat); - latWidth = (b.maxLat - b.minLat) / latSizeI; - lonWidth = (b.maxLon - b.minLon) / lonSizeI; - } - - public class InMemConstructionIndex { - - private TIntArrayList[] inMemIndex; - - void initBuffer(int latSizeI, int lonSizeI) { - inMemIndex = new TIntArrayList[latSizeI * lonSizeI]; - } - StopWatch sw = new StopWatch(); - - void initIndex() { - int nodes = g.getNodes(); - MyBitSet alreadyDone = new MyBitSetImpl(nodes); - int added = 0; - StopWatch swWhile = new StopWatch(); - for (int node = 0; node < nodes; node++) { - alreadyDone.add(node); - double lat = g.getLatitude(node); - double lon = g.getLongitude(node); - added++; - add((int) algo.encode(lat, lon), node); - - if (calcEdgeDistance) { - swWhile.start(); - EdgeIterator iter = g.getOutgoing(node); - while (iter.next()) { - int connNode = iter.node(); - if (alreadyDone.contains(connNode)) - continue; - - double connLat = g.getLatitude(connNode); - double connLon = g.getLongitude(connNode); - // already done in main loop: add((int) algo.encode(connLat, connLon), connNode); - - double tmpLat = lat; - double tmpLon = lon; - if (connLat < lat) { - double tmp = tmpLat; - tmpLat = connLat; - connLat = tmp; - } - - if (connLon < lon) { - double tmp = tmpLon; - tmpLon = connLon; - connLon = tmp; - } - - // add edge to all possible entries - // TODO use bresenhamLine - for (double tryLat = tmpLat; tryLat < connLat + latWidth; tryLat += latWidth) { - for (double tryLon = tmpLon; tryLon < connLon + lonWidth; tryLon += lonWidth) { - if (NumHelper.equals(tryLon, tmpLon) && NumHelper.equals(tryLat, tmpLat) - || NumHelper.equals(tryLon, connLon) && NumHelper.equals(tryLat, connLat)) - continue; - added++; - add((int) algo.encode(tryLat, tryLon), connNode); - } - } - } - swWhile.stop(); - } -// if (added % 100000 == 0) -// logger.info("node:" + node + ", added:" + added + " add:" + sw.getSeconds() + ", while:" + swWhile.getSeconds()); - } - } - - void add(int key, int node) { - sw.start(); - if (inMemIndex[key] == null) - inMemIndex[key] = new TIntArrayList(30); - if (!inMemIndex[key].contains(node)) - inMemIndex[key].add(node); - sw.stop(); - } - - void compact() { - // TODO save a more memory: remove all nodes which can be reached from other nodes within - // the tile width <=> only one entry per subgraph. query needs to be adapted to search - // until it leaves the current tile - - // save memory - int sum = 0; - int max = 0; - int counter = 0; - for (int i = 0; i < inMemIndex.length; i++) { - if (inMemIndex[i] != null) { - inMemIndex[i].trimToSize(); - counter++; - sum += inMemIndex[i].size(); - if (max < inMemIndex[i].size()) - max = inMemIndex[i].size(); - } - } - - // bavaria (full init): max:3327, mean:320 - // System.out.println("max:" + max + ", mean:" + (float) sum / counter); - } - - void initEmptySlots(ListOfArrays la) { - // Here we don't need the precision of edge distance which will make it too slow. - // Also just use just the reference of the found entry to save space - int len = inMemIndex.length; - TIntArrayList[] indexCopy = new TIntArrayList[len]; - int initializedCounter = 0; - while (initializedCounter < len) { - initializedCounter = 0; - System.arraycopy(inMemIndex, 0, indexCopy, 0, len); - - // fan out initialized entries - for (int i = 0; i < len; i++) { - if (indexCopy[i] != null) { - // check change "initialized to empty" - if ((i + 1) % lonSizeI != 0 && indexCopy[i + 1] == null) { - inMemIndex[i + 1] = indexCopy[i]; - la.setSameReference(i + 1, i); - } else if (i + lonSizeI < len && indexCopy[i + lonSizeI] == null) { - inMemIndex[i + lonSizeI] = indexCopy[i]; - la.setSameReference(i + lonSizeI, i); - } - } else { - // check change "empty to initialized" - if ((i + 1) % lonSizeI != 0 && indexCopy[i + 1] != null) { - inMemIndex[i] = indexCopy[i + 1]; - la.setSameReference(i, i + 1); - } else if (i + lonSizeI < len && indexCopy[i + lonSizeI] != null) { - inMemIndex[i] = indexCopy[i + lonSizeI]; - la.setSameReference(i, i + lonSizeI); - } - } - - if (inMemIndex[i] != null) - initializedCounter++; - } - - if (initializedCounter == 0) - throw new IllegalStateException("at least one entry has to be != null, which should have happened in initIndex"); - } - } - - void fill(ListOfArrays la) { - for (int i = 0; i < inMemIndex.length; i++) { - if (inMemIndex[i] != null) - la.set(i, inMemIndex[i]); - } - } - - public int getLength() { - return inMemIndex.length; - } - - public TIntArrayList getNodes(int tileNumber) { - return inMemIndex[tileNumber]; - } - } - - @Override - public int findID(final double lat, final double lon) { - long key = algo.encode(lat, lon); - IntIterator iter = index.getIterator((int) key); - if (!iter.next()) - throw new IllegalStateException("shouldn't happen as all keys should have at least one associated id"); - - int node = iter.value(); - double mainLat = g.getLatitude(node); - double mainLon = g.getLongitude(node); - final WeightedNode closestNode = new WeightedNode(node, calc.calcNormalizedDist(lat, lon, mainLat, mainLon)); - final MyBitSet bs = new MyTBitSet(); - while (true) { - bs.clear(); - // traverse graph starting at node - new XFirstSearch() { - @Override protected MyBitSet createBitSet(int size) { - return bs; - } - double currLat; - double currLon; - int currNode; - double currDist; - boolean goFurther = true; - - @Override - protected boolean goFurther(int nodeId) { - currLat = g.getLatitude(nodeId); - currLon = g.getLongitude(nodeId); - currNode = nodeId; - - currDist = calc.calcNormalizedDist(currLat, currLon, lat, lon); - if (currDist < closestNode.weight) { - closestNode.weight = currDist; - closestNode.node = currNode; - } - - return goFurther; - } - - @Override - protected boolean checkConnected(int connectNode) { - goFurther = false; - double connLat = g.getLatitude(connectNode); - double connLon = g.getLongitude(connectNode); - - // while traversing check distance of lat,lon to currNode and to the whole currEdge - double connectDist = calc.calcNormalizedDist(connLat, connLon, lat, lon); - double d = connectDist; - int tmpNode = connectNode; - if (calcEdgeDistance && calc.validEdgeDistance(lat, lon, currLat, currLon, connLat, connLon)) { - d = calc.calcNormalizedEdgeDistance(lat, lon, currLat, currLon, connLat, connLon); - if (currDist < connectDist) - tmpNode = currNode; - } - - if (d < closestNode.weight) { - closestNode.weight = d; - closestNode.node = tmpNode; - } - return true; - } - }.start(g, node, false); - if (!iter.next()) - break; - - node = iter.value(); - } - // logger.info("nodes:" + len + " key:" + key + " lat:" + lat + ",lon:" + lon); - return closestNode.node; - } - - // http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm - // or even better: http://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm - void bresenhamLine(double x0, double y0, double x1, double y1) { - double dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1; - double dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1; - double err = (dx > dy ? dx : -dy) / 2; - - while (true) { - // setPixel(x0, y0); - if (x0 == x1 && y0 == y1) - break; - double e2 = err; - if (e2 > -dx) { - err -= dy; - x0 += sx; - } - if (e2 < dy) { - err += dx; - y0 += sy; - } - } - } - - public void flush() { - index.setHeader(0, latSizeI); - index.setHeader(1, lonSizeI); - index.setHeader(2, calcEdgeDistance ? 1 : 0); - index.setHeader(3, g.getNodes()); - index.flush(); - } - - @Override - public float calcMemInMB() { - return (float) index.capacity() / (1 << 20); - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/old/Location2IDPreciseIndex.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/old/Location2IDPreciseIndex.java deleted file mode 100755 index 9d519ba..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/old/Location2IDPreciseIndex.java +++ /dev/null @@ -1,409 +0,0 @@ -/* - * Copyright 2012 Peter Karich - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.graphhopper.storage; - -import com.graphhopper.coll.MyBitSet; -import com.graphhopper.coll.MyBitSetImpl; -import com.graphhopper.coll.MyTBitSet; -import com.graphhopper.geohash.KeyAlgo; -import com.graphhopper.geohash.LinearKeyAlgo; -import com.graphhopper.util.DistanceCalc; -import com.graphhopper.util.DistanceCosProjection; -import com.graphhopper.util.EdgeIterator; -import com.graphhopper.util.StopWatch; -import com.graphhopper.util.XFirstSearch; -import com.graphhopper.util.shapes.BBox; -import gnu.trove.list.array.TIntArrayList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Faster and more precise index compared to Location2IDQuadtree. - * - * 1. use an array organized as quadtree. I.e. you can devide your area into tiles, and per tile you - * have an array entry. - * - * TODO 1 Omit this for now to make querying faster and implementation simpler: 2. now in a - * preprocessing step you need to find out which subgraphs are necessary to reach all nodes in one - * tiles. - * - * 3. querying on point A=(lat,lon) converting this to the tile number. Then you'll get all - * necessary subgraphs. Now you'll need to calculate nearest neighbor of the nodes/edges to your - * point A using euclidean geometry (which should be fine as long as they are not too far away which - * is the case for nearest neighbor). - * - * @author Peter Karich - */ -public class Location2IDPreciseIndex implements Location2IDIndex { - - private Logger logger = LoggerFactory.getLogger(getClass()); - private static final String LIST_NAME = "loc2idIndex"; - private ListOfArrays index; - private Graph g; - private DistanceCalc calc = new DistanceCalc(); - private KeyAlgo algo; - private double latWidth, lonWidth; - private int latSizeI, lonSizeI; - private boolean calcEdgeDistance = true; - - public Location2IDPreciseIndex(Graph g, Directory dir) { - this.g = g; - index = new ListOfArrays(dir, LIST_NAME); - } - - /** - * Loads the index from disc if exists. Make sure you are using the identical graph which was - * used while flusing this index. - * - * @return if loading from file was successfully. - */ - public boolean loadExisting() { - if (index.loadExisting()) { - latSizeI = index.getHeader(0); - lonSizeI = index.getHeader(1); - calcEdgeDistance = index.getHeader(2) == 1; - int checksum = index.getHeader(3); - if (checksum != g.getNodes()) - throw new IllegalStateException("index was created from a different graph with " - + checksum + ". Current nodes:" + g.getNodes()); - prepareAlgo(); - return true; - } - return false; - } - - /** - * Applies only if called before prepareIndex - */ - public Location2IDIndex setCalcEdgeDistance(boolean calcEdgeDist) { - calcEdgeDistance = calcEdgeDist; - return this; - } - - @Override - public Location2IDIndex setPrecision(boolean approxDist) { - if (approxDist) - calc = new DistanceCosProjection(); - else - calc = new DistanceCalc(); - return this; - } - - DistanceCalc getCalc() { - return calc; - } - - public InMemConstructionIndex prepareInMemoryIndex(int capacity) { - prepareBounds(capacity); - prepareAlgo(); - InMemConstructionIndex hi = new InMemConstructionIndex(); - hi.initBuffer(latSizeI, lonSizeI); - hi.initIndex(); - hi.compact(); - return hi; - } - - @Override - public Location2IDIndex prepareIndex(int capacity) { - InMemConstructionIndex hi = prepareInMemoryIndex(capacity); - index.createNew(latSizeI * lonSizeI); - hi.fill(index); - hi.initEmptySlots(index); - return this; - } - - private void prepareBounds(int size) { - latSizeI = lonSizeI = (int) Math.sqrt(size); - - // Same number of entries for x and y otherwise we would need an adapted spatialkey algo. - // Accordingly the width of a tile is different for x and y! - if (latSizeI * lonSizeI < size) - lonSizeI++; - } - - protected KeyAlgo createKeyAlgo(int latS, int lonS) { - return new LinearKeyAlgo(latS, lonS); - } - - private void prepareAlgo() { - BBox b = g.getBounds(); - algo = createKeyAlgo(latSizeI, lonSizeI).setInitialBounds(b.minLon, b.maxLon, b.minLat, b.maxLat); - latWidth = (b.maxLat - b.minLat) / latSizeI; - lonWidth = (b.maxLon - b.minLon) / lonSizeI; - } - - public class InMemConstructionIndex { - - private TIntArrayList[] inMemIndex; - - void initBuffer(int latSizeI, int lonSizeI) { - inMemIndex = new TIntArrayList[latSizeI * lonSizeI]; - } - StopWatch sw = new StopWatch(); - - void initIndex() { - int nodes = g.getNodes(); - MyBitSet alreadyDone = new MyBitSetImpl(nodes); - int added = 0; - StopWatch swWhile = new StopWatch(); - for (int node = 0; node < nodes; node++) { - alreadyDone.add(node); - double lat = g.getLatitude(node); - double lon = g.getLongitude(node); - added++; - add((int) algo.encode(lat, lon), node); - - if (calcEdgeDistance) { - swWhile.start(); - EdgeIterator iter = g.getOutgoing(node); - while (iter.next()) { - int connNode = iter.node(); - if (alreadyDone.contains(connNode)) - continue; - - double connLat = g.getLatitude(connNode); - double connLon = g.getLongitude(connNode); - // already done in main loop: add((int) algo.encode(connLat, connLon), connNode); - - double tmpLat = lat; - double tmpLon = lon; - if (connLat < lat) { - double tmp = tmpLat; - tmpLat = connLat; - connLat = tmp; - } - - if (connLon < lon) { - double tmp = tmpLon; - tmpLon = connLon; - connLon = tmp; - } - - // add edge to all possible entries - // TODO use bresenhamLine - for (double tryLat = tmpLat; tryLat < connLat + latWidth; tryLat += latWidth) { - for (double tryLon = tmpLon; tryLon < connLon + lonWidth; tryLon += lonWidth) { - if (tryLon == tmpLon && tryLat == tmpLat || tryLon == connLon && tryLat == connLat) - continue; - added++; - add((int) algo.encode(tryLat, tryLon), connNode); - } - } - } - swWhile.stop(); - } -// if (added % 100000 == 0) -// logger.info("node:" + node + ", added:" + added + " add:" + sw.getSeconds() + ", while:" + swWhile.getSeconds()); - } - } - - void add(int key, int node) { - sw.start(); - if (inMemIndex[key] == null) - inMemIndex[key] = new TIntArrayList(30); - if (!inMemIndex[key].contains(node)) - inMemIndex[key].add(node); - sw.stop(); - } - - void compact() { - // TODO save a more memory: remove all nodes which can be reached from other nodes within - // the tile width <=> only one entry per subgraph. query needs to be adapted to search - // until it leaves the current tile - - // save memory - int sum = 0; - int max = 0; - int counter = 0; - for (int i = 0; i < inMemIndex.length; i++) { - if (inMemIndex[i] != null) { - inMemIndex[i].trimToSize(); - counter++; - sum += inMemIndex[i].size(); - if (max < inMemIndex[i].size()) - max = inMemIndex[i].size(); - } - } - - // bavaria (full init): max:3327, mean:320 - // System.out.println("max:" + max + ", mean:" + (float) sum / counter); - } - - void initEmptySlots(ListOfArrays la) { - // Here we don't need the precision of edge distance which will make it too slow. - // Also just use just the reference of the found entry to save space - int len = inMemIndex.length; - TIntArrayList[] indexCopy = new TIntArrayList[len]; - int initializedCounter = 0; - while (initializedCounter < len) { - initializedCounter = 0; - System.arraycopy(inMemIndex, 0, indexCopy, 0, len); - - // fan out initialized entries - for (int i = 0; i < len; i++) { - if (indexCopy[i] != null) { - // check change "initialized to empty" - if ((i + 1) % lonSizeI != 0 && indexCopy[i + 1] == null) { - inMemIndex[i + 1] = indexCopy[i]; - la.setSameReference(i + 1, i); - } else if (i + lonSizeI < len && indexCopy[i + lonSizeI] == null) { - inMemIndex[i + lonSizeI] = indexCopy[i]; - la.setSameReference(i + lonSizeI, i); - } - } else { - // check change "empty to initialized" - if ((i + 1) % lonSizeI != 0 && indexCopy[i + 1] != null) { - inMemIndex[i] = indexCopy[i + 1]; - la.setSameReference(i, i + 1); - } else if (i + lonSizeI < len && indexCopy[i + lonSizeI] != null) { - inMemIndex[i] = indexCopy[i + lonSizeI]; - la.setSameReference(i, i + lonSizeI); - } - } - - if (inMemIndex[i] != null) - initializedCounter++; - } - - if (initializedCounter == 0) - throw new IllegalStateException("at least one entry has to be != null, which should have happened in initIndex"); - } - } - - void fill(ListOfArrays la) { - for (int i = 0; i < inMemIndex.length; i++) { - if (inMemIndex[i] != null) - la.set(i, inMemIndex[i]); - } - } - - public int getLength() { - return inMemIndex.length; - } - - public TIntArrayList getNodes(int tileNumber) { - return inMemIndex[tileNumber]; - } - } - - @Override - public int findID(final double lat, final double lon) { - long key = algo.encode(lat, lon); - IntIterator iter = index.getIterator((int) key); - if (!iter.next()) - throw new IllegalStateException("shouldn't happen as all keys should have at least one associated id"); - - int node = iter.value(); - double mainLat = g.getLatitude(node); - double mainLon = g.getLongitude(node); - final WeightedNode closestNode = new WeightedNode(node, calc.calcNormalizedDist(lat, lon, mainLat, mainLon)); - final MyBitSet bs = new MyTBitSet(); - while (true) { - bs.clear(); - // traverse graph starting at node - new XFirstSearch() { - @Override protected MyBitSet createBitSet(int size) { - return bs; - } - double currLat; - double currLon; - int currNode; - double currDist; - boolean goFurther = true; - - @Override - protected boolean goFurther(int nodeId) { - currLat = g.getLatitude(nodeId); - currLon = g.getLongitude(nodeId); - currNode = nodeId; - - currDist = calc.calcNormalizedDist(currLat, currLon, lat, lon); - if (currDist < closestNode.weight) { - closestNode.weight = currDist; - closestNode.node = currNode; - } - - return goFurther; - } - - @Override - protected boolean checkConnected(int connectNode) { - goFurther = false; - double connLat = g.getLatitude(connectNode); - double connLon = g.getLongitude(connectNode); - - // while traversing check distance of lat,lon to currNode and to the whole currEdge - double connectDist = calc.calcNormalizedDist(connLat, connLon, lat, lon); - double d = connectDist; - int tmpNode = connectNode; - if (calcEdgeDistance && calc.validEdgeDistance(lat, lon, currLat, currLon, connLat, connLon)) { - d = calc.calcNormalizedEdgeDistance(lat, lon, currLat, currLon, connLat, connLon); - if (currDist < connectDist) - tmpNode = currNode; - } - - if (d < closestNode.weight) { - closestNode.weight = d; - closestNode.node = tmpNode; - } - return true; - } - }.start(g, node, false); - if (!iter.next()) - break; - - node = iter.value(); - } - // logger.info("nodes:" + len + " key:" + key + " lat:" + lat + ",lon:" + lon); - return closestNode.node; - } - - // http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm - // or even better: http://en.wikipedia.org/wiki/Xiaolin_Wu%27s_line_algorithm - void bresenhamLine(double x0, double y0, double x1, double y1) { - double dx = Math.abs(x1 - x0), sx = x0 < x1 ? 1 : -1; - double dy = Math.abs(y1 - y0), sy = y0 < y1 ? 1 : -1; - double err = (dx > dy ? dx : -dy) / 2; - - while (true) { - // setPixel(x0, y0); - if (x0 == x1 && y0 == y1) - break; - double e2 = err; - if (e2 > -dx) { - err -= dy; - x0 += sx; - } - if (e2 < dy) { - err += dx; - y0 += sy; - } - } - } - - public void flush() { - index.setHeader(0, latSizeI); - index.setHeader(1, lonSizeI); - index.setHeader(2, calcEdgeDistance ? 1 : 0); - index.setHeader(3, g.getNodes()); - index.flush(); - } - - @Override - public float calcMemInMB() { - return (float) index.capacity() / (1 << 20); - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/pair.info b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/pair.info deleted file mode 100755 index 6023c0f..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77856/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:77856 -comSha:a2090c9029f14ae72fb37f0921cd29245bcb45c8 -parentComSha:3200cb32b231c905d172414ad6093ad744119842 -BuggyFilePath:src/main/java/com/graphhopper/storage/Location2IDPreciseIndex.java -FixedFilePath:src/main/java/com/graphhopper/storage/Location2IDPreciseIndex.java -StartLineNum:52 -EndLineNum:52 -repoName:graphhopper#graphhopper \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/comMsg.txt b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/comMsg.txt deleted file mode 100755 index 141f449..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -algos: more consistent naming \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/diff.diff b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/diff.diff deleted file mode 100755 index ff7a8f9..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/core/src/main/java/com/graphhopper/GraphHopper.java b/core/src/main/java/com/graphhopper/GraphHopper.java -index 384134d0c..62374a133 100644 ---- a/core/src/main/java/com/graphhopper/GraphHopper.java -+++ b/core/src/main/java/com/graphhopper/GraphHopper.java -@@ -40 +39,0 @@ import java.util.concurrent.atomic.AtomicLong; -- -@@ -65 +63,0 @@ public class GraphHopper implements GraphHopperAPI -- private boolean turnCosts = false; -@@ -168,0 +167,5 @@ public class GraphHopper implements GraphHopperAPI -+ public TraversalMode getTraversalMode() -+ { -+ return traversalMode; -+ } -+ \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/new/GraphHopper.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/new/GraphHopper.java deleted file mode 100755 index 62374a1..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/new/GraphHopper.java +++ /dev/null @@ -1,1079 +0,0 @@ -/* - * Licensed to GraphHopper and Peter Karich under one or more contributor - * license agreements. See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - * - * GraphHopper 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 com.graphhopper; - -import com.graphhopper.reader.DataReader; -import com.graphhopper.reader.OSMReader; -import com.graphhopper.reader.dem.CGIARProvider; -import com.graphhopper.reader.dem.ElevationProvider; -import com.graphhopper.reader.dem.SRTMProvider; -import com.graphhopper.routing.Path; -import com.graphhopper.routing.RoutingAlgorithm; -import com.graphhopper.routing.ch.PrepareContractionHierarchies; -import com.graphhopper.routing.util.*; -import com.graphhopper.storage.*; -import com.graphhopper.storage.index.*; -import com.graphhopper.util.*; -import com.graphhopper.util.shapes.GHPoint; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.atomic.AtomicLong; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Easy to use access point to configure import and (offline) routing. - *

- * @see GraphHopperAPI - * @author Peter Karich - */ -public class GraphHopper implements GraphHopperAPI -{ - private final Logger logger = LoggerFactory.getLogger(getClass()); - // for graph: - private GraphStorage graph; - private EncodingManager encodingManager; - private int defaultSegmentSize = -1; - private String ghLocation = ""; - private DAType dataAccessType = DAType.RAM_STORE; - private boolean sortGraph = false; - boolean removeZipped = true; - private boolean elevation = false; - private LockFactory lockFactory = new NativeFSLockFactory(); - private final String fileLockName = "gh.lock"; - private boolean allowWrites = true; - private boolean enableInstructions = true; - private boolean fullyLoaded = false; - // for routing - private boolean simplifyRequest = true; - private TraversalMode traversalMode = TraversalMode.NODE_BASED; - // for index - private LocationIndex locationIndex; - private int preciseIndexResolution = 300; - private int maxRegionSearch = 4; - // for prepare - private int minNetworkSize = 200; - private int minOnewayNetworkSize = 0; - // for CH prepare - private AlgorithmPreparation prepare; - private boolean doPrepare = true; - private boolean chEnabled = true; - private String chWeighting = "fastest"; - private int periodicUpdates = -1; - private int lazyUpdates = -1; - private int neighborUpdates = -1; - private double logMessages = -1; - // for OSM import - private String osmFile; - private double wayPointMaxDistance = 1; - private int workerThreads = -1; - private boolean calcPoints = true; - // utils - private final TranslationMap trMap = new TranslationMap().doImport(); - private ElevationProvider eleProvider = ElevationProvider.NOOP; - private final AtomicLong visitedSum = new AtomicLong(0); - - public GraphHopper() - { - } - - /** - * For testing only - */ - protected GraphHopper loadGraph( GraphStorage g ) - { - this.graph = g; - fullyLoaded = true; - initLocationIndex(); - return this; - } - - /** - * Specify which vehicles can be read by this GraphHopper instance. An encoding manager defines - * how data from every vehicle is written (und read) into edges of the graph. - */ - public GraphHopper setEncodingManager( EncodingManager acceptWay ) - { - ensureNotLoaded(); - this.encodingManager = acceptWay; - return this; - } - - public EncodingManager getEncodingManager() - { - return encodingManager; - } - - public GraphHopper setElevationProvider( ElevationProvider eleProvider ) - { - if (eleProvider == null || eleProvider == ElevationProvider.NOOP) - setElevation(false); - else - setElevation(true); - this.eleProvider = eleProvider; - return this; - } - - /** - * Threads for data reading. - */ - protected int getWorkerThreads() - { - return workerThreads; - } - - /** - * Return maximum distance (in meter) to reduce points via douglas peucker while OSM import. - */ - protected double getWayPointMaxDistance() - { - return wayPointMaxDistance; - } - - public GraphHopper setWayPointMaxDistance( double wayPointMaxDistance ) - { - this.wayPointMaxDistance = wayPointMaxDistance; - return this; - } - - /** - * Sets the default traversal mode used for the algorithms and preparation. - */ - public GraphHopper setTraversalMode( TraversalMode traversalMode ) - { - this.traversalMode = traversalMode; - return this; - } - - public TraversalMode getTraversalMode() - { - return traversalMode; - } - - /** - * Configures the underlying storage to be used on a well equipped server. - */ - public GraphHopper forServer() - { - // simplify to reduce network IO - setSimplifyResponse(true); - return setInMemory(); - } - - /** - * Configures the underlying storage to be used on a Desktop computer with enough RAM but no - * network latency. - */ - public GraphHopper forDesktop() - { - setSimplifyResponse(false); - return setInMemory(); - } - - /** - * Configures the underlying storage to be used on a less powerful machine like Android and - * Raspberry Pi with only few RAM. - */ - public GraphHopper forMobile() - { - setSimplifyResponse(false); - return setMemoryMapped(); - } - - /** - * Precise location resolution index means also more space (disc/RAM) could be consumed and - * probably slower query times, which would be e.g. not suitable for Android. The resolution - * specifies the tile width (in meter). - */ - public GraphHopper setPreciseIndexResolution( int precision ) - { - ensureNotLoaded(); - preciseIndexResolution = precision; - return this; - } - - /** - * This method call results in an in-memory graph. - */ - public GraphHopper setInMemory() - { - ensureNotLoaded(); - dataAccessType = DAType.RAM_STORE; - return this; - } - - /** - * Only valid option for in-memory graph and if you e.g. want to disable store on flush for unit - * tests. Specify storeOnFlush to true if you want that existing data will be loaded FROM disc - * and all in-memory data will be flushed TO disc after flush is called e.g. while OSM import. - *

- * @param storeOnFlush true by default - */ - public GraphHopper setStoreOnFlush( boolean storeOnFlush ) - { - ensureNotLoaded(); - if (storeOnFlush) - dataAccessType = DAType.RAM_STORE; - else - dataAccessType = DAType.RAM; - return this; - } - - /** - * Enable memory mapped configuration if not enough memory is available on the target platform. - */ - public GraphHopper setMemoryMapped() - { - ensureNotLoaded(); - dataAccessType = DAType.MMAP; - return this; - } - - /** - * Not yet stable enough to offer it for everyone - */ - private GraphHopper setUnsafeMemory() - { - ensureNotLoaded(); - dataAccessType = DAType.UNSAFE_STORE; - return this; - } - - /** - * Disables "CH-preparation". Use only if you know what you do. - */ - public GraphHopper setDoPrepare( boolean doPrepare ) - { - this.doPrepare = doPrepare; - return this; - } - - /** - * Enables the use of contraction hierarchies to reduce query times. Enabled by default. - *

- * @param weighting can be "fastest", "shortest" or your own weight-calculation type. - * @see #setCHEnable(boolean) - */ - public GraphHopper setCHWeighting( String weighting ) - { - ensureNotLoaded(); - chWeighting = weighting; - return this; - } - - public String getCHWeighting() - { - return chWeighting; - } - - /** - * Enables or disables contraction hierarchies. Enabled by default. - */ - public GraphHopper setCHEnable( boolean enable ) - { - ensureNotLoaded(); - chEnabled = enable; - return this; - } - - public boolean isCHEnabled() - { - return chEnabled; - } - - /** - * @return true if storing and fetching elevation data is enabled. Default is false - */ - public boolean hasElevation() - { - return elevation; - } - - /** - * Enable storing and fetching elevation data. Default is false - */ - public GraphHopper setElevation( boolean includeElevation ) - { - this.elevation = includeElevation; - return this; - } - - /** - * This method specifies if the import should include way names to be able to return - * instructions for a route. - */ - public GraphHopper setEnableInstructions( boolean b ) - { - ensureNotLoaded(); - enableInstructions = b; - return this; - } - - /** - * This methods enables gps point calculation. If disabled only distance will be calculated. - */ - public GraphHopper setEnableCalcPoints( boolean b ) - { - calcPoints = b; - return this; - } - - /** - * This method specifies if the returned path should be simplified or not, via douglas-peucker - * or similar algorithm. - */ - private GraphHopper setSimplifyResponse( boolean doSimplify ) - { - this.simplifyRequest = doSimplify; - return this; - } - - /** - * Sets the graphhopper folder. - */ - public GraphHopper setGraphHopperLocation( String ghLocation ) - { - ensureNotLoaded(); - if (ghLocation == null) - throw new IllegalArgumentException("graphhopper location cannot be null"); - - this.ghLocation = ghLocation; - return this; - } - - public String getGraphHopperLocation() - { - return ghLocation; - } - - /** - * This file can be an osm xml (.osm), a compressed xml (.osm.zip or .osm.gz) or a protobuf file - * (.pbf). - */ - public GraphHopper setOSMFile( String osmFileStr ) - { - ensureNotLoaded(); - if (Helper.isEmpty(osmFileStr)) - throw new IllegalArgumentException("OSM file cannot be empty."); - - osmFile = osmFileStr; - return this; - } - - public String getOSMFile() - { - return osmFile; - } - - /** - * The underlying graph used in algorithms. - *

- * @throws IllegalStateException if graph is not instantiated. - */ - public GraphStorage getGraph() - { - if (graph == null) - throw new IllegalStateException("Graph not initialized"); - - return graph; - } - - public void setGraph( GraphStorage graph ) - { - this.graph = graph; - } - - protected void setLocationIndex( LocationIndex locationIndex ) - { - this.locationIndex = locationIndex; - } - - /** - * The location index created from the graph. - *

- * @throws IllegalStateException if index is not initialized - */ - public LocationIndex getLocationIndex() - { - if (locationIndex == null) - throw new IllegalStateException("Location index not initialized"); - - return locationIndex; - } - - public AlgorithmPreparation getPreparation() - { - return prepare; - } - - /** - * Sorts the graph which requires more RAM while import. See #12 - */ - public GraphHopper setSortGraph( boolean sortGraph ) - { - ensureNotLoaded(); - this.sortGraph = sortGraph; - return this; - } - - /** - * Specifies if it is allowed for GraphHopper to write. E.g. for read only filesystems it is not - * possible to create a lock file and so we can avoid write locks. - */ - public GraphHopper setAllowWrites( boolean allowWrites ) - { - this.allowWrites = allowWrites; - return this; - } - - public boolean isAllowWrites() - { - return allowWrites; - } - - public TranslationMap getTranslationMap() - { - return trMap; - } - - /** - * Reads configuration from a CmdArgs object. Which can be manually filled, or via main(String[] - * args) ala CmdArgs.read(args) or via configuration file ala - * CmdArgs.readFromConfig("config.properties", "graphhopper.config") - */ - public GraphHopper init( CmdArgs args ) - { - args = CmdArgs.readFromConfigAndMerge(args, "config", "graphhopper.config"); - String tmpOsmFile = args.get("osmreader.osm", ""); - if (!Helper.isEmpty(tmpOsmFile)) - osmFile = tmpOsmFile; - - String graphHopperFolder = args.get("graph.location", ""); - if (Helper.isEmpty(graphHopperFolder) && Helper.isEmpty(ghLocation)) - { - if (Helper.isEmpty(osmFile)) - throw new IllegalArgumentException("You need to specify an OSM file."); - - graphHopperFolder = Helper.pruneFileEnd(osmFile) + "-gh"; - } - - // graph - setGraphHopperLocation(graphHopperFolder); - defaultSegmentSize = args.getInt("graph.dataaccess.segmentSize", defaultSegmentSize); - - String graphDATypeStr = args.get("graph.dataaccess", "RAM_STORE"); - dataAccessType = DAType.fromString(graphDATypeStr); - - sortGraph = args.getBool("graph.doSort", sortGraph); - removeZipped = args.getBool("graph.removeZipped", removeZipped); - int bytesForFlags = args.getInt("graph.bytesForFlags", 4); - if (args.get("graph.locktype", "native").equals("simple")) - lockFactory = new SimpleFSLockFactory(); - else - lockFactory = new NativeFSLockFactory(); - - // elevation - String eleProviderStr = args.get("graph.elevation.provider", "noop").toLowerCase(); - boolean eleCalcMean = args.getBool("graph.elevation.calcmean", false); - String cacheDirStr = args.get("graph.elevation.cachedir", ""); - String baseURL = args.get("graph.elevation.baseurl", ""); - DAType elevationDAType = DAType.fromString(args.get("graph.elevation.dataaccess", "MMAP")); - ElevationProvider tmpProvider = ElevationProvider.NOOP; - if (eleProviderStr.equalsIgnoreCase("srtm")) - { - tmpProvider = new SRTMProvider(); - } else if (eleProviderStr.equalsIgnoreCase("cgiar")) - { - CGIARProvider cgiarProvider = new CGIARProvider(); - cgiarProvider.setAutoRemoveTemporaryFiles(args.getBool("graph.elevation.cgiar.clear", true)); - tmpProvider = cgiarProvider; - } - - tmpProvider.setCalcMean(eleCalcMean); - tmpProvider.setCacheDir(new File(cacheDirStr)); - if (!baseURL.isEmpty()) - tmpProvider.setBaseURL(baseURL); - tmpProvider.setDAType(elevationDAType); - setElevationProvider(tmpProvider); - - // optimizable prepare - minNetworkSize = args.getInt("prepare.minNetworkSize", minNetworkSize); - minOnewayNetworkSize = args.getInt("prepare.minOnewayNetworkSize", minOnewayNetworkSize); - - // prepare CH - doPrepare = args.getBool("prepare.doPrepare", doPrepare); - String tmpCHWeighting = args.get("prepare.chWeighting", "fastest"); - chEnabled = "fastest".equals(tmpCHWeighting) || "shortest".equals(tmpCHWeighting); - if (chEnabled) - setCHWeighting(tmpCHWeighting); - - periodicUpdates = args.getInt("prepare.updates.periodic", periodicUpdates); - lazyUpdates = args.getInt("prepare.updates.lazy", lazyUpdates); - neighborUpdates = args.getInt("prepare.updates.neighbor", neighborUpdates); - logMessages = args.getDouble("prepare.logmessages", logMessages); - - // osm import - wayPointMaxDistance = args.getDouble("osmreader.wayPointMaxDistance", wayPointMaxDistance); - String flagEncoders = args.get("graph.flagEncoders", "CAR"); - encodingManager = new EncodingManager(flagEncoders, bytesForFlags); - workerThreads = args.getInt("osmreader.workerThreads", workerThreads); - enableInstructions = args.getBool("osmreader.instructions", enableInstructions); - - // index - preciseIndexResolution = args.getInt("index.highResolution", preciseIndexResolution); - maxRegionSearch = args.getInt("index.maxRegionSearch", maxRegionSearch); - return this; - } - - private void printInfo() - { - logger.info("version " + Constants.VERSION + "|" + Constants.BUILD_DATE + " (" + Constants.getVersions() + ")"); - if (graph != null) - logger.info("graph " + graph.toString() + ", details:" + graph.toDetailsString()); - } - - /** - * Imports provided data from disc and creates graph. Depending on the settings the resulting - * graph will be stored to disc so on a second call this method will only load the graph from - * disc which is usually a lot faster. - */ - public GraphHopper importOrLoad() - { - if (!load(ghLocation)) - { - printInfo(); - process(ghLocation); - } else - { - printInfo(); - } - return this; - } - - /** - * Creates the graph from OSM data. - */ - private GraphHopper process( String graphHopperLocation ) - { - setGraphHopperLocation(graphHopperLocation); - Lock lock = null; - try - { - if (graph.getDirectory().getDefaultType().isStoring()) - { - lockFactory.setLockDir(new File(graphHopperLocation)); - lock = lockFactory.create(fileLockName, true); - if (!lock.tryLock()) - throw new RuntimeException("To avoid multiple writers we need to obtain a write lock but it failed. In " + graphHopperLocation, lock.getObtainFailedReason()); - } - - try - { - importData(); - graph.getProperties().put("osmreader.import.date", formatDateTime(new Date())); - } catch (IOException ex) - { - throw new RuntimeException("Cannot parse OSM file " + getOSMFile(), ex); - } - cleanUp(); - optimize(); - postProcessing(); - flush(); - } finally - { - if (lock != null) - lock.release(); - } - return this; - } - - protected DataReader importData() throws IOException - { - ensureWriteAccess(); - if (graph == null) - throw new IllegalStateException("Load graph before importing OSM data"); - - if (osmFile == null) - throw new IllegalStateException("Couldn't load from existing folder: " + ghLocation - + " but also cannot import from OSM file as it wasn't specified!"); - - encodingManager.setEnableInstructions(enableInstructions); - DataReader reader = createReader(graph); - logger.info("using " + graph.toString() + ", memory:" + Helper.getMemInfo()); - reader.readGraph(); - return reader; - } - - protected DataReader createReader( GraphStorage tmpGraph ) - { - return initOSMReader(new OSMReader(tmpGraph)); - } - - protected OSMReader initOSMReader( OSMReader reader ) - { - if (osmFile == null) - throw new IllegalArgumentException("No OSM file specified"); - - logger.info("start creating graph from " + osmFile); - File osmTmpFile = new File(osmFile); - return reader.setOSMFile(osmTmpFile). - setElevationProvider(eleProvider). - setWorkerThreads(workerThreads). - setEncodingManager(encodingManager). - setWayPointMaxDistance(wayPointMaxDistance); - } - - /** - * Opens existing graph. - *

- * @param graphHopperFolder is the folder containing graphhopper files (which can be compressed - * too) - */ - @Override - public boolean load( String graphHopperFolder ) - { - if (Helper.isEmpty(graphHopperFolder)) - throw new IllegalStateException("graphHopperLocation is not specified. call init before"); - - if (fullyLoaded) - throw new IllegalStateException("graph is already successfully loaded"); - - if (graphHopperFolder.endsWith("-gh")) - { - // do nothing - } else if (graphHopperFolder.endsWith(".osm") || graphHopperFolder.endsWith(".xml")) - { - throw new IllegalArgumentException("To import an osm file you need to use importOrLoad"); - } else if (graphHopperFolder.indexOf(".") < 0) - { - if (new File(graphHopperFolder + "-gh").exists()) - graphHopperFolder += "-gh"; - } else - { - File compressed = new File(graphHopperFolder + ".ghz"); - if (compressed.exists() && !compressed.isDirectory()) - { - try - { - new Unzipper().unzip(compressed.getAbsolutePath(), graphHopperFolder, removeZipped); - } catch (IOException ex) - { - throw new RuntimeException("Couldn't extract file " + compressed.getAbsolutePath() - + " to " + graphHopperFolder, ex); - } - } - } - - setGraphHopperLocation(graphHopperFolder); - - if (encodingManager == null) - encodingManager = EncodingManager.create(ghLocation); - - GHDirectory dir = new GHDirectory(ghLocation, dataAccessType); - if (chEnabled) - graph = new LevelGraphStorage(dir, encodingManager, hasElevation()); - else if (encodingManager.needsTurnCostsSupport()) - graph = new GraphHopperStorage(dir, encodingManager, hasElevation(), new TurnCostStorage()); - else - graph = new GraphHopperStorage(dir, encodingManager, hasElevation()); - - graph.setSegmentSize(defaultSegmentSize); - - Lock lock = null; - try - { - // create locks only if writes are allowed, if they are not allowed a lock cannot be created - // (e.g. on a read only filesystem locks would fail) - if (graph.getDirectory().getDefaultType().isStoring() && isAllowWrites()) - { - lockFactory.setLockDir(new File(ghLocation)); - lock = lockFactory.create(fileLockName, false); - if (!lock.tryLock()) - throw new RuntimeException("To avoid reading partial data we need to obtain the read lock but it failed. In " + ghLocation, lock.getObtainFailedReason()); - } - - if (!graph.loadExisting()) - return false; - - postProcessing(); - fullyLoaded = true; - return true; - } finally - { - if (lock != null) - lock.release(); - } - } - - /** - * Sets EncodingManager, does the preparation and creates the locationIndex - */ - protected void postProcessing() - { - encodingManager = graph.getEncodingManager(); - if (chEnabled) - initCHPrepare(); - - if (!isPrepared()) - prepare(); - initLocationIndex(); - } - - private boolean isPrepared() - { - return "true".equals(graph.getProperties().get("prepare.done")); - } - - protected void initCHPrepare() - { - FlagEncoder encoder = encodingManager.getSingle(); - PrepareContractionHierarchies tmpPrepareCH = new PrepareContractionHierarchies(encoder, - createWeighting(Weighting.Params.create(chWeighting), encoder), traversalMode); - tmpPrepareCH.setPeriodicUpdates(periodicUpdates). - setLazyUpdates(lazyUpdates). - setNeighborUpdates(neighborUpdates). - setLogMessages(logMessages); - - prepare = tmpPrepareCH; - prepare.setGraph(graph); - } - - /** - * Based on the weightingParameters and the specified vehicle a Weighting instance can be - * created. Note that all URL parameters are available in the weightingParameters as String if - * you use the GraphHopper Web module. - *

- * @see Weighting.Params.create - * @param weightingParameters the request parameters - * @param encoder the required vehicle - * @return the weighting to be used for route calculation - */ - public Weighting createWeighting( Map weightingParameters, FlagEncoder encoder ) - { - String weighting = (String) weightingParameters.get("weighting"); - weighting = weighting == null ? "" : weighting; - - Weighting result; - - if ("shortest".equalsIgnoreCase(weighting)) - { - result = new ShortestWeighting(); - } else if ("fastest".equalsIgnoreCase(weighting) || weighting.isEmpty()) - { - if (encoder instanceof BikeCommonFlagEncoder) - result = new PriorityWeighting(encoder); - else - result = new FastestWeighting(encoder); - } else - { - throw new UnsupportedOperationException("weighting " + weighting + " not supported"); - } - - if (encoder.supportsTurnCosts()) - { - result = new TurnWeighting(result, encoder, (TurnCostStorage) graph.getExtendedStorage()); - } - return result; - } - - @Override - public GHResponse route( GHRequest request ) - { - if (graph == null || !fullyLoaded) - throw new IllegalStateException("Call load or importOrLoad before routing"); - - if (graph.isClosed()) - throw new IllegalStateException("You need to create a new GraphHopper instance as it is already closed"); - - GHResponse response = new GHResponse(); - List paths = getPaths(request, response); - if (response.hasErrors()) - return response; - - enableInstructions = request.getHint("instructions", enableInstructions); - calcPoints = request.getHint("calcPoints", calcPoints); - simplifyRequest = request.getHint("simplifyRequest", simplifyRequest); - double minPathPrecision = request.getHint("douglas.minprecision", 1d); - Locale locale = request.getLocale(); - DouglasPeucker peucker = new DouglasPeucker().setMaxDistance(minPathPrecision); - - new PathMerger(). - setCalcPoints(calcPoints). - setDouglasPeucker(peucker). - setEnableInstructions(enableInstructions). - setSimplifyRequest(simplifyRequest && minPathPrecision > 0). - doWork(response, paths, trMap.getWithFallBack(locale)); - return response; - } - - protected List getPaths( GHRequest request, GHResponse rsp ) - { - String vehicle = request.getVehicle(); - if (vehicle.isEmpty()) - vehicle = encodingManager.getSingle().toString(); - - if (!encodingManager.supports(vehicle)) - { - rsp.addError(new IllegalArgumentException("Vehicle " + vehicle + " unsupported. " - + "Supported are: " + getEncodingManager())); - return Collections.emptyList(); - } - - List points = request.getPoints(); - if (points.size() < 2) - { - rsp.addError(new IllegalStateException("At least 2 points has to be specified, but was:" + points.size())); - return Collections.emptyList(); - } - - FlagEncoder encoder = encodingManager.getEncoder(vehicle); - EdgeFilter edgeFilter = new DefaultEdgeFilter(encoder); - GHPoint startPoint = points.get(0); - StopWatch sw = new StopWatch().start(); - QueryResult fromRes = locationIndex.findClosest(startPoint.lat, startPoint.lon, edgeFilter); - String debug = "idLookup[0]:" + sw.stop().getSeconds() + "s"; - sw.stop(); - if (!fromRes.isValid()) - { - rsp.addError(new IllegalArgumentException("Cannot find point 0: " + startPoint)); - return Collections.emptyList(); - } - - List paths = new ArrayList(points.size() - 1); - for (int placeIndex = 1; placeIndex < points.size(); placeIndex++) - { - GHPoint point = points.get(placeIndex); - sw = new StopWatch().start(); - QueryResult toRes = locationIndex.findClosest(point.lat, point.lon, edgeFilter); - debug += ", [" + placeIndex + "] idLookup:" + sw.stop().getSeconds() + "s"; - if (!toRes.isValid()) - { - rsp.addError(new IllegalArgumentException("Cannot find point " + placeIndex + ": " + point)); - break; - } - - sw = new StopWatch().start(); - String algoStr = request.getAlgorithm().isEmpty() ? "dijkstrabi" : request.getAlgorithm(); - RoutingAlgorithm algo = null; - if (chEnabled) - { - if (prepare == null) - throw new IllegalStateException("Preparation object is null. CH-preparation wasn't done or did you " - + "forget to call setCHEnable(false)?"); - - if (algoStr.equals("dijkstrabi")) - algo = prepare.createAlgo(); - else if (algoStr.equals("astarbi")) - algo = ((PrepareContractionHierarchies) prepare).createAStar(); - else - { - rsp.addError(new IllegalStateException( - "Only dijkstrabi and astarbi is supported for LevelGraph (using contraction hierarchies)!")); - break; - } - } else - { - Weighting weighting = createWeighting(request.getHints(), encoder); - prepare = NoOpAlgorithmPreparation.createAlgoPrepare(graph, algoStr, encoder, weighting, traversalMode); - algo = prepare.createAlgo(); - } - - debug += ", algoInit:" + sw.stop().getSeconds() + "s"; - sw = new StopWatch().start(); - - Path path = algo.calcPath(fromRes, toRes); - if (path.getMillis() < 0) - throw new RuntimeException("Time was negative. Please report as bug and include:" + request); - - paths.add(path); - debug += ", " + algo.getName() + "-routing:" + sw.stop().getSeconds() + "s, " + path.getDebugInfo(); - visitedSum.addAndGet(algo.getVisitedNodes()); - fromRes = toRes; - } - - if (rsp.hasErrors()) - return Collections.emptyList(); - - if (points.size() - 1 != paths.size()) - throw new RuntimeException("There should be exactly one more places than paths. places:" + points.size() + ", paths:" + paths.size()); - - rsp.setDebugInfo(debug); - return paths; - } - - protected LocationIndex createLocationIndex( Directory dir ) - { - LocationIndex tmpIndex; - if (graph instanceof LevelGraph) - { - tmpIndex = new LocationIndexTreeSC((LevelGraph) graph, dir); - } else - { - tmpIndex = new LocationIndexTree(graph, dir); - } - tmpIndex.setResolution(preciseIndexResolution); - ((LocationIndexTree) tmpIndex).setMaxRegionSearch(maxRegionSearch); - - if (!tmpIndex.loadExisting()) - { - ensureWriteAccess(); - tmpIndex.prepareIndex(); - } - - return tmpIndex; - } - - /** - * Initializes the location index. Currently this has to be done after the ch-preparation! - * Because - to improve performance - certain edges won't be available in a ch-graph and the - * index needs to know this and selects the correct nodes which still see the correct neighbors. - * See #116 - */ - protected void initLocationIndex() - { - if (locationIndex != null) - throw new IllegalStateException("Cannot initialize locationIndex twice!"); - - locationIndex = createLocationIndex(graph.getDirectory()); - } - - protected void optimize() - { - logger.info("optimizing ... (" + Helper.getMemInfo() + ")"); - graph.optimize(); - logger.info("finished optimize (" + Helper.getMemInfo() + ")"); - - // Later: move this into the GraphStorage.optimize method - // Or: Doing it after preparation to optimize shortcuts too. But not possible yet #12 - if (sortGraph) - { - if (graph instanceof LevelGraph && isPrepared()) - throw new IllegalArgumentException("Sorting prepared LevelGraph is not possible yet. See #12"); - - GraphStorage newGraph = GHUtility.newStorage(graph); - GHUtility.sortDFS(graph, newGraph); - logger.info("graph sorted (" + Helper.getMemInfo() + ")"); - graph = newGraph; - } - } - - protected void prepare() - { - boolean tmpPrepare = doPrepare && prepare != null; - if (tmpPrepare) - { - ensureWriteAccess(); - if (prepare instanceof PrepareContractionHierarchies && encodingManager.getVehicleCount() > 1) - throw new IllegalArgumentException("Contraction hierarchies preparation " - + "requires (at the moment) only one vehicle. But was:" + encodingManager); - - logger.info("calling prepare.doWork for " + encodingManager.toString() + " ... (" + Helper.getMemInfo() + ")"); - prepare.doWork(); - graph.getProperties().put("prepare.date", formatDateTime(new Date())); - } - graph.getProperties().put("prepare.done", tmpPrepare); - } - - protected void cleanUp() - { - int prev = graph.getNodes(); - PrepareRoutingSubnetworks preparation = new PrepareRoutingSubnetworks(graph, encodingManager); - preparation.setMinNetworkSize(minNetworkSize); - preparation.setMinOnewayNetworkSize(this.minOnewayNetworkSize); - logger.info("start finding subnetworks, " + Helper.getMemInfo()); - preparation.doWork(); - int n = graph.getNodes(); - // calculate remaining subnetworks - int remainingSubnetworks = preparation.findSubnetworks().size(); - logger.info("edges: " + graph.getAllEdges().getMaxId() + ", nodes " + n + ", there were " + preparation.getSubNetworks() - + " subnetworks. removed them => " + (prev - n) + " less nodes. Remaining subnetworks:" + remainingSubnetworks); - } - - protected void flush() - { - logger.info("flushing graph " + graph.toString() + ", details:" + graph.toDetailsString() + ", " + Helper.getMemInfo() + ")"); - graph.flush(); - fullyLoaded = true; - } - - /** - * Releases all associated resources like memory or files. But it does not remove them. To - * remove the files created in graphhopperLocation you have to call clean(). - */ - public void close() - { - if (graph != null) - graph.close(); - - if (locationIndex != null) - locationIndex.close(); - - try - { - lockFactory.forceRemove(fileLockName, true); - } catch (Exception ex) - { - // silently fail - } - } - - /** - * Removes the on-disc routing files. Call only after calling close or before importOrLoad or - * load - */ - public void clean() - { - if (getGraphHopperLocation().isEmpty()) - throw new IllegalStateException("Cannot clean GraphHopper without specified graphHopperLocation"); - - File folder = new File(getGraphHopperLocation()); - Helper.removeDir(folder); - } - - // make sure this is identical to buildDate used in pom.xml - // yyyy-MM-dd'T'HH:mm:ssZ - private String formatDateTime( Date date ) - { - return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(date); - } - - protected void ensureNotLoaded() - { - if (fullyLoaded) - throw new IllegalStateException("No configuration changes are possible after loading the graph"); - } - - protected void ensureWriteAccess() - { - if (!allowWrites) - throw new IllegalStateException("Writes are not allowed!"); - } - - /** - * Returns the current sum of the visited nodes while routing. Mainly for statistic and - * debugging purposes. - */ - public long getVisitedSum() - { - return visitedSum.get(); - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/old/GraphHopper.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/old/GraphHopper.java deleted file mode 100755 index 384134d..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/old/GraphHopper.java +++ /dev/null @@ -1,1076 +0,0 @@ -/* - * Licensed to GraphHopper and Peter Karich under one or more contributor - * license agreements. See the NOTICE file distributed with this work for - * additional information regarding copyright ownership. - * - * GraphHopper 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 com.graphhopper; - -import com.graphhopper.reader.DataReader; -import com.graphhopper.reader.OSMReader; -import com.graphhopper.reader.dem.CGIARProvider; -import com.graphhopper.reader.dem.ElevationProvider; -import com.graphhopper.reader.dem.SRTMProvider; -import com.graphhopper.routing.Path; -import com.graphhopper.routing.RoutingAlgorithm; -import com.graphhopper.routing.ch.PrepareContractionHierarchies; -import com.graphhopper.routing.util.*; -import com.graphhopper.storage.*; -import com.graphhopper.storage.index.*; -import com.graphhopper.util.*; -import com.graphhopper.util.shapes.GHPoint; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.concurrent.atomic.AtomicLong; - - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * Easy to use access point to configure import and (offline) routing. - *

- * @see GraphHopperAPI - * @author Peter Karich - */ -public class GraphHopper implements GraphHopperAPI -{ - private final Logger logger = LoggerFactory.getLogger(getClass()); - // for graph: - private GraphStorage graph; - private EncodingManager encodingManager; - private int defaultSegmentSize = -1; - private String ghLocation = ""; - private DAType dataAccessType = DAType.RAM_STORE; - private boolean sortGraph = false; - boolean removeZipped = true; - private boolean elevation = false; - private LockFactory lockFactory = new NativeFSLockFactory(); - private final String fileLockName = "gh.lock"; - private boolean allowWrites = true; - private boolean turnCosts = false; - private boolean enableInstructions = true; - private boolean fullyLoaded = false; - // for routing - private boolean simplifyRequest = true; - private TraversalMode traversalMode = TraversalMode.NODE_BASED; - // for index - private LocationIndex locationIndex; - private int preciseIndexResolution = 300; - private int maxRegionSearch = 4; - // for prepare - private int minNetworkSize = 200; - private int minOnewayNetworkSize = 0; - // for CH prepare - private AlgorithmPreparation prepare; - private boolean doPrepare = true; - private boolean chEnabled = true; - private String chWeighting = "fastest"; - private int periodicUpdates = -1; - private int lazyUpdates = -1; - private int neighborUpdates = -1; - private double logMessages = -1; - // for OSM import - private String osmFile; - private double wayPointMaxDistance = 1; - private int workerThreads = -1; - private boolean calcPoints = true; - // utils - private final TranslationMap trMap = new TranslationMap().doImport(); - private ElevationProvider eleProvider = ElevationProvider.NOOP; - private final AtomicLong visitedSum = new AtomicLong(0); - - public GraphHopper() - { - } - - /** - * For testing only - */ - protected GraphHopper loadGraph( GraphStorage g ) - { - this.graph = g; - fullyLoaded = true; - initLocationIndex(); - return this; - } - - /** - * Specify which vehicles can be read by this GraphHopper instance. An encoding manager defines - * how data from every vehicle is written (und read) into edges of the graph. - */ - public GraphHopper setEncodingManager( EncodingManager acceptWay ) - { - ensureNotLoaded(); - this.encodingManager = acceptWay; - return this; - } - - public EncodingManager getEncodingManager() - { - return encodingManager; - } - - public GraphHopper setElevationProvider( ElevationProvider eleProvider ) - { - if (eleProvider == null || eleProvider == ElevationProvider.NOOP) - setElevation(false); - else - setElevation(true); - this.eleProvider = eleProvider; - return this; - } - - /** - * Threads for data reading. - */ - protected int getWorkerThreads() - { - return workerThreads; - } - - /** - * Return maximum distance (in meter) to reduce points via douglas peucker while OSM import. - */ - protected double getWayPointMaxDistance() - { - return wayPointMaxDistance; - } - - public GraphHopper setWayPointMaxDistance( double wayPointMaxDistance ) - { - this.wayPointMaxDistance = wayPointMaxDistance; - return this; - } - - /** - * Sets the default traversal mode used for the algorithms and preparation. - */ - public GraphHopper setTraversalMode( TraversalMode traversalMode ) - { - this.traversalMode = traversalMode; - return this; - } - - /** - * Configures the underlying storage to be used on a well equipped server. - */ - public GraphHopper forServer() - { - // simplify to reduce network IO - setSimplifyResponse(true); - return setInMemory(); - } - - /** - * Configures the underlying storage to be used on a Desktop computer with enough RAM but no - * network latency. - */ - public GraphHopper forDesktop() - { - setSimplifyResponse(false); - return setInMemory(); - } - - /** - * Configures the underlying storage to be used on a less powerful machine like Android and - * Raspberry Pi with only few RAM. - */ - public GraphHopper forMobile() - { - setSimplifyResponse(false); - return setMemoryMapped(); - } - - /** - * Precise location resolution index means also more space (disc/RAM) could be consumed and - * probably slower query times, which would be e.g. not suitable for Android. The resolution - * specifies the tile width (in meter). - */ - public GraphHopper setPreciseIndexResolution( int precision ) - { - ensureNotLoaded(); - preciseIndexResolution = precision; - return this; - } - - /** - * This method call results in an in-memory graph. - */ - public GraphHopper setInMemory() - { - ensureNotLoaded(); - dataAccessType = DAType.RAM_STORE; - return this; - } - - /** - * Only valid option for in-memory graph and if you e.g. want to disable store on flush for unit - * tests. Specify storeOnFlush to true if you want that existing data will be loaded FROM disc - * and all in-memory data will be flushed TO disc after flush is called e.g. while OSM import. - *

- * @param storeOnFlush true by default - */ - public GraphHopper setStoreOnFlush( boolean storeOnFlush ) - { - ensureNotLoaded(); - if (storeOnFlush) - dataAccessType = DAType.RAM_STORE; - else - dataAccessType = DAType.RAM; - return this; - } - - /** - * Enable memory mapped configuration if not enough memory is available on the target platform. - */ - public GraphHopper setMemoryMapped() - { - ensureNotLoaded(); - dataAccessType = DAType.MMAP; - return this; - } - - /** - * Not yet stable enough to offer it for everyone - */ - private GraphHopper setUnsafeMemory() - { - ensureNotLoaded(); - dataAccessType = DAType.UNSAFE_STORE; - return this; - } - - /** - * Disables "CH-preparation". Use only if you know what you do. - */ - public GraphHopper setDoPrepare( boolean doPrepare ) - { - this.doPrepare = doPrepare; - return this; - } - - /** - * Enables the use of contraction hierarchies to reduce query times. Enabled by default. - *

- * @param weighting can be "fastest", "shortest" or your own weight-calculation type. - * @see #setCHEnable(boolean) - */ - public GraphHopper setCHWeighting( String weighting ) - { - ensureNotLoaded(); - chWeighting = weighting; - return this; - } - - public String getCHWeighting() - { - return chWeighting; - } - - /** - * Enables or disables contraction hierarchies. Enabled by default. - */ - public GraphHopper setCHEnable( boolean enable ) - { - ensureNotLoaded(); - chEnabled = enable; - return this; - } - - public boolean isCHEnabled() - { - return chEnabled; - } - - /** - * @return true if storing and fetching elevation data is enabled. Default is false - */ - public boolean hasElevation() - { - return elevation; - } - - /** - * Enable storing and fetching elevation data. Default is false - */ - public GraphHopper setElevation( boolean includeElevation ) - { - this.elevation = includeElevation; - return this; - } - - /** - * This method specifies if the import should include way names to be able to return - * instructions for a route. - */ - public GraphHopper setEnableInstructions( boolean b ) - { - ensureNotLoaded(); - enableInstructions = b; - return this; - } - - /** - * This methods enables gps point calculation. If disabled only distance will be calculated. - */ - public GraphHopper setEnableCalcPoints( boolean b ) - { - calcPoints = b; - return this; - } - - /** - * This method specifies if the returned path should be simplified or not, via douglas-peucker - * or similar algorithm. - */ - private GraphHopper setSimplifyResponse( boolean doSimplify ) - { - this.simplifyRequest = doSimplify; - return this; - } - - /** - * Sets the graphhopper folder. - */ - public GraphHopper setGraphHopperLocation( String ghLocation ) - { - ensureNotLoaded(); - if (ghLocation == null) - throw new IllegalArgumentException("graphhopper location cannot be null"); - - this.ghLocation = ghLocation; - return this; - } - - public String getGraphHopperLocation() - { - return ghLocation; - } - - /** - * This file can be an osm xml (.osm), a compressed xml (.osm.zip or .osm.gz) or a protobuf file - * (.pbf). - */ - public GraphHopper setOSMFile( String osmFileStr ) - { - ensureNotLoaded(); - if (Helper.isEmpty(osmFileStr)) - throw new IllegalArgumentException("OSM file cannot be empty."); - - osmFile = osmFileStr; - return this; - } - - public String getOSMFile() - { - return osmFile; - } - - /** - * The underlying graph used in algorithms. - *

- * @throws IllegalStateException if graph is not instantiated. - */ - public GraphStorage getGraph() - { - if (graph == null) - throw new IllegalStateException("Graph not initialized"); - - return graph; - } - - public void setGraph( GraphStorage graph ) - { - this.graph = graph; - } - - protected void setLocationIndex( LocationIndex locationIndex ) - { - this.locationIndex = locationIndex; - } - - /** - * The location index created from the graph. - *

- * @throws IllegalStateException if index is not initialized - */ - public LocationIndex getLocationIndex() - { - if (locationIndex == null) - throw new IllegalStateException("Location index not initialized"); - - return locationIndex; - } - - public AlgorithmPreparation getPreparation() - { - return prepare; - } - - /** - * Sorts the graph which requires more RAM while import. See #12 - */ - public GraphHopper setSortGraph( boolean sortGraph ) - { - ensureNotLoaded(); - this.sortGraph = sortGraph; - return this; - } - - /** - * Specifies if it is allowed for GraphHopper to write. E.g. for read only filesystems it is not - * possible to create a lock file and so we can avoid write locks. - */ - public GraphHopper setAllowWrites( boolean allowWrites ) - { - this.allowWrites = allowWrites; - return this; - } - - public boolean isAllowWrites() - { - return allowWrites; - } - - public TranslationMap getTranslationMap() - { - return trMap; - } - - /** - * Reads configuration from a CmdArgs object. Which can be manually filled, or via main(String[] - * args) ala CmdArgs.read(args) or via configuration file ala - * CmdArgs.readFromConfig("config.properties", "graphhopper.config") - */ - public GraphHopper init( CmdArgs args ) - { - args = CmdArgs.readFromConfigAndMerge(args, "config", "graphhopper.config"); - String tmpOsmFile = args.get("osmreader.osm", ""); - if (!Helper.isEmpty(tmpOsmFile)) - osmFile = tmpOsmFile; - - String graphHopperFolder = args.get("graph.location", ""); - if (Helper.isEmpty(graphHopperFolder) && Helper.isEmpty(ghLocation)) - { - if (Helper.isEmpty(osmFile)) - throw new IllegalArgumentException("You need to specify an OSM file."); - - graphHopperFolder = Helper.pruneFileEnd(osmFile) + "-gh"; - } - - // graph - setGraphHopperLocation(graphHopperFolder); - defaultSegmentSize = args.getInt("graph.dataaccess.segmentSize", defaultSegmentSize); - - String graphDATypeStr = args.get("graph.dataaccess", "RAM_STORE"); - dataAccessType = DAType.fromString(graphDATypeStr); - - sortGraph = args.getBool("graph.doSort", sortGraph); - removeZipped = args.getBool("graph.removeZipped", removeZipped); - int bytesForFlags = args.getInt("graph.bytesForFlags", 4); - if (args.get("graph.locktype", "native").equals("simple")) - lockFactory = new SimpleFSLockFactory(); - else - lockFactory = new NativeFSLockFactory(); - - // elevation - String eleProviderStr = args.get("graph.elevation.provider", "noop").toLowerCase(); - boolean eleCalcMean = args.getBool("graph.elevation.calcmean", false); - String cacheDirStr = args.get("graph.elevation.cachedir", ""); - String baseURL = args.get("graph.elevation.baseurl", ""); - DAType elevationDAType = DAType.fromString(args.get("graph.elevation.dataaccess", "MMAP")); - ElevationProvider tmpProvider = ElevationProvider.NOOP; - if (eleProviderStr.equalsIgnoreCase("srtm")) - { - tmpProvider = new SRTMProvider(); - } else if (eleProviderStr.equalsIgnoreCase("cgiar")) - { - CGIARProvider cgiarProvider = new CGIARProvider(); - cgiarProvider.setAutoRemoveTemporaryFiles(args.getBool("graph.elevation.cgiar.clear", true)); - tmpProvider = cgiarProvider; - } - - tmpProvider.setCalcMean(eleCalcMean); - tmpProvider.setCacheDir(new File(cacheDirStr)); - if (!baseURL.isEmpty()) - tmpProvider.setBaseURL(baseURL); - tmpProvider.setDAType(elevationDAType); - setElevationProvider(tmpProvider); - - // optimizable prepare - minNetworkSize = args.getInt("prepare.minNetworkSize", minNetworkSize); - minOnewayNetworkSize = args.getInt("prepare.minOnewayNetworkSize", minOnewayNetworkSize); - - // prepare CH - doPrepare = args.getBool("prepare.doPrepare", doPrepare); - String tmpCHWeighting = args.get("prepare.chWeighting", "fastest"); - chEnabled = "fastest".equals(tmpCHWeighting) || "shortest".equals(tmpCHWeighting); - if (chEnabled) - setCHWeighting(tmpCHWeighting); - - periodicUpdates = args.getInt("prepare.updates.periodic", periodicUpdates); - lazyUpdates = args.getInt("prepare.updates.lazy", lazyUpdates); - neighborUpdates = args.getInt("prepare.updates.neighbor", neighborUpdates); - logMessages = args.getDouble("prepare.logmessages", logMessages); - - // osm import - wayPointMaxDistance = args.getDouble("osmreader.wayPointMaxDistance", wayPointMaxDistance); - String flagEncoders = args.get("graph.flagEncoders", "CAR"); - encodingManager = new EncodingManager(flagEncoders, bytesForFlags); - workerThreads = args.getInt("osmreader.workerThreads", workerThreads); - enableInstructions = args.getBool("osmreader.instructions", enableInstructions); - - // index - preciseIndexResolution = args.getInt("index.highResolution", preciseIndexResolution); - maxRegionSearch = args.getInt("index.maxRegionSearch", maxRegionSearch); - return this; - } - - private void printInfo() - { - logger.info("version " + Constants.VERSION + "|" + Constants.BUILD_DATE + " (" + Constants.getVersions() + ")"); - if (graph != null) - logger.info("graph " + graph.toString() + ", details:" + graph.toDetailsString()); - } - - /** - * Imports provided data from disc and creates graph. Depending on the settings the resulting - * graph will be stored to disc so on a second call this method will only load the graph from - * disc which is usually a lot faster. - */ - public GraphHopper importOrLoad() - { - if (!load(ghLocation)) - { - printInfo(); - process(ghLocation); - } else - { - printInfo(); - } - return this; - } - - /** - * Creates the graph from OSM data. - */ - private GraphHopper process( String graphHopperLocation ) - { - setGraphHopperLocation(graphHopperLocation); - Lock lock = null; - try - { - if (graph.getDirectory().getDefaultType().isStoring()) - { - lockFactory.setLockDir(new File(graphHopperLocation)); - lock = lockFactory.create(fileLockName, true); - if (!lock.tryLock()) - throw new RuntimeException("To avoid multiple writers we need to obtain a write lock but it failed. In " + graphHopperLocation, lock.getObtainFailedReason()); - } - - try - { - importData(); - graph.getProperties().put("osmreader.import.date", formatDateTime(new Date())); - } catch (IOException ex) - { - throw new RuntimeException("Cannot parse OSM file " + getOSMFile(), ex); - } - cleanUp(); - optimize(); - postProcessing(); - flush(); - } finally - { - if (lock != null) - lock.release(); - } - return this; - } - - protected DataReader importData() throws IOException - { - ensureWriteAccess(); - if (graph == null) - throw new IllegalStateException("Load graph before importing OSM data"); - - if (osmFile == null) - throw new IllegalStateException("Couldn't load from existing folder: " + ghLocation - + " but also cannot import from OSM file as it wasn't specified!"); - - encodingManager.setEnableInstructions(enableInstructions); - DataReader reader = createReader(graph); - logger.info("using " + graph.toString() + ", memory:" + Helper.getMemInfo()); - reader.readGraph(); - return reader; - } - - protected DataReader createReader( GraphStorage tmpGraph ) - { - return initOSMReader(new OSMReader(tmpGraph)); - } - - protected OSMReader initOSMReader( OSMReader reader ) - { - if (osmFile == null) - throw new IllegalArgumentException("No OSM file specified"); - - logger.info("start creating graph from " + osmFile); - File osmTmpFile = new File(osmFile); - return reader.setOSMFile(osmTmpFile). - setElevationProvider(eleProvider). - setWorkerThreads(workerThreads). - setEncodingManager(encodingManager). - setWayPointMaxDistance(wayPointMaxDistance); - } - - /** - * Opens existing graph. - *

- * @param graphHopperFolder is the folder containing graphhopper files (which can be compressed - * too) - */ - @Override - public boolean load( String graphHopperFolder ) - { - if (Helper.isEmpty(graphHopperFolder)) - throw new IllegalStateException("graphHopperLocation is not specified. call init before"); - - if (fullyLoaded) - throw new IllegalStateException("graph is already successfully loaded"); - - if (graphHopperFolder.endsWith("-gh")) - { - // do nothing - } else if (graphHopperFolder.endsWith(".osm") || graphHopperFolder.endsWith(".xml")) - { - throw new IllegalArgumentException("To import an osm file you need to use importOrLoad"); - } else if (graphHopperFolder.indexOf(".") < 0) - { - if (new File(graphHopperFolder + "-gh").exists()) - graphHopperFolder += "-gh"; - } else - { - File compressed = new File(graphHopperFolder + ".ghz"); - if (compressed.exists() && !compressed.isDirectory()) - { - try - { - new Unzipper().unzip(compressed.getAbsolutePath(), graphHopperFolder, removeZipped); - } catch (IOException ex) - { - throw new RuntimeException("Couldn't extract file " + compressed.getAbsolutePath() - + " to " + graphHopperFolder, ex); - } - } - } - - setGraphHopperLocation(graphHopperFolder); - - if (encodingManager == null) - encodingManager = EncodingManager.create(ghLocation); - - GHDirectory dir = new GHDirectory(ghLocation, dataAccessType); - if (chEnabled) - graph = new LevelGraphStorage(dir, encodingManager, hasElevation()); - else if (encodingManager.needsTurnCostsSupport()) - graph = new GraphHopperStorage(dir, encodingManager, hasElevation(), new TurnCostStorage()); - else - graph = new GraphHopperStorage(dir, encodingManager, hasElevation()); - - graph.setSegmentSize(defaultSegmentSize); - - Lock lock = null; - try - { - // create locks only if writes are allowed, if they are not allowed a lock cannot be created - // (e.g. on a read only filesystem locks would fail) - if (graph.getDirectory().getDefaultType().isStoring() && isAllowWrites()) - { - lockFactory.setLockDir(new File(ghLocation)); - lock = lockFactory.create(fileLockName, false); - if (!lock.tryLock()) - throw new RuntimeException("To avoid reading partial data we need to obtain the read lock but it failed. In " + ghLocation, lock.getObtainFailedReason()); - } - - if (!graph.loadExisting()) - return false; - - postProcessing(); - fullyLoaded = true; - return true; - } finally - { - if (lock != null) - lock.release(); - } - } - - /** - * Sets EncodingManager, does the preparation and creates the locationIndex - */ - protected void postProcessing() - { - encodingManager = graph.getEncodingManager(); - if (chEnabled) - initCHPrepare(); - - if (!isPrepared()) - prepare(); - initLocationIndex(); - } - - private boolean isPrepared() - { - return "true".equals(graph.getProperties().get("prepare.done")); - } - - protected void initCHPrepare() - { - FlagEncoder encoder = encodingManager.getSingle(); - PrepareContractionHierarchies tmpPrepareCH = new PrepareContractionHierarchies(encoder, - createWeighting(Weighting.Params.create(chWeighting), encoder), traversalMode); - tmpPrepareCH.setPeriodicUpdates(periodicUpdates). - setLazyUpdates(lazyUpdates). - setNeighborUpdates(neighborUpdates). - setLogMessages(logMessages); - - prepare = tmpPrepareCH; - prepare.setGraph(graph); - } - - /** - * Based on the weightingParameters and the specified vehicle a Weighting instance can be - * created. Note that all URL parameters are available in the weightingParameters as String if - * you use the GraphHopper Web module. - *

- * @see Weighting.Params.create - * @param weightingParameters the request parameters - * @param encoder the required vehicle - * @return the weighting to be used for route calculation - */ - public Weighting createWeighting( Map weightingParameters, FlagEncoder encoder ) - { - String weighting = (String) weightingParameters.get("weighting"); - weighting = weighting == null ? "" : weighting; - - Weighting result; - - if ("shortest".equalsIgnoreCase(weighting)) - { - result = new ShortestWeighting(); - } else if ("fastest".equalsIgnoreCase(weighting) || weighting.isEmpty()) - { - if (encoder instanceof BikeCommonFlagEncoder) - result = new PriorityWeighting(encoder); - else - result = new FastestWeighting(encoder); - } else - { - throw new UnsupportedOperationException("weighting " + weighting + " not supported"); - } - - if (encoder.supportsTurnCosts()) - { - result = new TurnWeighting(result, encoder, (TurnCostStorage) graph.getExtendedStorage()); - } - return result; - } - - @Override - public GHResponse route( GHRequest request ) - { - if (graph == null || !fullyLoaded) - throw new IllegalStateException("Call load or importOrLoad before routing"); - - if (graph.isClosed()) - throw new IllegalStateException("You need to create a new GraphHopper instance as it is already closed"); - - GHResponse response = new GHResponse(); - List paths = getPaths(request, response); - if (response.hasErrors()) - return response; - - enableInstructions = request.getHint("instructions", enableInstructions); - calcPoints = request.getHint("calcPoints", calcPoints); - simplifyRequest = request.getHint("simplifyRequest", simplifyRequest); - double minPathPrecision = request.getHint("douglas.minprecision", 1d); - Locale locale = request.getLocale(); - DouglasPeucker peucker = new DouglasPeucker().setMaxDistance(minPathPrecision); - - new PathMerger(). - setCalcPoints(calcPoints). - setDouglasPeucker(peucker). - setEnableInstructions(enableInstructions). - setSimplifyRequest(simplifyRequest && minPathPrecision > 0). - doWork(response, paths, trMap.getWithFallBack(locale)); - return response; - } - - protected List getPaths( GHRequest request, GHResponse rsp ) - { - String vehicle = request.getVehicle(); - if (vehicle.isEmpty()) - vehicle = encodingManager.getSingle().toString(); - - if (!encodingManager.supports(vehicle)) - { - rsp.addError(new IllegalArgumentException("Vehicle " + vehicle + " unsupported. " - + "Supported are: " + getEncodingManager())); - return Collections.emptyList(); - } - - List points = request.getPoints(); - if (points.size() < 2) - { - rsp.addError(new IllegalStateException("At least 2 points has to be specified, but was:" + points.size())); - return Collections.emptyList(); - } - - FlagEncoder encoder = encodingManager.getEncoder(vehicle); - EdgeFilter edgeFilter = new DefaultEdgeFilter(encoder); - GHPoint startPoint = points.get(0); - StopWatch sw = new StopWatch().start(); - QueryResult fromRes = locationIndex.findClosest(startPoint.lat, startPoint.lon, edgeFilter); - String debug = "idLookup[0]:" + sw.stop().getSeconds() + "s"; - sw.stop(); - if (!fromRes.isValid()) - { - rsp.addError(new IllegalArgumentException("Cannot find point 0: " + startPoint)); - return Collections.emptyList(); - } - - List paths = new ArrayList(points.size() - 1); - for (int placeIndex = 1; placeIndex < points.size(); placeIndex++) - { - GHPoint point = points.get(placeIndex); - sw = new StopWatch().start(); - QueryResult toRes = locationIndex.findClosest(point.lat, point.lon, edgeFilter); - debug += ", [" + placeIndex + "] idLookup:" + sw.stop().getSeconds() + "s"; - if (!toRes.isValid()) - { - rsp.addError(new IllegalArgumentException("Cannot find point " + placeIndex + ": " + point)); - break; - } - - sw = new StopWatch().start(); - String algoStr = request.getAlgorithm().isEmpty() ? "dijkstrabi" : request.getAlgorithm(); - RoutingAlgorithm algo = null; - if (chEnabled) - { - if (prepare == null) - throw new IllegalStateException("Preparation object is null. CH-preparation wasn't done or did you " - + "forget to call setCHEnable(false)?"); - - if (algoStr.equals("dijkstrabi")) - algo = prepare.createAlgo(); - else if (algoStr.equals("astarbi")) - algo = ((PrepareContractionHierarchies) prepare).createAStar(); - else - { - rsp.addError(new IllegalStateException( - "Only dijkstrabi and astarbi is supported for LevelGraph (using contraction hierarchies)!")); - break; - } - } else - { - Weighting weighting = createWeighting(request.getHints(), encoder); - prepare = NoOpAlgorithmPreparation.createAlgoPrepare(graph, algoStr, encoder, weighting, traversalMode); - algo = prepare.createAlgo(); - } - - debug += ", algoInit:" + sw.stop().getSeconds() + "s"; - sw = new StopWatch().start(); - - Path path = algo.calcPath(fromRes, toRes); - if (path.getMillis() < 0) - throw new RuntimeException("Time was negative. Please report as bug and include:" + request); - - paths.add(path); - debug += ", " + algo.getName() + "-routing:" + sw.stop().getSeconds() + "s, " + path.getDebugInfo(); - visitedSum.addAndGet(algo.getVisitedNodes()); - fromRes = toRes; - } - - if (rsp.hasErrors()) - return Collections.emptyList(); - - if (points.size() - 1 != paths.size()) - throw new RuntimeException("There should be exactly one more places than paths. places:" + points.size() + ", paths:" + paths.size()); - - rsp.setDebugInfo(debug); - return paths; - } - - protected LocationIndex createLocationIndex( Directory dir ) - { - LocationIndex tmpIndex; - if (graph instanceof LevelGraph) - { - tmpIndex = new LocationIndexTreeSC((LevelGraph) graph, dir); - } else - { - tmpIndex = new LocationIndexTree(graph, dir); - } - tmpIndex.setResolution(preciseIndexResolution); - ((LocationIndexTree) tmpIndex).setMaxRegionSearch(maxRegionSearch); - - if (!tmpIndex.loadExisting()) - { - ensureWriteAccess(); - tmpIndex.prepareIndex(); - } - - return tmpIndex; - } - - /** - * Initializes the location index. Currently this has to be done after the ch-preparation! - * Because - to improve performance - certain edges won't be available in a ch-graph and the - * index needs to know this and selects the correct nodes which still see the correct neighbors. - * See #116 - */ - protected void initLocationIndex() - { - if (locationIndex != null) - throw new IllegalStateException("Cannot initialize locationIndex twice!"); - - locationIndex = createLocationIndex(graph.getDirectory()); - } - - protected void optimize() - { - logger.info("optimizing ... (" + Helper.getMemInfo() + ")"); - graph.optimize(); - logger.info("finished optimize (" + Helper.getMemInfo() + ")"); - - // Later: move this into the GraphStorage.optimize method - // Or: Doing it after preparation to optimize shortcuts too. But not possible yet #12 - if (sortGraph) - { - if (graph instanceof LevelGraph && isPrepared()) - throw new IllegalArgumentException("Sorting prepared LevelGraph is not possible yet. See #12"); - - GraphStorage newGraph = GHUtility.newStorage(graph); - GHUtility.sortDFS(graph, newGraph); - logger.info("graph sorted (" + Helper.getMemInfo() + ")"); - graph = newGraph; - } - } - - protected void prepare() - { - boolean tmpPrepare = doPrepare && prepare != null; - if (tmpPrepare) - { - ensureWriteAccess(); - if (prepare instanceof PrepareContractionHierarchies && encodingManager.getVehicleCount() > 1) - throw new IllegalArgumentException("Contraction hierarchies preparation " - + "requires (at the moment) only one vehicle. But was:" + encodingManager); - - logger.info("calling prepare.doWork for " + encodingManager.toString() + " ... (" + Helper.getMemInfo() + ")"); - prepare.doWork(); - graph.getProperties().put("prepare.date", formatDateTime(new Date())); - } - graph.getProperties().put("prepare.done", tmpPrepare); - } - - protected void cleanUp() - { - int prev = graph.getNodes(); - PrepareRoutingSubnetworks preparation = new PrepareRoutingSubnetworks(graph, encodingManager); - preparation.setMinNetworkSize(minNetworkSize); - preparation.setMinOnewayNetworkSize(this.minOnewayNetworkSize); - logger.info("start finding subnetworks, " + Helper.getMemInfo()); - preparation.doWork(); - int n = graph.getNodes(); - // calculate remaining subnetworks - int remainingSubnetworks = preparation.findSubnetworks().size(); - logger.info("edges: " + graph.getAllEdges().getMaxId() + ", nodes " + n + ", there were " + preparation.getSubNetworks() - + " subnetworks. removed them => " + (prev - n) + " less nodes. Remaining subnetworks:" + remainingSubnetworks); - } - - protected void flush() - { - logger.info("flushing graph " + graph.toString() + ", details:" + graph.toDetailsString() + ", " + Helper.getMemInfo() + ")"); - graph.flush(); - fullyLoaded = true; - } - - /** - * Releases all associated resources like memory or files. But it does not remove them. To - * remove the files created in graphhopperLocation you have to call clean(). - */ - public void close() - { - if (graph != null) - graph.close(); - - if (locationIndex != null) - locationIndex.close(); - - try - { - lockFactory.forceRemove(fileLockName, true); - } catch (Exception ex) - { - // silently fail - } - } - - /** - * Removes the on-disc routing files. Call only after calling close or before importOrLoad or - * load - */ - public void clean() - { - if (getGraphHopperLocation().isEmpty()) - throw new IllegalStateException("Cannot clean GraphHopper without specified graphHopperLocation"); - - File folder = new File(getGraphHopperLocation()); - Helper.removeDir(folder); - } - - // make sure this is identical to buildDate used in pom.xml - // yyyy-MM-dd'T'HH:mm:ssZ - private String formatDateTime( Date date ) - { - return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(date); - } - - protected void ensureNotLoaded() - { - if (fullyLoaded) - throw new IllegalStateException("No configuration changes are possible after loading the graph"); - } - - protected void ensureWriteAccess() - { - if (!allowWrites) - throw new IllegalStateException("Writes are not allowed!"); - } - - /** - * Returns the current sum of the visited nodes while routing. Mainly for statistic and - * debugging purposes. - */ - public long getVisitedSum() - { - return visitedSum.get(); - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/pair.info b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/pair.info deleted file mode 100755 index 97a7e8c..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#77943/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:77943 -comSha:f693f6c753186c92bcf5b5ab2b9e1ae234da1429 -parentComSha:58d4404e84ac69958f949f33c3eb246dc91bb15f -BuggyFilePath:core/src/main/java/com/graphhopper/GraphHopper.java -FixedFilePath:core/src/main/java/com/graphhopper/GraphHopper.java -StartLineNum:65 -EndLineNum:65 -repoName:graphhopper#graphhopper \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/comMsg.txt b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/comMsg.txt deleted file mode 100755 index 23996b9..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/comMsg.txt +++ /dev/null @@ -1,3 +0,0 @@ -cleanup, removing desription internal variable, since not used - -git-svn-id: http://code.open-bio.org/repos/biojava/biojava-live/trunk@8741 7c6358e6-4a41-0410-a743-a5b2a554c398 \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/diff.diff b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/diff.diff deleted file mode 100755 index d657817..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/diff.diff +++ /dev/null @@ -1,19 +0,0 @@ -diff --git a/biojava3-protmod/src/main/java/org/biojava3/protmod/ProteinModificationImpl.java b/biojava3-protmod/src/main/java/org/biojava3/protmod/ProteinModificationImpl.java -index 7194cc4bd..1456c250c 100644 ---- a/biojava3-protmod/src/main/java/org/biojava3/protmod/ProteinModificationImpl.java -+++ b/biojava3-protmod/src/main/java/org/biojava3/protmod/ProteinModificationImpl.java -@@ -54 +54 @@ implements ProteinModification { -- private final String description; -+ -@@ -243 +243 @@ implements ProteinModification { -- private String description = null; -+ -@@ -281 +281 @@ implements ProteinModification { -- this.description = copyFrom.getDescription(); -+ -@@ -379 +379 @@ implements ProteinModification { -- this.description = description; -+ // description is created on the fly in getDescription -@@ -440 +440 @@ implements ProteinModification { -- this.description = builder.description; -+ \ No newline at end of file diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/new/ProteinModificationImpl.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/new/ProteinModificationImpl.java deleted file mode 100755 index 1456c25..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/new/ProteinModificationImpl.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on May 27, 2010 - * Author: Jianjiong Gao - * - */ - -package org.biojava3.protmod; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -/** - * This class contains information about a specific protein - * modification. - * - * @author Jianjiong Gao - * @since 3.0 - */ -public class ProteinModificationImpl -implements ProteinModification { - - private final String id; - private final ModificationCondition condition; - private final ModificationCategory category; - private final ModificationOccurrenceType occurrenceType; - - private final String pdbccId; - private final String pdbccName; - private final String residId; - private final String residName; - private final String psimodId; - private final String psimodName; - private final String sysName; - private final String formula; - - private final Set keywords; - - public String getId() { - return id; - } - - public String getPdbccId() { - return pdbccId; - } - - public String getPdbccName() { - return pdbccName; - } - - public String getResidId() { - return residId; - } - - public String getResidName() { - return residName; - } - - public String getPsimodId() { - return psimodId; - } - - public String getPsimodName() { - return psimodName; - } - - public String getSystematicName() { - return sysName; - } - - public String getDescription() { - return toString(); - //return description; - } - - public Set getKeywords() { - return keywords; - } - - public ModificationCondition getCondition() { - return condition; - } - - public String getFormula() { - return formula; - } - - public ModificationCategory getCategory() { - return category; - } - - public ModificationOccurrenceType getOccurrenceType() { - return occurrenceType; - } - - @Override - public String toString() { - return printModification(this); -// StringBuilder sb = new StringBuilder(); -// -// sb.append("ID:"+getId()); -// sb.append("\nPDBCC ID:"+getPdbccId()); -// sb.append("\tPDBCC name:"+getPdbccName()); -// sb.append("\nRESID ID:"+getResidId()); -// sb.append("\tRESID name:"+getResidName()); -// sb.append("\nPSI-MOD ID:"+getPsimodId()); -// sb.append("\tPSI-MOD name:"+getPsimodName()); -// sb.append("\nDescription:"+getDescription()); -// sb.append("\nSystematic name:"+getSystematicName()); -// sb.append("\nCategory:"+getCategory().label()); -// sb.append("\nOccurrence type:"+getOccurrenceType().label()); -// sb.append("\nKeywords:"+getKeywords()); -// sb.append("\nCondition:"+getCondition()); -// return sb.toString(); - } - - private String printModification(ProteinModificationImpl mod) { - StringBuilder sb = new StringBuilder(); - - String name = getBestPossibleName(mod); - boolean hasName = true; - if ( name.equals("")) - hasName = false; - sb.append(name); - - Set keywords = mod.getKeywords(); - if (keywords!=null && !keywords.isEmpty()) { - if ( hasName) - sb.append(" ("); - for (String keyword : keywords) { - - sb.append(keyword); - sb.append(", "); - } - sb.delete(sb.length()-2,sb.length()); - } - if ( hasName) - sb.append(")"); - return sb.toString(); - } - - private String getBestPossibleName(ProteinModificationImpl mod) { - - //System.out.println(mod.getResidName() + " : " + mod.getPsimodName() + " : " + mod.getPdbccName() + " : " + mod.getSystematicName()); - - // first: get resid - String resid = mod.getResidId(); - if (resid != null) { - String residname = mod.getResidName(); - if (residname != null) { - return residname; - } - } - - // 2nd: PSI-MOD - - String name = mod.getPsimodName(); - if ( name != null) { - //System.out.println("PSI_MOD name:" + name); - return name; - } - - // 3rd PDB-CC - - String pdbcc = mod.getPdbccName(); - if ( pdbcc != null ) { - //System.out.println("PDBCC name: " + pdbcc); - return pdbcc; - } - - - // no public name know, use the systematic name - - String systematic = mod.getSystematicName(); - if ( systematic != null) { - //System.out.println("SYSTEMATIC NAME: " + mod.getSystematicName()); - return systematic; - } - - - return ""; - - } - - public int hashCode() { - int ret = id.hashCode(); - ret = ret * 31 + category.hashCode(); - return ret; - } - - public boolean equals(Object obj) { - if (!(obj instanceof ProteinModification)) - return false; - - ProteinModification mod = (ProteinModification)obj; - if (!id.equals(mod.getId())) - return false; - - if (category != mod.getCategory()) - return false; - - return true; - } - - - - /** - * Uses Builder pattern to build a ProteinModification. - */ - public static class Builder { - private final String id; - - private ModificationCondition condition; - private ModificationCategory category; - private ModificationOccurrenceType occurrenceType; - - private String pdbccId = null; - private String pdbccName = null; - private String residId = null; - private String residName = null; - private String psimodId = null; - private String psimodName = null; - private String sysName = null; - private String formula = null; - - private Set keywords = new HashSet(); - - /** - * - * @param id - * @param cat - * @param occType - * @param condition - */ - public Builder(final String id, final ModificationCategory cat, - final ModificationOccurrenceType occType, - final ModificationCondition condition) { - if ( id == null) throw new IllegalArgumentException("id == null!"); - if ( cat == null) throw new IllegalArgumentException("cat == null!"); - if ( occType == null) throw new IllegalArgumentException("occType == null!"); - if ( condition == null) throw new IllegalArgumentException("condition == null!"); - - this.id = id; - this.category = cat; - this.occurrenceType = occType; - this.condition = condition; - } - - /** - * Create a Builder from an existing ProteinModification. - * @param copyFrom the ProteinModification to be copied from. - */ - public Builder(final ProteinModification copyFrom) { - this(copyFrom.getId(), copyFrom.getCategory(), copyFrom.getOccurrenceType(), copyFrom.getCondition()); - this.pdbccId = copyFrom.getPdbccId(); - this.pdbccName = copyFrom.getPdbccName(); - this.residId = copyFrom.getResidId(); - this.residName = copyFrom.getResidName(); - this.psimodId = copyFrom.getPsimodId(); - this.psimodName = copyFrom.getPsimodName(); - this.sysName = copyFrom.getSystematicName(); - this.formula = copyFrom.getFormula(); - - this.keywords = new HashSet(copyFrom.getKeywords()); - } - - public Builder setCategory(final ModificationCategory cat) { - if (cat == null) throw new IllegalArgumentException("cat == null!"); - this.category = cat; - return this; - } - - public Builder setOccurrenceType(final ModificationOccurrenceType occType) { - if (occType == null) throw new IllegalArgumentException("occType == null!"); - this.occurrenceType =occType; - return this; - } - - public Builder setCondition(final ModificationCondition condition) { - if (condition == null) throw new IllegalArgumentException("condition == null!"); - this.condition = condition; - return this; - } - - /** - * Set the Protein Data Bank Chemical Component ID. - * @param pdbccId Protein Data Bank Chemical Component ID. - * @return the same Builder object so you can chain setters. - */ - public Builder setPdbccId(final String pdbccId) { - this.pdbccId = pdbccId; - return this; - } - - /** - * Set the Protein Data Bank Chemical Component name. - * @param pdbccName Protein Data Bank Chemical Component name. - * @return the same Builder object so you can chain setters. - */ - public Builder setPdbccName(final String pdbccName) { - this.pdbccName = pdbccName; - return this; - } - - /** - * Set the RESID ID. - * @param residId RESID ID. - * @return the same Builder object so you can chain setters. - */ - public Builder setResidId(final String residId) { - this.residId = residId; - return this; - } - - /** - * Set the RESID name. - * @param residName RESID name. - * @return the same Builder object so you can chain setters. - */ - public Builder setResidName(final String residName) { - this.residName = residName; - return this; - } - - /** - * Set the PSI-MOD ID. - * @param psimodId PSI-MOD ID. - * @return the same Builder object so you can chain setters. - */ - public Builder setPsimodId(final String psimodId) { - this.psimodId = psimodId; - return this; - } - - /** - * Set the PSI-MOD name. - * @param psimodName PSI-MOD name. - * @return the same Builder object so you can chain setters. - */ - public Builder setPsimodName(final String psimodName) { - this.psimodName = psimodName; - return this; - } - - /** - * Set the systematic name. - * @param sysName systematic name. - * @return the same Builder object so you can chain setters. - */ - public Builder setSystematicName(final String sysName) { - this.sysName = sysName; - return this; - } - - /** - * - * @param description description of the modification. - * @return the same Builder object so you can chain setters. - */ - public Builder setDescription(final String description) { - // description is created on the fly in getDescription - return this; - } - - /** - * Add a keyword associate with the PTM. - * @param keyword a keyword. - * @return the same Builder object so you can chain setters. - * @throws IllegalArgumentException if the keyword is null. - */ - public Builder addKeyword(String keyword) { - if (keyword == null) throw new IllegalArgumentException("Keyword cannot be null."); - keywords.add(keyword); - return this; - } - - public Builder addKeywords(Collection keywords) { - if (keywords==null) throw new IllegalArgumentException("Keywords cannot be null."); - - for (String keyword : keywords) { - addKeyword(keyword); - } - - return this; - } - - /** - * Set the residue formula. - * @param formula residue formula. - * @return the same Builder object so you can chain setters. - */ - public Builder setFormula(final String formula) { - this.formula = formula; - return this; - } - - /** - * - * @return build ProteinModification. - */ - public ProteinModificationImpl build() { - return new ProteinModificationImpl(this); - } - } - - /** - * - */ - private ProteinModificationImpl(Builder builder) { - this.id = builder.id; - this.category = builder.category; - this.occurrenceType = builder.occurrenceType; - this.condition = builder.condition; - this.pdbccId = builder.pdbccId; - this.pdbccName = builder.pdbccName; - this.residId = builder.residId; - this.residName = builder.residName; - this.psimodId = builder.psimodId; - this.psimodName = builder.psimodName; - this.sysName = builder.sysName; - this.formula = builder.formula; - - this.keywords = new HashSet(builder.keywords); - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/old/ProteinModificationImpl.java b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/old/ProteinModificationImpl.java deleted file mode 100755 index 7194cc4..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/old/ProteinModificationImpl.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * BioJava development code - * - * This code may be freely distributed and modified under the - * terms of the GNU Lesser General Public Licence. This should - * be distributed with the code. If you do not have a copy, - * see: - * - * http://www.gnu.org/copyleft/lesser.html - * - * Copyright for this code is held jointly by the individual - * authors. These should be listed in @author doc comments. - * - * For more information on the BioJava project and its aims, - * or to join the biojava-l mailing list, visit the home page - * at: - * - * http://www.biojava.org/ - * - * Created on May 27, 2010 - * Author: Jianjiong Gao - * - */ - -package org.biojava3.protmod; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -/** - * This class contains information about a specific protein - * modification. - * - * @author Jianjiong Gao - * @since 3.0 - */ -public class ProteinModificationImpl -implements ProteinModification { - - private final String id; - private final ModificationCondition condition; - private final ModificationCategory category; - private final ModificationOccurrenceType occurrenceType; - - private final String pdbccId; - private final String pdbccName; - private final String residId; - private final String residName; - private final String psimodId; - private final String psimodName; - private final String sysName; - private final String formula; - private final String description; - private final Set keywords; - - public String getId() { - return id; - } - - public String getPdbccId() { - return pdbccId; - } - - public String getPdbccName() { - return pdbccName; - } - - public String getResidId() { - return residId; - } - - public String getResidName() { - return residName; - } - - public String getPsimodId() { - return psimodId; - } - - public String getPsimodName() { - return psimodName; - } - - public String getSystematicName() { - return sysName; - } - - public String getDescription() { - return toString(); - //return description; - } - - public Set getKeywords() { - return keywords; - } - - public ModificationCondition getCondition() { - return condition; - } - - public String getFormula() { - return formula; - } - - public ModificationCategory getCategory() { - return category; - } - - public ModificationOccurrenceType getOccurrenceType() { - return occurrenceType; - } - - @Override - public String toString() { - return printModification(this); -// StringBuilder sb = new StringBuilder(); -// -// sb.append("ID:"+getId()); -// sb.append("\nPDBCC ID:"+getPdbccId()); -// sb.append("\tPDBCC name:"+getPdbccName()); -// sb.append("\nRESID ID:"+getResidId()); -// sb.append("\tRESID name:"+getResidName()); -// sb.append("\nPSI-MOD ID:"+getPsimodId()); -// sb.append("\tPSI-MOD name:"+getPsimodName()); -// sb.append("\nDescription:"+getDescription()); -// sb.append("\nSystematic name:"+getSystematicName()); -// sb.append("\nCategory:"+getCategory().label()); -// sb.append("\nOccurrence type:"+getOccurrenceType().label()); -// sb.append("\nKeywords:"+getKeywords()); -// sb.append("\nCondition:"+getCondition()); -// return sb.toString(); - } - - private String printModification(ProteinModificationImpl mod) { - StringBuilder sb = new StringBuilder(); - - String name = getBestPossibleName(mod); - boolean hasName = true; - if ( name.equals("")) - hasName = false; - sb.append(name); - - Set keywords = mod.getKeywords(); - if (keywords!=null && !keywords.isEmpty()) { - if ( hasName) - sb.append(" ("); - for (String keyword : keywords) { - - sb.append(keyword); - sb.append(", "); - } - sb.delete(sb.length()-2,sb.length()); - } - if ( hasName) - sb.append(")"); - return sb.toString(); - } - - private String getBestPossibleName(ProteinModificationImpl mod) { - - //System.out.println(mod.getResidName() + " : " + mod.getPsimodName() + " : " + mod.getPdbccName() + " : " + mod.getSystematicName()); - - // first: get resid - String resid = mod.getResidId(); - if (resid != null) { - String residname = mod.getResidName(); - if (residname != null) { - return residname; - } - } - - // 2nd: PSI-MOD - - String name = mod.getPsimodName(); - if ( name != null) { - //System.out.println("PSI_MOD name:" + name); - return name; - } - - // 3rd PDB-CC - - String pdbcc = mod.getPdbccName(); - if ( pdbcc != null ) { - //System.out.println("PDBCC name: " + pdbcc); - return pdbcc; - } - - - // no public name know, use the systematic name - - String systematic = mod.getSystematicName(); - if ( systematic != null) { - //System.out.println("SYSTEMATIC NAME: " + mod.getSystematicName()); - return systematic; - } - - - return ""; - - } - - public int hashCode() { - int ret = id.hashCode(); - ret = ret * 31 + category.hashCode(); - return ret; - } - - public boolean equals(Object obj) { - if (!(obj instanceof ProteinModification)) - return false; - - ProteinModification mod = (ProteinModification)obj; - if (!id.equals(mod.getId())) - return false; - - if (category != mod.getCategory()) - return false; - - return true; - } - - - - /** - * Uses Builder pattern to build a ProteinModification. - */ - public static class Builder { - private final String id; - - private ModificationCondition condition; - private ModificationCategory category; - private ModificationOccurrenceType occurrenceType; - - private String pdbccId = null; - private String pdbccName = null; - private String residId = null; - private String residName = null; - private String psimodId = null; - private String psimodName = null; - private String sysName = null; - private String formula = null; - private String description = null; - private Set keywords = new HashSet(); - - /** - * - * @param id - * @param cat - * @param occType - * @param condition - */ - public Builder(final String id, final ModificationCategory cat, - final ModificationOccurrenceType occType, - final ModificationCondition condition) { - if ( id == null) throw new IllegalArgumentException("id == null!"); - if ( cat == null) throw new IllegalArgumentException("cat == null!"); - if ( occType == null) throw new IllegalArgumentException("occType == null!"); - if ( condition == null) throw new IllegalArgumentException("condition == null!"); - - this.id = id; - this.category = cat; - this.occurrenceType = occType; - this.condition = condition; - } - - /** - * Create a Builder from an existing ProteinModification. - * @param copyFrom the ProteinModification to be copied from. - */ - public Builder(final ProteinModification copyFrom) { - this(copyFrom.getId(), copyFrom.getCategory(), copyFrom.getOccurrenceType(), copyFrom.getCondition()); - this.pdbccId = copyFrom.getPdbccId(); - this.pdbccName = copyFrom.getPdbccName(); - this.residId = copyFrom.getResidId(); - this.residName = copyFrom.getResidName(); - this.psimodId = copyFrom.getPsimodId(); - this.psimodName = copyFrom.getPsimodName(); - this.sysName = copyFrom.getSystematicName(); - this.formula = copyFrom.getFormula(); - this.description = copyFrom.getDescription(); - this.keywords = new HashSet(copyFrom.getKeywords()); - } - - public Builder setCategory(final ModificationCategory cat) { - if (cat == null) throw new IllegalArgumentException("cat == null!"); - this.category = cat; - return this; - } - - public Builder setOccurrenceType(final ModificationOccurrenceType occType) { - if (occType == null) throw new IllegalArgumentException("occType == null!"); - this.occurrenceType =occType; - return this; - } - - public Builder setCondition(final ModificationCondition condition) { - if (condition == null) throw new IllegalArgumentException("condition == null!"); - this.condition = condition; - return this; - } - - /** - * Set the Protein Data Bank Chemical Component ID. - * @param pdbccId Protein Data Bank Chemical Component ID. - * @return the same Builder object so you can chain setters. - */ - public Builder setPdbccId(final String pdbccId) { - this.pdbccId = pdbccId; - return this; - } - - /** - * Set the Protein Data Bank Chemical Component name. - * @param pdbccName Protein Data Bank Chemical Component name. - * @return the same Builder object so you can chain setters. - */ - public Builder setPdbccName(final String pdbccName) { - this.pdbccName = pdbccName; - return this; - } - - /** - * Set the RESID ID. - * @param residId RESID ID. - * @return the same Builder object so you can chain setters. - */ - public Builder setResidId(final String residId) { - this.residId = residId; - return this; - } - - /** - * Set the RESID name. - * @param residName RESID name. - * @return the same Builder object so you can chain setters. - */ - public Builder setResidName(final String residName) { - this.residName = residName; - return this; - } - - /** - * Set the PSI-MOD ID. - * @param psimodId PSI-MOD ID. - * @return the same Builder object so you can chain setters. - */ - public Builder setPsimodId(final String psimodId) { - this.psimodId = psimodId; - return this; - } - - /** - * Set the PSI-MOD name. - * @param psimodName PSI-MOD name. - * @return the same Builder object so you can chain setters. - */ - public Builder setPsimodName(final String psimodName) { - this.psimodName = psimodName; - return this; - } - - /** - * Set the systematic name. - * @param sysName systematic name. - * @return the same Builder object so you can chain setters. - */ - public Builder setSystematicName(final String sysName) { - this.sysName = sysName; - return this; - } - - /** - * - * @param description description of the modification. - * @return the same Builder object so you can chain setters. - */ - public Builder setDescription(final String description) { - this.description = description; - return this; - } - - /** - * Add a keyword associate with the PTM. - * @param keyword a keyword. - * @return the same Builder object so you can chain setters. - * @throws IllegalArgumentException if the keyword is null. - */ - public Builder addKeyword(String keyword) { - if (keyword == null) throw new IllegalArgumentException("Keyword cannot be null."); - keywords.add(keyword); - return this; - } - - public Builder addKeywords(Collection keywords) { - if (keywords==null) throw new IllegalArgumentException("Keywords cannot be null."); - - for (String keyword : keywords) { - addKeyword(keyword); - } - - return this; - } - - /** - * Set the residue formula. - * @param formula residue formula. - * @return the same Builder object so you can chain setters. - */ - public Builder setFormula(final String formula) { - this.formula = formula; - return this; - } - - /** - * - * @return build ProteinModification. - */ - public ProteinModificationImpl build() { - return new ProteinModificationImpl(this); - } - } - - /** - * - */ - private ProteinModificationImpl(Builder builder) { - this.id = builder.id; - this.category = builder.category; - this.occurrenceType = builder.occurrenceType; - this.condition = builder.condition; - this.pdbccId = builder.pdbccId; - this.pdbccName = builder.pdbccName; - this.residId = builder.residId; - this.residName = builder.residName; - this.psimodId = builder.psimodId; - this.psimodName = builder.psimodName; - this.sysName = builder.sysName; - this.formula = builder.formula; - this.description = builder.description; - this.keywords = new HashSet(builder.keywords); - } -} diff --git a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/pair.info b/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/pair.info deleted file mode 100755 index d8c2f87..0000000 --- a/All/FindBugs-URF_UNREAD_FIELD/FBViolation#96/pair.info +++ /dev/null @@ -1,8 +0,0 @@ -Id:96 -comSha:a591c7987e0b576d38dac9239dcdeadd8812338c -parentComSha:004d5e65de1e40f4366b80d1592930f4fe5fdf15 -BuggyFilePath:biojava3-protmod/src/main/java/org/biojava3/protmod/ProteinModificationImpl.java -FixedFilePath:biojava3-protmod/src/main/java/org/biojava3/protmod/ProteinModificationImpl.java -StartLineNum:440 -EndLineNum:440 -repoName:biojava#biojava \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#0/comMsg.txt b/All/Genesis-NP/Genesis#0/comMsg.txt deleted file mode 100755 index c031b9c..0000000 --- a/All/Genesis-NP/Genesis#0/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -PLANNER-560 don't let bestUninitializedVariableCount default to 0, because a race condition can grab it before it's initialized upon solver start. (it should have really been an Integer type, so it defaulted to null and we had NPE's, but anyway we're cleaning this up in 405 anyway) diff --git a/All/Genesis-NP/Genesis#0/diff.diff b/All/Genesis-NP/Genesis#0/diff.diff deleted file mode 100755 index b4fd0f3..0000000 --- a/All/Genesis-NP/Genesis#0/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/optaplanner-core/src/main/java/org/optaplanner/core/impl/solver/scope/DefaultSolverScope.java b/optaplanner-core/src/main/java/org/optaplanner/core/impl/solver/scope/DefaultSolverScope.java -index 42ea34b..a264e00 100644 ---- a/optaplanner-core/src/main/java/org/optaplanner/core/impl/solver/scope/DefaultSolverScope.java -+++ b/optaplanner-core/src/main/java/org/optaplanner/core/impl/solver/scope/DefaultSolverScope.java -@@ -48 +48 @@ public class DefaultSolverScope { -- protected volatile int bestUninitializedVariableCount; // TODO remove me by folding me into bestSolution.getScore(): https://issues.jboss.org/browse/PLANNER-405 -+ protected volatile int bestUninitializedVariableCount = Integer.MAX_VALUE; // TODO remove me by folding me into bestSolution.getScore(): https://issues.jboss.org/browse/PLANNER-405 diff --git a/All/Genesis-NP/Genesis#0/new/DefaultSolverScope.java b/All/Genesis-NP/Genesis#0/new/DefaultSolverScope.java deleted file mode 100755 index a264e00..0000000 --- a/All/Genesis-NP/Genesis#0/new/DefaultSolverScope.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright 2011 Red Hat, Inc. and/or its affiliates. - * - * 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.optaplanner.core.impl.solver.scope; - -import java.util.List; -import java.util.Random; - -import org.optaplanner.core.api.domain.solution.PlanningSolution; -import org.optaplanner.core.api.score.Score; -import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor; -import org.optaplanner.core.impl.score.ScoreUtils; -import org.optaplanner.core.impl.score.definition.ScoreDefinition; -import org.optaplanner.core.impl.score.director.InnerScoreDirector; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @param the solution type, the class with the {@link PlanningSolution} annotation - */ -public class DefaultSolverScope { - - protected final transient Logger logger = LoggerFactory.getLogger(getClass()); - - protected int startingSolverCount; - protected Random workingRandom; - protected InnerScoreDirector scoreDirector; - - protected Long startingSystemTimeMillis; - protected Long endingSystemTimeMillis; - - protected Score startingInitializedScore; // TODO after initialization => ambiguous with solve()'s planningProblem - - protected volatile Solution_ bestSolution; - protected volatile int bestUninitializedVariableCount = Integer.MAX_VALUE; // TODO remove me by folding me into bestSolution.getScore(): https://issues.jboss.org/browse/PLANNER-405 - protected volatile Score bestScore; // TODO remove me by folding me into bestSolution.getScore(): https://issues.jboss.org/browse/PLANNER-405 - protected Long bestSolutionTimeMillis; - - - public int getStartingSolverCount() { - return startingSolverCount; - } - - public void setStartingSolverCount(int startingSolverCount) { - this.startingSolverCount = startingSolverCount; - } - - public Random getWorkingRandom() { - return workingRandom; - } - - public void setWorkingRandom(Random workingRandom) { - this.workingRandom = workingRandom; - } - - public InnerScoreDirector getScoreDirector() { - return scoreDirector; - } - - public void setScoreDirector(InnerScoreDirector scoreDirector) { - this.scoreDirector = scoreDirector; - } - - public Long getStartingSystemTimeMillis() { - return startingSystemTimeMillis; - } - - public void setStartingSystemTimeMillis(Long startingSystemTimeMillis) { - this.startingSystemTimeMillis = startingSystemTimeMillis; - } - - public Long getEndingSystemTimeMillis() { - return endingSystemTimeMillis; - } - - public void setEndingSystemTimeMillis(Long endingSystemTimeMillis) { - this.endingSystemTimeMillis = endingSystemTimeMillis; - } - - public SolutionDescriptor getSolutionDescriptor() { - return scoreDirector.getSolutionDescriptor(); - } - - public ScoreDefinition getScoreDefinition() { - return scoreDirector.getScoreDefinition(); - } - - public Solution_ getWorkingSolution() { - return scoreDirector.getWorkingSolution(); - } - - public int getWorkingEntityCount() { - return scoreDirector.getWorkingEntityCount(); - } - - public List getWorkingEntityList() { - return scoreDirector.getWorkingEntityList(); - } - - public int getWorkingValueCount() { - return scoreDirector.getWorkingValueCount(); - } - - public Score calculateScore() { - return scoreDirector.calculateScore(); - } - - public void assertExpectedWorkingScore(Score expectedWorkingScore, Object completedAction) { - scoreDirector.assertExpectedWorkingScore(expectedWorkingScore, completedAction); - } - - public void assertWorkingScoreFromScratch(Score workingScore, Object completedAction) { - scoreDirector.assertWorkingScoreFromScratch(workingScore, completedAction); - } - - public void assertScoreFromScratch(Solution_ solution) { - scoreDirector.getScoreDirectorFactory().assertScoreFromScratch(solution); - } - - public Score getStartingInitializedScore() { - return startingInitializedScore; - } - - public void setStartingInitializedScore(Score startingInitializedScore) { - this.startingInitializedScore = startingInitializedScore; - } - - public long getCalculateCount() { - return scoreDirector.getCalculateCount(); - } - - public Solution_ getBestSolution() { - return bestSolution; - } - - /** - * The {@link PlanningSolution best solution} must never be the same instance - * as the {@link PlanningSolution working solution}, it should be a (un)changed clone. - * @param bestSolution never null - */ - public void setBestSolution(Solution_ bestSolution) { - this.bestSolution = bestSolution; - } - - public int getBestUninitializedVariableCount() { - return bestUninitializedVariableCount; - } - - public void setBestUninitializedVariableCount(int bestUninitializedVariableCount) { - if (bestUninitializedVariableCount < 0) { - throw new IllegalArgumentException("The bestUninitializedVariableCount (" - + bestUninitializedVariableCount + ") cannot be negative."); - } - this.bestUninitializedVariableCount = bestUninitializedVariableCount; - } - - public Score getBestScore() { - return bestScore; - } - - public void setBestScore(Score bestScore) { - this.bestScore = bestScore; - } - - public Long getBestSolutionTimeMillis() { - return bestSolutionTimeMillis; - } - - public void setBestSolutionTimeMillis(Long bestSolutionTimeMillis) { - this.bestSolutionTimeMillis = bestSolutionTimeMillis; - } - - // ************************************************************************ - // Calculated methods - // ************************************************************************ - - public boolean isBestSolutionInitialized() { - return bestUninitializedVariableCount == 0; - } - - public long calculateTimeMillisSpent() { - long now = System.currentTimeMillis(); - return now - startingSystemTimeMillis; - } - - public void setWorkingSolutionFromBestSolution() { - // The workingSolution must never be the same instance as the bestSolution. - scoreDirector.setWorkingSolution(scoreDirector.cloneSolution(bestSolution)); - } - - public String getBestScoreWithUninitializedPrefix() { - return ScoreUtils.getScoreWithUninitializedPrefix(bestUninitializedVariableCount, bestScore); - } - -} diff --git a/All/Genesis-NP/Genesis#0/old/DefaultSolverScope.java b/All/Genesis-NP/Genesis#0/old/DefaultSolverScope.java deleted file mode 100755 index 42ea34b..0000000 --- a/All/Genesis-NP/Genesis#0/old/DefaultSolverScope.java +++ /dev/null @@ -1,208 +0,0 @@ -/* - * Copyright 2011 Red Hat, Inc. and/or its affiliates. - * - * 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.optaplanner.core.impl.solver.scope; - -import java.util.List; -import java.util.Random; - -import org.optaplanner.core.api.domain.solution.PlanningSolution; -import org.optaplanner.core.api.score.Score; -import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor; -import org.optaplanner.core.impl.score.ScoreUtils; -import org.optaplanner.core.impl.score.definition.ScoreDefinition; -import org.optaplanner.core.impl.score.director.InnerScoreDirector; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @param the solution type, the class with the {@link PlanningSolution} annotation - */ -public class DefaultSolverScope { - - protected final transient Logger logger = LoggerFactory.getLogger(getClass()); - - protected int startingSolverCount; - protected Random workingRandom; - protected InnerScoreDirector scoreDirector; - - protected Long startingSystemTimeMillis; - protected Long endingSystemTimeMillis; - - protected Score startingInitializedScore; // TODO after initialization => ambiguous with solve()'s planningProblem - - protected volatile Solution_ bestSolution; - protected volatile int bestUninitializedVariableCount; // TODO remove me by folding me into bestSolution.getScore(): https://issues.jboss.org/browse/PLANNER-405 - protected volatile Score bestScore; // TODO remove me by folding me into bestSolution.getScore(): https://issues.jboss.org/browse/PLANNER-405 - protected Long bestSolutionTimeMillis; - - - public int getStartingSolverCount() { - return startingSolverCount; - } - - public void setStartingSolverCount(int startingSolverCount) { - this.startingSolverCount = startingSolverCount; - } - - public Random getWorkingRandom() { - return workingRandom; - } - - public void setWorkingRandom(Random workingRandom) { - this.workingRandom = workingRandom; - } - - public InnerScoreDirector getScoreDirector() { - return scoreDirector; - } - - public void setScoreDirector(InnerScoreDirector scoreDirector) { - this.scoreDirector = scoreDirector; - } - - public Long getStartingSystemTimeMillis() { - return startingSystemTimeMillis; - } - - public void setStartingSystemTimeMillis(Long startingSystemTimeMillis) { - this.startingSystemTimeMillis = startingSystemTimeMillis; - } - - public Long getEndingSystemTimeMillis() { - return endingSystemTimeMillis; - } - - public void setEndingSystemTimeMillis(Long endingSystemTimeMillis) { - this.endingSystemTimeMillis = endingSystemTimeMillis; - } - - public SolutionDescriptor getSolutionDescriptor() { - return scoreDirector.getSolutionDescriptor(); - } - - public ScoreDefinition getScoreDefinition() { - return scoreDirector.getScoreDefinition(); - } - - public Solution_ getWorkingSolution() { - return scoreDirector.getWorkingSolution(); - } - - public int getWorkingEntityCount() { - return scoreDirector.getWorkingEntityCount(); - } - - public List getWorkingEntityList() { - return scoreDirector.getWorkingEntityList(); - } - - public int getWorkingValueCount() { - return scoreDirector.getWorkingValueCount(); - } - - public Score calculateScore() { - return scoreDirector.calculateScore(); - } - - public void assertExpectedWorkingScore(Score expectedWorkingScore, Object completedAction) { - scoreDirector.assertExpectedWorkingScore(expectedWorkingScore, completedAction); - } - - public void assertWorkingScoreFromScratch(Score workingScore, Object completedAction) { - scoreDirector.assertWorkingScoreFromScratch(workingScore, completedAction); - } - - public void assertScoreFromScratch(Solution_ solution) { - scoreDirector.getScoreDirectorFactory().assertScoreFromScratch(solution); - } - - public Score getStartingInitializedScore() { - return startingInitializedScore; - } - - public void setStartingInitializedScore(Score startingInitializedScore) { - this.startingInitializedScore = startingInitializedScore; - } - - public long getCalculateCount() { - return scoreDirector.getCalculateCount(); - } - - public Solution_ getBestSolution() { - return bestSolution; - } - - /** - * The {@link PlanningSolution best solution} must never be the same instance - * as the {@link PlanningSolution working solution}, it should be a (un)changed clone. - * @param bestSolution never null - */ - public void setBestSolution(Solution_ bestSolution) { - this.bestSolution = bestSolution; - } - - public int getBestUninitializedVariableCount() { - return bestUninitializedVariableCount; - } - - public void setBestUninitializedVariableCount(int bestUninitializedVariableCount) { - if (bestUninitializedVariableCount < 0) { - throw new IllegalArgumentException("The bestUninitializedVariableCount (" - + bestUninitializedVariableCount + ") cannot be negative."); - } - this.bestUninitializedVariableCount = bestUninitializedVariableCount; - } - - public Score getBestScore() { - return bestScore; - } - - public void setBestScore(Score bestScore) { - this.bestScore = bestScore; - } - - public Long getBestSolutionTimeMillis() { - return bestSolutionTimeMillis; - } - - public void setBestSolutionTimeMillis(Long bestSolutionTimeMillis) { - this.bestSolutionTimeMillis = bestSolutionTimeMillis; - } - - // ************************************************************************ - // Calculated methods - // ************************************************************************ - - public boolean isBestSolutionInitialized() { - return bestUninitializedVariableCount == 0; - } - - public long calculateTimeMillisSpent() { - long now = System.currentTimeMillis(); - return now - startingSystemTimeMillis; - } - - public void setWorkingSolutionFromBestSolution() { - // The workingSolution must never be the same instance as the bestSolution. - scoreDirector.setWorkingSolution(scoreDirector.cloneSolution(bestSolution)); - } - - public String getBestScoreWithUninitializedPrefix() { - return ScoreUtils.getScoreWithUninitializedPrefix(bestUninitializedVariableCount, bestScore); - } - -} diff --git a/All/Genesis-NP/Genesis#0/pair.info b/All/Genesis-NP/Genesis#0/pair.info deleted file mode 100755 index 5a02bbc..0000000 --- a/All/Genesis-NP/Genesis#0/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:0 -SATName:Genesis -modifiedFPath:optaplanner-core/src/main/java/org/optaplanner/core/impl/solver/scope/DefaultSolverScope.java -comSha:ae87505c4ba10d055e9f1146048983a9d7762342 -parentComSha:ae87505c4ba10d055e9f1146048983a9d7762342^1 -githubUrl:https://github.com/droolsjbpm/optaplanner -repoName:droolsjbpm#optaplanner \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#110/comMsg.txt b/All/Genesis-NP/Genesis#110/comMsg.txt deleted file mode 100755 index c8455be..0000000 --- a/All/Genesis-NP/Genesis#110/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -WW-4456 - Got NPE when File Upload Limitation exceeds in portal env. diff --git a/All/Genesis-NP/Genesis#110/diff.diff b/All/Genesis-NP/Genesis#110/diff.diff deleted file mode 100755 index 0660f08..0000000 --- a/All/Genesis-NP/Genesis#110/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaMultiPartRequest.java b/core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaMultiPartRequest.java -index e9ac67f..643d73d 100644 ---- a/core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaMultiPartRequest.java -+++ b/core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaMultiPartRequest.java -@@ -86 +86 @@ public class JakartaMultiPartRequest implements MultiPartRequest { -- } catch (FileUploadBase.SizeLimitExceededException e) { -+ } catch (FileUploadException e) { -@@ -88 +88,9 @@ public class JakartaMultiPartRequest implements MultiPartRequest { -- String errorMessage = buildErrorMessage(e, new Object[]{e.getPermittedSize(), e.getActualSize()}); -+ String errorMessage = null; -+ -+ if(e instanceof FileUploadBase.SizeLimitExceededException) { -+ FileUploadBase.SizeLimitExceededException ex = (FileUploadBase.SizeLimitExceededException) e; -+ errorMessage = buildErrorMessage(e, new Object[]{ex.getPermittedSize(), ex.getActualSize()}); -+ } else { -+ errorMessage = buildErrorMessage(e, new Object[]{}); -+ } -+ diff --git a/All/Genesis-NP/Genesis#110/new/JakartaMultiPartRequest.java b/All/Genesis-NP/Genesis#110/new/JakartaMultiPartRequest.java deleted file mode 100755 index 643d73d..0000000 --- a/All/Genesis-NP/Genesis#110/new/JakartaMultiPartRequest.java +++ /dev/null @@ -1,390 +0,0 @@ -/* - * $Id$ - * - * 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.struts2.dispatcher.multipart; - -import com.opensymphony.xwork2.LocaleProvider; -import com.opensymphony.xwork2.inject.Inject; -import com.opensymphony.xwork2.util.LocalizedTextUtil; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileUploadBase; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.RequestContext; -import org.apache.commons.fileupload.disk.DiskFileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.struts2.StrutsConstants; - -import javax.servlet.http.HttpServletRequest; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.*; - -/** - * Multipart form data request adapter for Jakarta Commons Fileupload package. - */ -public class JakartaMultiPartRequest implements MultiPartRequest { - - static final Logger LOG = LogManager.getLogger(JakartaMultiPartRequest.class); - - // maps parameter name -> List of FileItem objects - protected Map> files = new HashMap<>(); - - // maps parameter name -> List of param values - protected Map> params = new HashMap<>(); - - // any errors while processing this request - protected List errors = new ArrayList<>(); - - protected long maxSize; - private Locale defaultLocale = Locale.ENGLISH; - - @Inject(StrutsConstants.STRUTS_MULTIPART_MAXSIZE) - public void setMaxSize(String maxSize) { - this.maxSize = Long.parseLong(maxSize); - } - - @Inject - public void setLocaleProvider(LocaleProvider provider) { - defaultLocale = provider.getLocale(); - } - - /** - * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's - * multipart classes (see class description). - * - * @param saveDir the directory to save off the file - * @param request the request containing the multipart - * @throws java.io.IOException is thrown if encoding fails. - */ - public void parse(HttpServletRequest request, String saveDir) throws IOException { - try { - setLocale(request); - processUpload(request, saveDir); - } catch (FileUploadException e) { - LOG.warn("Request exceeded size limit!", e); - String errorMessage = null; - - if(e instanceof FileUploadBase.SizeLimitExceededException) { - FileUploadBase.SizeLimitExceededException ex = (FileUploadBase.SizeLimitExceededException) e; - errorMessage = buildErrorMessage(e, new Object[]{ex.getPermittedSize(), ex.getActualSize()}); - } else { - errorMessage = buildErrorMessage(e, new Object[]{}); - } - - if (!errors.contains(errorMessage)) { - errors.add(errorMessage); - } - } catch (Exception e) { - LOG.warn("Unable to parse request", e); - String errorMessage = buildErrorMessage(e, new Object[]{}); - if (!errors.contains(errorMessage)) { - errors.add(errorMessage); - } - } - } - - protected void setLocale(HttpServletRequest request) { - if (defaultLocale == null) { - defaultLocale = request.getLocale(); - } - } - - protected String buildErrorMessage(Throwable e, Object[] args) { - String errorKey = "struts.messages.upload.error." + e.getClass().getSimpleName(); - LOG.debug("Preparing error message for key: [{}]", errorKey); - return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args); - } - - protected void processUpload(HttpServletRequest request, String saveDir) throws FileUploadException, UnsupportedEncodingException { - for (FileItem item : parseRequest(request, saveDir)) { - LOG.debug("Found file item: [{}]", item.getFieldName()); - if (item.isFormField()) { - processNormalFormField(item, request.getCharacterEncoding()); - } else { - processFileField(item); - } - } - } - - protected void processFileField(FileItem item) { - LOG.debug("Item is a file upload"); - - // Skip file uploads that don't have a file name - meaning that no file was selected. - if (item.getName() == null || item.getName().trim().length() < 1) { - LOG.debug("No file has been uploaded for the field: {}", item.getFieldName()); - return; - } - - List values; - if (files.get(item.getFieldName()) != null) { - values = files.get(item.getFieldName()); - } else { - values = new ArrayList<>(); - } - - values.add(item); - files.put(item.getFieldName(), values); - } - - protected void processNormalFormField(FileItem item, String charset) throws UnsupportedEncodingException { - LOG.debug("Item is a normal form field"); - - List values; - if (params.get(item.getFieldName()) != null) { - values = params.get(item.getFieldName()); - } else { - values = new ArrayList<>(); - } - - // note: see http://jira.opensymphony.com/browse/WW-633 - // basically, in some cases the charset may be null, so - // we're just going to try to "other" method (no idea if this - // will work) - if (charset != null) { - values.add(item.getString(charset)); - } else { - values.add(item.getString()); - } - params.put(item.getFieldName(), values); - item.delete(); - } - - protected List parseRequest(HttpServletRequest servletRequest, String saveDir) throws FileUploadException { - DiskFileItemFactory fac = createDiskFileItemFactory(saveDir); - ServletFileUpload upload = createServletFileUpload(fac); - return upload.parseRequest(createRequestContext(servletRequest)); - } - - protected ServletFileUpload createServletFileUpload(DiskFileItemFactory fac) { - ServletFileUpload upload = new ServletFileUpload(fac); - upload.setSizeMax(maxSize); - return upload; - } - - protected DiskFileItemFactory createDiskFileItemFactory(String saveDir) { - DiskFileItemFactory fac = new DiskFileItemFactory(); - // Make sure that the data is written to file - fac.setSizeThreshold(0); - if (saveDir != null) { - fac.setRepository(new File(saveDir)); - } - return fac; - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFileParameterNames() - */ - public Enumeration getFileParameterNames() { - return Collections.enumeration(files.keySet()); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getContentType(java.lang.String) - */ - public String[] getContentType(String fieldName) { - List items = files.get(fieldName); - - if (items == null) { - return null; - } - - List contentTypes = new ArrayList<>(items.size()); - for (FileItem fileItem : items) { - contentTypes.add(fileItem.getContentType()); - } - - return contentTypes.toArray(new String[contentTypes.size()]); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFile(java.lang.String) - */ - public File[] getFile(String fieldName) { - List items = files.get(fieldName); - - if (items == null) { - return null; - } - - List fileList = new ArrayList<>(items.size()); - for (FileItem fileItem : items) { - File storeLocation = ((DiskFileItem) fileItem).getStoreLocation(); - if (fileItem.isInMemory() && storeLocation != null && !storeLocation.exists()) { - try { - storeLocation.createNewFile(); - } catch (IOException e) { - LOG.error("Cannot write uploaded empty file to disk: {}", storeLocation.getAbsolutePath(), e); - } - } - fileList.add(storeLocation); - } - - return fileList.toArray(new File[fileList.size()]); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFileNames(java.lang.String) - */ - public String[] getFileNames(String fieldName) { - List items = files.get(fieldName); - - if (items == null) { - return null; - } - - List fileNames = new ArrayList<>(items.size()); - for (FileItem fileItem : items) { - fileNames.add(getCanonicalName(fileItem.getName())); - } - - return fileNames.toArray(new String[fileNames.size()]); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFilesystemName(java.lang.String) - */ - public String[] getFilesystemName(String fieldName) { - List items = files.get(fieldName); - - if (items == null) { - return null; - } - - List fileNames = new ArrayList<>(items.size()); - for (FileItem fileItem : items) { - fileNames.add(((DiskFileItem) fileItem).getStoreLocation().getName()); - } - - return fileNames.toArray(new String[fileNames.size()]); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameter(java.lang.String) - */ - public String getParameter(String name) { - List v = params.get(name); - if (v != null && v.size() > 0) { - return v.get(0); - } - - return null; - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameterNames() - */ - public Enumeration getParameterNames() { - return Collections.enumeration(params.keySet()); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameterValues(java.lang.String) - */ - public String[] getParameterValues(String name) { - List v = params.get(name); - if (v != null && v.size() > 0) { - return v.toArray(new String[v.size()]); - } - - return null; - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getErrors() - */ - public List getErrors() { - return errors; - } - - /** - * Returns the canonical name of the given file. - * - * @param filename the given file - * @return the canonical name of the given file - */ - private String getCanonicalName(String filename) { - int forwardSlash = filename.lastIndexOf("/"); - int backwardSlash = filename.lastIndexOf("\\"); - if (forwardSlash != -1 && forwardSlash > backwardSlash) { - filename = filename.substring(forwardSlash + 1, filename.length()); - } else if (backwardSlash != -1 && backwardSlash >= forwardSlash) { - filename = filename.substring(backwardSlash + 1, filename.length()); - } - - return filename; - } - - /** - * Creates a RequestContext needed by Jakarta Commons Upload. - * - * @param req the request. - * @return a new request context. - */ - protected RequestContext createRequestContext(final HttpServletRequest req) { - return new RequestContext() { - public String getCharacterEncoding() { - return req.getCharacterEncoding(); - } - - public String getContentType() { - return req.getContentType(); - } - - public int getContentLength() { - return req.getContentLength(); - } - - public InputStream getInputStream() throws IOException { - InputStream in = req.getInputStream(); - if (in == null) { - throw new IOException("Missing content in the request"); - } - return req.getInputStream(); - } - }; - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#cleanUp() - */ - public void cleanUp() { - Set names = files.keySet(); - for (String name : names) { - List items = files.get(name); - for (FileItem item : items) { - if (LOG.isDebugEnabled()) { - String msg = LocalizedTextUtil.findText(this.getClass(), "struts.messages.removing.file", - Locale.ENGLISH, "no.message.found", new Object[]{name, item}); - LOG.debug(msg); - } - if (!item.isInMemory()) { - item.delete(); - } - } - } - } - -} diff --git a/All/Genesis-NP/Genesis#110/old/JakartaMultiPartRequest.java b/All/Genesis-NP/Genesis#110/old/JakartaMultiPartRequest.java deleted file mode 100755 index e9ac67f..0000000 --- a/All/Genesis-NP/Genesis#110/old/JakartaMultiPartRequest.java +++ /dev/null @@ -1,382 +0,0 @@ -/* - * $Id$ - * - * 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.struts2.dispatcher.multipart; - -import com.opensymphony.xwork2.LocaleProvider; -import com.opensymphony.xwork2.inject.Inject; -import com.opensymphony.xwork2.util.LocalizedTextUtil; -import org.apache.commons.fileupload.FileItem; -import org.apache.commons.fileupload.FileUploadBase; -import org.apache.commons.fileupload.FileUploadException; -import org.apache.commons.fileupload.RequestContext; -import org.apache.commons.fileupload.disk.DiskFileItem; -import org.apache.commons.fileupload.disk.DiskFileItemFactory; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.logging.log4j.LogManager; -import org.apache.logging.log4j.Logger; -import org.apache.struts2.StrutsConstants; - -import javax.servlet.http.HttpServletRequest; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.util.*; - -/** - * Multipart form data request adapter for Jakarta Commons Fileupload package. - */ -public class JakartaMultiPartRequest implements MultiPartRequest { - - static final Logger LOG = LogManager.getLogger(JakartaMultiPartRequest.class); - - // maps parameter name -> List of FileItem objects - protected Map> files = new HashMap<>(); - - // maps parameter name -> List of param values - protected Map> params = new HashMap<>(); - - // any errors while processing this request - protected List errors = new ArrayList<>(); - - protected long maxSize; - private Locale defaultLocale = Locale.ENGLISH; - - @Inject(StrutsConstants.STRUTS_MULTIPART_MAXSIZE) - public void setMaxSize(String maxSize) { - this.maxSize = Long.parseLong(maxSize); - } - - @Inject - public void setLocaleProvider(LocaleProvider provider) { - defaultLocale = provider.getLocale(); - } - - /** - * Creates a new request wrapper to handle multi-part data using methods adapted from Jason Pell's - * multipart classes (see class description). - * - * @param saveDir the directory to save off the file - * @param request the request containing the multipart - * @throws java.io.IOException is thrown if encoding fails. - */ - public void parse(HttpServletRequest request, String saveDir) throws IOException { - try { - setLocale(request); - processUpload(request, saveDir); - } catch (FileUploadBase.SizeLimitExceededException e) { - LOG.warn("Request exceeded size limit!", e); - String errorMessage = buildErrorMessage(e, new Object[]{e.getPermittedSize(), e.getActualSize()}); - if (!errors.contains(errorMessage)) { - errors.add(errorMessage); - } - } catch (Exception e) { - LOG.warn("Unable to parse request", e); - String errorMessage = buildErrorMessage(e, new Object[]{}); - if (!errors.contains(errorMessage)) { - errors.add(errorMessage); - } - } - } - - protected void setLocale(HttpServletRequest request) { - if (defaultLocale == null) { - defaultLocale = request.getLocale(); - } - } - - protected String buildErrorMessage(Throwable e, Object[] args) { - String errorKey = "struts.messages.upload.error." + e.getClass().getSimpleName(); - LOG.debug("Preparing error message for key: [{}]", errorKey); - return LocalizedTextUtil.findText(this.getClass(), errorKey, defaultLocale, e.getMessage(), args); - } - - protected void processUpload(HttpServletRequest request, String saveDir) throws FileUploadException, UnsupportedEncodingException { - for (FileItem item : parseRequest(request, saveDir)) { - LOG.debug("Found file item: [{}]", item.getFieldName()); - if (item.isFormField()) { - processNormalFormField(item, request.getCharacterEncoding()); - } else { - processFileField(item); - } - } - } - - protected void processFileField(FileItem item) { - LOG.debug("Item is a file upload"); - - // Skip file uploads that don't have a file name - meaning that no file was selected. - if (item.getName() == null || item.getName().trim().length() < 1) { - LOG.debug("No file has been uploaded for the field: {}", item.getFieldName()); - return; - } - - List values; - if (files.get(item.getFieldName()) != null) { - values = files.get(item.getFieldName()); - } else { - values = new ArrayList<>(); - } - - values.add(item); - files.put(item.getFieldName(), values); - } - - protected void processNormalFormField(FileItem item, String charset) throws UnsupportedEncodingException { - LOG.debug("Item is a normal form field"); - - List values; - if (params.get(item.getFieldName()) != null) { - values = params.get(item.getFieldName()); - } else { - values = new ArrayList<>(); - } - - // note: see http://jira.opensymphony.com/browse/WW-633 - // basically, in some cases the charset may be null, so - // we're just going to try to "other" method (no idea if this - // will work) - if (charset != null) { - values.add(item.getString(charset)); - } else { - values.add(item.getString()); - } - params.put(item.getFieldName(), values); - item.delete(); - } - - protected List parseRequest(HttpServletRequest servletRequest, String saveDir) throws FileUploadException { - DiskFileItemFactory fac = createDiskFileItemFactory(saveDir); - ServletFileUpload upload = createServletFileUpload(fac); - return upload.parseRequest(createRequestContext(servletRequest)); - } - - protected ServletFileUpload createServletFileUpload(DiskFileItemFactory fac) { - ServletFileUpload upload = new ServletFileUpload(fac); - upload.setSizeMax(maxSize); - return upload; - } - - protected DiskFileItemFactory createDiskFileItemFactory(String saveDir) { - DiskFileItemFactory fac = new DiskFileItemFactory(); - // Make sure that the data is written to file - fac.setSizeThreshold(0); - if (saveDir != null) { - fac.setRepository(new File(saveDir)); - } - return fac; - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFileParameterNames() - */ - public Enumeration getFileParameterNames() { - return Collections.enumeration(files.keySet()); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getContentType(java.lang.String) - */ - public String[] getContentType(String fieldName) { - List items = files.get(fieldName); - - if (items == null) { - return null; - } - - List contentTypes = new ArrayList<>(items.size()); - for (FileItem fileItem : items) { - contentTypes.add(fileItem.getContentType()); - } - - return contentTypes.toArray(new String[contentTypes.size()]); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFile(java.lang.String) - */ - public File[] getFile(String fieldName) { - List items = files.get(fieldName); - - if (items == null) { - return null; - } - - List fileList = new ArrayList<>(items.size()); - for (FileItem fileItem : items) { - File storeLocation = ((DiskFileItem) fileItem).getStoreLocation(); - if (fileItem.isInMemory() && storeLocation != null && !storeLocation.exists()) { - try { - storeLocation.createNewFile(); - } catch (IOException e) { - LOG.error("Cannot write uploaded empty file to disk: {}", storeLocation.getAbsolutePath(), e); - } - } - fileList.add(storeLocation); - } - - return fileList.toArray(new File[fileList.size()]); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFileNames(java.lang.String) - */ - public String[] getFileNames(String fieldName) { - List items = files.get(fieldName); - - if (items == null) { - return null; - } - - List fileNames = new ArrayList<>(items.size()); - for (FileItem fileItem : items) { - fileNames.add(getCanonicalName(fileItem.getName())); - } - - return fileNames.toArray(new String[fileNames.size()]); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getFilesystemName(java.lang.String) - */ - public String[] getFilesystemName(String fieldName) { - List items = files.get(fieldName); - - if (items == null) { - return null; - } - - List fileNames = new ArrayList<>(items.size()); - for (FileItem fileItem : items) { - fileNames.add(((DiskFileItem) fileItem).getStoreLocation().getName()); - } - - return fileNames.toArray(new String[fileNames.size()]); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameter(java.lang.String) - */ - public String getParameter(String name) { - List v = params.get(name); - if (v != null && v.size() > 0) { - return v.get(0); - } - - return null; - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameterNames() - */ - public Enumeration getParameterNames() { - return Collections.enumeration(params.keySet()); - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getParameterValues(java.lang.String) - */ - public String[] getParameterValues(String name) { - List v = params.get(name); - if (v != null && v.size() > 0) { - return v.toArray(new String[v.size()]); - } - - return null; - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#getErrors() - */ - public List getErrors() { - return errors; - } - - /** - * Returns the canonical name of the given file. - * - * @param filename the given file - * @return the canonical name of the given file - */ - private String getCanonicalName(String filename) { - int forwardSlash = filename.lastIndexOf("/"); - int backwardSlash = filename.lastIndexOf("\\"); - if (forwardSlash != -1 && forwardSlash > backwardSlash) { - filename = filename.substring(forwardSlash + 1, filename.length()); - } else if (backwardSlash != -1 && backwardSlash >= forwardSlash) { - filename = filename.substring(backwardSlash + 1, filename.length()); - } - - return filename; - } - - /** - * Creates a RequestContext needed by Jakarta Commons Upload. - * - * @param req the request. - * @return a new request context. - */ - protected RequestContext createRequestContext(final HttpServletRequest req) { - return new RequestContext() { - public String getCharacterEncoding() { - return req.getCharacterEncoding(); - } - - public String getContentType() { - return req.getContentType(); - } - - public int getContentLength() { - return req.getContentLength(); - } - - public InputStream getInputStream() throws IOException { - InputStream in = req.getInputStream(); - if (in == null) { - throw new IOException("Missing content in the request"); - } - return req.getInputStream(); - } - }; - } - - /* (non-Javadoc) - * @see org.apache.struts2.dispatcher.multipart.MultiPartRequest#cleanUp() - */ - public void cleanUp() { - Set names = files.keySet(); - for (String name : names) { - List items = files.get(name); - for (FileItem item : items) { - if (LOG.isDebugEnabled()) { - String msg = LocalizedTextUtil.findText(this.getClass(), "struts.messages.removing.file", - Locale.ENGLISH, "no.message.found", new Object[]{name, item}); - LOG.debug(msg); - } - if (!item.isInMemory()) { - item.delete(); - } - } - } - } - -} diff --git a/All/Genesis-NP/Genesis#110/pair.info b/All/Genesis-NP/Genesis#110/pair.info deleted file mode 100755 index 2b24620..0000000 --- a/All/Genesis-NP/Genesis#110/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:110 -SATName:Genesis -modifiedFPath:core/src/main/java/org/apache/struts2/dispatcher/multipart/JakartaMultiPartRequest.java -comSha:bc8d37464756bf821acae003c6a140af6dcbaf09 -parentComSha:bc8d37464756bf821acae003c6a140af6dcbaf09^1 -githubUrl:https://github.com/apache/struts -repoName:apache#struts \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#113/comMsg.txt b/All/Genesis-NP/Genesis#113/comMsg.txt deleted file mode 100755 index 5044f12..0000000 --- a/All/Genesis-NP/Genesis#113/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE when using logstash appender without any custom fields. diff --git a/All/Genesis-NP/Genesis#113/diff.diff b/All/Genesis-NP/Genesis#113/diff.diff deleted file mode 100755 index f2ada8d..0000000 --- a/All/Genesis-NP/Genesis#113/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/src/main/java/net/logstash/logback/appender/LogstashSocketAppender.java b/src/main/java/net/logstash/logback/appender/LogstashSocketAppender.java -index f80ab18..6dd34d3 100644 ---- a/src/main/java/net/logstash/logback/appender/LogstashSocketAppender.java -+++ b/src/main/java/net/logstash/logback/appender/LogstashSocketAppender.java -@@ -23 +23 @@ public class LogstashSocketAppender extends SyslogAppenderBase { -- private String customFields; -+ private String customFields = "{}"; diff --git a/All/Genesis-NP/Genesis#113/new/LogstashSocketAppender.java b/All/Genesis-NP/Genesis#113/new/LogstashSocketAppender.java deleted file mode 100755 index 6dd34d3..0000000 --- a/All/Genesis-NP/Genesis#113/new/LogstashSocketAppender.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.logstash.logback.appender; - -import net.logstash.logback.layout.LogstashLayout; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.Layout; -import ch.qos.logback.core.net.SyslogAppenderBase; - -public class LogstashSocketAppender extends SyslogAppenderBase { - - private String customFields = "{}"; - private boolean includeCallerInfo; - - @Override - public Layout buildLayout() { - LogstashLayout layout = new LogstashLayout(); - layout.setContext(getContext()); - layout.setCustomFields(customFields); - layout.setIncludeCallerInfo(includeCallerInfo); - return layout; - } - - public LogstashSocketAppender() { - setFacility("NEWS"); // NOTE: this value is never used - } - - @Override - public int getSeverityForEvent(Object eventObject) { - return 0; // NOTE: this value is never used - } - - public String getHost() { - return getSyslogHost(); - } - - /** - * Just an alias for syslogHost (since that name doesn't make much sense here) - * - * @param host - */ - public void setHost(String host) { - setSyslogHost(host); - } - - public void setCustomFields(String customFields) { - this.customFields = customFields; - } - - public String getCustomFields() { - return this.customFields; - } - - public boolean isIncludeCallerInfo() { - return this.includeCallerInfo; - } - - public void setIncludeCallerInfo(boolean includeCallerInfo) { - this.includeCallerInfo = includeCallerInfo; - } -} diff --git a/All/Genesis-NP/Genesis#113/old/LogstashSocketAppender.java b/All/Genesis-NP/Genesis#113/old/LogstashSocketAppender.java deleted file mode 100755 index f80ab18..0000000 --- a/All/Genesis-NP/Genesis#113/old/LogstashSocketAppender.java +++ /dev/null @@ -1,72 +0,0 @@ -/** - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package net.logstash.logback.appender; - -import net.logstash.logback.layout.LogstashLayout; -import ch.qos.logback.classic.spi.ILoggingEvent; -import ch.qos.logback.core.Layout; -import ch.qos.logback.core.net.SyslogAppenderBase; - -public class LogstashSocketAppender extends SyslogAppenderBase { - - private String customFields; - private boolean includeCallerInfo; - - @Override - public Layout buildLayout() { - LogstashLayout layout = new LogstashLayout(); - layout.setContext(getContext()); - layout.setCustomFields(customFields); - layout.setIncludeCallerInfo(includeCallerInfo); - return layout; - } - - public LogstashSocketAppender() { - setFacility("NEWS"); // NOTE: this value is never used - } - - @Override - public int getSeverityForEvent(Object eventObject) { - return 0; // NOTE: this value is never used - } - - public String getHost() { - return getSyslogHost(); - } - - /** - * Just an alias for syslogHost (since that name doesn't make much sense here) - * - * @param host - */ - public void setHost(String host) { - setSyslogHost(host); - } - - public void setCustomFields(String customFields) { - this.customFields = customFields; - } - - public String getCustomFields() { - return this.customFields; - } - - public boolean isIncludeCallerInfo() { - return this.includeCallerInfo; - } - - public void setIncludeCallerInfo(boolean includeCallerInfo) { - this.includeCallerInfo = includeCallerInfo; - } -} diff --git a/All/Genesis-NP/Genesis#113/pair.info b/All/Genesis-NP/Genesis#113/pair.info deleted file mode 100755 index a6aad36..0000000 --- a/All/Genesis-NP/Genesis#113/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:113 -SATName:Genesis -modifiedFPath:src/main/java/net/logstash/logback/appender/LogstashSocketAppender.java -comSha:c6a5972f8f68b4ac879b67b1d9106063d09d3d14 -parentComSha:c6a5972f8f68b4ac879b67b1d9106063d09d3d14^1 -githubUrl:https://github.com/logstash/logstash-logback-encoder -repoName:logstash#logstash-logback-encoder \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#124/comMsg.txt b/All/Genesis-NP/Genesis#124/comMsg.txt deleted file mode 100755 index fc3a157..0000000 --- a/All/Genesis-NP/Genesis#124/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -#27 nullpointer fix diff --git a/All/Genesis-NP/Genesis#124/diff.diff b/All/Genesis-NP/Genesis#124/diff.diff deleted file mode 100755 index 86031a1..0000000 --- a/All/Genesis-NP/Genesis#124/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/webmagic-core/src/main/java/us/codecraft/webmagic/downloader/HttpClientPool.java b/webmagic-core/src/main/java/us/codecraft/webmagic/downloader/HttpClientPool.java -index c256ac4..f3b72b6 100644 ---- a/webmagic-core/src/main/java/us/codecraft/webmagic/downloader/HttpClientPool.java -+++ b/webmagic-core/src/main/java/us/codecraft/webmagic/downloader/HttpClientPool.java -@@ -54 +53,0 @@ public class HttpClientPool { -- } -@@ -56,0 +56,6 @@ public class HttpClientPool { -+ } else { -+ params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000); -+ params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); -+ } -+ -+ -@@ -76 +80,0 @@ public class HttpClientPool { -- diff --git a/All/Genesis-NP/Genesis#124/new/HttpClientPool.java b/All/Genesis-NP/Genesis#124/new/HttpClientPool.java deleted file mode 100755 index f3b72b6..0000000 --- a/All/Genesis-NP/Genesis#124/new/HttpClientPool.java +++ /dev/null @@ -1,96 +0,0 @@ -package us.codecraft.webmagic.downloader; - -import org.apache.http.HttpVersion; -import org.apache.http.client.CookieStore; -import org.apache.http.client.HttpClient; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.CookiePolicy; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.apache.http.impl.cookie.BasicClientCookie; -import org.apache.http.params.*; -import us.codecraft.webmagic.Site; - -import java.util.Map; - -/** - * @author code4crafter@gmail.com
- * @since 0.1.0 - */ -public class HttpClientPool { - - public static volatile HttpClientPool INSTANCE; - - public static HttpClientPool getInstance(int poolSize) { - if (INSTANCE == null) { - synchronized (HttpClientPool.class) { - if (INSTANCE == null) { - INSTANCE = new HttpClientPool(poolSize); - } - } - } - return INSTANCE; - } - - private int poolSize; - - private HttpClientPool(int poolSize) { - this.poolSize = poolSize; - } - - public HttpClient getClient(Site site) { - return generateClient(site); - } - - private HttpClient generateClient(Site site) { - HttpParams params = new BasicHttpParams(); - if (site != null && site.getUserAgent() != null) { - params.setParameter(CoreProtocolPNames.USER_AGENT, site.getUserAgent()); - params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, site.getTimeOut()); - params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, site.getTimeOut()); - } else { - params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 3000); - params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); - } - - - params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); - HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); - paramsBean.setVersion(HttpVersion.HTTP_1_1); - if (site != null && site.getCharset() != null) { - paramsBean.setContentCharset(site.getCharset()); - } - paramsBean.setUseExpectContinue(false); - - SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); - schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); - - PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry); - connectionManager.setMaxTotal(poolSize); - connectionManager.setDefaultMaxPerRoute(100); - DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params); - if (site != null) { - generateCookie(httpClient, site); - } - return httpClient; - } - - private void generateCookie(DefaultHttpClient httpClient, Site site) { - CookieStore cookieStore = new BasicCookieStore(); - if (site.getCookies() != null) { - for (Map.Entry cookieEntry : site.getCookies().entrySet()) { - BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue()); - cookie.setDomain(site.getDomain()); - cookieStore.addCookie(cookie); - } - } - httpClient.setCookieStore(cookieStore); - } - -} diff --git a/All/Genesis-NP/Genesis#124/old/HttpClientPool.java b/All/Genesis-NP/Genesis#124/old/HttpClientPool.java deleted file mode 100755 index c256ac4..0000000 --- a/All/Genesis-NP/Genesis#124/old/HttpClientPool.java +++ /dev/null @@ -1,92 +0,0 @@ -package us.codecraft.webmagic.downloader; - -import org.apache.http.HttpVersion; -import org.apache.http.client.CookieStore; -import org.apache.http.client.HttpClient; -import org.apache.http.client.params.ClientPNames; -import org.apache.http.client.params.CookiePolicy; -import org.apache.http.conn.scheme.PlainSocketFactory; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.scheme.SchemeRegistry; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.impl.client.BasicCookieStore; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.impl.conn.PoolingClientConnectionManager; -import org.apache.http.impl.cookie.BasicClientCookie; -import org.apache.http.params.*; -import us.codecraft.webmagic.Site; - -import java.util.Map; - -/** - * @author code4crafter@gmail.com
- * @since 0.1.0 - */ -public class HttpClientPool { - - public static volatile HttpClientPool INSTANCE; - - public static HttpClientPool getInstance(int poolSize) { - if (INSTANCE == null) { - synchronized (HttpClientPool.class) { - if (INSTANCE == null) { - INSTANCE = new HttpClientPool(poolSize); - } - } - } - return INSTANCE; - } - - private int poolSize; - - private HttpClientPool(int poolSize) { - this.poolSize = poolSize; - } - - public HttpClient getClient(Site site) { - return generateClient(site); - } - - private HttpClient generateClient(Site site) { - HttpParams params = new BasicHttpParams(); - if (site != null && site.getUserAgent() != null) { - params.setParameter(CoreProtocolPNames.USER_AGENT, site.getUserAgent()); - } - params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, site.getTimeOut()); - params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, site.getTimeOut()); - params.setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); - HttpProtocolParamBean paramsBean = new HttpProtocolParamBean(params); - paramsBean.setVersion(HttpVersion.HTTP_1_1); - if (site != null && site.getCharset() != null) { - paramsBean.setContentCharset(site.getCharset()); - } - paramsBean.setUseExpectContinue(false); - - SchemeRegistry schemeRegistry = new SchemeRegistry(); - schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); - schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); - - PoolingClientConnectionManager connectionManager = new PoolingClientConnectionManager(schemeRegistry); - connectionManager.setMaxTotal(poolSize); - connectionManager.setDefaultMaxPerRoute(100); - DefaultHttpClient httpClient = new DefaultHttpClient(connectionManager, params); - if (site != null) { - generateCookie(httpClient, site); - } - - return httpClient; - } - - private void generateCookie(DefaultHttpClient httpClient, Site site) { - CookieStore cookieStore = new BasicCookieStore(); - if (site.getCookies() != null) { - for (Map.Entry cookieEntry : site.getCookies().entrySet()) { - BasicClientCookie cookie = new BasicClientCookie(cookieEntry.getKey(), cookieEntry.getValue()); - cookie.setDomain(site.getDomain()); - cookieStore.addCookie(cookie); - } - } - httpClient.setCookieStore(cookieStore); - } - -} diff --git a/All/Genesis-NP/Genesis#124/pair.info b/All/Genesis-NP/Genesis#124/pair.info deleted file mode 100755 index 2fd76b9..0000000 --- a/All/Genesis-NP/Genesis#124/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:124 -SATName:Genesis -modifiedFPath:webmagic-core/src/main/java/us/codecraft/webmagic/downloader/HttpClientPool.java -comSha:5a226387e0f344555603e762b69afc4a9f0ebd57 -parentComSha:5a226387e0f344555603e762b69afc4a9f0ebd57^1 -githubUrl:https://github.com/code4craft/webmagic -repoName:code4craft#webmagic \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#126/comMsg.txt b/All/Genesis-NP/Genesis#126/comMsg.txt deleted file mode 100755 index 53fdc64..0000000 --- a/All/Genesis-NP/Genesis#126/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix WildcardTypeName.get(WildcardType), which would always fail with NullPointerException since either the extends bound or the super bound or both will be null. diff --git a/All/Genesis-NP/Genesis#126/diff.diff b/All/Genesis-NP/Genesis#126/diff.diff deleted file mode 100755 index 2b4c300..0000000 --- a/All/Genesis-NP/Genesis#126/diff.diff +++ /dev/null @@ -1,21 +0,0 @@ -diff --git a/src/main/java/com/squareup/javapoet/WildcardTypeName.java b/src/main/java/com/squareup/javapoet/WildcardTypeName.java -index eb1c429..711b278 100644 ---- a/src/main/java/com/squareup/javapoet/WildcardTypeName.java -+++ b/src/main/java/com/squareup/javapoet/WildcardTypeName.java -@@ -23,0 +24 @@ import java.util.List; -+import javax.lang.model.type.TypeMirror; -@@ -92,3 +93,11 @@ public final class WildcardTypeName extends TypeName { -- TypeName extendsBound = TypeName.get(mirror.getExtendsBound()); -- TypeName superBound = TypeName.get(mirror.getSuperBound()); -- return superBound != null ? supertypeOf(superBound) : subtypeOf(extendsBound); -+ TypeMirror extendsBound = mirror.getExtendsBound(); -+ if (extendsBound == null) { -+ TypeMirror superBound = mirror.getSuperBound(); -+ if (superBound == null) { -+ return subtypeOf(Object.class); -+ } else { -+ return supertypeOf(TypeName.get(superBound)); -+ } -+ } else { -+ return subtypeOf(TypeName.get(extendsBound)); -+ } diff --git a/All/Genesis-NP/Genesis#126/new/WildcardTypeName.java b/All/Genesis-NP/Genesis#126/new/WildcardTypeName.java deleted file mode 100755 index 711b278..0000000 --- a/All/Genesis-NP/Genesis#126/new/WildcardTypeName.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2015 Square, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.squareup.javapoet; - -import java.io.IOException; -import java.lang.reflect.Type; -import java.lang.reflect.WildcardType; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import javax.lang.model.type.TypeMirror; - -import static com.squareup.javapoet.Util.checkArgument; - -public final class WildcardTypeName extends TypeName { - public final List upperBounds; - public final List lowerBounds; - - private WildcardTypeName(List upperBounds, List lowerBounds) { - this.upperBounds = Util.immutableList(upperBounds); - this.lowerBounds = Util.immutableList(lowerBounds); - - checkArgument(this.upperBounds.size() == 1, "unexpected extends bounds: %s", upperBounds); - for (TypeName upperBound : this.upperBounds) { - checkArgument(!upperBound.isPrimitive() && upperBound != VOID, - "invalid upper bound: %s", upperBound); - } - for (TypeName lowerBound : this.lowerBounds) { - checkArgument(!lowerBound.isPrimitive() && lowerBound != VOID, - "invalid lower bound: %s", lowerBound); - } - } - - @Override public boolean equals(Object o) { - return o instanceof WildcardTypeName - && ((WildcardTypeName) o).upperBounds.equals(upperBounds) - && ((WildcardTypeName) o).lowerBounds.equals(lowerBounds); - } - - @Override public int hashCode() { - return upperBounds.hashCode() ^ lowerBounds.hashCode(); - } - - @Override CodeWriter emit(CodeWriter out) throws IOException { - if (lowerBounds.size() == 1) { - return out.emit("? super $T", lowerBounds.get(0)); - } - return upperBounds.get(0).equals(TypeName.OBJECT) - ? out.emit("?") - : out.emit("? extends $T", upperBounds.get(0)); - } - - /** - * Returns a type that represents an unknown type that extends {@code bound}. For example, if - * {@code bound} is {@code CharSequence.class}, this returns {@code ? extends CharSequence}. If - * {@code bound} is {@code Object.class}, this returns {@code ?}, which is shorthand for {@code - * ? extends Object}. - */ - public static WildcardTypeName subtypeOf(TypeName upperBound) { - return new WildcardTypeName(Arrays.asList(upperBound), Collections.emptyList()); - } - - public static WildcardTypeName subtypeOf(Type upperBound) { - return subtypeOf(TypeName.get(upperBound)); - } - - /** - * Returns a type that represents an unknown supertype of {@code bound}. For example, if {@code - * bound} is {@code String.class}, this returns {@code ? super String}. - */ - public static WildcardTypeName supertypeOf(TypeName lowerBound) { - return new WildcardTypeName(Arrays.asList(OBJECT), Arrays.asList(lowerBound)); - } - - public static WildcardTypeName supertypeOf(Type lowerBound) { - return supertypeOf(TypeName.get(lowerBound)); - } - - public static TypeName get(javax.lang.model.type.WildcardType mirror) { - TypeMirror extendsBound = mirror.getExtendsBound(); - if (extendsBound == null) { - TypeMirror superBound = mirror.getSuperBound(); - if (superBound == null) { - return subtypeOf(Object.class); - } else { - return supertypeOf(TypeName.get(superBound)); - } - } else { - return subtypeOf(TypeName.get(extendsBound)); - } - } - - public static TypeName get(WildcardType wildcardName) { - return new WildcardTypeName( - list(wildcardName.getUpperBounds()), - list(wildcardName.getLowerBounds())); - } -} diff --git a/All/Genesis-NP/Genesis#126/old/WildcardTypeName.java b/All/Genesis-NP/Genesis#126/old/WildcardTypeName.java deleted file mode 100755 index eb1c429..0000000 --- a/All/Genesis-NP/Genesis#126/old/WildcardTypeName.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2015 Square, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.squareup.javapoet; - -import java.io.IOException; -import java.lang.reflect.Type; -import java.lang.reflect.WildcardType; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static com.squareup.javapoet.Util.checkArgument; - -public final class WildcardTypeName extends TypeName { - public final List upperBounds; - public final List lowerBounds; - - private WildcardTypeName(List upperBounds, List lowerBounds) { - this.upperBounds = Util.immutableList(upperBounds); - this.lowerBounds = Util.immutableList(lowerBounds); - - checkArgument(this.upperBounds.size() == 1, "unexpected extends bounds: %s", upperBounds); - for (TypeName upperBound : this.upperBounds) { - checkArgument(!upperBound.isPrimitive() && upperBound != VOID, - "invalid upper bound: %s", upperBound); - } - for (TypeName lowerBound : this.lowerBounds) { - checkArgument(!lowerBound.isPrimitive() && lowerBound != VOID, - "invalid lower bound: %s", lowerBound); - } - } - - @Override public boolean equals(Object o) { - return o instanceof WildcardTypeName - && ((WildcardTypeName) o).upperBounds.equals(upperBounds) - && ((WildcardTypeName) o).lowerBounds.equals(lowerBounds); - } - - @Override public int hashCode() { - return upperBounds.hashCode() ^ lowerBounds.hashCode(); - } - - @Override CodeWriter emit(CodeWriter out) throws IOException { - if (lowerBounds.size() == 1) { - return out.emit("? super $T", lowerBounds.get(0)); - } - return upperBounds.get(0).equals(TypeName.OBJECT) - ? out.emit("?") - : out.emit("? extends $T", upperBounds.get(0)); - } - - /** - * Returns a type that represents an unknown type that extends {@code bound}. For example, if - * {@code bound} is {@code CharSequence.class}, this returns {@code ? extends CharSequence}. If - * {@code bound} is {@code Object.class}, this returns {@code ?}, which is shorthand for {@code - * ? extends Object}. - */ - public static WildcardTypeName subtypeOf(TypeName upperBound) { - return new WildcardTypeName(Arrays.asList(upperBound), Collections.emptyList()); - } - - public static WildcardTypeName subtypeOf(Type upperBound) { - return subtypeOf(TypeName.get(upperBound)); - } - - /** - * Returns a type that represents an unknown supertype of {@code bound}. For example, if {@code - * bound} is {@code String.class}, this returns {@code ? super String}. - */ - public static WildcardTypeName supertypeOf(TypeName lowerBound) { - return new WildcardTypeName(Arrays.asList(OBJECT), Arrays.asList(lowerBound)); - } - - public static WildcardTypeName supertypeOf(Type lowerBound) { - return supertypeOf(TypeName.get(lowerBound)); - } - - public static TypeName get(javax.lang.model.type.WildcardType mirror) { - TypeName extendsBound = TypeName.get(mirror.getExtendsBound()); - TypeName superBound = TypeName.get(mirror.getSuperBound()); - return superBound != null ? supertypeOf(superBound) : subtypeOf(extendsBound); - } - - public static TypeName get(WildcardType wildcardName) { - return new WildcardTypeName( - list(wildcardName.getUpperBounds()), - list(wildcardName.getLowerBounds())); - } -} diff --git a/All/Genesis-NP/Genesis#126/pair.info b/All/Genesis-NP/Genesis#126/pair.info deleted file mode 100755 index d4d32b8..0000000 --- a/All/Genesis-NP/Genesis#126/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:126 -SATName:Genesis -modifiedFPath:src/main/java/com/squareup/javapoet/WildcardTypeName.java -comSha:70b38e5a0b2ef538c110e4108ae51ccb41bd6034 -parentComSha:70b38e5a0b2ef538c110e4108ae51ccb41bd6034^1 -githubUrl:https://github.com/square/javapoet -repoName:square#javapoet \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#129/comMsg.txt b/All/Genesis-NP/Genesis#129/comMsg.txt deleted file mode 100755 index 8e4c55d..0000000 --- a/All/Genesis-NP/Genesis#129/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -HBASE-4907 NPE of MobUtils.hasMobColumns in Build failed in Jenkins: HBase-Trunk_matrix latest1.8,Hadoop #513 (Jingcheng Du) diff --git a/All/Genesis-NP/Genesis#129/diff.diff b/All/Genesis-NP/Genesis#129/diff.diff deleted file mode 100755 index 8d352fc..0000000 --- a/All/Genesis-NP/Genesis#129/diff.diff +++ /dev/null @@ -1,20 +0,0 @@ -diff --git a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/procedure/DeleteTableProcedure.java b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/procedure/DeleteTableProcedure.java -index 4b95fa8..1e86254 100644 ---- a/hbase-server/src/main/java/org/apache/hadoop/hbase/master/procedure/DeleteTableProcedure.java -+++ b/hbase-server/src/main/java/org/apache/hadoop/hbase/master/procedure/DeleteTableProcedure.java -@@ -34 +33,0 @@ import org.apache.hadoop.hbase.HRegionInfo; --import org.apache.hadoop.hbase.HTableDescriptor; -@@ -348,5 +346,0 @@ public class DeleteTableProcedure -- // Archive the mob data if there is a mob-enabled column -- HTableDescriptor htd = env.getMasterServices().getTableDescriptors().get(tableName); -- boolean hasMob = MobUtils.hasMobColumns(htd); -- Path mobTableDir = null; -- if (hasMob) { -@@ -354 +348 @@ public class DeleteTableProcedure -- mobTableDir = FSUtils.getTableDir(new Path(mfs.getRootDir(), MobConstants.MOB_DIR_NAME), -+ Path mobTableDir = FSUtils.getTableDir(new Path(mfs.getRootDir(), MobConstants.MOB_DIR_NAME), -@@ -361 +354,0 @@ public class DeleteTableProcedure -- } -@@ -369 +362 @@ public class DeleteTableProcedure -- if (hasMob && mobTableDir != null && fs.exists(mobTableDir)) { -+ if (mobTableDir != null && fs.exists(mobTableDir)) { diff --git a/All/Genesis-NP/Genesis#129/new/DeleteTableProcedure.java b/All/Genesis-NP/Genesis#129/new/DeleteTableProcedure.java deleted file mode 100755 index 1e86254..0000000 --- a/All/Genesis-NP/Genesis#129/new/DeleteTableProcedure.java +++ /dev/null @@ -1,428 +0,0 @@ -/** - * 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.hbase.master.procedure; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.hadoop.fs.FileStatus; -import org.apache.hadoop.fs.FileSystem; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.hbase.HRegionInfo; -import org.apache.hadoop.hbase.MetaTableAccessor; -import org.apache.hadoop.hbase.TableName; -import org.apache.hadoop.hbase.TableNotDisabledException; -import org.apache.hadoop.hbase.TableNotFoundException; -import org.apache.hadoop.hbase.backup.HFileArchiver; -import org.apache.hadoop.hbase.classification.InterfaceAudience; -import org.apache.hadoop.hbase.client.ClusterConnection; -import org.apache.hadoop.hbase.client.Delete; -import org.apache.hadoop.hbase.client.Result; -import org.apache.hadoop.hbase.client.ResultScanner; -import org.apache.hadoop.hbase.client.Scan; -import org.apache.hadoop.hbase.client.Table; -import org.apache.hadoop.hbase.exceptions.HBaseException; -import org.apache.hadoop.hbase.master.AssignmentManager; -import org.apache.hadoop.hbase.master.MasterCoprocessorHost; -import org.apache.hadoop.hbase.master.MasterFileSystem; -import org.apache.hadoop.hbase.mob.MobConstants; -import org.apache.hadoop.hbase.mob.MobUtils; -import org.apache.hadoop.hbase.procedure2.StateMachineProcedure; -import org.apache.hadoop.hbase.protobuf.ProtobufUtil; -import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos; -import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos; -import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.DeleteTableState; -import org.apache.hadoop.hbase.regionserver.HRegion; -import org.apache.hadoop.hbase.util.FSUtils; -import org.apache.hadoop.security.UserGroupInformation; - -@InterfaceAudience.Private -public class DeleteTableProcedure - extends StateMachineProcedure - implements TableProcedureInterface { - private static final Log LOG = LogFactory.getLog(DeleteTableProcedure.class); - - private List regions; - private UserGroupInformation user; - private TableName tableName; - - // used for compatibility with old clients - private final ProcedurePrepareLatch syncLatch; - - public DeleteTableProcedure() { - // Required by the Procedure framework to create the procedure on replay - syncLatch = null; - } - - public DeleteTableProcedure(final MasterProcedureEnv env, final TableName tableName) - throws IOException { - this(env, tableName, null); - } - - public DeleteTableProcedure(final MasterProcedureEnv env, final TableName tableName, - final ProcedurePrepareLatch syncLatch) throws IOException { - this.tableName = tableName; - this.user = env.getRequestUser().getUGI(); - this.setOwner(this.user.getShortUserName()); - - // used for compatibility with clients without procedures - // they need a sync TableNotFoundException, TableNotDisabledException, ... - this.syncLatch = syncLatch; - } - - @Override - protected Flow executeFromState(final MasterProcedureEnv env, DeleteTableState state) - throws InterruptedException { - if (LOG.isTraceEnabled()) { - LOG.trace(this + " execute state=" + state); - } - try { - switch (state) { - case DELETE_TABLE_PRE_OPERATION: - // Verify if we can delete the table - boolean deletable = prepareDelete(env); - ProcedurePrepareLatch.releaseLatch(syncLatch, this); - if (!deletable) { - assert isFailed() : "the delete should have an exception here"; - return Flow.NO_MORE_STATE; - } - - // TODO: Move out... in the acquireLock() - LOG.debug("waiting for '" + getTableName() + "' regions in transition"); - regions = ProcedureSyncWait.getRegionsFromMeta(env, getTableName()); - assert regions != null && !regions.isEmpty() : "unexpected 0 regions"; - ProcedureSyncWait.waitRegionInTransition(env, regions); - - // Call coprocessors - preDelete(env); - - setNextState(DeleteTableState.DELETE_TABLE_REMOVE_FROM_META); - break; - case DELETE_TABLE_REMOVE_FROM_META: - LOG.debug("delete '" + getTableName() + "' regions from META"); - DeleteTableProcedure.deleteFromMeta(env, getTableName(), regions); - setNextState(DeleteTableState.DELETE_TABLE_CLEAR_FS_LAYOUT); - break; - case DELETE_TABLE_CLEAR_FS_LAYOUT: - LOG.debug("delete '" + getTableName() + "' from filesystem"); - DeleteTableProcedure.deleteFromFs(env, getTableName(), regions, true); - setNextState(DeleteTableState.DELETE_TABLE_UPDATE_DESC_CACHE); - regions = null; - break; - case DELETE_TABLE_UPDATE_DESC_CACHE: - LOG.debug("delete '" + getTableName() + "' descriptor"); - DeleteTableProcedure.deleteTableDescriptorCache(env, getTableName()); - setNextState(DeleteTableState.DELETE_TABLE_UNASSIGN_REGIONS); - break; - case DELETE_TABLE_UNASSIGN_REGIONS: - LOG.debug("delete '" + getTableName() + "' assignment state"); - DeleteTableProcedure.deleteAssignmentState(env, getTableName()); - setNextState(DeleteTableState.DELETE_TABLE_POST_OPERATION); - break; - case DELETE_TABLE_POST_OPERATION: - postDelete(env); - LOG.debug("delete '" + getTableName() + "' completed"); - return Flow.NO_MORE_STATE; - default: - throw new UnsupportedOperationException("unhandled state=" + state); - } - } catch (HBaseException|IOException e) { - LOG.warn("Retriable error trying to delete table=" + getTableName() + " state=" + state, e); - } - return Flow.HAS_MORE_STATE; - } - - @Override - protected void rollbackState(final MasterProcedureEnv env, final DeleteTableState state) { - if (state == DeleteTableState.DELETE_TABLE_PRE_OPERATION) { - // nothing to rollback, pre-delete is just table-state checks. - // We can fail if the table does not exist or is not disabled. - ProcedurePrepareLatch.releaseLatch(syncLatch, this); - return; - } - - // The delete doesn't have a rollback. The execution will succeed, at some point. - throw new UnsupportedOperationException("unhandled state=" + state); - } - - @Override - protected DeleteTableState getState(final int stateId) { - return DeleteTableState.valueOf(stateId); - } - - @Override - protected int getStateId(final DeleteTableState state) { - return state.getNumber(); - } - - @Override - protected DeleteTableState getInitialState() { - return DeleteTableState.DELETE_TABLE_PRE_OPERATION; - } - - @Override - public TableName getTableName() { - return tableName; - } - - @Override - public TableOperationType getTableOperationType() { - return TableOperationType.DELETE; - } - - @Override - public boolean abort(final MasterProcedureEnv env) { - // TODO: We may be able to abort if the procedure is not started yet. - return false; - } - - @Override - protected boolean acquireLock(final MasterProcedureEnv env) { - if (!env.isInitialized()) return false; - return env.getProcedureQueue().tryAcquireTableExclusiveLock(getTableName(), "delete table"); - } - - @Override - protected void releaseLock(final MasterProcedureEnv env) { - env.getProcedureQueue().releaseTableExclusiveLock(getTableName()); - } - - @Override - public void toStringClassDetails(StringBuilder sb) { - sb.append(getClass().getSimpleName()); - sb.append(" (table="); - sb.append(getTableName()); - sb.append(")"); - } - - @Override - public void serializeStateData(final OutputStream stream) throws IOException { - super.serializeStateData(stream); - - MasterProcedureProtos.DeleteTableStateData.Builder state = - MasterProcedureProtos.DeleteTableStateData.newBuilder() - .setUserInfo(MasterProcedureUtil.toProtoUserInfo(this.user)) - .setTableName(ProtobufUtil.toProtoTableName(tableName)); - if (regions != null) { - for (HRegionInfo hri: regions) { - state.addRegionInfo(HRegionInfo.convert(hri)); - } - } - state.build().writeDelimitedTo(stream); - } - - @Override - public void deserializeStateData(final InputStream stream) throws IOException { - super.deserializeStateData(stream); - - MasterProcedureProtos.DeleteTableStateData state = - MasterProcedureProtos.DeleteTableStateData.parseDelimitedFrom(stream); - user = MasterProcedureUtil.toUserInfo(state.getUserInfo()); - tableName = ProtobufUtil.toTableName(state.getTableName()); - if (state.getRegionInfoCount() == 0) { - regions = null; - } else { - regions = new ArrayList(state.getRegionInfoCount()); - for (HBaseProtos.RegionInfo hri: state.getRegionInfoList()) { - regions.add(HRegionInfo.convert(hri)); - } - } - } - - private boolean prepareDelete(final MasterProcedureEnv env) throws IOException { - try { - env.getMasterServices().checkTableModifiable(tableName); - } catch (TableNotFoundException|TableNotDisabledException e) { - setFailure("master-delete-table", e); - return false; - } - return true; - } - - private boolean preDelete(final MasterProcedureEnv env) - throws IOException, InterruptedException { - final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); - if (cpHost != null) { - final TableName tableName = this.tableName; - user.doAs(new PrivilegedExceptionAction() { - @Override - public Void run() throws Exception { - cpHost.preDeleteTableHandler(tableName); - return null; - } - }); - } - return true; - } - - private void postDelete(final MasterProcedureEnv env) - throws IOException, InterruptedException { - deleteTableStates(env, tableName); - - final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); - if (cpHost != null) { - final TableName tableName = this.tableName; - user.doAs(new PrivilegedExceptionAction() { - @Override - public Void run() throws Exception { - cpHost.postDeleteTableHandler(tableName); - return null; - } - }); - } - } - - protected static void deleteFromFs(final MasterProcedureEnv env, - final TableName tableName, final List regions, - final boolean archive) throws IOException { - final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); - final FileSystem fs = mfs.getFileSystem(); - final Path tempdir = mfs.getTempDir(); - - final Path tableDir = FSUtils.getTableDir(mfs.getRootDir(), tableName); - final Path tempTableDir = FSUtils.getTableDir(tempdir, tableName); - - if (fs.exists(tableDir)) { - // Ensure temp exists - if (!fs.exists(tempdir) && !fs.mkdirs(tempdir)) { - throw new IOException("HBase temp directory '" + tempdir + "' creation failure."); - } - - // Ensure parent exists - if (!fs.exists(tempTableDir.getParent()) && !fs.mkdirs(tempTableDir.getParent())) { - throw new IOException("HBase temp directory '" + tempdir + "' creation failure."); - } - - // Move the table in /hbase/.tmp - if (!fs.rename(tableDir, tempTableDir)) { - if (fs.exists(tempTableDir)) { - // TODO - // what's in this dir? something old? probably something manual from the user... - // let's get rid of this stuff... - FileStatus[] files = fs.listStatus(tempdir); - if (files != null && files.length > 0) { - for (int i = 0; i < files.length; ++i) { - if (!files[i].isDir()) continue; - HFileArchiver.archiveRegion(fs, mfs.getRootDir(), tempTableDir, files[i].getPath()); - } - } - fs.delete(tempdir, true); - } - throw new IOException("Unable to move '" + tableDir + "' to temp '" + tempTableDir + "'"); - } - } - - // Archive regions from FS (temp directory) - if (archive) { - for (HRegionInfo hri : regions) { - LOG.debug("Archiving region " + hri.getRegionNameAsString() + " from FS"); - HFileArchiver.archiveRegion(fs, mfs.getRootDir(), - tempTableDir, HRegion.getRegionDir(tempTableDir, hri.getEncodedName())); - } - LOG.debug("Table '" + tableName + "' archived!"); - } - - // Archive mob data - Path mobTableDir = FSUtils.getTableDir(new Path(mfs.getRootDir(), MobConstants.MOB_DIR_NAME), - tableName); - Path regionDir = - new Path(mobTableDir, MobUtils.getMobRegionInfo(tableName).getEncodedName()); - if (fs.exists(regionDir)) { - HFileArchiver.archiveRegion(fs, mfs.getRootDir(), mobTableDir, regionDir); - } - - // Delete table directory from FS (temp directory) - if (!fs.delete(tempTableDir, true) && fs.exists(tempTableDir)) { - throw new IOException("Couldn't delete " + tempTableDir); - } - - // Delete the table directory where the mob files are saved - if (mobTableDir != null && fs.exists(mobTableDir)) { - if (!fs.delete(mobTableDir, true)) { - throw new IOException("Couldn't delete mob dir " + mobTableDir); - } - } - } - - /** - * There may be items for this table still up in hbase:meta in the case where the - * info:regioninfo column was empty because of some write error. Remove ALL rows from hbase:meta - * that have to do with this table. See HBASE-12980. - * @throws IOException - */ - private static void cleanAnyRemainingRows(final MasterProcedureEnv env, - final TableName tableName) throws IOException { - ClusterConnection connection = env.getMasterServices().getConnection(); - Scan tableScan = MetaTableAccessor.getScanForTableName(connection, tableName); - try (Table metaTable = - connection.getTable(TableName.META_TABLE_NAME)) { - List deletes = new ArrayList(); - try (ResultScanner resScanner = metaTable.getScanner(tableScan)) { - for (Result result : resScanner) { - deletes.add(new Delete(result.getRow())); - } - } - if (!deletes.isEmpty()) { - LOG.warn("Deleting some vestigal " + deletes.size() + " rows of " + tableName + - " from " + TableName.META_TABLE_NAME); - metaTable.delete(deletes); - } - } - } - - protected static void deleteFromMeta(final MasterProcedureEnv env, - final TableName tableName, List regions) throws IOException { - MetaTableAccessor.deleteRegions(env.getMasterServices().getConnection(), regions); - - // Clean any remaining rows for this table. - cleanAnyRemainingRows(env, tableName); - } - - protected static void deleteAssignmentState(final MasterProcedureEnv env, - final TableName tableName) throws IOException { - AssignmentManager am = env.getMasterServices().getAssignmentManager(); - - // Clean up regions of the table in RegionStates. - LOG.debug("Removing '" + tableName + "' from region states."); - am.getRegionStates().tableDeleted(tableName); - - // If entry for this table states, remove it. - LOG.debug("Marking '" + tableName + "' as deleted."); - am.getTableStateManager().setDeletedTable(tableName); - } - - protected static void deleteTableDescriptorCache(final MasterProcedureEnv env, - final TableName tableName) throws IOException { - LOG.debug("Removing '" + tableName + "' descriptor."); - env.getMasterServices().getTableDescriptors().remove(tableName); - } - - protected static void deleteTableStates(final MasterProcedureEnv env, final TableName tableName) - throws IOException { - if (!tableName.isSystemTable()) { - ProcedureSyncWait.getMasterQuotaManager(env).removeTableFromNamespaceQuota(tableName); - } - } -} diff --git a/All/Genesis-NP/Genesis#129/old/DeleteTableProcedure.java b/All/Genesis-NP/Genesis#129/old/DeleteTableProcedure.java deleted file mode 100755 index 4b95fa8..0000000 --- a/All/Genesis-NP/Genesis#129/old/DeleteTableProcedure.java +++ /dev/null @@ -1,435 +0,0 @@ -/** - * 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.hbase.master.procedure; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.security.PrivilegedExceptionAction; -import java.util.ArrayList; -import java.util.List; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.hadoop.fs.FileStatus; -import org.apache.hadoop.fs.FileSystem; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.hbase.HRegionInfo; -import org.apache.hadoop.hbase.HTableDescriptor; -import org.apache.hadoop.hbase.MetaTableAccessor; -import org.apache.hadoop.hbase.TableName; -import org.apache.hadoop.hbase.TableNotDisabledException; -import org.apache.hadoop.hbase.TableNotFoundException; -import org.apache.hadoop.hbase.backup.HFileArchiver; -import org.apache.hadoop.hbase.classification.InterfaceAudience; -import org.apache.hadoop.hbase.client.ClusterConnection; -import org.apache.hadoop.hbase.client.Delete; -import org.apache.hadoop.hbase.client.Result; -import org.apache.hadoop.hbase.client.ResultScanner; -import org.apache.hadoop.hbase.client.Scan; -import org.apache.hadoop.hbase.client.Table; -import org.apache.hadoop.hbase.exceptions.HBaseException; -import org.apache.hadoop.hbase.master.AssignmentManager; -import org.apache.hadoop.hbase.master.MasterCoprocessorHost; -import org.apache.hadoop.hbase.master.MasterFileSystem; -import org.apache.hadoop.hbase.mob.MobConstants; -import org.apache.hadoop.hbase.mob.MobUtils; -import org.apache.hadoop.hbase.procedure2.StateMachineProcedure; -import org.apache.hadoop.hbase.protobuf.ProtobufUtil; -import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos; -import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos; -import org.apache.hadoop.hbase.protobuf.generated.MasterProcedureProtos.DeleteTableState; -import org.apache.hadoop.hbase.regionserver.HRegion; -import org.apache.hadoop.hbase.util.FSUtils; -import org.apache.hadoop.security.UserGroupInformation; - -@InterfaceAudience.Private -public class DeleteTableProcedure - extends StateMachineProcedure - implements TableProcedureInterface { - private static final Log LOG = LogFactory.getLog(DeleteTableProcedure.class); - - private List regions; - private UserGroupInformation user; - private TableName tableName; - - // used for compatibility with old clients - private final ProcedurePrepareLatch syncLatch; - - public DeleteTableProcedure() { - // Required by the Procedure framework to create the procedure on replay - syncLatch = null; - } - - public DeleteTableProcedure(final MasterProcedureEnv env, final TableName tableName) - throws IOException { - this(env, tableName, null); - } - - public DeleteTableProcedure(final MasterProcedureEnv env, final TableName tableName, - final ProcedurePrepareLatch syncLatch) throws IOException { - this.tableName = tableName; - this.user = env.getRequestUser().getUGI(); - this.setOwner(this.user.getShortUserName()); - - // used for compatibility with clients without procedures - // they need a sync TableNotFoundException, TableNotDisabledException, ... - this.syncLatch = syncLatch; - } - - @Override - protected Flow executeFromState(final MasterProcedureEnv env, DeleteTableState state) - throws InterruptedException { - if (LOG.isTraceEnabled()) { - LOG.trace(this + " execute state=" + state); - } - try { - switch (state) { - case DELETE_TABLE_PRE_OPERATION: - // Verify if we can delete the table - boolean deletable = prepareDelete(env); - ProcedurePrepareLatch.releaseLatch(syncLatch, this); - if (!deletable) { - assert isFailed() : "the delete should have an exception here"; - return Flow.NO_MORE_STATE; - } - - // TODO: Move out... in the acquireLock() - LOG.debug("waiting for '" + getTableName() + "' regions in transition"); - regions = ProcedureSyncWait.getRegionsFromMeta(env, getTableName()); - assert regions != null && !regions.isEmpty() : "unexpected 0 regions"; - ProcedureSyncWait.waitRegionInTransition(env, regions); - - // Call coprocessors - preDelete(env); - - setNextState(DeleteTableState.DELETE_TABLE_REMOVE_FROM_META); - break; - case DELETE_TABLE_REMOVE_FROM_META: - LOG.debug("delete '" + getTableName() + "' regions from META"); - DeleteTableProcedure.deleteFromMeta(env, getTableName(), regions); - setNextState(DeleteTableState.DELETE_TABLE_CLEAR_FS_LAYOUT); - break; - case DELETE_TABLE_CLEAR_FS_LAYOUT: - LOG.debug("delete '" + getTableName() + "' from filesystem"); - DeleteTableProcedure.deleteFromFs(env, getTableName(), regions, true); - setNextState(DeleteTableState.DELETE_TABLE_UPDATE_DESC_CACHE); - regions = null; - break; - case DELETE_TABLE_UPDATE_DESC_CACHE: - LOG.debug("delete '" + getTableName() + "' descriptor"); - DeleteTableProcedure.deleteTableDescriptorCache(env, getTableName()); - setNextState(DeleteTableState.DELETE_TABLE_UNASSIGN_REGIONS); - break; - case DELETE_TABLE_UNASSIGN_REGIONS: - LOG.debug("delete '" + getTableName() + "' assignment state"); - DeleteTableProcedure.deleteAssignmentState(env, getTableName()); - setNextState(DeleteTableState.DELETE_TABLE_POST_OPERATION); - break; - case DELETE_TABLE_POST_OPERATION: - postDelete(env); - LOG.debug("delete '" + getTableName() + "' completed"); - return Flow.NO_MORE_STATE; - default: - throw new UnsupportedOperationException("unhandled state=" + state); - } - } catch (HBaseException|IOException e) { - LOG.warn("Retriable error trying to delete table=" + getTableName() + " state=" + state, e); - } - return Flow.HAS_MORE_STATE; - } - - @Override - protected void rollbackState(final MasterProcedureEnv env, final DeleteTableState state) { - if (state == DeleteTableState.DELETE_TABLE_PRE_OPERATION) { - // nothing to rollback, pre-delete is just table-state checks. - // We can fail if the table does not exist or is not disabled. - ProcedurePrepareLatch.releaseLatch(syncLatch, this); - return; - } - - // The delete doesn't have a rollback. The execution will succeed, at some point. - throw new UnsupportedOperationException("unhandled state=" + state); - } - - @Override - protected DeleteTableState getState(final int stateId) { - return DeleteTableState.valueOf(stateId); - } - - @Override - protected int getStateId(final DeleteTableState state) { - return state.getNumber(); - } - - @Override - protected DeleteTableState getInitialState() { - return DeleteTableState.DELETE_TABLE_PRE_OPERATION; - } - - @Override - public TableName getTableName() { - return tableName; - } - - @Override - public TableOperationType getTableOperationType() { - return TableOperationType.DELETE; - } - - @Override - public boolean abort(final MasterProcedureEnv env) { - // TODO: We may be able to abort if the procedure is not started yet. - return false; - } - - @Override - protected boolean acquireLock(final MasterProcedureEnv env) { - if (!env.isInitialized()) return false; - return env.getProcedureQueue().tryAcquireTableExclusiveLock(getTableName(), "delete table"); - } - - @Override - protected void releaseLock(final MasterProcedureEnv env) { - env.getProcedureQueue().releaseTableExclusiveLock(getTableName()); - } - - @Override - public void toStringClassDetails(StringBuilder sb) { - sb.append(getClass().getSimpleName()); - sb.append(" (table="); - sb.append(getTableName()); - sb.append(")"); - } - - @Override - public void serializeStateData(final OutputStream stream) throws IOException { - super.serializeStateData(stream); - - MasterProcedureProtos.DeleteTableStateData.Builder state = - MasterProcedureProtos.DeleteTableStateData.newBuilder() - .setUserInfo(MasterProcedureUtil.toProtoUserInfo(this.user)) - .setTableName(ProtobufUtil.toProtoTableName(tableName)); - if (regions != null) { - for (HRegionInfo hri: regions) { - state.addRegionInfo(HRegionInfo.convert(hri)); - } - } - state.build().writeDelimitedTo(stream); - } - - @Override - public void deserializeStateData(final InputStream stream) throws IOException { - super.deserializeStateData(stream); - - MasterProcedureProtos.DeleteTableStateData state = - MasterProcedureProtos.DeleteTableStateData.parseDelimitedFrom(stream); - user = MasterProcedureUtil.toUserInfo(state.getUserInfo()); - tableName = ProtobufUtil.toTableName(state.getTableName()); - if (state.getRegionInfoCount() == 0) { - regions = null; - } else { - regions = new ArrayList(state.getRegionInfoCount()); - for (HBaseProtos.RegionInfo hri: state.getRegionInfoList()) { - regions.add(HRegionInfo.convert(hri)); - } - } - } - - private boolean prepareDelete(final MasterProcedureEnv env) throws IOException { - try { - env.getMasterServices().checkTableModifiable(tableName); - } catch (TableNotFoundException|TableNotDisabledException e) { - setFailure("master-delete-table", e); - return false; - } - return true; - } - - private boolean preDelete(final MasterProcedureEnv env) - throws IOException, InterruptedException { - final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); - if (cpHost != null) { - final TableName tableName = this.tableName; - user.doAs(new PrivilegedExceptionAction() { - @Override - public Void run() throws Exception { - cpHost.preDeleteTableHandler(tableName); - return null; - } - }); - } - return true; - } - - private void postDelete(final MasterProcedureEnv env) - throws IOException, InterruptedException { - deleteTableStates(env, tableName); - - final MasterCoprocessorHost cpHost = env.getMasterCoprocessorHost(); - if (cpHost != null) { - final TableName tableName = this.tableName; - user.doAs(new PrivilegedExceptionAction() { - @Override - public Void run() throws Exception { - cpHost.postDeleteTableHandler(tableName); - return null; - } - }); - } - } - - protected static void deleteFromFs(final MasterProcedureEnv env, - final TableName tableName, final List regions, - final boolean archive) throws IOException { - final MasterFileSystem mfs = env.getMasterServices().getMasterFileSystem(); - final FileSystem fs = mfs.getFileSystem(); - final Path tempdir = mfs.getTempDir(); - - final Path tableDir = FSUtils.getTableDir(mfs.getRootDir(), tableName); - final Path tempTableDir = FSUtils.getTableDir(tempdir, tableName); - - if (fs.exists(tableDir)) { - // Ensure temp exists - if (!fs.exists(tempdir) && !fs.mkdirs(tempdir)) { - throw new IOException("HBase temp directory '" + tempdir + "' creation failure."); - } - - // Ensure parent exists - if (!fs.exists(tempTableDir.getParent()) && !fs.mkdirs(tempTableDir.getParent())) { - throw new IOException("HBase temp directory '" + tempdir + "' creation failure."); - } - - // Move the table in /hbase/.tmp - if (!fs.rename(tableDir, tempTableDir)) { - if (fs.exists(tempTableDir)) { - // TODO - // what's in this dir? something old? probably something manual from the user... - // let's get rid of this stuff... - FileStatus[] files = fs.listStatus(tempdir); - if (files != null && files.length > 0) { - for (int i = 0; i < files.length; ++i) { - if (!files[i].isDir()) continue; - HFileArchiver.archiveRegion(fs, mfs.getRootDir(), tempTableDir, files[i].getPath()); - } - } - fs.delete(tempdir, true); - } - throw new IOException("Unable to move '" + tableDir + "' to temp '" + tempTableDir + "'"); - } - } - - // Archive regions from FS (temp directory) - if (archive) { - for (HRegionInfo hri : regions) { - LOG.debug("Archiving region " + hri.getRegionNameAsString() + " from FS"); - HFileArchiver.archiveRegion(fs, mfs.getRootDir(), - tempTableDir, HRegion.getRegionDir(tempTableDir, hri.getEncodedName())); - } - LOG.debug("Table '" + tableName + "' archived!"); - } - - // Archive the mob data if there is a mob-enabled column - HTableDescriptor htd = env.getMasterServices().getTableDescriptors().get(tableName); - boolean hasMob = MobUtils.hasMobColumns(htd); - Path mobTableDir = null; - if (hasMob) { - // Archive mob data - mobTableDir = FSUtils.getTableDir(new Path(mfs.getRootDir(), MobConstants.MOB_DIR_NAME), - tableName); - Path regionDir = - new Path(mobTableDir, MobUtils.getMobRegionInfo(tableName).getEncodedName()); - if (fs.exists(regionDir)) { - HFileArchiver.archiveRegion(fs, mfs.getRootDir(), mobTableDir, regionDir); - } - } - - // Delete table directory from FS (temp directory) - if (!fs.delete(tempTableDir, true) && fs.exists(tempTableDir)) { - throw new IOException("Couldn't delete " + tempTableDir); - } - - // Delete the table directory where the mob files are saved - if (hasMob && mobTableDir != null && fs.exists(mobTableDir)) { - if (!fs.delete(mobTableDir, true)) { - throw new IOException("Couldn't delete mob dir " + mobTableDir); - } - } - } - - /** - * There may be items for this table still up in hbase:meta in the case where the - * info:regioninfo column was empty because of some write error. Remove ALL rows from hbase:meta - * that have to do with this table. See HBASE-12980. - * @throws IOException - */ - private static void cleanAnyRemainingRows(final MasterProcedureEnv env, - final TableName tableName) throws IOException { - ClusterConnection connection = env.getMasterServices().getConnection(); - Scan tableScan = MetaTableAccessor.getScanForTableName(connection, tableName); - try (Table metaTable = - connection.getTable(TableName.META_TABLE_NAME)) { - List deletes = new ArrayList(); - try (ResultScanner resScanner = metaTable.getScanner(tableScan)) { - for (Result result : resScanner) { - deletes.add(new Delete(result.getRow())); - } - } - if (!deletes.isEmpty()) { - LOG.warn("Deleting some vestigal " + deletes.size() + " rows of " + tableName + - " from " + TableName.META_TABLE_NAME); - metaTable.delete(deletes); - } - } - } - - protected static void deleteFromMeta(final MasterProcedureEnv env, - final TableName tableName, List regions) throws IOException { - MetaTableAccessor.deleteRegions(env.getMasterServices().getConnection(), regions); - - // Clean any remaining rows for this table. - cleanAnyRemainingRows(env, tableName); - } - - protected static void deleteAssignmentState(final MasterProcedureEnv env, - final TableName tableName) throws IOException { - AssignmentManager am = env.getMasterServices().getAssignmentManager(); - - // Clean up regions of the table in RegionStates. - LOG.debug("Removing '" + tableName + "' from region states."); - am.getRegionStates().tableDeleted(tableName); - - // If entry for this table states, remove it. - LOG.debug("Marking '" + tableName + "' as deleted."); - am.getTableStateManager().setDeletedTable(tableName); - } - - protected static void deleteTableDescriptorCache(final MasterProcedureEnv env, - final TableName tableName) throws IOException { - LOG.debug("Removing '" + tableName + "' descriptor."); - env.getMasterServices().getTableDescriptors().remove(tableName); - } - - protected static void deleteTableStates(final MasterProcedureEnv env, final TableName tableName) - throws IOException { - if (!tableName.isSystemTable()) { - ProcedureSyncWait.getMasterQuotaManager(env).removeTableFromNamespaceQuota(tableName); - } - } -} diff --git a/All/Genesis-NP/Genesis#129/pair.info b/All/Genesis-NP/Genesis#129/pair.info deleted file mode 100755 index da4740b..0000000 --- a/All/Genesis-NP/Genesis#129/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:129 -SATName:Genesis -modifiedFPath:hbase-server/src/main/java/org/apache/hadoop/hbase/master/procedure/DeleteTableProcedure.java -comSha:03e4712f0ca08d57586b3fc4d93cf02c999515d8 -parentComSha:03e4712f0ca08d57586b3fc4d93cf02c999515d8^1 -githubUrl:https://github.com/apache/hbase -repoName:apache#hbase \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#154/comMsg.txt b/All/Genesis-NP/Genesis#154/comMsg.txt deleted file mode 100755 index 599308b..0000000 --- a/All/Genesis-NP/Genesis#154/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix NPE occuring when trying to access start and end nodes of relationships without proper access rights. diff --git a/All/Genesis-NP/Genesis#154/diff.diff b/All/Genesis-NP/Genesis#154/diff.diff deleted file mode 100755 index ab0f0af..0000000 --- a/All/Genesis-NP/Genesis#154/diff.diff +++ /dev/null @@ -1,51 +0,0 @@ -diff --git a/structr-core/src/main/java/org/structr/core/parser/Functions.java b/structr-core/src/main/java/org/structr/core/parser/Functions.java -index 61353ce..71b1b55 100644 ---- a/structr-core/src/main/java/org/structr/core/parser/Functions.java -+++ b/structr-core/src/main/java/org/structr/core/parser/Functions.java -@@ -3270,2 +3270,2 @@ public class Functions { -- AbstractNode sourceNode = null; -- AbstractNode targetNode = null; -+ NodeInterface sourceNode = null; -+ NodeInterface targetNode = null; -@@ -3273 +3273 @@ public class Functions { -- if (source instanceof AbstractNode && target instanceof AbstractNode) { -+ if (source instanceof NodeInterface && target instanceof NodeInterface) { -@@ -3275,2 +3275,2 @@ public class Functions { -- sourceNode = (AbstractNode) source; -- targetNode = (AbstractNode) target; -+ sourceNode = (NodeInterface) source; -+ targetNode = (NodeInterface) target; -@@ -3280 +3280 @@ public class Functions { -- return "Error: entities are not nodes."; -+ return "Error: Entities are not nodes."; -@@ -3287 +3287,12 @@ public class Functions { -- if ( (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { -+ final NodeInterface s = rel.getSourceNode(); -+ final NodeInterface t = rel.getTargetNode(); -+ -+ // We need to check if current user can see source and target node which is often not the case for OWNS or SECURITY rels -+ if ( -+ s != null -+ && t != null -+ && ( -+ (s.equals(sourceNode) && t.equals(targetNode)) -+ || (s.equals(targetNode) && t.equals(sourceNode)) -+ ) -+ ) { -@@ -3299 +3310,15 @@ public class Functions { -- if ( rel.getRelType().name().equals(relType) && ((rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode))) ) { -+ final NodeInterface s = rel.getSourceNode(); -+ final NodeInterface t = rel.getTargetNode(); -+ -+ // We need to check if current user can see source and target node which is often not the case for OWNS or SECURITY rels -+ if ( -+ s != null -+ && t != null -+ && ( -+ rel.getRelType().name().equals(relType) -+ && ( -+ (s.equals(sourceNode) && t.equals(targetNode)) -+ || (s.equals(targetNode) && t.equals(sourceNode)) -+ ) -+ ) -+ ) { diff --git a/All/Genesis-NP/Genesis#154/new/Functions.java b/All/Genesis-NP/Genesis#154/new/Functions.java deleted file mode 100755 index 71b1b55..0000000 --- a/All/Genesis-NP/Genesis#154/new/Functions.java +++ /dev/null @@ -1,3929 +0,0 @@ -/** - * Copyright (C) 2010-2014 Morgner UG (haftungsbeschränkt) - * - * This file is part of Structr . - * - * Structr is free software: you can redistribute it and/or modify it under the - * terms of the GNU General Public License as published by the Free Software - * Foundation, either version 3 of the License, or (at your option) any later - * version. - * - * Structr is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - * A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * Structr. If not, see . - */ -package org.structr.core.parser; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.reflect.TypeToken; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.StreamTokenizer; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.net.URLEncoder; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.Normalizer; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Random; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.apache.commons.mail.EmailException; -import org.neo4j.graphdb.Direction; -import org.neo4j.graphdb.DynamicRelationshipType; -import org.structr.common.GraphObjectComparator; -import org.structr.common.MailHelper; -import org.structr.common.Permission; -import org.structr.common.SecurityContext; -import org.structr.common.error.ErrorToken; -import org.structr.common.error.FrameworkException; -import org.structr.common.error.SemanticErrorToken; -import org.structr.common.geo.GeoCodingResult; -import org.structr.common.geo.GeoHelper; -import org.structr.core.GraphObject; -import org.structr.core.GraphObjectMap; -import org.structr.core.Services; -import org.structr.core.app.App; -import org.structr.core.app.Query; -import org.structr.core.app.StructrApp; -import org.structr.core.converter.PropertyConverter; -import org.structr.core.entity.AbstractNode; -import org.structr.core.entity.AbstractRelationship; -import org.structr.core.entity.MailTemplate; -import org.structr.core.entity.Principal; -import org.structr.core.graph.NodeInterface; -import org.structr.core.graph.RelationshipFactory; -import org.structr.core.graph.RelationshipInterface; -import org.structr.core.property.ISO8601DateProperty; -import org.structr.core.property.PropertyKey; -import org.structr.core.property.PropertyMap; -import org.structr.core.property.StringProperty; -import org.structr.core.script.Scripting; -import org.structr.schema.ConfigurationProvider; -import org.structr.schema.action.ActionContext; -import org.structr.schema.action.Function; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * - * @author Christian Morgner - */ -public class Functions { - - private static final Logger logger = Logger.getLogger(Functions.class.getName()); - public static final Map> functions = new LinkedHashMap<>(); - - public static final String NULL_STRING = "___NULL___"; - - public static final String ERROR_MESSAGE_MD5 = "Usage: ${md5(string)}. Example: ${md5(this.email)}"; - public static final String ERROR_MESSAGE_ERROR = "Usage: ${error(...)}. Example: ${error(\"base\", \"must_equal\", int(5))}"; - public static final String ERROR_MESSAGE_UPPER = "Usage: ${upper(string)}. Example: ${upper(this.nickName)}"; - public static final String ERROR_MESSAGE_LOWER = "Usage: ${lower(string)}. Example: ${lower(this.email)}"; - public static final String ERROR_MESSAGE_JOIN = "Usage: ${join(collection, separator)}. Example: ${join(this.names, \",\")}"; - public static final String ERROR_MESSAGE_CONCAT = "Usage: ${concat(values...)}. Example: ${concat(this.firstName, this.lastName)}"; - public static final String ERROR_MESSAGE_SPLIT = "Usage: ${split(value)}. Example: ${split(this.commaSeparatedItems)}"; - public static final String ERROR_MESSAGE_ABBR = "Usage: ${abbr(longString, maxLength)}. Example: ${abbr(this.title, 20)}"; - public static final String ERROR_MESSAGE_CAPITALIZE = "Usage: ${capitalize(string)}. Example: ${capitalize(this.nickName)}"; - public static final String ERROR_MESSAGE_TITLEIZE = "Usage: ${titleize(string, separator}. (Default separator is \" \") Example: ${titleize(this.lowerCamelCaseString, \"_\")}"; - public static final String ERROR_MESSAGE_NUM = "Usage: ${num(string)}. Example: ${num(this.numericalStringValue)}"; - public static final String ERROR_MESSAGE_INT = "Usage: ${int(string)}. Example: ${int(this.numericalStringValue)}"; - public static final String ERROR_MESSAGE_RANDOM = "Usage: ${random(num)}. Example: ${set(this, \"password\", random(8))}"; - public static final String ERROR_MESSAGE_RINT = "Usage: ${rint(range)}. Example: ${rint(1000)}"; - public static final String ERROR_MESSAGE_INDEX_OF = "Usage: ${index_of(string, word)}. Example: ${index_of(this.name, \"the\")}"; - public static final String ERROR_MESSAGE_CONTAINS = "Usage: ${contains(string, word)}. Example: ${contains(this.name, \"the\")}"; - public static final String ERROR_MESSAGE_SUBSTRING = "Usage: ${substring(string, start, length)}. Example: ${substring(this.name, 19, 3)}"; - public static final String ERROR_MESSAGE_LENGTH = "Usage: ${length(string)}. Example: ${length(this.name)}"; - public static final String ERROR_MESSAGE_REPLACE = "Usage: ${replace(template, source)}. Example: ${replace(\"${this.id}\", this)}"; - public static final String ERROR_MESSAGE_CLEAN = "Usage: ${clean(string)}. Example: ${clean(this.stringWithNonWordChars)}"; - public static final String ERROR_MESSAGE_URLENCODE = "Usage: ${urlencode(string)}. Example: ${urlencode(this.email)}"; - public static final String ERROR_MESSAGE_ESCAPE_JS = "Usage: ${escape_javascript(string)}. Example: ${escape_javascript(this.name)}"; - public static final String ERROR_MESSAGE_IF = "Usage: ${if(condition, trueValue, falseValue)}. Example: ${if(empty(this.name), this.nickName, this.name)}"; - public static final String ERROR_MESSAGE_EMPTY = "Usage: ${empty(string)}. Example: ${if(empty(possibleEmptyString), \"empty\", \"non-empty\")}"; - public static final String ERROR_MESSAGE_EQUAL = "Usage: ${equal(value1, value2)}. Example: ${equal(this.children.size, 0)}"; - public static final String ERROR_MESSAGE_ADD = "Usage: ${add(values...)}. Example: ${add(1, 2, 3, this.children.size)}"; - public static final String ERROR_MESSAGE_INT_SUM = "Usage: ${int_sum(list)}. Example: ${int_sum(extract(this.children, \"number\"))}"; - public static final String ERROR_MESSAGE_DOUBLE_SUM = "Usage: ${double_sum(list)}. Example: ${double_sum(extract(this.children, \"amount\"))}"; - public static final String ERROR_MESSAGE_IS_COLLECTION = "Usage: ${is_collection(value)}. Example: ${is_collection(this)}"; - public static final String ERROR_MESSAGE_IS_ENTITY = "Usage: ${is_entity(value)}. Example: ${is_entity(this)}"; - public static final String ERROR_MESSAGE_EXTRACT = "Usage: ${extract(list, propertyName)}. Example: ${extract(this.children, \"amount\")}"; - public static final String ERROR_MESSAGE_FILTER = "Usage: ${filter(list, expression)}. Example: ${filter(this.children, gt(size(data.children), 0))}"; - public static final String ERROR_MESSAGE_MERGE = "Usage: ${merge(list1, list2, list3, ...)}. Example: ${merge(this.children, this.siblings)}"; - public static final String ERROR_MESSAGE_COMPLEMENT = "Usage: ${complement(list1, list2, list3, ...)}. (The resulting list contains no duplicates) Example: ${merge(allUsers, me)} => List of all users except myself"; - public static final String ERROR_MESSAGE_UNWIND = "Usage: ${unwind(list1, ...)}. Example: ${unwind(this.children)}"; - public static final String ERROR_MESSAGE_SORT = "Usage: ${sort(list1, key [, true])}. Example: ${sort(this.children, \"name\")}"; - public static final String ERROR_MESSAGE_LT = "Usage: ${lt(value1, value2)}. Example: ${if(lt(this.children, 2), \"Less than two\", \"Equal to or more than two\")}"; - public static final String ERROR_MESSAGE_GT = "Usage: ${gt(value1, value2)}. Example: ${if(gt(this.children, 2), \"More than two\", \"Equal to or less than two\")}"; - public static final String ERROR_MESSAGE_LTE = "Usage: ${lte(value1, value2)}. Example: ${if(lte(this.children, 2), \"Equal to or less than two\", \"More than two\")}"; - public static final String ERROR_MESSAGE_GTE = "Usage: ${gte(value1, value2)}. Example: ${if(gte(this.children, 2), \"Equal to or more than two\", \"Less than two\")}"; - public static final String ERROR_MESSAGE_SUBT = "Usage: ${subt(value1, value)}. Example: ${subt(5, 2)}"; - public static final String ERROR_MESSAGE_MULT = "Usage: ${mult(value1, value)}. Example: ${mult(5, 2)}"; - public static final String ERROR_MESSAGE_QUOT = "Usage: ${quot(value1, value)}. Example: ${quot(5, 2)}"; - public static final String ERROR_MESSAGE_ROUND = "Usage: ${round(value1 [, decimalPlaces])}. Example: ${round(2.345678, 2)}"; - public static final String ERROR_MESSAGE_MAX = "Usage: ${max(value1, value2)}. Example: ${max(this.children, 10)}"; - public static final String ERROR_MESSAGE_MIN = "Usage: ${min(value1, value2)}. Example: ${min(this.children, 5)}"; - public static final String ERROR_MESSAGE_CONFIG = "Usage: ${config(keyFromStructrConf)}. Example: ${config(\"base.path\")}"; - public static final String ERROR_MESSAGE_DATE_FORMAT = "Usage: ${date_format(value, pattern)}. Example: ${date_format(this.creationDate, \"yyyy-MM-dd'T'HH:mm:ssZ\")}"; - public static final String ERROR_MESSAGE_PARSE_DATE = "Usage: ${parse_date(value, pattern)}. Example: ${parse_format(\"2014-01-01\", \"yyyy-MM-dd\")}"; - public static final String ERROR_MESSAGE_NUMBER_FORMAT = "Usage: ${number_format(value, ISO639LangCode, pattern)}. Example: ${number_format(12345.6789, 'en', '#,##0.00')}"; - public static final String ERROR_MESSAGE_TEMPLATE = "Usage: ${template(name, locale, source)}. Example: ${template(\"TEXT_TEMPLATE_1\", \"en_EN\", this)}"; - public static final String ERROR_MESSAGE_NOT = "Usage: ${not(bool1, bool2)}. Example: ${not(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_AND = "Usage: ${and(bool1, bool2)}. Example: ${and(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_OR = "Usage: ${or(bool1, bool2)}. Example: ${or(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_GET = "Usage: ${get(entity, propertyKey)}. Example: ${get(this, \"children\")}"; - public static final String ERROR_MESSAGE_GET_ENTITY = "Cannot evaluate first argument to entity, must be entity or single element list of entities."; - public static final String ERROR_MESSAGE_SIZE = "Usage: ${size(collection)}. Example: ${size(this.children)}"; - public static final String ERROR_MESSAGE_FIRST = "Usage: ${first(collection)}. Example: ${first(this.children)}"; - public static final String ERROR_MESSAGE_LAST = "Usage: ${last(collection)}. Example: ${last(this.children)}"; - public static final String ERROR_MESSAGE_NTH = "Usage: ${nth(collection)}. Example: ${nth(this.children, 2)}"; - public static final String ERROR_MESSAGE_GET_COUNTER = "Usage: ${get_counter(level)}. Example: ${get_counter(1)}"; - public static final String ERROR_MESSAGE_INC_COUNTER = "Usage: ${inc_counter(level, [resetLowerLevels])}. Example: ${inc_counter(1, true)}"; - public static final String ERROR_MESSAGE_RESET_COUNTER = "Usage: ${reset_counter(level)}. Example: ${reset_counter(1)}"; - public static final String ERROR_MESSAGE_MERGE_PROPERTIES = "Usage: ${merge_properties(source, target , mergeKeys...)}. Example: ${merge_properties(this, parent, \"eMail\")}"; - public static final String ERROR_MESSAGE_KEYS = "Usage: ${keys(entity, viewName)}. Example: ${keys(this, \"ui\")}"; - public static final String ERROR_MESSAGE_EACH = "Usage: ${each(collection, expression)}. Example: ${each(this.children, \"set(this, \"email\", lower(get(this.email))))\")}"; - public static final String ERROR_MESSAGE_STORE = "Usage: ${store(key, value)}. Example: ${store('tmpUser', this.owner)}"; - public static final String ERROR_MESSAGE_RETRIEVE = "Usage: ${retrieve(key)}. Example: ${retrieve('tmpUser')}"; - public static final String ERROR_MESSAGE_PRINT = "Usage: ${print(objects...)}. Example: ${print(this.name, \"test\")}"; - public static final String ERROR_MESSAGE_READ = "Usage: ${read(filename)}. Example: ${read(\"text.xml\")}"; - public static final String ERROR_MESSAGE_WRITE = "Usage: ${write(filename, value)}. Example: ${write(\"text.txt\", this.name)}"; - public static final String ERROR_MESSAGE_APPEND = "Usage: ${append(filename, value)}. Example: ${append(\"test.txt\", this.name)}"; - public static final String ERROR_MESSAGE_XML = "Usage: ${xml(xmlSource)}. Example: ${xpath(xml(this.xmlSource), \"/test/testValue\")}"; - public static final String ERROR_MESSAGE_XPATH = "Usage: ${xpath(xmlDocument, expression)}. Example: ${xpath(xml(this.xmlSource), \"/test/testValue\")}"; - public static final String ERROR_MESSAGE_SET = "Usage: ${set(entity, propertyKey, value)}. Example: ${set(this, \"email\", lower(this.email))}"; - public static final String ERROR_MESSAGE_SEND_PLAINTEXT_MAIL = "Usage: ${send_plaintext_mail(fromAddress, fromName, toAddress, toName, subject, content)}."; - public static final String ERROR_MESSAGE_SEND_HTML_MAIL = "Usage: ${send_html_mail(fromAddress, fromName, toAddress, toName, subject, content)}."; - public static final String ERROR_MESSAGE_GEOCODE = "Usage: ${geocode(street, city, country)}. Example: ${set(this, geocode(this.street, this.city, this.country))}"; - public static final String ERROR_MESSAGE_FIND = "Usage: ${find(type, key, value)}. Example: ${find(\"User\", \"email\", \"tester@test.com\"}"; - public static final String ERROR_MESSAGE_SEARCH = "Usage: ${search(type, key, value)}. Example: ${search(\"User\", \"name\", \"abc\"}"; - public static final String ERROR_MESSAGE_CREATE = "Usage: ${create(type, key, value)}. Example: ${create(\"Feedback\", \"text\", this.text)}"; - public static final String ERROR_MESSAGE_DELETE = "Usage: ${delete(entity)}. Example: ${delete(this)}"; - public static final String ERROR_MESSAGE_CACHE = "Usage: ${cache(key, timeout, valueExpression)}. Example: ${cache('value', 60, GET('http://rate-limited-URL.com'))}"; - public static final String ERROR_MESSAGE_GRANT = "Usage: ${grant(principal, node, permissions)}. Example: ${grant(me, this, 'read, write, delete'))}"; - public static final String ERROR_MESSAGE_REVOKE = "Usage: ${revoke(principal, node, permissions)}. Example: ${revoke(me, this, 'write, delete'))}"; - - // Special functions for relationships - public static final String ERROR_MESSAGE_INCOMING = "Usage: ${incoming(entity [, relType])}. Example: ${incoming(this, 'PARENT_OF')}"; - public static final String ERROR_MESSAGE_OUTGOING = "Usage: ${outgoing(entity [, relType])}. Example: ${outgoing(this, 'PARENT_OF')}"; - public static final String ERROR_MESSAGE_HAS_RELATIONSHIP = "Usage: ${has_relationship(entity1, entity2 [, relType])}. Example: ${has_relationship(me, user, 'FOLLOWS')} (ignores direction of the relationship)"; - public static final String ERROR_MESSAGE_HAS_OUTGOING_RELATIONSHIP = "Usage: ${has_outgoing_relationship(from, to [, relType])}. Example: ${has_outgoing_relationship(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_HAS_INCOMING_RELATIONSHIP = "Usage: ${has_incoming_relationship(from, to [, relType])}. Example: ${has_incoming_relationship(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_GET_RELATIONSHIPS = "Usage: ${get_relationships(entity1, entity2 [, relType])}. Example: ${get_relationships(me, user, 'FOLLOWS')} (ignores direction of the relationship)"; - public static final String ERROR_MESSAGE_GET_OUTGOING_RELATIONSHIPS = "Usage: ${get_outgoing_relationships(from, to [, relType])}. Example: ${get_outgoing_relationships(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_GET_INCOMING_RELATIONSHIPS = "Usage: ${get_incoming_relationships(from, to [, relType])}. Example: ${get_incoming_relationships(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_CREATE_RELATIONSHIP = "Usage: ${create_relationship(from, to, relType)}. Example: ${create_relationship(me, user, 'FOLLOWS')} (Relationshiptype has to exist)"; - - public static Function get(final String name) { - return functions.get(name); - } - - public static Object evaluate(final ActionContext actionContext, final GraphObject entity, final String expression) throws FrameworkException { - - final String expressionWithoutNewlines = expression.replace('\n', ' '); - final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(expressionWithoutNewlines)); - tokenizer.eolIsSignificant(true); - tokenizer.ordinaryChar('.'); - tokenizer.wordChars('_', '_'); - tokenizer.wordChars('.', '.'); - tokenizer.wordChars('!', '!'); - - Expression root = new RootExpression(); - Expression current = root; - Expression next = null; - String lastToken = null; - int token = 0; - int level = 0; - - while (token != StreamTokenizer.TT_EOF) { - - token = nextToken(tokenizer); - - switch (token) { - - case StreamTokenizer.TT_EOF: - break; - - case StreamTokenizer.TT_EOL: - break; - - case StreamTokenizer.TT_NUMBER: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before NUMBER"); - } - next = new ConstantExpression(tokenizer.nval); - current.add(next); - lastToken += "NUMBER"; - break; - - case StreamTokenizer.TT_WORD: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval); - } - next = checkReservedWords(tokenizer.sval); - current.add(next); - lastToken = tokenizer.sval; - break; - - case '(': - if (((current == null || current instanceof RootExpression) && next == null) || current == next) { - - // an additional bracket without a new function, - // this can only be an execution group. - next = new GroupExpression(); - current.add(next); - } - - current = next; - lastToken += "("; - level++; - break; - - case ')': - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + lastToken); - } - current = current.getParent(); - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - lastToken += ")"; - level--; - break; - - case '[': - // bind directly to the previous expression - next = new ArrayExpression(); - current.add(next); - current = next; - lastToken += "["; - level++; - break; - - case ']': - - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket before " + lastToken); - } - current = current.getParent(); - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - lastToken += "]"; - level--; - break; - - case ';': - next = null; - lastToken += ";"; - break; - - case ',': - next = current; - lastToken += ","; - break; - - default: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval); - } - current.add(new ConstantExpression(tokenizer.sval)); - lastToken = tokenizer.sval; - - } - } - - if (level > 0) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - - return root.evaluate(actionContext, entity); - } - - private static Expression checkReservedWords(final String word) throws FrameworkException { - - if (word == null) { - return new NullExpression(); - } - - switch (word) { - - case "cache": - return new CacheExpression(); - - case "true": - return new ConstantExpression(true); - - case "false": - return new ConstantExpression(false); - - case "if": - return new IfExpression(); - - case "each": - return new EachExpression(); - - case "filter": - return new FilterExpression(); - - case "data": - return new ValueExpression("data"); - - case "null": - return new ConstantExpression(NULL_STRING); - } - - // no match, try functions - final Function function = Functions.get(word); - if (function != null) { - - return new FunctionExpression(word, function); - - } else { - - return new ValueExpression(word); - } - } - - public static int nextToken(final StreamTokenizer tokenizer) { - - try { - - return tokenizer.nextToken(); - - } catch (IOException ioex) { - } - - return StreamTokenizer.TT_EOF; - } - - static { - - functions.put("error", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entity.getClass(), sources[0].toString()); - ctx.raiseError(entity.getType(), new ErrorToken(422, key) { - - @Override - public JsonElement getContent() { - return new JsonPrimitive(getErrorToken()); - } - - @Override - public String getErrorToken() { - return sources[1].toString(); - } - }); - - } else if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entity.getClass(), sources[0].toString()); - ctx.raiseError(entity.getType(), new SemanticErrorToken(key) { - - @Override - public JsonElement getContent() { - - JsonObject obj = new JsonObject(); - - if (sources[2] instanceof Number) { - - obj.add(getErrorToken(), new JsonPrimitive((Number) sources[2])); - - } else if (sources[2] instanceof Boolean) { - - obj.add(getErrorToken(), new JsonPrimitive((Boolean) sources[2])); - - } else { - - obj.add(getErrorToken(), new JsonPrimitive(sources[2].toString())); - } - - return obj; - } - - @Override - public String getErrorToken() { - return sources[1].toString(); - } - }); - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_ERROR; - } - }); - functions.put("md5", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? DigestUtils.md5Hex(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MD5; - } - }); - functions.put("upper", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? sources[0].toString().toUpperCase() - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_UPPER; - } - - }); - functions.put("lower", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? sources[0].toString().toLowerCase() - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LOWER; - } - - }); - functions.put("join", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof Collection) { - - return StringUtils.join((Collection) sources[0], sources[1].toString()); - } - - if (sources[0].getClass().isArray()) { - - return StringUtils.join((Object[]) sources[0], sources[1].toString()); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_JOIN; - } - - }); - functions.put("concat", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - // collection can contain nulls.. - if (source != null) { - - if (source instanceof Collection) { - - list.addAll((Collection) source); - - } else if (source.getClass().isArray()) { - - list.addAll(Arrays.asList((Object[])source)); - - } else { - - list.add(source); - } - } - } - - return StringUtils.join(list, ""); - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONCAT; - } - - }); - functions.put("split", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final String toSplit = sources[0].toString(); - String splitExpr = "[,;]+"; - - if (sources.length >= 2) { - splitExpr = sources[1].toString(); - } - - return Arrays.asList(toSplit.split(splitExpr)); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SPLIT; - } - - }); - functions.put("abbr", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - try { - int maxLength = Double.valueOf(sources[1].toString()).intValue(); - - if (sources[0].toString().length() > maxLength) { - - return StringUtils.substringBeforeLast(StringUtils.substring(sources[0].toString(), 0, maxLength), " ").concat("…"); - - } else { - - return sources[0]; - } - - } catch (NumberFormatException nfe) { - - return nfe.getMessage(); - - } - - } - - return ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ABBR; - } - - }); - functions.put("capitalize", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? StringUtils.capitalize(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_CAPITALIZE; - } - }); - functions.put("titleize", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources[0] == null) { - return null; - } - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - final String separator; - if (sources.length < 2) { - separator = " "; - } else { - separator = sources[1].toString(); - } - - String[] in = StringUtils.split(sources[0].toString(), separator); - String[] out = new String[in.length]; - for (int i = 0; i < in.length; i++) { - out[i] = StringUtils.capitalize(in[i]); - } - return StringUtils.join(out, " "); - - } - - @Override - public String usage() { - return ERROR_MESSAGE_TITLEIZE; - } - - }); - functions.put("num", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - return getDoubleOrNull(sources[0]); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NUM; - } - }); - functions.put("int", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Number) { - return ((Number) sources[0]).intValue(); - } - - try { - return getDoubleOrNull(sources[0]).intValue(); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INT; - } - }); - functions.put("random", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof Number) { - - try { - return RandomStringUtils.randomAlphanumeric(((Number) sources[0]).intValue()); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RANDOM; - } - }); - functions.put("rint", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof Number) { - - try { - return new Random(System.currentTimeMillis()).nextInt(((Number) sources[0]).intValue()); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RINT; - } - }); - functions.put("index_of", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final String source = sources[0].toString(); - final String part = sources[1].toString(); - - return source.indexOf(part); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INDEX_OF; - } - }); - functions.put("contains", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof String && sources[1] instanceof String) { - - final String source = sources[0].toString(); - final String part = sources[1].toString(); - - return source.contains(part); - - } else if (sources[0] instanceof Collection && sources[1] instanceof GraphObject) { - - final Collection collection = (Collection) sources[0]; - final GraphObject obj = (GraphObject) sources[1]; - - return collection.contains(obj); - - } else if (sources[0].getClass().isArray()) { - - return ArrayUtils.contains((Object[])sources[0], sources[1]); - } - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONTAINS; - } - }); - functions.put("substring", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final String source = sources[0].toString(); - final int sourceLength = source.length(); - final int start = parseInt(sources[1]); - final int length = sources.length >= 3 ? parseInt(sources[2]) : sourceLength - start; - final int end = start + length; - - if (start >= 0 && start < sourceLength && end >= 0 && end <= sourceLength && start <= end) { - - return source.substring(start, end); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBSTRING; - } - }); - functions.put("length", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - return sources[0].toString().length(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBSTRING; - } - }); - functions.put("replace", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final String template = sources[0].toString(); - AbstractNode node = null; - - if (sources[1] instanceof AbstractNode) { - node = (AbstractNode) sources[1]; - } - - if (sources[1] instanceof List) { - - final List list = (List) sources[1]; - if (list.size() == 1 && list.get(0) instanceof AbstractNode) { - - node = (AbstractNode) list.get(0); - } - } - - if (node != null) { - - // recursive replacement call, be careful here - return Scripting.replaceVariables(ctx, node, template); - } - - return ""; - } - - return usage(); - - } - - @Override - public String usage() { - return ERROR_MESSAGE_REPLACE; - } - }); - functions.put("clean", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - return cleanString(sources[0]); - } - - return null; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_CLEAN; - } - - }); - functions.put("urlencode", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? encodeURL(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_URLENCODE; - } - - }); - functions.put("escape_javascript", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? StringEscapeUtils.escapeEcmaScript(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ESCAPE_JS; - } - - }); - functions.put("if", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources[0] == null || sources.length < 3) { - - return ""; - } - - if ("true".equals(sources[0]) || Boolean.TRUE.equals(sources[0])) { - - return sources[1]; - - } else { - - return sources[2]; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IF; - } - - }); - functions.put("empty", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources.length == 0 || sources[0] == null || StringUtils.isEmpty(sources[0].toString())) { - - return true; - - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_EMPTY; - } - - }); - functions.put("equal", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - logger.log(Level.FINE, "Length: {0}", sources.length); - - if (sources.length < 2) { - - return true; - } - - logger.log(Level.FINE, "Comparing {0} to {1}", new java.lang.Object[]{sources[0], sources[1]}); - - if (sources[0] == null && sources[1] == null) { - return true; - } - - if (sources[0] == null || sources[1] == null) { - return false; - } - - return valueEquals(sources[0], sources[1]); - } - - @Override - public String usage() { - return ERROR_MESSAGE_EQUAL; - } - - }); - functions.put("eq", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return functions.get("equal").apply(ctx, entity, sources); - } - - @Override - public String usage() { - - return functions.get("equal").usage(); - } - - }); - functions.put("add", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Double result = 0.0; - - if (sources != null) { - - for (Object i : sources) { - - if (i != null) { - - try { - - result += Double.parseDouble(i.toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - result += 0.0; - } - } - - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ADD; - } - - }); - functions.put("double_sum", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - double result = 0.0; - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Collection) { - - for (final Number num : (Collection) sources[0]) { - - result += num.doubleValue(); - } - } - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_DOUBLE_SUM; - } - - }); - functions.put("int_sum", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - int result = 0; - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Collection) { - - for (final Number num : (Collection) sources[0]) { - - result += num.intValue(); - } - } - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_INT_SUM; - } - - }); - functions.put("is_collection", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - return (sources[0] instanceof Collection); - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IS_COLLECTION; - } - - }); - functions.put("is_entity", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - return (sources[0] instanceof GraphObject); - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IS_ENTITY; - } - - }); - functions.put("extract", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - // no property key given, maybe we should extract a list of lists? - if (sources[0] instanceof Collection) { - - final List extraction = new LinkedList(); - - for (final Object obj : (Collection) sources[0]) { - - if (obj instanceof Collection) { - - extraction.addAll((Collection) obj); - } - } - - return extraction; - } - - } else if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof Collection && sources[1] instanceof String) { - - final ConfigurationProvider config = StructrApp.getConfiguration(); - final List extraction = new LinkedList(); - final String keyName = (String) sources[1]; - - for (final Object obj : (Collection) sources[0]) { - - if (obj instanceof GraphObject) { - - final PropertyKey key = config.getPropertyKeyForJSONName(obj.getClass(), keyName); - final Object value = ((GraphObject) obj).getProperty(key); - if (value != null) { - - extraction.add(value); - } - } - } - - return extraction; - } - } - - return null; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_EXTRACT; - } - - }); - functions.put("merge", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - - if (obj != null) { - - list.add(obj); - } - } - - } else if (source != null) { - - list.add(source); - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE; - } - - }); - functions.put("complement", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final Set sourceSet = new HashSet(); - - if (sources[0] instanceof Collection) { - - sourceSet.addAll((Collection)sources[0]); - - for (int cnt = 1; cnt < sources.length; cnt++) { - - final Object source = sources[cnt]; - - if (source instanceof Collection) { - - sourceSet.removeAll((Collection)source); - - } else if (source != null) { - - sourceSet.remove(source); - } - } - - } else { - - return "Argument 1 for complement must be a Collection"; - } - - return sourceSet; - } - - @Override - public String usage() { - return ERROR_MESSAGE_COMPLEMENT; - } - - }); - functions.put("unwind", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - if (obj != null) { - - if (obj instanceof Collection) { - - for (final Object elem : (Collection) obj) { - - if (elem != null) { - - list.add(elem); - } - } - - } else { - - list.add(obj); - } - } - } - - } else if (source != null) { - - list.add(source); - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_UNWIND; - } - - }); - functions.put("sort", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof List && sources[1] instanceof String) { - - final List list = (List) sources[0]; - final String sortKey = sources[1].toString(); - final Iterator iterator = list.iterator(); - - if (iterator.hasNext()) { - - final Object firstElement = iterator.next(); - if (firstElement instanceof GraphObject) { - - final Class type = firstElement.getClass(); - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(type, sortKey); - final boolean descending = sources.length == 3 && sources[2] != null && "true".equals(sources[2].toString()); - - if (key != null) { - - List sortCollection = (List) list; - Collections.sort(sortCollection, new GraphObjectComparator(key, descending)); - } - } - - } - } - } - - return sources[0]; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SORT; - } - - }); - functions.put("lt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 < value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LT; - } - }); - functions.put("gt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 > value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_GT; - } - }); - functions.put("lte", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 <= value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LTE; - } - }); - functions.put("gte", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 >= value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_GTE; - } - }); - functions.put("subt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - try { - - Double result = Double.parseDouble(sources[0].toString()); - - for (int i = 1; i < sources.length; i++) { - - result -= Double.parseDouble(sources[i].toString()); - - } - - return result; - - } catch (Throwable t) { - - return t.getMessage(); - - } - } - - return ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBT; - } - }); - functions.put("mult", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Double result = 1.0d; - - if (sources != null) { - - for (Object i : sources) { - - try { - - result *= Double.parseDouble(i.toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - } - - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MULT; - } - }); - functions.put("quot", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - - return Double.parseDouble(sources[0].toString()) / Double.parseDouble(sources[1].toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - if (sources != null) { - - if (sources.length > 0 && sources[0] != null) { - return Double.valueOf(sources[0].toString()); - } - - return ""; - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_QUOT; - } - }); - functions.put("round", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - try { - - Double f1 = Double.parseDouble(sources[0].toString()); - double f2 = Math.pow(10, (Double.parseDouble(sources[1].toString()))); - long r = Math.round(f1 * f2); - - return (double) r / f2; - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - return ""; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_ROUND; - } - }); - functions.put("max", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Object result = ""; - String errorMsg = "ERROR! Usage: ${max(val1, val2)}. Example: ${max(5,10)}"; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - result = Math.max(Double.parseDouble(sources[0].toString()), Double.parseDouble(sources[1].toString())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Could not determine max() of {0} and {1}", new Object[]{sources[0], sources[1]}); - result = errorMsg; - } - - } else { - - result = ""; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MAX; - } - }); - functions.put("min", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Object result = ""; - String errorMsg = "ERROR! Usage: ${min(val1, val2)}. Example: ${min(5,10)}"; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - result = Math.min(Double.parseDouble(sources[0].toString()), Double.parseDouble(sources[1].toString())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Could not determine min() of {0} and {1}", new Object[]{sources[0], sources[1]}); - result = errorMsg; - } - - } else { - - result = ""; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MIN; - } - }); - functions.put("config", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final String configKey = sources[0].toString(); - final String defaultValue = sources.length >= 2 ? sources[1].toString() : ""; - - return StructrApp.getConfigurationValue(configKey, defaultValue); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONFIG; - } - }); - functions.put("date_format", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 2) { - return ERROR_MESSAGE_DATE_FORMAT; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - Date date = null; - - if (sources[0] instanceof Date) { - - date = (Date) sources[0]; - - } else if (sources[0] instanceof Number) { - - date = new Date(((Number) sources[0]).longValue()); - - } else { - - try { - - // parse with format from IS - date = new SimpleDateFormat(ISO8601DateProperty.PATTERN).parse(sources[0].toString()); - - } catch (ParseException ex) { - ex.printStackTrace(); - } - - } - - // format with given pattern - return new SimpleDateFormat(sources[1].toString()).format(date); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_DATE_FORMAT; - } - }); - functions.put("parse_date", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 2) { - return ERROR_MESSAGE_PARSE_DATE; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - String dateString = sources[0].toString(); - - if (StringUtils.isBlank(dateString)) { - return ""; - } - - String pattern = sources[1].toString(); - - try { - // parse with format from IS - return new SimpleDateFormat(pattern).parse(dateString); - - } catch (ParseException ex) { - logger.log(Level.WARNING, "Could not parse date " + dateString + " and format it to pattern " + pattern, ex); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_PARSE_DATE; - } - }); - functions.put("number_format", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 3) { - return ERROR_MESSAGE_NUMBER_FORMAT; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - try { - - Double val = Double.parseDouble(sources[0].toString()); - String langCode = sources[1].toString(); - String pattern = sources[2].toString(); - - return new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.forLanguageTag(langCode))).format(val); - - } catch (Throwable t) { - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NUMBER_FORMAT; - } - }); - functions.put("template", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 3) { - return ERROR_MESSAGE_TEMPLATE; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 3) && sources[2] instanceof AbstractNode) { - - final App app = StructrApp.getInstance(entity.getSecurityContext()); - final String name = sources[0].toString(); - final String locale = sources[1].toString(); - final MailTemplate template = app.nodeQuery(MailTemplate.class).andName(name).and(MailTemplate.locale, locale).getFirst(); - final AbstractNode templateInstance = (AbstractNode) sources[2]; - - if (template != null) { - - final String text = template.getProperty(MailTemplate.text); - if (text != null) { - - // recursive replacement call, be careful here - return Scripting.replaceVariables(ctx, templateInstance, text); - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_TEMPLATE; - } - }); - functions.put("not", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - return !("true".equals(sources[0].toString()) || Boolean.TRUE.equals(sources[0])); - - } - - return true; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NOT; - } - - }); - functions.put("and", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - boolean result = true; - - if (sources != null) { - - if (sources.length < 2) { - return usage(); - } - - for (Object i : sources) { - - if (i != null) { - - try { - - result &= "true".equals(i.toString()) || Boolean.TRUE.equals(i); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - // null is false - return false; - } - } - - } - - return result; - } - - @Override - public String usage() { - return ERROR_MESSAGE_AND; - } - - }); - functions.put("or", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - boolean result = false; - - if (sources != null) { - - if (sources.length < 2) { - return usage(); - } - - for (Object i : sources) { - - if (i != null) { - - try { - - result |= "true".equals(i.toString()) || Boolean.TRUE.equals(i); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - // null is false - result |= false; - } - } - - } - - return result; - } - - @Override - public String usage() { - return ERROR_MESSAGE_OR; - } - }); - functions.put("get", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final SecurityContext securityContext = entity.getSecurityContext(); - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - GraphObject dataObject = null; - - if (sources[0] instanceof GraphObject) { - dataObject = (GraphObject) sources[0]; - } - - if (sources[0] instanceof List) { - - final List list = (List) sources[0]; - if (list.size() == 1 && list.get(0) instanceof GraphObject) { - - dataObject = (GraphObject) list.get(0); - } - } - - if (dataObject != null) { - - final String keyName = sources[1].toString(); - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(dataObject.getClass(), keyName); - - if (key != null) { - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = dataObject.getProperty(key); - - if (inputConverter != null) { - return inputConverter.revert(value); - } - - return dataObject.getProperty(key); - } - - return ""; - - } else { - - return ERROR_MESSAGE_GET_ENTITY; - } - } - - return usage(); - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET; - } - }); - functions.put("size", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source != null) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - if (obj != null && !NULL_STRING.equals(obj)) { - - list.add(obj); - } - } - - } else if(source.getClass().isArray()) { - - list.addAll(Arrays.asList((Object[])source)); - - } else if (source != null && !NULL_STRING.equals(source)) { - - list.add(source); - } - - return list.size(); - } - } - - return 0; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SIZE; - } - }); - functions.put("first", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - return ((List) sources[0]).get(0); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (arr.length > 0) { - - return arr[0]; - } - } - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIRST; - } - }); - functions.put("last", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - - final List list = (List) sources[0]; - return list.get(list.size() - 1); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (arr.length > 0) { - - return arr[arr.length - 1]; - } - } - - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_LAST; - } - }); - functions.put("nth", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final int pos = Double.valueOf(sources[1].toString()).intValue(); - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - - final List list = (List) sources[0]; - final int size = list.size(); - - if (pos >= size) { - - return null; - - } - - return list.get(Math.min(Math.max(0, pos), size - 1)); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (pos <= arr.length) { - - return arr[pos]; - } - } - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NTH; - } - }); - functions.put("get_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - return ctx.getCounter(parseInt(sources[0])); - } - - return 0; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_COUNTER; - } - }); - functions.put("inc_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final int level = parseInt(sources[0]); - - ctx.incrementCounter(level); - - // reset lower levels? - if (sources.length == 2 && "true".equals(sources[1].toString())) { - - // reset lower levels - for (int i = level + 1; i < 10; i++) { - ctx.resetCounter(i); - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INC_COUNTER; - } - }); - functions.put("reset_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - ctx.resetCounter(parseInt(sources[0])); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RESET_COUNTER; - } - }); - functions.put("merge_properties", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof GraphObject && sources[1] instanceof GraphObject) { - - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Set mergeKeys = new LinkedHashSet<>(); - final GraphObject source = (GraphObject) sources[0]; - final GraphObject target = (GraphObject) sources[1]; - final int paramCount = sources.length; - - for (int i = 2; i < paramCount; i++) { - - final String keyName = sources[i].toString(); - final PropertyKey key = config.getPropertyKeyForJSONName(target.getClass(), keyName); - - mergeKeys.add(key); - } - - for (final PropertyKey key : mergeKeys) { - - final Object sourceValue = source.getProperty(key); - if (sourceValue != null) { - - target.setProperty(key, sourceValue); - } - - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE_PROPERTIES; - } - }); - functions.put("keys", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof GraphObject) { - - final Set keys = new LinkedHashSet<>(); - final GraphObject source = (GraphObject) sources[0]; - - for (final PropertyKey key : source.getPropertyKeys(sources[1].toString())) { - keys.add(key.jsonName()); - } - - return new LinkedList<>(keys); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_KEYS; - } - }); - - // ----- BEGIN functions with side effects ----- - functions.put("retrieve", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String) { - - return ctx.retrieve(sources[0].toString()); - - } else { - - return ERROR_MESSAGE_RETRIEVE; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_RETRIEVE; - } - }); - functions.put("store", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof String) { - - ctx.store(sources[0].toString(), sources[1]); - - } else { - - return ERROR_MESSAGE_STORE; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_STORE; - } - }); - functions.put("print", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - for (Object i : sources) { - - System.out.print(i); - } - - System.out.println(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_PRINT; - } - }); - functions.put("read", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - if (file.exists() && file.length() < 10000000) { - - try (final FileInputStream fis = new FileInputStream(file)) { - - return IOUtils.toString(fis, "utf-8"); - } - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_READ; - } - }); - functions.put("write", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - if (!file.exists()) { - - try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file, false))) { - - for (int i = 1; i < sources.length; i++) { - if (sources[i] != null) { - IOUtils.write(sources[i].toString(), writer); - } - } - - writer.flush(); - } - - } else { - - logger.log(Level.SEVERE, "Trying to overwrite an existing file, please use append() for that purpose."); - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_WRITE; - } - }); - functions.put("append", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - - try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file, true))) { - - for (int i = 1; i < sources.length; i++) { - IOUtils.write(sources[i].toString(), writer); - } - - writer.flush(); - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_APPEND; - } - }); - functions.put("xml", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String) { - - try { - - final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - if (builder != null) { - - final String xml = (String) sources[0]; - final StringReader reader = new StringReader(xml); - final InputSource src = new InputSource(reader); - - return builder.parse(src); - } - - } catch (IOException | SAXException | ParserConfigurationException ex) { - ex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_XML; - } - }); - functions.put("xpath", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof Document) { - - try { - - XPath xpath = XPathFactory.newInstance().newXPath(); - return xpath.evaluate(sources[1].toString(), sources[0], XPathConstants.STRING); - - } catch (XPathExpressionException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_XPATH; - } - }); - functions.put("set", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof GraphObject) { - - final GraphObject source = (GraphObject) sources[0]; - final Map properties = new LinkedHashMap<>(); - final SecurityContext securityContext = source.getSecurityContext(); - final Gson gson = new GsonBuilder().create(); - final Class type = source.getClass(); - final int sourceCount = sources.length; - - if (sources.length == 3 && sources[2] != null && sources[1].toString().matches("[a-zA-Z0-9_]+")) { - - properties.put(sources[1].toString(), sources[2]); - - } else { - - // we either have and odd number of items, or two multi-value items. - for (int i = 1; i < sourceCount; i++) { - - final Map values = deserialize(gson, sources[i].toString()); - if (values != null) { - - properties.putAll(values); - } - } - } - - // store values in entity - final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, properties); - for (final Map.Entry entry : map.entrySet()) { - - source.setProperty(entry.getKey(), entry.getValue()); - } - - } else { - - throw new FrameworkException(422, "Invalid use of builtin method set, usage: set(entity, params..)"); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SET; - } - }); - functions.put("send_plaintext_mail", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 6)) { - - final String from = sources[0].toString(); - final String fromName = sources[1].toString(); - final String to = sources[2].toString(); - final String toName = sources[3].toString(); - final String subject = sources[4].toString(); - final String textContent = sources[5].toString(); - - try { - return MailHelper.sendSimpleMail(from, fromName, to, toName, null, null, from, subject, textContent); - - } catch (EmailException eex) { - eex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SEND_PLAINTEXT_MAIL; - } - }); - functions.put("send_html_mail", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 6)) { - - final String from = sources[0].toString(); - final String fromName = sources[1].toString(); - final String to = sources[2].toString(); - final String toName = sources[3].toString(); - final String subject = sources[4].toString(); - final String htmlContent = sources[5].toString(); - String textContent = ""; - - if (sources.length == 7) { - textContent = sources[6].toString(); - } - - try { - return MailHelper.sendHtmlMail(from, fromName, to, toName, null, null, from, subject, htmlContent, textContent); - - } catch (EmailException eex) { - eex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SEND_HTML_MAIL; - } - }); - functions.put("geocode", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final Gson gson = new GsonBuilder().create(); - final String street = sources[0].toString(); - final String city = sources[1].toString(); - final String country = sources[2].toString(); - - GeoCodingResult result = GeoHelper.geocode(street, null, null, city, null, country); - if (result != null) { - - final Map map = new LinkedHashMap<>(); - - map.put("latitude", result.getLatitude()); - map.put("longitude", result.getLongitude()); - - return serialize(gson, map); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GEOCODE; - } - }); - functions.put("find", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = ctx.getSecurityContext(); - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Query query = StructrApp.getInstance(securityContext).nodeQuery().sort(GraphObject.createdDate).order(false); - - // the type to query for - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type != null) { - - query.andTypes(type); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - query.and(PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1])); - - } else { - - - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - // throw exception if key is not indexed (otherwise the user will never know) - if (!key.isSearchable()) { - - throw new FrameworkException(400, "Search key " + key.jsonName() + " is not indexed."); - } - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - query.and(key, value); - } - } - } - - return query.getAsList(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIND; - } - }); - functions.put("search", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Query query = StructrApp.getInstance(securityContext).nodeQuery(); - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type != null) { - - query.andTypes(type); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1]); - for (final Entry entry : map.entrySet()) { - - query.and(entry.getKey(), entry.getValue(), false); - } - - } else { - - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - // throw exception if key is not indexed (otherwise the user will never know) - if (!key.isSearchable()) { - - throw new FrameworkException(400, "Search key " + key.jsonName() + " is not indexed."); - } - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - query.and(key, value, false); - } - - } - } - - final Object x = query.getAsList(); - - // return search results - return x; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIND; - } - }); - functions.put("create", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final App app = StructrApp.getInstance(securityContext); - final ConfigurationProvider config = StructrApp.getConfiguration(); - PropertyMap propertyMap = null; - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type.equals(entity.getClass())) { - - throw new FrameworkException(422, "Cannot create() entity of the same type in save action."); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - propertyMap = PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1]); - - } else { - - propertyMap = new PropertyMap(); - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_CREATE); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - propertyMap.put(key, value); - - } - - } - } - - if (type != null) { - - return app.create(type, propertyMap); - - } else { - - throw new FrameworkException(422, "Unknown type in create() save action."); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CREATE; - } - }); - functions.put("delete", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final App app = StructrApp.getInstance(entity.getSecurityContext()); - for (final Object obj : sources) { - - if (obj instanceof NodeInterface) { - - app.delete((NodeInterface) obj); - continue; - } - - if (obj instanceof RelationshipInterface) { - - app.delete((RelationshipInterface) obj); - continue; - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_DELETE; - } - }); - functions.put("incoming", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final RelationshipFactory factory = new RelationshipFactory(entity.getSecurityContext()); - final Object source = sources[0]; - - if (source instanceof NodeInterface) { - - final NodeInterface node = (NodeInterface) source; - if (sources.length > 1) { - - final Object relType = sources[1]; - if (relType != null && relType instanceof String) { - - final String relTypeName = (String) relType; - return factory.instantiate(node.getNode().getRelationships(Direction.INCOMING, DynamicRelationshipType.withName(relTypeName))); - } - - } else { - - return factory.instantiate(node.getNode().getRelationships(Direction.INCOMING)); - } - - } else { - - return "Error: entity is not a node."; - } - } - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INCOMING; - } - }); - functions.put("outgoing", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final RelationshipFactory factory = new RelationshipFactory(entity.getSecurityContext()); - final Object source = sources[0]; - - if (source instanceof NodeInterface) { - - final NodeInterface node = (NodeInterface) source; - if (sources.length > 1) { - - final Object relType = sources[1]; - if (relType != null && relType instanceof String) { - - final String relTypeName = (String) relType; - return factory.instantiate(node.getNode().getRelationships(Direction.OUTGOING, DynamicRelationshipType.withName(relTypeName))); - } - - } else { - - return factory.instantiate(node.getNode().getRelationships(Direction.OUTGOING)); - } - - } else { - - return "Error: entity is not a node."; - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_OUTGOING; - } - }); - functions.put("has_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - return true; - } - } - - } else if (sources.length == 3) { - - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( rel.getRelType().name().equals(relType) && ((rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode))) ) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_RELATIONSHIP; - } - }); - functions.put("has_outgoing_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - return true; - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getRelType().name().equals(relType) && rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_OUTGOING_RELATIONSHIP; - } - }); - functions.put("has_incoming_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) { - return true; - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getRelType().name().equals(relType) && (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_INCOMING_RELATIONSHIP; - } - }); - functions.put("get_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - NodeInterface sourceNode = null; - NodeInterface targetNode = null; - - if (source instanceof NodeInterface && target instanceof NodeInterface) { - - sourceNode = (NodeInterface) source; - targetNode = (NodeInterface) target; - - } else { - - return "Error: Entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - final NodeInterface s = rel.getSourceNode(); - final NodeInterface t = rel.getTargetNode(); - - // We need to check if current user can see source and target node which is often not the case for OWNS or SECURITY rels - if ( - s != null - && t != null - && ( - (s.equals(sourceNode) && t.equals(targetNode)) - || (s.equals(targetNode) && t.equals(sourceNode)) - ) - ) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - final NodeInterface s = rel.getSourceNode(); - final NodeInterface t = rel.getTargetNode(); - - // We need to check if current user can see source and target node which is often not the case for OWNS or SECURITY rels - if ( - s != null - && t != null - && ( - rel.getRelType().name().equals(relType) - && ( - (s.equals(sourceNode) && t.equals(targetNode)) - || (s.equals(targetNode) && t.equals(sourceNode)) - ) - ) - ) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_RELATIONSHIPS; - } - }); - functions.put("get_outgoing_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getRelType().name().equals(relType) && rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_OUTGOING_RELATIONSHIPS; - } - }); - functions.put("get_incoming_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getRelType().name().equals(relType) && (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_INCOMING_RELATIONSHIPS; - } - }); - functions.put("create_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final Object source = sources[0]; - final Object target = sources[1]; - final String relType = (String) sources[2]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - final Class relClass = StructrApp.getConfiguration().getRelationClassForCombinedType(sourceNode.getType(), relType, targetNode.getType()); - - if (relClass != null) { - - StructrApp.getInstance(sourceNode.getSecurityContext()).create(sourceNode, targetNode, relClass); - - } else { - - return "Error: Unknown relationship type"; - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CREATE_RELATIONSHIP; - } - }); - functions.put("grant", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 3)) { - - if (sources[0] instanceof Principal) { - - final Principal principal = (Principal) sources[0]; - - if (sources[1] instanceof AbstractNode) { - - final AbstractNode node = (AbstractNode) sources[1]; - - if (sources[2] instanceof String) { - - final String[] parts = ((String) sources[2]).split("[,]+"); - for (final String part : parts) { - - final String trimmedPart = part.trim(); - if (trimmedPart.length() > 0) { - - try { - - final Permission permission = Permission.valueOf(trimmedPart); - principal.grant(permission, node); - - } catch (IllegalArgumentException iex) { - - return "Error: unknown permission " + trimmedPart; - } - } - } - - return ""; - - } else { - - return "Error: third argument is not a string."; - } - - } else { - - return "Error: second argument is not a node."; - } - - } else { - - return "Error: first argument is not of type Principal."; - } - - } else { - - return ERROR_MESSAGE_GRANT; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_GRANT; - } - }); - functions.put("revoke", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 3)) { - - if (sources[0] instanceof Principal) { - - final Principal principal = (Principal) sources[0]; - - if (sources[1] instanceof AbstractNode) { - - final AbstractNode node = (AbstractNode) sources[1]; - - if (sources[2] instanceof String) { - - final String[] parts = ((String) sources[2]).split("[,]+"); - for (final String part : parts) { - - final String trimmedPart = part.trim(); - if (trimmedPart.length() > 0) { - - try { - - final Permission permission = Permission.valueOf(trimmedPart); - principal.revoke(permission, node); - - } catch (IllegalArgumentException iex) { - - return "Error: unknown permission " + trimmedPart; - } - } - } - - return ""; - - } else { - - return "Error: third argument is not a string."; - } - - } else { - - return "Error: second argument is not a node."; - } - - } else { - - return "Error: first argument is not of type Principal."; - } - - } else { - - return ERROR_MESSAGE_REVOKE; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_REVOKE; - } - }); - } - - /** - * Test if the given object array has a minimum length and all its - * elements are not null. - * - * @param array - * @param minLength If null, don't do length check - * @return true if array has min length and all elements are not null - */ - public static boolean arrayHasMinLengthAndAllElementsNotNull(final Object[] array, final Integer minLength) { - - if (array == null) { - return false; - } - - for (final Object element : array) { - - if (element == null) { - return false; - } - - } - - return minLength != null ? array.length >= minLength : true; - - } - - /** - * Test if the given object array has exact the given length and all its - * elements are not null. - * - * @param array - * @param length If null, don't do length check - * @return true if array has exact length and all elements are not null - */ - public static boolean arrayHasLengthAndAllElementsNotNull(final Object[] array, final Integer length) { - - if (array == null) { - return false; - } - - for (final Object element : array) { - - if (element == null) { - return false; - } - - } - - return length != null ? array.length == length : true; - - } - - protected static String serialize(final Gson gson, final Map map) { - return gson.toJson(map, new TypeToken>() { - }.getType()); - } - - protected static Map deserialize(final Gson gson, final String source) { - return gson.fromJson(source, new TypeToken>() { - }.getType()); - } - - protected static Integer parseInt(final Object source) { - - if (source instanceof Integer) { - - return ((Integer) source); - } - - if (source instanceof Number) { - - return ((Number) source).intValue(); - } - - if (source instanceof String) { - - return Integer.parseInt((String) source); - } - - return null; - } - - protected static String encodeURL(final String source) { - - try { - return URLEncoder.encode(source, "UTF-8"); - - } catch (UnsupportedEncodingException ex) { - - logger.log(Level.WARNING, "Unsupported Encoding", ex); - } - - // fallback, unencoded - return source; - } - - protected static double getDoubleForComparison(final Object obj) { - - if (obj instanceof Date) { - - return ((Date) obj).getTime(); - - } else if (obj instanceof Number) { - - return ((Number) obj).doubleValue(); - - } else { - - try { - return Double.valueOf(obj.toString()); - - } catch (Throwable t) { - - t.printStackTrace(); - } - } - - return 0.0; - } - - protected static Double getDoubleOrNull(final Object obj) { - - if (obj instanceof Date) { - - return Double.valueOf(((Date) obj).getTime()); - - } else if (obj instanceof Number) { - - return ((Number) obj).doubleValue(); - - } else { - - try { - return Double.valueOf(obj.toString()); - - } catch (Throwable t) { - - t.printStackTrace(); - } - } - - return null; - } - - protected static boolean valueEquals(final Object obj1, final Object obj2) { - - if (obj1 instanceof Enum || obj2 instanceof Enum) { - - return obj1.toString().equals(obj2.toString()); - - } - - if (obj1 instanceof Number && obj2 instanceof Number) { - - return ((Number) obj1).doubleValue() == ((Number) obj2).doubleValue(); - } - - return obj1.equals(obj2); - } - - protected static String getSandboxFileName(final String source) throws IOException { - - final File sandboxFile = new File(source); - final String fileName = sandboxFile.getName(); - final String basePath = StructrApp.getConfigurationValue(Services.BASE_PATH); - - if (!basePath.isEmpty()) { - - final String defaultExchangePath = basePath.endsWith("/") ? basePath.concat("exchange") : basePath.concat("/exchange"); - String exchangeDir = StructrApp.getConfigurationValue(Services.DATA_EXCHANGE_PATH, defaultExchangePath); - - if (!exchangeDir.endsWith("/")) { - exchangeDir = exchangeDir.concat("/"); - } - - // create exchange directory - final File dir = new File(exchangeDir); - if (!dir.exists()) { - - dir.mkdirs(); - } - - // return sandboxed file name - return exchangeDir.concat(fileName); - - } else { - - logger.log(Level.WARNING, "Unable to determine base.path from structr.conf, no data input/output possible."); - } - - return null; - } - - public static String cleanString(final Object input) { - - if (input == null) { - - return ""; - - } - - String normalized = Normalizer.normalize(input.toString(), Normalizer.Form.NFD) - .replaceAll("\\<", "") - .replaceAll("\\>", "") - .replaceAll("\\.", "") - .replaceAll("\\'", "-") - .replaceAll("\\?", "") - .replaceAll("\\(", "") - .replaceAll("\\)", "") - .replaceAll("\\{", "") - .replaceAll("\\}", "") - .replaceAll("\\[", "") - .replaceAll("\\]", "") - .replaceAll("\\+", "-") - .replaceAll("/", "-") - .replaceAll("–", "-") - .replaceAll("\\\\", "-") - .replaceAll("\\|", "-") - .replaceAll("'", "-") - .replaceAll("!", "") - .replaceAll(",", "") - .replaceAll("-", " ") - .replaceAll("_", " ") - .replaceAll("`", "-"); - - String result = normalized.replaceAll("-", " "); - result = StringUtils.normalizeSpace(result.toLowerCase()); - result = result.replaceAll("[^\\p{ASCII}]", "").replaceAll("\\p{P}", "-").replaceAll("\\-(\\s+\\-)+", "-"); - result = result.replaceAll(" ", "-"); - - return result; - - } - - public static void recursivelyConvertMapToGraphObjectMap(final GraphObjectMap destination, final Map source, final int depth) { - - if (depth > 20) { - return; - } - - for (final Map.Entry entry : source.entrySet()) { - - final String key = entry.getKey(); - final Object value = entry.getValue(); - - if (value instanceof Map) { - - final Map map = (Map) value; - final GraphObjectMap obj = new GraphObjectMap(); - - destination.put(new StringProperty(key), obj); - - recursivelyConvertMapToGraphObjectMap(obj, map, depth+1); - - } else if (value instanceof Collection) { - - final List list = new LinkedList(); - final Collection collection = (Collection)value; - - for (final Object obj : collection) { - - if (obj instanceof Map) { - - final GraphObjectMap container = new GraphObjectMap(); - list.add(container); - - recursivelyConvertMapToGraphObjectMap(container, (Map)obj, depth+1); - - } else { - - list.add(obj); - } - } - - destination.put(new StringProperty(key), list); - - } else { - - destination.put(new StringProperty(key), value); - } - } - } - - public static Object numberOrString(final String value) { - - if (value != null) { - - if ("true".equals(value.toLowerCase())) { - return true; - } - - if ("false".equals(value.toLowerCase())) { - return false; - } - - if (NumberUtils.isNumber(value)) { - return NumberUtils.createNumber(value); - } - } - - return value; - } -} diff --git a/All/Genesis-NP/Genesis#154/old/Functions.java b/All/Genesis-NP/Genesis#154/old/Functions.java deleted file mode 100755 index 61353ce..0000000 --- a/All/Genesis-NP/Genesis#154/old/Functions.java +++ /dev/null @@ -1,3904 +0,0 @@ -/** - * Copyright (C) 2010-2014 Morgner UG (haftungsbeschränkt) - * - * This file is part of Structr . - * - * Structr is free software: you can redistribute it and/or modify it under the - * terms of the GNU General Public License as published by the Free Software - * Foundation, either version 3 of the License, or (at your option) any later - * version. - * - * Structr is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - * A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * Structr. If not, see . - */ -package org.structr.core.parser; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.reflect.TypeToken; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.StreamTokenizer; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.net.URLEncoder; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.Normalizer; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Random; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.apache.commons.mail.EmailException; -import org.neo4j.graphdb.Direction; -import org.neo4j.graphdb.DynamicRelationshipType; -import org.structr.common.GraphObjectComparator; -import org.structr.common.MailHelper; -import org.structr.common.Permission; -import org.structr.common.SecurityContext; -import org.structr.common.error.ErrorToken; -import org.structr.common.error.FrameworkException; -import org.structr.common.error.SemanticErrorToken; -import org.structr.common.geo.GeoCodingResult; -import org.structr.common.geo.GeoHelper; -import org.structr.core.GraphObject; -import org.structr.core.GraphObjectMap; -import org.structr.core.Services; -import org.structr.core.app.App; -import org.structr.core.app.Query; -import org.structr.core.app.StructrApp; -import org.structr.core.converter.PropertyConverter; -import org.structr.core.entity.AbstractNode; -import org.structr.core.entity.AbstractRelationship; -import org.structr.core.entity.MailTemplate; -import org.structr.core.entity.Principal; -import org.structr.core.graph.NodeInterface; -import org.structr.core.graph.RelationshipFactory; -import org.structr.core.graph.RelationshipInterface; -import org.structr.core.property.ISO8601DateProperty; -import org.structr.core.property.PropertyKey; -import org.structr.core.property.PropertyMap; -import org.structr.core.property.StringProperty; -import org.structr.core.script.Scripting; -import org.structr.schema.ConfigurationProvider; -import org.structr.schema.action.ActionContext; -import org.structr.schema.action.Function; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * - * @author Christian Morgner - */ -public class Functions { - - private static final Logger logger = Logger.getLogger(Functions.class.getName()); - public static final Map> functions = new LinkedHashMap<>(); - - public static final String NULL_STRING = "___NULL___"; - - public static final String ERROR_MESSAGE_MD5 = "Usage: ${md5(string)}. Example: ${md5(this.email)}"; - public static final String ERROR_MESSAGE_ERROR = "Usage: ${error(...)}. Example: ${error(\"base\", \"must_equal\", int(5))}"; - public static final String ERROR_MESSAGE_UPPER = "Usage: ${upper(string)}. Example: ${upper(this.nickName)}"; - public static final String ERROR_MESSAGE_LOWER = "Usage: ${lower(string)}. Example: ${lower(this.email)}"; - public static final String ERROR_MESSAGE_JOIN = "Usage: ${join(collection, separator)}. Example: ${join(this.names, \",\")}"; - public static final String ERROR_MESSAGE_CONCAT = "Usage: ${concat(values...)}. Example: ${concat(this.firstName, this.lastName)}"; - public static final String ERROR_MESSAGE_SPLIT = "Usage: ${split(value)}. Example: ${split(this.commaSeparatedItems)}"; - public static final String ERROR_MESSAGE_ABBR = "Usage: ${abbr(longString, maxLength)}. Example: ${abbr(this.title, 20)}"; - public static final String ERROR_MESSAGE_CAPITALIZE = "Usage: ${capitalize(string)}. Example: ${capitalize(this.nickName)}"; - public static final String ERROR_MESSAGE_TITLEIZE = "Usage: ${titleize(string, separator}. (Default separator is \" \") Example: ${titleize(this.lowerCamelCaseString, \"_\")}"; - public static final String ERROR_MESSAGE_NUM = "Usage: ${num(string)}. Example: ${num(this.numericalStringValue)}"; - public static final String ERROR_MESSAGE_INT = "Usage: ${int(string)}. Example: ${int(this.numericalStringValue)}"; - public static final String ERROR_MESSAGE_RANDOM = "Usage: ${random(num)}. Example: ${set(this, \"password\", random(8))}"; - public static final String ERROR_MESSAGE_RINT = "Usage: ${rint(range)}. Example: ${rint(1000)}"; - public static final String ERROR_MESSAGE_INDEX_OF = "Usage: ${index_of(string, word)}. Example: ${index_of(this.name, \"the\")}"; - public static final String ERROR_MESSAGE_CONTAINS = "Usage: ${contains(string, word)}. Example: ${contains(this.name, \"the\")}"; - public static final String ERROR_MESSAGE_SUBSTRING = "Usage: ${substring(string, start, length)}. Example: ${substring(this.name, 19, 3)}"; - public static final String ERROR_MESSAGE_LENGTH = "Usage: ${length(string)}. Example: ${length(this.name)}"; - public static final String ERROR_MESSAGE_REPLACE = "Usage: ${replace(template, source)}. Example: ${replace(\"${this.id}\", this)}"; - public static final String ERROR_MESSAGE_CLEAN = "Usage: ${clean(string)}. Example: ${clean(this.stringWithNonWordChars)}"; - public static final String ERROR_MESSAGE_URLENCODE = "Usage: ${urlencode(string)}. Example: ${urlencode(this.email)}"; - public static final String ERROR_MESSAGE_ESCAPE_JS = "Usage: ${escape_javascript(string)}. Example: ${escape_javascript(this.name)}"; - public static final String ERROR_MESSAGE_IF = "Usage: ${if(condition, trueValue, falseValue)}. Example: ${if(empty(this.name), this.nickName, this.name)}"; - public static final String ERROR_MESSAGE_EMPTY = "Usage: ${empty(string)}. Example: ${if(empty(possibleEmptyString), \"empty\", \"non-empty\")}"; - public static final String ERROR_MESSAGE_EQUAL = "Usage: ${equal(value1, value2)}. Example: ${equal(this.children.size, 0)}"; - public static final String ERROR_MESSAGE_ADD = "Usage: ${add(values...)}. Example: ${add(1, 2, 3, this.children.size)}"; - public static final String ERROR_MESSAGE_INT_SUM = "Usage: ${int_sum(list)}. Example: ${int_sum(extract(this.children, \"number\"))}"; - public static final String ERROR_MESSAGE_DOUBLE_SUM = "Usage: ${double_sum(list)}. Example: ${double_sum(extract(this.children, \"amount\"))}"; - public static final String ERROR_MESSAGE_IS_COLLECTION = "Usage: ${is_collection(value)}. Example: ${is_collection(this)}"; - public static final String ERROR_MESSAGE_IS_ENTITY = "Usage: ${is_entity(value)}. Example: ${is_entity(this)}"; - public static final String ERROR_MESSAGE_EXTRACT = "Usage: ${extract(list, propertyName)}. Example: ${extract(this.children, \"amount\")}"; - public static final String ERROR_MESSAGE_FILTER = "Usage: ${filter(list, expression)}. Example: ${filter(this.children, gt(size(data.children), 0))}"; - public static final String ERROR_MESSAGE_MERGE = "Usage: ${merge(list1, list2, list3, ...)}. Example: ${merge(this.children, this.siblings)}"; - public static final String ERROR_MESSAGE_COMPLEMENT = "Usage: ${complement(list1, list2, list3, ...)}. (The resulting list contains no duplicates) Example: ${merge(allUsers, me)} => List of all users except myself"; - public static final String ERROR_MESSAGE_UNWIND = "Usage: ${unwind(list1, ...)}. Example: ${unwind(this.children)}"; - public static final String ERROR_MESSAGE_SORT = "Usage: ${sort(list1, key [, true])}. Example: ${sort(this.children, \"name\")}"; - public static final String ERROR_MESSAGE_LT = "Usage: ${lt(value1, value2)}. Example: ${if(lt(this.children, 2), \"Less than two\", \"Equal to or more than two\")}"; - public static final String ERROR_MESSAGE_GT = "Usage: ${gt(value1, value2)}. Example: ${if(gt(this.children, 2), \"More than two\", \"Equal to or less than two\")}"; - public static final String ERROR_MESSAGE_LTE = "Usage: ${lte(value1, value2)}. Example: ${if(lte(this.children, 2), \"Equal to or less than two\", \"More than two\")}"; - public static final String ERROR_MESSAGE_GTE = "Usage: ${gte(value1, value2)}. Example: ${if(gte(this.children, 2), \"Equal to or more than two\", \"Less than two\")}"; - public static final String ERROR_MESSAGE_SUBT = "Usage: ${subt(value1, value)}. Example: ${subt(5, 2)}"; - public static final String ERROR_MESSAGE_MULT = "Usage: ${mult(value1, value)}. Example: ${mult(5, 2)}"; - public static final String ERROR_MESSAGE_QUOT = "Usage: ${quot(value1, value)}. Example: ${quot(5, 2)}"; - public static final String ERROR_MESSAGE_ROUND = "Usage: ${round(value1 [, decimalPlaces])}. Example: ${round(2.345678, 2)}"; - public static final String ERROR_MESSAGE_MAX = "Usage: ${max(value1, value2)}. Example: ${max(this.children, 10)}"; - public static final String ERROR_MESSAGE_MIN = "Usage: ${min(value1, value2)}. Example: ${min(this.children, 5)}"; - public static final String ERROR_MESSAGE_CONFIG = "Usage: ${config(keyFromStructrConf)}. Example: ${config(\"base.path\")}"; - public static final String ERROR_MESSAGE_DATE_FORMAT = "Usage: ${date_format(value, pattern)}. Example: ${date_format(this.creationDate, \"yyyy-MM-dd'T'HH:mm:ssZ\")}"; - public static final String ERROR_MESSAGE_PARSE_DATE = "Usage: ${parse_date(value, pattern)}. Example: ${parse_format(\"2014-01-01\", \"yyyy-MM-dd\")}"; - public static final String ERROR_MESSAGE_NUMBER_FORMAT = "Usage: ${number_format(value, ISO639LangCode, pattern)}. Example: ${number_format(12345.6789, 'en', '#,##0.00')}"; - public static final String ERROR_MESSAGE_TEMPLATE = "Usage: ${template(name, locale, source)}. Example: ${template(\"TEXT_TEMPLATE_1\", \"en_EN\", this)}"; - public static final String ERROR_MESSAGE_NOT = "Usage: ${not(bool1, bool2)}. Example: ${not(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_AND = "Usage: ${and(bool1, bool2)}. Example: ${and(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_OR = "Usage: ${or(bool1, bool2)}. Example: ${or(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_GET = "Usage: ${get(entity, propertyKey)}. Example: ${get(this, \"children\")}"; - public static final String ERROR_MESSAGE_GET_ENTITY = "Cannot evaluate first argument to entity, must be entity or single element list of entities."; - public static final String ERROR_MESSAGE_SIZE = "Usage: ${size(collection)}. Example: ${size(this.children)}"; - public static final String ERROR_MESSAGE_FIRST = "Usage: ${first(collection)}. Example: ${first(this.children)}"; - public static final String ERROR_MESSAGE_LAST = "Usage: ${last(collection)}. Example: ${last(this.children)}"; - public static final String ERROR_MESSAGE_NTH = "Usage: ${nth(collection)}. Example: ${nth(this.children, 2)}"; - public static final String ERROR_MESSAGE_GET_COUNTER = "Usage: ${get_counter(level)}. Example: ${get_counter(1)}"; - public static final String ERROR_MESSAGE_INC_COUNTER = "Usage: ${inc_counter(level, [resetLowerLevels])}. Example: ${inc_counter(1, true)}"; - public static final String ERROR_MESSAGE_RESET_COUNTER = "Usage: ${reset_counter(level)}. Example: ${reset_counter(1)}"; - public static final String ERROR_MESSAGE_MERGE_PROPERTIES = "Usage: ${merge_properties(source, target , mergeKeys...)}. Example: ${merge_properties(this, parent, \"eMail\")}"; - public static final String ERROR_MESSAGE_KEYS = "Usage: ${keys(entity, viewName)}. Example: ${keys(this, \"ui\")}"; - public static final String ERROR_MESSAGE_EACH = "Usage: ${each(collection, expression)}. Example: ${each(this.children, \"set(this, \"email\", lower(get(this.email))))\")}"; - public static final String ERROR_MESSAGE_STORE = "Usage: ${store(key, value)}. Example: ${store('tmpUser', this.owner)}"; - public static final String ERROR_MESSAGE_RETRIEVE = "Usage: ${retrieve(key)}. Example: ${retrieve('tmpUser')}"; - public static final String ERROR_MESSAGE_PRINT = "Usage: ${print(objects...)}. Example: ${print(this.name, \"test\")}"; - public static final String ERROR_MESSAGE_READ = "Usage: ${read(filename)}. Example: ${read(\"text.xml\")}"; - public static final String ERROR_MESSAGE_WRITE = "Usage: ${write(filename, value)}. Example: ${write(\"text.txt\", this.name)}"; - public static final String ERROR_MESSAGE_APPEND = "Usage: ${append(filename, value)}. Example: ${append(\"test.txt\", this.name)}"; - public static final String ERROR_MESSAGE_XML = "Usage: ${xml(xmlSource)}. Example: ${xpath(xml(this.xmlSource), \"/test/testValue\")}"; - public static final String ERROR_MESSAGE_XPATH = "Usage: ${xpath(xmlDocument, expression)}. Example: ${xpath(xml(this.xmlSource), \"/test/testValue\")}"; - public static final String ERROR_MESSAGE_SET = "Usage: ${set(entity, propertyKey, value)}. Example: ${set(this, \"email\", lower(this.email))}"; - public static final String ERROR_MESSAGE_SEND_PLAINTEXT_MAIL = "Usage: ${send_plaintext_mail(fromAddress, fromName, toAddress, toName, subject, content)}."; - public static final String ERROR_MESSAGE_SEND_HTML_MAIL = "Usage: ${send_html_mail(fromAddress, fromName, toAddress, toName, subject, content)}."; - public static final String ERROR_MESSAGE_GEOCODE = "Usage: ${geocode(street, city, country)}. Example: ${set(this, geocode(this.street, this.city, this.country))}"; - public static final String ERROR_MESSAGE_FIND = "Usage: ${find(type, key, value)}. Example: ${find(\"User\", \"email\", \"tester@test.com\"}"; - public static final String ERROR_MESSAGE_SEARCH = "Usage: ${search(type, key, value)}. Example: ${search(\"User\", \"name\", \"abc\"}"; - public static final String ERROR_MESSAGE_CREATE = "Usage: ${create(type, key, value)}. Example: ${create(\"Feedback\", \"text\", this.text)}"; - public static final String ERROR_MESSAGE_DELETE = "Usage: ${delete(entity)}. Example: ${delete(this)}"; - public static final String ERROR_MESSAGE_CACHE = "Usage: ${cache(key, timeout, valueExpression)}. Example: ${cache('value', 60, GET('http://rate-limited-URL.com'))}"; - public static final String ERROR_MESSAGE_GRANT = "Usage: ${grant(principal, node, permissions)}. Example: ${grant(me, this, 'read, write, delete'))}"; - public static final String ERROR_MESSAGE_REVOKE = "Usage: ${revoke(principal, node, permissions)}. Example: ${revoke(me, this, 'write, delete'))}"; - - // Special functions for relationships - public static final String ERROR_MESSAGE_INCOMING = "Usage: ${incoming(entity [, relType])}. Example: ${incoming(this, 'PARENT_OF')}"; - public static final String ERROR_MESSAGE_OUTGOING = "Usage: ${outgoing(entity [, relType])}. Example: ${outgoing(this, 'PARENT_OF')}"; - public static final String ERROR_MESSAGE_HAS_RELATIONSHIP = "Usage: ${has_relationship(entity1, entity2 [, relType])}. Example: ${has_relationship(me, user, 'FOLLOWS')} (ignores direction of the relationship)"; - public static final String ERROR_MESSAGE_HAS_OUTGOING_RELATIONSHIP = "Usage: ${has_outgoing_relationship(from, to [, relType])}. Example: ${has_outgoing_relationship(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_HAS_INCOMING_RELATIONSHIP = "Usage: ${has_incoming_relationship(from, to [, relType])}. Example: ${has_incoming_relationship(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_GET_RELATIONSHIPS = "Usage: ${get_relationships(entity1, entity2 [, relType])}. Example: ${get_relationships(me, user, 'FOLLOWS')} (ignores direction of the relationship)"; - public static final String ERROR_MESSAGE_GET_OUTGOING_RELATIONSHIPS = "Usage: ${get_outgoing_relationships(from, to [, relType])}. Example: ${get_outgoing_relationships(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_GET_INCOMING_RELATIONSHIPS = "Usage: ${get_incoming_relationships(from, to [, relType])}. Example: ${get_incoming_relationships(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_CREATE_RELATIONSHIP = "Usage: ${create_relationship(from, to, relType)}. Example: ${create_relationship(me, user, 'FOLLOWS')} (Relationshiptype has to exist)"; - - public static Function get(final String name) { - return functions.get(name); - } - - public static Object evaluate(final ActionContext actionContext, final GraphObject entity, final String expression) throws FrameworkException { - - final String expressionWithoutNewlines = expression.replace('\n', ' '); - final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(expressionWithoutNewlines)); - tokenizer.eolIsSignificant(true); - tokenizer.ordinaryChar('.'); - tokenizer.wordChars('_', '_'); - tokenizer.wordChars('.', '.'); - tokenizer.wordChars('!', '!'); - - Expression root = new RootExpression(); - Expression current = root; - Expression next = null; - String lastToken = null; - int token = 0; - int level = 0; - - while (token != StreamTokenizer.TT_EOF) { - - token = nextToken(tokenizer); - - switch (token) { - - case StreamTokenizer.TT_EOF: - break; - - case StreamTokenizer.TT_EOL: - break; - - case StreamTokenizer.TT_NUMBER: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before NUMBER"); - } - next = new ConstantExpression(tokenizer.nval); - current.add(next); - lastToken += "NUMBER"; - break; - - case StreamTokenizer.TT_WORD: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval); - } - next = checkReservedWords(tokenizer.sval); - current.add(next); - lastToken = tokenizer.sval; - break; - - case '(': - if (((current == null || current instanceof RootExpression) && next == null) || current == next) { - - // an additional bracket without a new function, - // this can only be an execution group. - next = new GroupExpression(); - current.add(next); - } - - current = next; - lastToken += "("; - level++; - break; - - case ')': - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + lastToken); - } - current = current.getParent(); - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - lastToken += ")"; - level--; - break; - - case '[': - // bind directly to the previous expression - next = new ArrayExpression(); - current.add(next); - current = next; - lastToken += "["; - level++; - break; - - case ']': - - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket before " + lastToken); - } - current = current.getParent(); - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - lastToken += "]"; - level--; - break; - - case ';': - next = null; - lastToken += ";"; - break; - - case ',': - next = current; - lastToken += ","; - break; - - default: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval); - } - current.add(new ConstantExpression(tokenizer.sval)); - lastToken = tokenizer.sval; - - } - } - - if (level > 0) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - - return root.evaluate(actionContext, entity); - } - - private static Expression checkReservedWords(final String word) throws FrameworkException { - - if (word == null) { - return new NullExpression(); - } - - switch (word) { - - case "cache": - return new CacheExpression(); - - case "true": - return new ConstantExpression(true); - - case "false": - return new ConstantExpression(false); - - case "if": - return new IfExpression(); - - case "each": - return new EachExpression(); - - case "filter": - return new FilterExpression(); - - case "data": - return new ValueExpression("data"); - - case "null": - return new ConstantExpression(NULL_STRING); - } - - // no match, try functions - final Function function = Functions.get(word); - if (function != null) { - - return new FunctionExpression(word, function); - - } else { - - return new ValueExpression(word); - } - } - - public static int nextToken(final StreamTokenizer tokenizer) { - - try { - - return tokenizer.nextToken(); - - } catch (IOException ioex) { - } - - return StreamTokenizer.TT_EOF; - } - - static { - - functions.put("error", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entity.getClass(), sources[0].toString()); - ctx.raiseError(entity.getType(), new ErrorToken(422, key) { - - @Override - public JsonElement getContent() { - return new JsonPrimitive(getErrorToken()); - } - - @Override - public String getErrorToken() { - return sources[1].toString(); - } - }); - - } else if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entity.getClass(), sources[0].toString()); - ctx.raiseError(entity.getType(), new SemanticErrorToken(key) { - - @Override - public JsonElement getContent() { - - JsonObject obj = new JsonObject(); - - if (sources[2] instanceof Number) { - - obj.add(getErrorToken(), new JsonPrimitive((Number) sources[2])); - - } else if (sources[2] instanceof Boolean) { - - obj.add(getErrorToken(), new JsonPrimitive((Boolean) sources[2])); - - } else { - - obj.add(getErrorToken(), new JsonPrimitive(sources[2].toString())); - } - - return obj; - } - - @Override - public String getErrorToken() { - return sources[1].toString(); - } - }); - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_ERROR; - } - }); - functions.put("md5", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? DigestUtils.md5Hex(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MD5; - } - }); - functions.put("upper", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? sources[0].toString().toUpperCase() - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_UPPER; - } - - }); - functions.put("lower", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? sources[0].toString().toLowerCase() - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LOWER; - } - - }); - functions.put("join", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof Collection) { - - return StringUtils.join((Collection) sources[0], sources[1].toString()); - } - - if (sources[0].getClass().isArray()) { - - return StringUtils.join((Object[]) sources[0], sources[1].toString()); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_JOIN; - } - - }); - functions.put("concat", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - // collection can contain nulls.. - if (source != null) { - - if (source instanceof Collection) { - - list.addAll((Collection) source); - - } else if (source.getClass().isArray()) { - - list.addAll(Arrays.asList((Object[])source)); - - } else { - - list.add(source); - } - } - } - - return StringUtils.join(list, ""); - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONCAT; - } - - }); - functions.put("split", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final String toSplit = sources[0].toString(); - String splitExpr = "[,;]+"; - - if (sources.length >= 2) { - splitExpr = sources[1].toString(); - } - - return Arrays.asList(toSplit.split(splitExpr)); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SPLIT; - } - - }); - functions.put("abbr", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - try { - int maxLength = Double.valueOf(sources[1].toString()).intValue(); - - if (sources[0].toString().length() > maxLength) { - - return StringUtils.substringBeforeLast(StringUtils.substring(sources[0].toString(), 0, maxLength), " ").concat("…"); - - } else { - - return sources[0]; - } - - } catch (NumberFormatException nfe) { - - return nfe.getMessage(); - - } - - } - - return ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ABBR; - } - - }); - functions.put("capitalize", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? StringUtils.capitalize(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_CAPITALIZE; - } - }); - functions.put("titleize", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources[0] == null) { - return null; - } - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - final String separator; - if (sources.length < 2) { - separator = " "; - } else { - separator = sources[1].toString(); - } - - String[] in = StringUtils.split(sources[0].toString(), separator); - String[] out = new String[in.length]; - for (int i = 0; i < in.length; i++) { - out[i] = StringUtils.capitalize(in[i]); - } - return StringUtils.join(out, " "); - - } - - @Override - public String usage() { - return ERROR_MESSAGE_TITLEIZE; - } - - }); - functions.put("num", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - return getDoubleOrNull(sources[0]); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NUM; - } - }); - functions.put("int", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Number) { - return ((Number) sources[0]).intValue(); - } - - try { - return getDoubleOrNull(sources[0]).intValue(); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INT; - } - }); - functions.put("random", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof Number) { - - try { - return RandomStringUtils.randomAlphanumeric(((Number) sources[0]).intValue()); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RANDOM; - } - }); - functions.put("rint", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof Number) { - - try { - return new Random(System.currentTimeMillis()).nextInt(((Number) sources[0]).intValue()); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RINT; - } - }); - functions.put("index_of", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final String source = sources[0].toString(); - final String part = sources[1].toString(); - - return source.indexOf(part); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INDEX_OF; - } - }); - functions.put("contains", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof String && sources[1] instanceof String) { - - final String source = sources[0].toString(); - final String part = sources[1].toString(); - - return source.contains(part); - - } else if (sources[0] instanceof Collection && sources[1] instanceof GraphObject) { - - final Collection collection = (Collection) sources[0]; - final GraphObject obj = (GraphObject) sources[1]; - - return collection.contains(obj); - - } else if (sources[0].getClass().isArray()) { - - return ArrayUtils.contains((Object[])sources[0], sources[1]); - } - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONTAINS; - } - }); - functions.put("substring", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final String source = sources[0].toString(); - final int sourceLength = source.length(); - final int start = parseInt(sources[1]); - final int length = sources.length >= 3 ? parseInt(sources[2]) : sourceLength - start; - final int end = start + length; - - if (start >= 0 && start < sourceLength && end >= 0 && end <= sourceLength && start <= end) { - - return source.substring(start, end); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBSTRING; - } - }); - functions.put("length", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - return sources[0].toString().length(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBSTRING; - } - }); - functions.put("replace", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final String template = sources[0].toString(); - AbstractNode node = null; - - if (sources[1] instanceof AbstractNode) { - node = (AbstractNode) sources[1]; - } - - if (sources[1] instanceof List) { - - final List list = (List) sources[1]; - if (list.size() == 1 && list.get(0) instanceof AbstractNode) { - - node = (AbstractNode) list.get(0); - } - } - - if (node != null) { - - // recursive replacement call, be careful here - return Scripting.replaceVariables(ctx, node, template); - } - - return ""; - } - - return usage(); - - } - - @Override - public String usage() { - return ERROR_MESSAGE_REPLACE; - } - }); - functions.put("clean", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - return cleanString(sources[0]); - } - - return null; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_CLEAN; - } - - }); - functions.put("urlencode", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? encodeURL(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_URLENCODE; - } - - }); - functions.put("escape_javascript", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? StringEscapeUtils.escapeEcmaScript(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ESCAPE_JS; - } - - }); - functions.put("if", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources[0] == null || sources.length < 3) { - - return ""; - } - - if ("true".equals(sources[0]) || Boolean.TRUE.equals(sources[0])) { - - return sources[1]; - - } else { - - return sources[2]; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IF; - } - - }); - functions.put("empty", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources.length == 0 || sources[0] == null || StringUtils.isEmpty(sources[0].toString())) { - - return true; - - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_EMPTY; - } - - }); - functions.put("equal", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - logger.log(Level.FINE, "Length: {0}", sources.length); - - if (sources.length < 2) { - - return true; - } - - logger.log(Level.FINE, "Comparing {0} to {1}", new java.lang.Object[]{sources[0], sources[1]}); - - if (sources[0] == null && sources[1] == null) { - return true; - } - - if (sources[0] == null || sources[1] == null) { - return false; - } - - return valueEquals(sources[0], sources[1]); - } - - @Override - public String usage() { - return ERROR_MESSAGE_EQUAL; - } - - }); - functions.put("eq", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return functions.get("equal").apply(ctx, entity, sources); - } - - @Override - public String usage() { - - return functions.get("equal").usage(); - } - - }); - functions.put("add", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Double result = 0.0; - - if (sources != null) { - - for (Object i : sources) { - - if (i != null) { - - try { - - result += Double.parseDouble(i.toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - result += 0.0; - } - } - - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ADD; - } - - }); - functions.put("double_sum", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - double result = 0.0; - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Collection) { - - for (final Number num : (Collection) sources[0]) { - - result += num.doubleValue(); - } - } - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_DOUBLE_SUM; - } - - }); - functions.put("int_sum", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - int result = 0; - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Collection) { - - for (final Number num : (Collection) sources[0]) { - - result += num.intValue(); - } - } - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_INT_SUM; - } - - }); - functions.put("is_collection", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - return (sources[0] instanceof Collection); - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IS_COLLECTION; - } - - }); - functions.put("is_entity", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - return (sources[0] instanceof GraphObject); - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IS_ENTITY; - } - - }); - functions.put("extract", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - // no property key given, maybe we should extract a list of lists? - if (sources[0] instanceof Collection) { - - final List extraction = new LinkedList(); - - for (final Object obj : (Collection) sources[0]) { - - if (obj instanceof Collection) { - - extraction.addAll((Collection) obj); - } - } - - return extraction; - } - - } else if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof Collection && sources[1] instanceof String) { - - final ConfigurationProvider config = StructrApp.getConfiguration(); - final List extraction = new LinkedList(); - final String keyName = (String) sources[1]; - - for (final Object obj : (Collection) sources[0]) { - - if (obj instanceof GraphObject) { - - final PropertyKey key = config.getPropertyKeyForJSONName(obj.getClass(), keyName); - final Object value = ((GraphObject) obj).getProperty(key); - if (value != null) { - - extraction.add(value); - } - } - } - - return extraction; - } - } - - return null; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_EXTRACT; - } - - }); - functions.put("merge", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - - if (obj != null) { - - list.add(obj); - } - } - - } else if (source != null) { - - list.add(source); - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE; - } - - }); - functions.put("complement", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final Set sourceSet = new HashSet(); - - if (sources[0] instanceof Collection) { - - sourceSet.addAll((Collection)sources[0]); - - for (int cnt = 1; cnt < sources.length; cnt++) { - - final Object source = sources[cnt]; - - if (source instanceof Collection) { - - sourceSet.removeAll((Collection)source); - - } else if (source != null) { - - sourceSet.remove(source); - } - } - - } else { - - return "Argument 1 for complement must be a Collection"; - } - - return sourceSet; - } - - @Override - public String usage() { - return ERROR_MESSAGE_COMPLEMENT; - } - - }); - functions.put("unwind", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - if (obj != null) { - - if (obj instanceof Collection) { - - for (final Object elem : (Collection) obj) { - - if (elem != null) { - - list.add(elem); - } - } - - } else { - - list.add(obj); - } - } - } - - } else if (source != null) { - - list.add(source); - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_UNWIND; - } - - }); - functions.put("sort", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof List && sources[1] instanceof String) { - - final List list = (List) sources[0]; - final String sortKey = sources[1].toString(); - final Iterator iterator = list.iterator(); - - if (iterator.hasNext()) { - - final Object firstElement = iterator.next(); - if (firstElement instanceof GraphObject) { - - final Class type = firstElement.getClass(); - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(type, sortKey); - final boolean descending = sources.length == 3 && sources[2] != null && "true".equals(sources[2].toString()); - - if (key != null) { - - List sortCollection = (List) list; - Collections.sort(sortCollection, new GraphObjectComparator(key, descending)); - } - } - - } - } - } - - return sources[0]; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SORT; - } - - }); - functions.put("lt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 < value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LT; - } - }); - functions.put("gt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 > value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_GT; - } - }); - functions.put("lte", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 <= value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LTE; - } - }); - functions.put("gte", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 >= value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_GTE; - } - }); - functions.put("subt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - try { - - Double result = Double.parseDouble(sources[0].toString()); - - for (int i = 1; i < sources.length; i++) { - - result -= Double.parseDouble(sources[i].toString()); - - } - - return result; - - } catch (Throwable t) { - - return t.getMessage(); - - } - } - - return ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBT; - } - }); - functions.put("mult", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Double result = 1.0d; - - if (sources != null) { - - for (Object i : sources) { - - try { - - result *= Double.parseDouble(i.toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - } - - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MULT; - } - }); - functions.put("quot", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - - return Double.parseDouble(sources[0].toString()) / Double.parseDouble(sources[1].toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - if (sources != null) { - - if (sources.length > 0 && sources[0] != null) { - return Double.valueOf(sources[0].toString()); - } - - return ""; - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_QUOT; - } - }); - functions.put("round", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - try { - - Double f1 = Double.parseDouble(sources[0].toString()); - double f2 = Math.pow(10, (Double.parseDouble(sources[1].toString()))); - long r = Math.round(f1 * f2); - - return (double) r / f2; - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - return ""; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_ROUND; - } - }); - functions.put("max", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Object result = ""; - String errorMsg = "ERROR! Usage: ${max(val1, val2)}. Example: ${max(5,10)}"; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - result = Math.max(Double.parseDouble(sources[0].toString()), Double.parseDouble(sources[1].toString())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Could not determine max() of {0} and {1}", new Object[]{sources[0], sources[1]}); - result = errorMsg; - } - - } else { - - result = ""; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MAX; - } - }); - functions.put("min", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Object result = ""; - String errorMsg = "ERROR! Usage: ${min(val1, val2)}. Example: ${min(5,10)}"; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - result = Math.min(Double.parseDouble(sources[0].toString()), Double.parseDouble(sources[1].toString())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Could not determine min() of {0} and {1}", new Object[]{sources[0], sources[1]}); - result = errorMsg; - } - - } else { - - result = ""; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MIN; - } - }); - functions.put("config", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final String configKey = sources[0].toString(); - final String defaultValue = sources.length >= 2 ? sources[1].toString() : ""; - - return StructrApp.getConfigurationValue(configKey, defaultValue); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONFIG; - } - }); - functions.put("date_format", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 2) { - return ERROR_MESSAGE_DATE_FORMAT; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - Date date = null; - - if (sources[0] instanceof Date) { - - date = (Date) sources[0]; - - } else if (sources[0] instanceof Number) { - - date = new Date(((Number) sources[0]).longValue()); - - } else { - - try { - - // parse with format from IS - date = new SimpleDateFormat(ISO8601DateProperty.PATTERN).parse(sources[0].toString()); - - } catch (ParseException ex) { - ex.printStackTrace(); - } - - } - - // format with given pattern - return new SimpleDateFormat(sources[1].toString()).format(date); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_DATE_FORMAT; - } - }); - functions.put("parse_date", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 2) { - return ERROR_MESSAGE_PARSE_DATE; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - String dateString = sources[0].toString(); - - if (StringUtils.isBlank(dateString)) { - return ""; - } - - String pattern = sources[1].toString(); - - try { - // parse with format from IS - return new SimpleDateFormat(pattern).parse(dateString); - - } catch (ParseException ex) { - logger.log(Level.WARNING, "Could not parse date " + dateString + " and format it to pattern " + pattern, ex); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_PARSE_DATE; - } - }); - functions.put("number_format", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 3) { - return ERROR_MESSAGE_NUMBER_FORMAT; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - try { - - Double val = Double.parseDouble(sources[0].toString()); - String langCode = sources[1].toString(); - String pattern = sources[2].toString(); - - return new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.forLanguageTag(langCode))).format(val); - - } catch (Throwable t) { - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NUMBER_FORMAT; - } - }); - functions.put("template", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 3) { - return ERROR_MESSAGE_TEMPLATE; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 3) && sources[2] instanceof AbstractNode) { - - final App app = StructrApp.getInstance(entity.getSecurityContext()); - final String name = sources[0].toString(); - final String locale = sources[1].toString(); - final MailTemplate template = app.nodeQuery(MailTemplate.class).andName(name).and(MailTemplate.locale, locale).getFirst(); - final AbstractNode templateInstance = (AbstractNode) sources[2]; - - if (template != null) { - - final String text = template.getProperty(MailTemplate.text); - if (text != null) { - - // recursive replacement call, be careful here - return Scripting.replaceVariables(ctx, templateInstance, text); - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_TEMPLATE; - } - }); - functions.put("not", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - return !("true".equals(sources[0].toString()) || Boolean.TRUE.equals(sources[0])); - - } - - return true; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NOT; - } - - }); - functions.put("and", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - boolean result = true; - - if (sources != null) { - - if (sources.length < 2) { - return usage(); - } - - for (Object i : sources) { - - if (i != null) { - - try { - - result &= "true".equals(i.toString()) || Boolean.TRUE.equals(i); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - // null is false - return false; - } - } - - } - - return result; - } - - @Override - public String usage() { - return ERROR_MESSAGE_AND; - } - - }); - functions.put("or", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - boolean result = false; - - if (sources != null) { - - if (sources.length < 2) { - return usage(); - } - - for (Object i : sources) { - - if (i != null) { - - try { - - result |= "true".equals(i.toString()) || Boolean.TRUE.equals(i); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - // null is false - result |= false; - } - } - - } - - return result; - } - - @Override - public String usage() { - return ERROR_MESSAGE_OR; - } - }); - functions.put("get", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final SecurityContext securityContext = entity.getSecurityContext(); - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - GraphObject dataObject = null; - - if (sources[0] instanceof GraphObject) { - dataObject = (GraphObject) sources[0]; - } - - if (sources[0] instanceof List) { - - final List list = (List) sources[0]; - if (list.size() == 1 && list.get(0) instanceof GraphObject) { - - dataObject = (GraphObject) list.get(0); - } - } - - if (dataObject != null) { - - final String keyName = sources[1].toString(); - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(dataObject.getClass(), keyName); - - if (key != null) { - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = dataObject.getProperty(key); - - if (inputConverter != null) { - return inputConverter.revert(value); - } - - return dataObject.getProperty(key); - } - - return ""; - - } else { - - return ERROR_MESSAGE_GET_ENTITY; - } - } - - return usage(); - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET; - } - }); - functions.put("size", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source != null) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - if (obj != null && !NULL_STRING.equals(obj)) { - - list.add(obj); - } - } - - } else if(source.getClass().isArray()) { - - list.addAll(Arrays.asList((Object[])source)); - - } else if (source != null && !NULL_STRING.equals(source)) { - - list.add(source); - } - - return list.size(); - } - } - - return 0; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SIZE; - } - }); - functions.put("first", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - return ((List) sources[0]).get(0); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (arr.length > 0) { - - return arr[0]; - } - } - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIRST; - } - }); - functions.put("last", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - - final List list = (List) sources[0]; - return list.get(list.size() - 1); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (arr.length > 0) { - - return arr[arr.length - 1]; - } - } - - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_LAST; - } - }); - functions.put("nth", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final int pos = Double.valueOf(sources[1].toString()).intValue(); - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - - final List list = (List) sources[0]; - final int size = list.size(); - - if (pos >= size) { - - return null; - - } - - return list.get(Math.min(Math.max(0, pos), size - 1)); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (pos <= arr.length) { - - return arr[pos]; - } - } - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NTH; - } - }); - functions.put("get_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - return ctx.getCounter(parseInt(sources[0])); - } - - return 0; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_COUNTER; - } - }); - functions.put("inc_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final int level = parseInt(sources[0]); - - ctx.incrementCounter(level); - - // reset lower levels? - if (sources.length == 2 && "true".equals(sources[1].toString())) { - - // reset lower levels - for (int i = level + 1; i < 10; i++) { - ctx.resetCounter(i); - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INC_COUNTER; - } - }); - functions.put("reset_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - ctx.resetCounter(parseInt(sources[0])); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RESET_COUNTER; - } - }); - functions.put("merge_properties", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof GraphObject && sources[1] instanceof GraphObject) { - - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Set mergeKeys = new LinkedHashSet<>(); - final GraphObject source = (GraphObject) sources[0]; - final GraphObject target = (GraphObject) sources[1]; - final int paramCount = sources.length; - - for (int i = 2; i < paramCount; i++) { - - final String keyName = sources[i].toString(); - final PropertyKey key = config.getPropertyKeyForJSONName(target.getClass(), keyName); - - mergeKeys.add(key); - } - - for (final PropertyKey key : mergeKeys) { - - final Object sourceValue = source.getProperty(key); - if (sourceValue != null) { - - target.setProperty(key, sourceValue); - } - - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE_PROPERTIES; - } - }); - functions.put("keys", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof GraphObject) { - - final Set keys = new LinkedHashSet<>(); - final GraphObject source = (GraphObject) sources[0]; - - for (final PropertyKey key : source.getPropertyKeys(sources[1].toString())) { - keys.add(key.jsonName()); - } - - return new LinkedList<>(keys); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_KEYS; - } - }); - - // ----- BEGIN functions with side effects ----- - functions.put("retrieve", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String) { - - return ctx.retrieve(sources[0].toString()); - - } else { - - return ERROR_MESSAGE_RETRIEVE; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_RETRIEVE; - } - }); - functions.put("store", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof String) { - - ctx.store(sources[0].toString(), sources[1]); - - } else { - - return ERROR_MESSAGE_STORE; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_STORE; - } - }); - functions.put("print", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - for (Object i : sources) { - - System.out.print(i); - } - - System.out.println(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_PRINT; - } - }); - functions.put("read", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - if (file.exists() && file.length() < 10000000) { - - try (final FileInputStream fis = new FileInputStream(file)) { - - return IOUtils.toString(fis, "utf-8"); - } - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_READ; - } - }); - functions.put("write", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - if (!file.exists()) { - - try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file, false))) { - - for (int i = 1; i < sources.length; i++) { - if (sources[i] != null) { - IOUtils.write(sources[i].toString(), writer); - } - } - - writer.flush(); - } - - } else { - - logger.log(Level.SEVERE, "Trying to overwrite an existing file, please use append() for that purpose."); - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_WRITE; - } - }); - functions.put("append", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - - try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file, true))) { - - for (int i = 1; i < sources.length; i++) { - IOUtils.write(sources[i].toString(), writer); - } - - writer.flush(); - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_APPEND; - } - }); - functions.put("xml", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String) { - - try { - - final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - if (builder != null) { - - final String xml = (String) sources[0]; - final StringReader reader = new StringReader(xml); - final InputSource src = new InputSource(reader); - - return builder.parse(src); - } - - } catch (IOException | SAXException | ParserConfigurationException ex) { - ex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_XML; - } - }); - functions.put("xpath", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof Document) { - - try { - - XPath xpath = XPathFactory.newInstance().newXPath(); - return xpath.evaluate(sources[1].toString(), sources[0], XPathConstants.STRING); - - } catch (XPathExpressionException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_XPATH; - } - }); - functions.put("set", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof GraphObject) { - - final GraphObject source = (GraphObject) sources[0]; - final Map properties = new LinkedHashMap<>(); - final SecurityContext securityContext = source.getSecurityContext(); - final Gson gson = new GsonBuilder().create(); - final Class type = source.getClass(); - final int sourceCount = sources.length; - - if (sources.length == 3 && sources[2] != null && sources[1].toString().matches("[a-zA-Z0-9_]+")) { - - properties.put(sources[1].toString(), sources[2]); - - } else { - - // we either have and odd number of items, or two multi-value items. - for (int i = 1; i < sourceCount; i++) { - - final Map values = deserialize(gson, sources[i].toString()); - if (values != null) { - - properties.putAll(values); - } - } - } - - // store values in entity - final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, properties); - for (final Map.Entry entry : map.entrySet()) { - - source.setProperty(entry.getKey(), entry.getValue()); - } - - } else { - - throw new FrameworkException(422, "Invalid use of builtin method set, usage: set(entity, params..)"); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SET; - } - }); - functions.put("send_plaintext_mail", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 6)) { - - final String from = sources[0].toString(); - final String fromName = sources[1].toString(); - final String to = sources[2].toString(); - final String toName = sources[3].toString(); - final String subject = sources[4].toString(); - final String textContent = sources[5].toString(); - - try { - return MailHelper.sendSimpleMail(from, fromName, to, toName, null, null, from, subject, textContent); - - } catch (EmailException eex) { - eex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SEND_PLAINTEXT_MAIL; - } - }); - functions.put("send_html_mail", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 6)) { - - final String from = sources[0].toString(); - final String fromName = sources[1].toString(); - final String to = sources[2].toString(); - final String toName = sources[3].toString(); - final String subject = sources[4].toString(); - final String htmlContent = sources[5].toString(); - String textContent = ""; - - if (sources.length == 7) { - textContent = sources[6].toString(); - } - - try { - return MailHelper.sendHtmlMail(from, fromName, to, toName, null, null, from, subject, htmlContent, textContent); - - } catch (EmailException eex) { - eex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SEND_HTML_MAIL; - } - }); - functions.put("geocode", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final Gson gson = new GsonBuilder().create(); - final String street = sources[0].toString(); - final String city = sources[1].toString(); - final String country = sources[2].toString(); - - GeoCodingResult result = GeoHelper.geocode(street, null, null, city, null, country); - if (result != null) { - - final Map map = new LinkedHashMap<>(); - - map.put("latitude", result.getLatitude()); - map.put("longitude", result.getLongitude()); - - return serialize(gson, map); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GEOCODE; - } - }); - functions.put("find", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = ctx.getSecurityContext(); - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Query query = StructrApp.getInstance(securityContext).nodeQuery().sort(GraphObject.createdDate).order(false); - - // the type to query for - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type != null) { - - query.andTypes(type); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - query.and(PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1])); - - } else { - - - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - // throw exception if key is not indexed (otherwise the user will never know) - if (!key.isSearchable()) { - - throw new FrameworkException(400, "Search key " + key.jsonName() + " is not indexed."); - } - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - query.and(key, value); - } - } - } - - return query.getAsList(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIND; - } - }); - functions.put("search", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Query query = StructrApp.getInstance(securityContext).nodeQuery(); - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type != null) { - - query.andTypes(type); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1]); - for (final Entry entry : map.entrySet()) { - - query.and(entry.getKey(), entry.getValue(), false); - } - - } else { - - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - // throw exception if key is not indexed (otherwise the user will never know) - if (!key.isSearchable()) { - - throw new FrameworkException(400, "Search key " + key.jsonName() + " is not indexed."); - } - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - query.and(key, value, false); - } - - } - } - - final Object x = query.getAsList(); - - // return search results - return x; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIND; - } - }); - functions.put("create", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final App app = StructrApp.getInstance(securityContext); - final ConfigurationProvider config = StructrApp.getConfiguration(); - PropertyMap propertyMap = null; - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type.equals(entity.getClass())) { - - throw new FrameworkException(422, "Cannot create() entity of the same type in save action."); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - propertyMap = PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1]); - - } else { - - propertyMap = new PropertyMap(); - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_CREATE); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - propertyMap.put(key, value); - - } - - } - } - - if (type != null) { - - return app.create(type, propertyMap); - - } else { - - throw new FrameworkException(422, "Unknown type in create() save action."); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CREATE; - } - }); - functions.put("delete", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final App app = StructrApp.getInstance(entity.getSecurityContext()); - for (final Object obj : sources) { - - if (obj instanceof NodeInterface) { - - app.delete((NodeInterface) obj); - continue; - } - - if (obj instanceof RelationshipInterface) { - - app.delete((RelationshipInterface) obj); - continue; - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_DELETE; - } - }); - functions.put("incoming", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final RelationshipFactory factory = new RelationshipFactory(entity.getSecurityContext()); - final Object source = sources[0]; - - if (source instanceof NodeInterface) { - - final NodeInterface node = (NodeInterface) source; - if (sources.length > 1) { - - final Object relType = sources[1]; - if (relType != null && relType instanceof String) { - - final String relTypeName = (String) relType; - return factory.instantiate(node.getNode().getRelationships(Direction.INCOMING, DynamicRelationshipType.withName(relTypeName))); - } - - } else { - - return factory.instantiate(node.getNode().getRelationships(Direction.INCOMING)); - } - - } else { - - return "Error: entity is not a node."; - } - } - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INCOMING; - } - }); - functions.put("outgoing", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final RelationshipFactory factory = new RelationshipFactory(entity.getSecurityContext()); - final Object source = sources[0]; - - if (source instanceof NodeInterface) { - - final NodeInterface node = (NodeInterface) source; - if (sources.length > 1) { - - final Object relType = sources[1]; - if (relType != null && relType instanceof String) { - - final String relTypeName = (String) relType; - return factory.instantiate(node.getNode().getRelationships(Direction.OUTGOING, DynamicRelationshipType.withName(relTypeName))); - } - - } else { - - return factory.instantiate(node.getNode().getRelationships(Direction.OUTGOING)); - } - - } else { - - return "Error: entity is not a node."; - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_OUTGOING; - } - }); - functions.put("has_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - return true; - } - } - - } else if (sources.length == 3) { - - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( rel.getRelType().name().equals(relType) && ((rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode))) ) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_RELATIONSHIP; - } - }); - functions.put("has_outgoing_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - return true; - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getRelType().name().equals(relType) && rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_OUTGOING_RELATIONSHIP; - } - }); - functions.put("has_incoming_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) { - return true; - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getRelType().name().equals(relType) && (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_INCOMING_RELATIONSHIP; - } - }); - functions.put("get_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( rel.getRelType().name().equals(relType) && ((rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode))) ) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_RELATIONSHIPS; - } - }); - functions.put("get_outgoing_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getRelType().name().equals(relType) && rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_OUTGOING_RELATIONSHIPS; - } - }); - functions.put("get_incoming_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getRelType().name().equals(relType) && (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_INCOMING_RELATIONSHIPS; - } - }); - functions.put("create_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final Object source = sources[0]; - final Object target = sources[1]; - final String relType = (String) sources[2]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - final Class relClass = StructrApp.getConfiguration().getRelationClassForCombinedType(sourceNode.getType(), relType, targetNode.getType()); - - if (relClass != null) { - - StructrApp.getInstance(sourceNode.getSecurityContext()).create(sourceNode, targetNode, relClass); - - } else { - - return "Error: Unknown relationship type"; - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CREATE_RELATIONSHIP; - } - }); - functions.put("grant", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 3)) { - - if (sources[0] instanceof Principal) { - - final Principal principal = (Principal) sources[0]; - - if (sources[1] instanceof AbstractNode) { - - final AbstractNode node = (AbstractNode) sources[1]; - - if (sources[2] instanceof String) { - - final String[] parts = ((String) sources[2]).split("[,]+"); - for (final String part : parts) { - - final String trimmedPart = part.trim(); - if (trimmedPart.length() > 0) { - - try { - - final Permission permission = Permission.valueOf(trimmedPart); - principal.grant(permission, node); - - } catch (IllegalArgumentException iex) { - - return "Error: unknown permission " + trimmedPart; - } - } - } - - return ""; - - } else { - - return "Error: third argument is not a string."; - } - - } else { - - return "Error: second argument is not a node."; - } - - } else { - - return "Error: first argument is not of type Principal."; - } - - } else { - - return ERROR_MESSAGE_GRANT; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_GRANT; - } - }); - functions.put("revoke", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 3)) { - - if (sources[0] instanceof Principal) { - - final Principal principal = (Principal) sources[0]; - - if (sources[1] instanceof AbstractNode) { - - final AbstractNode node = (AbstractNode) sources[1]; - - if (sources[2] instanceof String) { - - final String[] parts = ((String) sources[2]).split("[,]+"); - for (final String part : parts) { - - final String trimmedPart = part.trim(); - if (trimmedPart.length() > 0) { - - try { - - final Permission permission = Permission.valueOf(trimmedPart); - principal.revoke(permission, node); - - } catch (IllegalArgumentException iex) { - - return "Error: unknown permission " + trimmedPart; - } - } - } - - return ""; - - } else { - - return "Error: third argument is not a string."; - } - - } else { - - return "Error: second argument is not a node."; - } - - } else { - - return "Error: first argument is not of type Principal."; - } - - } else { - - return ERROR_MESSAGE_REVOKE; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_REVOKE; - } - }); - } - - /** - * Test if the given object array has a minimum length and all its - * elements are not null. - * - * @param array - * @param minLength If null, don't do length check - * @return true if array has min length and all elements are not null - */ - public static boolean arrayHasMinLengthAndAllElementsNotNull(final Object[] array, final Integer minLength) { - - if (array == null) { - return false; - } - - for (final Object element : array) { - - if (element == null) { - return false; - } - - } - - return minLength != null ? array.length >= minLength : true; - - } - - /** - * Test if the given object array has exact the given length and all its - * elements are not null. - * - * @param array - * @param length If null, don't do length check - * @return true if array has exact length and all elements are not null - */ - public static boolean arrayHasLengthAndAllElementsNotNull(final Object[] array, final Integer length) { - - if (array == null) { - return false; - } - - for (final Object element : array) { - - if (element == null) { - return false; - } - - } - - return length != null ? array.length == length : true; - - } - - protected static String serialize(final Gson gson, final Map map) { - return gson.toJson(map, new TypeToken>() { - }.getType()); - } - - protected static Map deserialize(final Gson gson, final String source) { - return gson.fromJson(source, new TypeToken>() { - }.getType()); - } - - protected static Integer parseInt(final Object source) { - - if (source instanceof Integer) { - - return ((Integer) source); - } - - if (source instanceof Number) { - - return ((Number) source).intValue(); - } - - if (source instanceof String) { - - return Integer.parseInt((String) source); - } - - return null; - } - - protected static String encodeURL(final String source) { - - try { - return URLEncoder.encode(source, "UTF-8"); - - } catch (UnsupportedEncodingException ex) { - - logger.log(Level.WARNING, "Unsupported Encoding", ex); - } - - // fallback, unencoded - return source; - } - - protected static double getDoubleForComparison(final Object obj) { - - if (obj instanceof Date) { - - return ((Date) obj).getTime(); - - } else if (obj instanceof Number) { - - return ((Number) obj).doubleValue(); - - } else { - - try { - return Double.valueOf(obj.toString()); - - } catch (Throwable t) { - - t.printStackTrace(); - } - } - - return 0.0; - } - - protected static Double getDoubleOrNull(final Object obj) { - - if (obj instanceof Date) { - - return Double.valueOf(((Date) obj).getTime()); - - } else if (obj instanceof Number) { - - return ((Number) obj).doubleValue(); - - } else { - - try { - return Double.valueOf(obj.toString()); - - } catch (Throwable t) { - - t.printStackTrace(); - } - } - - return null; - } - - protected static boolean valueEquals(final Object obj1, final Object obj2) { - - if (obj1 instanceof Enum || obj2 instanceof Enum) { - - return obj1.toString().equals(obj2.toString()); - - } - - if (obj1 instanceof Number && obj2 instanceof Number) { - - return ((Number) obj1).doubleValue() == ((Number) obj2).doubleValue(); - } - - return obj1.equals(obj2); - } - - protected static String getSandboxFileName(final String source) throws IOException { - - final File sandboxFile = new File(source); - final String fileName = sandboxFile.getName(); - final String basePath = StructrApp.getConfigurationValue(Services.BASE_PATH); - - if (!basePath.isEmpty()) { - - final String defaultExchangePath = basePath.endsWith("/") ? basePath.concat("exchange") : basePath.concat("/exchange"); - String exchangeDir = StructrApp.getConfigurationValue(Services.DATA_EXCHANGE_PATH, defaultExchangePath); - - if (!exchangeDir.endsWith("/")) { - exchangeDir = exchangeDir.concat("/"); - } - - // create exchange directory - final File dir = new File(exchangeDir); - if (!dir.exists()) { - - dir.mkdirs(); - } - - // return sandboxed file name - return exchangeDir.concat(fileName); - - } else { - - logger.log(Level.WARNING, "Unable to determine base.path from structr.conf, no data input/output possible."); - } - - return null; - } - - public static String cleanString(final Object input) { - - if (input == null) { - - return ""; - - } - - String normalized = Normalizer.normalize(input.toString(), Normalizer.Form.NFD) - .replaceAll("\\<", "") - .replaceAll("\\>", "") - .replaceAll("\\.", "") - .replaceAll("\\'", "-") - .replaceAll("\\?", "") - .replaceAll("\\(", "") - .replaceAll("\\)", "") - .replaceAll("\\{", "") - .replaceAll("\\}", "") - .replaceAll("\\[", "") - .replaceAll("\\]", "") - .replaceAll("\\+", "-") - .replaceAll("/", "-") - .replaceAll("–", "-") - .replaceAll("\\\\", "-") - .replaceAll("\\|", "-") - .replaceAll("'", "-") - .replaceAll("!", "") - .replaceAll(",", "") - .replaceAll("-", " ") - .replaceAll("_", " ") - .replaceAll("`", "-"); - - String result = normalized.replaceAll("-", " "); - result = StringUtils.normalizeSpace(result.toLowerCase()); - result = result.replaceAll("[^\\p{ASCII}]", "").replaceAll("\\p{P}", "-").replaceAll("\\-(\\s+\\-)+", "-"); - result = result.replaceAll(" ", "-"); - - return result; - - } - - public static void recursivelyConvertMapToGraphObjectMap(final GraphObjectMap destination, final Map source, final int depth) { - - if (depth > 20) { - return; - } - - for (final Map.Entry entry : source.entrySet()) { - - final String key = entry.getKey(); - final Object value = entry.getValue(); - - if (value instanceof Map) { - - final Map map = (Map) value; - final GraphObjectMap obj = new GraphObjectMap(); - - destination.put(new StringProperty(key), obj); - - recursivelyConvertMapToGraphObjectMap(obj, map, depth+1); - - } else if (value instanceof Collection) { - - final List list = new LinkedList(); - final Collection collection = (Collection)value; - - for (final Object obj : collection) { - - if (obj instanceof Map) { - - final GraphObjectMap container = new GraphObjectMap(); - list.add(container); - - recursivelyConvertMapToGraphObjectMap(container, (Map)obj, depth+1); - - } else { - - list.add(obj); - } - } - - destination.put(new StringProperty(key), list); - - } else { - - destination.put(new StringProperty(key), value); - } - } - } - - public static Object numberOrString(final String value) { - - if (value != null) { - - if ("true".equals(value.toLowerCase())) { - return true; - } - - if ("false".equals(value.toLowerCase())) { - return false; - } - - if (NumberUtils.isNumber(value)) { - return NumberUtils.createNumber(value); - } - } - - return value; - } -} diff --git a/All/Genesis-NP/Genesis#154/pair.info b/All/Genesis-NP/Genesis#154/pair.info deleted file mode 100755 index 915c3dd..0000000 --- a/All/Genesis-NP/Genesis#154/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:154 -SATName:Genesis -modifiedFPath:structr-core/src/main/java/org/structr/core/parser/Functions.java -comSha:3e252af00f4daa6b9f16744ab005a575f17fbe5e -parentComSha:3e252af00f4daa6b9f16744ab005a575f17fbe5e^1 -githubUrl:https://github.com/structr/structr -repoName:structr#structr \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#155/comMsg.txt b/All/Genesis-NP/Genesis#155/comMsg.txt deleted file mode 100755 index e25f879..0000000 --- a/All/Genesis-NP/Genesis#155/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE in create() function due to invalid toString() on unchecked array element. diff --git a/All/Genesis-NP/Genesis#155/diff.diff b/All/Genesis-NP/Genesis#155/diff.diff deleted file mode 100755 index 8be2a77..0000000 --- a/All/Genesis-NP/Genesis#155/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/structr-core/src/main/java/org/structr/core/parser/Functions.java b/structr-core/src/main/java/org/structr/core/parser/Functions.java -index b5f4e9d..c6b824e 100644 ---- a/structr-core/src/main/java/org/structr/core/parser/Functions.java -+++ b/structr-core/src/main/java/org/structr/core/parser/Functions.java -@@ -2943 +2943 @@ public class Functions { -- Object value = sources[c+1].toString(); -+ Object value = sources[c+1]; diff --git a/All/Genesis-NP/Genesis#155/new/Functions.java b/All/Genesis-NP/Genesis#155/new/Functions.java deleted file mode 100755 index c6b824e..0000000 --- a/All/Genesis-NP/Genesis#155/new/Functions.java +++ /dev/null @@ -1,3904 +0,0 @@ -/** - * Copyright (C) 2010-2014 Morgner UG (haftungsbeschränkt) - * - * This file is part of Structr . - * - * Structr is free software: you can redistribute it and/or modify it under the - * terms of the GNU General Public License as published by the Free Software - * Foundation, either version 3 of the License, or (at your option) any later - * version. - * - * Structr is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - * A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * Structr. If not, see . - */ -package org.structr.core.parser; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.reflect.TypeToken; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.StreamTokenizer; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.net.URLEncoder; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.Normalizer; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Random; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.apache.commons.mail.EmailException; -import org.neo4j.graphdb.Direction; -import org.neo4j.graphdb.DynamicRelationshipType; -import org.structr.common.GraphObjectComparator; -import org.structr.common.MailHelper; -import org.structr.common.Permission; -import org.structr.common.SecurityContext; -import org.structr.common.error.ErrorToken; -import org.structr.common.error.FrameworkException; -import org.structr.common.error.SemanticErrorToken; -import org.structr.common.geo.GeoCodingResult; -import org.structr.common.geo.GeoHelper; -import org.structr.core.GraphObject; -import org.structr.core.GraphObjectMap; -import org.structr.core.Services; -import org.structr.core.app.App; -import org.structr.core.app.Query; -import org.structr.core.app.StructrApp; -import org.structr.core.converter.PropertyConverter; -import org.structr.core.entity.AbstractNode; -import org.structr.core.entity.AbstractRelationship; -import org.structr.core.entity.MailTemplate; -import org.structr.core.entity.Principal; -import org.structr.core.graph.NodeInterface; -import org.structr.core.graph.RelationshipFactory; -import org.structr.core.graph.RelationshipInterface; -import org.structr.core.property.ISO8601DateProperty; -import org.structr.core.property.PropertyKey; -import org.structr.core.property.PropertyMap; -import org.structr.core.property.StringProperty; -import org.structr.core.script.Scripting; -import org.structr.schema.ConfigurationProvider; -import org.structr.schema.action.ActionContext; -import org.structr.schema.action.Function; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * - * @author Christian Morgner - */ -public class Functions { - - private static final Logger logger = Logger.getLogger(Functions.class.getName()); - public static final Map> functions = new LinkedHashMap<>(); - - public static final String NULL_STRING = "___NULL___"; - - public static final String ERROR_MESSAGE_MD5 = "Usage: ${md5(string)}. Example: ${md5(this.email)}"; - public static final String ERROR_MESSAGE_ERROR = "Usage: ${error(...)}. Example: ${error(\"base\", \"must_equal\", int(5))}"; - public static final String ERROR_MESSAGE_UPPER = "Usage: ${upper(string)}. Example: ${upper(this.nickName)}"; - public static final String ERROR_MESSAGE_LOWER = "Usage: ${lower(string)}. Example: ${lower(this.email)}"; - public static final String ERROR_MESSAGE_JOIN = "Usage: ${join(collection, separator)}. Example: ${join(this.names, \",\")}"; - public static final String ERROR_MESSAGE_CONCAT = "Usage: ${concat(values...)}. Example: ${concat(this.firstName, this.lastName)}"; - public static final String ERROR_MESSAGE_SPLIT = "Usage: ${split(value)}. Example: ${split(this.commaSeparatedItems)}"; - public static final String ERROR_MESSAGE_ABBR = "Usage: ${abbr(longString, maxLength)}. Example: ${abbr(this.title, 20)}"; - public static final String ERROR_MESSAGE_CAPITALIZE = "Usage: ${capitalize(string)}. Example: ${capitalize(this.nickName)}"; - public static final String ERROR_MESSAGE_TITLEIZE = "Usage: ${titleize(string, separator}. Example: ${titleize(this.lowerCamelCaseString, \"_\")}"; - public static final String ERROR_MESSAGE_NUM = "Usage: ${num(string)}. Example: ${num(this.numericalStringValue)}"; - public static final String ERROR_MESSAGE_INT = "Usage: ${to_int(string)}. Example: ${int(this.numericalStringValue)}"; - public static final String ERROR_MESSAGE_RANDOM = "Usage: ${random(num)}. Example: ${set(this, \"password\", random(8))}"; - public static final String ERROR_MESSAGE_RINT = "Usage: ${rint(range)}. Example: ${rint(1000)}"; - public static final String ERROR_MESSAGE_INDEX_OF = "Usage: ${index_of(string, word)}. Example: ${index_of(this.name, \"the\")}"; - public static final String ERROR_MESSAGE_CONTAINS = "Usage: ${contains(string, word)}. Example: ${contains(this.name, \"the\")}"; - public static final String ERROR_MESSAGE_SUBSTRING = "Usage: ${substring(string, start, length)}. Example: ${substring(this.name, 19, 3)}"; - public static final String ERROR_MESSAGE_LENGTH = "Usage: ${length(string)}. Example: ${length(this.name)}"; - public static final String ERROR_MESSAGE_REPLACE = "Usage: ${replace(template, source)}. Example: ${replace(\"${this.id}\", this)}"; - public static final String ERROR_MESSAGE_CLEAN = "Usage: ${clean(string)}. Example: ${clean(this.stringWithNonWordChars)}"; - public static final String ERROR_MESSAGE_URLENCODE = "Usage: ${urlencode(string)}. Example: ${urlencode(this.email)}"; - public static final String ERROR_MESSAGE_ESCAPE_JS = "Usage: ${escape_javascript(string)}. Example: ${escape_javascript(this.name)}"; - public static final String ERROR_MESSAGE_IF = "Usage: ${if(condition, trueValue, falseValue)}. Example: ${if(empty(this.name), this.nickName, this.name)}"; - public static final String ERROR_MESSAGE_EMPTY = "Usage: ${empty(string)}. Example: ${if(empty(possibleEmptyString), \"empty\", \"non-empty\")}"; - public static final String ERROR_MESSAGE_EQUAL = "Usage: ${equal(value1, value2)}. Example: ${equal(this.children.size, 0)}"; - public static final String ERROR_MESSAGE_ADD = "Usage: ${add(values...)}. Example: ${add(1, 2, 3, this.children.size)}"; - public static final String ERROR_MESSAGE_INT_SUM = "Usage: ${int_sum(list)}. Example: ${int_sum(extract(this.children, \"number\"))}"; - public static final String ERROR_MESSAGE_DOUBLE_SUM = "Usage: ${double_sum(list)}. Example: ${double_sum(extract(this.children, \"amount\"))}"; - public static final String ERROR_MESSAGE_IS_COLLECTION = "Usage: ${is_collection(value)}. Example: ${is_collection(this)}"; - public static final String ERROR_MESSAGE_IS_ENTITY = "Usage: ${is_entity(value)}. Example: ${is_entity(this)}"; - public static final String ERROR_MESSAGE_EXTRACT = "Usage: ${extract(list, propertyName)}. Example: ${extract(this.children, \"amount\")}"; - public static final String ERROR_MESSAGE_FILTER = "Usage: ${filter(list, expression)}. Example: ${filter(this.children, gt(size(data.children), 0))}"; - public static final String ERROR_MESSAGE_MERGE = "Usage: ${merge(list1, list2, list3, ...)}. Example: ${merge(this.children, this.siblings)}"; - public static final String ERROR_MESSAGE_COMPLEMENT = "Usage: ${complement(list1, list2, list3, ...)}. (The resulting list contains no duplicates) Example: ${merge(allUsers, me)} => List of all users except myself"; - public static final String ERROR_MESSAGE_UNWIND = "Usage: ${unwind(list1, ...)}. Example: ${unwind(this.children)}"; - public static final String ERROR_MESSAGE_SORT = "Usage: ${sort(list1, key [, true])}. Example: ${sort(this.children, \"name\")}"; - public static final String ERROR_MESSAGE_LT = "Usage: ${lt(value1, value2)}. Example: ${if(lt(this.children, 2), \"Less than two\", \"Equal to or more than two\")}"; - public static final String ERROR_MESSAGE_GT = "Usage: ${gt(value1, value2)}. Example: ${if(gt(this.children, 2), \"More than two\", \"Equal to or less than two\")}"; - public static final String ERROR_MESSAGE_LTE = "Usage: ${lte(value1, value2)}. Example: ${if(lte(this.children, 2), \"Equal to or less than two\", \"More than two\")}"; - public static final String ERROR_MESSAGE_GTE = "Usage: ${gte(value1, value2)}. Example: ${if(gte(this.children, 2), \"Equal to or more than two\", \"Less than two\")}"; - public static final String ERROR_MESSAGE_SUBT = "Usage: ${subt(value1, value)}. Example: ${subt(5, 2)}"; - public static final String ERROR_MESSAGE_MULT = "Usage: ${mult(value1, value)}. Example: ${mult(5, 2)}"; - public static final String ERROR_MESSAGE_QUOT = "Usage: ${quot(value1, value)}. Example: ${quot(5, 2)}"; - public static final String ERROR_MESSAGE_ROUND = "Usage: ${round(value1 [, decimalPlaces])}. Example: ${round(2.345678, 2)}"; - public static final String ERROR_MESSAGE_MAX = "Usage: ${max(value1, value2)}. Example: ${max(this.children, 10)}"; - public static final String ERROR_MESSAGE_MIN = "Usage: ${min(value1, value2)}. Example: ${min(this.children, 5)}"; - public static final String ERROR_MESSAGE_CONFIG = "Usage: ${config(keyFromStructrConf)}. Example: ${config(\"base.path\")}"; - public static final String ERROR_MESSAGE_DATE_FORMAT = "Usage: ${date_format(value, pattern)}. Example: ${date_format(this.creationDate, \"yyyy-MM-dd'T'HH:mm:ssZ\")}"; - public static final String ERROR_MESSAGE_PARSE_DATE = "Usage: ${parse_date(value, pattern)}. Example: ${parse_format(\"2014-01-01\", \"yyyy-MM-dd\")}"; - public static final String ERROR_MESSAGE_NUMBER_FORMAT = "Usage: ${number_format(value, ISO639LangCode, pattern)}. Example: ${number_format(12345.6789, 'en', '#,##0.00')}"; - public static final String ERROR_MESSAGE_TEMPLATE = "Usage: ${template(name, locale, source)}. Example: ${template(\"TEXT_TEMPLATE_1\", \"en_EN\", this)}"; - public static final String ERROR_MESSAGE_NOT = "Usage: ${not(bool1, bool2)}. Example: ${not(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_AND = "Usage: ${and(bool1, bool2)}. Example: ${and(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_OR = "Usage: ${or(bool1, bool2)}. Example: ${or(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_GET = "Usage: ${get(entity, propertyKey)}. Example: ${get(this, \"children\")}"; - public static final String ERROR_MESSAGE_GET_ENTITY = "Cannot evaluate first argument to entity, must be entity or single element list of entities."; - public static final String ERROR_MESSAGE_SIZE = "Usage: ${size(collection)}. Example: ${size(this.children)}"; - public static final String ERROR_MESSAGE_FIRST = "Usage: ${first(collection)}. Example: ${first(this.children)}"; - public static final String ERROR_MESSAGE_LAST = "Usage: ${last(collection)}. Example: ${last(this.children)}"; - public static final String ERROR_MESSAGE_NTH = "Usage: ${nth(collection)}. Example: ${nth(this.children, 2)}"; - public static final String ERROR_MESSAGE_GET_COUNTER = "Usage: ${get_counter(level)}. Example: ${get_counter(1)}"; - public static final String ERROR_MESSAGE_INC_COUNTER = "Usage: ${inc_counter(level, [resetLowerLevels])}. Example: ${inc_counter(1, true)}"; - public static final String ERROR_MESSAGE_RESET_COUNTER = "Usage: ${reset_counter(level)}. Example: ${reset_counter(1)}"; - public static final String ERROR_MESSAGE_MERGE_PROPERTIES = "Usage: ${merge_properties(source, target , mergeKeys...)}. Example: ${merge_properties(this, parent, \"eMail\")}"; - public static final String ERROR_MESSAGE_KEYS = "Usage: ${keys(entity, viewName)}. Example: ${keys(this, \"ui\")}"; - public static final String ERROR_MESSAGE_EACH = "Usage: ${each(collection, expression)}. Example: ${each(this.children, \"set(this, \"email\", lower(get(this.email))))\")}"; - public static final String ERROR_MESSAGE_STORE = "Usage: ${store(key, value)}. Example: ${store('tmpUser', this.owner)}"; - public static final String ERROR_MESSAGE_RETRIEVE = "Usage: ${retrieve(key)}. Example: ${retrieve('tmpUser')}"; - public static final String ERROR_MESSAGE_PRINT = "Usage: ${print(objects...)}. Example: ${print(this.name, \"test\")}"; - public static final String ERROR_MESSAGE_READ = "Usage: ${read(filename)}. Example: ${read(\"text.xml\")}"; - public static final String ERROR_MESSAGE_WRITE = "Usage: ${write(filename, value)}. Example: ${write(\"text.txt\", this.name)}"; - public static final String ERROR_MESSAGE_APPEND = "Usage: ${append(filename, value)}. Example: ${append(\"test.txt\", this.name)}"; - public static final String ERROR_MESSAGE_XML = "Usage: ${xml(xmlSource)}. Example: ${xpath(xml(this.xmlSource), \"/test/testValue\")}"; - public static final String ERROR_MESSAGE_XPATH = "Usage: ${xpath(xmlDocument, expression)}. Example: ${xpath(xml(this.xmlSource), \"/test/testValue\")}"; - public static final String ERROR_MESSAGE_SET = "Usage: ${set(entity, propertyKey, value)}. Example: ${set(this, \"email\", lower(this.email))}"; - public static final String ERROR_MESSAGE_SEND_PLAINTEXT_MAIL = "Usage: ${send_plaintext_mail(fromAddress, fromName, toAddress, toName, subject, content)}."; - public static final String ERROR_MESSAGE_SEND_HTML_MAIL = "Usage: ${send_html_mail(fromAddress, fromName, toAddress, toName, subject, content)}."; - public static final String ERROR_MESSAGE_GEOCODE = "Usage: ${geocode(street, city, country)}. Example: ${set(this, geocode(this.street, this.city, this.country))}"; - public static final String ERROR_MESSAGE_FIND = "Usage: ${find(type, key, value)}. Example: ${find(\"User\", \"email\", \"tester@test.com\"}"; - public static final String ERROR_MESSAGE_SEARCH = "Usage: ${search(type, key, value)}. Example: ${search(\"User\", \"name\", \"abc\"}"; - public static final String ERROR_MESSAGE_CREATE = "Usage: ${create(type, key, value)}. Example: ${create(\"Feedback\", \"text\", this.text)}"; - public static final String ERROR_MESSAGE_DELETE = "Usage: ${delete(entity)}. Example: ${delete(this)}"; - public static final String ERROR_MESSAGE_CACHE = "Usage: ${cache(key, timeout, valueExpression)}. Example: ${cache('value', 60, GET('http://rate-limited-URL.com'))}"; - public static final String ERROR_MESSAGE_GRANT = "Usage: ${grant(principal, node, permissions)}. Example: ${grant(me, this, 'read, write, delete'))}"; - public static final String ERROR_MESSAGE_REVOKE = "Usage: ${revoke(principal, node, permissions)}. Example: ${revoke(me, this, 'write, delete'))}"; - - // Special functions for relationships - public static final String ERROR_MESSAGE_INCOMING = "Usage: ${incoming(entity [, relType])}. Example: ${incoming(this, 'PARENT_OF')}"; - public static final String ERROR_MESSAGE_OUTGOING = "Usage: ${outgoing(entity [, relType])}. Example: ${outgoing(this, 'PARENT_OF')}"; - public static final String ERROR_MESSAGE_HAS_RELATIONSHIP = "Usage: ${has_relationship(entity1, entity2 [, relType])}. Example: ${has_relationship(me, user, 'FOLLOWS')} (ignores direction of the relationship)"; - public static final String ERROR_MESSAGE_HAS_OUTGOING_RELATIONSHIP = "Usage: ${has_outgoing_relationship(from, to [, relType])}. Example: ${has_outgoing_relationship(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_HAS_INCOMING_RELATIONSHIP = "Usage: ${has_incoming_relationship(from, to [, relType])}. Example: ${has_incoming_relationship(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_GET_RELATIONSHIPS = "Usage: ${get_relationships(entity1, entity2 [, relType])}. Example: ${get_relationships(me, user, 'FOLLOWS')} (ignores direction of the relationship)"; - public static final String ERROR_MESSAGE_GET_OUTGOING_RELATIONSHIPS = "Usage: ${get_outgoing_relationships(from, to [, relType])}. Example: ${get_outgoing_relationships(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_GET_INCOMING_RELATIONSHIPS = "Usage: ${get_incoming_relationships(from, to [, relType])}. Example: ${get_incoming_relationships(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_CREATE_RELATIONSHIP = "Usage: ${create_relationship(from, to, relType)}. Example: ${create_relationship(me, user, 'FOLLOWS')} (Relationshiptype has to exist)"; - - public static Function get(final String name) { - return functions.get(name); - } - - public static Object evaluate(final SecurityContext securityContext, final ActionContext actionContext, final GraphObject entity, final String expression) throws FrameworkException { - - final String expressionWithoutNewlines = expression.replace('\n', ' '); - final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(expressionWithoutNewlines)); - tokenizer.eolIsSignificant(true); - tokenizer.ordinaryChar('.'); - tokenizer.wordChars('_', '_'); - tokenizer.wordChars('.', '.'); - tokenizer.wordChars('!', '!'); - - Expression root = new RootExpression(); - Expression current = root; - Expression next = null; - String lastToken = null; - int token = 0; - int level = 0; - - while (token != StreamTokenizer.TT_EOF) { - - token = nextToken(tokenizer); - - switch (token) { - - case StreamTokenizer.TT_EOF: - break; - - case StreamTokenizer.TT_EOL: - break; - - case StreamTokenizer.TT_NUMBER: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before NUMBER"); - } - next = new ConstantExpression(tokenizer.nval); - current.add(next); - lastToken += "NUMBER"; - break; - - case StreamTokenizer.TT_WORD: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval); - } - next = checkReservedWords(tokenizer.sval); - current.add(next); - lastToken = tokenizer.sval; - break; - - case '(': - if (((current == null || current instanceof RootExpression) && next == null) || current == next) { - - // an additional bracket without a new function, - // this can only be an execution group. - next = new GroupExpression(); - current.add(next); - } - - current = next; - lastToken += "("; - level++; - break; - - case ')': - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + lastToken); - } - current = current.getParent(); - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - lastToken += ")"; - level--; - break; - - case '[': - // bind directly to the previous expression - next = new ArrayExpression(); - current.add(next); - current = next; - lastToken += "["; - level++; - break; - - case ']': - - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket before " + lastToken); - } - current = current.getParent(); - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - lastToken += "]"; - level--; - break; - - case ';': - next = null; - lastToken += ";"; - break; - - case ',': - next = current; - lastToken += ","; - break; - - default: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval); - } - current.add(new ConstantExpression(tokenizer.sval)); - lastToken = tokenizer.sval; - - } - } - - if (level > 0) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - - return root.evaluate(securityContext, actionContext, entity); - } - - private static Expression checkReservedWords(final String word) throws FrameworkException { - - if (word == null) { - return new NullExpression(); - } - - switch (word) { - - case "cache": - return new CacheExpression(); - - case "true": - return new ConstantExpression(true); - - case "false": - return new ConstantExpression(false); - - case "if": - return new IfExpression(); - - case "each": - return new EachExpression(); - - case "filter": - return new FilterExpression(); - - case "data": - return new ValueExpression("data"); - - case "null": - return new ConstantExpression(NULL_STRING); - } - - // no match, try functions - final Function function = Functions.get(word); - if (function != null) { - - return new FunctionExpression(word, function); - - } else { - - return new ValueExpression(word); - } - } - - public static int nextToken(final StreamTokenizer tokenizer) { - - try { - - return tokenizer.nextToken(); - - } catch (IOException ioex) { - } - - return StreamTokenizer.TT_EOF; - } - - static { - - functions.put("error", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entity.getClass(), sources[0].toString()); - ctx.raiseError(entity.getType(), new ErrorToken(422, key) { - - @Override - public JsonElement getContent() { - return new JsonPrimitive(getErrorToken()); - } - - @Override - public String getErrorToken() { - return sources[1].toString(); - } - }); - - } else if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entity.getClass(), sources[0].toString()); - ctx.raiseError(entity.getType(), new SemanticErrorToken(key) { - - @Override - public JsonElement getContent() { - - JsonObject obj = new JsonObject(); - - if (sources[2] instanceof Number) { - - obj.add(getErrorToken(), new JsonPrimitive((Number) sources[2])); - - } else if (sources[2] instanceof Boolean) { - - obj.add(getErrorToken(), new JsonPrimitive((Boolean) sources[2])); - - } else { - - obj.add(getErrorToken(), new JsonPrimitive(sources[2].toString())); - } - - return obj; - } - - @Override - public String getErrorToken() { - return sources[1].toString(); - } - }); - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_ERROR; - } - }); - functions.put("md5", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? DigestUtils.md5Hex(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MD5; - } - }); - functions.put("upper", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? sources[0].toString().toUpperCase() - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_UPPER; - } - - }); - functions.put("lower", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? sources[0].toString().toLowerCase() - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LOWER; - } - - }); - functions.put("join", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof Collection) { - - return StringUtils.join((Collection) sources[0], sources[1].toString()); - } - - if (sources[0].getClass().isArray()) { - - return StringUtils.join((Object[]) sources[0], sources[1].toString()); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_JOIN; - } - - }); - functions.put("concat", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - // collection can contain nulls.. - if (source != null) { - - if (source instanceof Collection) { - - list.addAll((Collection) source); - - } else if (source.getClass().isArray()) { - - list.addAll(Arrays.asList((Object[])source)); - - } else { - - list.add(source); - } - } - } - - return StringUtils.join(list, ""); - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONCAT; - } - - }); - functions.put("split", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final String toSplit = sources[0].toString(); - String splitExpr = "[,;]+"; - - if (sources.length >= 2) { - splitExpr = sources[1].toString(); - } - - return Arrays.asList(toSplit.split(splitExpr)); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SPLIT; - } - - }); - functions.put("abbr", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - try { - int maxLength = Double.valueOf(sources[1].toString()).intValue(); - - if (sources[0].toString().length() > maxLength) { - - return StringUtils.substringBeforeLast(StringUtils.substring(sources[0].toString(), 0, maxLength), " ").concat("…"); - - } else { - - return sources[0]; - } - - } catch (NumberFormatException nfe) { - - return nfe.getMessage(); - - } - - } - - return ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ABBR; - } - - }); - functions.put("capitalize", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? StringUtils.capitalize(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_CAPITALIZE; - } - }); - functions.put("titleize", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources.length < 2 || sources[0] == null) { - return null; - } - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - if (sources[1] == null) { - sources[1] = " "; - } - - String[] in = StringUtils.split(sources[0].toString(), sources[1].toString()); - String[] out = new String[in.length]; - for (int i = 0; i < in.length; i++) { - out[i] = StringUtils.capitalize(in[i]); - } - return StringUtils.join(out, " "); - - } - - @Override - public String usage() { - return ERROR_MESSAGE_TITLEIZE; - } - - }); - functions.put("num", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - return getDoubleOrNull(sources[0]); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NUM; - } - }); - functions.put("to_int", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Number) { - return ((Number) sources[0]).intValue(); - } - - try { - return getDoubleOrNull(sources[0]).intValue(); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INT; - } - }); - functions.put("random", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof Number) { - - try { - return RandomStringUtils.randomAlphanumeric(((Number) sources[0]).intValue()); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RANDOM; - } - }); - functions.put("rint", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof Number) { - - try { - return new Random(System.currentTimeMillis()).nextInt(((Number) sources[0]).intValue()); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RINT; - } - }); - functions.put("index_of", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final String source = sources[0].toString(); - final String part = sources[1].toString(); - - return source.indexOf(part); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INDEX_OF; - } - }); - functions.put("contains", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof String && sources[1] instanceof String) { - - final String source = sources[0].toString(); - final String part = sources[1].toString(); - - return source.contains(part); - - } else if (sources[0] instanceof Collection && sources[1] instanceof GraphObject) { - - final Collection collection = (Collection) sources[0]; - final GraphObject obj = (GraphObject) sources[1]; - - return collection.contains(obj); - - } else if (sources[0].getClass().isArray()) { - - return ArrayUtils.contains((Object[])sources[0], sources[1]); - } - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONTAINS; - } - }); - functions.put("substring", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final String source = sources[0].toString(); - final int sourceLength = source.length(); - final int start = parseInt(sources[1]); - final int length = sources.length >= 3 ? parseInt(sources[2]) : sourceLength - start; - final int end = start + length; - - if (start >= 0 && start < sourceLength && end >= 0 && end <= sourceLength && start <= end) { - - return source.substring(start, end); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBSTRING; - } - }); - functions.put("length", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - return sources[0].toString().length(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBSTRING; - } - }); - functions.put("replace", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final String template = sources[0].toString(); - AbstractNode node = null; - - if (sources[1] instanceof AbstractNode) { - node = (AbstractNode) sources[1]; - } - - if (sources[1] instanceof List) { - - final List list = (List) sources[1]; - if (list.size() == 1 && list.get(0) instanceof AbstractNode) { - - node = (AbstractNode) list.get(0); - } - } - - if (node != null) { - - // recursive replacement call, be careful here - return Scripting.replaceVariables(entity.getSecurityContext(), node, ctx, template); - } - - return ""; - } - - return usage(); - - } - - @Override - public String usage() { - return ERROR_MESSAGE_REPLACE; - } - }); - functions.put("clean", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - return cleanString(sources[0]); - } - - return null; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_CLEAN; - } - - }); - functions.put("urlencode", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? encodeURL(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_URLENCODE; - } - - }); - functions.put("escape_javascript", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? StringEscapeUtils.escapeEcmaScript(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ESCAPE_JS; - } - - }); - functions.put("if", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources[0] == null || sources.length < 3) { - - return ""; - } - - if ("true".equals(sources[0]) || Boolean.TRUE.equals(sources[0])) { - - return sources[1]; - - } else { - - return sources[2]; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IF; - } - - }); - functions.put("empty", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources.length == 0 || sources[0] == null || StringUtils.isEmpty(sources[0].toString())) { - - return true; - - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_EMPTY; - } - - }); - functions.put("equal", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - logger.log(Level.FINE, "Length: {0}", sources.length); - - if (sources.length < 2) { - - return true; - } - - logger.log(Level.FINE, "Comparing {0} to {1}", new java.lang.Object[]{sources[0], sources[1]}); - - if (sources[0] == null && sources[1] == null) { - return true; - } - - if (sources[0] == null || sources[1] == null) { - return false; - } - - return valueEquals(sources[0], sources[1]); - } - - @Override - public String usage() { - return ERROR_MESSAGE_EQUAL; - } - - }); - functions.put("eq", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return functions.get("equal").apply(ctx, entity, sources); - } - - @Override - public String usage() { - - return functions.get("equal").usage(); - } - - }); - functions.put("add", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Double result = 0.0; - - if (sources != null) { - - for (Object i : sources) { - - if (i != null) { - - try { - - result += Double.parseDouble(i.toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - result += 0.0; - } - } - - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ADD; - } - - }); - functions.put("double_sum", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - double result = 0.0; - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Collection) { - - for (final Number num : (Collection) sources[0]) { - - result += num.doubleValue(); - } - } - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_DOUBLE_SUM; - } - - }); - functions.put("int_sum", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - int result = 0; - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Collection) { - - for (final Number num : (Collection) sources[0]) { - - result += num.intValue(); - } - } - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_INT_SUM; - } - - }); - functions.put("is_collection", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - return (sources[0] instanceof Collection); - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IS_COLLECTION; - } - - }); - functions.put("is_entity", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - return (sources[0] instanceof GraphObject); - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IS_ENTITY; - } - - }); - functions.put("extract", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - // no property key given, maybe we should extract a list of lists? - if (sources[0] instanceof Collection) { - - final List extraction = new LinkedList(); - - for (final Object obj : (Collection) sources[0]) { - - if (obj instanceof Collection) { - - extraction.addAll((Collection) obj); - } - } - - return extraction; - } - - } else if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof Collection && sources[1] instanceof String) { - - final ConfigurationProvider config = StructrApp.getConfiguration(); - final List extraction = new LinkedList(); - final String keyName = (String) sources[1]; - - for (final Object obj : (Collection) sources[0]) { - - if (obj instanceof GraphObject) { - - final PropertyKey key = config.getPropertyKeyForJSONName(obj.getClass(), keyName); - final Object value = ((GraphObject) obj).getProperty(key); - if (value != null) { - - extraction.add(value); - } - } - } - - return extraction; - } - } - - return null; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_EXTRACT; - } - - }); - functions.put("merge", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - - if (obj != null) { - - list.add(obj); - } - } - - } else if (source != null) { - - list.add(source); - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE; - } - - }); - functions.put("complement", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final Set sourceSet = new HashSet(); - - if (sources[0] instanceof Collection) { - - sourceSet.addAll((Collection)sources[0]); - - for (int cnt = 1; cnt < sources.length; cnt++) { - - final Object source = sources[cnt]; - - if (source instanceof Collection) { - - sourceSet.removeAll((Collection)source); - - } else if (source != null) { - - sourceSet.remove(source); - } - } - - } else { - - return "Argument 1 for complement must be a Collection"; - } - - return sourceSet; - } - - @Override - public String usage() { - return ERROR_MESSAGE_COMPLEMENT; - } - - }); - functions.put("unwind", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - if (obj != null) { - - if (obj instanceof Collection) { - - for (final Object elem : (Collection) obj) { - - if (elem != null) { - - list.add(elem); - } - } - - } else { - - list.add(obj); - } - } - } - - } else if (source != null) { - - list.add(source); - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE; - } - - }); - functions.put("sort", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof List && sources[1] instanceof String) { - - final List list = (List) sources[0]; - final String sortKey = sources[1].toString(); - final Iterator iterator = list.iterator(); - - if (iterator.hasNext()) { - - final Object firstElement = iterator.next(); - if (firstElement instanceof GraphObject) { - - final Class type = firstElement.getClass(); - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(type, sortKey); - final boolean descending = sources.length == 3 && sources[2] != null && "true".equals(sources[2].toString()); - - if (key != null) { - - List sortCollection = (List) list; - Collections.sort(sortCollection, new GraphObjectComparator(key, descending)); - } - } - - } - } - } - - return sources[0]; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SORT; - } - - }); - functions.put("lt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 < value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LT; - } - }); - functions.put("gt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 > value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_GT; - } - }); - functions.put("lte", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 <= value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LTE; - } - }); - functions.put("gte", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 >= value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_GTE; - } - }); - functions.put("subt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - try { - - Double result = Double.parseDouble(sources[0].toString()); - - for (int i = 1; i < sources.length; i++) { - - result -= Double.parseDouble(sources[i].toString()); - - } - - return result; - - } catch (Throwable t) { - - return t.getMessage(); - - } - } - - return ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBT; - } - }); - functions.put("mult", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Double result = 1.0d; - - if (sources != null) { - - for (Object i : sources) { - - try { - - result *= Double.parseDouble(i.toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - } - - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MULT; - } - }); - functions.put("quot", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - - return Double.parseDouble(sources[0].toString()) / Double.parseDouble(sources[1].toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - if (sources != null) { - - if (sources.length > 0 && sources[0] != null) { - return Double.valueOf(sources[0].toString()); - } - - return ""; - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_QUOT; - } - }); - functions.put("round", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - try { - - Double f1 = Double.parseDouble(sources[0].toString()); - double f2 = Math.pow(10, (Double.parseDouble(sources[1].toString()))); - long r = Math.round(f1 * f2); - - return (double) r / f2; - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - return ""; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_ROUND; - } - }); - functions.put("max", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Object result = ""; - String errorMsg = "ERROR! Usage: ${max(val1, val2)}. Example: ${max(5,10)}"; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - result = Math.max(Double.parseDouble(sources[0].toString()), Double.parseDouble(sources[1].toString())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Could not determine max() of {0} and {1}", new Object[]{sources[0], sources[1]}); - result = errorMsg; - } - - } else { - - result = ""; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MAX; - } - }); - functions.put("min", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Object result = ""; - String errorMsg = "ERROR! Usage: ${min(val1, val2)}. Example: ${min(5,10)}"; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - result = Math.min(Double.parseDouble(sources[0].toString()), Double.parseDouble(sources[1].toString())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Could not determine min() of {0} and {1}", new Object[]{sources[0], sources[1]}); - result = errorMsg; - } - - } else { - - result = ""; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MIN; - } - }); - functions.put("config", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final String configKey = sources[0].toString(); - final String defaultValue = sources.length >= 2 ? sources[1].toString() : ""; - - return StructrApp.getConfigurationValue(configKey, defaultValue); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONFIG; - } - }); - functions.put("date_format", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 2) { - return ERROR_MESSAGE_DATE_FORMAT; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - Date date = null; - - if (sources[0] instanceof Date) { - - date = (Date) sources[0]; - - } else if (sources[0] instanceof Number) { - - date = new Date(((Number) sources[0]).longValue()); - - } else { - - try { - - // parse with format from IS - date = new SimpleDateFormat(ISO8601DateProperty.PATTERN).parse(sources[0].toString()); - - } catch (ParseException ex) { - ex.printStackTrace(); - } - - } - - // format with given pattern - return new SimpleDateFormat(sources[1].toString()).format(date); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_DATE_FORMAT; - } - }); - functions.put("parse_date", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 2) { - return ERROR_MESSAGE_PARSE_DATE; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - String dateString = sources[0].toString(); - - if (StringUtils.isBlank(dateString)) { - return ""; - } - - String pattern = sources[1].toString(); - - try { - // parse with format from IS - return new SimpleDateFormat(pattern).parse(dateString); - - } catch (ParseException ex) { - logger.log(Level.WARNING, "Could not parse date " + dateString + " and format it to pattern " + pattern, ex); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_PARSE_DATE; - } - }); - functions.put("number_format", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 3) { - return ERROR_MESSAGE_NUMBER_FORMAT; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - try { - - Double val = Double.parseDouble(sources[0].toString()); - String langCode = sources[1].toString(); - String pattern = sources[2].toString(); - - return new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.forLanguageTag(langCode))).format(val); - - } catch (Throwable t) { - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NUMBER_FORMAT; - } - }); - functions.put("template", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 3) { - return ERROR_MESSAGE_TEMPLATE; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 3) && sources[2] instanceof AbstractNode) { - - final App app = StructrApp.getInstance(entity.getSecurityContext()); - final String name = sources[0].toString(); - final String locale = sources[1].toString(); - final MailTemplate template = app.nodeQuery(MailTemplate.class).andName(name).and(MailTemplate.locale, locale).getFirst(); - final AbstractNode templateInstance = (AbstractNode) sources[2]; - - if (template != null) { - - final String text = template.getProperty(MailTemplate.text); - if (text != null) { - - // recursive replacement call, be careful here - return Scripting.replaceVariables(entity.getSecurityContext(), templateInstance, ctx, text); - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_TEMPLATE; - } - }); - functions.put("not", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - return !("true".equals(sources[0].toString()) || Boolean.TRUE.equals(sources[0])); - - } - - return true; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NOT; - } - - }); - functions.put("and", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - boolean result = true; - - if (sources != null) { - - if (sources.length < 2) { - return usage(); - } - - for (Object i : sources) { - - if (i != null) { - - try { - - result &= "true".equals(i.toString()) || Boolean.TRUE.equals(i); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - // null is false - return false; - } - } - - } - - return result; - } - - @Override - public String usage() { - return ERROR_MESSAGE_AND; - } - - }); - functions.put("or", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - boolean result = false; - - if (sources != null) { - - if (sources.length < 2) { - return usage(); - } - - for (Object i : sources) { - - if (i != null) { - - try { - - result |= "true".equals(i.toString()) || Boolean.TRUE.equals(i); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - // null is false - result |= false; - } - } - - } - - return result; - } - - @Override - public String usage() { - return ERROR_MESSAGE_OR; - } - }); - functions.put("get", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final SecurityContext securityContext = entity.getSecurityContext(); - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - GraphObject dataObject = null; - - if (sources[0] instanceof GraphObject) { - dataObject = (GraphObject) sources[0]; - } - - if (sources[0] instanceof List) { - - final List list = (List) sources[0]; - if (list.size() == 1 && list.get(0) instanceof GraphObject) { - - dataObject = (GraphObject) list.get(0); - } - } - - if (dataObject != null) { - - final String keyName = sources[1].toString(); - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(dataObject.getClass(), keyName); - - if (key != null) { - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = dataObject.getProperty(key); - - if (inputConverter != null) { - return inputConverter.revert(value); - } - - return dataObject.getProperty(key); - } - - return ""; - - } else { - - return ERROR_MESSAGE_GET_ENTITY; - } - } - - return usage(); - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET; - } - }); - functions.put("size", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source != null) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - if (obj != null && !NULL_STRING.equals(obj)) { - - list.add(obj); - } - } - - } else if(source.getClass().isArray()) { - - list.addAll(Arrays.asList((Object[])source)); - - } else if (source != null && !NULL_STRING.equals(source)) { - - list.add(source); - } - - return list.size(); - } - } - - return 0; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SIZE; - } - }); - functions.put("first", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - return ((List) sources[0]).get(0); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (arr.length > 0) { - - return arr[0]; - } - } - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIRST; - } - }); - functions.put("last", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - - final List list = (List) sources[0]; - return list.get(list.size() - 1); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (arr.length > 0) { - - return arr[arr.length - 1]; - } - } - - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_LAST; - } - }); - functions.put("nth", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final int pos = Double.valueOf(sources[1].toString()).intValue(); - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - - final List list = (List) sources[0]; - final int size = list.size(); - - if (pos >= size) { - - return null; - - } - - return list.get(Math.min(Math.max(0, pos), size - 1)); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (pos <= arr.length) { - - return arr[pos]; - } - } - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NTH; - } - }); - functions.put("get_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - return ctx.getCounter(parseInt(sources[0])); - } - - return 0; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_COUNTER; - } - }); - functions.put("inc_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final int level = parseInt(sources[0]); - - ctx.incrementCounter(level); - - // reset lower levels? - if (sources.length == 2 && "true".equals(sources[1].toString())) { - - // reset lower levels - for (int i = level + 1; i < 10; i++) { - ctx.resetCounter(i); - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INC_COUNTER; - } - }); - functions.put("reset_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - ctx.resetCounter(parseInt(sources[0])); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RESET_COUNTER; - } - }); - functions.put("merge_properties", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof GraphObject && sources[1] instanceof GraphObject) { - - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Set mergeKeys = new LinkedHashSet<>(); - final GraphObject source = (GraphObject) sources[0]; - final GraphObject target = (GraphObject) sources[1]; - final int paramCount = sources.length; - - for (int i = 2; i < paramCount; i++) { - - final String keyName = sources[i].toString(); - final PropertyKey key = config.getPropertyKeyForJSONName(target.getClass(), keyName); - - mergeKeys.add(key); - } - - for (final PropertyKey key : mergeKeys) { - - final Object sourceValue = source.getProperty(key); - if (sourceValue != null) { - - target.setProperty(key, sourceValue); - } - - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE_PROPERTIES; - } - }); - functions.put("keys", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof GraphObject) { - - final Set keys = new LinkedHashSet<>(); - final GraphObject source = (GraphObject) sources[0]; - - for (final PropertyKey key : source.getPropertyKeys(sources[1].toString())) { - keys.add(key.jsonName()); - } - - return new LinkedList<>(keys); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_KEYS; - } - }); - - // ----- BEGIN functions with side effects ----- - functions.put("retrieve", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String) { - - return ctx.retrieve(sources[0].toString()); - - } else { - - return ERROR_MESSAGE_RETRIEVE; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_RETRIEVE; - } - }); - functions.put("store", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof String) { - - ctx.store(sources[0].toString(), sources[1]); - - } else { - - return ERROR_MESSAGE_STORE; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_STORE; - } - }); - functions.put("print", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - for (Object i : sources) { - - System.out.print(i); - } - - System.out.println(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_PRINT; - } - }); - functions.put("read", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - if (file.exists() && file.length() < 10000000) { - - try (final FileInputStream fis = new FileInputStream(file)) { - - return IOUtils.toString(fis, "utf-8"); - } - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_READ; - } - }); - functions.put("write", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - if (!file.exists()) { - - try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file, false))) { - - for (int i = 1; i < sources.length; i++) { - if (sources[i] != null) { - IOUtils.write(sources[i].toString(), writer); - } - } - - writer.flush(); - } - - } else { - - logger.log(Level.SEVERE, "Trying to overwrite an existing file, please use append() for that purpose."); - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_WRITE; - } - }); - functions.put("append", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - - try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file, true))) { - - for (int i = 1; i < sources.length; i++) { - IOUtils.write(sources[i].toString(), writer); - } - - writer.flush(); - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_APPEND; - } - }); - functions.put("xml", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String) { - - try { - - final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - if (builder != null) { - - final String xml = (String) sources[0]; - final StringReader reader = new StringReader(xml); - final InputSource src = new InputSource(reader); - - return builder.parse(src); - } - - } catch (IOException | SAXException | ParserConfigurationException ex) { - ex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_XML; - } - }); - functions.put("xpath", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof Document) { - - try { - - XPath xpath = XPathFactory.newInstance().newXPath(); - return xpath.evaluate(sources[1].toString(), sources[0], XPathConstants.STRING); - - } catch (XPathExpressionException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_XPATH; - } - }); - functions.put("set", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof GraphObject) { - - final GraphObject source = (GraphObject) sources[0]; - final Map properties = new LinkedHashMap<>(); - final SecurityContext securityContext = source.getSecurityContext(); - final Gson gson = new GsonBuilder().create(); - final Class type = source.getClass(); - final int sourceCount = sources.length; - - if (sources.length == 3 && sources[2] != null && sources[1].toString().matches("[a-zA-Z0-9_]+")) { - - properties.put(sources[1].toString(), sources[2]); - - } else { - - // we either have and odd number of items, or two multi-value items. - for (int i = 1; i < sourceCount; i++) { - - final Map values = deserialize(gson, sources[i].toString()); - if (values != null) { - - properties.putAll(values); - } - } - } - - // store values in entity - final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, properties); - for (final Map.Entry entry : map.entrySet()) { - - source.setProperty(entry.getKey(), entry.getValue()); - } - - } else { - - throw new FrameworkException(422, "Invalid use of builtin method set, usage: set(entity, params..)"); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SET; - } - }); - functions.put("send_plaintext_mail", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 6)) { - - final String from = sources[0].toString(); - final String fromName = sources[1].toString(); - final String to = sources[2].toString(); - final String toName = sources[3].toString(); - final String subject = sources[4].toString(); - final String textContent = sources[5].toString(); - - try { - return MailHelper.sendSimpleMail(from, fromName, to, toName, null, null, from, subject, textContent); - - } catch (EmailException eex) { - eex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SEND_PLAINTEXT_MAIL; - } - }); - functions.put("send_html_mail", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 6)) { - - final String from = sources[0].toString(); - final String fromName = sources[1].toString(); - final String to = sources[2].toString(); - final String toName = sources[3].toString(); - final String subject = sources[4].toString(); - final String htmlContent = sources[5].toString(); - String textContent = ""; - - if (sources.length == 7) { - textContent = sources[6].toString(); - } - - try { - return MailHelper.sendHtmlMail(from, fromName, to, toName, null, null, from, subject, htmlContent, textContent); - - } catch (EmailException eex) { - eex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SEND_HTML_MAIL; - } - }); - functions.put("geocode", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final Gson gson = new GsonBuilder().create(); - final String street = sources[0].toString(); - final String city = sources[1].toString(); - final String country = sources[2].toString(); - - GeoCodingResult result = GeoHelper.geocode(street, null, null, city, null, country); - if (result != null) { - - final Map map = new LinkedHashMap<>(); - - map.put("latitude", result.getLatitude()); - map.put("longitude", result.getLongitude()); - - return serialize(gson, map); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GEOCODE; - } - }); - functions.put("find", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Query query = StructrApp.getInstance(securityContext).nodeQuery().sort(GraphObject.createdDate).order(false); - - // the type to query for - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type != null) { - - query.andTypes(type); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - query.and(PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1])); - - } else { - - - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - // throw exception if key is not indexed (otherwise the user will never know) - if (!key.isSearchable()) { - - throw new FrameworkException(400, "Search key " + key.jsonName() + " is not indexed."); - } - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - query.and(key, value); - } - } - } - - final Object x = query.getAsList(); - - // return search results - return x; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIND; - } - }); - functions.put("search", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Query query = StructrApp.getInstance(securityContext).nodeQuery(); - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type != null) { - - query.andTypes(type); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1]); - for (final Entry entry : map.entrySet()) { - - query.and(entry.getKey(), entry.getValue(), false); - } - - } else { - - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - // throw exception if key is not indexed (otherwise the user will never know) - if (!key.isSearchable()) { - - throw new FrameworkException(400, "Search key " + key.jsonName() + " is not indexed."); - } - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - query.and(key, value, false); - } - - } - } - - final Object x = query.getAsList(); - - // return search results - return x; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIND; - } - }); - functions.put("create", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final App app = StructrApp.getInstance(securityContext); - final ConfigurationProvider config = StructrApp.getConfiguration(); - PropertyMap propertyMap = null; - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type.equals(entity.getClass())) { - - throw new FrameworkException(422, "Cannot create() entity of the same type in save action."); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - propertyMap = PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1]); - - } else { - - propertyMap = new PropertyMap(); - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_CREATE); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - propertyMap.put(key, value); - - } - - } - } - - if (type != null) { - - return app.create(type, propertyMap); - - } else { - - throw new FrameworkException(422, "Unknown type in create() save action."); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CREATE; - } - }); - functions.put("delete", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final App app = StructrApp.getInstance(entity.getSecurityContext()); - for (final Object obj : sources) { - - if (obj instanceof NodeInterface) { - - app.delete((NodeInterface) obj); - continue; - } - - if (obj instanceof RelationshipInterface) { - - app.delete((RelationshipInterface) obj); - continue; - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_DELETE; - } - }); - functions.put("incoming", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final RelationshipFactory factory = new RelationshipFactory(entity.getSecurityContext()); - final Object source = sources[0]; - - if (source instanceof NodeInterface) { - - final NodeInterface node = (NodeInterface) source; - if (sources.length > 1) { - - final Object relType = sources[1]; - if (relType != null && relType instanceof String) { - - final String relTypeName = (String) relType; - return factory.instantiate(node.getNode().getRelationships(Direction.INCOMING, DynamicRelationshipType.withName(relTypeName))); - } - - } else { - - return factory.instantiate(node.getNode().getRelationships(Direction.INCOMING)); - } - - } else { - - return "Error: entity is not a node."; - } - } - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INCOMING; - } - }); - functions.put("outgoing", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final RelationshipFactory factory = new RelationshipFactory(entity.getSecurityContext()); - final Object source = sources[0]; - - if (source instanceof NodeInterface) { - - final NodeInterface node = (NodeInterface) source; - if (sources.length > 1) { - - final Object relType = sources[1]; - if (relType != null && relType instanceof String) { - - final String relTypeName = (String) relType; - return factory.instantiate(node.getNode().getRelationships(Direction.OUTGOING, DynamicRelationshipType.withName(relTypeName))); - } - - } else { - - return factory.instantiate(node.getNode().getRelationships(Direction.OUTGOING)); - } - - } else { - - return "Error: entity is not a node."; - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_OUTGOING; - } - }); - functions.put("has_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - return true; - } - } - - } else if (sources.length == 3) { - - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( rel.getRelType().name().equals(relType) && ((rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode))) ) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_RELATIONSHIP; - } - }); - functions.put("has_outgoing_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - return true; - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getRelType().name().equals(relType) && rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_OUTGOING_RELATIONSHIP; - } - }); - functions.put("has_incoming_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) { - return true; - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getRelType().name().equals(relType) && (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_INCOMING_RELATIONSHIP; - } - }); - functions.put("get_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( rel.getRelType().name().equals(relType) && ((rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode))) ) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_RELATIONSHIPS; - } - }); - functions.put("get_outgoing_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getRelType().name().equals(relType) && rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_OUTGOING_RELATIONSHIPS; - } - }); - functions.put("get_incoming_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getRelType().name().equals(relType) && (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_INCOMING_RELATIONSHIPS; - } - }); - functions.put("create_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final Object source = sources[0]; - final Object target = sources[1]; - final String relType = (String) sources[2]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - final Class relClass = StructrApp.getConfiguration().getRelationClassForCombinedType(sourceNode.getType(), relType, targetNode.getType()); - - if (relClass != null) { - - StructrApp.getInstance(sourceNode.getSecurityContext()).create(sourceNode, targetNode, relClass); - - } else { - - return "Error: Unknown relationship type"; - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CREATE_RELATIONSHIP; - } - }); - functions.put("grant", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 3)) { - - if (sources[0] instanceof Principal) { - - final Principal principal = (Principal) sources[0]; - - if (sources[1] instanceof AbstractNode) { - - final AbstractNode node = (AbstractNode) sources[1]; - - if (sources[2] instanceof String) { - - final String[] parts = ((String) sources[2]).split("[,]+"); - for (final String part : parts) { - - final String trimmedPart = part.trim(); - if (trimmedPart.length() > 0) { - - try { - - final Permission permission = Permission.valueOf(trimmedPart); - principal.grant(permission, node); - - } catch (IllegalArgumentException iex) { - - return "Error: unknown permission " + trimmedPart; - } - } - } - - return ""; - - } else { - - return "Error: third argument is not a string."; - } - - } else { - - return "Error: second argument is not a node."; - } - - } else { - - return "Error: first argument is not of type Principal."; - } - - } else { - - return ERROR_MESSAGE_GRANT; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_GRANT; - } - }); - functions.put("revoke", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 3)) { - - if (sources[0] instanceof Principal) { - - final Principal principal = (Principal) sources[0]; - - if (sources[1] instanceof AbstractNode) { - - final AbstractNode node = (AbstractNode) sources[1]; - - if (sources[2] instanceof String) { - - final String[] parts = ((String) sources[2]).split("[,]+"); - for (final String part : parts) { - - final String trimmedPart = part.trim(); - if (trimmedPart.length() > 0) { - - try { - - final Permission permission = Permission.valueOf(trimmedPart); - principal.revoke(permission, node); - - } catch (IllegalArgumentException iex) { - - return "Error: unknown permission " + trimmedPart; - } - } - } - - return ""; - - } else { - - return "Error: third argument is not a string."; - } - - } else { - - return "Error: second argument is not a node."; - } - - } else { - - return "Error: first argument is not of type Principal."; - } - - } else { - - return ERROR_MESSAGE_REVOKE; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_REVOKE; - } - }); - } - - /** - * Test if the given object array has a minimum length and all its - * elements are not null. - * - * @param array - * @param minLength If null, don't do length check - * @return true if array has min length and all elements are not null - */ - public static boolean arrayHasMinLengthAndAllElementsNotNull(final Object[] array, final Integer minLength) { - - if (array == null) { - return false; - } - - for (final Object element : array) { - - if (element == null) { - return false; - } - - } - - return minLength != null ? array.length >= minLength : true; - - } - - /** - * Test if the given object array has exact the given length and all its - * elements are not null. - * - * @param array - * @param length If null, don't do length check - * @return true if array has exact length and all elements are not null - */ - public static boolean arrayHasLengthAndAllElementsNotNull(final Object[] array, final Integer length) { - - if (array == null) { - return false; - } - - for (final Object element : array) { - - if (element == null) { - return false; - } - - } - - return length != null ? array.length == length : true; - - } - - protected static String serialize(final Gson gson, final Map map) { - return gson.toJson(map, new TypeToken>() { - }.getType()); - } - - protected static Map deserialize(final Gson gson, final String source) { - return gson.fromJson(source, new TypeToken>() { - }.getType()); - } - - protected static Integer parseInt(final Object source) { - - if (source instanceof Integer) { - - return ((Integer) source); - } - - if (source instanceof Number) { - - return ((Number) source).intValue(); - } - - if (source instanceof String) { - - return Integer.parseInt((String) source); - } - - return null; - } - - protected static String encodeURL(final String source) { - - try { - return URLEncoder.encode(source, "UTF-8"); - - } catch (UnsupportedEncodingException ex) { - - logger.log(Level.WARNING, "Unsupported Encoding", ex); - } - - // fallback, unencoded - return source; - } - - protected static double getDoubleForComparison(final Object obj) { - - if (obj instanceof Date) { - - return ((Date) obj).getTime(); - - } else if (obj instanceof Number) { - - return ((Number) obj).doubleValue(); - - } else { - - try { - return Double.valueOf(obj.toString()); - - } catch (Throwable t) { - - t.printStackTrace(); - } - } - - return 0.0; - } - - protected static Double getDoubleOrNull(final Object obj) { - - if (obj instanceof Date) { - - return Double.valueOf(((Date) obj).getTime()); - - } else if (obj instanceof Number) { - - return ((Number) obj).doubleValue(); - - } else { - - try { - return Double.valueOf(obj.toString()); - - } catch (Throwable t) { - - t.printStackTrace(); - } - } - - return null; - } - - protected static boolean valueEquals(final Object obj1, final Object obj2) { - - if (obj1 instanceof Enum || obj2 instanceof Enum) { - - return obj1.toString().equals(obj2.toString()); - - } - - if (obj1 instanceof Number && obj2 instanceof Number) { - - return ((Number) obj1).doubleValue() == ((Number) obj2).doubleValue(); - } - - return obj1.equals(obj2); - } - - protected static String getSandboxFileName(final String source) throws IOException { - - final File sandboxFile = new File(source); - final String fileName = sandboxFile.getName(); - final String basePath = StructrApp.getConfigurationValue(Services.BASE_PATH); - - if (!basePath.isEmpty()) { - - final String defaultExchangePath = basePath.endsWith("/") ? basePath.concat("exchange") : basePath.concat("/exchange"); - String exchangeDir = StructrApp.getConfigurationValue(Services.DATA_EXCHANGE_PATH, defaultExchangePath); - - if (!exchangeDir.endsWith("/")) { - exchangeDir = exchangeDir.concat("/"); - } - - // create exchange directory - final File dir = new File(exchangeDir); - if (!dir.exists()) { - - dir.mkdirs(); - } - - // return sandboxed file name - return exchangeDir.concat(fileName); - - } else { - - logger.log(Level.WARNING, "Unable to determine base.path from structr.conf, no data input/output possible."); - } - - return null; - } - - public static String cleanString(final Object input) { - - if (input == null) { - - return ""; - - } - - String normalized = Normalizer.normalize(input.toString(), Normalizer.Form.NFD) - .replaceAll("\\<", "") - .replaceAll("\\>", "") - .replaceAll("\\.", "") - .replaceAll("\\'", "-") - .replaceAll("\\?", "") - .replaceAll("\\(", "") - .replaceAll("\\)", "") - .replaceAll("\\{", "") - .replaceAll("\\}", "") - .replaceAll("\\[", "") - .replaceAll("\\]", "") - .replaceAll("\\+", "-") - .replaceAll("/", "-") - .replaceAll("–", "-") - .replaceAll("\\\\", "-") - .replaceAll("\\|", "-") - .replaceAll("'", "-") - .replaceAll("!", "") - .replaceAll(",", "") - .replaceAll("-", " ") - .replaceAll("_", " ") - .replaceAll("`", "-"); - - String result = normalized.replaceAll("-", " "); - result = StringUtils.normalizeSpace(result.toLowerCase()); - result = result.replaceAll("[^\\p{ASCII}]", "").replaceAll("\\p{P}", "-").replaceAll("\\-(\\s+\\-)+", "-"); - result = result.replaceAll(" ", "-"); - - return result; - - } - - public static void recursivelyConvertMapToGraphObjectMap(final GraphObjectMap destination, final Map source, final int depth) { - - if (depth > 20) { - return; - } - - for (final Map.Entry entry : source.entrySet()) { - - final String key = entry.getKey(); - final Object value = entry.getValue(); - - if (value instanceof Map) { - - final Map map = (Map) value; - final GraphObjectMap obj = new GraphObjectMap(); - - destination.put(new StringProperty(key), obj); - - recursivelyConvertMapToGraphObjectMap(obj, map, depth+1); - - } else if (value instanceof Collection) { - - final List list = new LinkedList(); - final Collection collection = (Collection)value; - - for (final Object obj : collection) { - - if (obj instanceof Map) { - - final GraphObjectMap container = new GraphObjectMap(); - list.add(container); - - recursivelyConvertMapToGraphObjectMap(container, (Map)obj, depth+1); - - } else { - - list.add(obj); - } - } - - destination.put(new StringProperty(key), list); - - } else { - - destination.put(new StringProperty(key), value); - } - } - } - - public static Object numberOrString(final String value) { - - if (value != null) { - - if ("true".equals(value.toLowerCase())) { - return true; - } - - if ("false".equals(value.toLowerCase())) { - return false; - } - - if (NumberUtils.isNumber(value)) { - return NumberUtils.createNumber(value); - } - } - - return value; - } -} diff --git a/All/Genesis-NP/Genesis#155/old/Functions.java b/All/Genesis-NP/Genesis#155/old/Functions.java deleted file mode 100755 index b5f4e9d..0000000 --- a/All/Genesis-NP/Genesis#155/old/Functions.java +++ /dev/null @@ -1,3904 +0,0 @@ -/** - * Copyright (C) 2010-2014 Morgner UG (haftungsbeschränkt) - * - * This file is part of Structr . - * - * Structr is free software: you can redistribute it and/or modify it under the - * terms of the GNU General Public License as published by the Free Software - * Foundation, either version 3 of the License, or (at your option) any later - * version. - * - * Structr is distributed in the hope that it will be useful, but WITHOUT ANY - * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR - * A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * Structr. If not, see . - */ -package org.structr.core.parser; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonPrimitive; -import com.google.gson.reflect.TypeToken; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStreamWriter; -import java.io.StreamTokenizer; -import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.io.Writer; -import java.net.URLEncoder; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.text.Normalizer; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Date; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Random; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.parsers.ParserConfigurationException; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; -import org.apache.commons.codec.digest.DigestUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.RandomStringUtils; -import org.apache.commons.lang3.StringEscapeUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.math.NumberUtils; -import org.apache.commons.mail.EmailException; -import org.neo4j.graphdb.Direction; -import org.neo4j.graphdb.DynamicRelationshipType; -import org.structr.common.GraphObjectComparator; -import org.structr.common.MailHelper; -import org.structr.common.Permission; -import org.structr.common.SecurityContext; -import org.structr.common.error.ErrorToken; -import org.structr.common.error.FrameworkException; -import org.structr.common.error.SemanticErrorToken; -import org.structr.common.geo.GeoCodingResult; -import org.structr.common.geo.GeoHelper; -import org.structr.core.GraphObject; -import org.structr.core.GraphObjectMap; -import org.structr.core.Services; -import org.structr.core.app.App; -import org.structr.core.app.Query; -import org.structr.core.app.StructrApp; -import org.structr.core.converter.PropertyConverter; -import org.structr.core.entity.AbstractNode; -import org.structr.core.entity.AbstractRelationship; -import org.structr.core.entity.MailTemplate; -import org.structr.core.entity.Principal; -import org.structr.core.graph.NodeInterface; -import org.structr.core.graph.RelationshipFactory; -import org.structr.core.graph.RelationshipInterface; -import org.structr.core.property.ISO8601DateProperty; -import org.structr.core.property.PropertyKey; -import org.structr.core.property.PropertyMap; -import org.structr.core.property.StringProperty; -import org.structr.core.script.Scripting; -import org.structr.schema.ConfigurationProvider; -import org.structr.schema.action.ActionContext; -import org.structr.schema.action.Function; -import org.w3c.dom.Document; -import org.xml.sax.InputSource; -import org.xml.sax.SAXException; - -/** - * - * @author Christian Morgner - */ -public class Functions { - - private static final Logger logger = Logger.getLogger(Functions.class.getName()); - public static final Map> functions = new LinkedHashMap<>(); - - public static final String NULL_STRING = "___NULL___"; - - public static final String ERROR_MESSAGE_MD5 = "Usage: ${md5(string)}. Example: ${md5(this.email)}"; - public static final String ERROR_MESSAGE_ERROR = "Usage: ${error(...)}. Example: ${error(\"base\", \"must_equal\", int(5))}"; - public static final String ERROR_MESSAGE_UPPER = "Usage: ${upper(string)}. Example: ${upper(this.nickName)}"; - public static final String ERROR_MESSAGE_LOWER = "Usage: ${lower(string)}. Example: ${lower(this.email)}"; - public static final String ERROR_MESSAGE_JOIN = "Usage: ${join(collection, separator)}. Example: ${join(this.names, \",\")}"; - public static final String ERROR_MESSAGE_CONCAT = "Usage: ${concat(values...)}. Example: ${concat(this.firstName, this.lastName)}"; - public static final String ERROR_MESSAGE_SPLIT = "Usage: ${split(value)}. Example: ${split(this.commaSeparatedItems)}"; - public static final String ERROR_MESSAGE_ABBR = "Usage: ${abbr(longString, maxLength)}. Example: ${abbr(this.title, 20)}"; - public static final String ERROR_MESSAGE_CAPITALIZE = "Usage: ${capitalize(string)}. Example: ${capitalize(this.nickName)}"; - public static final String ERROR_MESSAGE_TITLEIZE = "Usage: ${titleize(string, separator}. Example: ${titleize(this.lowerCamelCaseString, \"_\")}"; - public static final String ERROR_MESSAGE_NUM = "Usage: ${num(string)}. Example: ${num(this.numericalStringValue)}"; - public static final String ERROR_MESSAGE_INT = "Usage: ${to_int(string)}. Example: ${int(this.numericalStringValue)}"; - public static final String ERROR_MESSAGE_RANDOM = "Usage: ${random(num)}. Example: ${set(this, \"password\", random(8))}"; - public static final String ERROR_MESSAGE_RINT = "Usage: ${rint(range)}. Example: ${rint(1000)}"; - public static final String ERROR_MESSAGE_INDEX_OF = "Usage: ${index_of(string, word)}. Example: ${index_of(this.name, \"the\")}"; - public static final String ERROR_MESSAGE_CONTAINS = "Usage: ${contains(string, word)}. Example: ${contains(this.name, \"the\")}"; - public static final String ERROR_MESSAGE_SUBSTRING = "Usage: ${substring(string, start, length)}. Example: ${substring(this.name, 19, 3)}"; - public static final String ERROR_MESSAGE_LENGTH = "Usage: ${length(string)}. Example: ${length(this.name)}"; - public static final String ERROR_MESSAGE_REPLACE = "Usage: ${replace(template, source)}. Example: ${replace(\"${this.id}\", this)}"; - public static final String ERROR_MESSAGE_CLEAN = "Usage: ${clean(string)}. Example: ${clean(this.stringWithNonWordChars)}"; - public static final String ERROR_MESSAGE_URLENCODE = "Usage: ${urlencode(string)}. Example: ${urlencode(this.email)}"; - public static final String ERROR_MESSAGE_ESCAPE_JS = "Usage: ${escape_javascript(string)}. Example: ${escape_javascript(this.name)}"; - public static final String ERROR_MESSAGE_IF = "Usage: ${if(condition, trueValue, falseValue)}. Example: ${if(empty(this.name), this.nickName, this.name)}"; - public static final String ERROR_MESSAGE_EMPTY = "Usage: ${empty(string)}. Example: ${if(empty(possibleEmptyString), \"empty\", \"non-empty\")}"; - public static final String ERROR_MESSAGE_EQUAL = "Usage: ${equal(value1, value2)}. Example: ${equal(this.children.size, 0)}"; - public static final String ERROR_MESSAGE_ADD = "Usage: ${add(values...)}. Example: ${add(1, 2, 3, this.children.size)}"; - public static final String ERROR_MESSAGE_INT_SUM = "Usage: ${int_sum(list)}. Example: ${int_sum(extract(this.children, \"number\"))}"; - public static final String ERROR_MESSAGE_DOUBLE_SUM = "Usage: ${double_sum(list)}. Example: ${double_sum(extract(this.children, \"amount\"))}"; - public static final String ERROR_MESSAGE_IS_COLLECTION = "Usage: ${is_collection(value)}. Example: ${is_collection(this)}"; - public static final String ERROR_MESSAGE_IS_ENTITY = "Usage: ${is_entity(value)}. Example: ${is_entity(this)}"; - public static final String ERROR_MESSAGE_EXTRACT = "Usage: ${extract(list, propertyName)}. Example: ${extract(this.children, \"amount\")}"; - public static final String ERROR_MESSAGE_FILTER = "Usage: ${filter(list, expression)}. Example: ${filter(this.children, gt(size(data.children), 0))}"; - public static final String ERROR_MESSAGE_MERGE = "Usage: ${merge(list1, list2, list3, ...)}. Example: ${merge(this.children, this.siblings)}"; - public static final String ERROR_MESSAGE_COMPLEMENT = "Usage: ${complement(list1, list2, list3, ...)}. (The resulting list contains no duplicates) Example: ${merge(allUsers, me)} => List of all users except myself"; - public static final String ERROR_MESSAGE_UNWIND = "Usage: ${unwind(list1, ...)}. Example: ${unwind(this.children)}"; - public static final String ERROR_MESSAGE_SORT = "Usage: ${sort(list1, key [, true])}. Example: ${sort(this.children, \"name\")}"; - public static final String ERROR_MESSAGE_LT = "Usage: ${lt(value1, value2)}. Example: ${if(lt(this.children, 2), \"Less than two\", \"Equal to or more than two\")}"; - public static final String ERROR_MESSAGE_GT = "Usage: ${gt(value1, value2)}. Example: ${if(gt(this.children, 2), \"More than two\", \"Equal to or less than two\")}"; - public static final String ERROR_MESSAGE_LTE = "Usage: ${lte(value1, value2)}. Example: ${if(lte(this.children, 2), \"Equal to or less than two\", \"More than two\")}"; - public static final String ERROR_MESSAGE_GTE = "Usage: ${gte(value1, value2)}. Example: ${if(gte(this.children, 2), \"Equal to or more than two\", \"Less than two\")}"; - public static final String ERROR_MESSAGE_SUBT = "Usage: ${subt(value1, value)}. Example: ${subt(5, 2)}"; - public static final String ERROR_MESSAGE_MULT = "Usage: ${mult(value1, value)}. Example: ${mult(5, 2)}"; - public static final String ERROR_MESSAGE_QUOT = "Usage: ${quot(value1, value)}. Example: ${quot(5, 2)}"; - public static final String ERROR_MESSAGE_ROUND = "Usage: ${round(value1 [, decimalPlaces])}. Example: ${round(2.345678, 2)}"; - public static final String ERROR_MESSAGE_MAX = "Usage: ${max(value1, value2)}. Example: ${max(this.children, 10)}"; - public static final String ERROR_MESSAGE_MIN = "Usage: ${min(value1, value2)}. Example: ${min(this.children, 5)}"; - public static final String ERROR_MESSAGE_CONFIG = "Usage: ${config(keyFromStructrConf)}. Example: ${config(\"base.path\")}"; - public static final String ERROR_MESSAGE_DATE_FORMAT = "Usage: ${date_format(value, pattern)}. Example: ${date_format(this.creationDate, \"yyyy-MM-dd'T'HH:mm:ssZ\")}"; - public static final String ERROR_MESSAGE_PARSE_DATE = "Usage: ${parse_date(value, pattern)}. Example: ${parse_format(\"2014-01-01\", \"yyyy-MM-dd\")}"; - public static final String ERROR_MESSAGE_NUMBER_FORMAT = "Usage: ${number_format(value, ISO639LangCode, pattern)}. Example: ${number_format(12345.6789, 'en', '#,##0.00')}"; - public static final String ERROR_MESSAGE_TEMPLATE = "Usage: ${template(name, locale, source)}. Example: ${template(\"TEXT_TEMPLATE_1\", \"en_EN\", this)}"; - public static final String ERROR_MESSAGE_NOT = "Usage: ${not(bool1, bool2)}. Example: ${not(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_AND = "Usage: ${and(bool1, bool2)}. Example: ${and(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_OR = "Usage: ${or(bool1, bool2)}. Example: ${or(\"true\", \"true\")}"; - public static final String ERROR_MESSAGE_GET = "Usage: ${get(entity, propertyKey)}. Example: ${get(this, \"children\")}"; - public static final String ERROR_MESSAGE_GET_ENTITY = "Cannot evaluate first argument to entity, must be entity or single element list of entities."; - public static final String ERROR_MESSAGE_SIZE = "Usage: ${size(collection)}. Example: ${size(this.children)}"; - public static final String ERROR_MESSAGE_FIRST = "Usage: ${first(collection)}. Example: ${first(this.children)}"; - public static final String ERROR_MESSAGE_LAST = "Usage: ${last(collection)}. Example: ${last(this.children)}"; - public static final String ERROR_MESSAGE_NTH = "Usage: ${nth(collection)}. Example: ${nth(this.children, 2)}"; - public static final String ERROR_MESSAGE_GET_COUNTER = "Usage: ${get_counter(level)}. Example: ${get_counter(1)}"; - public static final String ERROR_MESSAGE_INC_COUNTER = "Usage: ${inc_counter(level, [resetLowerLevels])}. Example: ${inc_counter(1, true)}"; - public static final String ERROR_MESSAGE_RESET_COUNTER = "Usage: ${reset_counter(level)}. Example: ${reset_counter(1)}"; - public static final String ERROR_MESSAGE_MERGE_PROPERTIES = "Usage: ${merge_properties(source, target , mergeKeys...)}. Example: ${merge_properties(this, parent, \"eMail\")}"; - public static final String ERROR_MESSAGE_KEYS = "Usage: ${keys(entity, viewName)}. Example: ${keys(this, \"ui\")}"; - public static final String ERROR_MESSAGE_EACH = "Usage: ${each(collection, expression)}. Example: ${each(this.children, \"set(this, \"email\", lower(get(this.email))))\")}"; - public static final String ERROR_MESSAGE_STORE = "Usage: ${store(key, value)}. Example: ${store('tmpUser', this.owner)}"; - public static final String ERROR_MESSAGE_RETRIEVE = "Usage: ${retrieve(key)}. Example: ${retrieve('tmpUser')}"; - public static final String ERROR_MESSAGE_PRINT = "Usage: ${print(objects...)}. Example: ${print(this.name, \"test\")}"; - public static final String ERROR_MESSAGE_READ = "Usage: ${read(filename)}. Example: ${read(\"text.xml\")}"; - public static final String ERROR_MESSAGE_WRITE = "Usage: ${write(filename, value)}. Example: ${write(\"text.txt\", this.name)}"; - public static final String ERROR_MESSAGE_APPEND = "Usage: ${append(filename, value)}. Example: ${append(\"test.txt\", this.name)}"; - public static final String ERROR_MESSAGE_XML = "Usage: ${xml(xmlSource)}. Example: ${xpath(xml(this.xmlSource), \"/test/testValue\")}"; - public static final String ERROR_MESSAGE_XPATH = "Usage: ${xpath(xmlDocument, expression)}. Example: ${xpath(xml(this.xmlSource), \"/test/testValue\")}"; - public static final String ERROR_MESSAGE_SET = "Usage: ${set(entity, propertyKey, value)}. Example: ${set(this, \"email\", lower(this.email))}"; - public static final String ERROR_MESSAGE_SEND_PLAINTEXT_MAIL = "Usage: ${send_plaintext_mail(fromAddress, fromName, toAddress, toName, subject, content)}."; - public static final String ERROR_MESSAGE_SEND_HTML_MAIL = "Usage: ${send_html_mail(fromAddress, fromName, toAddress, toName, subject, content)}."; - public static final String ERROR_MESSAGE_GEOCODE = "Usage: ${geocode(street, city, country)}. Example: ${set(this, geocode(this.street, this.city, this.country))}"; - public static final String ERROR_MESSAGE_FIND = "Usage: ${find(type, key, value)}. Example: ${find(\"User\", \"email\", \"tester@test.com\"}"; - public static final String ERROR_MESSAGE_SEARCH = "Usage: ${search(type, key, value)}. Example: ${search(\"User\", \"name\", \"abc\"}"; - public static final String ERROR_MESSAGE_CREATE = "Usage: ${create(type, key, value)}. Example: ${create(\"Feedback\", \"text\", this.text)}"; - public static final String ERROR_MESSAGE_DELETE = "Usage: ${delete(entity)}. Example: ${delete(this)}"; - public static final String ERROR_MESSAGE_CACHE = "Usage: ${cache(key, timeout, valueExpression)}. Example: ${cache('value', 60, GET('http://rate-limited-URL.com'))}"; - public static final String ERROR_MESSAGE_GRANT = "Usage: ${grant(principal, node, permissions)}. Example: ${grant(me, this, 'read, write, delete'))}"; - public static final String ERROR_MESSAGE_REVOKE = "Usage: ${revoke(principal, node, permissions)}. Example: ${revoke(me, this, 'write, delete'))}"; - - // Special functions for relationships - public static final String ERROR_MESSAGE_INCOMING = "Usage: ${incoming(entity [, relType])}. Example: ${incoming(this, 'PARENT_OF')}"; - public static final String ERROR_MESSAGE_OUTGOING = "Usage: ${outgoing(entity [, relType])}. Example: ${outgoing(this, 'PARENT_OF')}"; - public static final String ERROR_MESSAGE_HAS_RELATIONSHIP = "Usage: ${has_relationship(entity1, entity2 [, relType])}. Example: ${has_relationship(me, user, 'FOLLOWS')} (ignores direction of the relationship)"; - public static final String ERROR_MESSAGE_HAS_OUTGOING_RELATIONSHIP = "Usage: ${has_outgoing_relationship(from, to [, relType])}. Example: ${has_outgoing_relationship(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_HAS_INCOMING_RELATIONSHIP = "Usage: ${has_incoming_relationship(from, to [, relType])}. Example: ${has_incoming_relationship(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_GET_RELATIONSHIPS = "Usage: ${get_relationships(entity1, entity2 [, relType])}. Example: ${get_relationships(me, user, 'FOLLOWS')} (ignores direction of the relationship)"; - public static final String ERROR_MESSAGE_GET_OUTGOING_RELATIONSHIPS = "Usage: ${get_outgoing_relationships(from, to [, relType])}. Example: ${get_outgoing_relationships(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_GET_INCOMING_RELATIONSHIPS = "Usage: ${get_incoming_relationships(from, to [, relType])}. Example: ${get_incoming_relationships(me, user, 'FOLLOWS')}"; - public static final String ERROR_MESSAGE_CREATE_RELATIONSHIP = "Usage: ${create_relationship(from, to, relType)}. Example: ${create_relationship(me, user, 'FOLLOWS')} (Relationshiptype has to exist)"; - - public static Function get(final String name) { - return functions.get(name); - } - - public static Object evaluate(final SecurityContext securityContext, final ActionContext actionContext, final GraphObject entity, final String expression) throws FrameworkException { - - final String expressionWithoutNewlines = expression.replace('\n', ' '); - final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(expressionWithoutNewlines)); - tokenizer.eolIsSignificant(true); - tokenizer.ordinaryChar('.'); - tokenizer.wordChars('_', '_'); - tokenizer.wordChars('.', '.'); - tokenizer.wordChars('!', '!'); - - Expression root = new RootExpression(); - Expression current = root; - Expression next = null; - String lastToken = null; - int token = 0; - int level = 0; - - while (token != StreamTokenizer.TT_EOF) { - - token = nextToken(tokenizer); - - switch (token) { - - case StreamTokenizer.TT_EOF: - break; - - case StreamTokenizer.TT_EOL: - break; - - case StreamTokenizer.TT_NUMBER: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before NUMBER"); - } - next = new ConstantExpression(tokenizer.nval); - current.add(next); - lastToken += "NUMBER"; - break; - - case StreamTokenizer.TT_WORD: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval); - } - next = checkReservedWords(tokenizer.sval); - current.add(next); - lastToken = tokenizer.sval; - break; - - case '(': - if (((current == null || current instanceof RootExpression) && next == null) || current == next) { - - // an additional bracket without a new function, - // this can only be an execution group. - next = new GroupExpression(); - current.add(next); - } - - current = next; - lastToken += "("; - level++; - break; - - case ')': - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + lastToken); - } - current = current.getParent(); - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - lastToken += ")"; - level--; - break; - - case '[': - // bind directly to the previous expression - next = new ArrayExpression(); - current.add(next); - current = next; - lastToken += "["; - level++; - break; - - case ']': - - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket before " + lastToken); - } - current = current.getParent(); - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - lastToken += "]"; - level--; - break; - - case ';': - next = null; - lastToken += ";"; - break; - - case ',': - next = current; - lastToken += ","; - break; - - default: - if (current == null) { - throw new FrameworkException(422, "Invalid expression: mismatched opening bracket before " + tokenizer.sval); - } - current.add(new ConstantExpression(tokenizer.sval)); - lastToken = tokenizer.sval; - - } - } - - if (level > 0) { - throw new FrameworkException(422, "Invalid expression: mismatched closing bracket after " + lastToken); - } - - return root.evaluate(securityContext, actionContext, entity); - } - - private static Expression checkReservedWords(final String word) throws FrameworkException { - - if (word == null) { - return new NullExpression(); - } - - switch (word) { - - case "cache": - return new CacheExpression(); - - case "true": - return new ConstantExpression(true); - - case "false": - return new ConstantExpression(false); - - case "if": - return new IfExpression(); - - case "each": - return new EachExpression(); - - case "filter": - return new FilterExpression(); - - case "data": - return new ValueExpression("data"); - - case "null": - return new ConstantExpression(NULL_STRING); - } - - // no match, try functions - final Function function = Functions.get(word); - if (function != null) { - - return new FunctionExpression(word, function); - - } else { - - return new ValueExpression(word); - } - } - - public static int nextToken(final StreamTokenizer tokenizer) { - - try { - - return tokenizer.nextToken(); - - } catch (IOException ioex) { - } - - return StreamTokenizer.TT_EOF; - } - - static { - - functions.put("error", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entity.getClass(), sources[0].toString()); - ctx.raiseError(entity.getType(), new ErrorToken(422, key) { - - @Override - public JsonElement getContent() { - return new JsonPrimitive(getErrorToken()); - } - - @Override - public String getErrorToken() { - return sources[1].toString(); - } - }); - - } else if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(entity.getClass(), sources[0].toString()); - ctx.raiseError(entity.getType(), new SemanticErrorToken(key) { - - @Override - public JsonElement getContent() { - - JsonObject obj = new JsonObject(); - - if (sources[2] instanceof Number) { - - obj.add(getErrorToken(), new JsonPrimitive((Number) sources[2])); - - } else if (sources[2] instanceof Boolean) { - - obj.add(getErrorToken(), new JsonPrimitive((Boolean) sources[2])); - - } else { - - obj.add(getErrorToken(), new JsonPrimitive(sources[2].toString())); - } - - return obj; - } - - @Override - public String getErrorToken() { - return sources[1].toString(); - } - }); - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_ERROR; - } - }); - functions.put("md5", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? DigestUtils.md5Hex(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MD5; - } - }); - functions.put("upper", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? sources[0].toString().toUpperCase() - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_UPPER; - } - - }); - functions.put("lower", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? sources[0].toString().toLowerCase() - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LOWER; - } - - }); - functions.put("join", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof Collection) { - - return StringUtils.join((Collection) sources[0], sources[1].toString()); - } - - if (sources[0].getClass().isArray()) { - - return StringUtils.join((Object[]) sources[0], sources[1].toString()); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_JOIN; - } - - }); - functions.put("concat", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - // collection can contain nulls.. - if (source != null) { - - if (source instanceof Collection) { - - list.addAll((Collection) source); - - } else if (source.getClass().isArray()) { - - list.addAll(Arrays.asList((Object[])source)); - - } else { - - list.add(source); - } - } - } - - return StringUtils.join(list, ""); - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONCAT; - } - - }); - functions.put("split", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final String toSplit = sources[0].toString(); - String splitExpr = "[,;]+"; - - if (sources.length >= 2) { - splitExpr = sources[1].toString(); - } - - return Arrays.asList(toSplit.split(splitExpr)); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SPLIT; - } - - }); - functions.put("abbr", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - try { - int maxLength = Double.valueOf(sources[1].toString()).intValue(); - - if (sources[0].toString().length() > maxLength) { - - return StringUtils.substringBeforeLast(StringUtils.substring(sources[0].toString(), 0, maxLength), " ").concat("…"); - - } else { - - return sources[0]; - } - - } catch (NumberFormatException nfe) { - - return nfe.getMessage(); - - } - - } - - return ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ABBR; - } - - }); - functions.put("capitalize", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? StringUtils.capitalize(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_CAPITALIZE; - } - }); - functions.put("titleize", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources.length < 2 || sources[0] == null) { - return null; - } - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - if (sources[1] == null) { - sources[1] = " "; - } - - String[] in = StringUtils.split(sources[0].toString(), sources[1].toString()); - String[] out = new String[in.length]; - for (int i = 0; i < in.length; i++) { - out[i] = StringUtils.capitalize(in[i]); - } - return StringUtils.join(out, " "); - - } - - @Override - public String usage() { - return ERROR_MESSAGE_TITLEIZE; - } - - }); - functions.put("num", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - return getDoubleOrNull(sources[0]); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NUM; - } - }); - functions.put("to_int", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Number) { - return ((Number) sources[0]).intValue(); - } - - try { - return getDoubleOrNull(sources[0]).intValue(); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INT; - } - }); - functions.put("random", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof Number) { - - try { - return RandomStringUtils.randomAlphanumeric(((Number) sources[0]).intValue()); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RANDOM; - } - }); - functions.put("rint", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof Number) { - - try { - return new Random(System.currentTimeMillis()).nextInt(((Number) sources[0]).intValue()); - - } catch (Throwable t) { - // ignore - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RINT; - } - }); - functions.put("index_of", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final String source = sources[0].toString(); - final String part = sources[1].toString(); - - return source.indexOf(part); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INDEX_OF; - } - }); - functions.put("contains", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof String && sources[1] instanceof String) { - - final String source = sources[0].toString(); - final String part = sources[1].toString(); - - return source.contains(part); - - } else if (sources[0] instanceof Collection && sources[1] instanceof GraphObject) { - - final Collection collection = (Collection) sources[0]; - final GraphObject obj = (GraphObject) sources[1]; - - return collection.contains(obj); - - } else if (sources[0].getClass().isArray()) { - - return ArrayUtils.contains((Object[])sources[0], sources[1]); - } - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONTAINS; - } - }); - functions.put("substring", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final String source = sources[0].toString(); - final int sourceLength = source.length(); - final int start = parseInt(sources[1]); - final int length = sources.length >= 3 ? parseInt(sources[2]) : sourceLength - start; - final int end = start + length; - - if (start >= 0 && start < sourceLength && end >= 0 && end <= sourceLength && start <= end) { - - return source.substring(start, end); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBSTRING; - } - }); - functions.put("length", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - return sources[0].toString().length(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBSTRING; - } - }); - functions.put("replace", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final String template = sources[0].toString(); - AbstractNode node = null; - - if (sources[1] instanceof AbstractNode) { - node = (AbstractNode) sources[1]; - } - - if (sources[1] instanceof List) { - - final List list = (List) sources[1]; - if (list.size() == 1 && list.get(0) instanceof AbstractNode) { - - node = (AbstractNode) list.get(0); - } - } - - if (node != null) { - - // recursive replacement call, be careful here - return Scripting.replaceVariables(entity.getSecurityContext(), node, ctx, template); - } - - return ""; - } - - return usage(); - - } - - @Override - public String usage() { - return ERROR_MESSAGE_REPLACE; - } - }); - functions.put("clean", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - return cleanString(sources[0]); - } - - return null; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_CLEAN; - } - - }); - functions.put("urlencode", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? encodeURL(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_URLENCODE; - } - - }); - functions.put("escape_javascript", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) - ? StringEscapeUtils.escapeEcmaScript(sources[0].toString()) - : ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ESCAPE_JS; - } - - }); - functions.put("if", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources[0] == null || sources.length < 3) { - - return ""; - } - - if ("true".equals(sources[0]) || Boolean.TRUE.equals(sources[0])) { - - return sources[1]; - - } else { - - return sources[2]; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IF; - } - - }); - functions.put("empty", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources.length == 0 || sources[0] == null || StringUtils.isEmpty(sources[0].toString())) { - - return true; - - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_EMPTY; - } - - }); - functions.put("equal", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - logger.log(Level.FINE, "Length: {0}", sources.length); - - if (sources.length < 2) { - - return true; - } - - logger.log(Level.FINE, "Comparing {0} to {1}", new java.lang.Object[]{sources[0], sources[1]}); - - if (sources[0] == null && sources[1] == null) { - return true; - } - - if (sources[0] == null || sources[1] == null) { - return false; - } - - return valueEquals(sources[0], sources[1]); - } - - @Override - public String usage() { - return ERROR_MESSAGE_EQUAL; - } - - }); - functions.put("eq", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - return functions.get("equal").apply(ctx, entity, sources); - } - - @Override - public String usage() { - - return functions.get("equal").usage(); - } - - }); - functions.put("add", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Double result = 0.0; - - if (sources != null) { - - for (Object i : sources) { - - if (i != null) { - - try { - - result += Double.parseDouble(i.toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - result += 0.0; - } - } - - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_ADD; - } - - }); - functions.put("double_sum", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - double result = 0.0; - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Collection) { - - for (final Number num : (Collection) sources[0]) { - - result += num.doubleValue(); - } - } - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_DOUBLE_SUM; - } - - }); - functions.put("int_sum", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - int result = 0; - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof Collection) { - - for (final Number num : (Collection) sources[0]) { - - result += num.intValue(); - } - } - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_INT_SUM; - } - - }); - functions.put("is_collection", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - return (sources[0] instanceof Collection); - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IS_COLLECTION; - } - - }); - functions.put("is_entity", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - return (sources[0] instanceof GraphObject); - } else { - return false; - } - - } - - @Override - public String usage() { - return ERROR_MESSAGE_IS_ENTITY; - } - - }); - functions.put("extract", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - // no property key given, maybe we should extract a list of lists? - if (sources[0] instanceof Collection) { - - final List extraction = new LinkedList(); - - for (final Object obj : (Collection) sources[0]) { - - if (obj instanceof Collection) { - - extraction.addAll((Collection) obj); - } - } - - return extraction; - } - - } else if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof Collection && sources[1] instanceof String) { - - final ConfigurationProvider config = StructrApp.getConfiguration(); - final List extraction = new LinkedList(); - final String keyName = (String) sources[1]; - - for (final Object obj : (Collection) sources[0]) { - - if (obj instanceof GraphObject) { - - final PropertyKey key = config.getPropertyKeyForJSONName(obj.getClass(), keyName); - final Object value = ((GraphObject) obj).getProperty(key); - if (value != null) { - - extraction.add(value); - } - } - } - - return extraction; - } - } - - return null; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_EXTRACT; - } - - }); - functions.put("merge", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - - if (obj != null) { - - list.add(obj); - } - } - - } else if (source != null) { - - list.add(source); - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE; - } - - }); - functions.put("complement", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final Set sourceSet = new HashSet(); - - if (sources[0] instanceof Collection) { - - sourceSet.addAll((Collection)sources[0]); - - for (int cnt = 1; cnt < sources.length; cnt++) { - - final Object source = sources[cnt]; - - if (source instanceof Collection) { - - sourceSet.removeAll((Collection)source); - - } else if (source != null) { - - sourceSet.remove(source); - } - } - - } else { - - return "Argument 1 for complement must be a Collection"; - } - - return sourceSet; - } - - @Override - public String usage() { - return ERROR_MESSAGE_COMPLEMENT; - } - - }); - functions.put("unwind", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - if (obj != null) { - - if (obj instanceof Collection) { - - for (final Object elem : (Collection) obj) { - - if (elem != null) { - - list.add(elem); - } - } - - } else { - - list.add(obj); - } - } - } - - } else if (source != null) { - - list.add(source); - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE; - } - - }); - functions.put("sort", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof List && sources[1] instanceof String) { - - final List list = (List) sources[0]; - final String sortKey = sources[1].toString(); - final Iterator iterator = list.iterator(); - - if (iterator.hasNext()) { - - final Object firstElement = iterator.next(); - if (firstElement instanceof GraphObject) { - - final Class type = firstElement.getClass(); - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(type, sortKey); - final boolean descending = sources.length == 3 && sources[2] != null && "true".equals(sources[2].toString()); - - if (key != null) { - - List sortCollection = (List) list; - Collections.sort(sortCollection, new GraphObjectComparator(key, descending)); - } - } - - } - } - } - - return sources[0]; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SORT; - } - - }); - functions.put("lt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 < value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LT; - } - }); - functions.put("gt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 > value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_GT; - } - }); - functions.put("lte", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 <= value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_LTE; - } - }); - functions.put("gte", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - String result = ""; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - double value1 = getDoubleForComparison(sources[0]); - double value2 = getDoubleForComparison(sources[1]); - - return value1 >= value2; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_GTE; - } - }); - functions.put("subt", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - try { - - Double result = Double.parseDouble(sources[0].toString()); - - for (int i = 1; i < sources.length; i++) { - - result -= Double.parseDouble(sources[i].toString()); - - } - - return result; - - } catch (Throwable t) { - - return t.getMessage(); - - } - } - - return ""; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_SUBT; - } - }); - functions.put("mult", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Double result = 1.0d; - - if (sources != null) { - - for (Object i : sources) { - - try { - - result *= Double.parseDouble(i.toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - } - - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MULT; - } - }); - functions.put("quot", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - - return Double.parseDouble(sources[0].toString()) / Double.parseDouble(sources[1].toString()); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - if (sources != null) { - - if (sources.length > 0 && sources[0] != null) { - return Double.valueOf(sources[0].toString()); - } - - return ""; - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_QUOT; - } - }); - functions.put("round", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - try { - - Double f1 = Double.parseDouble(sources[0].toString()); - double f2 = Math.pow(10, (Double.parseDouble(sources[1].toString()))); - long r = Math.round(f1 * f2); - - return (double) r / f2; - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - return ""; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_ROUND; - } - }); - functions.put("max", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Object result = ""; - String errorMsg = "ERROR! Usage: ${max(val1, val2)}. Example: ${max(5,10)}"; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - result = Math.max(Double.parseDouble(sources[0].toString()), Double.parseDouble(sources[1].toString())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Could not determine max() of {0} and {1}", new Object[]{sources[0], sources[1]}); - result = errorMsg; - } - - } else { - - result = ""; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MAX; - } - }); - functions.put("min", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - Object result = ""; - String errorMsg = "ERROR! Usage: ${min(val1, val2)}. Example: ${min(5,10)}"; - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - try { - result = Math.min(Double.parseDouble(sources[0].toString()), Double.parseDouble(sources[1].toString())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Could not determine min() of {0} and {1}", new Object[]{sources[0], sources[1]}); - result = errorMsg; - } - - } else { - - result = ""; - } - - return result; - - } - - @Override - public String usage() { - return ERROR_MESSAGE_MIN; - } - }); - functions.put("config", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final String configKey = sources[0].toString(); - final String defaultValue = sources.length >= 2 ? sources[1].toString() : ""; - - return StructrApp.getConfigurationValue(configKey, defaultValue); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CONFIG; - } - }); - functions.put("date_format", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 2) { - return ERROR_MESSAGE_DATE_FORMAT; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - Date date = null; - - if (sources[0] instanceof Date) { - - date = (Date) sources[0]; - - } else if (sources[0] instanceof Number) { - - date = new Date(((Number) sources[0]).longValue()); - - } else { - - try { - - // parse with format from IS - date = new SimpleDateFormat(ISO8601DateProperty.PATTERN).parse(sources[0].toString()); - - } catch (ParseException ex) { - ex.printStackTrace(); - } - - } - - // format with given pattern - return new SimpleDateFormat(sources[1].toString()).format(date); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_DATE_FORMAT; - } - }); - functions.put("parse_date", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 2) { - return ERROR_MESSAGE_PARSE_DATE; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - String dateString = sources[0].toString(); - - if (StringUtils.isBlank(dateString)) { - return ""; - } - - String pattern = sources[1].toString(); - - try { - // parse with format from IS - return new SimpleDateFormat(pattern).parse(dateString); - - } catch (ParseException ex) { - logger.log(Level.WARNING, "Could not parse date " + dateString + " and format it to pattern " + pattern, ex); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_PARSE_DATE; - } - }); - functions.put("number_format", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 3) { - return ERROR_MESSAGE_NUMBER_FORMAT; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - if (StringUtils.isBlank(sources[0].toString())) { - return ""; - } - - try { - - Double val = Double.parseDouble(sources[0].toString()); - String langCode = sources[1].toString(); - String pattern = sources[2].toString(); - - return new DecimalFormat(pattern, DecimalFormatSymbols.getInstance(Locale.forLanguageTag(langCode))).format(val); - - } catch (Throwable t) { - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NUMBER_FORMAT; - } - }); - functions.put("template", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources == null || sources != null && sources.length != 3) { - return ERROR_MESSAGE_TEMPLATE; - } - - if (arrayHasLengthAndAllElementsNotNull(sources, 3) && sources[2] instanceof AbstractNode) { - - final App app = StructrApp.getInstance(entity.getSecurityContext()); - final String name = sources[0].toString(); - final String locale = sources[1].toString(); - final MailTemplate template = app.nodeQuery(MailTemplate.class).andName(name).and(MailTemplate.locale, locale).getFirst(); - final AbstractNode templateInstance = (AbstractNode) sources[2]; - - if (template != null) { - - final String text = template.getProperty(MailTemplate.text); - if (text != null) { - - // recursive replacement call, be careful here - return Scripting.replaceVariables(entity.getSecurityContext(), templateInstance, ctx, text); - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_TEMPLATE; - } - }); - functions.put("not", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - return !("true".equals(sources[0].toString()) || Boolean.TRUE.equals(sources[0])); - - } - - return true; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NOT; - } - - }); - functions.put("and", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - boolean result = true; - - if (sources != null) { - - if (sources.length < 2) { - return usage(); - } - - for (Object i : sources) { - - if (i != null) { - - try { - - result &= "true".equals(i.toString()) || Boolean.TRUE.equals(i); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - // null is false - return false; - } - } - - } - - return result; - } - - @Override - public String usage() { - return ERROR_MESSAGE_AND; - } - - }); - functions.put("or", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - boolean result = false; - - if (sources != null) { - - if (sources.length < 2) { - return usage(); - } - - for (Object i : sources) { - - if (i != null) { - - try { - - result |= "true".equals(i.toString()) || Boolean.TRUE.equals(i); - - } catch (Throwable t) { - - return t.getMessage(); - - } - - } else { - - // null is false - result |= false; - } - } - - } - - return result; - } - - @Override - public String usage() { - return ERROR_MESSAGE_OR; - } - }); - functions.put("get", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final SecurityContext securityContext = entity.getSecurityContext(); - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - GraphObject dataObject = null; - - if (sources[0] instanceof GraphObject) { - dataObject = (GraphObject) sources[0]; - } - - if (sources[0] instanceof List) { - - final List list = (List) sources[0]; - if (list.size() == 1 && list.get(0) instanceof GraphObject) { - - dataObject = (GraphObject) list.get(0); - } - } - - if (dataObject != null) { - - final String keyName = sources[1].toString(); - final PropertyKey key = StructrApp.getConfiguration().getPropertyKeyForJSONName(dataObject.getClass(), keyName); - - if (key != null) { - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = dataObject.getProperty(key); - - if (inputConverter != null) { - return inputConverter.revert(value); - } - - return dataObject.getProperty(key); - } - - return ""; - - } else { - - return ERROR_MESSAGE_GET_ENTITY; - } - } - - return usage(); - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET; - } - }); - functions.put("size", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList(); - for (final Object source : sources) { - - if (source != null) { - - if (source instanceof Collection) { - - // filter null objects - for (Object obj : (Collection) source) { - if (obj != null && !NULL_STRING.equals(obj)) { - - list.add(obj); - } - } - - } else if(source.getClass().isArray()) { - - list.addAll(Arrays.asList((Object[])source)); - - } else if (source != null && !NULL_STRING.equals(source)) { - - list.add(source); - } - - return list.size(); - } - } - - return 0; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SIZE; - } - }); - functions.put("first", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - return ((List) sources[0]).get(0); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (arr.length > 0) { - - return arr[0]; - } - } - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIRST; - } - }); - functions.put("last", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - - final List list = (List) sources[0]; - return list.get(list.size() - 1); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (arr.length > 0) { - - return arr[arr.length - 1]; - } - } - - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_LAST; - } - }); - functions.put("nth", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2)) { - - final int pos = Double.valueOf(sources[1].toString()).intValue(); - - if (sources[0] instanceof List && !((List) sources[0]).isEmpty()) { - - final List list = (List) sources[0]; - final int size = list.size(); - - if (pos >= size) { - - return null; - - } - - return list.get(Math.min(Math.max(0, pos), size - 1)); - } - - if (sources[0].getClass().isArray()) { - - final Object[] arr = (Object[])sources[0]; - if (pos <= arr.length) { - - return arr[pos]; - } - } - } - - return null; - } - - @Override - public String usage() { - return ERROR_MESSAGE_NTH; - } - }); - functions.put("get_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - return ctx.getCounter(parseInt(sources[0])); - } - - return 0; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_COUNTER; - } - }); - functions.put("inc_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final int level = parseInt(sources[0]); - - ctx.incrementCounter(level); - - // reset lower levels? - if (sources.length == 2 && "true".equals(sources[1].toString())) { - - // reset lower levels - for (int i = level + 1; i < 10; i++) { - ctx.resetCounter(i); - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INC_COUNTER; - } - }); - functions.put("reset_counter", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - ctx.resetCounter(parseInt(sources[0])); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_RESET_COUNTER; - } - }); - functions.put("merge_properties", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof GraphObject && sources[1] instanceof GraphObject) { - - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Set mergeKeys = new LinkedHashSet<>(); - final GraphObject source = (GraphObject) sources[0]; - final GraphObject target = (GraphObject) sources[1]; - final int paramCount = sources.length; - - for (int i = 2; i < paramCount; i++) { - - final String keyName = sources[i].toString(); - final PropertyKey key = config.getPropertyKeyForJSONName(target.getClass(), keyName); - - mergeKeys.add(key); - } - - for (final PropertyKey key : mergeKeys) { - - final Object sourceValue = source.getProperty(key); - if (sourceValue != null) { - - target.setProperty(key, sourceValue); - } - - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_MERGE_PROPERTIES; - } - }); - functions.put("keys", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof GraphObject) { - - final Set keys = new LinkedHashSet<>(); - final GraphObject source = (GraphObject) sources[0]; - - for (final PropertyKey key : source.getPropertyKeys(sources[1].toString())) { - keys.add(key.jsonName()); - } - - return new LinkedList<>(keys); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_KEYS; - } - }); - - // ----- BEGIN functions with side effects ----- - functions.put("retrieve", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String) { - - return ctx.retrieve(sources[0].toString()); - - } else { - - return ERROR_MESSAGE_RETRIEVE; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_RETRIEVE; - } - }); - functions.put("store", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof String) { - - ctx.store(sources[0].toString(), sources[1]); - - } else { - - return ERROR_MESSAGE_STORE; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_STORE; - } - }); - functions.put("print", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - for (Object i : sources) { - - System.out.print(i); - } - - System.out.println(); - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_PRINT; - } - }); - functions.put("read", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - if (file.exists() && file.length() < 10000000) { - - try (final FileInputStream fis = new FileInputStream(file)) { - - return IOUtils.toString(fis, "utf-8"); - } - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_READ; - } - }); - functions.put("write", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - if (!file.exists()) { - - try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file, false))) { - - for (int i = 1; i < sources.length; i++) { - if (sources[i] != null) { - IOUtils.write(sources[i].toString(), writer); - } - } - - writer.flush(); - } - - } else { - - logger.log(Level.SEVERE, "Trying to overwrite an existing file, please use append() for that purpose."); - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_WRITE; - } - }); - functions.put("append", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - try { - final String sandboxFilename = getSandboxFileName(sources[0].toString()); - if (sandboxFilename != null) { - - final File file = new File(sandboxFilename); - - try (final Writer writer = new OutputStreamWriter(new FileOutputStream(file, true))) { - - for (int i = 1; i < sources.length; i++) { - IOUtils.write(sources[i].toString(), writer); - } - - writer.flush(); - } - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_APPEND; - } - }); - functions.put("xml", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 1) && sources[0] instanceof String) { - - try { - - final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - if (builder != null) { - - final String xml = (String) sources[0]; - final StringReader reader = new StringReader(xml); - final InputSource src = new InputSource(reader); - - return builder.parse(src); - } - - } catch (IOException | SAXException | ParserConfigurationException ex) { - ex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_XML; - } - }); - functions.put("xpath", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2) && sources[0] instanceof Document) { - - try { - - XPath xpath = XPathFactory.newInstance().newXPath(); - return xpath.evaluate(sources[1].toString(), sources[0], XPathConstants.STRING); - - } catch (XPathExpressionException ioex) { - ioex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_XPATH; - } - }); - functions.put("set", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - if (sources[0] instanceof GraphObject) { - - final GraphObject source = (GraphObject) sources[0]; - final Map properties = new LinkedHashMap<>(); - final SecurityContext securityContext = source.getSecurityContext(); - final Gson gson = new GsonBuilder().create(); - final Class type = source.getClass(); - final int sourceCount = sources.length; - - if (sources.length == 3 && sources[2] != null && sources[1].toString().matches("[a-zA-Z0-9_]+")) { - - properties.put(sources[1].toString(), sources[2]); - - } else { - - // we either have and odd number of items, or two multi-value items. - for (int i = 1; i < sourceCount; i++) { - - final Map values = deserialize(gson, sources[i].toString()); - if (values != null) { - - properties.putAll(values); - } - } - } - - // store values in entity - final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, properties); - for (final Map.Entry entry : map.entrySet()) { - - source.setProperty(entry.getKey(), entry.getValue()); - } - - } else { - - throw new FrameworkException(422, "Invalid use of builtin method set, usage: set(entity, params..)"); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SET; - } - }); - functions.put("send_plaintext_mail", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 6)) { - - final String from = sources[0].toString(); - final String fromName = sources[1].toString(); - final String to = sources[2].toString(); - final String toName = sources[3].toString(); - final String subject = sources[4].toString(); - final String textContent = sources[5].toString(); - - try { - return MailHelper.sendSimpleMail(from, fromName, to, toName, null, null, from, subject, textContent); - - } catch (EmailException eex) { - eex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SEND_PLAINTEXT_MAIL; - } - }); - functions.put("send_html_mail", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 6)) { - - final String from = sources[0].toString(); - final String fromName = sources[1].toString(); - final String to = sources[2].toString(); - final String toName = sources[3].toString(); - final String subject = sources[4].toString(); - final String htmlContent = sources[5].toString(); - String textContent = ""; - - if (sources.length == 7) { - textContent = sources[6].toString(); - } - - try { - return MailHelper.sendHtmlMail(from, fromName, to, toName, null, null, from, subject, htmlContent, textContent); - - } catch (EmailException eex) { - eex.printStackTrace(); - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_SEND_HTML_MAIL; - } - }); - functions.put("geocode", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final Gson gson = new GsonBuilder().create(); - final String street = sources[0].toString(); - final String city = sources[1].toString(); - final String country = sources[2].toString(); - - GeoCodingResult result = GeoHelper.geocode(street, null, null, city, null, country); - if (result != null) { - - final Map map = new LinkedHashMap<>(); - - map.put("latitude", result.getLatitude()); - map.put("longitude", result.getLongitude()); - - return serialize(gson, map); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GEOCODE; - } - }); - functions.put("find", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Query query = StructrApp.getInstance(securityContext).nodeQuery().sort(GraphObject.createdDate).order(false); - - // the type to query for - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type != null) { - - query.andTypes(type); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - query.and(PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1])); - - } else { - - - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - // throw exception if key is not indexed (otherwise the user will never know) - if (!key.isSearchable()) { - - throw new FrameworkException(400, "Search key " + key.jsonName() + " is not indexed."); - } - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - query.and(key, value); - } - } - } - - final Object x = query.getAsList(); - - // return search results - return x; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIND; - } - }); - functions.put("search", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final ConfigurationProvider config = StructrApp.getConfiguration(); - final Query query = StructrApp.getInstance(securityContext).nodeQuery(); - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type != null) { - - query.andTypes(type); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - final PropertyMap map = PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1]); - for (final Entry entry : map.entrySet()) { - - query.and(entry.getKey(), entry.getValue(), false); - } - - } else { - - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_FIND); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - // throw exception if key is not indexed (otherwise the user will never know) - if (!key.isSearchable()) { - - throw new FrameworkException(400, "Search key " + key.jsonName() + " is not indexed."); - } - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1]; - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - query.and(key, value, false); - } - - } - } - - final Object x = query.getAsList(); - - // return search results - return x; - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_FIND; - } - }); - functions.put("create", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final SecurityContext securityContext = entity.getSecurityContext(); - final App app = StructrApp.getInstance(securityContext); - final ConfigurationProvider config = StructrApp.getConfiguration(); - PropertyMap propertyMap = null; - Class type = null; - - if (sources.length >= 1 && sources[0] != null) { - - type = config.getNodeEntityClass(sources[0].toString()); - - if (type.equals(entity.getClass())) { - - throw new FrameworkException(422, "Cannot create() entity of the same type in save action."); - } - } - - // extension for native javascript objects - if (sources.length == 2 && sources[1] instanceof Map) { - - propertyMap = PropertyMap.inputTypeToJavaType(securityContext, type, (Map)sources[1]); - - } else { - - propertyMap = new PropertyMap(); - final Integer parameter_count = sources.length; - - if (parameter_count % 2 == 0) { - - throw new FrameworkException(400, "Invalid number of parameters: " + parameter_count + ". Should be uneven: " + ERROR_MESSAGE_CREATE); - } - - for (Integer c = 1; c < parameter_count; c+=2) { - - final PropertyKey key = config.getPropertyKeyForJSONName(type, sources[c].toString()); - - if (key != null) { - - final PropertyConverter inputConverter = key.inputConverter(securityContext); - Object value = sources[c+1].toString(); - - if (inputConverter != null) { - - value = inputConverter.convert(value); - } - - propertyMap.put(key, value); - - } - - } - } - - if (type != null) { - - return app.create(type, propertyMap); - - } else { - - throw new FrameworkException(422, "Unknown type in create() save action."); - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CREATE; - } - }); - functions.put("delete", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (sources != null) { - - final App app = StructrApp.getInstance(entity.getSecurityContext()); - for (final Object obj : sources) { - - if (obj instanceof NodeInterface) { - - app.delete((NodeInterface) obj); - continue; - } - - if (obj instanceof RelationshipInterface) { - - app.delete((RelationshipInterface) obj); - continue; - } - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_DELETE; - } - }); - functions.put("incoming", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final RelationshipFactory factory = new RelationshipFactory(entity.getSecurityContext()); - final Object source = sources[0]; - - if (source instanceof NodeInterface) { - - final NodeInterface node = (NodeInterface) source; - if (sources.length > 1) { - - final Object relType = sources[1]; - if (relType != null && relType instanceof String) { - - final String relTypeName = (String) relType; - return factory.instantiate(node.getNode().getRelationships(Direction.INCOMING, DynamicRelationshipType.withName(relTypeName))); - } - - } else { - - return factory.instantiate(node.getNode().getRelationships(Direction.INCOMING)); - } - - } else { - - return "Error: entity is not a node."; - } - } - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_INCOMING; - } - }); - functions.put("outgoing", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 1)) { - - final RelationshipFactory factory = new RelationshipFactory(entity.getSecurityContext()); - final Object source = sources[0]; - - if (source instanceof NodeInterface) { - - final NodeInterface node = (NodeInterface) source; - if (sources.length > 1) { - - final Object relType = sources[1]; - if (relType != null && relType instanceof String) { - - final String relTypeName = (String) relType; - return factory.instantiate(node.getNode().getRelationships(Direction.OUTGOING, DynamicRelationshipType.withName(relTypeName))); - } - - } else { - - return factory.instantiate(node.getNode().getRelationships(Direction.OUTGOING)); - } - - } else { - - return "Error: entity is not a node."; - } - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_OUTGOING; - } - }); - functions.put("has_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - return true; - } - } - - } else if (sources.length == 3) { - - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( rel.getRelType().name().equals(relType) && ((rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode))) ) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_RELATIONSHIP; - } - }); - functions.put("has_outgoing_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - return true; - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getRelType().name().equals(relType) && rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_OUTGOING_RELATIONSHIP; - } - }); - functions.put("has_incoming_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) { - return true; - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getRelType().name().equals(relType) && (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - return true; - } - } - - } - - } - - return false; - } - - @Override - public String usage() { - return ERROR_MESSAGE_HAS_INCOMING_RELATIONSHIP; - } - }); - functions.put("get_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getRelationships()) { - - if ( rel.getRelType().name().equals(relType) && ((rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) || (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode))) ) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_RELATIONSHIPS; - } - }); - functions.put("get_outgoing_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getOutgoingRelationships()) { - - if (rel.getRelType().name().equals(relType) && rel.getSourceNode().equals(sourceNode) && rel.getTargetNode().equals(targetNode)) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_OUTGOING_RELATIONSHIPS; - } - }); - functions.put("get_incoming_relationships", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - final List list = new ArrayList<>(); - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 2)) { - - final Object source = sources[0]; - final Object target = sources[1]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - if (sources.length == 2) { - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) { - list.add(rel); - } - } - - } else if (sources.length == 3) { - - // dont try to create the relClass because we would need to do that both ways!!! otherwise it just fails if the nodes are in the "wrong" order (see tests:890f) - final String relType = (String) sources[2]; - - for (final AbstractRelationship rel : sourceNode.getIncomingRelationships()) { - - if (rel.getRelType().name().equals(relType) && (rel.getSourceNode().equals(targetNode) && rel.getTargetNode().equals(sourceNode)) ) { - list.add(rel); - } - } - - } - } - - return list; - } - - @Override - public String usage() { - return ERROR_MESSAGE_GET_INCOMING_RELATIONSHIPS; - } - }); - functions.put("create_relationship", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasLengthAndAllElementsNotNull(sources, 3)) { - - final Object source = sources[0]; - final Object target = sources[1]; - final String relType = (String) sources[2]; - - AbstractNode sourceNode = null; - AbstractNode targetNode = null; - - if (source instanceof AbstractNode && target instanceof AbstractNode) { - - sourceNode = (AbstractNode) source; - targetNode = (AbstractNode) target; - - } else { - - return "Error: entities are not nodes."; - } - - final Class relClass = StructrApp.getConfiguration().getRelationClassForCombinedType(sourceNode.getType(), relType, targetNode.getType()); - - if (relClass != null) { - - StructrApp.getInstance(sourceNode.getSecurityContext()).create(sourceNode, targetNode, relClass); - - } else { - - return "Error: Unknown relationship type"; - } - - } - - return ""; - } - - @Override - public String usage() { - return ERROR_MESSAGE_CREATE_RELATIONSHIP; - } - }); - functions.put("grant", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 3)) { - - if (sources[0] instanceof Principal) { - - final Principal principal = (Principal) sources[0]; - - if (sources[1] instanceof AbstractNode) { - - final AbstractNode node = (AbstractNode) sources[1]; - - if (sources[2] instanceof String) { - - final String[] parts = ((String) sources[2]).split("[,]+"); - for (final String part : parts) { - - final String trimmedPart = part.trim(); - if (trimmedPart.length() > 0) { - - try { - - final Permission permission = Permission.valueOf(trimmedPart); - principal.grant(permission, node); - - } catch (IllegalArgumentException iex) { - - return "Error: unknown permission " + trimmedPart; - } - } - } - - return ""; - - } else { - - return "Error: third argument is not a string."; - } - - } else { - - return "Error: second argument is not a node."; - } - - } else { - - return "Error: first argument is not of type Principal."; - } - - } else { - - return ERROR_MESSAGE_GRANT; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_GRANT; - } - }); - functions.put("revoke", new Function() { - - @Override - public Object apply(final ActionContext ctx, final GraphObject entity, final Object[] sources) throws FrameworkException { - - if (arrayHasMinLengthAndAllElementsNotNull(sources, 3)) { - - if (sources[0] instanceof Principal) { - - final Principal principal = (Principal) sources[0]; - - if (sources[1] instanceof AbstractNode) { - - final AbstractNode node = (AbstractNode) sources[1]; - - if (sources[2] instanceof String) { - - final String[] parts = ((String) sources[2]).split("[,]+"); - for (final String part : parts) { - - final String trimmedPart = part.trim(); - if (trimmedPart.length() > 0) { - - try { - - final Permission permission = Permission.valueOf(trimmedPart); - principal.revoke(permission, node); - - } catch (IllegalArgumentException iex) { - - return "Error: unknown permission " + trimmedPart; - } - } - } - - return ""; - - } else { - - return "Error: third argument is not a string."; - } - - } else { - - return "Error: second argument is not a node."; - } - - } else { - - return "Error: first argument is not of type Principal."; - } - - } else { - - return ERROR_MESSAGE_REVOKE; - } - } - - @Override - public String usage() { - return ERROR_MESSAGE_REVOKE; - } - }); - } - - /** - * Test if the given object array has a minimum length and all its - * elements are not null. - * - * @param array - * @param minLength If null, don't do length check - * @return true if array has min length and all elements are not null - */ - public static boolean arrayHasMinLengthAndAllElementsNotNull(final Object[] array, final Integer minLength) { - - if (array == null) { - return false; - } - - for (final Object element : array) { - - if (element == null) { - return false; - } - - } - - return minLength != null ? array.length >= minLength : true; - - } - - /** - * Test if the given object array has exact the given length and all its - * elements are not null. - * - * @param array - * @param length If null, don't do length check - * @return true if array has exact length and all elements are not null - */ - public static boolean arrayHasLengthAndAllElementsNotNull(final Object[] array, final Integer length) { - - if (array == null) { - return false; - } - - for (final Object element : array) { - - if (element == null) { - return false; - } - - } - - return length != null ? array.length == length : true; - - } - - protected static String serialize(final Gson gson, final Map map) { - return gson.toJson(map, new TypeToken>() { - }.getType()); - } - - protected static Map deserialize(final Gson gson, final String source) { - return gson.fromJson(source, new TypeToken>() { - }.getType()); - } - - protected static Integer parseInt(final Object source) { - - if (source instanceof Integer) { - - return ((Integer) source); - } - - if (source instanceof Number) { - - return ((Number) source).intValue(); - } - - if (source instanceof String) { - - return Integer.parseInt((String) source); - } - - return null; - } - - protected static String encodeURL(final String source) { - - try { - return URLEncoder.encode(source, "UTF-8"); - - } catch (UnsupportedEncodingException ex) { - - logger.log(Level.WARNING, "Unsupported Encoding", ex); - } - - // fallback, unencoded - return source; - } - - protected static double getDoubleForComparison(final Object obj) { - - if (obj instanceof Date) { - - return ((Date) obj).getTime(); - - } else if (obj instanceof Number) { - - return ((Number) obj).doubleValue(); - - } else { - - try { - return Double.valueOf(obj.toString()); - - } catch (Throwable t) { - - t.printStackTrace(); - } - } - - return 0.0; - } - - protected static Double getDoubleOrNull(final Object obj) { - - if (obj instanceof Date) { - - return Double.valueOf(((Date) obj).getTime()); - - } else if (obj instanceof Number) { - - return ((Number) obj).doubleValue(); - - } else { - - try { - return Double.valueOf(obj.toString()); - - } catch (Throwable t) { - - t.printStackTrace(); - } - } - - return null; - } - - protected static boolean valueEquals(final Object obj1, final Object obj2) { - - if (obj1 instanceof Enum || obj2 instanceof Enum) { - - return obj1.toString().equals(obj2.toString()); - - } - - if (obj1 instanceof Number && obj2 instanceof Number) { - - return ((Number) obj1).doubleValue() == ((Number) obj2).doubleValue(); - } - - return obj1.equals(obj2); - } - - protected static String getSandboxFileName(final String source) throws IOException { - - final File sandboxFile = new File(source); - final String fileName = sandboxFile.getName(); - final String basePath = StructrApp.getConfigurationValue(Services.BASE_PATH); - - if (!basePath.isEmpty()) { - - final String defaultExchangePath = basePath.endsWith("/") ? basePath.concat("exchange") : basePath.concat("/exchange"); - String exchangeDir = StructrApp.getConfigurationValue(Services.DATA_EXCHANGE_PATH, defaultExchangePath); - - if (!exchangeDir.endsWith("/")) { - exchangeDir = exchangeDir.concat("/"); - } - - // create exchange directory - final File dir = new File(exchangeDir); - if (!dir.exists()) { - - dir.mkdirs(); - } - - // return sandboxed file name - return exchangeDir.concat(fileName); - - } else { - - logger.log(Level.WARNING, "Unable to determine base.path from structr.conf, no data input/output possible."); - } - - return null; - } - - public static String cleanString(final Object input) { - - if (input == null) { - - return ""; - - } - - String normalized = Normalizer.normalize(input.toString(), Normalizer.Form.NFD) - .replaceAll("\\<", "") - .replaceAll("\\>", "") - .replaceAll("\\.", "") - .replaceAll("\\'", "-") - .replaceAll("\\?", "") - .replaceAll("\\(", "") - .replaceAll("\\)", "") - .replaceAll("\\{", "") - .replaceAll("\\}", "") - .replaceAll("\\[", "") - .replaceAll("\\]", "") - .replaceAll("\\+", "-") - .replaceAll("/", "-") - .replaceAll("–", "-") - .replaceAll("\\\\", "-") - .replaceAll("\\|", "-") - .replaceAll("'", "-") - .replaceAll("!", "") - .replaceAll(",", "") - .replaceAll("-", " ") - .replaceAll("_", " ") - .replaceAll("`", "-"); - - String result = normalized.replaceAll("-", " "); - result = StringUtils.normalizeSpace(result.toLowerCase()); - result = result.replaceAll("[^\\p{ASCII}]", "").replaceAll("\\p{P}", "-").replaceAll("\\-(\\s+\\-)+", "-"); - result = result.replaceAll(" ", "-"); - - return result; - - } - - public static void recursivelyConvertMapToGraphObjectMap(final GraphObjectMap destination, final Map source, final int depth) { - - if (depth > 20) { - return; - } - - for (final Map.Entry entry : source.entrySet()) { - - final String key = entry.getKey(); - final Object value = entry.getValue(); - - if (value instanceof Map) { - - final Map map = (Map) value; - final GraphObjectMap obj = new GraphObjectMap(); - - destination.put(new StringProperty(key), obj); - - recursivelyConvertMapToGraphObjectMap(obj, map, depth+1); - - } else if (value instanceof Collection) { - - final List list = new LinkedList(); - final Collection collection = (Collection)value; - - for (final Object obj : collection) { - - if (obj instanceof Map) { - - final GraphObjectMap container = new GraphObjectMap(); - list.add(container); - - recursivelyConvertMapToGraphObjectMap(container, (Map)obj, depth+1); - - } else { - - list.add(obj); - } - } - - destination.put(new StringProperty(key), list); - - } else { - - destination.put(new StringProperty(key), value); - } - } - } - - public static Object numberOrString(final String value) { - - if (value != null) { - - if ("true".equals(value.toLowerCase())) { - return true; - } - - if ("false".equals(value.toLowerCase())) { - return false; - } - - if (NumberUtils.isNumber(value)) { - return NumberUtils.createNumber(value); - } - } - - return value; - } -} diff --git a/All/Genesis-NP/Genesis#155/pair.info b/All/Genesis-NP/Genesis#155/pair.info deleted file mode 100755 index 078b4c6..0000000 --- a/All/Genesis-NP/Genesis#155/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:155 -SATName:Genesis -modifiedFPath:structr-core/src/main/java/org/structr/core/parser/Functions.java -comSha:daf5d85019d275a8d01775e803edeb5e82805940 -parentComSha:daf5d85019d275a8d01775e803edeb5e82805940^1 -githubUrl:https://github.com/structr/structr -repoName:structr#structr \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#156/comMsg.txt b/All/Genesis-NP/Genesis#156/comMsg.txt deleted file mode 100755 index 7b78e26..0000000 --- a/All/Genesis-NP/Genesis#156/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE in StaticRelationshipResource when invoking custom methods using REST POST. diff --git a/All/Genesis-NP/Genesis#156/diff.diff b/All/Genesis-NP/Genesis#156/diff.diff deleted file mode 100755 index bea70f8..0000000 --- a/All/Genesis-NP/Genesis#156/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/structr-rest/src/main/java/org/structr/rest/servlet/JsonRestServlet.java b/structr-rest/src/main/java/org/structr/rest/servlet/JsonRestServlet.java -index 2ff9a4b..f79e73d 100644 ---- a/structr-rest/src/main/java/org/structr/rest/servlet/JsonRestServlet.java -+++ b/structr-rest/src/main/java/org/structr/rest/servlet/JsonRestServlet.java -@@ -466,0 +467,2 @@ public class JsonRestServlet extends HttpServlet implements HttpServiceServlet { -+ if (result != null) { -+ -@@ -484,0 +487 @@ public class JsonRestServlet extends HttpServlet implements HttpServiceServlet { -+ } diff --git a/All/Genesis-NP/Genesis#156/new/JsonRestServlet.java b/All/Genesis-NP/Genesis#156/new/JsonRestServlet.java deleted file mode 100755 index f79e73d..0000000 --- a/All/Genesis-NP/Genesis#156/new/JsonRestServlet.java +++ /dev/null @@ -1,987 +0,0 @@ -/** - * Copyright (C) 2010-2014 Morgner UG (haftungsbeschränkt) - * - * This file is part of Structr . - * - * Structr is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * Structr is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Structr. If not, see . - */ -package org.structr.rest.servlet; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; -import java.io.IOException; -import java.io.Writer; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.apache.commons.io.IOUtils; -import org.neo4j.kernel.DeadlockDetectedException; -import org.structr.common.PagingHelper; -import org.structr.common.SecurityContext; -import org.structr.common.error.FrameworkException; -import org.structr.core.*; -import org.structr.core.app.App; -import org.structr.core.app.StructrApp; -import org.structr.core.auth.Authenticator; -import org.structr.core.entity.AbstractNode; -import org.structr.core.graph.NodeFactory; -import org.structr.core.graph.Tx; -import org.structr.core.graph.search.SearchCommand; -import org.structr.core.property.PropertyKey; -import org.structr.rest.JsonInputGSONAdapter; -import org.structr.rest.ResourceProvider; -import org.structr.rest.RestMethodResult; -import org.structr.rest.adapter.FrameworkExceptionGSONAdapter; -import org.structr.rest.adapter.ResultGSONAdapter; -import org.structr.rest.resource.Resource; -import org.structr.rest.serialization.StreamingHtmlWriter; -import org.structr.rest.serialization.StreamingJsonWriter; -import org.structr.rest.service.HttpServiceServlet; -import org.structr.rest.service.StructrHttpServiceConfig; -import org.tuckey.web.filters.urlrewrite.utils.StringUtils; - -//~--- classes ---------------------------------------------------------------- - -/** - * Implements the structr REST API. - * - * @author Christian Morgner - */ -public class JsonRestServlet extends HttpServlet implements HttpServiceServlet { - - public static final int DEFAULT_VALUE_PAGE_SIZE = 20; - public static final String DEFAULT_VALUE_SORT_ORDER = "asc"; - public static final String REQUEST_PARAMETER_LOOSE_SEARCH = "loose"; - public static final String REQUEST_PARAMETER_PAGE_NUMBER = "page"; - public static final String REQUEST_PARAMETER_PAGE_SIZE = "pageSize"; - public static final String REQUEST_PARAMETER_OFFSET_ID = "pageStartId"; - public static final String REQUEST_PARAMETER_SORT_KEY = "sort"; - public static final String REQUEST_PARAMETER_SORT_ORDER = "order"; - public static final Set commonRequestParameters = new LinkedHashSet<>(); - private static final Logger logger = Logger.getLogger(JsonRestServlet.class.getName()); - - static { - - commonRequestParameters.add(REQUEST_PARAMETER_LOOSE_SEARCH); - commonRequestParameters.add(REQUEST_PARAMETER_PAGE_NUMBER); - commonRequestParameters.add(REQUEST_PARAMETER_PAGE_SIZE); - commonRequestParameters.add(REQUEST_PARAMETER_OFFSET_ID); - commonRequestParameters.add(REQUEST_PARAMETER_SORT_KEY); - commonRequestParameters.add(REQUEST_PARAMETER_SORT_ORDER); - - // cross reference here, but these need to be added as well.. - commonRequestParameters.add(SearchCommand.DISTANCE_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.LOCATION_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.STREET_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.HOUSE_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.POSTAL_CODE_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.CITY_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.STATE_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.COUNTRY_SEARCH_KEYWORD); - } - - // final fields - private final Map> resourceMap = new LinkedHashMap<>(); - private final StructrHttpServiceConfig config = new StructrHttpServiceConfig(); - - // non-final fields - private Value propertyView = null; - private ThreadLocalGson gson = null; - private boolean indentJson = true; - - //~--- methods -------------------------------------------------------- - - @Override - public StructrHttpServiceConfig getConfig() { - return config; - } - - @Override - public void init() { - - try { - indentJson = Boolean.parseBoolean(StructrApp.getConfigurationValue(Services.JSON_INDENTATION, "true")); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to parse value for {0}: {1}", new Object[] { Services.JSON_INDENTATION, t.getMessage() } ); - } - - - // inject resources - final ResourceProvider provider = config.getResourceProvider(); - if (provider != null) { - - resourceMap.putAll(provider.getResources()); - - } else { - - logger.log(Level.SEVERE, "Unable to initialize JsonRestServlet, no resource provider found. Please check structr.conf for a valid resource provider class."); - } - - // initialize variables - this.propertyView = new ThreadLocalPropertyView(); - this.gson = new ThreadLocalGson(config.getOutputNestingDepth()); - } - - // - @Override - protected void doDelete(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - - SecurityContext securityContext = null; - Authenticator authenticator = null; - RestMethodResult result = null; - Resource resource = null; - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - resource = ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, config.getDefaultIdProperty()), config.getDefaultIdProperty()); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - - tx.success(); - } - - // isolate doDelete - boolean retry = true; - while (retry) { - - try (final Tx tx = app.tx()) { - result = resource.doDelete(); - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - - // isolate write output - try (final Tx tx = app.tx()) { - result.commitResponse(gson.get(), response); - tx.success(); - } - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "JsonSyntaxException in DELETE", jsex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "JsonParseException in DELETE", jpex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + jpex.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in DELETE", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (IOException t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - @Override - protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - - final boolean returnContent = true; - - doGetOrHead(request, response, returnContent); - } - - @Override - protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - final boolean returnContent = false; - - doGetOrHead(request, response, returnContent); - } - - // - @Override - protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - final SecurityContext securityContext; - final Authenticator authenticator; - final Resource resource; - - RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST); - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - resource = ResourceHelper.applyViewTransformation(request, securityContext, - ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, - config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - tx.success(); - } - - // isolate doOptions - boolean retry = true; - while (retry) { - - try (final Tx tx = app.tx()) { - - result = resource.doOptions(); - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - - // isolate write output - try (final Tx tx = app.tx()) { - result.commitResponse(gson.get(), response); - tx.success(); - } - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "JsonSyntaxException in OPTIONS", jsex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "JsonParseException in OPTIONS", jpex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jpex.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in OPTIONS", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - // - @Override - protected void doPost(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - final List results = new LinkedList<>(); - final SecurityContext securityContext; - final Authenticator authenticator; - final Resource resource; - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - final String input = IOUtils.toString(request.getReader()); - final IJsonInput jsonInput = cleanAndParseJsonString(app, input); - - if (securityContext != null) { - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - resource = ResourceHelper.applyViewTransformation(request, securityContext, - ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, - config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - tx.success(); - } - - // isolate doPost - boolean retry = true; - while (retry) { - - if (resource.createPostTransaction()) { - - try (final Tx tx = app.tx()) { - - for (JsonInput propertySet : jsonInput.getJsonInputs()) { - - results.add(resource.doPost(convertPropertySetToMap(propertySet))); - } - - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - - } else { - - try { - - for (JsonInput propertySet : jsonInput.getJsonInputs()) { - - results.add(resource.doPost(convertPropertySetToMap(propertySet))); - } - - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - } - - // set default value for property view - propertyView.set(securityContext, config.getDefaultPropertyView()); - - // isolate write output - try (final Tx tx = app.tx()) { - - if (!results.isEmpty()) { - - final RestMethodResult result = results.get(0); - final int resultCount = results.size(); - - if (result != null) { - - if (resultCount > 1) { - - for (final RestMethodResult r : results) { - - final GraphObject objectCreated = r.getContent().get(0); - if (!result.getContent().contains(objectCreated)) { - - result.addContent(objectCreated); - } - - } - - // remove Location header if more than one object was - // written because it may only contain a single URL - result.addHeader("Location", null); - } - - result.commitResponse(gson.get(), response); - } - - } - - tx.success(); - } - - } else { - - // isolate write output - try (final Tx tx = app.tx()) { - - new RestMethodResult(HttpServletResponse.SC_FORBIDDEN).commitResponse(gson.get(), response); - tx.success(); - } - - } - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "POST: Invalid JSON syntax", jsex.getMessage()); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "Unable to parse JSON string", jpex.getMessage()); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonParseException in POST: " + jpex.getMessage())); - - } catch (UnsupportedOperationException uoe) { - - logger.log(Level.WARNING, "POST not supported"); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "POST not supported: " + uoe.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in POST", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - // - @Override - protected void doPut(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - - final SecurityContext securityContext; - final Authenticator authenticator; - final Resource resource; - - RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST); - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - final String input = IOUtils.toString(request.getReader()); - final IJsonInput jsonInput = cleanAndParseJsonString(app, input); - - if (securityContext != null) { - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - // evaluate constraint chain - resource = ResourceHelper.applyViewTransformation(request, securityContext, - ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, - config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - tx.success(); - } - - // isolate doPut - boolean retry = true; - while (retry) { - - try (final Tx tx = app.tx()) { - result = resource.doPut(convertPropertySetToMap(jsonInput.getJsonInputs().get(0))); - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - - // isolate write output - try (final Tx tx = app.tx()) { - result.commitResponse(gson.get(), response); - tx.success(); - } - - } else { - - // isolate write output - try (final Tx tx = app.tx()) { - result = new RestMethodResult(HttpServletResponse.SC_FORBIDDEN); - result.commitResponse(gson.get(), response); - tx.success(); - } - - } - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "PUT: Invalid JSON syntax", jsex.getMessage()); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "PUT: Unable to parse JSON string", jpex.getMessage()); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jpex.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in PUT", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - // - @Override - protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - -// logRequest("TRACE", request); - response.setContentType("application/json; charset=UTF-8"); - response.setCharacterEncoding("UTF-8"); - - int code = HttpServletResponse.SC_METHOD_NOT_ALLOWED; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "TRACE method not allowed")); - } - - // - - // - - private IJsonInput cleanAndParseJsonString(final App app, final String input) throws FrameworkException { - - IJsonInput jsonInput; - - // isolate input parsing (will include read and write operations) - try (final Tx tx = app.tx()) { - jsonInput = gson.get().fromJson(input, IJsonInput.class); - tx.success(); - } - - if (jsonInput == null) { - - if (StringUtils.isBlank(input)) { - - try (final Tx tx = app.tx()) { - jsonInput = gson.get().fromJson("{}", IJsonInput.class); - tx.success(); - } - - } else { - //throw new JsonParseException("Invalid or empty JSON string, must at least contain {} to be valid!"); - jsonInput = new JsonSingleInput(); - } - } - - return jsonInput; - - } - - private Map convertPropertySetToMap(JsonInput propertySet) { - - if (propertySet != null) { - return propertySet.getAttributes(); - } - - return new LinkedHashMap<>(); - } - - private void doGetOrHead(final HttpServletRequest request, final HttpServletResponse response, final boolean returnContent) throws ServletException, IOException { - - SecurityContext securityContext = null; - Authenticator authenticator = null; - Result result = null; - Resource resource = null; - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - - // set default value for property view - propertyView.set(securityContext, config.getDefaultPropertyView()); - - // evaluate constraints and measure query time - double queryTimeStart = System.nanoTime(); - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - resource = ResourceHelper.applyViewTransformation(request, securityContext, - ResourceHelper.optimizeNestedResourceChain( - ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, - config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - tx.success(); - } - - // add sorting & paging - String pageSizeParameter = request.getParameter(REQUEST_PARAMETER_PAGE_SIZE); - String pageParameter = request.getParameter(REQUEST_PARAMETER_PAGE_NUMBER); - String offsetId = request.getParameter(REQUEST_PARAMETER_OFFSET_ID); - String sortOrder = request.getParameter(REQUEST_PARAMETER_SORT_ORDER); - String sortKeyName = request.getParameter(REQUEST_PARAMETER_SORT_KEY); - boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase())); - int pageSize = Services.parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE); - int page = Services.parseInt(pageParameter, NodeFactory.DEFAULT_PAGE); - String baseUrl = request.getRequestURI(); - PropertyKey sortKey = null; - - // set sort key - if (sortKeyName != null) { - - Class type = resource.getEntityClass(); - if (type == null) { - - // fallback to default implementation - // if no type can be determined - type = AbstractNode.class; - } - - sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false); - } - - // isolate doGet - boolean retry = true; - while (retry) { - - try (final Tx tx = app.tx()) { - result = resource.doGet(sortKey, sortDescending, pageSize, page, offsetId); - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - - if (returnContent) { - - result.setIsCollection(resource.isCollectionResource()); - result.setIsPrimitiveArray(resource.isPrimitiveArray()); - - PagingHelper.addPagingParameter(result, pageSize, page); - - // timing.. - double queryTimeEnd = System.nanoTime(); - - // store property view that will be used to render the results - result.setPropertyView(propertyView.get(securityContext)); - - // allow resource to modify result set - resource.postProcessResultSet(result); - - DecimalFormat decimalFormat = new DecimalFormat("0.000000000", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); - result.setQueryTime(decimalFormat.format((queryTimeEnd - queryTimeStart) / 1000000000.0)); - - String accept = request.getHeader("Accept"); - - if (accept != null && accept.contains("text/html")) { - - final StreamingHtmlWriter htmlStreamer = new StreamingHtmlWriter(this.propertyView, indentJson, config.getOutputNestingDepth()); - - // isolate write output - try (final Tx tx = app.tx()) { - - response.setContentType("text/html; charset=utf-8"); - - try (final Writer writer = response.getWriter()) { - - htmlStreamer.stream(securityContext, writer, result, baseUrl); - writer.append("\n"); // useful newline - } - - tx.success(); - } - - } else { - - final StreamingJsonWriter jsonStreamer = new StreamingJsonWriter(this.propertyView, indentJson, config.getOutputNestingDepth()); - - // isolate write output - try (final Tx tx = app.tx()) { - - response.setContentType("application/json; charset=utf-8"); - try (final Writer writer = response.getWriter()) { - - jsonStreamer.stream(securityContext, writer, result, baseUrl); - writer.append("\n"); // useful newline - } - - tx.success(); - } - - } - } - - response.setStatus(HttpServletResponse.SC_OK); - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "JsonSyntaxException in GET", jsex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "Json syntax exception in GET: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "JsonParseException in GET", jpex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "Parser exception in GET: " + jpex.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in GET", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "Exception in GET: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - // - private class ThreadLocalPropertyView extends ThreadLocal implements Value { - - @Override - protected String initialValue() { - return config.getDefaultPropertyView(); - } - - @Override - public void set(SecurityContext securityContext, String value) { - set(value); - } - - @Override - public String get(SecurityContext securityContext) { - return get(); - } - } - - private class ThreadLocalGson extends ThreadLocal { - - private int outputNestingDepth = 3; - - public ThreadLocalGson(final int outputNestingDepth) { - this.outputNestingDepth = outputNestingDepth; - } - - @Override - protected Gson initialValue() { - - JsonInputGSONAdapter jsonInputAdapter = new JsonInputGSONAdapter(propertyView, config.getDefaultIdProperty()); - ResultGSONAdapter resultGsonAdapter = new ResultGSONAdapter(propertyView, config.getDefaultIdProperty(), outputNestingDepth); - - // create GSON serializer - final GsonBuilder gsonBuilder = new GsonBuilder() - .setPrettyPrinting() - .serializeNulls() - .registerTypeHierarchyAdapter(FrameworkException.class, new FrameworkExceptionGSONAdapter()) - .registerTypeAdapter(IJsonInput.class, jsonInputAdapter) - .registerTypeAdapter(Result.class, resultGsonAdapter); - - - final boolean lenient = Boolean.parseBoolean(StructrApp.getConfigurationValue("json.lenient", "false")); - if (lenient) { - - // Serializes NaN, -Infinity, Infinity, see http://code.google.com/p/google-gson/issues/detail?id=378 - gsonBuilder.serializeSpecialFloatingPointValues(); - - } - - return gsonBuilder.create(); - } - } - // -} diff --git a/All/Genesis-NP/Genesis#156/new/pom.xml b/All/Genesis-NP/Genesis#156/new/pom.xml deleted file mode 100755 index a1c0698..0000000 --- a/All/Genesis-NP/Genesis#156/new/pom.xml +++ /dev/null @@ -1,234 +0,0 @@ - - - 4.0.0 - - - org.structr - structr - 1.1-SNAPSHOT - - - org.structr - structr-rest - jar - 1.1-SNAPSHOT - Structr REST - Structr is an open source framework based on the popular Neo4j graph database. - - - Axel Morgner - am@structr.org - - - Christian Morgner - cm@structr.org - - - http://structr.org - - - structr-gpl30 - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - true - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - - - maven-surefire-plugin - 2.16 - - false - -Xmx1024m -XX:MaxPermSize=256m - - UTC - - - - - com.mycila - license-maven-plugin - 2.6 - -
header.txt
- - src/** - - - **/README - src/**/.directory - src/**/*.properties - - - 2014 - Morgner UG (haftungsbeschränkt) - -
- - - - format - - - -
-
-
- - - release-sign-artifacts - - - performRelease - true - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.4 - - - sign-artifacts - verify - - sign - - - - - - - - - - - ${project.groupId} - structr-core - ${project.version} - - - junit - junit - 4.11 - test - - - ch.qos.logback - logback-access - 1.1.2 - - - com.jayway.restassured - rest-assured - 2.3.1 - compile - false - - - org.eclipse.jetty - jetty-server - 9.1.4.v20140401 - - - org.eclipse.jetty - jetty-servlets - 9.1.4.v20140401 - - - org.eclipse.jetty - jetty-runner - 9.1.4.v20140401 - - - org.tuckey - urlrewritefilter - 4.0.4 - - - - - GNU General Public License, Version 3 - http://www.gnu.org/licenses/gpl-3.0-standalone.html - - Copyright (C) 2010-2014 Morgner UG (haftungsbeschränkt) <structr@structr.org> - - This file is part of structr <http://structr.org>. - - structr is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - structr is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with structr. If not, see <http://www.gnu.org/licenses/>. - - - - - - https://github.com/structr/structr - scm:git:https://github.com:structr/structr.git - scm:git:git@github.com:structr/structr.git - - - - - sonatype-nexus-staging - Maven Central Staging - https://oss.sonatype.org/service/local/staging/deploy/maven2 - - - sonatype-nexus-snapshots - Maven Central Snapshots - https://oss.sonatype.org/content/repositories/snapshots - - - -
- - - diff --git a/All/Genesis-NP/Genesis#156/old/JsonRestServlet.java b/All/Genesis-NP/Genesis#156/old/JsonRestServlet.java deleted file mode 100755 index 2ff9a4b..0000000 --- a/All/Genesis-NP/Genesis#156/old/JsonRestServlet.java +++ /dev/null @@ -1,984 +0,0 @@ -/** - * Copyright (C) 2010-2014 Morgner UG (haftungsbeschränkt) - * - * This file is part of Structr . - * - * Structr is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * Structr is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with Structr. If not, see . - */ -package org.structr.rest.servlet; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSyntaxException; -import java.io.IOException; -import java.io.Writer; -import java.text.DecimalFormat; -import java.text.DecimalFormatSymbols; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Pattern; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServlet; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.apache.commons.io.IOUtils; -import org.neo4j.kernel.DeadlockDetectedException; -import org.structr.common.PagingHelper; -import org.structr.common.SecurityContext; -import org.structr.common.error.FrameworkException; -import org.structr.core.*; -import org.structr.core.app.App; -import org.structr.core.app.StructrApp; -import org.structr.core.auth.Authenticator; -import org.structr.core.entity.AbstractNode; -import org.structr.core.graph.NodeFactory; -import org.structr.core.graph.Tx; -import org.structr.core.graph.search.SearchCommand; -import org.structr.core.property.PropertyKey; -import org.structr.rest.JsonInputGSONAdapter; -import org.structr.rest.ResourceProvider; -import org.structr.rest.RestMethodResult; -import org.structr.rest.adapter.FrameworkExceptionGSONAdapter; -import org.structr.rest.adapter.ResultGSONAdapter; -import org.structr.rest.resource.Resource; -import org.structr.rest.serialization.StreamingHtmlWriter; -import org.structr.rest.serialization.StreamingJsonWriter; -import org.structr.rest.service.HttpServiceServlet; -import org.structr.rest.service.StructrHttpServiceConfig; -import org.tuckey.web.filters.urlrewrite.utils.StringUtils; - -//~--- classes ---------------------------------------------------------------- - -/** - * Implements the structr REST API. - * - * @author Christian Morgner - */ -public class JsonRestServlet extends HttpServlet implements HttpServiceServlet { - - public static final int DEFAULT_VALUE_PAGE_SIZE = 20; - public static final String DEFAULT_VALUE_SORT_ORDER = "asc"; - public static final String REQUEST_PARAMETER_LOOSE_SEARCH = "loose"; - public static final String REQUEST_PARAMETER_PAGE_NUMBER = "page"; - public static final String REQUEST_PARAMETER_PAGE_SIZE = "pageSize"; - public static final String REQUEST_PARAMETER_OFFSET_ID = "pageStartId"; - public static final String REQUEST_PARAMETER_SORT_KEY = "sort"; - public static final String REQUEST_PARAMETER_SORT_ORDER = "order"; - public static final Set commonRequestParameters = new LinkedHashSet<>(); - private static final Logger logger = Logger.getLogger(JsonRestServlet.class.getName()); - - static { - - commonRequestParameters.add(REQUEST_PARAMETER_LOOSE_SEARCH); - commonRequestParameters.add(REQUEST_PARAMETER_PAGE_NUMBER); - commonRequestParameters.add(REQUEST_PARAMETER_PAGE_SIZE); - commonRequestParameters.add(REQUEST_PARAMETER_OFFSET_ID); - commonRequestParameters.add(REQUEST_PARAMETER_SORT_KEY); - commonRequestParameters.add(REQUEST_PARAMETER_SORT_ORDER); - - // cross reference here, but these need to be added as well.. - commonRequestParameters.add(SearchCommand.DISTANCE_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.LOCATION_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.STREET_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.HOUSE_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.POSTAL_CODE_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.CITY_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.STATE_SEARCH_KEYWORD); - commonRequestParameters.add(SearchCommand.COUNTRY_SEARCH_KEYWORD); - } - - // final fields - private final Map> resourceMap = new LinkedHashMap<>(); - private final StructrHttpServiceConfig config = new StructrHttpServiceConfig(); - - // non-final fields - private Value propertyView = null; - private ThreadLocalGson gson = null; - private boolean indentJson = true; - - //~--- methods -------------------------------------------------------- - - @Override - public StructrHttpServiceConfig getConfig() { - return config; - } - - @Override - public void init() { - - try { - indentJson = Boolean.parseBoolean(StructrApp.getConfigurationValue(Services.JSON_INDENTATION, "true")); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to parse value for {0}: {1}", new Object[] { Services.JSON_INDENTATION, t.getMessage() } ); - } - - - // inject resources - final ResourceProvider provider = config.getResourceProvider(); - if (provider != null) { - - resourceMap.putAll(provider.getResources()); - - } else { - - logger.log(Level.SEVERE, "Unable to initialize JsonRestServlet, no resource provider found. Please check structr.conf for a valid resource provider class."); - } - - // initialize variables - this.propertyView = new ThreadLocalPropertyView(); - this.gson = new ThreadLocalGson(config.getOutputNestingDepth()); - } - - // - @Override - protected void doDelete(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - - SecurityContext securityContext = null; - Authenticator authenticator = null; - RestMethodResult result = null; - Resource resource = null; - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - resource = ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, config.getDefaultIdProperty()), config.getDefaultIdProperty()); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - - tx.success(); - } - - // isolate doDelete - boolean retry = true; - while (retry) { - - try (final Tx tx = app.tx()) { - result = resource.doDelete(); - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - - // isolate write output - try (final Tx tx = app.tx()) { - result.commitResponse(gson.get(), response); - tx.success(); - } - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "JsonSyntaxException in DELETE", jsex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "JsonParseException in DELETE", jpex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + jpex.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in DELETE", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in DELETE: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (IOException t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - @Override - protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - - final boolean returnContent = true; - - doGetOrHead(request, response, returnContent); - } - - @Override - protected void doHead(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - final boolean returnContent = false; - - doGetOrHead(request, response, returnContent); - } - - // - @Override - protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - final SecurityContext securityContext; - final Authenticator authenticator; - final Resource resource; - - RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST); - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - resource = ResourceHelper.applyViewTransformation(request, securityContext, - ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, - config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - tx.success(); - } - - // isolate doOptions - boolean retry = true; - while (retry) { - - try (final Tx tx = app.tx()) { - - result = resource.doOptions(); - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - - // isolate write output - try (final Tx tx = app.tx()) { - result.commitResponse(gson.get(), response); - tx.success(); - } - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "JsonSyntaxException in OPTIONS", jsex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "JsonParseException in OPTIONS", jpex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + jpex.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in OPTIONS", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in OPTIONS: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - // - @Override - protected void doPost(final HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - - final List results = new LinkedList<>(); - final SecurityContext securityContext; - final Authenticator authenticator; - final Resource resource; - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - final String input = IOUtils.toString(request.getReader()); - final IJsonInput jsonInput = cleanAndParseJsonString(app, input); - - if (securityContext != null) { - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - resource = ResourceHelper.applyViewTransformation(request, securityContext, - ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, - config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - tx.success(); - } - - // isolate doPost - boolean retry = true; - while (retry) { - - if (resource.createPostTransaction()) { - - try (final Tx tx = app.tx()) { - - for (JsonInput propertySet : jsonInput.getJsonInputs()) { - - results.add(resource.doPost(convertPropertySetToMap(propertySet))); - } - - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - - } else { - - try { - - for (JsonInput propertySet : jsonInput.getJsonInputs()) { - - results.add(resource.doPost(convertPropertySetToMap(propertySet))); - } - - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - } - - // set default value for property view - propertyView.set(securityContext, config.getDefaultPropertyView()); - - // isolate write output - try (final Tx tx = app.tx()) { - - if (!results.isEmpty()) { - - final RestMethodResult result = results.get(0); - final int resultCount = results.size(); - - if (resultCount > 1) { - - for (final RestMethodResult r : results) { - - final GraphObject objectCreated = r.getContent().get(0); - if (!result.getContent().contains(objectCreated)) { - - result.addContent(objectCreated); - } - - } - - // remove Location header if more than one object was - // written because it may only contain a single URL - result.addHeader("Location", null); - } - - result.commitResponse(gson.get(), response); - - } - - tx.success(); - } - - } else { - - // isolate write output - try (final Tx tx = app.tx()) { - - new RestMethodResult(HttpServletResponse.SC_FORBIDDEN).commitResponse(gson.get(), response); - tx.success(); - } - - } - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "POST: Invalid JSON syntax", jsex.getMessage()); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "Unable to parse JSON string", jpex.getMessage()); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonParseException in POST: " + jpex.getMessage())); - - } catch (UnsupportedOperationException uoe) { - - logger.log(Level.WARNING, "POST not supported"); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "POST not supported: " + uoe.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in POST", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - // - @Override - protected void doPut(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { - - final SecurityContext securityContext; - final Authenticator authenticator; - final Resource resource; - - RestMethodResult result = new RestMethodResult(HttpServletResponse.SC_BAD_REQUEST); - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - final String input = IOUtils.toString(request.getReader()); - final IJsonInput jsonInput = cleanAndParseJsonString(app, input); - - if (securityContext != null) { - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - // evaluate constraint chain - resource = ResourceHelper.applyViewTransformation(request, securityContext, - ResourceHelper.optimizeNestedResourceChain(ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, - config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - tx.success(); - } - - // isolate doPut - boolean retry = true; - while (retry) { - - try (final Tx tx = app.tx()) { - result = resource.doPut(convertPropertySetToMap(jsonInput.getJsonInputs().get(0))); - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - - // isolate write output - try (final Tx tx = app.tx()) { - result.commitResponse(gson.get(), response); - tx.success(); - } - - } else { - - // isolate write output - try (final Tx tx = app.tx()) { - result = new RestMethodResult(HttpServletResponse.SC_FORBIDDEN); - result.commitResponse(gson.get(), response); - tx.success(); - } - - } - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "PUT: Invalid JSON syntax", jsex.getMessage()); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "PUT: Unable to parse JSON string", jpex.getMessage()); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + jpex.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in PUT", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in PUT: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - // - @Override - protected void doTrace(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - -// logRequest("TRACE", request); - response.setContentType("application/json; charset=UTF-8"); - response.setCharacterEncoding("UTF-8"); - - int code = HttpServletResponse.SC_METHOD_NOT_ALLOWED; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "TRACE method not allowed")); - } - - // - - // - - private IJsonInput cleanAndParseJsonString(final App app, final String input) throws FrameworkException { - - IJsonInput jsonInput; - - // isolate input parsing (will include read and write operations) - try (final Tx tx = app.tx()) { - jsonInput = gson.get().fromJson(input, IJsonInput.class); - tx.success(); - } - - if (jsonInput == null) { - - if (StringUtils.isBlank(input)) { - - try (final Tx tx = app.tx()) { - jsonInput = gson.get().fromJson("{}", IJsonInput.class); - tx.success(); - } - - } else { - //throw new JsonParseException("Invalid or empty JSON string, must at least contain {} to be valid!"); - jsonInput = new JsonSingleInput(); - } - } - - return jsonInput; - - } - - private Map convertPropertySetToMap(JsonInput propertySet) { - - if (propertySet != null) { - return propertySet.getAttributes(); - } - - return new LinkedHashMap<>(); - } - - private void doGetOrHead(final HttpServletRequest request, final HttpServletResponse response, final boolean returnContent) throws ServletException, IOException { - - SecurityContext securityContext = null; - Authenticator authenticator = null; - Result result = null; - Resource resource = null; - - try { - - // first thing to do! - request.setCharacterEncoding("UTF-8"); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/json; charset=utf-8"); - - // isolate request authentication in a transaction - try (final Tx tx = StructrApp.getInstance().tx()) { - authenticator = config.getAuthenticator(); - securityContext = authenticator.initializeAndExamineRequest(request, response); - tx.success(); - } - - final App app = StructrApp.getInstance(securityContext); - - // set default value for property view - propertyView.set(securityContext, config.getDefaultPropertyView()); - - // evaluate constraints and measure query time - double queryTimeStart = System.nanoTime(); - - // isolate resource authentication - try (final Tx tx = app.tx()) { - - resource = ResourceHelper.applyViewTransformation(request, securityContext, - ResourceHelper.optimizeNestedResourceChain( - ResourceHelper.parsePath(securityContext, request, resourceMap, propertyView, - config.getDefaultIdProperty()), config.getDefaultIdProperty()), propertyView); - authenticator.checkResourceAccess(securityContext, request, resource.getResourceSignature(), propertyView.get(securityContext)); - tx.success(); - } - - // add sorting & paging - String pageSizeParameter = request.getParameter(REQUEST_PARAMETER_PAGE_SIZE); - String pageParameter = request.getParameter(REQUEST_PARAMETER_PAGE_NUMBER); - String offsetId = request.getParameter(REQUEST_PARAMETER_OFFSET_ID); - String sortOrder = request.getParameter(REQUEST_PARAMETER_SORT_ORDER); - String sortKeyName = request.getParameter(REQUEST_PARAMETER_SORT_KEY); - boolean sortDescending = (sortOrder != null && "desc".equals(sortOrder.toLowerCase())); - int pageSize = Services.parseInt(pageSizeParameter, NodeFactory.DEFAULT_PAGE_SIZE); - int page = Services.parseInt(pageParameter, NodeFactory.DEFAULT_PAGE); - String baseUrl = request.getRequestURI(); - PropertyKey sortKey = null; - - // set sort key - if (sortKeyName != null) { - - Class type = resource.getEntityClass(); - if (type == null) { - - // fallback to default implementation - // if no type can be determined - type = AbstractNode.class; - } - - sortKey = StructrApp.getConfiguration().getPropertyKeyForDatabaseName(type, sortKeyName, false); - } - - // isolate doGet - boolean retry = true; - while (retry) { - - try (final Tx tx = app.tx()) { - result = resource.doGet(sortKey, sortDescending, pageSize, page, offsetId); - tx.success(); - retry = false; - - } catch (DeadlockDetectedException ddex) { - retry = true; - } - } - - if (returnContent) { - - result.setIsCollection(resource.isCollectionResource()); - result.setIsPrimitiveArray(resource.isPrimitiveArray()); - - PagingHelper.addPagingParameter(result, pageSize, page); - - // timing.. - double queryTimeEnd = System.nanoTime(); - - // store property view that will be used to render the results - result.setPropertyView(propertyView.get(securityContext)); - - // allow resource to modify result set - resource.postProcessResultSet(result); - - DecimalFormat decimalFormat = new DecimalFormat("0.000000000", DecimalFormatSymbols.getInstance(Locale.ENGLISH)); - result.setQueryTime(decimalFormat.format((queryTimeEnd - queryTimeStart) / 1000000000.0)); - - String accept = request.getHeader("Accept"); - - if (accept != null && accept.contains("text/html")) { - - final StreamingHtmlWriter htmlStreamer = new StreamingHtmlWriter(this.propertyView, indentJson, config.getOutputNestingDepth()); - - // isolate write output - try (final Tx tx = app.tx()) { - - response.setContentType("text/html; charset=utf-8"); - - try (final Writer writer = response.getWriter()) { - - htmlStreamer.stream(securityContext, writer, result, baseUrl); - writer.append("\n"); // useful newline - } - - tx.success(); - } - - } else { - - final StreamingJsonWriter jsonStreamer = new StreamingJsonWriter(this.propertyView, indentJson, config.getOutputNestingDepth()); - - // isolate write output - try (final Tx tx = app.tx()) { - - response.setContentType("application/json; charset=utf-8"); - try (final Writer writer = response.getWriter()) { - - jsonStreamer.stream(securityContext, writer, result, baseUrl); - writer.append("\n"); // useful newline - } - - tx.success(); - } - - } - } - - response.setStatus(HttpServletResponse.SC_OK); - - } catch (FrameworkException frameworkException) { - - // set status & write JSON output - response.setStatus(frameworkException.getStatus()); - gson.get().toJson(frameworkException, response.getWriter()); - response.getWriter().println(); - - } catch (JsonSyntaxException jsex) { - - logger.log(Level.WARNING, "JsonSyntaxException in GET", jsex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "Json syntax exception in GET: " + jsex.getMessage())); - - } catch (JsonParseException jpex) { - - logger.log(Level.WARNING, "JsonParseException in GET", jpex); - - int code = HttpServletResponse.SC_BAD_REQUEST; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "Parser exception in GET: " + jpex.getMessage())); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Exception in GET", t); - - int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; - - response.setStatus(code); - response.getWriter().append(RestMethodResult.jsonError(code, "Exception in GET: " + t.getMessage())); - - } finally { - - try { - //response.getWriter().flush(); - response.getWriter().close(); - - } catch (Throwable t) { - - logger.log(Level.WARNING, "Unable to flush and close response: {0}", t.getMessage()); - } - - } - } - - // - - // - private class ThreadLocalPropertyView extends ThreadLocal implements Value { - - @Override - protected String initialValue() { - return config.getDefaultPropertyView(); - } - - @Override - public void set(SecurityContext securityContext, String value) { - set(value); - } - - @Override - public String get(SecurityContext securityContext) { - return get(); - } - } - - private class ThreadLocalGson extends ThreadLocal { - - private int outputNestingDepth = 3; - - public ThreadLocalGson(final int outputNestingDepth) { - this.outputNestingDepth = outputNestingDepth; - } - - @Override - protected Gson initialValue() { - - JsonInputGSONAdapter jsonInputAdapter = new JsonInputGSONAdapter(propertyView, config.getDefaultIdProperty()); - ResultGSONAdapter resultGsonAdapter = new ResultGSONAdapter(propertyView, config.getDefaultIdProperty(), outputNestingDepth); - - // create GSON serializer - final GsonBuilder gsonBuilder = new GsonBuilder() - .setPrettyPrinting() - .serializeNulls() - .registerTypeHierarchyAdapter(FrameworkException.class, new FrameworkExceptionGSONAdapter()) - .registerTypeAdapter(IJsonInput.class, jsonInputAdapter) - .registerTypeAdapter(Result.class, resultGsonAdapter); - - - final boolean lenient = Boolean.parseBoolean(StructrApp.getConfigurationValue("json.lenient", "false")); - if (lenient) { - - // Serializes NaN, -Infinity, Infinity, see http://code.google.com/p/google-gson/issues/detail?id=378 - gsonBuilder.serializeSpecialFloatingPointValues(); - - } - - return gsonBuilder.create(); - } - } - // -} diff --git a/All/Genesis-NP/Genesis#156/old/pom.xml b/All/Genesis-NP/Genesis#156/old/pom.xml deleted file mode 100755 index ec2a591..0000000 --- a/All/Genesis-NP/Genesis#156/old/pom.xml +++ /dev/null @@ -1,237 +0,0 @@ - - - 4.0.0 - - - org.structr - structr - 1.1-SNAPSHOT - - - org.structr - structr-rest - jar - 1.1-SNAPSHOT - Structr REST - Structr is an open source framework based on the popular Neo4j graph database. - - - Axel Morgner - am@structr.org - - - Christian Morgner - cm@structr.org - - - http://structr.org - - - structr-gpl30 - UTF-8 - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - true - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - - attach-javadocs - - jar - - - - - - maven-surefire-plugin - 2.16 - - - false - -Xmx1024m -XX:MaxPermSize=256m - classes - 8 - - UTC - - - - - com.mycila - license-maven-plugin - 2.6 - -
header.txt
- - src/** - - - **/README - src/**/.directory - src/**/*.properties - - - 2014 - Morgner UG (haftungsbeschränkt) - -
- - - - format - - - -
-
-
- - - release-sign-artifacts - - - performRelease - true - - - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.4 - - - sign-artifacts - verify - - sign - - - - - - - - - - - ${project.groupId} - structr-core - ${project.version} - - - junit - junit - 4.11 - test - - - ch.qos.logback - logback-access - 1.1.2 - - - com.jayway.restassured - rest-assured - 2.3.1 - compile - false - - - org.eclipse.jetty - jetty-server - 9.1.4.v20140401 - - - org.eclipse.jetty - jetty-servlets - 9.1.4.v20140401 - - - org.eclipse.jetty - jetty-runner - 9.1.4.v20140401 - - - org.tuckey - urlrewritefilter - 4.0.4 - - - - - GNU General Public License, Version 3 - http://www.gnu.org/licenses/gpl-3.0-standalone.html - - Copyright (C) 2010-2014 Morgner UG (haftungsbeschränkt) <structr@structr.org> - - This file is part of structr <http://structr.org>. - - structr is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - structr is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with structr. If not, see <http://www.gnu.org/licenses/>. - - - - - - https://github.com/structr/structr - scm:git:https://github.com:structr/structr.git - scm:git:git@github.com:structr/structr.git - - - - - sonatype-nexus-staging - Maven Central Staging - https://oss.sonatype.org/service/local/staging/deploy/maven2 - - - sonatype-nexus-snapshots - Maven Central Snapshots - https://oss.sonatype.org/content/repositories/snapshots - - - -
- - - diff --git a/All/Genesis-NP/Genesis#156/pair.info b/All/Genesis-NP/Genesis#156/pair.info deleted file mode 100755 index c9d34b4..0000000 --- a/All/Genesis-NP/Genesis#156/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:156 -SATName:Genesis -modifiedFPath:structr-rest/src/main/java/org/structr/rest/servlet/JsonRestServlet.java -comSha:216bcebe23abc4316bb3db917ae98d5dc903ebee -parentComSha:216bcebe23abc4316bb3db917ae98d5dc903ebee^1 -githubUrl:https://github.com/structr/structr -repoName:structr#structr \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#160/comMsg.txt b/All/Genesis-NP/Genesis#160/comMsg.txt deleted file mode 100755 index f6b9db1..0000000 --- a/All/Genesis-NP/Genesis#160/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Set declaring class to avoid NPE in case of validation errors. diff --git a/All/Genesis-NP/Genesis#160/diff.diff b/All/Genesis-NP/Genesis#160/diff.diff deleted file mode 100755 index b1e0981..0000000 --- a/All/Genesis-NP/Genesis#160/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/structr-rest/src/main/java/org/structr/rest/resource/LogResource.java b/structr-rest/src/main/java/org/structr/rest/resource/LogResource.java -index 99032c2..b8f1d84 100644 ---- a/structr-rest/src/main/java/org/structr/rest/resource/LogResource.java -+++ b/structr-rest/src/main/java/org/structr/rest/resource/LogResource.java -@@ -65,0 +66,6 @@ public class LogResource extends Resource { -+ subjectProperty.setDeclaringClass(LogResource.class); -+ objectProperty.setDeclaringClass(LogResource.class); -+ actionProperty.setDeclaringClass(LogResource.class); -+ messageProperty.setDeclaringClass(LogResource.class); -+ timestampProperty.setDeclaringClass(LogResource.class); -+ diff --git a/All/Genesis-NP/Genesis#160/new/LogResource.java b/All/Genesis-NP/Genesis#160/new/LogResource.java deleted file mode 100755 index b8f1d84..0000000 --- a/All/Genesis-NP/Genesis#160/new/LogResource.java +++ /dev/null @@ -1,351 +0,0 @@ -package org.structr.rest.resource; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.nio.channels.FileChannel; -import java.nio.charset.Charset; -import java.nio.file.DirectoryStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Collections; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.logging.Logger; -import javax.servlet.http.HttpServletRequest; -import org.apache.commons.lang3.StringUtils; -import org.neo4j.helpers.Predicate; -import org.structr.common.GraphObjectComparator; -import org.structr.common.SecurityContext; -import org.structr.common.error.EmptyPropertyToken; -import org.structr.common.error.ErrorBuffer; -import org.structr.common.error.FrameworkException; -import org.structr.core.GraphObject; -import org.structr.core.GraphObjectMap; -import org.structr.core.Result; -import org.structr.core.Services; -import org.structr.core.app.Query; -import org.structr.core.app.StructrApp; -import org.structr.core.property.ISO8601DateProperty; -import org.structr.core.property.Property; -import org.structr.core.property.PropertyKey; -import org.structr.core.property.StringProperty; -import org.structr.rest.RestMethodResult; - -/** - * - * @author Christian Morgner - */ -public class LogResource extends Resource { - - private static final Logger logger = Logger.getLogger(LogResource.class.getName()); - - private static final String SUBJECTS = "/s/"; - private static final String OBJECTS = "/o/"; - - private static final Property subjectProperty = new StringProperty("subject"); - private static final Property objectProperty = new StringProperty("object"); - private static final Property actionProperty = new StringProperty("action"); - private static final Property messageProperty = new StringProperty("message"); - private static final ISO8601DateProperty timestampProperty = new ISO8601DateProperty("timestamp"); - - public static final String LOG_RESOURCE_URI = "log"; - - @Override - public Resource tryCombineWith(Resource next) throws FrameworkException { - return null; - } - - @Override - public boolean checkAndConfigure(String part, SecurityContext securityContext, HttpServletRequest request) throws FrameworkException { - - subjectProperty.setDeclaringClass(LogResource.class); - objectProperty.setDeclaringClass(LogResource.class); - actionProperty.setDeclaringClass(LogResource.class); - messageProperty.setDeclaringClass(LogResource.class); - timestampProperty.setDeclaringClass(LogResource.class); - - this.securityContext = securityContext; - this.securityContext.setRequest(request); - - return LOG_RESOURCE_URI.equals(part); - } - - @Override - public String getUriPart() { - return LOG_RESOURCE_URI; - } - - @Override - public Class getEntityClass() { - return GraphObject.class; - } - - @Override - public String getResourceSignature() { - return "Log"; - } - - @Override - public boolean isCollectionResource() throws FrameworkException { - return true; - } - - @Override - public Result doGet(PropertyKey sortKey, boolean sortDescending, int pageSize, int page, String offsetId) throws FrameworkException { - - final HttpServletRequest request = securityContext.getRequest(); - if (request != null) { - - final String filesPath = Services.getInstance().getConfigurationValue(Services.FILES_PATH); - final String subjectId = request.getParameter(subjectProperty.jsonName()); - final String objectId = request.getParameter(objectProperty.jsonName()); - final String action = request.getParameter(actionProperty.jsonName()); - final List files = new LinkedList<>(); - - boolean inverse = false; - - if (StringUtils.isNotEmpty(subjectId) && StringUtils.isNotEmpty(objectId)) { - - final String fileName = mergeIds(subjectId, objectId); - final String path = getDirectoryPath(fileName, 8); - final Path filePath = new File(filesPath + SUBJECTS + path + fileName).toPath(); - - if (Files.exists(filePath)) { - files.add(filePath); - } - - - } else if (StringUtils.isNotEmpty(subjectId) && StringUtils.isEmpty(objectId)) { - - final String path = getDirectoryPath(subjectId, 8); - final Path directoryPath = new File(filesPath + SUBJECTS + path).toPath(); - - try (final DirectoryStream stream = Files.newDirectoryStream(directoryPath, subjectId + "????????????????????????????????")) { - - for (final Path p : stream) { - files.add(p); - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - - } else if (StringUtils.isEmpty(subjectId) && StringUtils.isNotEmpty(objectId)) { - - inverse = true; - - final String path = getDirectoryPath(objectId, 8); - final Path directoryPath = new File(filesPath + OBJECTS + path).toPath(); - - try (final DirectoryStream stream = Files.newDirectoryStream(directoryPath, objectId + "????????????????????????????????")) { - - for (final Path p : stream) { - files.add(p); - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - final List entries = new LinkedList<>(); - final Predicate datePredicate = getTimestampPredicate(); - - for (final Path path : files) { - - try (final BufferedReader reader = Files.newBufferedReader(path, Charset.forName("utf-8"))) { - - final String fileName = path.getFileName().toString(); - String pathSubjectId = inverse ? fileName.substring(33, 64) : fileName.substring(0, 32); - String pathObjectId = inverse ? fileName.substring(0, 32) : fileName.substring(33, 64); - - String line = reader.readLine(); - while (line != null) { - - try { - - final int pos0 = line.indexOf(","); - final int pos1 = line.indexOf(",", pos0+1); - - final String part0 = line.substring(0, pos0); - final String part1 = line.substring(pos0+1, pos1); - final String part2 = line.substring(pos1+1); - - final Date date = new Date(Long.valueOf(part0)); - final String entryAction = part1; - final String entryMessage = part2; - - // action present or matching? - if (action == null || action.equals(entryAction)) { - - final GraphObjectMap map = new GraphObjectMap(); - map.put(subjectProperty, pathSubjectId); - map.put(objectProperty, pathObjectId); - map.put(actionProperty, entryAction); - map.put(timestampProperty, date); - map.put(messageProperty, entryMessage); - - // date predicate present? - if (date == null || datePredicate.accept(map)) { - entries.add(map); - } - } - - } catch (Throwable ignore) {} - - line = reader.readLine(); - } - - } catch (IOException ioex) {} - } - - // sort result - Collections.sort(entries, new GraphObjectComparator(timestampProperty, false)); - - return new Result(entries, entries.size(), true, true); - } - - // no request object, this is fatal - throw new FrameworkException(500, "No request object present, aborting."); - } - - @Override - public RestMethodResult doPost(Map propertySet) throws FrameworkException { - - final HttpServletRequest request = securityContext.getRequest(); - if (request != null) { - - final String filesPath = Services.getInstance().getConfigurationValue(Services.FILES_PATH); - final String subjectId = (String)propertySet.get(subjectProperty.jsonName()); - final String objectId = (String)propertySet.get(objectProperty.jsonName()); - final String action = (String)propertySet.get(actionProperty.jsonName()); - final String message = (String)propertySet.get(messageProperty.jsonName()); - - if (subjectId != null && objectId != null && action != null) { - - try { - - final StringBuilder data = new StringBuilder(); - data.append(System.currentTimeMillis()); - data.append(","); - data.append(action); - data.append(","); - data.append(message); - data.append("\n"); - - // write data and create link - final Path actualPath = write(filesPath + SUBJECTS, mergeIds(subjectId, objectId), data.toString()); - link(filesPath + OBJECTS, mergeIds(objectId, subjectId), actualPath); - - return new RestMethodResult(200); - - } catch (IOException ioex) { - - ioex.printStackTrace(); - throw new FrameworkException(500, ioex.getMessage()); - } - - } else { - - final ErrorBuffer errorBuffer = new ErrorBuffer(); - - if (StringUtils.isEmpty(subjectId)) { - errorBuffer.add("LogFile", new EmptyPropertyToken(subjectProperty)); - } - - if (StringUtils.isEmpty(objectId)) { - errorBuffer.add("LogFile", new EmptyPropertyToken(objectProperty)); - } - - if (StringUtils.isEmpty(action)) { - errorBuffer.add("LogFile", new EmptyPropertyToken(actionProperty)); - } - - throw new FrameworkException(422, errorBuffer); - } - } - - // no request object, this is fatal - throw new FrameworkException(500, "No request object present, aborting."); - } - - private Path write(final String basePath, final String fileName, final String data) throws IOException { - - final String path = getDirectoryPath(fileName, 8); - final Path directoryPath = new File(basePath + path).toPath(); - final Path filePath = new File(basePath + path + fileName).toPath(); - - if (!Files.exists(filePath)) { - Files.createDirectories(directoryPath); - } - - final FileOutputStream fos = new FileOutputStream(filePath.toString(), true); - final FileChannel channel = fos.getChannel(); - - channel.write(ByteBuffer.wrap(data.getBytes())); - - fos.flush(); - fos.close(); - - return filePath; - } - - private void link(final String basePath, final String fileName, final Path existing) throws IOException { - - final String path = getDirectoryPath(fileName, 8); - final Path directoryPath = new File(basePath + path).toPath(); - final Path filePath = new File(basePath + path + fileName).toPath(); - - if (Files.notExists(filePath)) { - Files.createDirectories(directoryPath); - } - - if (Files.notExists(filePath)) { - Files.createLink(filePath, existing); - } - } - - private String mergeIds(final String id1, final String id2) { - - final StringBuilder buf = new StringBuilder(); - - buf.append(id1); - buf.append(id2); - - return buf.toString(); - } - - private String getDirectoryPath(final String uuid, final int depth) { - - final StringBuilder buf = new StringBuilder(); - - if (StringUtils.isNotEmpty(uuid) && uuid.length() > depth) { - - for (int i=0; i subjectProperty = new StringProperty("subject"); - private static final Property objectProperty = new StringProperty("object"); - private static final Property actionProperty = new StringProperty("action"); - private static final Property messageProperty = new StringProperty("message"); - private static final ISO8601DateProperty timestampProperty = new ISO8601DateProperty("timestamp"); - - public static final String LOG_RESOURCE_URI = "log"; - - @Override - public Resource tryCombineWith(Resource next) throws FrameworkException { - return null; - } - - @Override - public boolean checkAndConfigure(String part, SecurityContext securityContext, HttpServletRequest request) throws FrameworkException { - - this.securityContext = securityContext; - this.securityContext.setRequest(request); - - return LOG_RESOURCE_URI.equals(part); - } - - @Override - public String getUriPart() { - return LOG_RESOURCE_URI; - } - - @Override - public Class getEntityClass() { - return GraphObject.class; - } - - @Override - public String getResourceSignature() { - return "Log"; - } - - @Override - public boolean isCollectionResource() throws FrameworkException { - return true; - } - - @Override - public Result doGet(PropertyKey sortKey, boolean sortDescending, int pageSize, int page, String offsetId) throws FrameworkException { - - final HttpServletRequest request = securityContext.getRequest(); - if (request != null) { - - final String filesPath = Services.getInstance().getConfigurationValue(Services.FILES_PATH); - final String subjectId = request.getParameter(subjectProperty.jsonName()); - final String objectId = request.getParameter(objectProperty.jsonName()); - final String action = request.getParameter(actionProperty.jsonName()); - final List files = new LinkedList<>(); - - boolean inverse = false; - - if (StringUtils.isNotEmpty(subjectId) && StringUtils.isNotEmpty(objectId)) { - - final String fileName = mergeIds(subjectId, objectId); - final String path = getDirectoryPath(fileName, 8); - final Path filePath = new File(filesPath + SUBJECTS + path + fileName).toPath(); - - if (Files.exists(filePath)) { - files.add(filePath); - } - - - } else if (StringUtils.isNotEmpty(subjectId) && StringUtils.isEmpty(objectId)) { - - final String path = getDirectoryPath(subjectId, 8); - final Path directoryPath = new File(filesPath + SUBJECTS + path).toPath(); - - try (final DirectoryStream stream = Files.newDirectoryStream(directoryPath, subjectId + "????????????????????????????????")) { - - for (final Path p : stream) { - files.add(p); - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - - } else if (StringUtils.isEmpty(subjectId) && StringUtils.isNotEmpty(objectId)) { - - inverse = true; - - final String path = getDirectoryPath(objectId, 8); - final Path directoryPath = new File(filesPath + OBJECTS + path).toPath(); - - try (final DirectoryStream stream = Files.newDirectoryStream(directoryPath, objectId + "????????????????????????????????")) { - - for (final Path p : stream) { - files.add(p); - } - - } catch (IOException ioex) { - ioex.printStackTrace(); - } - } - - final List entries = new LinkedList<>(); - final Predicate datePredicate = getTimestampPredicate(); - - for (final Path path : files) { - - try (final BufferedReader reader = Files.newBufferedReader(path, Charset.forName("utf-8"))) { - - final String fileName = path.getFileName().toString(); - String pathSubjectId = inverse ? fileName.substring(33, 64) : fileName.substring(0, 32); - String pathObjectId = inverse ? fileName.substring(0, 32) : fileName.substring(33, 64); - - String line = reader.readLine(); - while (line != null) { - - try { - - final int pos0 = line.indexOf(","); - final int pos1 = line.indexOf(",", pos0+1); - - final String part0 = line.substring(0, pos0); - final String part1 = line.substring(pos0+1, pos1); - final String part2 = line.substring(pos1+1); - - final Date date = new Date(Long.valueOf(part0)); - final String entryAction = part1; - final String entryMessage = part2; - - // action present or matching? - if (action == null || action.equals(entryAction)) { - - final GraphObjectMap map = new GraphObjectMap(); - map.put(subjectProperty, pathSubjectId); - map.put(objectProperty, pathObjectId); - map.put(actionProperty, entryAction); - map.put(timestampProperty, date); - map.put(messageProperty, entryMessage); - - // date predicate present? - if (date == null || datePredicate.accept(map)) { - entries.add(map); - } - } - - } catch (Throwable ignore) {} - - line = reader.readLine(); - } - - } catch (IOException ioex) {} - } - - // sort result - Collections.sort(entries, new GraphObjectComparator(timestampProperty, false)); - - return new Result(entries, entries.size(), true, true); - } - - // no request object, this is fatal - throw new FrameworkException(500, "No request object present, aborting."); - } - - @Override - public RestMethodResult doPost(Map propertySet) throws FrameworkException { - - final HttpServletRequest request = securityContext.getRequest(); - if (request != null) { - - final String filesPath = Services.getInstance().getConfigurationValue(Services.FILES_PATH); - final String subjectId = (String)propertySet.get(subjectProperty.jsonName()); - final String objectId = (String)propertySet.get(objectProperty.jsonName()); - final String action = (String)propertySet.get(actionProperty.jsonName()); - final String message = (String)propertySet.get(messageProperty.jsonName()); - - if (subjectId != null && objectId != null && action != null) { - - try { - - final StringBuilder data = new StringBuilder(); - data.append(System.currentTimeMillis()); - data.append(","); - data.append(action); - data.append(","); - data.append(message); - data.append("\n"); - - // write data and create link - final Path actualPath = write(filesPath + SUBJECTS, mergeIds(subjectId, objectId), data.toString()); - link(filesPath + OBJECTS, mergeIds(objectId, subjectId), actualPath); - - return new RestMethodResult(200); - - } catch (IOException ioex) { - - ioex.printStackTrace(); - throw new FrameworkException(500, ioex.getMessage()); - } - - } else { - - final ErrorBuffer errorBuffer = new ErrorBuffer(); - - if (StringUtils.isEmpty(subjectId)) { - errorBuffer.add("LogFile", new EmptyPropertyToken(subjectProperty)); - } - - if (StringUtils.isEmpty(objectId)) { - errorBuffer.add("LogFile", new EmptyPropertyToken(objectProperty)); - } - - if (StringUtils.isEmpty(action)) { - errorBuffer.add("LogFile", new EmptyPropertyToken(actionProperty)); - } - - throw new FrameworkException(422, errorBuffer); - } - } - - // no request object, this is fatal - throw new FrameworkException(500, "No request object present, aborting."); - } - - private Path write(final String basePath, final String fileName, final String data) throws IOException { - - final String path = getDirectoryPath(fileName, 8); - final Path directoryPath = new File(basePath + path).toPath(); - final Path filePath = new File(basePath + path + fileName).toPath(); - - if (!Files.exists(filePath)) { - Files.createDirectories(directoryPath); - } - - final FileOutputStream fos = new FileOutputStream(filePath.toString(), true); - final FileChannel channel = fos.getChannel(); - - channel.write(ByteBuffer.wrap(data.getBytes())); - - fos.flush(); - fos.close(); - - return filePath; - } - - private void link(final String basePath, final String fileName, final Path existing) throws IOException { - - final String path = getDirectoryPath(fileName, 8); - final Path directoryPath = new File(basePath + path).toPath(); - final Path filePath = new File(basePath + path + fileName).toPath(); - - if (Files.notExists(filePath)) { - Files.createDirectories(directoryPath); - } - - if (Files.notExists(filePath)) { - Files.createLink(filePath, existing); - } - } - - private String mergeIds(final String id1, final String id2) { - - final StringBuilder buf = new StringBuilder(); - - buf.append(id1); - buf.append(id2); - - return buf.toString(); - } - - private String getDirectoryPath(final String uuid, final int depth) { - - final StringBuilder buf = new StringBuilder(); - - if (StringUtils.isNotEmpty(uuid) && uuid.length() > depth) { - - for (int i=0; i. - * - * Structr is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * Structr is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with Structr. If not, see . - */ -package org.structr.websocket.command; - -import org.structr.common.SecurityContext; -import org.structr.common.error.FrameworkException; -import org.structr.core.entity.AbstractNode; -import org.structr.websocket.message.MessageBuilder; -import org.structr.websocket.message.WebSocketMessage; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.structr.core.GraphObject; -import org.structr.core.app.App; -import org.structr.core.app.StructrApp; -import org.structr.core.graph.NodeInterface; -import org.structr.core.property.PropertyMap; -import org.structr.dynamic.File; -import org.structr.schema.SchemaHelper; -import org.structr.web.entity.FileBase; -import org.structr.websocket.StructrWebSocket; - -//~--- classes ---------------------------------------------------------------- - -/** - * - * @author Christian Morgner - */ -public class CreateCommand extends AbstractCommand { - - private static final Logger logger = Logger.getLogger(CreateCommand.class.getName()); - - static { - - StructrWebSocket.addCommand(CreateCommand.class); - - } - - //~--- methods -------------------------------------------------------- - - @Override - public void processMessage(final WebSocketMessage webSocketData) { - - final SecurityContext securityContext = getWebSocket().getSecurityContext(); - final App app = StructrApp.getInstance(securityContext); - - Map nodeData = webSocketData.getNodeData(); - - try { - - final PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, nodeData); - Class type = SchemaHelper.getEntityClassForRawType(properties.get(AbstractNode.type)); - final NodeInterface newNode = app.create(type, properties); - - // check for File node and store in WebSocket to receive chunks - if (newNode instanceof FileBase) { - - long size = (Long) webSocketData.getNodeData().get("size"); - String contentType = (String) webSocketData.getNodeData().get("contentType"); - String name = (String) webSocketData.getNodeData().get("name"); - - File fileNode = (File) newNode; - String uuid = newNode.getProperty(GraphObject.id); - - fileNode.setProperty(File.relativeFilePath, File.getDirectoryPath(uuid) + "/" + uuid); - fileNode.setProperty(File.size, size); - fileNode.setProperty(File.contentType, contentType); - fileNode.setProperty(AbstractNode.name, name); - - getWebSocket().createFileUploadHandler(fileNode); - - } - - - } catch (FrameworkException fex) { - - logger.log(Level.WARNING, "Could not create node.", fex); - getWebSocket().send(MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(), true); - - } - } - - //~--- get methods ---------------------------------------------------- - - @Override - public String getCommand() { - return "CREATE"; - } -} diff --git a/All/Genesis-NP/Genesis#163/old/CreateCommand.java b/All/Genesis-NP/Genesis#163/old/CreateCommand.java deleted file mode 100755 index 4b95ad4..0000000 --- a/All/Genesis-NP/Genesis#163/old/CreateCommand.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * Copyright (C) 2010-2014 Morgner UG (haftungsbeschränkt) - * - * This file is part of Structr . - * - * Structr is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * Structr is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with Structr. If not, see . - */ -package org.structr.websocket.command; - -import org.structr.common.SecurityContext; -import org.structr.common.error.FrameworkException; -import org.structr.core.entity.AbstractNode; -import org.structr.websocket.message.MessageBuilder; -import org.structr.websocket.message.WebSocketMessage; - -//~--- JDK imports ------------------------------------------------------------ - -import java.util.Map; -import java.util.logging.Level; -import java.util.logging.Logger; -import org.structr.core.GraphObject; -import org.structr.core.app.App; -import org.structr.core.app.StructrApp; -import org.structr.core.graph.NodeInterface; -import org.structr.core.property.PropertyMap; -import org.structr.dynamic.File; -import org.structr.schema.SchemaHelper; -import org.structr.websocket.StructrWebSocket; - -//~--- classes ---------------------------------------------------------------- - -/** - * - * @author Christian Morgner - */ -public class CreateCommand extends AbstractCommand { - - private static final Logger logger = Logger.getLogger(CreateCommand.class.getName()); - - static { - - StructrWebSocket.addCommand(CreateCommand.class); - - } - - //~--- methods -------------------------------------------------------- - - @Override - public void processMessage(final WebSocketMessage webSocketData) { - - final SecurityContext securityContext = getWebSocket().getSecurityContext(); - final App app = StructrApp.getInstance(securityContext); - - Map nodeData = webSocketData.getNodeData(); - - try { - - final PropertyMap properties = PropertyMap.inputTypeToJavaType(securityContext, nodeData); - Class type = SchemaHelper.getEntityClassForRawType(properties.get(AbstractNode.type)); - final NodeInterface newNode = app.create(type, properties); - - // check for File node and store in WebSocket to receive chunks - if (newNode instanceof File) { - - long size = (Long) webSocketData.getNodeData().get("size"); - String contentType = (String) webSocketData.getNodeData().get("contentType"); - String name = (String) webSocketData.getNodeData().get("name"); - - File fileNode = (File) newNode; - String uuid = newNode.getProperty(GraphObject.id); - - fileNode.setProperty(File.relativeFilePath, File.getDirectoryPath(uuid) + "/" + uuid); - fileNode.setProperty(File.size, size); - fileNode.setProperty(File.contentType, contentType); - fileNode.setProperty(AbstractNode.name, name); - - getWebSocket().createFileUploadHandler(fileNode); - - } - - - } catch (FrameworkException fex) { - - logger.log(Level.WARNING, "Could not create node.", fex); - getWebSocket().send(MessageBuilder.status().code(fex.getStatus()).message(fex.getMessage()).build(), true); - - } - } - - //~--- get methods ---------------------------------------------------- - - @Override - public String getCommand() { - return "CREATE"; - } -} diff --git a/All/Genesis-NP/Genesis#163/pair.info b/All/Genesis-NP/Genesis#163/pair.info deleted file mode 100755 index b4c93a0..0000000 --- a/All/Genesis-NP/Genesis#163/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:163 -SATName:Genesis -modifiedFPath:structr-ui/src/main/java/org/structr/websocket/command/CreateCommand.java -comSha:bbad885e035831a6fbf1f7b15d325d68b1f40681 -parentComSha:bbad885e035831a6fbf1f7b15d325d68b1f40681^1 -githubUrl:https://github.com/structr/structr -repoName:structr#structr \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#17/comMsg.txt b/All/Genesis-NP/Genesis#17/comMsg.txt deleted file mode 100755 index 20f6cb0..0000000 --- a/All/Genesis-NP/Genesis#17/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Prevent NPE if ref can't be resolved when executing ReflogCommand diff --git a/All/Genesis-NP/Genesis#17/diff.diff b/All/Genesis-NP/Genesis#17/diff.diff deleted file mode 100755 index 42f8e5d..0000000 --- a/All/Genesis-NP/Genesis#17/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/api/ReflogCommand.java b/org.eclipse.jgit/src/org/eclipse/jgit/api/ReflogCommand.java -index 8cd78ae..4536af1 100644 ---- a/org.eclipse.jgit/src/org/eclipse/jgit/api/ReflogCommand.java -+++ b/org.eclipse.jgit/src/org/eclipse/jgit/api/ReflogCommand.java -@@ -50,0 +51 @@ -+import org.eclipse.jgit.api.errors.RefNotFoundException; -@@ -99,0 +101,3 @@ public ReflogCommand setRef(String ref) { -+ if (reader == null) -+ throw new RefNotFoundException(MessageFormat.format( -+ JGitText.get().refNotResolved, ref)); diff --git a/All/Genesis-NP/Genesis#17/new/ReflogCommand.java b/All/Genesis-NP/Genesis#17/new/ReflogCommand.java deleted file mode 100755 index 4536af1..0000000 --- a/All/Genesis-NP/Genesis#17/new/ReflogCommand.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright (C) 2011, Chris Aniszczyk - * and other copyright owners as documented in the project's IP log. - * - * This program and the accompanying materials are made available - * under the terms of the Eclipse Distribution License v1.0 which - * accompanies this distribution, is reproduced below, and is - * available at http://www.eclipse.org/org/documents/edl-v10.php - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or - * without modification, are permitted provided that the following - * conditions are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * - Neither the name of the Eclipse Foundation, Inc. nor the - * names of its contributors may be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.eclipse.jgit.api; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Collection; - -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.api.errors.InvalidRefNameException; -import org.eclipse.jgit.api.errors.RefNotFoundException; -import org.eclipse.jgit.internal.JGitText; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ReflogEntry; -import org.eclipse.jgit.lib.ReflogReader; -import org.eclipse.jgit.lib.Repository; - -/** - * The reflog command - * - * @see Git documentation about reflog - */ -public class ReflogCommand extends GitCommand> { - - private String ref = Constants.HEAD; - - /** - * @param repo - */ - public ReflogCommand(Repository repo) { - super(repo); - } - - /** - * The ref used for the reflog operation. If no ref is set, the default - * value of HEAD will be used. - * - * @param ref - * @return {@code this} - */ - public ReflogCommand setRef(String ref) { - checkCallable(); - this.ref = ref; - return this; - } - - /** - * Run the reflog command - * - * @throws GitAPIException - * @throws InvalidRefNameException - */ - public Collection call() throws GitAPIException, - InvalidRefNameException { - checkCallable(); - - try { - ReflogReader reader = repo.getReflogReader(ref); - if (reader == null) - throw new RefNotFoundException(MessageFormat.format( - JGitText.get().refNotResolved, ref)); - return reader.getReverseEntries(); - } catch (IOException e) { - throw new InvalidRefNameException(MessageFormat.format( - JGitText.get().cannotRead, ref), e); - } - } - -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#17/old/ReflogCommand.java b/All/Genesis-NP/Genesis#17/old/ReflogCommand.java deleted file mode 100755 index 8cd78ae..0000000 --- a/All/Genesis-NP/Genesis#17/old/ReflogCommand.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2011, Chris Aniszczyk - * and other copyright owners as documented in the project's IP log. - * - * This program and the accompanying materials are made available - * under the terms of the Eclipse Distribution License v1.0 which - * accompanies this distribution, is reproduced below, and is - * available at http://www.eclipse.org/org/documents/edl-v10.php - * - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or - * without modification, are permitted provided that the following - * conditions are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above - * copyright notice, this list of conditions and the following - * disclaimer in the documentation and/or other materials provided - * with the distribution. - * - * - Neither the name of the Eclipse Foundation, Inc. nor the - * names of its contributors may be used to endorse or promote - * products derived from this software without specific prior - * written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND - * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, - * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES - * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, - * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT - * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, - * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ -package org.eclipse.jgit.api; - -import java.io.IOException; -import java.text.MessageFormat; -import java.util.Collection; - -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.api.errors.InvalidRefNameException; -import org.eclipse.jgit.internal.JGitText; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ReflogEntry; -import org.eclipse.jgit.lib.ReflogReader; -import org.eclipse.jgit.lib.Repository; - -/** - * The reflog command - * - * @see Git documentation about reflog - */ -public class ReflogCommand extends GitCommand> { - - private String ref = Constants.HEAD; - - /** - * @param repo - */ - public ReflogCommand(Repository repo) { - super(repo); - } - - /** - * The ref used for the reflog operation. If no ref is set, the default - * value of HEAD will be used. - * - * @param ref - * @return {@code this} - */ - public ReflogCommand setRef(String ref) { - checkCallable(); - this.ref = ref; - return this; - } - - /** - * Run the reflog command - * - * @throws GitAPIException - * @throws InvalidRefNameException - */ - public Collection call() throws GitAPIException, - InvalidRefNameException { - checkCallable(); - - try { - ReflogReader reader = repo.getReflogReader(ref); - return reader.getReverseEntries(); - } catch (IOException e) { - throw new InvalidRefNameException(MessageFormat.format( - JGitText.get().cannotRead, ref), e); - } - } - -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#17/pair.info b/All/Genesis-NP/Genesis#17/pair.info deleted file mode 100755 index 921774f..0000000 --- a/All/Genesis-NP/Genesis#17/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:17 -SATName:Genesis -modifiedFPath:org.eclipse.jgit/src/org/eclipse/jgit/api/ReflogCommand.java -comSha:a24a99a13dc7bc256c9edc9703bc4a9d28b33ce7 -parentComSha:a24a99a13dc7bc256c9edc9703bc4a9d28b33ce7^1 -githubUrl:https://github.com/eclipse/jgit -repoName:eclipse#jgit \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#180/comMsg.txt b/All/Genesis-NP/Genesis#180/comMsg.txt deleted file mode 100755 index 0a8cc23..0000000 --- a/All/Genesis-NP/Genesis#180/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix NPE diff --git a/All/Genesis-NP/Genesis#180/diff.diff b/All/Genesis-NP/Genesis#180/diff.diff deleted file mode 100755 index 9444765..0000000 --- a/All/Genesis-NP/Genesis#180/diff.diff +++ /dev/null @@ -1,24 +0,0 @@ -diff --git a/job/src/main/java/com/kylinolap/job/cmd/JavaHadoopCmdOutput.java b/job/src/main/java/com/kylinolap/job/cmd/JavaHadoopCmdOutput.java -index 20dd9dd..c3f9236 100644 ---- a/job/src/main/java/com/kylinolap/job/cmd/JavaHadoopCmdOutput.java -+++ b/job/src/main/java/com/kylinolap/job/cmd/JavaHadoopCmdOutput.java -@@ -20,0 +21 @@ import java.util.Map; -+import org.apache.hadoop.mapreduce.Counters; -@@ -162,2 +163,9 @@ public class JavaHadoopCmdOutput implements ICommandOutput { -- this.output.append(job.getCounters().toString()).append("\n"); -- log.debug(job.getCounters().toString()); -+ Counters counters = job.getCounters(); -+ if (counters == null) { -+ String errorMsg = "no counters for job " + mrJobID; -+ log.warn(errorMsg); -+ output.append(errorMsg); -+ return; -+ } -+ this.output.append(counters.toString()).append("\n"); -+ log.debug(counters.toString()); -@@ -169 +177 @@ public class JavaHadoopCmdOutput implements ICommandOutput { -- long mapInputRecords = job.getCounters().findCounter(TaskCounter.MAP_INPUT_RECORDS).getValue(); -+ long mapInputRecords = counters.findCounter(TaskCounter.MAP_INPUT_RECORDS).getValue(); -@@ -171 +179 @@ public class JavaHadoopCmdOutput implements ICommandOutput { -- long hdfsBytesWritten = job.getCounters().findCounter("FileSystemCounters", "HDFS_BYTES_WRITTEN").getValue(); -+ long hdfsBytesWritten = counters.findCounter("FileSystemCounters", "HDFS_BYTES_WRITTEN").getValue(); diff --git a/All/Genesis-NP/Genesis#180/new/JavaHadoopCmdOutput.java b/All/Genesis-NP/Genesis#180/new/JavaHadoopCmdOutput.java deleted file mode 100755 index c3f9236..0000000 --- a/All/Genesis-NP/Genesis#180/new/JavaHadoopCmdOutput.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2013-2014 eBay Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.kylinolap.job.cmd; - -import java.util.Map; - -import org.apache.hadoop.mapreduce.Counters; -import org.apache.hadoop.mapreduce.TaskCounter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.kylinolap.common.KylinConfig; -import com.kylinolap.job.JobDAO; -import com.kylinolap.job.JobInstance; -import com.kylinolap.job.JobInstance.JobStep; -import com.kylinolap.job.constant.JobStepStatusEnum; -import com.kylinolap.job.engine.JobEngineConfig; -import com.kylinolap.job.hadoop.AbstractHadoopJob; -import com.kylinolap.job.tools.HadoopStatusChecker; - -/** - * @author xduo - * - */ -public class JavaHadoopCmdOutput implements ICommandOutput { - - protected static final Logger log = LoggerFactory.getLogger(JavaHadoopCmdOutput.class); - - protected StringBuilder output; - protected int exitCode; - protected JobStepStatusEnum status; - private final KylinConfig config; - private final String jobInstanceID; - private final int jobStepID; - private final String yarnUrl; - private final AbstractHadoopJob job; - private String mrJobID = null; - private String trackUrl = null; - private boolean isAsync; - - public JavaHadoopCmdOutput(String jobInstanceID, int jobStepID, JobEngineConfig engineConfig, AbstractHadoopJob job, boolean isAsync) { - super(); - this.config = engineConfig.getConfig(); - this.yarnUrl = engineConfig.getYarnStatusServiceUrl(); - this.jobInstanceID = jobInstanceID; - this.jobStepID = jobStepID; - this.job = job; - this.isAsync = isAsync; - - init(); - } - - @Override - public void setStatus(JobStepStatusEnum status) { - this.status = status; - } - - @Override - public JobStepStatusEnum getStatus() { - if (this.isAsync) { - if (this.status == JobStepStatusEnum.ERROR) { - return status; - } - - if (null == this.mrJobID || null == this.trackUrl) { - updateHadoopJobInfo(); - } - - status = new HadoopStatusChecker(this.yarnUrl, this.mrJobID, output).checkStatus(); - - if (this.status.isComplete()) { - updateJobCounter(); - } - } else { - status = (this.exitCode == 0) ? JobStepStatusEnum.FINISHED : JobStepStatusEnum.ERROR; - } - - return status; - } - - @Override - public void appendOutput(String message) { - log.debug(message); - output.append(message).append("\n"); - } - - @Override - public String getOutput() { - return output.toString(); - } - - @Override - public void setExitCode(int exitCode) { - this.exitCode = exitCode; - } - - @Override - public int getExitCode() { - return exitCode; - } - - @Override - public void reset() { - init(); - } - - private void init() { - output = new StringBuilder(); - exitCode = -1; - status = JobStepStatusEnum.NEW; - } - - /** - * @param jobStatus - */ - private void updateHadoopJobInfo() { - try { - Map jobInfo = job.getInfo(); - - JobDAO jobDAO = JobDAO.getInstance(config); - JobInstance jobInstance = jobDAO.getJob(jobInstanceID); - JobStep jobStep = jobInstance.getSteps().get(jobStepID); - boolean hasChange = false; - - if (null == this.mrJobID && jobInfo.containsKey(JobInstance.MR_JOB_ID)) { - this.mrJobID = jobInfo.get(JobInstance.MR_JOB_ID); - jobStep.putInfo(JobInstance.MR_JOB_ID, this.mrJobID); - output.append("Get job id " + this.mrJobID).append("\n"); - hasChange = true; - } - - if (null == this.trackUrl && jobInfo.containsKey(JobInstance.YARN_APP_URL)) { - this.trackUrl = jobInfo.get(JobInstance.YARN_APP_URL); - jobStep.putInfo(JobInstance.YARN_APP_URL, this.trackUrl); - output.append("Get job track url " + this.trackUrl).append("\n"); - hasChange = true; - } - if (hasChange) { - jobDAO.updateJobInstance(jobInstance); - } - } catch (Exception e) { - log.error(e.getLocalizedMessage(), e); - output.append(e.getLocalizedMessage()); - } - } - - private void updateJobCounter() { - try { - Counters counters = job.getCounters(); - if (counters == null) { - String errorMsg = "no counters for job " + mrJobID; - log.warn(errorMsg); - output.append(errorMsg); - return; - } - this.output.append(counters.toString()).append("\n"); - log.debug(counters.toString()); - - JobDAO jobDAO = JobDAO.getInstance(config); - JobInstance jobInstance = jobDAO.getJob(jobInstanceID); - JobStep jobStep = jobInstance.getSteps().get(jobStepID); - - long mapInputRecords = counters.findCounter(TaskCounter.MAP_INPUT_RECORDS).getValue(); - jobStep.putInfo(JobInstance.SOURCE_RECORDS_COUNT, String.valueOf(mapInputRecords)); - long hdfsBytesWritten = counters.findCounter("FileSystemCounters", "HDFS_BYTES_WRITTEN").getValue(); - jobStep.putInfo(JobInstance.HDFS_BYTES_WRITTEN, String.valueOf(hdfsBytesWritten)); - - jobDAO.updateJobInstance(jobInstance); - } catch (Exception e) { - log.error(e.getLocalizedMessage(), e); - output.append(e.getLocalizedMessage()); - } - } -} diff --git a/All/Genesis-NP/Genesis#180/old/JavaHadoopCmdOutput.java b/All/Genesis-NP/Genesis#180/old/JavaHadoopCmdOutput.java deleted file mode 100755 index 20dd9dd..0000000 --- a/All/Genesis-NP/Genesis#180/old/JavaHadoopCmdOutput.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2013-2014 eBay Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.kylinolap.job.cmd; - -import java.util.Map; - -import org.apache.hadoop.mapreduce.TaskCounter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.kylinolap.common.KylinConfig; -import com.kylinolap.job.JobDAO; -import com.kylinolap.job.JobInstance; -import com.kylinolap.job.JobInstance.JobStep; -import com.kylinolap.job.constant.JobStepStatusEnum; -import com.kylinolap.job.engine.JobEngineConfig; -import com.kylinolap.job.hadoop.AbstractHadoopJob; -import com.kylinolap.job.tools.HadoopStatusChecker; - -/** - * @author xduo - * - */ -public class JavaHadoopCmdOutput implements ICommandOutput { - - protected static final Logger log = LoggerFactory.getLogger(JavaHadoopCmdOutput.class); - - protected StringBuilder output; - protected int exitCode; - protected JobStepStatusEnum status; - private final KylinConfig config; - private final String jobInstanceID; - private final int jobStepID; - private final String yarnUrl; - private final AbstractHadoopJob job; - private String mrJobID = null; - private String trackUrl = null; - private boolean isAsync; - - public JavaHadoopCmdOutput(String jobInstanceID, int jobStepID, JobEngineConfig engineConfig, AbstractHadoopJob job, boolean isAsync) { - super(); - this.config = engineConfig.getConfig(); - this.yarnUrl = engineConfig.getYarnStatusServiceUrl(); - this.jobInstanceID = jobInstanceID; - this.jobStepID = jobStepID; - this.job = job; - this.isAsync = isAsync; - - init(); - } - - @Override - public void setStatus(JobStepStatusEnum status) { - this.status = status; - } - - @Override - public JobStepStatusEnum getStatus() { - if (this.isAsync) { - if (this.status == JobStepStatusEnum.ERROR) { - return status; - } - - if (null == this.mrJobID || null == this.trackUrl) { - updateHadoopJobInfo(); - } - - status = new HadoopStatusChecker(this.yarnUrl, this.mrJobID, output).checkStatus(); - - if (this.status.isComplete()) { - updateJobCounter(); - } - } else { - status = (this.exitCode == 0) ? JobStepStatusEnum.FINISHED : JobStepStatusEnum.ERROR; - } - - return status; - } - - @Override - public void appendOutput(String message) { - log.debug(message); - output.append(message).append("\n"); - } - - @Override - public String getOutput() { - return output.toString(); - } - - @Override - public void setExitCode(int exitCode) { - this.exitCode = exitCode; - } - - @Override - public int getExitCode() { - return exitCode; - } - - @Override - public void reset() { - init(); - } - - private void init() { - output = new StringBuilder(); - exitCode = -1; - status = JobStepStatusEnum.NEW; - } - - /** - * @param jobStatus - */ - private void updateHadoopJobInfo() { - try { - Map jobInfo = job.getInfo(); - - JobDAO jobDAO = JobDAO.getInstance(config); - JobInstance jobInstance = jobDAO.getJob(jobInstanceID); - JobStep jobStep = jobInstance.getSteps().get(jobStepID); - boolean hasChange = false; - - if (null == this.mrJobID && jobInfo.containsKey(JobInstance.MR_JOB_ID)) { - this.mrJobID = jobInfo.get(JobInstance.MR_JOB_ID); - jobStep.putInfo(JobInstance.MR_JOB_ID, this.mrJobID); - output.append("Get job id " + this.mrJobID).append("\n"); - hasChange = true; - } - - if (null == this.trackUrl && jobInfo.containsKey(JobInstance.YARN_APP_URL)) { - this.trackUrl = jobInfo.get(JobInstance.YARN_APP_URL); - jobStep.putInfo(JobInstance.YARN_APP_URL, this.trackUrl); - output.append("Get job track url " + this.trackUrl).append("\n"); - hasChange = true; - } - if (hasChange) { - jobDAO.updateJobInstance(jobInstance); - } - } catch (Exception e) { - log.error(e.getLocalizedMessage(), e); - output.append(e.getLocalizedMessage()); - } - } - - private void updateJobCounter() { - try { - this.output.append(job.getCounters().toString()).append("\n"); - log.debug(job.getCounters().toString()); - - JobDAO jobDAO = JobDAO.getInstance(config); - JobInstance jobInstance = jobDAO.getJob(jobInstanceID); - JobStep jobStep = jobInstance.getSteps().get(jobStepID); - - long mapInputRecords = job.getCounters().findCounter(TaskCounter.MAP_INPUT_RECORDS).getValue(); - jobStep.putInfo(JobInstance.SOURCE_RECORDS_COUNT, String.valueOf(mapInputRecords)); - long hdfsBytesWritten = job.getCounters().findCounter("FileSystemCounters", "HDFS_BYTES_WRITTEN").getValue(); - jobStep.putInfo(JobInstance.HDFS_BYTES_WRITTEN, String.valueOf(hdfsBytesWritten)); - - jobDAO.updateJobInstance(jobInstance); - } catch (Exception e) { - log.error(e.getLocalizedMessage(), e); - output.append(e.getLocalizedMessage()); - } - } -} diff --git a/All/Genesis-NP/Genesis#180/pair.info b/All/Genesis-NP/Genesis#180/pair.info deleted file mode 100755 index 953e4cd..0000000 --- a/All/Genesis-NP/Genesis#180/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:180 -SATName:Genesis -modifiedFPath:job/src/main/java/com/kylinolap/job/cmd/JavaHadoopCmdOutput.java -comSha:847f3859476baac5939fb3540e6d17414e109757 -parentComSha:847f3859476baac5939fb3540e6d17414e109757^1 -githubUrl:https://github.com/KylinOLAP/Kylin -repoName:KylinOLAP#Kylin \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#181/comMsg.txt b/All/Genesis-NP/Genesis#181/comMsg.txt deleted file mode 100755 index 8d8e19d..0000000 --- a/All/Genesis-NP/Genesis#181/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -add exception handle when project is null diff --git a/All/Genesis-NP/Genesis#181/diff.diff b/All/Genesis-NP/Genesis#181/diff.diff deleted file mode 100755 index 7531ca0..0000000 --- a/All/Genesis-NP/Genesis#181/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/cube/src/main/java/com/kylinolap/cube/project/ProjectManager.java b/cube/src/main/java/com/kylinolap/cube/project/ProjectManager.java -index bfbe282..f0294d1 100644 ---- a/cube/src/main/java/com/kylinolap/cube/project/ProjectManager.java -+++ b/cube/src/main/java/com/kylinolap/cube/project/ProjectManager.java -@@ -20,0 +21 @@ import java.util.ArrayList; -+import java.util.Collections; -@@ -237,0 +239,3 @@ public class ProjectManager { -+ if(null==project){ -+ return Collections.emptyList(); -+ } diff --git a/All/Genesis-NP/Genesis#181/new/ProjectManager.java b/All/Genesis-NP/Genesis#181/new/ProjectManager.java deleted file mode 100755 index f0294d1..0000000 --- a/All/Genesis-NP/Genesis#181/new/ProjectManager.java +++ /dev/null @@ -1,588 +0,0 @@ -/* - * Copyright 2013-2014 eBay Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.kylinolap.cube.project; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; -import com.kylinolap.common.KylinConfig; -import com.kylinolap.common.persistence.JsonSerializer; -import com.kylinolap.common.persistence.ResourceStore; -import com.kylinolap.common.persistence.Serializer; -import com.kylinolap.common.restclient.Broadcaster; -import com.kylinolap.common.restclient.SingleValueCache; -import com.kylinolap.cube.CubeInstance; -import com.kylinolap.cube.CubeManager; -import com.kylinolap.metadata.MetadataManager; -import com.kylinolap.metadata.model.cube.CubeDesc; -import com.kylinolap.metadata.model.cube.DimensionDesc; -import com.kylinolap.metadata.model.cube.FunctionDesc; -import com.kylinolap.metadata.model.cube.JoinDesc; -import com.kylinolap.metadata.model.cube.MeasureDesc; -import com.kylinolap.metadata.model.cube.TblColRef; -import com.kylinolap.metadata.model.schema.ColumnDesc; -import com.kylinolap.metadata.model.schema.TableDesc; - -/** - * @author xduo - * - */ -public class ProjectManager { - private static final Logger logger = LoggerFactory.getLogger(ProjectManager.class); - - // static cached instances - private static final ConcurrentHashMap CACHE = new ConcurrentHashMap(); - private static final Serializer PROJECT_SERIALIZER = new JsonSerializer(ProjectInstance.class); - - private KylinConfig config; - // project name => ProjrectDesc - private SingleValueCache projectMap = new SingleValueCache(Broadcaster.TYPE.PROJECT); - // project name => tables - private Multimap projectTables = Multimaps.synchronizedMultimap(HashMultimap. create()); - - public static ProjectManager getInstance(KylinConfig config) { - ProjectManager r = CACHE.get(config); - if (r != null) { - return r; - } - - synchronized (ProjectManager.class) { - r = CACHE.get(config); - if (r != null) { - return r; - } - try { - r = new ProjectManager(config); - CACHE.put(config, r); - if (CACHE.size() > 1) { - logger.warn("More than one singleton exist"); - } - return r; - } catch (IOException e) { - throw new IllegalStateException("Failed to init CubeManager from " + config, e); - } - } - } - - public static synchronized void removeInstance(KylinConfig config) { - CACHE.remove(config); - } - - private ProjectManager(KylinConfig config) throws IOException { - logger.info("Initializing CubeManager with metadata url " + config); - this.config = config; - - loadAllProjects(); - } - - public static String getDefaultProjectName() { - return ProjectInstance.DEFAULT_PROJECT_NAME; - } - - public List listAllProjects() { - return new ArrayList(projectMap.values()); - } - - public List getProjects(String cubeName) { - return this.findProjects(cubeName); - } - - public ProjectInstance dropProject(String projectName) throws IOException { - if (projectName == null) - throw new IllegalArgumentException("Project name not given"); - - ProjectInstance projectInstance = getProject(projectName); - - if (projectInstance == null) { - throw new IllegalStateException("The project named " + projectName + " does not exist"); - } - - if (projectInstance.getCubes().size() != 0) { - throw new IllegalStateException("The project named " + projectName + " can not be deleted because there's still cubes in it. Delete all the cubes first."); - } - - logger.info("Dropping project '" + projectInstance.getName() + "'"); - deleteResource(projectInstance); - - return projectInstance; - } - - public ProjectInstance getProject(String projectName) { - if (projectName == null) - return null; - projectName = ProjectInstance.getNormalizedProjectName(projectName); - return projectMap.get(projectName); - } - - public ProjectInstance createProject(String projectName, String owner, String description) throws IOException { - - logger.info("Creating project '" + projectName); - - ProjectInstance currentProject = getProject(projectName); - if (currentProject == null) { - currentProject = ProjectInstance.create(projectName, owner, description, null); - } else { - throw new IllegalStateException("The project named " + projectName + "already exists"); - } - - saveResource(currentProject); - - return currentProject; - } - - public ProjectInstance updateProject(ProjectInstance project, String newName, String newDesc) throws IOException { - if (!project.getName().equals(newName)) { - ProjectInstance newProject = this.createProject(newName, project.getOwner(), newDesc); - newProject.setCreateTime(project.getCreateTime()); - newProject.recordUpdateTime(System.currentTimeMillis()); - newProject.setCubes(project.getCubes()); - - deleteResource(project); - saveResource(newProject); - - return newProject; - } else { - project.setName(newName); - project.setDescription(newDesc); - - if (project.getUuid() == null) - project.updateRandomUuid(); - - saveResource(project); - - return project; - } - } - - public boolean isCubeInProject(String projectName, CubeInstance cube) { - return this.listAllCubes(projectName).contains(cube); - } - - public ProjectInstance updateCubeToProject(String cubeName, String newProjectName, String owner) throws IOException { - removeCubeFromProjects(cubeName); - - return addCubeToProject(cubeName, newProjectName, owner); - } - - public ProjectInstance updateTableToProject(String tables,String projectName) throws IOException { - ProjectInstance projectInstance = getProject(projectName); - String[] tokens = StringUtils.split(tables, ","); - for (int i = 0; i < tokens.length; i++) { - String token = tokens[i].trim(); - if (StringUtils.isNotEmpty(token)) { - projectInstance.addTable(token); - } - } - - List exposedTables = listExposedTables(projectName); - for(TableDesc table : exposedTables){ - projectInstance.addTable(table.getName()); - } - - saveResource(projectInstance); - return projectInstance; - } - - - public void removeCubeFromProjects(String cubeName) throws IOException { - for (ProjectInstance projectInstance : findProjects(cubeName)) { - projectInstance.removeCube(cubeName); - - saveResource(projectInstance); - } - } - - public List listExposedTables(String project) { - project = ProjectInstance.getNormalizedProjectName(project); - List tables = Lists.newArrayList(); - - for (ProjectTable table : projectTables.get(project)) { - TableDesc tableDesc = getMetadataManager().getTableDesc(table.getName()); - if (tableDesc != null) { - tables.add(tableDesc); - } - } - - return tables; - } - - - - public List listDefinedTablesInProject(String project) throws IOException { - if(null==project){ - return Collections.emptyList(); - } - project = ProjectInstance.getNormalizedProjectName(project); - ProjectInstance projectInstance = getProject(project); - - int originTableCount = projectInstance.getTablesCount(); - //sync exposed table to project when list - List exposedTables = listExposedTables(project); - for(TableDesc table : exposedTables){ - projectInstance.addTable(table.getName()); - } - - if (originTableCount < projectInstance.getTablesCount()) { - saveResource(projectInstance); - } - - List tables = Lists.newArrayList(); - for (String table : projectInstance.getTables()) { - TableDesc tableDesc = getMetadataManager().getTableDesc(table); - if (tableDesc != null) { - tables.add(tableDesc); - } - } - - return tables; - } - - public List listExposedColumns(String project, String table) { - project = ProjectInstance.getNormalizedProjectName(project); - - MetadataManager metaMgr = getMetadataManager(); - TableDesc tableDesc = metaMgr.getTableDesc(table); - List columns = Lists.newArrayList(); - - for (String column : this.getProjectTable(project, table).getColumns()) { - columns.add(tableDesc.findColumnByName(column)); - } - - return columns; - } - - public boolean isExposedTable(String project, String table) { - project = ProjectInstance.getNormalizedProjectName(project); - - return projectTables.containsEntry(project, new ProjectTable(table)); - } - - public boolean isExposedColumn(String project, String table, String col) { - project = ProjectInstance.getNormalizedProjectName(project); - - return getProjectTable(project, table).getColumns().contains(col); - } - - public List listAllCubes(String project) { - project = ProjectInstance.getNormalizedProjectName(project); - - HashSet ret = new HashSet(); - - ProjectInstance projectInstance = getProject(project); - if (projectInstance != null) { - for (String cubeName : projectInstance.getCubes()) { - CubeInstance cube = CubeManager.getInstance(config).getCube(cubeName); - if (null != cube) { - ret.add(cube); - } else { - logger.error("Failed to load cube " + cubeName); - } - } - } - - return new ArrayList(ret); - } - - - public List getCubesByTable(String project, String tableName) { - project = ProjectInstance.getNormalizedProjectName(project); - tableName = tableName.toUpperCase(); - List cubes = new ArrayList(); - - ProjectTable projectTable = getProjectTable(project, tableName); - cubes.addAll(projectTable.getCubes()); - - return cubes; - } - - public List getOnlineCubesByFactTable(String project, String factTableName) { - project = ProjectInstance.getNormalizedProjectName(project); - factTableName = factTableName.toUpperCase(); - List cubes = new ArrayList(); - ProjectTable projectTable = this.getProjectTable(project, factTableName); - for (CubeInstance cube : projectTable.getCubes()) { - if (cube.getDescriptor().isFactTable(factTableName) && cube.isReady()) { - cubes.add(cube); - } - } - - return cubes; - } - - public List listEffectiveRewriteMeasures(String project, String factTable) { - factTable = factTable.toUpperCase(); - - HashSet relatedDesc = new HashSet(); - for (CubeInstance cube : getProjectTable(project, factTable).getCubes()) { - if (cube.isReady() == false) - continue; - if (cube.getDescriptor().isFactTable(factTable) == false) - continue; - - relatedDesc.add(cube.getDescriptor()); - } - - List result = Lists.newArrayList(); - for (CubeDesc desc : relatedDesc) { - for (MeasureDesc m : desc.getMeasures()) { - FunctionDesc func = m.getFunction(); - if (func.needRewrite()) - result.add(m); - } - } - - return result; - } - - public void loadProjectCache(ProjectInstance project, boolean triggerUpdate) throws IOException { - loadProject(project.getResourcePath(), triggerUpdate); - loadTables(project.getResourcePath()); - } - - public void removeProjectCache(ProjectInstance project) { - String projectName = ProjectInstance.getNormalizedProjectName(project.getName()); - if (projectMap.containsKey(projectName)) { - projectMap.remove(projectName); - projectTables.removeAll(projectName); - } - } - - private void mapTableToCube(ProjectInstance projectInstance, CubeInstance cubeInstance) { - // schema sanity check - CubeDesc cubeDesc = cubeInstance.getDescriptor(); - if (cubeDesc == null) { - logger.warn("No CubeDesc found by name '" + cubeInstance.getDescName() + "'"); - return; - } - - // table ==> cube mapping - String factTable = cubeDesc.getFactTable(); - logger.debug("Fact Table: " + factTable + " -- Cube: " + cubeInstance.getName()); - assert this.getMetadataManager().getTableDesc(factTable) != null; - - String project = ProjectInstance.getNormalizedProjectName(projectInstance.getName()); - ProjectTable factProjTable = this.getProjectTable(project, factTable, true); - if (!factProjTable.getCubes().contains(cubeInstance)) { - factProjTable.getCubes().add(cubeInstance); - } - - for (DimensionDesc d : cubeDesc.getDimensions()) { - String lookupTable = d.getTable(); - logger.debug("Lookup Table: " + lookupTable + " -- Cube: " + cubeInstance.getName()); - assert this.getMetadataManager().getTableDesc(lookupTable) != null; - - ProjectTable dimensionProjTable = this.getProjectTable(project, lookupTable); - if (!dimensionProjTable.getCubes().contains(cubeInstance)) { - dimensionProjTable.getCubes().add(cubeInstance); - } - } - } - - private List findProjects(String cubeName) { - List projects = new ArrayList(); - for (ProjectInstance projectInstance : projectMap.values()) { - if (projectInstance.containsCube(cubeName)) { - projects.add(projectInstance); - } - } - - return projects; - } - - private synchronized ProjectInstance loadProject(String path, boolean triggerUpdate) throws IOException { - ResourceStore store = getStore(); - logger.debug("Loading CubeInstance " + store.getReadableResourcePath(path)); - - ProjectInstance projectInstance = store.getResource(path, ProjectInstance.class, PROJECT_SERIALIZER); - projectInstance.init(); - - if (StringUtils.isBlank(projectInstance.getName())) - throw new IllegalStateException("Project name must not be blank"); - - if (triggerUpdate) { - projectMap.put(projectInstance.getName().toUpperCase(), projectInstance); - } else { - projectMap.putLocal(projectInstance.getName().toUpperCase(), projectInstance); - } - - return projectInstance; - } - - private synchronized void loadTables(String path) throws IOException { - ResourceStore store = getStore(); - logger.debug("Loading CubeInstance " + store.getReadableResourcePath(path)); - - ProjectInstance projectInstance = store.getResource(path, ProjectInstance.class, PROJECT_SERIALIZER); - projectInstance.init(); - - String project = ProjectInstance.getNormalizedProjectName(projectInstance.getName()); - projectTables.removeAll(project); - - for (CubeInstance cubeInstance : this.listAllCubes(projectInstance.getName())) { - markExposedTablesAndColumns(projectInstance.getName(), cubeInstance); - mapTableToCube(projectInstance, cubeInstance); - } - } - - private void loadAllProjects() throws IOException { - ResourceStore store = getStore(); - List paths = store.collectResourceRecursively(ResourceStore.PROJECT_RESOURCE_ROOT, ".json"); - - logger.debug("Loading Project from folder " + store.getReadableResourcePath(ResourceStore.PROJECT_RESOURCE_ROOT)); - - for (String path : paths) { - loadProject(path, false); - loadTables(path); - } - - logger.debug("Loaded " + paths.size() + " Project(s)"); - } - - private ProjectInstance addCubeToProject(String cubeName, String project, String user) throws IOException { - String newProjectName = ProjectInstance.getNormalizedProjectName(project); - ProjectInstance newProject = getProject(newProjectName); - if (newProject == null) { - newProject = this.createProject(newProjectName, user, "This is a project automatically added when adding cube " + cubeName); - } - newProject.addCube(cubeName); - saveResource(newProject); - - return newProject; - } - - private void saveResource(ProjectInstance proj) throws IOException { - ResourceStore store = getStore(); - store.putResource(proj.getResourcePath(), proj, PROJECT_SERIALIZER); - afterProjectUpdated(proj); - } - - private void deleteResource(ProjectInstance proj) throws IOException { - ResourceStore store = getStore(); - store.deleteResource(proj.getResourcePath()); - this.afterProjectDropped(proj); - } - - private void afterProjectUpdated(ProjectInstance updatedProject) { - try { - this.loadProjectCache(updatedProject, true); - } catch (IOException e) { - logger.error(e.getLocalizedMessage(), e); - } - } - - private void afterProjectDropped(ProjectInstance droppedProject) { - this.removeProjectCache(droppedProject); - } - - // sync on update - private void markExposedTablesAndColumns(String projectName, CubeInstance cubeInstance) { - if (!cubeInstance.isReady()) - return; - - CubeDesc cubeDesc = cubeInstance.getDescriptor(); - String factTable = cubeDesc.getFactTable(); - for (DimensionDesc dim : cubeDesc.getDimensions()) { - String lookupTable = dim.getTable(); - JoinDesc join = dim.getJoin(); - if (join == null) - continue; // for dimensions on fact table, there's no join - - if (join.getForeignKeyColumns() == null) { - throw new IllegalStateException("Null FK for " + join); - } - for (TblColRef fkCol : join.getForeignKeyColumns()) { - markExposedTableAndColumn(projectName, factTable, fkCol.getName(), dim); - } - if (join.getPrimaryKeyColumns() == null) { - throw new IllegalStateException("Null PK for " + join); - } - for (TblColRef pkCol : join.getPrimaryKeyColumns()) { - markExposedTableAndColumn(projectName, lookupTable, pkCol.getName(), dim); - } - } - for (TblColRef col : cubeDesc.listAllColumns()) { - markExposedTableAndColumn(projectName, col.getTable(), col.getName(), col); - } - } - - private void markExposedTableAndColumn(String project, String table, String column, Object refObj) { - project = ProjectInstance.getNormalizedProjectName(project); - TableDesc t = this.getMetadataManager().getTableDesc(table); - if (t == null) - throw new IllegalStateException("No SourceTable found by name '" + table + "', ref by " + refObj); - table = t.getName(); // ensures upper case - - ProjectTable projTable = getProjectTable(project, table, true); - - ColumnDesc srcCol = t.findColumnByName(column); - if (srcCol == null) - throw new IllegalStateException("No SourceColumn found by name '" + table + "/" + column + "', ref by " + refObj); - - if (!projTable.getColumns().contains(srcCol.getName())) { - projTable.getColumns().add(srcCol.getName()); - } - } - - private ProjectTable getProjectTable(String project, final String table) { - return getProjectTable(project, table, false); - } - - private ProjectTable getProjectTable(String project, final String table, boolean autoCreate) { - ProjectTable projectTable = null; - project = ProjectInstance.getNormalizedProjectName(project); - - if (this.projectTables.containsEntry(project, new ProjectTable(table))) { - Iterator projsIter = this.projectTables.get(project).iterator(); - while (projsIter.hasNext()) { - ProjectTable oneTable = projsIter.next(); - if (oneTable.getName().equalsIgnoreCase(table)) { - projectTable = oneTable; - break; - } - } - } else { - projectTable = new ProjectTable(table); - - if (autoCreate) { - this.projectTables.put(project, projectTable); - } - } - - return projectTable; - } - - private ResourceStore getStore() { - return ResourceStore.getStore(this.config); - } - - private MetadataManager getMetadataManager() { - return MetadataManager.getInstance(config); - } -} diff --git a/All/Genesis-NP/Genesis#181/old/ProjectManager.java b/All/Genesis-NP/Genesis#181/old/ProjectManager.java deleted file mode 100755 index bfbe282..0000000 --- a/All/Genesis-NP/Genesis#181/old/ProjectManager.java +++ /dev/null @@ -1,584 +0,0 @@ -/* - * Copyright 2013-2014 eBay Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.kylinolap.cube.project; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.HashMultimap; -import com.google.common.collect.Lists; -import com.google.common.collect.Multimap; -import com.google.common.collect.Multimaps; -import com.kylinolap.common.KylinConfig; -import com.kylinolap.common.persistence.JsonSerializer; -import com.kylinolap.common.persistence.ResourceStore; -import com.kylinolap.common.persistence.Serializer; -import com.kylinolap.common.restclient.Broadcaster; -import com.kylinolap.common.restclient.SingleValueCache; -import com.kylinolap.cube.CubeInstance; -import com.kylinolap.cube.CubeManager; -import com.kylinolap.metadata.MetadataManager; -import com.kylinolap.metadata.model.cube.CubeDesc; -import com.kylinolap.metadata.model.cube.DimensionDesc; -import com.kylinolap.metadata.model.cube.FunctionDesc; -import com.kylinolap.metadata.model.cube.JoinDesc; -import com.kylinolap.metadata.model.cube.MeasureDesc; -import com.kylinolap.metadata.model.cube.TblColRef; -import com.kylinolap.metadata.model.schema.ColumnDesc; -import com.kylinolap.metadata.model.schema.TableDesc; - -/** - * @author xduo - * - */ -public class ProjectManager { - private static final Logger logger = LoggerFactory.getLogger(ProjectManager.class); - - // static cached instances - private static final ConcurrentHashMap CACHE = new ConcurrentHashMap(); - private static final Serializer PROJECT_SERIALIZER = new JsonSerializer(ProjectInstance.class); - - private KylinConfig config; - // project name => ProjrectDesc - private SingleValueCache projectMap = new SingleValueCache(Broadcaster.TYPE.PROJECT); - // project name => tables - private Multimap projectTables = Multimaps.synchronizedMultimap(HashMultimap. create()); - - public static ProjectManager getInstance(KylinConfig config) { - ProjectManager r = CACHE.get(config); - if (r != null) { - return r; - } - - synchronized (ProjectManager.class) { - r = CACHE.get(config); - if (r != null) { - return r; - } - try { - r = new ProjectManager(config); - CACHE.put(config, r); - if (CACHE.size() > 1) { - logger.warn("More than one singleton exist"); - } - return r; - } catch (IOException e) { - throw new IllegalStateException("Failed to init CubeManager from " + config, e); - } - } - } - - public static synchronized void removeInstance(KylinConfig config) { - CACHE.remove(config); - } - - private ProjectManager(KylinConfig config) throws IOException { - logger.info("Initializing CubeManager with metadata url " + config); - this.config = config; - - loadAllProjects(); - } - - public static String getDefaultProjectName() { - return ProjectInstance.DEFAULT_PROJECT_NAME; - } - - public List listAllProjects() { - return new ArrayList(projectMap.values()); - } - - public List getProjects(String cubeName) { - return this.findProjects(cubeName); - } - - public ProjectInstance dropProject(String projectName) throws IOException { - if (projectName == null) - throw new IllegalArgumentException("Project name not given"); - - ProjectInstance projectInstance = getProject(projectName); - - if (projectInstance == null) { - throw new IllegalStateException("The project named " + projectName + " does not exist"); - } - - if (projectInstance.getCubes().size() != 0) { - throw new IllegalStateException("The project named " + projectName + " can not be deleted because there's still cubes in it. Delete all the cubes first."); - } - - logger.info("Dropping project '" + projectInstance.getName() + "'"); - deleteResource(projectInstance); - - return projectInstance; - } - - public ProjectInstance getProject(String projectName) { - if (projectName == null) - return null; - projectName = ProjectInstance.getNormalizedProjectName(projectName); - return projectMap.get(projectName); - } - - public ProjectInstance createProject(String projectName, String owner, String description) throws IOException { - - logger.info("Creating project '" + projectName); - - ProjectInstance currentProject = getProject(projectName); - if (currentProject == null) { - currentProject = ProjectInstance.create(projectName, owner, description, null); - } else { - throw new IllegalStateException("The project named " + projectName + "already exists"); - } - - saveResource(currentProject); - - return currentProject; - } - - public ProjectInstance updateProject(ProjectInstance project, String newName, String newDesc) throws IOException { - if (!project.getName().equals(newName)) { - ProjectInstance newProject = this.createProject(newName, project.getOwner(), newDesc); - newProject.setCreateTime(project.getCreateTime()); - newProject.recordUpdateTime(System.currentTimeMillis()); - newProject.setCubes(project.getCubes()); - - deleteResource(project); - saveResource(newProject); - - return newProject; - } else { - project.setName(newName); - project.setDescription(newDesc); - - if (project.getUuid() == null) - project.updateRandomUuid(); - - saveResource(project); - - return project; - } - } - - public boolean isCubeInProject(String projectName, CubeInstance cube) { - return this.listAllCubes(projectName).contains(cube); - } - - public ProjectInstance updateCubeToProject(String cubeName, String newProjectName, String owner) throws IOException { - removeCubeFromProjects(cubeName); - - return addCubeToProject(cubeName, newProjectName, owner); - } - - public ProjectInstance updateTableToProject(String tables,String projectName) throws IOException { - ProjectInstance projectInstance = getProject(projectName); - String[] tokens = StringUtils.split(tables, ","); - for (int i = 0; i < tokens.length; i++) { - String token = tokens[i].trim(); - if (StringUtils.isNotEmpty(token)) { - projectInstance.addTable(token); - } - } - - List exposedTables = listExposedTables(projectName); - for(TableDesc table : exposedTables){ - projectInstance.addTable(table.getName()); - } - - saveResource(projectInstance); - return projectInstance; - } - - - public void removeCubeFromProjects(String cubeName) throws IOException { - for (ProjectInstance projectInstance : findProjects(cubeName)) { - projectInstance.removeCube(cubeName); - - saveResource(projectInstance); - } - } - - public List listExposedTables(String project) { - project = ProjectInstance.getNormalizedProjectName(project); - List tables = Lists.newArrayList(); - - for (ProjectTable table : projectTables.get(project)) { - TableDesc tableDesc = getMetadataManager().getTableDesc(table.getName()); - if (tableDesc != null) { - tables.add(tableDesc); - } - } - - return tables; - } - - - - public List listDefinedTablesInProject(String project) throws IOException { - project = ProjectInstance.getNormalizedProjectName(project); - ProjectInstance projectInstance = getProject(project); - - int originTableCount = projectInstance.getTablesCount(); - //sync exposed table to project when list - List exposedTables = listExposedTables(project); - for(TableDesc table : exposedTables){ - projectInstance.addTable(table.getName()); - } - - if (originTableCount < projectInstance.getTablesCount()) { - saveResource(projectInstance); - } - - List tables = Lists.newArrayList(); - for (String table : projectInstance.getTables()) { - TableDesc tableDesc = getMetadataManager().getTableDesc(table); - if (tableDesc != null) { - tables.add(tableDesc); - } - } - - return tables; - } - - public List listExposedColumns(String project, String table) { - project = ProjectInstance.getNormalizedProjectName(project); - - MetadataManager metaMgr = getMetadataManager(); - TableDesc tableDesc = metaMgr.getTableDesc(table); - List columns = Lists.newArrayList(); - - for (String column : this.getProjectTable(project, table).getColumns()) { - columns.add(tableDesc.findColumnByName(column)); - } - - return columns; - } - - public boolean isExposedTable(String project, String table) { - project = ProjectInstance.getNormalizedProjectName(project); - - return projectTables.containsEntry(project, new ProjectTable(table)); - } - - public boolean isExposedColumn(String project, String table, String col) { - project = ProjectInstance.getNormalizedProjectName(project); - - return getProjectTable(project, table).getColumns().contains(col); - } - - public List listAllCubes(String project) { - project = ProjectInstance.getNormalizedProjectName(project); - - HashSet ret = new HashSet(); - - ProjectInstance projectInstance = getProject(project); - if (projectInstance != null) { - for (String cubeName : projectInstance.getCubes()) { - CubeInstance cube = CubeManager.getInstance(config).getCube(cubeName); - if (null != cube) { - ret.add(cube); - } else { - logger.error("Failed to load cube " + cubeName); - } - } - } - - return new ArrayList(ret); - } - - - public List getCubesByTable(String project, String tableName) { - project = ProjectInstance.getNormalizedProjectName(project); - tableName = tableName.toUpperCase(); - List cubes = new ArrayList(); - - ProjectTable projectTable = getProjectTable(project, tableName); - cubes.addAll(projectTable.getCubes()); - - return cubes; - } - - public List getOnlineCubesByFactTable(String project, String factTableName) { - project = ProjectInstance.getNormalizedProjectName(project); - factTableName = factTableName.toUpperCase(); - List cubes = new ArrayList(); - ProjectTable projectTable = this.getProjectTable(project, factTableName); - for (CubeInstance cube : projectTable.getCubes()) { - if (cube.getDescriptor().isFactTable(factTableName) && cube.isReady()) { - cubes.add(cube); - } - } - - return cubes; - } - - public List listEffectiveRewriteMeasures(String project, String factTable) { - factTable = factTable.toUpperCase(); - - HashSet relatedDesc = new HashSet(); - for (CubeInstance cube : getProjectTable(project, factTable).getCubes()) { - if (cube.isReady() == false) - continue; - if (cube.getDescriptor().isFactTable(factTable) == false) - continue; - - relatedDesc.add(cube.getDescriptor()); - } - - List result = Lists.newArrayList(); - for (CubeDesc desc : relatedDesc) { - for (MeasureDesc m : desc.getMeasures()) { - FunctionDesc func = m.getFunction(); - if (func.needRewrite()) - result.add(m); - } - } - - return result; - } - - public void loadProjectCache(ProjectInstance project, boolean triggerUpdate) throws IOException { - loadProject(project.getResourcePath(), triggerUpdate); - loadTables(project.getResourcePath()); - } - - public void removeProjectCache(ProjectInstance project) { - String projectName = ProjectInstance.getNormalizedProjectName(project.getName()); - if (projectMap.containsKey(projectName)) { - projectMap.remove(projectName); - projectTables.removeAll(projectName); - } - } - - private void mapTableToCube(ProjectInstance projectInstance, CubeInstance cubeInstance) { - // schema sanity check - CubeDesc cubeDesc = cubeInstance.getDescriptor(); - if (cubeDesc == null) { - logger.warn("No CubeDesc found by name '" + cubeInstance.getDescName() + "'"); - return; - } - - // table ==> cube mapping - String factTable = cubeDesc.getFactTable(); - logger.debug("Fact Table: " + factTable + " -- Cube: " + cubeInstance.getName()); - assert this.getMetadataManager().getTableDesc(factTable) != null; - - String project = ProjectInstance.getNormalizedProjectName(projectInstance.getName()); - ProjectTable factProjTable = this.getProjectTable(project, factTable, true); - if (!factProjTable.getCubes().contains(cubeInstance)) { - factProjTable.getCubes().add(cubeInstance); - } - - for (DimensionDesc d : cubeDesc.getDimensions()) { - String lookupTable = d.getTable(); - logger.debug("Lookup Table: " + lookupTable + " -- Cube: " + cubeInstance.getName()); - assert this.getMetadataManager().getTableDesc(lookupTable) != null; - - ProjectTable dimensionProjTable = this.getProjectTable(project, lookupTable); - if (!dimensionProjTable.getCubes().contains(cubeInstance)) { - dimensionProjTable.getCubes().add(cubeInstance); - } - } - } - - private List findProjects(String cubeName) { - List projects = new ArrayList(); - for (ProjectInstance projectInstance : projectMap.values()) { - if (projectInstance.containsCube(cubeName)) { - projects.add(projectInstance); - } - } - - return projects; - } - - private synchronized ProjectInstance loadProject(String path, boolean triggerUpdate) throws IOException { - ResourceStore store = getStore(); - logger.debug("Loading CubeInstance " + store.getReadableResourcePath(path)); - - ProjectInstance projectInstance = store.getResource(path, ProjectInstance.class, PROJECT_SERIALIZER); - projectInstance.init(); - - if (StringUtils.isBlank(projectInstance.getName())) - throw new IllegalStateException("Project name must not be blank"); - - if (triggerUpdate) { - projectMap.put(projectInstance.getName().toUpperCase(), projectInstance); - } else { - projectMap.putLocal(projectInstance.getName().toUpperCase(), projectInstance); - } - - return projectInstance; - } - - private synchronized void loadTables(String path) throws IOException { - ResourceStore store = getStore(); - logger.debug("Loading CubeInstance " + store.getReadableResourcePath(path)); - - ProjectInstance projectInstance = store.getResource(path, ProjectInstance.class, PROJECT_SERIALIZER); - projectInstance.init(); - - String project = ProjectInstance.getNormalizedProjectName(projectInstance.getName()); - projectTables.removeAll(project); - - for (CubeInstance cubeInstance : this.listAllCubes(projectInstance.getName())) { - markExposedTablesAndColumns(projectInstance.getName(), cubeInstance); - mapTableToCube(projectInstance, cubeInstance); - } - } - - private void loadAllProjects() throws IOException { - ResourceStore store = getStore(); - List paths = store.collectResourceRecursively(ResourceStore.PROJECT_RESOURCE_ROOT, ".json"); - - logger.debug("Loading Project from folder " + store.getReadableResourcePath(ResourceStore.PROJECT_RESOURCE_ROOT)); - - for (String path : paths) { - loadProject(path, false); - loadTables(path); - } - - logger.debug("Loaded " + paths.size() + " Project(s)"); - } - - private ProjectInstance addCubeToProject(String cubeName, String project, String user) throws IOException { - String newProjectName = ProjectInstance.getNormalizedProjectName(project); - ProjectInstance newProject = getProject(newProjectName); - if (newProject == null) { - newProject = this.createProject(newProjectName, user, "This is a project automatically added when adding cube " + cubeName); - } - newProject.addCube(cubeName); - saveResource(newProject); - - return newProject; - } - - private void saveResource(ProjectInstance proj) throws IOException { - ResourceStore store = getStore(); - store.putResource(proj.getResourcePath(), proj, PROJECT_SERIALIZER); - afterProjectUpdated(proj); - } - - private void deleteResource(ProjectInstance proj) throws IOException { - ResourceStore store = getStore(); - store.deleteResource(proj.getResourcePath()); - this.afterProjectDropped(proj); - } - - private void afterProjectUpdated(ProjectInstance updatedProject) { - try { - this.loadProjectCache(updatedProject, true); - } catch (IOException e) { - logger.error(e.getLocalizedMessage(), e); - } - } - - private void afterProjectDropped(ProjectInstance droppedProject) { - this.removeProjectCache(droppedProject); - } - - // sync on update - private void markExposedTablesAndColumns(String projectName, CubeInstance cubeInstance) { - if (!cubeInstance.isReady()) - return; - - CubeDesc cubeDesc = cubeInstance.getDescriptor(); - String factTable = cubeDesc.getFactTable(); - for (DimensionDesc dim : cubeDesc.getDimensions()) { - String lookupTable = dim.getTable(); - JoinDesc join = dim.getJoin(); - if (join == null) - continue; // for dimensions on fact table, there's no join - - if (join.getForeignKeyColumns() == null) { - throw new IllegalStateException("Null FK for " + join); - } - for (TblColRef fkCol : join.getForeignKeyColumns()) { - markExposedTableAndColumn(projectName, factTable, fkCol.getName(), dim); - } - if (join.getPrimaryKeyColumns() == null) { - throw new IllegalStateException("Null PK for " + join); - } - for (TblColRef pkCol : join.getPrimaryKeyColumns()) { - markExposedTableAndColumn(projectName, lookupTable, pkCol.getName(), dim); - } - } - for (TblColRef col : cubeDesc.listAllColumns()) { - markExposedTableAndColumn(projectName, col.getTable(), col.getName(), col); - } - } - - private void markExposedTableAndColumn(String project, String table, String column, Object refObj) { - project = ProjectInstance.getNormalizedProjectName(project); - TableDesc t = this.getMetadataManager().getTableDesc(table); - if (t == null) - throw new IllegalStateException("No SourceTable found by name '" + table + "', ref by " + refObj); - table = t.getName(); // ensures upper case - - ProjectTable projTable = getProjectTable(project, table, true); - - ColumnDesc srcCol = t.findColumnByName(column); - if (srcCol == null) - throw new IllegalStateException("No SourceColumn found by name '" + table + "/" + column + "', ref by " + refObj); - - if (!projTable.getColumns().contains(srcCol.getName())) { - projTable.getColumns().add(srcCol.getName()); - } - } - - private ProjectTable getProjectTable(String project, final String table) { - return getProjectTable(project, table, false); - } - - private ProjectTable getProjectTable(String project, final String table, boolean autoCreate) { - ProjectTable projectTable = null; - project = ProjectInstance.getNormalizedProjectName(project); - - if (this.projectTables.containsEntry(project, new ProjectTable(table))) { - Iterator projsIter = this.projectTables.get(project).iterator(); - while (projsIter.hasNext()) { - ProjectTable oneTable = projsIter.next(); - if (oneTable.getName().equalsIgnoreCase(table)) { - projectTable = oneTable; - break; - } - } - } else { - projectTable = new ProjectTable(table); - - if (autoCreate) { - this.projectTables.put(project, projectTable); - } - } - - return projectTable; - } - - private ResourceStore getStore() { - return ResourceStore.getStore(this.config); - } - - private MetadataManager getMetadataManager() { - return MetadataManager.getInstance(config); - } -} diff --git a/All/Genesis-NP/Genesis#181/pair.info b/All/Genesis-NP/Genesis#181/pair.info deleted file mode 100755 index d5236ab..0000000 --- a/All/Genesis-NP/Genesis#181/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:181 -SATName:Genesis -modifiedFPath:cube/src/main/java/com/kylinolap/cube/project/ProjectManager.java -comSha:ecfef68ac2c1b2265f7ba13eab3d385db068fac9 -parentComSha:ecfef68ac2c1b2265f7ba13eab3d385db068fac9^1 -githubUrl:https://github.com/KylinOLAP/Kylin -repoName:KylinOLAP#Kylin \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#194/comMsg.txt b/All/Genesis-NP/Genesis#194/comMsg.txt deleted file mode 100755 index efe5696..0000000 --- a/All/Genesis-NP/Genesis#194/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NullpointerException when plugin is executed in Maven module without image configuration diff --git a/All/Genesis-NP/Genesis#194/diff.diff b/All/Genesis-NP/Genesis#194/diff.diff deleted file mode 100755 index 210f178..0000000 --- a/All/Genesis-NP/Genesis#194/diff.diff +++ /dev/null @@ -1,46 +0,0 @@ -diff --git a/src/main/java/org/jolokia/docker/maven/AbstractDockerMojo.java b/src/main/java/org/jolokia/docker/maven/AbstractDockerMojo.java -index 23a69fa..6af200b 100644 ---- a/src/main/java/org/jolokia/docker/maven/AbstractDockerMojo.java -+++ b/src/main/java/org/jolokia/docker/maven/AbstractDockerMojo.java -@@ -3,14 +3 @@ package org.jolokia.docker.maven; --import java.io.IOException; --import java.net.URI; --import java.net.URISyntaxException; --import java.util.ArrayList; --import java.util.Arrays; --import java.util.HashSet; --import java.util.List; --import java.util.Map; --import java.util.Properties; --import java.util.Set; -- --import org.apache.maven.plugin.AbstractMojo; --import org.apache.maven.plugin.MojoExecutionException; --import org.apache.maven.plugin.MojoFailureException; -+import org.apache.maven.plugin.*; -@@ -24,3 +11 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; --import org.jolokia.docker.maven.access.AuthConfig; --import org.jolokia.docker.maven.access.DockerAccess; --import org.jolokia.docker.maven.access.DockerAccessException; -+import org.jolokia.docker.maven.access.*; -@@ -28,3 +13 @@ import org.jolokia.docker.maven.access.hc.DockerAccessWithHcClient; --import org.jolokia.docker.maven.config.ImageConfiguration; --import org.jolokia.docker.maven.config.LogConfiguration; --import org.jolokia.docker.maven.config.RunImageConfiguration; -+import org.jolokia.docker.maven.config.*; -@@ -36,5 +19,6 @@ import org.jolokia.docker.maven.service.ServiceHub; --import org.jolokia.docker.maven.util.AnsiLogger; --import org.jolokia.docker.maven.util.AuthConfigFactory; --import org.jolokia.docker.maven.util.EnvUtil; --import org.jolokia.docker.maven.util.ImageName; --import org.jolokia.docker.maven.util.Logger; -+import org.jolokia.docker.maven.util.*; -+ -+import java.io.IOException; -+import java.net.URI; -+import java.net.URISyntaxException; -+import java.util.*; -@@ -185,0 +170 @@ public abstract class AbstractDockerMojo extends AbstractMojo implements Context -+ if (images != null) { -@@ -189,0 +175 @@ public abstract class AbstractDockerMojo extends AbstractMojo implements Context -+ } diff --git a/All/Genesis-NP/Genesis#194/new/AbstractDockerMojo.java b/All/Genesis-NP/Genesis#194/new/AbstractDockerMojo.java deleted file mode 100755 index 6af200b..0000000 --- a/All/Genesis-NP/Genesis#194/new/AbstractDockerMojo.java +++ /dev/null @@ -1,383 +0,0 @@ -package org.jolokia.docker.maven; - -import org.apache.maven.plugin.*; -import org.apache.maven.project.MavenProject; -import org.apache.maven.settings.Settings; -import org.codehaus.plexus.PlexusConstants; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.context.Context; -import org.codehaus.plexus.context.ContextException; -import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; -import org.jolokia.docker.maven.access.*; -import org.jolokia.docker.maven.access.hc.DockerAccessWithHcClient; -import org.jolokia.docker.maven.config.*; -import org.jolokia.docker.maven.config.handler.ImageConfigResolver; -import org.jolokia.docker.maven.log.ContainerLogOutputSpec; -import org.jolokia.docker.maven.log.LogDispatcher; -import org.jolokia.docker.maven.service.QueryService; -import org.jolokia.docker.maven.service.ServiceHub; -import org.jolokia.docker.maven.util.*; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.*; - -/** - * Base class for this plugin. - * - * @author roland - * @since 26.03.14 - */ -public abstract class AbstractDockerMojo extends AbstractMojo implements Contextualizable { - - // Key for indicating that a "start" goal has run - public static final String CONTEXT_KEY_START_CALLED = "CONTEXT_KEY_DOCKER_START_CALLED"; - - // Key holding the log dispatcher - public static final Object CONTEXT_KEY_LOG_DISPATCHER = "CONTEXT_KEY_DOCKER_LOG_DISPATCHER"; - - // Standard HTTPS port (IANA registered). The other 2375 with plain HTTP is used only in older - // docker installations. - public static final String DOCKER_HTTPS_PORT = "2376"; - - public static final String API_VERSION = "v1.17"; - - // Current maven project - /** @parameter default-value="${project}" */ - protected MavenProject project; - - // Settings holding authentication info - /** @component */ - protected Settings settings; - - // Handler for external configurations - /** @component */ - protected ImageConfigResolver imageConfigResolver; - - /** @component **/ - protected ServiceHub serviceHub; - - /** @parameter property = "docker.autoPull" default-value = "on" */ - protected String autoPull; - - /** - * Whether to keep the containers afters stopping (start/watch/stop) - * - * @parameter property = "docker.keepContainer" default-value = "false" - */ - protected boolean keepContainer; - - /** - * Whether to remove volumes when removing the container (start/watch/stop) - * - * @parameter property = "docker.removeVolumes" defaultValue = "false" - */ - protected boolean removeVolumes; - - /** @parameter property = "docker.apiVersion" */ - private String apiVersion; - - // URL to docker daemon - /** @parameter property = "docker.host" */ - private String dockerHost; - - /** @parameter property = "docker.certPath" */ - private String certPath; - - // If logging is enabled globally - - // Whether to use color - /** @parameter property = "docker.useColor" default-value = "true" */ - protected boolean useColor; - - // For verbose output - /** @parameter property = "docker.verbose" default-value = "false" */ - protected boolean verbose; - - // The date format to use when putting out logs - /** @parameter property = "docker.logDate" */ - private String logDate; - - // Whether to skip docker altogether - /** @parameter property = "docker.skip" default-value = "false" */ - private boolean skip; - - // Whether to restrict operation to a single image. This can be either - // the image or an alias name. It can also be comma separated list. - // This parameter is typically set via the command line. - /** @parameter property = "docker.image" */ - private String image; - - // Default registry to use if no registry is specified - /** @parameter property = "docker.registry" */ - private String registry; - - // maximum connection to use in parallel for connecting the docker host - /** @parameter property = "docker.maxConnections" default-value = "100" */ - private int maxConnections; - - // property file to write out with port mappings - /** @parameter */ - protected String portPropertyFile; - - // Authentication information - /** @parameter */ - Map authConfig; - - // Relevant configuration to use. This includes also references to external - // images - /** - * @parameter - */ - private List images; - - // Handler dealing with authentication credentials - private AuthConfigFactory authConfigFactory; - - protected Logger log; - - /** - * Entry point for this plugin. It will set up the helper class and then calls {@link #executeInternal(DockerAccess)} - * which must be implemented by subclass. - * - * @throws MojoExecutionException - * @throws MojoFailureException - */ - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - if (!skip) { - log = new AnsiLogger(getLog(), useColor, verbose); - - validateConfiguration(log); - - String dockerUrl = EnvUtil.extractUrl(dockerHost); - DockerAccess access = createDockerAccess(dockerUrl); - setDockerHostAddressProperty(dockerUrl); - serviceHub.init(access,log); - - try { - executeInternal(access); - } catch (DockerAccessException exp) { - throw new MojoExecutionException(log.errorMessage(exp.getMessage()), exp); - } finally { - access.shutdown(); - } - } - } - - private void validateConfiguration(Logger log) { - if (images != null) { - for (ImageConfiguration imageConfiguration : images) { - imageConfiguration.validate(log); - } - } - } - - /** - * Hook for subclass for doing the real job - * - * @param dockerAccess access object for getting to the DockerServer - */ - protected abstract void executeInternal(DockerAccess dockerAccess) - throws DockerAccessException, MojoExecutionException; - - // ============================================================================================= - - /** - * Get all images to use. Can be restricted via -Ddocker.image to pick a one or more images. The values - * is taken as comma separated list. - * - * @return list of image configuration to use - */ - protected List getImages() { - List resolvedImages = resolveImages(); - List ret = new ArrayList<>(); - for (ImageConfiguration imageConfig : resolvedImages) { - if (matchesConfiguredImages(this.image, imageConfig)) { - ret.add(imageConfig); - } - } - return ret; - } - - private List resolveImages() { - List ret = new ArrayList<>(); - if (images != null) { - for (ImageConfiguration image : images) { - ret.addAll(imageConfigResolver.resolve(image, project.getProperties())); - } - verifyImageNames(ret); - } - return ret; - } - - // Extract authentication information - private void verifyImageNames(List ret) { - for (ImageConfiguration config : ret) { - if (config.getName() == null) { - throw new IllegalArgumentException("Configuration error: must have a non-null "); - } - } - } - - // Check if the provided image configuration matches the given - protected boolean matchesConfiguredImages(String imageList, ImageConfiguration imageConfig) { - if (imageList == null) { - return true; - } - Set imagesAllowed = new HashSet<>(Arrays.asList(imageList.split("\\s*,\\s*"))); - return imagesAllowed.contains(imageConfig.getName()) || imagesAllowed.contains(imageConfig.getAlias()); - } - - private DockerAccess createDockerAccess(String baseUrl) throws MojoExecutionException { - try { - String version = (apiVersion == null) ? API_VERSION : apiVersion; - DockerAccess client = new DockerAccessWithHcClient(version, baseUrl, - EnvUtil.getCertPath(certPath), maxConnections, log); - client.start(); - - return client; - } - catch (IOException e) { - throw new MojoExecutionException("Cannot create docker access object ", e); - } - } - - // Registry for managed containers - private void setDockerHostAddressProperty(String dockerUrl) throws MojoFailureException { - Properties props = project.getProperties(); - if (props.getProperty("docker.host.address") == null) { - final String host; - try { - URI uri = new URI(dockerUrl); - if (uri.getHost() == null && uri.getScheme().equals("unix")) { - host = "localhost"; - } else { - host = uri.getHost(); - } - } catch (URISyntaxException e) { - throw new MojoFailureException("Cannot parse " + dockerUrl + " as URI: " + e.getMessage(), e); - } - props.setProperty("docker.host.address", host == null ? "" : host); - } - } - - // ================================================================================= - - @Override - public void contextualize(Context context) throws ContextException { - authConfigFactory = new AuthConfigFactory((PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY)); - } - - // ================================================================================= - - protected AuthConfig prepareAuthConfig(String image, String configuredRegistry) throws MojoExecutionException { - ImageName name = new ImageName(image); - String user = name.getUser(); - String registry = name.getRegistry() != null ? name.getRegistry() : configuredRegistry; - - return authConfigFactory.createAuthConfig(authConfig, settings, user, registry); - } - - protected LogDispatcher getLogDispatcher(DockerAccess docker) { - LogDispatcher dispatcher = (LogDispatcher) getPluginContext().get(CONTEXT_KEY_LOG_DISPATCHER); - if (dispatcher == null) { - dispatcher = new LogDispatcher(docker, useColor); - dispatcher.addLogOutputStream(System.out); - getPluginContext().put(CONTEXT_KEY_LOG_DISPATCHER, dispatcher); - } - return dispatcher; - } - - protected ContainerLogOutputSpec getContainerLogSpec(String containerId, ImageConfiguration imageConfiguration) { - ContainerLogOutputSpec.Builder builder = new ContainerLogOutputSpec.Builder(); - LogConfiguration logConfig = extractLogConfiguration(imageConfiguration); - - addLogFormat(builder, logConfig); - addPrefix(builder, logConfig.getPrefix(), imageConfiguration.getAlias(), containerId); - - builder.containerId(containerId) - .color(logConfig.getColor()); - - return builder.build(); - } - - private void addPrefix(ContainerLogOutputSpec.Builder builder, String logPrefix, String alias, String containerId) { - String prefix = logPrefix; - if (prefix == null) { - prefix = alias; - } - if (prefix == null) { - prefix = containerId.substring(0, 6); - } - builder.prefix(prefix); - } - - private void addLogFormat(ContainerLogOutputSpec.Builder builder, LogConfiguration logConfig) { - String logFormat = logConfig.getDate() != null ? logConfig.getDate() : logDate; - if (logFormat != null && logFormat.equalsIgnoreCase("true")) { - logFormat = "DEFAULT"; - } - if (logFormat != null) { - builder.timeFormatter(logFormat); - } - } - - private LogConfiguration extractLogConfiguration(ImageConfiguration imageConfiguration) { - RunImageConfiguration runConfig = imageConfiguration.getRunConfiguration(); - LogConfiguration logConfig = null; - if (runConfig != null) { - logConfig = runConfig.getLog(); - } - if (logConfig == null) { - logConfig = LogConfiguration.DEFAULT; - } - return logConfig; - } - - /** - * Try to get the registry from various configuration parameters - * - * @param imageConfig image config which might contain the registry - * @return the registry found or null if none could be extracted - */ - protected String getConfiguredRegistry(ImageConfiguration imageConfig) { - return EnvUtil.findRegistry(imageConfig.getRegistry(), registry); - } - - /** - * Check an image, and, if autoPull is set to true, fetch it. Otherwise if the image - * is not existent, throw an error - * - * @param docker access object to lookup an image (if autoPull is enabled) - * @param name image name - * @param registry optional registry which is used if the image itself doesn't have a registry. - * @param autoPullAlwaysAllowed whether an unconditional autopull is allowed. - * - * @throws DockerAccessException - * @throws MojoExecutionException - */ - protected void checkImageWithAutoPull(DockerAccess docker, String name, String registry, - boolean autoPullAlwaysAllowed) throws DockerAccessException, MojoExecutionException { - // TODO: further refactoring could be done to avoid referencing the QueryService here - QueryService queryService = serviceHub.getQueryService(); - if (!queryService.imageRequiresAutoPull(autoPull, name, autoPullAlwaysAllowed)) { - return; - } - - docker.pullImage(withLatestIfNoTag(name), prepareAuthConfig(name, registry), registry); - ImageName imageName = new ImageName(name); - if (registry != null && !imageName.hasRegistry()) { - // If coming from a registry which was not contained in the original name, add a tag from the - // short name with no-registry to the full name with the registry. - docker.tag(imageName.getFullName(registry), name, false); - } - } - - // Fetch only latest if no tag is given - private String withLatestIfNoTag(String name) { - ImageName imageName = new ImageName(name); - return imageName.getTag() == null ? imageName.getNameWithoutTag() + ":latest" : name; - } -} diff --git a/All/Genesis-NP/Genesis#194/old/AbstractDockerMojo.java b/All/Genesis-NP/Genesis#194/old/AbstractDockerMojo.java deleted file mode 100755 index 23a69fa..0000000 --- a/All/Genesis-NP/Genesis#194/old/AbstractDockerMojo.java +++ /dev/null @@ -1,397 +0,0 @@ -package org.jolokia.docker.maven; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.project.MavenProject; -import org.apache.maven.settings.Settings; -import org.codehaus.plexus.PlexusConstants; -import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.context.Context; -import org.codehaus.plexus.context.ContextException; -import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; -import org.jolokia.docker.maven.access.AuthConfig; -import org.jolokia.docker.maven.access.DockerAccess; -import org.jolokia.docker.maven.access.DockerAccessException; -import org.jolokia.docker.maven.access.hc.DockerAccessWithHcClient; -import org.jolokia.docker.maven.config.ImageConfiguration; -import org.jolokia.docker.maven.config.LogConfiguration; -import org.jolokia.docker.maven.config.RunImageConfiguration; -import org.jolokia.docker.maven.config.handler.ImageConfigResolver; -import org.jolokia.docker.maven.log.ContainerLogOutputSpec; -import org.jolokia.docker.maven.log.LogDispatcher; -import org.jolokia.docker.maven.service.QueryService; -import org.jolokia.docker.maven.service.ServiceHub; -import org.jolokia.docker.maven.util.AnsiLogger; -import org.jolokia.docker.maven.util.AuthConfigFactory; -import org.jolokia.docker.maven.util.EnvUtil; -import org.jolokia.docker.maven.util.ImageName; -import org.jolokia.docker.maven.util.Logger; - -/** - * Base class for this plugin. - * - * @author roland - * @since 26.03.14 - */ -public abstract class AbstractDockerMojo extends AbstractMojo implements Contextualizable { - - // Key for indicating that a "start" goal has run - public static final String CONTEXT_KEY_START_CALLED = "CONTEXT_KEY_DOCKER_START_CALLED"; - - // Key holding the log dispatcher - public static final Object CONTEXT_KEY_LOG_DISPATCHER = "CONTEXT_KEY_DOCKER_LOG_DISPATCHER"; - - // Standard HTTPS port (IANA registered). The other 2375 with plain HTTP is used only in older - // docker installations. - public static final String DOCKER_HTTPS_PORT = "2376"; - - public static final String API_VERSION = "v1.17"; - - // Current maven project - /** @parameter default-value="${project}" */ - protected MavenProject project; - - // Settings holding authentication info - /** @component */ - protected Settings settings; - - // Handler for external configurations - /** @component */ - protected ImageConfigResolver imageConfigResolver; - - /** @component **/ - protected ServiceHub serviceHub; - - /** @parameter property = "docker.autoPull" default-value = "on" */ - protected String autoPull; - - /** - * Whether to keep the containers afters stopping (start/watch/stop) - * - * @parameter property = "docker.keepContainer" default-value = "false" - */ - protected boolean keepContainer; - - /** - * Whether to remove volumes when removing the container (start/watch/stop) - * - * @parameter property = "docker.removeVolumes" defaultValue = "false" - */ - protected boolean removeVolumes; - - /** @parameter property = "docker.apiVersion" */ - private String apiVersion; - - // URL to docker daemon - /** @parameter property = "docker.host" */ - private String dockerHost; - - /** @parameter property = "docker.certPath" */ - private String certPath; - - // If logging is enabled globally - - // Whether to use color - /** @parameter property = "docker.useColor" default-value = "true" */ - protected boolean useColor; - - // For verbose output - /** @parameter property = "docker.verbose" default-value = "false" */ - protected boolean verbose; - - // The date format to use when putting out logs - /** @parameter property = "docker.logDate" */ - private String logDate; - - // Whether to skip docker altogether - /** @parameter property = "docker.skip" default-value = "false" */ - private boolean skip; - - // Whether to restrict operation to a single image. This can be either - // the image or an alias name. It can also be comma separated list. - // This parameter is typically set via the command line. - /** @parameter property = "docker.image" */ - private String image; - - // Default registry to use if no registry is specified - /** @parameter property = "docker.registry" */ - private String registry; - - // maximum connection to use in parallel for connecting the docker host - /** @parameter property = "docker.maxConnections" default-value = "100" */ - private int maxConnections; - - // property file to write out with port mappings - /** @parameter */ - protected String portPropertyFile; - - // Authentication information - /** @parameter */ - Map authConfig; - - // Relevant configuration to use. This includes also references to external - // images - /** - * @parameter - */ - private List images; - - // Handler dealing with authentication credentials - private AuthConfigFactory authConfigFactory; - - protected Logger log; - - /** - * Entry point for this plugin. It will set up the helper class and then calls {@link #executeInternal(DockerAccess)} - * which must be implemented by subclass. - * - * @throws MojoExecutionException - * @throws MojoFailureException - */ - @Override - public void execute() throws MojoExecutionException, MojoFailureException { - if (!skip) { - log = new AnsiLogger(getLog(), useColor, verbose); - - validateConfiguration(log); - - String dockerUrl = EnvUtil.extractUrl(dockerHost); - DockerAccess access = createDockerAccess(dockerUrl); - setDockerHostAddressProperty(dockerUrl); - serviceHub.init(access,log); - - try { - executeInternal(access); - } catch (DockerAccessException exp) { - throw new MojoExecutionException(log.errorMessage(exp.getMessage()), exp); - } finally { - access.shutdown(); - } - } - } - - private void validateConfiguration(Logger log) { - for (ImageConfiguration imageConfiguration : images) { - imageConfiguration.validate(log); - } - } - - /** - * Hook for subclass for doing the real job - * - * @param dockerAccess access object for getting to the DockerServer - */ - protected abstract void executeInternal(DockerAccess dockerAccess) - throws DockerAccessException, MojoExecutionException; - - // ============================================================================================= - - /** - * Get all images to use. Can be restricted via -Ddocker.image to pick a one or more images. The values - * is taken as comma separated list. - * - * @return list of image configuration to use - */ - protected List getImages() { - List resolvedImages = resolveImages(); - List ret = new ArrayList<>(); - for (ImageConfiguration imageConfig : resolvedImages) { - if (matchesConfiguredImages(this.image, imageConfig)) { - ret.add(imageConfig); - } - } - return ret; - } - - private List resolveImages() { - List ret = new ArrayList<>(); - if (images != null) { - for (ImageConfiguration image : images) { - ret.addAll(imageConfigResolver.resolve(image, project.getProperties())); - } - verifyImageNames(ret); - } - return ret; - } - - // Extract authentication information - private void verifyImageNames(List ret) { - for (ImageConfiguration config : ret) { - if (config.getName() == null) { - throw new IllegalArgumentException("Configuration error: must have a non-null "); - } - } - } - - // Check if the provided image configuration matches the given - protected boolean matchesConfiguredImages(String imageList, ImageConfiguration imageConfig) { - if (imageList == null) { - return true; - } - Set imagesAllowed = new HashSet<>(Arrays.asList(imageList.split("\\s*,\\s*"))); - return imagesAllowed.contains(imageConfig.getName()) || imagesAllowed.contains(imageConfig.getAlias()); - } - - private DockerAccess createDockerAccess(String baseUrl) throws MojoExecutionException { - try { - String version = (apiVersion == null) ? API_VERSION : apiVersion; - DockerAccess client = new DockerAccessWithHcClient(version, baseUrl, - EnvUtil.getCertPath(certPath), maxConnections, log); - client.start(); - - return client; - } - catch (IOException e) { - throw new MojoExecutionException("Cannot create docker access object ", e); - } - } - - // Registry for managed containers - private void setDockerHostAddressProperty(String dockerUrl) throws MojoFailureException { - Properties props = project.getProperties(); - if (props.getProperty("docker.host.address") == null) { - final String host; - try { - URI uri = new URI(dockerUrl); - if (uri.getHost() == null && uri.getScheme().equals("unix")) { - host = "localhost"; - } else { - host = uri.getHost(); - } - } catch (URISyntaxException e) { - throw new MojoFailureException("Cannot parse " + dockerUrl + " as URI: " + e.getMessage(), e); - } - props.setProperty("docker.host.address", host == null ? "" : host); - } - } - - // ================================================================================= - - @Override - public void contextualize(Context context) throws ContextException { - authConfigFactory = new AuthConfigFactory((PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY)); - } - - // ================================================================================= - - protected AuthConfig prepareAuthConfig(String image, String configuredRegistry) throws MojoExecutionException { - ImageName name = new ImageName(image); - String user = name.getUser(); - String registry = name.getRegistry() != null ? name.getRegistry() : configuredRegistry; - - return authConfigFactory.createAuthConfig(authConfig, settings, user, registry); - } - - protected LogDispatcher getLogDispatcher(DockerAccess docker) { - LogDispatcher dispatcher = (LogDispatcher) getPluginContext().get(CONTEXT_KEY_LOG_DISPATCHER); - if (dispatcher == null) { - dispatcher = new LogDispatcher(docker, useColor); - dispatcher.addLogOutputStream(System.out); - getPluginContext().put(CONTEXT_KEY_LOG_DISPATCHER, dispatcher); - } - return dispatcher; - } - - protected ContainerLogOutputSpec getContainerLogSpec(String containerId, ImageConfiguration imageConfiguration) { - ContainerLogOutputSpec.Builder builder = new ContainerLogOutputSpec.Builder(); - LogConfiguration logConfig = extractLogConfiguration(imageConfiguration); - - addLogFormat(builder, logConfig); - addPrefix(builder, logConfig.getPrefix(), imageConfiguration.getAlias(), containerId); - - builder.containerId(containerId) - .color(logConfig.getColor()); - - return builder.build(); - } - - private void addPrefix(ContainerLogOutputSpec.Builder builder, String logPrefix, String alias, String containerId) { - String prefix = logPrefix; - if (prefix == null) { - prefix = alias; - } - if (prefix == null) { - prefix = containerId.substring(0, 6); - } - builder.prefix(prefix); - } - - private void addLogFormat(ContainerLogOutputSpec.Builder builder, LogConfiguration logConfig) { - String logFormat = logConfig.getDate() != null ? logConfig.getDate() : logDate; - if (logFormat != null && logFormat.equalsIgnoreCase("true")) { - logFormat = "DEFAULT"; - } - if (logFormat != null) { - builder.timeFormatter(logFormat); - } - } - - private LogConfiguration extractLogConfiguration(ImageConfiguration imageConfiguration) { - RunImageConfiguration runConfig = imageConfiguration.getRunConfiguration(); - LogConfiguration logConfig = null; - if (runConfig != null) { - logConfig = runConfig.getLog(); - } - if (logConfig == null) { - logConfig = LogConfiguration.DEFAULT; - } - return logConfig; - } - - /** - * Try to get the registry from various configuration parameters - * - * @param imageConfig image config which might contain the registry - * @return the registry found or null if none could be extracted - */ - protected String getConfiguredRegistry(ImageConfiguration imageConfig) { - return EnvUtil.findRegistry(imageConfig.getRegistry(), registry); - } - - /** - * Check an image, and, if autoPull is set to true, fetch it. Otherwise if the image - * is not existent, throw an error - * - * @param docker access object to lookup an image (if autoPull is enabled) - * @param name image name - * @param registry optional registry which is used if the image itself doesn't have a registry. - * @param autoPullAlwaysAllowed whether an unconditional autopull is allowed. - * - * @throws DockerAccessException - * @throws MojoExecutionException - */ - protected void checkImageWithAutoPull(DockerAccess docker, String name, String registry, - boolean autoPullAlwaysAllowed) throws DockerAccessException, MojoExecutionException { - // TODO: further refactoring could be done to avoid referencing the QueryService here - QueryService queryService = serviceHub.getQueryService(); - if (!queryService.imageRequiresAutoPull(autoPull, name, autoPullAlwaysAllowed)) { - return; - } - - docker.pullImage(withLatestIfNoTag(name), prepareAuthConfig(name, registry), registry); - ImageName imageName = new ImageName(name); - if (registry != null && !imageName.hasRegistry()) { - // If coming from a registry which was not contained in the original name, add a tag from the - // short name with no-registry to the full name with the registry. - docker.tag(imageName.getFullName(registry), name, false); - } - } - - // Fetch only latest if no tag is given - private String withLatestIfNoTag(String name) { - ImageName imageName = new ImageName(name); - return imageName.getTag() == null ? imageName.getNameWithoutTag() + ":latest" : name; - } -} diff --git a/All/Genesis-NP/Genesis#194/pair.info b/All/Genesis-NP/Genesis#194/pair.info deleted file mode 100755 index 69bff02..0000000 --- a/All/Genesis-NP/Genesis#194/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:194 -SATName:Genesis -modifiedFPath:src/main/java/org/jolokia/docker/maven/AbstractDockerMojo.java -comSha:ebc07da6fe3b300677d4b4741934cd1b3b961ca5 -parentComSha:ebc07da6fe3b300677d4b4741934cd1b3b961ca5^1 -githubUrl:https://github.com/rhuss/docker-maven-plugin -repoName:rhuss#docker-maven-plugin \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#203/comMsg.txt b/All/Genesis-NP/Genesis#203/comMsg.txt deleted file mode 100755 index 4755a2a..0000000 --- a/All/Genesis-NP/Genesis#203/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Avoid NPE as discussed in https://github.com/ktoso/maven-git-commit-id-plugin/issues/57 diff --git a/All/Genesis-NP/Genesis#203/diff.diff b/All/Genesis-NP/Genesis#203/diff.diff deleted file mode 100755 index d403bed..0000000 --- a/All/Genesis-NP/Genesis#203/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/main/java/pl/project13/maven/git/JGitProvider.java b/src/main/java/pl/project13/maven/git/JGitProvider.java -index 9778217..8d11122 100644 ---- a/src/main/java/pl/project13/maven/git/JGitProvider.java -+++ b/src/main/java/pl/project13/maven/git/JGitProvider.java -@@ -86,2 +86,2 @@ public class JGitProvider extends GitDataProvider { -- Ref HEAD = git.getRef(Constants.HEAD); -- if (HEAD == null) { -+ Ref head = git.getRef(Constants.HEAD); -+ if (head == null) { -@@ -91 +91,5 @@ public class JGitProvider extends GitDataProvider { -- headCommit = revWalk.parseCommit(HEAD.getObjectId()); -+ ObjectId headObjectId = head.getObjectId(); -+ if(headObjectId == null){ -+ throw new MojoExecutionException("Could not get HEAD Ref, are you sure you've some commits in the dotGitDirectory?"); -+ } -+ headCommit = revWalk.parseCommit(headObjectId); diff --git a/All/Genesis-NP/Genesis#203/new/JGitProvider.java b/All/Genesis-NP/Genesis#203/new/JGitProvider.java deleted file mode 100755 index 8d11122..0000000 --- a/All/Genesis-NP/Genesis#203/new/JGitProvider.java +++ /dev/null @@ -1,280 +0,0 @@ -package pl.project13.maven.git; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.base.MoreObjects; -import com.google.common.base.Objects; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; - -import org.apache.maven.plugin.MojoExecutionException; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.AbbreviatedObjectId; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; -import org.jetbrains.annotations.NotNull; - -import pl.project13.jgit.DescribeCommand; -import pl.project13.jgit.DescribeResult; -import pl.project13.maven.git.log.LoggerBridge; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Collection; -import java.util.Date; -import java.util.List; - -/** - * @author Konrad 'ktoso' Malawski - */ -public class JGitProvider extends GitDataProvider { - - private File dotGitDirectory; - private Repository git; - private ObjectReader objectReader; - private RevWalk revWalk; - private RevCommit headCommit; - - @NotNull - public static JGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) { - return new JGitProvider(dotGitDirectory, loggerBridge); - } - - JGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) { - super(loggerBridge); - this.dotGitDirectory = dotGitDirectory; - } - - @NotNull - public JGitProvider setVerbose(boolean verbose) { - super.verbose = verbose; - super.loggerBridge.setVerbose(verbose); - return this; - } - - @Override - protected void init() throws MojoExecutionException { - git = getGitRepository(); - objectReader = git.newObjectReader(); - } - - @Override - protected String getBuildAuthorName() { - String userName = git.getConfig().getString("user", null, "name"); - return MoreObjects.firstNonNull(userName, ""); - } - - @Override - protected String getBuildAuthorEmail() { - String userEmail = git.getConfig().getString("user", null, "email"); - return MoreObjects.firstNonNull(userEmail, ""); - } - - @Override - protected void prepareGitToExtractMoreDetailedReproInformation() throws MojoExecutionException { - try { - // more details parsed out bellow - Ref head = git.getRef(Constants.HEAD); - if (head == null) { - throw new MojoExecutionException("Could not get HEAD Ref, are you sure you've set the dotGitDirectory property of this plugin to a valid path?"); - } - revWalk = new RevWalk(git); - ObjectId headObjectId = head.getObjectId(); - if(headObjectId == null){ - throw new MojoExecutionException("Could not get HEAD Ref, are you sure you've some commits in the dotGitDirectory?"); - } - headCommit = revWalk.parseCommit(headObjectId); - revWalk.markStart(headCommit); - } catch (MojoExecutionException e) { - throw e; - } catch (Exception e) { - throw new MojoExecutionException("Error", e); - } - } - - @Override - protected String getBranchName() throws IOException { - String branch = git.getBranch(); - return branch; - } - - @Override - protected String getGitDescribe() throws MojoExecutionException { - String gitDescribe = getGitDescribe(git); - return gitDescribe; - } - - @Override - protected String getCommitId() { - String commitId = headCommit.getName(); - return commitId; - } - - @Override - protected String getAbbrevCommitId() throws MojoExecutionException { - String abbrevCommitId = getAbbrevCommitId(objectReader, headCommit, abbrevLength); - return abbrevCommitId; - } - - @Override - protected boolean isDirty() throws MojoExecutionException { - Git gitObject = Git.wrap(git); - try { - return !gitObject.status().call().isClean(); - } catch (GitAPIException e) { - throw new MojoExecutionException("Failed to get git status: " + e.getMessage(), e); - } - } - - @Override - protected String getCommitAuthorName() { - String commitAuthor = headCommit.getAuthorIdent().getName(); - return commitAuthor; - } - - @Override - protected String getCommitAuthorEmail() { - String commitEmail = headCommit.getAuthorIdent().getEmailAddress(); - return commitEmail; - } - - @Override - protected String getCommitMessageFull() { - String fullMessage = headCommit.getFullMessage(); - return fullMessage.trim(); - } - - @Override - protected String getCommitMessageShort() { - String shortMessage = headCommit.getShortMessage(); - return shortMessage.trim(); - } - - @Override - protected String getCommitTime() { - long timeSinceEpoch = headCommit.getCommitTime(); - Date commitDate = new Date(timeSinceEpoch * 1000); // git is "by sec" and java is "by ms" - SimpleDateFormat smf = new SimpleDateFormat(dateFormat); - return smf.format(commitDate); - } - - @Override - protected String getRemoteOriginUrl() throws MojoExecutionException { - String remoteOriginUrl = git.getConfig().getString("remote", "origin", "url"); - return remoteOriginUrl; - } - - @Override - protected String getTags() throws MojoExecutionException { - RevWalk walk = null; - try { - Repository repo = getGitRepository(); - Git git = Git.wrap(repo); - walk = new RevWalk(repo); - List tagRefs = git.tagList().call(); - - final ObjectId headId = headCommit.toObjectId(); - final RevWalk finalWalk = walk; - Collection tagsForHeadCommit = Collections2.filter(tagRefs, new Predicate() { - @Override public boolean apply(Ref tagRef) { - boolean lightweightTag = tagRef.getObjectId().equals(headId); - - try { - // TODO make this configurable (most users shouldn't really care too much what kind of tag it is though) - return lightweightTag || finalWalk.parseTag(tagRef.getObjectId()).getObject().getId().equals(headId); // or normal tag - } catch (IOException e) { - return false; - } - } - }); - - Collection tags = Collections2.transform(tagsForHeadCommit, new Function() { - @Override public String apply(Ref input) { - return input.getName().replaceAll("refs/tags/", ""); - } - }); - - return Joiner.on(",").join(tags); - } catch (GitAPIException e) { - loggerBridge.error("Unable to extract tags from commit: " + headCommit.getName() + " (" + e.getClass().getName() + ")"); - return ""; - } finally { - if (walk != null) { - walk.dispose(); - } - } - } - - @Override - protected void finalCleanUp() { - if (revWalk != null) { - revWalk.dispose(); - } - } - - - @VisibleForTesting String getGitDescribe(@NotNull Repository repository) throws MojoExecutionException { - try { - DescribeResult describeResult = DescribeCommand - .on(repository) - .withLoggerBridge(super.loggerBridge) - .setVerbose(super.verbose) - .apply(super.gitDescribe) - .call(); - - return describeResult.toString(); - } catch (GitAPIException ex) { - ex.printStackTrace(); - throw new MojoExecutionException("Unable to obtain git.commit.id.describe information", ex); - } - } - - private String getAbbrevCommitId(ObjectReader objectReader, RevCommit headCommit, int abbrevLength) throws MojoExecutionException { - try { - AbbreviatedObjectId abbreviatedObjectId = objectReader.abbreviate(headCommit, abbrevLength); - return abbreviatedObjectId.name(); - } catch (IOException e) { - throw new MojoExecutionException("Unable to abbreviate commit id! " + - "You may want to investigate the element in your configuration.", e); - } - } - - - @NotNull - private Repository getGitRepository() throws MojoExecutionException { - Repository repository; - - FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder(); - try { - repository = repositoryBuilder - .setGitDir(dotGitDirectory) - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build(); - } catch (IOException e) { - throw new MojoExecutionException("Could not initialize repository...", e); - } - - if (repository == null) { - throw new MojoExecutionException("Could not create git repository. Are you sure '" + dotGitDirectory + "' is the valid Git root for your project?"); - } - - return repository; - } - - // SETTERS FOR TESTS ---------------------------------------------------- - - @VisibleForTesting - public void setRepository(Repository git) { - this.git = git; - } -} diff --git a/All/Genesis-NP/Genesis#203/old/JGitProvider.java b/All/Genesis-NP/Genesis#203/old/JGitProvider.java deleted file mode 100755 index 9778217..0000000 --- a/All/Genesis-NP/Genesis#203/old/JGitProvider.java +++ /dev/null @@ -1,276 +0,0 @@ -package pl.project13.maven.git; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Function; -import com.google.common.base.Joiner; -import com.google.common.base.MoreObjects; -import com.google.common.base.Objects; -import com.google.common.base.Predicate; -import com.google.common.collect.Collections2; - -import org.apache.maven.plugin.MojoExecutionException; -import org.eclipse.jgit.api.Git; -import org.eclipse.jgit.api.errors.GitAPIException; -import org.eclipse.jgit.lib.AbbreviatedObjectId; -import org.eclipse.jgit.lib.Constants; -import org.eclipse.jgit.lib.ObjectId; -import org.eclipse.jgit.lib.ObjectReader; -import org.eclipse.jgit.lib.Ref; -import org.eclipse.jgit.lib.Repository; -import org.eclipse.jgit.revwalk.RevCommit; -import org.eclipse.jgit.revwalk.RevWalk; -import org.eclipse.jgit.storage.file.FileRepositoryBuilder; -import org.jetbrains.annotations.NotNull; - -import pl.project13.jgit.DescribeCommand; -import pl.project13.jgit.DescribeResult; -import pl.project13.maven.git.log.LoggerBridge; - -import java.io.File; -import java.io.IOException; -import java.text.SimpleDateFormat; -import java.util.Collection; -import java.util.Date; -import java.util.List; - -/** - * @author Konrad 'ktoso' Malawski - */ -public class JGitProvider extends GitDataProvider { - - private File dotGitDirectory; - private Repository git; - private ObjectReader objectReader; - private RevWalk revWalk; - private RevCommit headCommit; - - @NotNull - public static JGitProvider on(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) { - return new JGitProvider(dotGitDirectory, loggerBridge); - } - - JGitProvider(@NotNull File dotGitDirectory, @NotNull LoggerBridge loggerBridge) { - super(loggerBridge); - this.dotGitDirectory = dotGitDirectory; - } - - @NotNull - public JGitProvider setVerbose(boolean verbose) { - super.verbose = verbose; - super.loggerBridge.setVerbose(verbose); - return this; - } - - @Override - protected void init() throws MojoExecutionException { - git = getGitRepository(); - objectReader = git.newObjectReader(); - } - - @Override - protected String getBuildAuthorName() { - String userName = git.getConfig().getString("user", null, "name"); - return MoreObjects.firstNonNull(userName, ""); - } - - @Override - protected String getBuildAuthorEmail() { - String userEmail = git.getConfig().getString("user", null, "email"); - return MoreObjects.firstNonNull(userEmail, ""); - } - - @Override - protected void prepareGitToExtractMoreDetailedReproInformation() throws MojoExecutionException { - try { - // more details parsed out bellow - Ref HEAD = git.getRef(Constants.HEAD); - if (HEAD == null) { - throw new MojoExecutionException("Could not get HEAD Ref, are you sure you've set the dotGitDirectory property of this plugin to a valid path?"); - } - revWalk = new RevWalk(git); - headCommit = revWalk.parseCommit(HEAD.getObjectId()); - revWalk.markStart(headCommit); - } catch (MojoExecutionException e) { - throw e; - } catch (Exception e) { - throw new MojoExecutionException("Error", e); - } - } - - @Override - protected String getBranchName() throws IOException { - String branch = git.getBranch(); - return branch; - } - - @Override - protected String getGitDescribe() throws MojoExecutionException { - String gitDescribe = getGitDescribe(git); - return gitDescribe; - } - - @Override - protected String getCommitId() { - String commitId = headCommit.getName(); - return commitId; - } - - @Override - protected String getAbbrevCommitId() throws MojoExecutionException { - String abbrevCommitId = getAbbrevCommitId(objectReader, headCommit, abbrevLength); - return abbrevCommitId; - } - - @Override - protected boolean isDirty() throws MojoExecutionException { - Git gitObject = Git.wrap(git); - try { - return !gitObject.status().call().isClean(); - } catch (GitAPIException e) { - throw new MojoExecutionException("Failed to get git status: " + e.getMessage(), e); - } - } - - @Override - protected String getCommitAuthorName() { - String commitAuthor = headCommit.getAuthorIdent().getName(); - return commitAuthor; - } - - @Override - protected String getCommitAuthorEmail() { - String commitEmail = headCommit.getAuthorIdent().getEmailAddress(); - return commitEmail; - } - - @Override - protected String getCommitMessageFull() { - String fullMessage = headCommit.getFullMessage(); - return fullMessage.trim(); - } - - @Override - protected String getCommitMessageShort() { - String shortMessage = headCommit.getShortMessage(); - return shortMessage.trim(); - } - - @Override - protected String getCommitTime() { - long timeSinceEpoch = headCommit.getCommitTime(); - Date commitDate = new Date(timeSinceEpoch * 1000); // git is "by sec" and java is "by ms" - SimpleDateFormat smf = new SimpleDateFormat(dateFormat); - return smf.format(commitDate); - } - - @Override - protected String getRemoteOriginUrl() throws MojoExecutionException { - String remoteOriginUrl = git.getConfig().getString("remote", "origin", "url"); - return remoteOriginUrl; - } - - @Override - protected String getTags() throws MojoExecutionException { - RevWalk walk = null; - try { - Repository repo = getGitRepository(); - Git git = Git.wrap(repo); - walk = new RevWalk(repo); - List tagRefs = git.tagList().call(); - - final ObjectId headId = headCommit.toObjectId(); - final RevWalk finalWalk = walk; - Collection tagsForHeadCommit = Collections2.filter(tagRefs, new Predicate() { - @Override public boolean apply(Ref tagRef) { - boolean lightweightTag = tagRef.getObjectId().equals(headId); - - try { - // TODO make this configurable (most users shouldn't really care too much what kind of tag it is though) - return lightweightTag || finalWalk.parseTag(tagRef.getObjectId()).getObject().getId().equals(headId); // or normal tag - } catch (IOException e) { - return false; - } - } - }); - - Collection tags = Collections2.transform(tagsForHeadCommit, new Function() { - @Override public String apply(Ref input) { - return input.getName().replaceAll("refs/tags/", ""); - } - }); - - return Joiner.on(",").join(tags); - } catch (GitAPIException e) { - loggerBridge.error("Unable to extract tags from commit: " + headCommit.getName() + " (" + e.getClass().getName() + ")"); - return ""; - } finally { - if (walk != null) { - walk.dispose(); - } - } - } - - @Override - protected void finalCleanUp() { - if (revWalk != null) { - revWalk.dispose(); - } - } - - - @VisibleForTesting String getGitDescribe(@NotNull Repository repository) throws MojoExecutionException { - try { - DescribeResult describeResult = DescribeCommand - .on(repository) - .withLoggerBridge(super.loggerBridge) - .setVerbose(super.verbose) - .apply(super.gitDescribe) - .call(); - - return describeResult.toString(); - } catch (GitAPIException ex) { - ex.printStackTrace(); - throw new MojoExecutionException("Unable to obtain git.commit.id.describe information", ex); - } - } - - private String getAbbrevCommitId(ObjectReader objectReader, RevCommit headCommit, int abbrevLength) throws MojoExecutionException { - try { - AbbreviatedObjectId abbreviatedObjectId = objectReader.abbreviate(headCommit, abbrevLength); - return abbreviatedObjectId.name(); - } catch (IOException e) { - throw new MojoExecutionException("Unable to abbreviate commit id! " + - "You may want to investigate the element in your configuration.", e); - } - } - - - @NotNull - private Repository getGitRepository() throws MojoExecutionException { - Repository repository; - - FileRepositoryBuilder repositoryBuilder = new FileRepositoryBuilder(); - try { - repository = repositoryBuilder - .setGitDir(dotGitDirectory) - .readEnvironment() // scan environment GIT_* variables - .findGitDir() // scan up the file system tree - .build(); - } catch (IOException e) { - throw new MojoExecutionException("Could not initialize repository...", e); - } - - if (repository == null) { - throw new MojoExecutionException("Could not create git repository. Are you sure '" + dotGitDirectory + "' is the valid Git root for your project?"); - } - - return repository; - } - - // SETTERS FOR TESTS ---------------------------------------------------- - - @VisibleForTesting - public void setRepository(Repository git) { - this.git = git; - } -} diff --git a/All/Genesis-NP/Genesis#203/pair.info b/All/Genesis-NP/Genesis#203/pair.info deleted file mode 100755 index d1f3d1d..0000000 --- a/All/Genesis-NP/Genesis#203/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:203 -SATName:Genesis -modifiedFPath:src/main/java/pl/project13/maven/git/JGitProvider.java -comSha:b5740b7672344bff38f178c048822b4aecd8239f -parentComSha:b5740b7672344bff38f178c048822b4aecd8239f^1 -githubUrl:https://github.com/ktoso/maven-git-commit-id-plugin -repoName:ktoso#maven-git-commit-id-plugin \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#205/comMsg.txt b/All/Genesis-NP/Genesis#205/comMsg.txt deleted file mode 100755 index 38fcb1c..0000000 --- a/All/Genesis-NP/Genesis#205/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -#590 Update methods are not supported for "method-and-conversion" methods (can currently cause NullPointerExceptions) diff --git a/All/Genesis-NP/Genesis#205/diff.diff b/All/Genesis-NP/Genesis#205/diff.diff deleted file mode 100755 index 246239d..0000000 --- a/All/Genesis-NP/Genesis#205/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/processor/src/main/java/org/mapstruct/ap/internal/processor/creation/MappingResolverImpl.java b/processor/src/main/java/org/mapstruct/ap/internal/processor/creation/MappingResolverImpl.java -index 41db416..8566fbc 100755 ---- a/processor/src/main/java/org/mapstruct/ap/internal/processor/creation/MappingResolverImpl.java -+++ b/processor/src/main/java/org/mapstruct/ap/internal/processor/creation/MappingResolverImpl.java -@@ -33,0 +34 @@ -+import org.mapstruct.ap.internal.model.MappingBuilderContext.MappingResolver; -@@ -36 +36,0 @@ --import org.mapstruct.ap.internal.model.MappingBuilderContext.MappingResolver; -@@ -393,0 +394,4 @@ private Assignment resolveViaMethodAndConversion(Type sourceType, Type targetTyp -+ if ( methodXCandidate.getMappingTargetParameter() != null ) { -+ continue; -+ } -+ diff --git a/All/Genesis-NP/Genesis#205/new/MappingResolverImpl.java b/All/Genesis-NP/Genesis#205/new/MappingResolverImpl.java deleted file mode 100755 index 8566fbc..0000000 --- a/All/Genesis-NP/Genesis#205/new/MappingResolverImpl.java +++ /dev/null @@ -1,607 +0,0 @@ -/** - * Copyright 2012-2015 Gunnar Morling (http://www.gunnarmorling.de/) - * and/or other contributors as indicated by the @authors tag. See the - * copyright.txt file in the distribution for a full listing of all - * contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.mapstruct.ap.internal.processor.creation; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; - -import org.mapstruct.ap.internal.conversion.ConversionProvider; -import org.mapstruct.ap.internal.conversion.Conversions; -import org.mapstruct.ap.internal.model.AssignmentFactory; -import org.mapstruct.ap.internal.model.MapperReference; -import org.mapstruct.ap.internal.model.MappingBuilderContext.MappingResolver; -import org.mapstruct.ap.internal.model.MethodReference; -import org.mapstruct.ap.internal.model.VirtualMappingMethod; -import org.mapstruct.ap.internal.model.assignment.Assignment; -import org.mapstruct.ap.internal.model.common.ConversionContext; -import org.mapstruct.ap.internal.model.common.DefaultConversionContext; -import org.mapstruct.ap.internal.model.common.Type; -import org.mapstruct.ap.internal.model.common.TypeFactory; -import org.mapstruct.ap.internal.model.source.Method; -import org.mapstruct.ap.internal.model.source.SourceMethod; -import org.mapstruct.ap.internal.model.source.builtin.BuiltInMappingMethods; -import org.mapstruct.ap.internal.model.source.builtin.BuiltInMethod; -import org.mapstruct.ap.internal.model.source.selector.MethodSelectors; -import org.mapstruct.ap.internal.model.source.selector.SelectionCriteria; -import org.mapstruct.ap.internal.util.FormattingMessager; -import org.mapstruct.ap.internal.util.Message; -import org.mapstruct.ap.internal.util.SpecificCompilerWorkarounds; -import org.mapstruct.ap.internal.util.Strings; - -/** - * The one and only implementation of {@link MappingResolver}. The class has been split into an interface an - * implementation for the sake of avoiding package dependencies. Specifically, this implementation refers to classes - * which should not be exposed to the {@code model} package. - * - * @author Sjaak Derksen - */ -public class MappingResolverImpl implements MappingResolver { - - private final FormattingMessager messager; - private final Types typeUtils; - private final TypeFactory typeFactory; - - private final List sourceModel; - private final List mapperReferences; - - private final Conversions conversions; - private final BuiltInMappingMethods builtInMethods; - private final MethodSelectors methodSelectors; - - /** - * Private methods which are not present in the original mapper interface and are added to map certain property - * types. - */ - private final Set usedVirtualMappings = new HashSet(); - - public MappingResolverImpl(FormattingMessager messager, Elements elementUtils, Types typeUtils, - TypeFactory typeFactory, List sourceModel, - List mapperReferences) { - this.messager = messager; - this.typeUtils = typeUtils; - this.typeFactory = typeFactory; - - this.sourceModel = sourceModel; - this.mapperReferences = mapperReferences; - - this.conversions = new Conversions( elementUtils, typeFactory ); - this.builtInMethods = new BuiltInMappingMethods( typeFactory ); - this.methodSelectors = new MethodSelectors( - typeUtils, - elementUtils, - typeFactory - ); - } - - @Override - public Assignment getTargetAssignment(Method mappingMethod, String mappedElement, Type sourceType, - Type targetType, String targetPropertyName, String dateFormat, List qualifiers, - TypeMirror resultType, String sourceReference, boolean preferUpdateMapping) { - - SelectionCriteria criteria = - new SelectionCriteria(qualifiers, targetPropertyName, resultType, preferUpdateMapping ); - - ResolvingAttempt attempt = new ResolvingAttempt( - sourceModel, - mappingMethod, - mappedElement, - dateFormat, - sourceReference, - criteria - ); - - return attempt.getTargetAssignment( sourceType, targetType ); - } - - @Override - public Set getUsedVirtualMappings() { - return usedVirtualMappings; - } - - @Override - public MethodReference getFactoryMethod( Method mappingMethod, Type targetType, List qualifiers, - TypeMirror resultType ) { - - SelectionCriteria criteria = new SelectionCriteria( qualifiers, null, resultType, false ); - - ResolvingAttempt attempt = new ResolvingAttempt( - sourceModel, - mappingMethod, - null, - null, - null, - criteria - ); - - SourceMethod matchingSourceMethod = attempt.getBestMatch( sourceModel, null, targetType ); - if ( matchingSourceMethod != null ) { - MapperReference ref = attempt.findMapperReference( matchingSourceMethod ); - return new MethodReference( matchingSourceMethod, ref, null ); - } - return null; - - } - - private class ResolvingAttempt { - - private final Method mappingMethod; - private final String mappedElement; - private final List methods; - private final String dateFormat; - private final SelectionCriteria selectionCriteria; - private final String sourceReference; - private final boolean savedPreferUpdateMapping; - - // resolving via 2 steps creates the possibillity of wrong matches, first builtin method matches, - // second doesn't. In that case, the first builtin method should not lead to a virtual method - // so this set must be cleared. - private final Set virtualMethodCandidates; - - private ResolvingAttempt(List sourceModel, Method mappingMethod, String mappedElement, - String dateFormat, String sourceReference, SelectionCriteria criteria) { - - this.mappingMethod = mappingMethod; - this.mappedElement = mappedElement; - this.methods = filterPossibleCandidateMethods( sourceModel ); - this.dateFormat = dateFormat; - this.sourceReference = sourceReference; - this.virtualMethodCandidates = new HashSet(); - this.selectionCriteria = criteria; - this.savedPreferUpdateMapping = criteria.isPreferUpdateMapping(); - } - - private List filterPossibleCandidateMethods(List candidateMethods) { - List result = new ArrayList( candidateMethods.size() ); - for ( T candidate : candidateMethods ) { - if ( isCandidateForMapping( candidate ) ) { - result.add( candidate ); - } - } - - return result; - } - - private Assignment getTargetAssignment(Type sourceType, Type targetType) { - - // first simple mapping method - Assignment referencedMethod = resolveViaMethod( sourceType, targetType, false ); - if ( referencedMethod != null ) { - referencedMethod.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - return referencedMethod; - } - - // then direct assignable - if ( sourceType.isAssignableTo( targetType ) || isPropertyMappable( sourceType, targetType ) ) { - Assignment simpleAssignment = AssignmentFactory.createDirect( sourceReference ); - return simpleAssignment; - } - - // then type conversion - Assignment conversion = resolveViaConversion( sourceType, targetType ); - if ( conversion != null ) { - conversion.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - return conversion; - } - - // check for a built-in method - Assignment builtInMethod = resolveViaBuiltInMethod( sourceType, targetType ); - if ( builtInMethod != null ) { - builtInMethod.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - usedVirtualMappings.addAll( virtualMethodCandidates ); - return builtInMethod; - } - - // 2 step method, first: method(method(source)) - referencedMethod = resolveViaMethodAndMethod( sourceType, targetType ); - if ( referencedMethod != null ) { - usedVirtualMappings.addAll( virtualMethodCandidates ); - return referencedMethod; - } - - // 2 step method, then: method(conversion(source)) - referencedMethod = resolveViaConversionAndMethod( sourceType, targetType ); - if ( referencedMethod != null ) { - usedVirtualMappings.addAll( virtualMethodCandidates ); - return referencedMethod; - } - - // stop here when looking for update methods. - selectionCriteria.setPreferUpdateMapping( false ); - - // 2 step method, finally: conversion(method(source)) - conversion = resolveViaMethodAndConversion( sourceType, targetType ); - if ( conversion != null ) { - usedVirtualMappings.addAll( virtualMethodCandidates ); - return conversion; - } - - // if nothing works, alas, the result is null - return null; - } - - private Assignment resolveViaConversion(Type sourceType, Type targetType) { - ConversionProvider conversionProvider = conversions.getConversion( sourceType, targetType ); - - if ( conversionProvider == null ) { - return null; - } - - ConversionContext ctx = - new DefaultConversionContext( typeFactory, messager, sourceType, targetType, dateFormat ); - return conversionProvider.to( ctx ); - } - - /** - * Returns a reference to a method mapping the given source type to the given target type, if such a method - * exists. - */ - private Assignment resolveViaMethod(Type sourceType, Type targetType, boolean considerBuiltInMethods) { - - // first try to find a matching source method - SourceMethod matchingSourceMethod = getBestMatch( methods, sourceType, targetType ); - - if ( matchingSourceMethod != null ) { - return getMappingMethodReference( matchingSourceMethod, targetType ); - } - - if ( considerBuiltInMethods ) { - return resolveViaBuiltInMethod( sourceType, targetType ); - } - - return null; - } - - private Assignment resolveViaBuiltInMethod(Type sourceType, Type targetType) { - BuiltInMethod matchingBuiltInMethod = - getBestMatch( builtInMethods.getBuiltInMethods(), sourceType, targetType ); - - if ( matchingBuiltInMethod != null ) { - virtualMethodCandidates.add( new VirtualMappingMethod( matchingBuiltInMethod ) ); - ConversionContext ctx = new DefaultConversionContext( typeFactory, messager, - sourceType, - targetType, dateFormat ); - Assignment methodReference = AssignmentFactory.createMethodReference( matchingBuiltInMethod, ctx ); - methodReference.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - return methodReference; - } - - return null; - } - - /** - * Suppose mapping required from A to C and: - *
    - *
  • no direct referenced mapping method either built-in or referenced is available from A to C
  • - *
  • no conversion is available
  • - *
  • there is a method from A to B, methodX
  • - *
  • there is a method from B to C, methodY
  • - *
- * then this method tries to resolve this combination and make a mapping methodY( methodX ( parameter ) ) - */ - private Assignment resolveViaMethodAndMethod(Type sourceType, Type targetType) { - - List methodYCandidates = new ArrayList( methods ); - methodYCandidates.addAll( builtInMethods.getBuiltInMethods() ); - - Assignment methodRefY = null; - - // Iterate over all source methods. Check if the return type matches with the parameter that we need. - // so assume we need a method from A to C we look for a methodX from A to B (all methods in the - // list form such a candidate). - // For each of the candidates, we need to look if there's a methodY, either - // sourceMethod or builtIn that fits the signature B to C. Only then there is a match. If we have a match - // a nested method call can be called. so C = methodY( methodX (A) ) - for ( Method methodYCandidate : methodYCandidates ) { - methodRefY = - resolveViaMethod( methodYCandidate.getSourceParameters().get( 0 ).getType(), targetType, true ); - - if ( methodRefY != null ) { - selectionCriteria.setPreferUpdateMapping( false ); - Assignment methodRefX = - resolveViaMethod( sourceType, methodYCandidate.getSourceParameters().get( 0 ).getType(), true ); - selectionCriteria.setPreferUpdateMapping( savedPreferUpdateMapping ); - if ( methodRefX != null ) { - methodRefY.setAssignment( methodRefX ); - methodRefX.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - break; - } - else { - // both should match; - virtualMethodCandidates.clear(); - methodRefY = null; - } - } - } - return methodRefY; - } - - /** - * Suppose mapping required from A to C and: - *
    - *
  • there is a conversion from A to B, conversionX
  • - *
  • there is a method from B to C, methodY
  • - *
- * then this method tries to resolve this combination and make a mapping methodY( conversionX ( parameter ) ) - */ - private Assignment resolveViaConversionAndMethod(Type sourceType, Type targetType) { - - List methodYCandidates = new ArrayList( methods ); - methodYCandidates.addAll( builtInMethods.getBuiltInMethods() ); - - Assignment methodRefY = null; - - for ( Method methodYCandidate : methodYCandidates ) { - methodRefY = - resolveViaMethod( methodYCandidate.getSourceParameters().get( 0 ).getType(), targetType, true ); - - if ( methodRefY != null ) { - Assignment conversionXRef = - resolveViaConversion( sourceType, methodYCandidate.getSourceParameters().get( 0 ).getType() ); - if ( conversionXRef != null ) { - methodRefY.setAssignment( conversionXRef ); - conversionXRef.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - break; - } - else { - // both should match - virtualMethodCandidates.clear(); - methodRefY = null; - } - } - } - return methodRefY; - } - - /** - * Suppose mapping required from A to C and: - *
    - *
  • there is a conversion from A to B, conversionX
  • - *
  • there is a method from B to C, methodY
  • - *
- * then this method tries to resolve this combination and make a mapping methodY( conversionX ( parameter ) ) - */ - private Assignment resolveViaMethodAndConversion(Type sourceType, Type targetType) { - - List methodXCandidates = new ArrayList( methods ); - methodXCandidates.addAll( builtInMethods.getBuiltInMethods() ); - - Assignment conversionYRef = null; - - // search the other way around - for ( Method methodXCandidate : methodXCandidates ) { - if ( methodXCandidate.getMappingTargetParameter() != null ) { - continue; - } - - Assignment methodRefX = resolveViaMethod( - sourceType, - methodXCandidate.getReturnType(), - true - ); - if ( methodRefX != null ) { - conversionYRef = resolveViaConversion( methodXCandidate.getReturnType(), targetType ); - if ( conversionYRef != null ) { - conversionYRef.setAssignment( methodRefX ); - methodRefX.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - break; - } - else { - // both should match; - virtualMethodCandidates.clear(); - conversionYRef = null; - } - } - } - return conversionYRef; - } - - private boolean isCandidateForMapping(Method methodCandidate) { - return isCreateMethodForMapping( methodCandidate ) || isUpdateMethodForMapping( methodCandidate ); - } - - private boolean isCreateMethodForMapping(Method methodCandidate) { - // a create method may not return void and has no target parameter - return methodCandidate.getSourceParameters().size() == 1 - && !methodCandidate.getReturnType().isVoid() - && methodCandidate.getMappingTargetParameter() == null - && !methodCandidate.isLifecycleCallbackMethod(); - } - - private boolean isUpdateMethodForMapping(Method methodCandidate) { - // an update method may, or may not return void and has a target parameter - return methodCandidate.getSourceParameters().size() == 1 - && methodCandidate.getMappingTargetParameter() != null - && !methodCandidate.isLifecycleCallbackMethod(); - } - - private T getBestMatch(List methods, Type sourceType, Type returnType) { - - List candidates = methodSelectors.getMatchingMethods( - mappingMethod, - methods, - sourceType, - returnType, - selectionCriteria - ); - - // raise an error if more than one mapping method is suitable to map the given source type - // into the target type - if ( candidates.size() > 1 ) { - - if ( mappedElement != null ) { - messager.printMessage( mappingMethod.getExecutable(), - Message.GENERAL_AMBIGIOUS_MAPPING_METHOD, - mappedElement, - returnType, - Strings.join( candidates, ", " ) - ); - } - else { - messager.printMessage( mappingMethod.getExecutable(), - Message.GENERAL_AMBIGIOUS_FACTORY_METHOD, - returnType, - Strings.join( candidates, ", " ) - ); - } - } - - if ( !candidates.isEmpty() ) { - return candidates.get( 0 ); - } - - return null; - } - - private Assignment getMappingMethodReference(SourceMethod method, - Type targetType) { - MapperReference mapperReference = findMapperReference( method ); - - return AssignmentFactory.createMethodReference( - method, - mapperReference, - SourceMethod.containsTargetTypeParameter( method.getParameters() ) ? targetType : null - ); - } - - private MapperReference findMapperReference(SourceMethod method) { - for ( MapperReference ref : mapperReferences ) { - if ( ref.getType().equals( method.getDeclaringMapper() ) ) { - ref.setUsed( !method.isStatic() ); - ref.setTypeRequiresImport( true ); - return ref; - } - } - return null; - } - - /** - * Whether the specified property can be mapped from source to target or not. A mapping if possible if one of - * the following conditions is true: - *
    - *
  • the source type is assignable to the target type
  • - *
  • a mapping method exists
  • - *
  • a built-in conversion exists
  • - *
  • the property is of a collection or map type and the constructor of the target type (either itself or its - * implementation type) accepts the source type.
  • - *
- * - * @return {@code true} if the specified property can be mapped, {@code false} otherwise. - */ - private boolean isPropertyMappable(Type sourceType, Type targetType) { - boolean collectionOrMapTargetTypeHasCompatibleConstructor = false; - - if ( sourceType.isCollectionType() && targetType.isCollectionType() ) { - collectionOrMapTargetTypeHasCompatibleConstructor = collectionTypeHasCompatibleConstructor( - sourceType, - targetType.getImplementationType() != null - ? targetType.getImplementationType() : targetType - ); - } - - if ( sourceType.isMapType() && targetType.isMapType() ) { - collectionOrMapTargetTypeHasCompatibleConstructor = mapTypeHasCompatibleConstructor( - sourceType, - targetType.getImplementationType() != null - ? targetType.getImplementationType() : targetType - ); - } - - if ( ( ( targetType.isCollectionType() || targetType.isMapType() ) - && collectionOrMapTargetTypeHasCompatibleConstructor ) ) { - return true; - } - - return false; - } - - /** - * Whether the given target type has a single-argument constructor which accepts the given source type. - * - * @param sourceType the source type - * @param targetType the target type - * - * @return {@code true} if the target type has a constructor accepting the given source type, {@code false} - * otherwise. - */ - private boolean collectionTypeHasCompatibleConstructor(Type sourceType, Type targetType) { - // note (issue #127): actually this should check for the presence of a matching constructor, with help of - // Types#asMemberOf(); but this method seems to not work correctly in the Eclipse implementation, so instead - // we just check whether the target type is parameterized in a way that it implicitly should have a - // constructor which accepts the source type - - TypeMirror sourceElementType = sourceType.getTypeParameters().isEmpty() - ? typeFactory.getType( Object.class ).getTypeMirror() - : sourceType.getTypeParameters().get( 0 ).getTypeMirror(); - - TypeMirror targetElementType = targetType.getTypeParameters().isEmpty() - ? typeFactory.getType( Object.class ).getTypeMirror() - : targetType.getTypeParameters().get( 0 ).getTypeMirror(); - - return SpecificCompilerWorkarounds.isAssignable( typeUtils, sourceElementType, targetElementType ); - } - - /** - * Whether the given target type has a single-argument constructor which accepts the given source type. - * - * @param sourceType the source type - * @param targetType the target type - * - * @return {@code true} if the target type has a constructor accepting the given source type, {@code false} - * otherwise. - */ - private boolean mapTypeHasCompatibleConstructor(Type sourceType, Type targetType) { - // note (issue #127): actually this should check for the presence of a matching constructor, with help of - // Types#asMemberOf(); but this method seems to not work correctly in the Eclipse implementation, so instead - // we just check whether the target type is parameterized in a way that it implicitly should have a - // constructor which accepts the source type - - TypeMirror sourceKeyType; - TypeMirror targetKeyType; - TypeMirror sourceValueType; - TypeMirror targetValueType; - - if ( sourceType.getTypeParameters().isEmpty() ) { - sourceKeyType = typeFactory.getType( Object.class ).getTypeMirror(); - sourceValueType = typeFactory.getType( Object.class ).getTypeMirror(); - } - else { - sourceKeyType = sourceType.getTypeParameters().get( 0 ).getTypeMirror(); - sourceValueType = sourceType.getTypeParameters().get( 1 ).getTypeMirror(); - } - - if ( targetType.getTypeParameters().isEmpty() ) { - targetKeyType = typeFactory.getType( Object.class ).getTypeMirror(); - targetValueType = typeFactory.getType( Object.class ).getTypeMirror(); - } - else { - targetKeyType = targetType.getTypeParameters().get( 0 ).getTypeMirror(); - targetValueType = targetType.getTypeParameters().get( 1 ).getTypeMirror(); - } - - return typeUtils.isAssignable( sourceKeyType, targetKeyType ) - && typeUtils.isAssignable( sourceValueType, targetValueType ); - } - } -} diff --git a/All/Genesis-NP/Genesis#205/old/MappingResolverImpl.java b/All/Genesis-NP/Genesis#205/old/MappingResolverImpl.java deleted file mode 100755 index 41db416..0000000 --- a/All/Genesis-NP/Genesis#205/old/MappingResolverImpl.java +++ /dev/null @@ -1,603 +0,0 @@ -/** - * Copyright 2012-2015 Gunnar Morling (http://www.gunnarmorling.de/) - * and/or other contributors as indicated by the @authors tag. See the - * copyright.txt file in the distribution for a full listing of all - * contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.mapstruct.ap.internal.processor.creation; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; - -import org.mapstruct.ap.internal.conversion.ConversionProvider; -import org.mapstruct.ap.internal.conversion.Conversions; -import org.mapstruct.ap.internal.model.AssignmentFactory; -import org.mapstruct.ap.internal.model.MapperReference; -import org.mapstruct.ap.internal.model.MethodReference; -import org.mapstruct.ap.internal.model.VirtualMappingMethod; -import org.mapstruct.ap.internal.model.MappingBuilderContext.MappingResolver; -import org.mapstruct.ap.internal.model.assignment.Assignment; -import org.mapstruct.ap.internal.model.common.ConversionContext; -import org.mapstruct.ap.internal.model.common.DefaultConversionContext; -import org.mapstruct.ap.internal.model.common.Type; -import org.mapstruct.ap.internal.model.common.TypeFactory; -import org.mapstruct.ap.internal.model.source.Method; -import org.mapstruct.ap.internal.model.source.SourceMethod; -import org.mapstruct.ap.internal.model.source.builtin.BuiltInMappingMethods; -import org.mapstruct.ap.internal.model.source.builtin.BuiltInMethod; -import org.mapstruct.ap.internal.model.source.selector.MethodSelectors; -import org.mapstruct.ap.internal.model.source.selector.SelectionCriteria; -import org.mapstruct.ap.internal.util.FormattingMessager; -import org.mapstruct.ap.internal.util.Message; -import org.mapstruct.ap.internal.util.SpecificCompilerWorkarounds; -import org.mapstruct.ap.internal.util.Strings; - -/** - * The one and only implementation of {@link MappingResolver}. The class has been split into an interface an - * implementation for the sake of avoiding package dependencies. Specifically, this implementation refers to classes - * which should not be exposed to the {@code model} package. - * - * @author Sjaak Derksen - */ -public class MappingResolverImpl implements MappingResolver { - - private final FormattingMessager messager; - private final Types typeUtils; - private final TypeFactory typeFactory; - - private final List sourceModel; - private final List mapperReferences; - - private final Conversions conversions; - private final BuiltInMappingMethods builtInMethods; - private final MethodSelectors methodSelectors; - - /** - * Private methods which are not present in the original mapper interface and are added to map certain property - * types. - */ - private final Set usedVirtualMappings = new HashSet(); - - public MappingResolverImpl(FormattingMessager messager, Elements elementUtils, Types typeUtils, - TypeFactory typeFactory, List sourceModel, - List mapperReferences) { - this.messager = messager; - this.typeUtils = typeUtils; - this.typeFactory = typeFactory; - - this.sourceModel = sourceModel; - this.mapperReferences = mapperReferences; - - this.conversions = new Conversions( elementUtils, typeFactory ); - this.builtInMethods = new BuiltInMappingMethods( typeFactory ); - this.methodSelectors = new MethodSelectors( - typeUtils, - elementUtils, - typeFactory - ); - } - - @Override - public Assignment getTargetAssignment(Method mappingMethod, String mappedElement, Type sourceType, - Type targetType, String targetPropertyName, String dateFormat, List qualifiers, - TypeMirror resultType, String sourceReference, boolean preferUpdateMapping) { - - SelectionCriteria criteria = - new SelectionCriteria(qualifiers, targetPropertyName, resultType, preferUpdateMapping ); - - ResolvingAttempt attempt = new ResolvingAttempt( - sourceModel, - mappingMethod, - mappedElement, - dateFormat, - sourceReference, - criteria - ); - - return attempt.getTargetAssignment( sourceType, targetType ); - } - - @Override - public Set getUsedVirtualMappings() { - return usedVirtualMappings; - } - - @Override - public MethodReference getFactoryMethod( Method mappingMethod, Type targetType, List qualifiers, - TypeMirror resultType ) { - - SelectionCriteria criteria = new SelectionCriteria( qualifiers, null, resultType, false ); - - ResolvingAttempt attempt = new ResolvingAttempt( - sourceModel, - mappingMethod, - null, - null, - null, - criteria - ); - - SourceMethod matchingSourceMethod = attempt.getBestMatch( sourceModel, null, targetType ); - if ( matchingSourceMethod != null ) { - MapperReference ref = attempt.findMapperReference( matchingSourceMethod ); - return new MethodReference( matchingSourceMethod, ref, null ); - } - return null; - - } - - private class ResolvingAttempt { - - private final Method mappingMethod; - private final String mappedElement; - private final List methods; - private final String dateFormat; - private final SelectionCriteria selectionCriteria; - private final String sourceReference; - private final boolean savedPreferUpdateMapping; - - // resolving via 2 steps creates the possibillity of wrong matches, first builtin method matches, - // second doesn't. In that case, the first builtin method should not lead to a virtual method - // so this set must be cleared. - private final Set virtualMethodCandidates; - - private ResolvingAttempt(List sourceModel, Method mappingMethod, String mappedElement, - String dateFormat, String sourceReference, SelectionCriteria criteria) { - - this.mappingMethod = mappingMethod; - this.mappedElement = mappedElement; - this.methods = filterPossibleCandidateMethods( sourceModel ); - this.dateFormat = dateFormat; - this.sourceReference = sourceReference; - this.virtualMethodCandidates = new HashSet(); - this.selectionCriteria = criteria; - this.savedPreferUpdateMapping = criteria.isPreferUpdateMapping(); - } - - private List filterPossibleCandidateMethods(List candidateMethods) { - List result = new ArrayList( candidateMethods.size() ); - for ( T candidate : candidateMethods ) { - if ( isCandidateForMapping( candidate ) ) { - result.add( candidate ); - } - } - - return result; - } - - private Assignment getTargetAssignment(Type sourceType, Type targetType) { - - // first simple mapping method - Assignment referencedMethod = resolveViaMethod( sourceType, targetType, false ); - if ( referencedMethod != null ) { - referencedMethod.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - return referencedMethod; - } - - // then direct assignable - if ( sourceType.isAssignableTo( targetType ) || isPropertyMappable( sourceType, targetType ) ) { - Assignment simpleAssignment = AssignmentFactory.createDirect( sourceReference ); - return simpleAssignment; - } - - // then type conversion - Assignment conversion = resolveViaConversion( sourceType, targetType ); - if ( conversion != null ) { - conversion.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - return conversion; - } - - // check for a built-in method - Assignment builtInMethod = resolveViaBuiltInMethod( sourceType, targetType ); - if ( builtInMethod != null ) { - builtInMethod.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - usedVirtualMappings.addAll( virtualMethodCandidates ); - return builtInMethod; - } - - // 2 step method, first: method(method(source)) - referencedMethod = resolveViaMethodAndMethod( sourceType, targetType ); - if ( referencedMethod != null ) { - usedVirtualMappings.addAll( virtualMethodCandidates ); - return referencedMethod; - } - - // 2 step method, then: method(conversion(source)) - referencedMethod = resolveViaConversionAndMethod( sourceType, targetType ); - if ( referencedMethod != null ) { - usedVirtualMappings.addAll( virtualMethodCandidates ); - return referencedMethod; - } - - // stop here when looking for update methods. - selectionCriteria.setPreferUpdateMapping( false ); - - // 2 step method, finally: conversion(method(source)) - conversion = resolveViaMethodAndConversion( sourceType, targetType ); - if ( conversion != null ) { - usedVirtualMappings.addAll( virtualMethodCandidates ); - return conversion; - } - - // if nothing works, alas, the result is null - return null; - } - - private Assignment resolveViaConversion(Type sourceType, Type targetType) { - ConversionProvider conversionProvider = conversions.getConversion( sourceType, targetType ); - - if ( conversionProvider == null ) { - return null; - } - - ConversionContext ctx = - new DefaultConversionContext( typeFactory, messager, sourceType, targetType, dateFormat ); - return conversionProvider.to( ctx ); - } - - /** - * Returns a reference to a method mapping the given source type to the given target type, if such a method - * exists. - */ - private Assignment resolveViaMethod(Type sourceType, Type targetType, boolean considerBuiltInMethods) { - - // first try to find a matching source method - SourceMethod matchingSourceMethod = getBestMatch( methods, sourceType, targetType ); - - if ( matchingSourceMethod != null ) { - return getMappingMethodReference( matchingSourceMethod, targetType ); - } - - if ( considerBuiltInMethods ) { - return resolveViaBuiltInMethod( sourceType, targetType ); - } - - return null; - } - - private Assignment resolveViaBuiltInMethod(Type sourceType, Type targetType) { - BuiltInMethod matchingBuiltInMethod = - getBestMatch( builtInMethods.getBuiltInMethods(), sourceType, targetType ); - - if ( matchingBuiltInMethod != null ) { - virtualMethodCandidates.add( new VirtualMappingMethod( matchingBuiltInMethod ) ); - ConversionContext ctx = new DefaultConversionContext( typeFactory, messager, - sourceType, - targetType, dateFormat ); - Assignment methodReference = AssignmentFactory.createMethodReference( matchingBuiltInMethod, ctx ); - methodReference.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - return methodReference; - } - - return null; - } - - /** - * Suppose mapping required from A to C and: - *
    - *
  • no direct referenced mapping method either built-in or referenced is available from A to C
  • - *
  • no conversion is available
  • - *
  • there is a method from A to B, methodX
  • - *
  • there is a method from B to C, methodY
  • - *
- * then this method tries to resolve this combination and make a mapping methodY( methodX ( parameter ) ) - */ - private Assignment resolveViaMethodAndMethod(Type sourceType, Type targetType) { - - List methodYCandidates = new ArrayList( methods ); - methodYCandidates.addAll( builtInMethods.getBuiltInMethods() ); - - Assignment methodRefY = null; - - // Iterate over all source methods. Check if the return type matches with the parameter that we need. - // so assume we need a method from A to C we look for a methodX from A to B (all methods in the - // list form such a candidate). - // For each of the candidates, we need to look if there's a methodY, either - // sourceMethod or builtIn that fits the signature B to C. Only then there is a match. If we have a match - // a nested method call can be called. so C = methodY( methodX (A) ) - for ( Method methodYCandidate : methodYCandidates ) { - methodRefY = - resolveViaMethod( methodYCandidate.getSourceParameters().get( 0 ).getType(), targetType, true ); - - if ( methodRefY != null ) { - selectionCriteria.setPreferUpdateMapping( false ); - Assignment methodRefX = - resolveViaMethod( sourceType, methodYCandidate.getSourceParameters().get( 0 ).getType(), true ); - selectionCriteria.setPreferUpdateMapping( savedPreferUpdateMapping ); - if ( methodRefX != null ) { - methodRefY.setAssignment( methodRefX ); - methodRefX.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - break; - } - else { - // both should match; - virtualMethodCandidates.clear(); - methodRefY = null; - } - } - } - return methodRefY; - } - - /** - * Suppose mapping required from A to C and: - *
    - *
  • there is a conversion from A to B, conversionX
  • - *
  • there is a method from B to C, methodY
  • - *
- * then this method tries to resolve this combination and make a mapping methodY( conversionX ( parameter ) ) - */ - private Assignment resolveViaConversionAndMethod(Type sourceType, Type targetType) { - - List methodYCandidates = new ArrayList( methods ); - methodYCandidates.addAll( builtInMethods.getBuiltInMethods() ); - - Assignment methodRefY = null; - - for ( Method methodYCandidate : methodYCandidates ) { - methodRefY = - resolveViaMethod( methodYCandidate.getSourceParameters().get( 0 ).getType(), targetType, true ); - - if ( methodRefY != null ) { - Assignment conversionXRef = - resolveViaConversion( sourceType, methodYCandidate.getSourceParameters().get( 0 ).getType() ); - if ( conversionXRef != null ) { - methodRefY.setAssignment( conversionXRef ); - conversionXRef.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - break; - } - else { - // both should match - virtualMethodCandidates.clear(); - methodRefY = null; - } - } - } - return methodRefY; - } - - /** - * Suppose mapping required from A to C and: - *
    - *
  • there is a conversion from A to B, conversionX
  • - *
  • there is a method from B to C, methodY
  • - *
- * then this method tries to resolve this combination and make a mapping methodY( conversionX ( parameter ) ) - */ - private Assignment resolveViaMethodAndConversion(Type sourceType, Type targetType) { - - List methodXCandidates = new ArrayList( methods ); - methodXCandidates.addAll( builtInMethods.getBuiltInMethods() ); - - Assignment conversionYRef = null; - - // search the other way around - for ( Method methodXCandidate : methodXCandidates ) { - Assignment methodRefX = resolveViaMethod( - sourceType, - methodXCandidate.getReturnType(), - true - ); - if ( methodRefX != null ) { - conversionYRef = resolveViaConversion( methodXCandidate.getReturnType(), targetType ); - if ( conversionYRef != null ) { - conversionYRef.setAssignment( methodRefX ); - methodRefX.setAssignment( AssignmentFactory.createDirect( sourceReference ) ); - break; - } - else { - // both should match; - virtualMethodCandidates.clear(); - conversionYRef = null; - } - } - } - return conversionYRef; - } - - private boolean isCandidateForMapping(Method methodCandidate) { - return isCreateMethodForMapping( methodCandidate ) || isUpdateMethodForMapping( methodCandidate ); - } - - private boolean isCreateMethodForMapping(Method methodCandidate) { - // a create method may not return void and has no target parameter - return methodCandidate.getSourceParameters().size() == 1 - && !methodCandidate.getReturnType().isVoid() - && methodCandidate.getMappingTargetParameter() == null - && !methodCandidate.isLifecycleCallbackMethod(); - } - - private boolean isUpdateMethodForMapping(Method methodCandidate) { - // an update method may, or may not return void and has a target parameter - return methodCandidate.getSourceParameters().size() == 1 - && methodCandidate.getMappingTargetParameter() != null - && !methodCandidate.isLifecycleCallbackMethod(); - } - - private T getBestMatch(List methods, Type sourceType, Type returnType) { - - List candidates = methodSelectors.getMatchingMethods( - mappingMethod, - methods, - sourceType, - returnType, - selectionCriteria - ); - - // raise an error if more than one mapping method is suitable to map the given source type - // into the target type - if ( candidates.size() > 1 ) { - - if ( mappedElement != null ) { - messager.printMessage( mappingMethod.getExecutable(), - Message.GENERAL_AMBIGIOUS_MAPPING_METHOD, - mappedElement, - returnType, - Strings.join( candidates, ", " ) - ); - } - else { - messager.printMessage( mappingMethod.getExecutable(), - Message.GENERAL_AMBIGIOUS_FACTORY_METHOD, - returnType, - Strings.join( candidates, ", " ) - ); - } - } - - if ( !candidates.isEmpty() ) { - return candidates.get( 0 ); - } - - return null; - } - - private Assignment getMappingMethodReference(SourceMethod method, - Type targetType) { - MapperReference mapperReference = findMapperReference( method ); - - return AssignmentFactory.createMethodReference( - method, - mapperReference, - SourceMethod.containsTargetTypeParameter( method.getParameters() ) ? targetType : null - ); - } - - private MapperReference findMapperReference(SourceMethod method) { - for ( MapperReference ref : mapperReferences ) { - if ( ref.getType().equals( method.getDeclaringMapper() ) ) { - ref.setUsed( !method.isStatic() ); - ref.setTypeRequiresImport( true ); - return ref; - } - } - return null; - } - - /** - * Whether the specified property can be mapped from source to target or not. A mapping if possible if one of - * the following conditions is true: - *
    - *
  • the source type is assignable to the target type
  • - *
  • a mapping method exists
  • - *
  • a built-in conversion exists
  • - *
  • the property is of a collection or map type and the constructor of the target type (either itself or its - * implementation type) accepts the source type.
  • - *
- * - * @return {@code true} if the specified property can be mapped, {@code false} otherwise. - */ - private boolean isPropertyMappable(Type sourceType, Type targetType) { - boolean collectionOrMapTargetTypeHasCompatibleConstructor = false; - - if ( sourceType.isCollectionType() && targetType.isCollectionType() ) { - collectionOrMapTargetTypeHasCompatibleConstructor = collectionTypeHasCompatibleConstructor( - sourceType, - targetType.getImplementationType() != null - ? targetType.getImplementationType() : targetType - ); - } - - if ( sourceType.isMapType() && targetType.isMapType() ) { - collectionOrMapTargetTypeHasCompatibleConstructor = mapTypeHasCompatibleConstructor( - sourceType, - targetType.getImplementationType() != null - ? targetType.getImplementationType() : targetType - ); - } - - if ( ( ( targetType.isCollectionType() || targetType.isMapType() ) - && collectionOrMapTargetTypeHasCompatibleConstructor ) ) { - return true; - } - - return false; - } - - /** - * Whether the given target type has a single-argument constructor which accepts the given source type. - * - * @param sourceType the source type - * @param targetType the target type - * - * @return {@code true} if the target type has a constructor accepting the given source type, {@code false} - * otherwise. - */ - private boolean collectionTypeHasCompatibleConstructor(Type sourceType, Type targetType) { - // note (issue #127): actually this should check for the presence of a matching constructor, with help of - // Types#asMemberOf(); but this method seems to not work correctly in the Eclipse implementation, so instead - // we just check whether the target type is parameterized in a way that it implicitly should have a - // constructor which accepts the source type - - TypeMirror sourceElementType = sourceType.getTypeParameters().isEmpty() - ? typeFactory.getType( Object.class ).getTypeMirror() - : sourceType.getTypeParameters().get( 0 ).getTypeMirror(); - - TypeMirror targetElementType = targetType.getTypeParameters().isEmpty() - ? typeFactory.getType( Object.class ).getTypeMirror() - : targetType.getTypeParameters().get( 0 ).getTypeMirror(); - - return SpecificCompilerWorkarounds.isAssignable( typeUtils, sourceElementType, targetElementType ); - } - - /** - * Whether the given target type has a single-argument constructor which accepts the given source type. - * - * @param sourceType the source type - * @param targetType the target type - * - * @return {@code true} if the target type has a constructor accepting the given source type, {@code false} - * otherwise. - */ - private boolean mapTypeHasCompatibleConstructor(Type sourceType, Type targetType) { - // note (issue #127): actually this should check for the presence of a matching constructor, with help of - // Types#asMemberOf(); but this method seems to not work correctly in the Eclipse implementation, so instead - // we just check whether the target type is parameterized in a way that it implicitly should have a - // constructor which accepts the source type - - TypeMirror sourceKeyType; - TypeMirror targetKeyType; - TypeMirror sourceValueType; - TypeMirror targetValueType; - - if ( sourceType.getTypeParameters().isEmpty() ) { - sourceKeyType = typeFactory.getType( Object.class ).getTypeMirror(); - sourceValueType = typeFactory.getType( Object.class ).getTypeMirror(); - } - else { - sourceKeyType = sourceType.getTypeParameters().get( 0 ).getTypeMirror(); - sourceValueType = sourceType.getTypeParameters().get( 1 ).getTypeMirror(); - } - - if ( targetType.getTypeParameters().isEmpty() ) { - targetKeyType = typeFactory.getType( Object.class ).getTypeMirror(); - targetValueType = typeFactory.getType( Object.class ).getTypeMirror(); - } - else { - targetKeyType = targetType.getTypeParameters().get( 0 ).getTypeMirror(); - targetValueType = targetType.getTypeParameters().get( 1 ).getTypeMirror(); - } - - return typeUtils.isAssignable( sourceKeyType, targetKeyType ) - && typeUtils.isAssignable( sourceValueType, targetValueType ); - } - } -} diff --git a/All/Genesis-NP/Genesis#205/pair.info b/All/Genesis-NP/Genesis#205/pair.info deleted file mode 100755 index ca95157..0000000 --- a/All/Genesis-NP/Genesis#205/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:205 -SATName:Genesis -modifiedFPath:processor/src/main/java/org/mapstruct/ap/internal/processor/creation/MappingResolverImpl.java -comSha:5217e67f8dc905a96fb35cf110affc02a5893c77 -parentComSha:5217e67f8dc905a96fb35cf110affc02a5893c77^1 -githubUrl:https://github.com/mapstruct/mapstruct -repoName:mapstruct#mapstruct \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#209/comMsg.txt b/All/Genesis-NP/Genesis#209/comMsg.txt deleted file mode 100755 index 949069c..0000000 --- a/All/Genesis-NP/Genesis#209/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -#17 Fixing NPE in case of attribute without setter in source type diff --git a/All/Genesis-NP/Genesis#209/diff.diff b/All/Genesis-NP/Genesis#209/diff.diff deleted file mode 100755 index 2085e40..0000000 --- a/All/Genesis-NP/Genesis#209/diff.diff +++ /dev/null @@ -1,23 +0,0 @@ -diff --git a/processor/src/main/java/org/mapstruct/ap/MapperGenerationVisitor.java b/processor/src/main/java/org/mapstruct/ap/MapperGenerationVisitor.java -index b958749..2f38a5e 100644 ---- a/processor/src/main/java/org/mapstruct/ap/MapperGenerationVisitor.java -+++ b/processor/src/main/java/org/mapstruct/ap/MapperGenerationVisitor.java -@@ -465,0 +466,8 @@ private Method getReverseMappingMethod(List rawMethods, -+ ExecutableElement correspondingSetter = Executables.getCorrespondingPropertyAccessor( -+ getterMethod, -+ sourceSetters -+ ); -+ ExecutableElement correspondingGetter = Executables.getCorrespondingPropertyAccessor( -+ setterMethod, -+ targetGetters -+ ); -@@ -470,3 +478 @@ private Method getReverseMappingMethod(List rawMethods, -- Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ) -- .getSimpleName() -- .toString(), -+ correspondingSetter != null ? correspondingSetter.getSimpleName().toString() : null, -@@ -475,3 +481 @@ private Method getReverseMappingMethod(List rawMethods, -- Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ) -- .getSimpleName() -- .toString(), -+ correspondingGetter != null ? correspondingGetter.getSimpleName().toString() : null, diff --git a/All/Genesis-NP/Genesis#209/new/MapperGenerationVisitor.java b/All/Genesis-NP/Genesis#209/new/MapperGenerationVisitor.java deleted file mode 100755 index 2f38a5e..0000000 --- a/All/Genesis-NP/Genesis#209/new/MapperGenerationVisitor.java +++ /dev/null @@ -1,583 +0,0 @@ -/** - * Copyright 2012-2013 Gunnar Morling (http://www.gunnarmorling.de/) - * and/or other contributors as indicated by the @authors tag. See the - * copyright.txt file in the distribution for a full listing of all - * contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.mapstruct.ap; - -import java.beans.Introspector; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -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 javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.AnnotationValue; -import javax.lang.model.element.Element; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; -import javax.lang.model.type.DeclaredType; -import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.ElementKindVisitor6; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import javax.tools.Diagnostic.Kind; -import javax.tools.JavaFileObject; - -import org.mapstruct.ap.conversion.Conversion; -import org.mapstruct.ap.conversion.Conversions; -import org.mapstruct.ap.model.BeanMapping; -import org.mapstruct.ap.model.Mapper; -import org.mapstruct.ap.model.MappingMethod; -import org.mapstruct.ap.model.Options; -import org.mapstruct.ap.model.PropertyMapping; -import org.mapstruct.ap.model.Type; -import org.mapstruct.ap.model.source.MappedProperty; -import org.mapstruct.ap.model.source.Mapping; -import org.mapstruct.ap.model.source.Method; -import org.mapstruct.ap.model.source.Parameter; -import org.mapstruct.ap.util.Executables; -import org.mapstruct.ap.util.Filters; -import org.mapstruct.ap.util.TypeUtil; -import org.mapstruct.ap.writer.ModelWriter; - -import static javax.lang.model.util.ElementFilter.methodsIn; - -public class MapperGenerationVisitor extends ElementKindVisitor6 { - - private static final String IMPLEMENTATION_SUFFIX = "Impl"; - - private final ProcessingEnvironment processingEnvironment; - private final Types typeUtils; - private final Elements elementUtils; - private final TypeUtil typeUtil; - private final Options options; - - private boolean mappingErroneous = false; - - public MapperGenerationVisitor(ProcessingEnvironment processingEnvironment, Options options) { - this.processingEnvironment = processingEnvironment; - this.typeUtils = processingEnvironment.getTypeUtils(); - this.elementUtils = processingEnvironment.getElementUtils(); - this.typeUtil = new TypeUtil( elementUtils, typeUtils ); - this.options = options; - } - - @Override - public Void visitTypeAsInterface(TypeElement element, Void p) { - Mapper model = retrieveModel( element ); - - if ( !mappingErroneous ) { - String sourceFileName = element.getQualifiedName() + IMPLEMENTATION_SUFFIX; - writeModelToSourceFile( sourceFileName, model ); - } - - return null; - } - - private void writeModelToSourceFile(String fileName, Mapper model) { - JavaFileObject sourceFile; - try { - sourceFile = processingEnvironment.getFiler().createSourceFile( fileName ); - } - catch ( IOException e ) { - throw new RuntimeException( e ); - } - - ModelWriter modelWriter = new ModelWriter( "mapper-implementation.ftl" ); - modelWriter.writeModel( sourceFile, model ); - } - - private Mapper retrieveModel(TypeElement element) { - List methods = retrieveMethods( null, element ); - List mappings = getMappings( methods ); - List usedMapperTypes = getUsedMapperTypes( element ); - - Mapper mapper = new Mapper( - elementUtils.getPackageOf( element ).getQualifiedName().toString(), - element.getSimpleName().toString(), - element.getSimpleName() + IMPLEMENTATION_SUFFIX, - mappings, - usedMapperTypes, - options - ); - - return mapper; - } - - private List getMappings(List methods) { - Conversions conversions = new Conversions( elementUtils, typeUtils, typeUtil ); - - List mappings = new ArrayList(); - Set processedMethods = new HashSet(); - - for ( Method method : methods ) { - if ( processedMethods.contains( method ) ) { - continue; - } - - MappingMethod mappingMethod = new MappingMethod( - method.getDeclaringMapper(), - method.getName(), - method.getParameterName(), - getElementMappingMethod( methods, method ) - ); - - MappingMethod reverseMappingMethod = null; - Method rawReverseMappingMethod = getReverseMappingMethod( methods, method ); - if ( rawReverseMappingMethod != null ) { - processedMethods.add( rawReverseMappingMethod ); - - reverseMappingMethod = new MappingMethod( - rawReverseMappingMethod.getDeclaringMapper(), - rawReverseMappingMethod.getName(), - rawReverseMappingMethod.getParameterName(), - getElementMappingMethod( methods, rawReverseMappingMethod ) - ); - } - - List propertyMappings = new ArrayList(); - - for ( MappedProperty property : method.getMappedProperties() ) { - Method propertyMappingMethod = getPropertyMappingMethod( methods, property ); - Method reversePropertyMappingMethod = getReversePropertyMappingMethod( methods, property ); - Conversion conversion = conversions.getConversion( property.getSourceType(), property.getTargetType() ); - - reportErrorIfPropertyCanNotBeMapped( - method, - rawReverseMappingMethod, - property, - propertyMappingMethod, - reversePropertyMappingMethod, - conversion - ); - - propertyMappings.add( - new PropertyMapping( - property.getSourceReadAccessorName(), - property.getSourceWriteAccessorName(), - property.getSourceType(), - property.getTargetReadAccessorName(), - property.getTargetWriteAccessorName(), - property.getTargetType(), - propertyMappingMethod != null ? new MappingMethod( - propertyMappingMethod.getDeclaringMapper(), - propertyMappingMethod.getName(), - propertyMappingMethod.getParameterName() - ) : null, - reversePropertyMappingMethod != null ? new MappingMethod( - reversePropertyMappingMethod.getDeclaringMapper(), - reversePropertyMappingMethod.getName(), - reversePropertyMappingMethod.getParameterName() - ) : null, - conversion != null ? conversion.to( - mappingMethod.getParameterName() + "." + property.getSourceReadAccessorName() + "()", - property.getTargetType() - ) : null, - conversion != null && reverseMappingMethod != null ? conversion.from( - reverseMappingMethod.getParameterName() + "." + property.getTargetReadAccessorName() + "()", - property.getSourceType() - ) : null - ) - ); - } - - boolean isIterableMapping = method.getSourceType().isIterableType() && method.getTargetType() - .isIterableType(); - - String toConversionString = null; - String fromConversionString = null; - - if ( isIterableMapping ) { - toConversionString = getIterableConversionString( - conversions, - method.getSourceType().getElementType(), - method.getTargetType().getElementType(), - true - ); - fromConversionString = getIterableConversionString( - conversions, - method.getTargetType().getElementType(), - method.getSourceType().getElementType(), - false - ); - } - - BeanMapping mapping = new BeanMapping( - method.getSourceType(), - method.getTargetType(), - propertyMappings, - mappingMethod, - reverseMappingMethod, - toConversionString, - fromConversionString - ); - - mappings.add( mapping ); - } - return mappings; - } - - private void reportErrorIfPropertyCanNotBeMapped(Method method, Method reverseMethod, MappedProperty property, - Method propertyMappingMethod, Method reversePropertyMappingMethod, - Conversion conversion) { - if ( property.getSourceType().equals( property.getTargetType() ) ) { - return; - } - - //no mapping method nor conversion nor collection with default implementation - if ( !( - propertyMappingMethod != null || - conversion != null || - ( property.getTargetType().isCollectionType() && property.getTargetType() - .getCollectionImplementationType() != null ) ) ) { - - reportError( - String.format( - "Can't map property \"%s %s\" to \"%s %s\".", - property.getSourceType(), - property.getSourceName(), - property.getTargetType(), - property.getTargetName() - ), - method.getExecutable() - ); - } - - if ( reverseMethod == null ) { - return; - } - - if ( !( - reversePropertyMappingMethod != null || - conversion != null || - ( property.getSourceType().isCollectionType() && property.getSourceType() - .getCollectionImplementationType() != null ) ) ) { - - reportError( - String.format( - "Can't map property \"%s %s\" to \"%s %s\".", - property.getTargetType(), - property.getTargetName(), - property.getSourceType(), - property.getSourceName() - ), - reverseMethod.getExecutable() - ); - } - } - - private String getIterableConversionString(Conversions conversions, Type sourceElementType, Type targetElementType, - boolean isToConversion) { - Conversion conversion = conversions.getConversion( sourceElementType, targetElementType ); - - if ( conversion == null ) { - return null; - } - - return conversion.to( - Introspector.decapitalize( sourceElementType.getName() ), - targetElementType - ); - } - - private List getUsedMapperTypes(TypeElement element) { - List usedMapperTypes = new LinkedList(); - MapperPrism mapperPrism = MapperPrism.getInstanceOn( element ); - for ( TypeMirror usedMapper : mapperPrism.uses() ) { - usedMapperTypes.add( typeUtil.retrieveType( usedMapper ) ); - } - return usedMapperTypes; - } - - private MappingMethod getElementMappingMethod(Iterable methods, Method method) { - Method elementMappingMethod = null; - for ( Method oneMethod : methods ) { - if ( oneMethod.getSourceType().equals( method.getSourceType().getElementType() ) ) { - elementMappingMethod = oneMethod; - break; - } - } - return elementMappingMethod == null ? null : new MappingMethod( - elementMappingMethod.getDeclaringMapper(), - elementMappingMethod.getName(), - elementMappingMethod.getParameterName() - ); - } - - private Method getPropertyMappingMethod(Iterable rawMethods, MappedProperty property) { - for ( Method oneMethod : rawMethods ) { - if ( oneMethod.getSourceType().equals( property.getSourceType() ) && oneMethod.getTargetType() - .equals( property.getTargetType() ) ) { - return oneMethod; - } - } - return null; - } - - private Method getReversePropertyMappingMethod(Iterable methods, MappedProperty property) { - for ( Method method : methods ) { - if ( method.getSourceType().equals( property.getTargetType() ) && method.getTargetType() - .equals( property.getSourceType() ) ) { - return method; - } - } - return null; - } - - private Method getReverseMappingMethod(List rawMethods, - Method method) { - for ( Method oneMethod : rawMethods ) { - if ( oneMethod.reverses( method ) ) { - return oneMethod; - } - } - return null; - } - - private List retrieveMethods(Type declaringMapper, Element element) { - List methods = new ArrayList(); - - for ( ExecutableElement method : methodsIn( element.getEnclosedElements() ) ) { - Parameter parameter = retrieveParameter( method ); - Type returnType = retrieveReturnType( method ); - boolean mappingErroneous = false; - - if ( declaringMapper == null ) { - if ( parameter.getType().isIterableType() && !returnType.isIterableType() ) { - reportError( "Can't generate mapping method from iterable type to non-iterable type.", method ); - mappingErroneous = true; - } - if ( !parameter.getType().isIterableType() && returnType.isIterableType() ) { - reportError( "Can't generate mapping method from non-iterable type to iterable type.", method ); - mappingErroneous = true; - } - if ( parameter.getType().isPrimitive() ) { - reportError( "Can't generate mapping method with primitive parameter type.", method ); - mappingErroneous = true; - } - if ( returnType.isPrimitive() ) { - reportError( "Can't generate mapping method with primitive return type.", method ); - mappingErroneous = true; - } - - if ( mappingErroneous ) { - continue; - } - } - - //retrieve property mappings if an implementation for the method needs to be generated - List properties = declaringMapper == null ? retrieveMappedProperties( method ) : Collections - .emptyList(); - - methods.add( - new Method( - declaringMapper, - method, - parameter.getName(), - parameter.getType(), - returnType, - properties - ) - ); - } - - MapperPrism mapperPrism = MapperPrism.getInstanceOn( element ); - - if ( mapperPrism != null ) { - for ( TypeMirror usedMapper : mapperPrism.uses() ) { - methods.addAll( - retrieveMethods( - typeUtil.retrieveType( usedMapper ), - ( (DeclaredType) usedMapper ).asElement() - ) - ); - } - } - - return methods; - } - - private List retrieveMappedProperties(ExecutableElement method) { - Map mappings = new HashMap(); - - MappingPrism mappingAnnotation = MappingPrism.getInstanceOn( method ); - MappingsPrism mappingsAnnotation = MappingsPrism.getInstanceOn( method ); - - if ( mappingAnnotation != null ) { - mappings.put( mappingAnnotation.source(), getMapping( mappingAnnotation ) ); - } - - if ( mappingsAnnotation != null ) { - mappings.putAll( getMappings( mappingsAnnotation ) ); - } - - return getMappedProperties( method, mappings ); - } - - private List getMappedProperties(ExecutableElement method, Map mappings) { - TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); - TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); - - List properties = new ArrayList(); - - List sourceGetters = Filters.getterMethodsIn( - elementUtils.getAllMembers( parameterElement ) - ); - List targetSetters = Filters.setterMethodsIn( - elementUtils.getAllMembers( returnTypeElement ) - ); - List sourceSetters = Filters.setterMethodsIn( - elementUtils.getAllMembers( parameterElement ) - ); - List targetGetters = Filters.getterMethodsIn( - elementUtils.getAllMembers( returnTypeElement ) - ); - - reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); - - for ( ExecutableElement getterMethod : sourceGetters ) { - String sourcePropertyName = Executables.getPropertyName( getterMethod ); - Mapping mapping = mappings.get( sourcePropertyName ); - - for ( ExecutableElement setterMethod : targetSetters ) { - String targetPropertyName = Executables.getPropertyName( setterMethod ); - - if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { - ExecutableElement correspondingSetter = Executables.getCorrespondingPropertyAccessor( - getterMethod, - sourceSetters - ); - ExecutableElement correspondingGetter = Executables.getCorrespondingPropertyAccessor( - setterMethod, - targetGetters - ); - properties.add( - new MappedProperty( - sourcePropertyName, - getterMethod.getSimpleName().toString(), - correspondingSetter != null ? correspondingSetter.getSimpleName().toString() : null, - retrieveReturnType( getterMethod ), - mapping != null ? mapping.getTargetName() : targetPropertyName, - correspondingGetter != null ? correspondingGetter.getSimpleName().toString() : null, - setterMethod.getSimpleName().toString(), - retrieveParameter( setterMethod ).getType() - ) - ); - } - } - } - - return properties; - } - - private void reportErrorIfMappedPropertiesDontExist(ExecutableElement method, Map mappings, - List sourceGetters, - List targetSetters) { - - Set sourcePropertyNames = getPropertyNames( sourceGetters ); - Set targetPropertyNames = getPropertyNames( targetSetters ); - - for ( Mapping mappedProperty : mappings.values() ) { - if ( !sourcePropertyNames.contains( mappedProperty.getSourceName() ) ) { - reportError( - String.format( - "Unknown property \"%s\" in parameter type %s.", - mappedProperty.getSourceName(), - retrieveParameter( method ).getType() - ), method, mappedProperty.getMirror(), mappedProperty.getSourceAnnotationValue() - ); - } - if ( !targetPropertyNames.contains( mappedProperty.getTargetName() ) ) { - reportError( - String.format( - "Unknown property \"%s\" in return type %s.", - mappedProperty.getTargetName(), - retrieveReturnType( method ) - ), method, mappedProperty.getMirror(), mappedProperty.getTargetAnnotationValue() - ); - } - } - } - - private Set getPropertyNames(List propertyAccessors) { - Set propertyNames = new HashSet(); - - for ( ExecutableElement executableElement : propertyAccessors ) { - propertyNames.add( Executables.getPropertyName( executableElement ) ); - } - - return propertyNames; - } - - private Map getMappings(MappingsPrism mappingsAnnotation) { - Map mappings = new HashMap(); - - for ( MappingPrism mapping : mappingsAnnotation.value() ) { - mappings.put( mapping.source(), getMapping( mapping ) ); - } - - return mappings; - } - - private Mapping getMapping(MappingPrism mapping) { - return new Mapping( - mapping.source(), - mapping.target(), - mapping.mirror, - mapping.values.source(), - mapping.values.target() - ); - } - - private Parameter retrieveParameter(ExecutableElement method) { - List parameters = method.getParameters(); - - if ( parameters.size() != 1 ) { - //TODO: Log error - return null; - } - - VariableElement parameter = parameters.get( 0 ); - - return new Parameter( - parameter.getSimpleName().toString(), - typeUtil.retrieveType( parameter.asType() ) - ); - } - - private Type retrieveReturnType(ExecutableElement method) { - return typeUtil.retrieveType( method.getReturnType() ); - } - - private void reportError(String message, Element element) { - processingEnvironment.getMessager().printMessage( Kind.ERROR, message, element ); - mappingErroneous = true; - } - - private void reportError(String message, Element element, AnnotationMirror annotationMirror, - AnnotationValue annotationValue) { - processingEnvironment.getMessager() - .printMessage( Kind.ERROR, message, element, annotationMirror, annotationValue ); - mappingErroneous = true; - } -} diff --git a/All/Genesis-NP/Genesis#209/old/MapperGenerationVisitor.java b/All/Genesis-NP/Genesis#209/old/MapperGenerationVisitor.java deleted file mode 100755 index b958749..0000000 --- a/All/Genesis-NP/Genesis#209/old/MapperGenerationVisitor.java +++ /dev/null @@ -1,579 +0,0 @@ -/** - * Copyright 2012-2013 Gunnar Morling (http://www.gunnarmorling.de/) - * and/or other contributors as indicated by the @authors tag. See the - * copyright.txt file in the distribution for a full listing of all - * contributors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.mapstruct.ap; - -import java.beans.Introspector; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collections; -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 javax.annotation.processing.ProcessingEnvironment; -import javax.lang.model.element.AnnotationMirror; -import javax.lang.model.element.AnnotationValue; -import javax.lang.model.element.Element; -import javax.lang.model.element.ExecutableElement; -import javax.lang.model.element.TypeElement; -import javax.lang.model.element.VariableElement; -import javax.lang.model.type.DeclaredType; -import javax.lang.model.type.TypeMirror; -import javax.lang.model.util.ElementKindVisitor6; -import javax.lang.model.util.Elements; -import javax.lang.model.util.Types; -import javax.tools.Diagnostic.Kind; -import javax.tools.JavaFileObject; - -import org.mapstruct.ap.conversion.Conversion; -import org.mapstruct.ap.conversion.Conversions; -import org.mapstruct.ap.model.BeanMapping; -import org.mapstruct.ap.model.Mapper; -import org.mapstruct.ap.model.MappingMethod; -import org.mapstruct.ap.model.Options; -import org.mapstruct.ap.model.PropertyMapping; -import org.mapstruct.ap.model.Type; -import org.mapstruct.ap.model.source.MappedProperty; -import org.mapstruct.ap.model.source.Mapping; -import org.mapstruct.ap.model.source.Method; -import org.mapstruct.ap.model.source.Parameter; -import org.mapstruct.ap.util.Executables; -import org.mapstruct.ap.util.Filters; -import org.mapstruct.ap.util.TypeUtil; -import org.mapstruct.ap.writer.ModelWriter; - -import static javax.lang.model.util.ElementFilter.methodsIn; - -public class MapperGenerationVisitor extends ElementKindVisitor6 { - - private static final String IMPLEMENTATION_SUFFIX = "Impl"; - - private final ProcessingEnvironment processingEnvironment; - private final Types typeUtils; - private final Elements elementUtils; - private final TypeUtil typeUtil; - private final Options options; - - private boolean mappingErroneous = false; - - public MapperGenerationVisitor(ProcessingEnvironment processingEnvironment, Options options) { - this.processingEnvironment = processingEnvironment; - this.typeUtils = processingEnvironment.getTypeUtils(); - this.elementUtils = processingEnvironment.getElementUtils(); - this.typeUtil = new TypeUtil( elementUtils, typeUtils ); - this.options = options; - } - - @Override - public Void visitTypeAsInterface(TypeElement element, Void p) { - Mapper model = retrieveModel( element ); - - if ( !mappingErroneous ) { - String sourceFileName = element.getQualifiedName() + IMPLEMENTATION_SUFFIX; - writeModelToSourceFile( sourceFileName, model ); - } - - return null; - } - - private void writeModelToSourceFile(String fileName, Mapper model) { - JavaFileObject sourceFile; - try { - sourceFile = processingEnvironment.getFiler().createSourceFile( fileName ); - } - catch ( IOException e ) { - throw new RuntimeException( e ); - } - - ModelWriter modelWriter = new ModelWriter( "mapper-implementation.ftl" ); - modelWriter.writeModel( sourceFile, model ); - } - - private Mapper retrieveModel(TypeElement element) { - List methods = retrieveMethods( null, element ); - List mappings = getMappings( methods ); - List usedMapperTypes = getUsedMapperTypes( element ); - - Mapper mapper = new Mapper( - elementUtils.getPackageOf( element ).getQualifiedName().toString(), - element.getSimpleName().toString(), - element.getSimpleName() + IMPLEMENTATION_SUFFIX, - mappings, - usedMapperTypes, - options - ); - - return mapper; - } - - private List getMappings(List methods) { - Conversions conversions = new Conversions( elementUtils, typeUtils, typeUtil ); - - List mappings = new ArrayList(); - Set processedMethods = new HashSet(); - - for ( Method method : methods ) { - if ( processedMethods.contains( method ) ) { - continue; - } - - MappingMethod mappingMethod = new MappingMethod( - method.getDeclaringMapper(), - method.getName(), - method.getParameterName(), - getElementMappingMethod( methods, method ) - ); - - MappingMethod reverseMappingMethod = null; - Method rawReverseMappingMethod = getReverseMappingMethod( methods, method ); - if ( rawReverseMappingMethod != null ) { - processedMethods.add( rawReverseMappingMethod ); - - reverseMappingMethod = new MappingMethod( - rawReverseMappingMethod.getDeclaringMapper(), - rawReverseMappingMethod.getName(), - rawReverseMappingMethod.getParameterName(), - getElementMappingMethod( methods, rawReverseMappingMethod ) - ); - } - - List propertyMappings = new ArrayList(); - - for ( MappedProperty property : method.getMappedProperties() ) { - Method propertyMappingMethod = getPropertyMappingMethod( methods, property ); - Method reversePropertyMappingMethod = getReversePropertyMappingMethod( methods, property ); - Conversion conversion = conversions.getConversion( property.getSourceType(), property.getTargetType() ); - - reportErrorIfPropertyCanNotBeMapped( - method, - rawReverseMappingMethod, - property, - propertyMappingMethod, - reversePropertyMappingMethod, - conversion - ); - - propertyMappings.add( - new PropertyMapping( - property.getSourceReadAccessorName(), - property.getSourceWriteAccessorName(), - property.getSourceType(), - property.getTargetReadAccessorName(), - property.getTargetWriteAccessorName(), - property.getTargetType(), - propertyMappingMethod != null ? new MappingMethod( - propertyMappingMethod.getDeclaringMapper(), - propertyMappingMethod.getName(), - propertyMappingMethod.getParameterName() - ) : null, - reversePropertyMappingMethod != null ? new MappingMethod( - reversePropertyMappingMethod.getDeclaringMapper(), - reversePropertyMappingMethod.getName(), - reversePropertyMappingMethod.getParameterName() - ) : null, - conversion != null ? conversion.to( - mappingMethod.getParameterName() + "." + property.getSourceReadAccessorName() + "()", - property.getTargetType() - ) : null, - conversion != null && reverseMappingMethod != null ? conversion.from( - reverseMappingMethod.getParameterName() + "." + property.getTargetReadAccessorName() + "()", - property.getSourceType() - ) : null - ) - ); - } - - boolean isIterableMapping = method.getSourceType().isIterableType() && method.getTargetType() - .isIterableType(); - - String toConversionString = null; - String fromConversionString = null; - - if ( isIterableMapping ) { - toConversionString = getIterableConversionString( - conversions, - method.getSourceType().getElementType(), - method.getTargetType().getElementType(), - true - ); - fromConversionString = getIterableConversionString( - conversions, - method.getTargetType().getElementType(), - method.getSourceType().getElementType(), - false - ); - } - - BeanMapping mapping = new BeanMapping( - method.getSourceType(), - method.getTargetType(), - propertyMappings, - mappingMethod, - reverseMappingMethod, - toConversionString, - fromConversionString - ); - - mappings.add( mapping ); - } - return mappings; - } - - private void reportErrorIfPropertyCanNotBeMapped(Method method, Method reverseMethod, MappedProperty property, - Method propertyMappingMethod, Method reversePropertyMappingMethod, - Conversion conversion) { - if ( property.getSourceType().equals( property.getTargetType() ) ) { - return; - } - - //no mapping method nor conversion nor collection with default implementation - if ( !( - propertyMappingMethod != null || - conversion != null || - ( property.getTargetType().isCollectionType() && property.getTargetType() - .getCollectionImplementationType() != null ) ) ) { - - reportError( - String.format( - "Can't map property \"%s %s\" to \"%s %s\".", - property.getSourceType(), - property.getSourceName(), - property.getTargetType(), - property.getTargetName() - ), - method.getExecutable() - ); - } - - if ( reverseMethod == null ) { - return; - } - - if ( !( - reversePropertyMappingMethod != null || - conversion != null || - ( property.getSourceType().isCollectionType() && property.getSourceType() - .getCollectionImplementationType() != null ) ) ) { - - reportError( - String.format( - "Can't map property \"%s %s\" to \"%s %s\".", - property.getTargetType(), - property.getTargetName(), - property.getSourceType(), - property.getSourceName() - ), - reverseMethod.getExecutable() - ); - } - } - - private String getIterableConversionString(Conversions conversions, Type sourceElementType, Type targetElementType, - boolean isToConversion) { - Conversion conversion = conversions.getConversion( sourceElementType, targetElementType ); - - if ( conversion == null ) { - return null; - } - - return conversion.to( - Introspector.decapitalize( sourceElementType.getName() ), - targetElementType - ); - } - - private List getUsedMapperTypes(TypeElement element) { - List usedMapperTypes = new LinkedList(); - MapperPrism mapperPrism = MapperPrism.getInstanceOn( element ); - for ( TypeMirror usedMapper : mapperPrism.uses() ) { - usedMapperTypes.add( typeUtil.retrieveType( usedMapper ) ); - } - return usedMapperTypes; - } - - private MappingMethod getElementMappingMethod(Iterable methods, Method method) { - Method elementMappingMethod = null; - for ( Method oneMethod : methods ) { - if ( oneMethod.getSourceType().equals( method.getSourceType().getElementType() ) ) { - elementMappingMethod = oneMethod; - break; - } - } - return elementMappingMethod == null ? null : new MappingMethod( - elementMappingMethod.getDeclaringMapper(), - elementMappingMethod.getName(), - elementMappingMethod.getParameterName() - ); - } - - private Method getPropertyMappingMethod(Iterable rawMethods, MappedProperty property) { - for ( Method oneMethod : rawMethods ) { - if ( oneMethod.getSourceType().equals( property.getSourceType() ) && oneMethod.getTargetType() - .equals( property.getTargetType() ) ) { - return oneMethod; - } - } - return null; - } - - private Method getReversePropertyMappingMethod(Iterable methods, MappedProperty property) { - for ( Method method : methods ) { - if ( method.getSourceType().equals( property.getTargetType() ) && method.getTargetType() - .equals( property.getSourceType() ) ) { - return method; - } - } - return null; - } - - private Method getReverseMappingMethod(List rawMethods, - Method method) { - for ( Method oneMethod : rawMethods ) { - if ( oneMethod.reverses( method ) ) { - return oneMethod; - } - } - return null; - } - - private List retrieveMethods(Type declaringMapper, Element element) { - List methods = new ArrayList(); - - for ( ExecutableElement method : methodsIn( element.getEnclosedElements() ) ) { - Parameter parameter = retrieveParameter( method ); - Type returnType = retrieveReturnType( method ); - boolean mappingErroneous = false; - - if ( declaringMapper == null ) { - if ( parameter.getType().isIterableType() && !returnType.isIterableType() ) { - reportError( "Can't generate mapping method from iterable type to non-iterable type.", method ); - mappingErroneous = true; - } - if ( !parameter.getType().isIterableType() && returnType.isIterableType() ) { - reportError( "Can't generate mapping method from non-iterable type to iterable type.", method ); - mappingErroneous = true; - } - if ( parameter.getType().isPrimitive() ) { - reportError( "Can't generate mapping method with primitive parameter type.", method ); - mappingErroneous = true; - } - if ( returnType.isPrimitive() ) { - reportError( "Can't generate mapping method with primitive return type.", method ); - mappingErroneous = true; - } - - if ( mappingErroneous ) { - continue; - } - } - - //retrieve property mappings if an implementation for the method needs to be generated - List properties = declaringMapper == null ? retrieveMappedProperties( method ) : Collections - .emptyList(); - - methods.add( - new Method( - declaringMapper, - method, - parameter.getName(), - parameter.getType(), - returnType, - properties - ) - ); - } - - MapperPrism mapperPrism = MapperPrism.getInstanceOn( element ); - - if ( mapperPrism != null ) { - for ( TypeMirror usedMapper : mapperPrism.uses() ) { - methods.addAll( - retrieveMethods( - typeUtil.retrieveType( usedMapper ), - ( (DeclaredType) usedMapper ).asElement() - ) - ); - } - } - - return methods; - } - - private List retrieveMappedProperties(ExecutableElement method) { - Map mappings = new HashMap(); - - MappingPrism mappingAnnotation = MappingPrism.getInstanceOn( method ); - MappingsPrism mappingsAnnotation = MappingsPrism.getInstanceOn( method ); - - if ( mappingAnnotation != null ) { - mappings.put( mappingAnnotation.source(), getMapping( mappingAnnotation ) ); - } - - if ( mappingsAnnotation != null ) { - mappings.putAll( getMappings( mappingsAnnotation ) ); - } - - return getMappedProperties( method, mappings ); - } - - private List getMappedProperties(ExecutableElement method, Map mappings) { - TypeElement returnTypeElement = (TypeElement) typeUtils.asElement( method.getReturnType() ); - TypeElement parameterElement = (TypeElement) typeUtils.asElement( method.getParameters().get( 0 ).asType() ); - - List properties = new ArrayList(); - - List sourceGetters = Filters.getterMethodsIn( - elementUtils.getAllMembers( parameterElement ) - ); - List targetSetters = Filters.setterMethodsIn( - elementUtils.getAllMembers( returnTypeElement ) - ); - List sourceSetters = Filters.setterMethodsIn( - elementUtils.getAllMembers( parameterElement ) - ); - List targetGetters = Filters.getterMethodsIn( - elementUtils.getAllMembers( returnTypeElement ) - ); - - reportErrorIfMappedPropertiesDontExist( method, mappings, sourceGetters, targetSetters ); - - for ( ExecutableElement getterMethod : sourceGetters ) { - String sourcePropertyName = Executables.getPropertyName( getterMethod ); - Mapping mapping = mappings.get( sourcePropertyName ); - - for ( ExecutableElement setterMethod : targetSetters ) { - String targetPropertyName = Executables.getPropertyName( setterMethod ); - - if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) { - properties.add( - new MappedProperty( - sourcePropertyName, - getterMethod.getSimpleName().toString(), - Executables.getCorrespondingPropertyAccessor( getterMethod, sourceSetters ) - .getSimpleName() - .toString(), - retrieveReturnType( getterMethod ), - mapping != null ? mapping.getTargetName() : targetPropertyName, - Executables.getCorrespondingPropertyAccessor( setterMethod, targetGetters ) - .getSimpleName() - .toString(), - setterMethod.getSimpleName().toString(), - retrieveParameter( setterMethod ).getType() - ) - ); - } - } - } - - return properties; - } - - private void reportErrorIfMappedPropertiesDontExist(ExecutableElement method, Map mappings, - List sourceGetters, - List targetSetters) { - - Set sourcePropertyNames = getPropertyNames( sourceGetters ); - Set targetPropertyNames = getPropertyNames( targetSetters ); - - for ( Mapping mappedProperty : mappings.values() ) { - if ( !sourcePropertyNames.contains( mappedProperty.getSourceName() ) ) { - reportError( - String.format( - "Unknown property \"%s\" in parameter type %s.", - mappedProperty.getSourceName(), - retrieveParameter( method ).getType() - ), method, mappedProperty.getMirror(), mappedProperty.getSourceAnnotationValue() - ); - } - if ( !targetPropertyNames.contains( mappedProperty.getTargetName() ) ) { - reportError( - String.format( - "Unknown property \"%s\" in return type %s.", - mappedProperty.getTargetName(), - retrieveReturnType( method ) - ), method, mappedProperty.getMirror(), mappedProperty.getTargetAnnotationValue() - ); - } - } - } - - private Set getPropertyNames(List propertyAccessors) { - Set propertyNames = new HashSet(); - - for ( ExecutableElement executableElement : propertyAccessors ) { - propertyNames.add( Executables.getPropertyName( executableElement ) ); - } - - return propertyNames; - } - - private Map getMappings(MappingsPrism mappingsAnnotation) { - Map mappings = new HashMap(); - - for ( MappingPrism mapping : mappingsAnnotation.value() ) { - mappings.put( mapping.source(), getMapping( mapping ) ); - } - - return mappings; - } - - private Mapping getMapping(MappingPrism mapping) { - return new Mapping( - mapping.source(), - mapping.target(), - mapping.mirror, - mapping.values.source(), - mapping.values.target() - ); - } - - private Parameter retrieveParameter(ExecutableElement method) { - List parameters = method.getParameters(); - - if ( parameters.size() != 1 ) { - //TODO: Log error - return null; - } - - VariableElement parameter = parameters.get( 0 ); - - return new Parameter( - parameter.getSimpleName().toString(), - typeUtil.retrieveType( parameter.asType() ) - ); - } - - private Type retrieveReturnType(ExecutableElement method) { - return typeUtil.retrieveType( method.getReturnType() ); - } - - private void reportError(String message, Element element) { - processingEnvironment.getMessager().printMessage( Kind.ERROR, message, element ); - mappingErroneous = true; - } - - private void reportError(String message, Element element, AnnotationMirror annotationMirror, - AnnotationValue annotationValue) { - processingEnvironment.getMessager() - .printMessage( Kind.ERROR, message, element, annotationMirror, annotationValue ); - mappingErroneous = true; - } -} diff --git a/All/Genesis-NP/Genesis#209/pair.info b/All/Genesis-NP/Genesis#209/pair.info deleted file mode 100755 index 9ec2267..0000000 --- a/All/Genesis-NP/Genesis#209/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:209 -SATName:Genesis -modifiedFPath:processor/src/main/java/org/mapstruct/ap/MapperGenerationVisitor.java -comSha:bc22e6ce1567e27fa338fa0c329b61065507c291 -parentComSha:bc22e6ce1567e27fa338fa0c329b61065507c291^1 -githubUrl:https://github.com/mapstruct/mapstruct -repoName:mapstruct#mapstruct \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#214/comMsg.txt b/All/Genesis-NP/Genesis#214/comMsg.txt deleted file mode 100755 index ca84895..0000000 --- a/All/Genesis-NP/Genesis#214/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixed NPE in TemplateEngineManagerImpl diff --git a/All/Genesis-NP/Genesis#214/diff.diff b/All/Genesis-NP/Genesis#214/diff.diff deleted file mode 100755 index 6720c05..0000000 --- a/All/Genesis-NP/Genesis#214/diff.diff +++ /dev/null @@ -1,27 +0,0 @@ -diff --git a/ninja-core/src/main/java/ninja/template/TemplateEngineManagerImpl.java b/ninja-core/src/main/java/ninja/template/TemplateEngineManagerImpl.java -index 06596b7..8cfb2e1 100644 ---- a/ninja-core/src/main/java/ninja/template/TemplateEngineManagerImpl.java -+++ b/ninja-core/src/main/java/ninja/template/TemplateEngineManagerImpl.java -@@ -3,3 +2,0 @@ package ninja.template; --import com.google.common.collect.ImmutableMap; --import com.google.inject.*; -- -@@ -8,0 +6,8 @@ import java.util.Map; -+import com.google.common.collect.ImmutableMap; -+import com.google.inject.Binding; -+import com.google.inject.Inject; -+import com.google.inject.Injector; -+import com.google.inject.Key; -+import com.google.inject.Provider; -+import com.google.inject.Singleton; -+ -@@ -43 +48,8 @@ public class TemplateEngineManagerImpl implements TemplateEngineManager { -- return contentTypeToTemplateEngineMap.get(contentType).get(); -+ Provider provider = contentTypeToTemplateEngineMap -+ .get(contentType); -+ -+ if (provider != null) { -+ return provider.get(); -+ } else { -+ return null; -+ } diff --git a/All/Genesis-NP/Genesis#214/new/TemplateEngineManagerImpl.java b/All/Genesis-NP/Genesis#214/new/TemplateEngineManagerImpl.java deleted file mode 100755 index 8cfb2e1..0000000 --- a/All/Genesis-NP/Genesis#214/new/TemplateEngineManagerImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package ninja.template; - -import java.util.HashMap; -import java.util.Map; - -import com.google.common.collect.ImmutableMap; -import com.google.inject.Binding; -import com.google.inject.Inject; -import com.google.inject.Injector; -import com.google.inject.Key; -import com.google.inject.Provider; -import com.google.inject.Singleton; - -@Singleton -public class TemplateEngineManagerImpl implements TemplateEngineManager { - - // Keep a reference of providers rather than instances, so template engines don't have - // to be singleton if they don't want - private final Map> contentTypeToTemplateEngineMap; - - @Inject - public TemplateEngineManagerImpl(Provider templateEngineFreemarker, - Provider templateEngineJsonGson, - Injector injector) { - - Map> map - = new HashMap>(); - - // First put the built in ones in, this is so they can be overridden by - // custom bindings - map.put(templateEngineFreemarker.get().getContentType(), templateEngineFreemarker); - map.put(templateEngineJsonGson.get().getContentType(), templateEngineJsonGson); - - // Now lookup all explicit bindings, and find the ones that implement TemplateEngine - for (Map.Entry, Binding> binding : injector.getBindings().entrySet()) { - if (TemplateEngine.class.isAssignableFrom(binding.getKey().getTypeLiteral().getRawType())) { - Provider provider = - (Provider) binding.getValue().getProvider(); - map.put(provider.get().getContentType(), provider); - } - } - - contentTypeToTemplateEngineMap = ImmutableMap.copyOf(map); - } - - @Override - public TemplateEngine getTemplateEngineForContentType(String contentType) { - Provider provider = contentTypeToTemplateEngineMap - .get(contentType); - - if (provider != null) { - return provider.get(); - } else { - return null; - } - } -} diff --git a/All/Genesis-NP/Genesis#214/old/TemplateEngineManagerImpl.java b/All/Genesis-NP/Genesis#214/old/TemplateEngineManagerImpl.java deleted file mode 100755 index 06596b7..0000000 --- a/All/Genesis-NP/Genesis#214/old/TemplateEngineManagerImpl.java +++ /dev/null @@ -1,45 +0,0 @@ -package ninja.template; - -import com.google.common.collect.ImmutableMap; -import com.google.inject.*; - -import java.util.HashMap; -import java.util.Map; - -@Singleton -public class TemplateEngineManagerImpl implements TemplateEngineManager { - - // Keep a reference of providers rather than instances, so template engines don't have - // to be singleton if they don't want - private final Map> contentTypeToTemplateEngineMap; - - @Inject - public TemplateEngineManagerImpl(Provider templateEngineFreemarker, - Provider templateEngineJsonGson, - Injector injector) { - - Map> map - = new HashMap>(); - - // First put the built in ones in, this is so they can be overridden by - // custom bindings - map.put(templateEngineFreemarker.get().getContentType(), templateEngineFreemarker); - map.put(templateEngineJsonGson.get().getContentType(), templateEngineJsonGson); - - // Now lookup all explicit bindings, and find the ones that implement TemplateEngine - for (Map.Entry, Binding> binding : injector.getBindings().entrySet()) { - if (TemplateEngine.class.isAssignableFrom(binding.getKey().getTypeLiteral().getRawType())) { - Provider provider = - (Provider) binding.getValue().getProvider(); - map.put(provider.get().getContentType(), provider); - } - } - - contentTypeToTemplateEngineMap = ImmutableMap.copyOf(map); - } - - @Override - public TemplateEngine getTemplateEngineForContentType(String contentType) { - return contentTypeToTemplateEngineMap.get(contentType).get(); - } -} diff --git a/All/Genesis-NP/Genesis#214/pair.info b/All/Genesis-NP/Genesis#214/pair.info deleted file mode 100755 index 42ae91c..0000000 --- a/All/Genesis-NP/Genesis#214/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:214 -SATName:Genesis -modifiedFPath:ninja-core/src/main/java/ninja/template/TemplateEngineManagerImpl.java -comSha:1731d23da3eacefd3c113d65328bd25746261e7b -parentComSha:1731d23da3eacefd3c113d65328bd25746261e7b^1 -githubUrl:https://github.com/ninjaframework/ninja -repoName:ninjaframework#ninja \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#215/comMsg.txt b/All/Genesis-NP/Genesis#215/comMsg.txt deleted file mode 100755 index 61d29c6..0000000 --- a/All/Genesis-NP/Genesis#215/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix for NPE during TermsAggregation instantiation diff --git a/All/Genesis-NP/Genesis#215/diff.diff b/All/Genesis-NP/Genesis#215/diff.diff deleted file mode 100755 index 21dd3ae..0000000 --- a/All/Genesis-NP/Genesis#215/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/jest-common/src/main/java/io/searchbox/core/search/aggregation/TermsAggregation.java b/jest-common/src/main/java/io/searchbox/core/search/aggregation/TermsAggregation.java -index 5c26270..93472c2 100644 ---- a/jest-common/src/main/java/io/searchbox/core/search/aggregation/TermsAggregation.java -+++ b/jest-common/src/main/java/io/searchbox/core/search/aggregation/TermsAggregation.java -@@ -12 +12,5 @@ import java.util.List; --import static io.searchbox.core.search.aggregation.AggregationField.*; -+import static io.searchbox.core.search.aggregation.AggregationField.BUCKETS; -+import static io.searchbox.core.search.aggregation.AggregationField.DOC_COUNT; -+import static io.searchbox.core.search.aggregation.AggregationField.DOC_COUNT_ERROR_UPPER_BOUND; -+import static io.searchbox.core.search.aggregation.AggregationField.KEY; -+import static io.searchbox.core.search.aggregation.AggregationField.SUM_OTHER_DOC_COUNT; -@@ -27,0 +32 @@ public class TermsAggregation extends BucketAggregation { -+ if (termAggregation.has(String.valueOf(DOC_COUNT_ERROR_UPPER_BOUND))) { -@@ -28,0 +34,2 @@ public class TermsAggregation extends BucketAggregation { -+ } -+ if (termAggregation.has(String.valueOf(SUM_OTHER_DOC_COUNT))) { -@@ -29,0 +37 @@ public class TermsAggregation extends BucketAggregation { -+ } diff --git a/All/Genesis-NP/Genesis#215/new/TermsAggregation.java b/All/Genesis-NP/Genesis#215/new/TermsAggregation.java deleted file mode 100755 index 93472c2..0000000 --- a/All/Genesis-NP/Genesis#215/new/TermsAggregation.java +++ /dev/null @@ -1,134 +0,0 @@ -package io.searchbox.core.search.aggregation; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.LinkedList; -import java.util.List; - -import static io.searchbox.core.search.aggregation.AggregationField.BUCKETS; -import static io.searchbox.core.search.aggregation.AggregationField.DOC_COUNT; -import static io.searchbox.core.search.aggregation.AggregationField.DOC_COUNT_ERROR_UPPER_BOUND; -import static io.searchbox.core.search.aggregation.AggregationField.KEY; -import static io.searchbox.core.search.aggregation.AggregationField.SUM_OTHER_DOC_COUNT; - -/** - * @author cfstout - */ - -public class TermsAggregation extends BucketAggregation { - - public static final String TYPE = "terms"; - - private Long docCountErrorUpperBound; - private Long sumOtherDocCount; - private List buckets = new LinkedList(); - - public TermsAggregation(String name, JsonObject termAggregation) { - super(name, termAggregation); - if (termAggregation.has(String.valueOf(DOC_COUNT_ERROR_UPPER_BOUND))) { - docCountErrorUpperBound = termAggregation.get(String.valueOf(DOC_COUNT_ERROR_UPPER_BOUND)).getAsLong(); - } - if (termAggregation.has(String.valueOf(SUM_OTHER_DOC_COUNT))) { - sumOtherDocCount = termAggregation.get(String.valueOf(SUM_OTHER_DOC_COUNT)).getAsLong(); - } - - if (termAggregation.has(String.valueOf(BUCKETS)) && termAggregation.get(String.valueOf(BUCKETS)).isJsonArray()) { - parseBuckets(termAggregation.get(String.valueOf(BUCKETS)).getAsJsonArray()); - } - } - - private void parseBuckets(JsonArray bucketsSource) { - for(JsonElement bucketElement : bucketsSource) { - JsonObject bucket = (JsonObject) bucketElement; - Entry entry = new Entry(bucket, bucket.get(String.valueOf(KEY)).getAsString(), bucket.get(String.valueOf(DOC_COUNT)).getAsLong()); - buckets.add(entry); - } - } - - public Long getDocCountErrorUpperBound() { - return docCountErrorUpperBound; - } - - public Long getSumOtherDocCount() { - return sumOtherDocCount; - } - - public List getBuckets() { - return buckets; - } - - public class Entry extends Bucket { - private String key; - - public Entry(JsonObject bucket, String key, Long count) { - super(bucket, count); - this.key = key; - } - - public String getKey() { - return key; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj.getClass() != getClass()) { - return false; - } - - Entry rhs = (Entry) obj; - return new EqualsBuilder() - .appendSuper(super.equals(obj)) - .append(key, rhs.key) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder() - .append(getCount()) - .append(getKey()) - .toHashCode(); - } - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj.getClass() != getClass()) { - return false; - } - - TermsAggregation rhs = (TermsAggregation) obj; - return new EqualsBuilder() - .appendSuper(super.equals(obj)) - .append(buckets, rhs.buckets) - .append(docCountErrorUpperBound, rhs.docCountErrorUpperBound) - .append(sumOtherDocCount, rhs.sumOtherDocCount) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder() - .appendSuper(super.hashCode()) - .append(docCountErrorUpperBound) - .append(sumOtherDocCount) - .append(buckets) - .toHashCode(); - } -} diff --git a/All/Genesis-NP/Genesis#215/old/TermsAggregation.java b/All/Genesis-NP/Genesis#215/old/TermsAggregation.java deleted file mode 100755 index 5c26270..0000000 --- a/All/Genesis-NP/Genesis#215/old/TermsAggregation.java +++ /dev/null @@ -1,126 +0,0 @@ -package io.searchbox.core.search.aggregation; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import org.apache.commons.lang3.builder.EqualsBuilder; -import org.apache.commons.lang3.builder.HashCodeBuilder; - -import java.util.LinkedList; -import java.util.List; - -import static io.searchbox.core.search.aggregation.AggregationField.*; - -/** - * @author cfstout - */ - -public class TermsAggregation extends BucketAggregation { - - public static final String TYPE = "terms"; - - private Long docCountErrorUpperBound; - private Long sumOtherDocCount; - private List buckets = new LinkedList(); - - public TermsAggregation(String name, JsonObject termAggregation) { - super(name, termAggregation); - docCountErrorUpperBound = termAggregation.get(String.valueOf(DOC_COUNT_ERROR_UPPER_BOUND)).getAsLong(); - sumOtherDocCount = termAggregation.get(String.valueOf(SUM_OTHER_DOC_COUNT)).getAsLong(); - - if(termAggregation.has(String.valueOf(BUCKETS)) && termAggregation.get(String.valueOf(BUCKETS)).isJsonArray()) { - parseBuckets(termAggregation.get(String.valueOf(BUCKETS)).getAsJsonArray()); - } - } - - private void parseBuckets(JsonArray bucketsSource) { - for(JsonElement bucketElement : bucketsSource) { - JsonObject bucket = (JsonObject) bucketElement; - Entry entry = new Entry(bucket, bucket.get(String.valueOf(KEY)).getAsString(), bucket.get(String.valueOf(DOC_COUNT)).getAsLong()); - buckets.add(entry); - } - } - - public Long getDocCountErrorUpperBound() { - return docCountErrorUpperBound; - } - - public Long getSumOtherDocCount() { - return sumOtherDocCount; - } - - public List getBuckets() { - return buckets; - } - - public class Entry extends Bucket { - private String key; - - public Entry(JsonObject bucket, String key, Long count) { - super(bucket, count); - this.key = key; - } - - public String getKey() { - return key; - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj.getClass() != getClass()) { - return false; - } - - Entry rhs = (Entry) obj; - return new EqualsBuilder() - .appendSuper(super.equals(obj)) - .append(key, rhs.key) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder() - .append(getCount()) - .append(getKey()) - .toHashCode(); - } - } - - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (obj == this) { - return true; - } - if (obj.getClass() != getClass()) { - return false; - } - - TermsAggregation rhs = (TermsAggregation) obj; - return new EqualsBuilder() - .appendSuper(super.equals(obj)) - .append(buckets, rhs.buckets) - .append(docCountErrorUpperBound, rhs.docCountErrorUpperBound) - .append(sumOtherDocCount, rhs.sumOtherDocCount) - .isEquals(); - } - - @Override - public int hashCode() { - return new HashCodeBuilder() - .appendSuper(super.hashCode()) - .append(docCountErrorUpperBound) - .append(sumOtherDocCount) - .append(buckets) - .toHashCode(); - } -} diff --git a/All/Genesis-NP/Genesis#215/pair.info b/All/Genesis-NP/Genesis#215/pair.info deleted file mode 100755 index d86918e..0000000 --- a/All/Genesis-NP/Genesis#215/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:215 -SATName:Genesis -modifiedFPath:jest-common/src/main/java/io/searchbox/core/search/aggregation/TermsAggregation.java -comSha:88387d13a4566e01c60f795b982e0a8b20b04ec0 -parentComSha:88387d13a4566e01c60f795b982e0a8b20b04ec0^1 -githubUrl:https://github.com/searchbox-io/Jest -repoName:searchbox-io#Jest \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#219/comMsg.txt b/All/Genesis-NP/Genesis#219/comMsg.txt deleted file mode 100755 index a6e5b48..0000000 --- a/All/Genesis-NP/Genesis#219/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixed: NPE with find(), if region's timeout is set to 0 diff --git a/All/Genesis-NP/Genesis#219/diff.diff b/All/Genesis-NP/Genesis#219/diff.diff deleted file mode 100755 index c1cb261..0000000 --- a/All/Genesis-NP/Genesis#219/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/API/src/main/java/org/sikuli/script/Region.java b/API/src/main/java/org/sikuli/script/Region.java -index 47aeefa..f4227e0 100644 ---- a/API/src/main/java/org/sikuli/script/Region.java -+++ b/API/src/main/java/org/sikuli/script/Region.java -@@ -2707,0 +2708,4 @@ public class Region { -+ double findTimeout = autoWaitTimeout; -+ if (repeating != null) { -+ findTimeout = repeating.getFindTimeOut(); -+ } -@@ -2729 +2733 @@ public class Region { -- f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), null); -+ f = checkLastSeenAndCreateFinder(img, findTimeout, null); -@@ -2752 +2756 @@ public class Region { -- f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), (Pattern) ptn); -+ f = checkLastSeenAndCreateFinder(img, findTimeout, (Pattern) ptn); -@@ -2764 +2768 @@ public class Region { -- f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), null); -+ f = checkLastSeenAndCreateFinder(img, findTimeout, null); diff --git a/All/Genesis-NP/Genesis#219/new/Region.java b/All/Genesis-NP/Genesis#219/new/Region.java deleted file mode 100755 index f4227e0..0000000 --- a/All/Genesis-NP/Genesis#219/new/Region.java +++ /dev/null @@ -1,4306 +0,0 @@ -/* - * Copyright 2010-2014, Sikuli.org, Sikulix.com - * Released under the MIT License. - * - * modified RaiMan - */ -package org.sikuli.script; - -import org.sikuli.util.ScreenHighlighter; -import java.awt.Rectangle; -import java.awt.event.InputEvent; -import java.awt.event.KeyEvent; -import java.io.IOException; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import org.sikuli.basics.Debug; -import org.sikuli.basics.Settings; - -import edu.unh.iol.dlc.VNCScreen; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; - -/** - * A Region is a rectengular area and lies always completely inside its parent screen - * - */ -public class Region { - - static RunTime runTime = RunTime.get(); - - private static String me = "Region: "; - private static int lvl = 3; - - private static void log(int level, String message, Object... args) { - Debug.logx(level, me + message, args); - } - - /** - * The Screen containing the Region - */ - private IScreen scr; - protected boolean otherScreen = false; - - /** - * The ScreenHighlighter for this Region - */ - private ScreenHighlighter overlay = null; - /** - * X-coordinate of the Region - */ - public int x; - /** - * Y-coordinate of the Region - */ - public int y; - /** - * Width of the Region - */ - public int w; - /** - * Height of the Region - */ - public int h; - /** - * Setting, how to react if an image is not found {@link FindFailed} - */ - private FindFailedResponse findFailedResponse = FindFailed.defaultFindFailedResponse; - /** - * Setting {@link Settings}, if exception is thrown if an image is not found - */ - private boolean throwException = Settings.ThrowException; - /** - * Default time to wait for an image {@link Settings} - */ - private double autoWaitTimeout = Settings.AutoWaitTimeout; - private float waitScanRate = Settings.WaitScanRate; - /** - * Flag, if an observer is running on this region {@link Settings} - */ - private boolean observing = false; - private float observeScanRate = Settings.ObserveScanRate; - private int repeatWaitTime = Settings.RepeatWaitTime; - /** - * The {@link Observer} Singleton instance - */ - private Observer regionObserver = null; - - /** - * The last found {@link Match} in the Region - */ - private Match lastMatch = null; - /** - * The last found {@link Match}es in the Region - */ - private Iterator lastMatches = null; - private long lastSearchTime = -1; - private long lastFindTime = -1; - private boolean isScreenUnion = false; - private boolean isVirtual = false; - private long lastSearchTimeRepeat = -1; - - /** - * in case of not found the total wait time - * @return the duration of the last find op - */ - public long getLastTime() { - return lastFindTime; - } - - /** - * the area constants for use with get() - */ - public static final int NW = 300, NORTH_WEST = NW, TL = NW; - public static final int NM = 301, NORTH_MID = NM, TM = NM; - public static final int NE = 302, NORTH_EAST = NE, TR = NE; - public static final int EM = 312, EAST_MID = EM, RM = EM; - public static final int SE = 322, SOUTH_EAST = SE, BR = SE; - public static final int SM = 321, SOUTH_MID = SM, BM = SM; - public static final int SW = 320, SOUTH_WEST = SW, BL = SW; - public static final int WM = 310, WEST_MID = WM, LM = WM; - public static final int MM = 311, MIDDLE = MM, M3 = MM; - public static final int TT = 200; - public static final int RR = 201; - public static final int BB = 211; - public static final int LL = 210; - public static final int NH = 202, NORTH = NH, TH = NH; - public static final int EH = 221, EAST = EH, RH = EH; - public static final int SH = 212, SOUTH = SH, BH = SH; - public static final int WH = 220, WEST = WH, LH = WH; - public static final int MV = 441, MID_VERTICAL = MV, CV = MV; - public static final int MH = 414, MID_HORIZONTAL = MH, CH = MH; - public static final int M2 = 444, MIDDLE_BIG = M2, C2 = M2; - public static final int EN = NE, EAST_NORTH = NE, RT = TR; - public static final int ES = SE, EAST_SOUTH = SE, RB = BR; - public static final int WN = NW, WEST_NORTH = NW, LT = TL; - public static final int WS = SW, WEST_SOUTH = SW, LB = BL; - - /** - * to support a raster over the region - */ - private int rows; - private int cols = 0; - private int rowH = 0; - private int colW = 0; - private int rowHd = 0; - private int colWd = 0; - - /** - * {@inheritDoc} - * - * @return the description - */ - @Override - public String toString() { - return String.format("R[%d,%d %dx%d]@%s E:%s, T:%.1f", - x, y, w, h, (getScreen() == null ? "Screen null" : getScreen().toStringShort()), - throwException ? "Y" : "N", autoWaitTimeout); - } - - /** - * - * @return a compact description - */ - public String toStringShort() { - return String.format("R[%d,%d %dx%d]@S(%s)", x, y, w, h, (getScreen() == null ? "?" : getScreen().getID())); - } - - public String toJSON() { - return String.format("[\"R\", %d, %d, %d, %d]", x, y, w, h); - } - - // - /* - public Object __enter__() { - Debug.error("Region: with(__enter__): Trying to make it a Jython Region for with: usage"); - IScriptRunner runner = Settings.getScriptRunner("jython", null, null); - if (runner != null) { - Object[] jyreg = new Object[]{this}; - if (runner.doSomethingSpecial("createRegionForWith", jyreg)) { - if (jyreg[0] != null) { - return jyreg[0]; - } - } - } - Debug.error("Region: with(__enter__): Sorry, not possible"); - return null; - } - - public void __exit__(Object type, Object value, Object traceback) { - Debug.error("Region: with(__exit__): Sorry, not a Jython Region and not posssible!"); - } - */ - // - - // - /** - * Detects on which Screen the Region is present. The region is cropped to the intersection with the given screen or - * the screen with the largest intersection - * - * @param iscr The Screen containing the Region - */ - public void initScreen(IScreen iscr) { - // check given screen first - Rectangle rect, screenRect; - IScreen screen, screenOn; - if (iscr != null) { - if (iscr.isOtherScreen()) { - if (x < 0) { - w = w + x; - x = 0; - } - if (y < 0) { - h = h + y; - y = 0; - } - this.scr = iscr; - this.otherScreen = true; - return; - } - if (iscr.getID() > -1) { - rect = regionOnScreen(iscr); - if (rect != null) { - x = rect.x; - y = rect.y; - w = rect.width; - h = rect.height; - this.scr = iscr; - return; - } - } else { - // is ScreenUnion - return; - } - } - // check all possible screens if no screen was given or the region is not on given screen - // crop to the screen with the largest intersection - screenRect = new Rectangle(0, 0, 0, 0); - screenOn = null; - boolean isVNC; - if (iscr == null) { - isVNC = scr instanceof VNCScreen; - } else { - isVNC = iscr instanceof VNCScreen; - } - if (!isVNC) { - for (int i = 0; i < Screen.getNumberScreens(); i++) { - screen = Screen.getScreen(i); - rect = regionOnScreen(screen); - if (rect != null) { - if (rect.width * rect.height > screenRect.width * screenRect.height) { - screenRect = rect; - screenOn = screen; - } - } - } - } else { - for (int i = 0; i < VNCScreen.getNumberScreens(); i++) { - screen = VNCScreen.getScreen(i); - rect = regionOnScreen(screen); - if (rect != null) { - if (rect.width * rect.height > screenRect.width * screenRect.height) { - screenRect = rect; - screenOn = screen; - } - } - } - } - if (screenOn != null) { - x = screenRect.x; - y = screenRect.y; - w = screenRect.width; - h = screenRect.height; - this.scr = screenOn; - } else { - // no screen found - this.scr = null; - Debug.error("Region(%d,%d,%d,%d) outside any screen - subsequent actions might not work as expected", x, y, w, h); - } - } - - private Location checkAndSetRemote(Location loc) { - if (!isOtherScreen()) { - return loc; - } - return loc.setOtherScreen(scr); - } - - public static Region virtual(Rectangle rect) { - Region reg = new Region(); - reg.x = rect.x; - reg.y = rect.y; - reg.w = rect.width; - reg.h = rect.height; - reg.setVirtual(true); - reg.scr = Screen.getPrimaryScreen(); - return reg; - } - - /** - * INTERNAL USE - EXPERIMENTAL - * if true: this region is not bound to any screen - * @return the current state - */ - public boolean isVirtual() { - return isVirtual; - } - - /** - * INTERNAL USE - EXPERIMENTAL - * @param state if true: this region is not bound to any screen - */ - public void setVirtual(boolean state) { - isVirtual = state; - } - - /** - * INTERNAL USE: - * checks wether this region belongs to a non-Desktop screen - * @return true/false - */ - public boolean isOtherScreen() { - return otherScreen; - } - - /** - * INTERNAL USE: - * flags this region as belonging to a non-Desktop screen - */ - public void setOtherScreen() { - otherScreen = true; - } - - /** - * Checks if the Screen contains the Region. - * - * @param screen The Screen in which the Region might be - * @return True, if the Region is on the Screen. False if the Region is not inside the Screen - */ - protected Rectangle regionOnScreen(IScreen screen) { - if (screen == null) { - return null; - } - // get intersection of Region and Screen - Rectangle rect = screen.getRect().intersection(getRect()); - // no Intersection, Region is not on the Screen - if (rect.isEmpty()) { - return null; - } - return rect; - } - - /** - * Check wether thie Region is contained by any of the available screens - * @return true if yes, false otherwise - */ - public boolean isValid() { - return scr != null; - } - // - - // - /** - * Create a region with the provided coordinate / size and screen - * - * @param X X position - * @param Y Y position - * @param W width - * @param H heigth - * @param screenNumber The number of the screen containing the Region - */ - public Region(int X, int Y, int W, int H, int screenNumber) { - this(X, Y, W, H, Screen.getScreen(screenNumber)); - this.rows = 0; - } - - /** - * Create a region with the provided coordinate / size and screen - * - * @param X X position - * @param Y Y position - * @param W width - * @param H heigth - * @param parentScreen the screen containing the Region - */ - public Region(int X, int Y, int W, int H, IScreen parentScreen) { - this.rows = 0; - this.x = X; - this.y = Y; - this.w = W > 1 ? W : 1; - this.h = H > 1 ? H : 1; - initScreen(parentScreen); - } - - /** - * Create a region with the provided coordinate / size - * - * @param X X position - * @param Y Y position - * @param W width - * @param H heigth - */ - public Region(int X, int Y, int W, int H) { - this(X, Y, W, H, null); - this.rows = 0; - log(lvl, "init: (%d, %d, %d, %d)", X, Y, W, H); - } - - /** - * Create a region from a Rectangle - * - * @param r the Rectangle - */ - public Region(Rectangle r) { - this(r.x, r.y, r.width, r.height, null); - this.rows = 0; - } - - /** - * Create a new region from another region
including the region's settings - * - * @param r the region - */ - public Region(Region r) { - this(r.x, r.y, r.w, r.h, r.getScreen()); - this.rows = 0; - autoWaitTimeout = r.autoWaitTimeout; - findFailedResponse = r.findFailedResponse; - throwException = r.throwException; - } - - //
- - // - /** - * internal use only, used for new Screen objects to get the Region behavior - */ - protected Region() { - this.rows = 0; - } - - /** - * internal use only, used for new Screen objects to get the Region behavior - */ - protected Region(boolean isScreenUnion) { - this.isScreenUnion = isScreenUnion; - this.rows = 0; - } - - /** - * Create a region with the provided top left corner and size - * - * @param X top left X position - * @param Y top left Y position - * @param W width - * @param H heigth - * @return then new region - */ - public static Region create(int X, int Y, int W, int H) { - return Region.create(X, Y, W, H, null); - } - - /** - * Create a region with the provided top left corner and size - * - * @param X top left X position - * @param Y top left Y position - * @param W width - * @param H heigth - * @param scr the source screen - * @return the new region - */ - private static Region create(int X, int Y, int W, int H, IScreen scr) { - return new Region(X, Y, W, H, scr); - } - - /** - * Create a region with the provided top left corner and size - * - * @param loc top left corner - * @param w width - * @param h height - * @return then new region - */ - public static Region create(Location loc, int w, int h) { - return Region.create(loc.x, loc.y, w, h, loc.getScreen()); - } - /** - * Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the left corner of - * the new Region. - */ - public final static int CREATE_X_DIRECTION_LEFT = 0; - /** - * Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the right corner of - * the new Region. - */ - public final static int CREATE_X_DIRECTION_RIGHT = 1; - /** - * Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the top corner of the - * new Region. - */ - public final static int CREATE_Y_DIRECTION_TOP = 0; - /** - * Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the bottom corner of - * the new Region. - */ - public final static int CREATE_Y_DIRECTION_BOTTOM = 1; - - /** - * create a region with a corner at the given point
as specified with x y
0 0 top left
0 1 bottom left
- * 1 0 top right
1 1 bottom right
- * - * @param loc the refence point - * @param create_x_direction == 0 is left side !=0 is right side - * @param create_y_direction == 0 is top side !=0 is bottom side - * @param w the width - * @param h the height - * @return the new region - */ - public static Region create(Location loc, int create_x_direction, int create_y_direction, int w, int h) { - int X; - int Y; - int W = w; - int H = h; - if (create_x_direction == CREATE_X_DIRECTION_LEFT) { - if (create_y_direction == CREATE_Y_DIRECTION_TOP) { - X = loc.x; - Y = loc.y; - } else { - X = loc.x; - Y = loc.y - h; - } - } else { - if (create_y_direction == CREATE_Y_DIRECTION_TOP) { - X = loc.x - w; - Y = loc.y; - } else { - X = loc.x - w; - Y = loc.y - h; - } - } - return Region.create(X, Y, W, H, loc.getScreen()); - } - - /** - * create a region with a corner at the given point
as specified with x y
0 0 top left
0 1 bottom left
- * 1 0 top right
1 1 bottom right
same as the corresponding create method, here to be naming compatible with - * class Location - * - * @param loc the refence point - * @param x ==0 is left side !=0 is right side - * @param y ==0 is top side !=0 is bottom side - * @param w the width - * @param h the height - * @return the new region - */ - public static Region grow(Location loc, int x, int y, int w, int h) { - return Region.create(loc, x, y, w, h); - } - - /** - * Create a region from a Rectangle - * - * @param r the Rectangle - * @return the new region - */ - public static Region create(Rectangle r) { - return Region.create(r.x, r.y, r.width, r.height, null); - } - - /** - * Create a region from a Rectangle on a given Screen - * - * @param r the Rectangle - * @param parentScreen the new parent screen - * @return the new region - */ - protected static Region create(Rectangle r, IScreen parentScreen) { - return Region.create(r.x, r.y, r.width, r.height, parentScreen); - } - - /** - * Create a region from another region
including the region's settings - * - * @param r the region - * @return then new region - */ - public static Region create(Region r) { - Region reg = Region.create(r.x, r.y, r.w, r.h, r.getScreen()); - reg.autoWaitTimeout = r.autoWaitTimeout; - reg.findFailedResponse = r.findFailedResponse; - reg.throwException = r.throwException; - return reg; - } - - /** - * create a region with the given point as center and the given size - * - * @param loc the center point - * @param w the width - * @param h the height - * @return the new region - */ - public static Region grow(Location loc, int w, int h) { - int X = loc.x - (int) w / 2; - int Y = loc.y - (int) h / 2; - return Region.create(X, Y, w, h, loc.getScreen()); - } - - /** - * create a minimal region at given point with size 1 x 1 - * - * @param loc the point - * @return the new region - */ - public static Region grow(Location loc) { - return Region.create(loc.x, loc.y, 1, 1, loc.getScreen()); - } - - //
- - // - /** - * check if current region contains given point - * - * @param point Point - * @return true/false - */ - public boolean contains(Location point) { - return getRect().contains(point.x, point.y); - } - - /** - * check if mouse pointer is inside current region - * - * @return true/false - */ - public boolean containsMouse() { - return contains(Mouse.at()); - } - - /** - * new region with same offset to current screen's top left on given screen - * - * @param scrID number of screen - * @return new region - */ - public Region copyTo(int scrID) { - return copyTo(Screen.getScreen(scrID)); - } - - /** - * new region with same offset to current screen's top left on given screen - * - * @param screen new parent screen - * @return new region - */ - public Region copyTo(IScreen screen) { - Location o = new Location(getScreen().getBounds().getLocation()); - Location n = new Location(screen.getBounds().getLocation()); - return Region.create(n.x + x - o.x, n.y + y - o.y, w, h, screen); - } - - /** - * used in Observer.callChangeObserving, Finder.next to adjust region relative coordinates of matches to - screen coordinates - * - * @param m - * @return the modified match - */ - protected Match toGlobalCoord(Match m) { - m.x += x; - m.y += y; - return m; - } - // - - // - //TODO should be possible to reset to current global value resetXXX() - /** - * true - (initial setting) should throw exception FindFailed if findX unsuccessful in this region
false - do not - * abort script on FindFailed (might leed to null pointer exceptions later) - * - * @param flag true/false - */ - public void setThrowException(boolean flag) { - throwException = flag; - if (throwException) { - findFailedResponse = FindFailedResponse.ABORT; - } else { - findFailedResponse = FindFailedResponse.SKIP; - } - } - - /** - * current setting for this region (see setThrowException) - * - * @return true/false - */ - public boolean getThrowException() { - return throwException; - } - - /** - * the time in seconds a find operation should wait for the appearence of the target in this region
initial value - * is the global AutoWaitTimeout setting at time of Region creation - * - * @param sec seconds - */ - public void setAutoWaitTimeout(double sec) { - autoWaitTimeout = sec; - } - - /** - * current setting for this region (see setAutoWaitTimeout) - * - * @return value of seconds - */ - public double getAutoWaitTimeout() { - return autoWaitTimeout; - } - - /** - * FindFailedResponse.
ABORT - (initial value) abort script on FindFailed (= setThrowException(true) )
SKIP - - * ignore FindFailed (same as setThrowException(false) )
- * PROMPT - display prompt on FindFailed to let user decide how to proceed
RETRY - continue to wait for appearence - * on FindFailed (caution: endless loop) - * - * @param response the FindFailedResponse - */ - public void setFindFailedResponse(FindFailedResponse response) { - findFailedResponse = response; - } - - /** - * - * @return the current setting (see setFindFailedResponse) - */ - public FindFailedResponse getFindFailedResponse() { - return findFailedResponse; - } - - /** - * - * @return the regions current WaitScanRate - */ - public float getWaitScanRate() { - return waitScanRate; - } - - /** - * set the regions individual WaitScanRate - * - * @param waitScanRate decimal number - */ - public void setWaitScanRate(float waitScanRate) { - this.waitScanRate = waitScanRate; - } - - /** - * - * @return the regions current ObserveScanRate - */ - public float getObserveScanRate() { - return observeScanRate; - } - - /** - * set the regions individual ObserveScanRate - * - * @param observeScanRate decimal number - */ - public void setObserveScanRate(float observeScanRate) { - this.observeScanRate = observeScanRate; - } - - /** - * INTERNAL USE: Observe - * @return the regions current RepeatWaitTime time in seconds - */ - public int getRepeatWaitTime() { - return repeatWaitTime; - } - - /** - * INTERNAL USE: Observe - * set the regions individual WaitForVanish - * - * @param time in seconds - */ - public void setRepeatWaitTime(int time) { - repeatWaitTime = time; - } - - //
- - // - /** - * - * @return the Screen object containing the region - */ - public IScreen getScreen() { - return scr; - } - - // to avoid NPE for Regions being outside any screen - private IRobot getRobotForRegion() { - if (getScreen() == null || isScreenUnion) { - return Screen.getPrimaryScreen().getRobot(); - } - return getScreen().getRobot(); - } - - /** - * - * @return the screen, that contains the top left corner of the region. Returns primary screen if outside of any - * screen. - * @deprecated Only for compatibility, to get the screen containing this region, use {@link #getScreen()} - */ - @Deprecated - public IScreen getScreenContaining() { - return getScreen(); - } - - /** - * Sets a new Screen for this region. - * - * @param scr the containing screen object - * @return the region itself - */ - protected Region setScreen(IScreen scr) { - initScreen(scr); - return this; - } - - /** - * Sets a new Screen for this region. - * - * @param id the containing screen object's id - * @return the region itself - */ - protected Region setScreen(int id) { - return setScreen(Screen.getScreen(id)); - } - - /** - * synonym for showMonitors - */ - public void showScreens() { - Screen.showMonitors(); - } - - /** - * synonym for resetMonitors - */ - public void resetScreens() { - Screen.resetMonitors(); - } - - // ************************************************ - /** - * - * @return the center pixel location of the region - */ - public Location getCenter() { - return checkAndSetRemote(new Location(getX() + getW() / 2, getY() + getH() / 2)); - } - - /** - * convenience method - * - * @return the region's center - */ - public Location getTarget() { - return getCenter(); - } - - /** - * Moves the region to the area, whose center is the given location - * - * @param loc the location which is the new center of the region - * @return the region itself - */ - public Region setCenter(Location loc) { - Location c = getCenter(); - x = x - c.x + loc.x; - y = y - c.y + loc.y; - initScreen(null); - return this; - } - - /** - * - * @return top left corner Location - */ - public Location getTopLeft() { - return checkAndSetRemote(new Location(x, y)); - } - - /** - * Moves the region to the area, whose top left corner is the given location - * - * @param loc the location which is the new top left point of the region - * @return the region itself - */ - public Region setTopLeft(Location loc) { - return setLocation(loc); - } - - /** - * - * @return top right corner Location - */ - public Location getTopRight() { - return checkAndSetRemote(new Location(x + w - 1, y)); - } - - /** - * Moves the region to the area, whose top right corner is the given location - * - * @param loc the location which is the new top right point of the region - * @return the region itself - */ - public Region setTopRight(Location loc) { - Location c = getTopRight(); - x = x - c.x + loc.x; - y = y - c.y + loc.y; - initScreen(null); - return this; - } - - /** - * - * @return bottom left corner Location - */ - public Location getBottomLeft() { - return checkAndSetRemote(new Location(x, y + h - 1)); - } - - /** - * Moves the region to the area, whose bottom left corner is the given location - * - * @param loc the location which is the new bottom left point of the region - * @return the region itself - */ - public Region setBottomLeft(Location loc) { - Location c = getBottomLeft(); - x = x - c.x + loc.x; - y = y - c.y + loc.y; - initScreen(null); - return this; - } - - /** - * - * @return bottom right corner Location - */ - public Location getBottomRight() { - return checkAndSetRemote(new Location(x + w - 1, y + h - 1)); - } - - /** - * Moves the region to the area, whose bottom right corner is the given location - * - * @param loc the location which is the new bottom right point of the region - * @return the region itself - */ - public Region setBottomRight(Location loc) { - Location c = getBottomRight(); - x = x - c.x + loc.x; - y = y - c.y + loc.y; - initScreen(null); - return this; - } - - // ************************************************ - /** - * - * @return x of top left corner - */ - public int getX() { - return x; - } - - /** - * - * @return y of top left corner - */ - public int getY() { - return y; - } - - /** - * - * @return width of region - */ - public int getW() { - return w; - } - - /** - * - * @return height of region - */ - public int getH() { - return h; - } - - /** - * - * @param X new x position of top left corner - */ - public void setX(int X) { - x = X; - initScreen(null); - } - - /** - * - * @param Y new y position of top left corner - */ - public void setY(int Y) { - y = Y; - initScreen(null); - } - - /** - * - * @param W new width - */ - public void setW(int W) { - w = W > 1 ? W : 1; - initScreen(null); - } - - /** - * - * @param H new height - */ - public void setH(int H) { - h = H > 1 ? H : 1; - initScreen(null); - } - - // ************************************************ - /** - * - * @param W new width - * @param H new height - * @return the region itself - */ - public Region setSize(int W, int H) { - w = W > 1 ? W : 1; - h = H > 1 ? H : 1; - initScreen(null); - return this; - } - - /** - * - * @return the AWT Rectangle of the region - */ - public Rectangle getRect() { - return new Rectangle(x, y, w, h); - } - - /** - * set the regions position/size
this might move the region even to another screen - * - * @param r the AWT Rectangle to use for position/size - * @return the region itself - */ - public Region setRect(Rectangle r) { - return setRect(r.x, r.y, r.width, r.height); - } - - /** - * set the regions position/size
this might move the region even to another screen - * - * @param X new x of top left corner - * @param Y new y of top left corner - * @param W new width - * @param H new height - * @return the region itself - */ - public Region setRect(int X, int Y, int W, int H) { - x = X; - y = Y; - w = W > 1 ? W : 1; - h = H > 1 ? H : 1; - initScreen(null); - return this; - } - - /** - * set the regions position/size
this might move the region even to another screen - * - * @param r the region to use for position/size - * @return the region itself - */ - public Region setRect(Region r) { - return setRect(r.x, r.y, r.w, r.h); - } - - // **************************************************** - -/** - * resets this region (usually a Screen object) to the coordinates of the containing screen - * - * Because of the wanted side effect for the containing screen, this should only be used with screen objects. - * For Region objects use setRect() instead. - */ - public void setROI() { - setROI(getScreen().getBounds()); - } - - /** - * resets this region to the given location, and size
this might move the region even to another screen - * - *
Because of the wanted side effect for the containing screen, this should only be used with screen objects. - *
For Region objects use setRect() instead. - * - * @param X new x - * @param Y new y - * @param W new width - * @param H new height - */ - public void setROI(int X, int Y, int W, int H) { - x = X; - y = Y; - w = W > 1 ? W : 1; - h = H > 1 ? H : 1; - initScreen(null); - } - - /** - * resets this region to the given rectangle
this might move the region even to another screen - * - *
Because of the wanted side effect for the containing screen, this should only be used with screen objects. - *
For Region objects use setRect() instead. - * - * @param r AWT Rectangle - */ - public void setROI(Rectangle r) { - setROI(r.x, r.y, r.width, r.height); - } - - /** - * resets this region to the given region
this might move the region even to another screen - * - *
Because of the wanted side effect for the containing screen, this should only be used with screen objects. - *
For Region objects use setRect() instead. - * - * @param reg Region - */ - public void setROI(Region reg) { - setROI(reg.getX(), reg.getY(), reg.getW(), reg.getH()); - } - - /** - * A function only for backward compatibility - Only makes sense with Screen objects - * - * @return the Region being the current ROI of the containing Screen - */ - public Region getROI() { - return new Region(getScreen().getRect()); - } - - // **************************************************** - /** - * - * @return the region itself - * @deprecated only for backward compatibility - */ - @Deprecated - public Region inside() { - return this; - } - - /** - * set the regions position
this might move the region even to another screen - * - * @param loc new top left corner - * @return the region itself - * @deprecated to be like AWT Rectangle API use setLocation() - */ - @Deprecated - public Region moveTo(Location loc) { - return setLocation(loc); - } - - /** - * set the regions position
this might move the region even to another screen - * - * @param loc new top left corner - * @return the region itself - */ - public Region setLocation(Location loc) { - x = loc.x; - y = loc.y; - initScreen(null); - return this; - } - - /** - * set the regions position/size
this might move the region even to another screen - * - * @param r Region - * @return the region itself - * @deprecated to be like AWT Rectangle API use setRect() instead - */ - @Deprecated - public Region morphTo(Region r) { - return setRect(r); - } - - /** - * resize the region using the given padding values
might be negative - * - * @param l padding on left side - * @param r padding on right side - * @param t padding at top side - * @param b padding at bottom side - * @return the region itself - */ - public Region add(int l, int r, int t, int b) { - x = x - l; - y = y - t; - w = w + l + r; - if (w < 1) { - w = 1; - } - h = h + t + b; - if (h < 1) { - h = 1; - } - initScreen(null); - return this; - } - - /** - * extend the region, so it contains the given region
but only the part inside the current screen - * - * @param r the region to include - * @return the region itself - */ - public Region add(Region r) { - Rectangle rect = getRect(); - rect.add(r.getRect()); - setRect(rect); - initScreen(null); - return this; - } - - /** - * extend the region, so it contains the given point
but only the part inside the current screen - * - * @param loc the point to include - * @return the region itself - */ - public Region add(Location loc) { - Rectangle rect = getRect(); - rect.add(loc.x, loc.y); - setRect(rect); - initScreen(null); - return this; - } - - // ************************************************ - /** - * a find operation saves its match on success in the used region object
unchanged if not successful - * - * @return the Match object from last successful find in this region - */ - public Match getLastMatch() { - return lastMatch; - } - - // ************************************************ - /** - * a searchAll operation saves its matches on success in the used region object
unchanged if not successful - * - * @return a Match-Iterator of matches from last successful searchAll in this region - */ - public Iterator getLastMatches() { - return lastMatches; - } - - // ************************************************ - /** - * get the last image taken on this regions screen - * - * @return the stored ScreenImage - */ - public ScreenImage getLastScreenImage() { - return getScreen().getLastScreenImageFromScreen(); - } - - /** - * stores the lastScreenImage in the current bundle path with a created unique name - * - * @return the absolute file name - * @throws java.io.IOException if not possible - */ - public String getLastScreenImageFile() throws IOException { - return getScreen().getLastScreenImageFile(ImagePath.getBundlePath(), null); - } - - /** - * stores the lastScreenImage in the current bundle path with the given name - * - * @param name file name (.png is added if not there) - * @return the absolute file name - * @throws java.io.IOException if not possible - */ - public String getLastScreenImageFile(String name) throws IOException { - return getScreen().getLastScreenImageFromScreen().getFile(ImagePath.getBundlePath(), name); - } - - /** - * stores the lastScreenImage in the given path with the given name - * - * @param path path to use - * @param name file name (.png is added if not there) - * @return the absolute file name - * @throws java.io.IOException if not possible - */ - public String getLastScreenImageFile(String path, String name) throws IOException { - return getScreen().getLastScreenImageFromScreen().getFile(path, name); - } - - //
- - // - /** - * check if current region contains given region - * - * @param region the other Region - * @return true/false - */ - public boolean contains(Region region) { - return getRect().contains(region.getRect()); - } - - /** - * create a Location object, that can be used as an offset taking the width and hight of this Region - * @return a new Location object with width and height as x and y - */ - public Location asOffset() { - return new Location(w, h); - } - - /** - * create region with same size at top left corner offset - * - * @param loc use its x and y to set the offset - * @return the new region - */ - public Region offset(Location loc) { - return Region.create(x + loc.x, y + loc.y, w, h, scr); - } - - /** - * create region with same size at top left corner offset - * - * @param x horizontal offset - * @param y vertical offset - * @return the new region - */ - public Region offset(int x, int y) { - return Region.create(this.x + x, this.y + y, w, h, scr); - } - - /** - * create a region enlarged Settings.DefaultPadding pixels on each side - * - * @return the new region - * @deprecated to be like AWT Rectangle API use grow() instead - */ - @Deprecated - public Region nearby() { - return grow(Settings.DefaultPadding, Settings.DefaultPadding); - } - - /** - * create a region enlarged range pixels on each side - * - * @param range the margin to be added around - * @return the new region - * @deprecated to be like AWT Rectangle API use grow() instaed - */ - @Deprecated - public Region nearby(int range) { - return grow(range, range); - } - - /** - * create a region enlarged n pixels on each side (n = Settings.DefaultPadding = 50 default) - * - * @return the new region - */ - public Region grow() { - return grow(Settings.DefaultPadding, Settings.DefaultPadding); - } - - /** - * create a region enlarged range pixels on each side - * - * @param range the margin to be added around - * @return the new region - */ - public Region grow(int range) { - return grow(range, range); - } - - /** - * create a region enlarged w pixels on left and right side - * and h pixels at top and bottom - * - * @param w pixels horizontally - * @param h pixels vertically - * @return the new region - */ - public Region grow(int w, int h) { - Rectangle r = getRect(); - r.grow(w, h); - return Region.create(r.x, r.y, r.width, r.height, scr); - } - - /** - * create a region enlarged l pixels on left and r pixels right side - * and t pixels at top side and b pixels a bottom side. - * negative values go inside (shrink) - * - * @param l add to the left - * @param r add to right - * @param t add above - * @param b add beneath - * @return the new region - */ - public Region grow(int l, int r, int t, int b) { - return Region.create(x - l, y - t, w + l + r, h + t + b, scr); - } - - /** - * point middle on right edge - * @return point middle on right edge - */ - public Location rightAt() { - return rightAt(0); - } - - /** - * positive offset goes to the right. - * might be off current screen - * - * @param offset pixels - * @return point with given offset horizontally to middle point on right edge - */ - public Location rightAt(int offset) { - return checkAndSetRemote(new Location(x + w + offset, y + h / 2)); - } - - /** - * create a region right of the right side with same height. - * the new region extends to the right screen border
- * use grow() to include the current region - * - * @return the new region - */ - public Region right() { - int distToRightScreenBorder = getScreen().getX() + getScreen().getW() - (getX() + getW()); - return right(distToRightScreenBorder); - } - - /** - * create a region right of the right side with same height and given width. - * negative width creates the right part with width inside the region
- * use grow() to include the current region - * - * @param width pixels - * @return the new region - */ - public Region right(int width) { - int _x; - if (width < 0) { - _x = x + w + width; - } else { - _x = x + w; - } - return Region.create(_x, y, Math.abs(width), h, scr); - } - - /** - * - * @return point middle on left edge - */ - public Location leftAt() { - return leftAt(0); - } - - /** - * negative offset goes to the left
might be off current screen - * - * @param offset pixels - * @return point with given offset horizontally to middle point on left edge - */ - public Location leftAt(int offset) { - return checkAndSetRemote(new Location(x + offset, y + h / 2)); - } - - /** - * create a region left of the left side with same height
the new region extends to the left screen border
use - * grow() to include the current region - * - * @return the new region - */ - public Region left() { - int distToLeftScreenBorder = getX() - getScreen().getX(); - return left(distToLeftScreenBorder); - } - - /** - * create a region left of the left side with same height and given width
- * negative width creates the left part with width inside the region use grow() to include the current region
- * - * @param width pixels - * @return the new region - */ - public Region left(int width) { - int _x; - if (width < 0) { - _x = x; - } else { - _x = x - width; - } - return Region.create(getScreen().getBounds().intersection(new Rectangle(_x, y, Math.abs(width), h)), scr); - } - - /** - * - * @return point middle on top edge - */ - public Location aboveAt() { - return aboveAt(0); - } - - /** - * negative offset goes towards top of screen
might be off current screen - * - * @param offset pixels - * @return point with given offset vertically to middle point on top edge - */ - public Location aboveAt(int offset) { - return checkAndSetRemote(new Location(x + w / 2, y + offset)); - } - - /** - * create a region above the top side with same width
the new region extends to the top screen border
use - * grow() to include the current region - * - * @return the new region - */ - public Region above() { - int distToAboveScreenBorder = getY() - getScreen().getY(); - return above(distToAboveScreenBorder); - } - - /** - * create a region above the top side with same width and given height
- * negative height creates the top part with height inside the region use grow() to include the current region - * - * @param height pixels - * @return the new region - */ - public Region above(int height) { - int _y; - if (height < 0) { - _y = y; - } else { - _y = y - height; - } - return Region.create(getScreen().getBounds().intersection(new Rectangle(x, _y, w, Math.abs(height))), scr); - } - - /** - * - * @return point middle on bottom edge - */ - public Location belowAt() { - return belowAt(0); - } - - /** - * positive offset goes towards bottom of screen
might be off current screen - * - * @param offset pixels - * @return point with given offset vertically to middle point on bottom edge - */ - public Location belowAt(int offset) { - return checkAndSetRemote(new Location(x + w / 2, y + h - offset)); - } - - /** - * create a region below the bottom side with same width
the new region extends to the bottom screen border
- * use grow() to include the current region - * - * @return the new region - */ - public Region below() { - int distToBelowScreenBorder = getScreen().getY() + getScreen().getH() - (getY() + getH()); - return below(distToBelowScreenBorder); - } - - /** - * create a region below the bottom side with same width and given height
- * negative height creates the bottom part with height inside the region use grow() to include the current region - * - * @param height pixels - * @return the new region - */ - public Region below(int height) { - int _y; - if (height < 0) { - _y = y + h + height; - } else { - _y = y + h; - } - return Region.create(x, _y, w, Math.abs(height), scr); - } - - /** - * create a new region containing both regions - * - * @param ur region to unite with - * @return the new region - */ - public Region union(Region ur) { - Rectangle r = getRect().union(ur.getRect()); - return Region.create(r.x, r.y, r.width, r.height, scr); - } - - /** - * create a region that is the intersection of the given regions - * - * @param ir the region to intersect with like AWT Rectangle API - * @return the new region - */ - public Region intersection(Region ir) { - Rectangle r = getRect().intersection(ir.getRect()); - return Region.create(r.x, r.y, r.width, r.height, scr); - } - - //
- - // - /** - * select the specified part of the region. - * - *
Constants for the top parts of a region (Usage: Region.CONSTANT)
- * shown in brackets: possible shortcuts for the part constant
- * NORTH (NH, TH) - upper half
- * NORTH_WEST (NW, TL) - left third in upper third
- * NORTH_MID (NM, TM) - middle third in upper third
- * NORTH_EAST (NE, TR) - right third in upper third
- * ... similar for the other directions:
- * right side: EAST (Ex, Rx)
- * bottom part: SOUTH (Sx, Bx)
- * left side: WEST (Wx, Lx)
- *
- * specials for quartered:
- * TT top left quarter
- * RR top right quarter
- * BB bottom right quarter
- * LL bottom left quarter
- *
- * specials for the center parts:
- * MID_VERTICAL (MV, CV) half of width vertically centered
- * MID_HORIZONTAL (MH, CH) half of height horizontally centered
- * MID_BIG (M2, C2) half of width / half of height centered
- * MID_THIRD (MM, CC) third of width / third of height centered
- *
- * Based on the scheme behind these constants there is another possible usage:
- * specify part as e 3 digit integer - * where the digits xyz have the following meaning
- * 1st x: use a raster of x rows and x columns
- * 2nd y: the row number of the wanted cell
- * 3rd z: the column number of the wanted cell
- * y and z are counting from 0
- * valid numbers: 200 up to 999 (< 200 are invalid and return the region itself)
- * example: get(522) will use a raster of 5 rows and 5 columns and return the cell in the middle
- * special cases:
- * if either y or z are == or > x: returns the respective row or column
- * example: get(525) will use a raster of 5 rows and 5 columns and return the row in the middle
- *
- * internally this is based on {@link #setRaster(int, int) setRaster} - * and {@link #getCell(int, int) getCell}
- *
- * If you need only one row in one column with x rows or - * only one column in one row with x columns you can use {@link #getRow(int, int) getRow} or {@link #getCol(int, int) getCol} - * @param part the part to get (Region.PART long or short) - * @return new region - */ - public Region get(int part) { - return Region.create(getRectangle(getRect(), part)); - } - - protected static Rectangle getRectangle(Rectangle rect, int part) { - if (part < 200 || part > 999) { - return rect; - } - Region r = Region.create(rect); - int pTyp = (int) (part / 100); - int pPos = part - pTyp * 100; - int pRow = (int) (pPos / 10); - int pCol = pPos - pRow * 10; - r.setRaster(pTyp, pTyp); - if (pTyp == 3) { - // NW = 300, NORTH_WEST = NW; - // NM = 301, NORTH_MID = NM; - // NE = 302, NORTH_EAST = NE; - // EM = 312, EAST_MID = EM; - // SE = 322, SOUTH_EAST = SE; - // SM = 321, SOUTH_MID = SM; - // SW = 320, SOUTH_WEST = SW; - // WM = 310, WEST_MID = WM; - // MM = 311, MIDDLE = MM, M3 = MM; - return r.getCell(pRow, pCol).getRect(); - } - if (pTyp == 2) { - // NH = 202, NORTH = NH; - // EH = 221, EAST = EH; - // SH = 212, SOUTH = SH; - // WH = 220, WEST = WH; - if (pRow > 1) { - return r.getCol(pCol).getRect(); - } else if (pCol > 1) { - return r.getRow(pRow).getRect(); - } - return r.getCell(pRow, pCol).getRect(); - } - if (pTyp == 4) { - // MV = 441, MID_VERTICAL = MV; - // MH = 414, MID_HORIZONTAL = MH; - // M2 = 444, MIDDLE_BIG = M2; - if (pRow > 3) { - if (pCol > 3 ) { - return r.getCell(1, 1).union(r.getCell(2, 2)).getRect(); - } - return r.getCell(0, 1).union(r.getCell(3, 2)).getRect(); - } else if (pCol > 3) { - return r.getCell(1, 0).union(r.getCell(2, 3)).getRect(); - } - return r.getCell(pRow, pCol).getRect(); - } - return rect; - } - - /** - * store info: this region is divided vertically into n even rows
- * a preparation for using getRow() - * - * @param n number of rows - * @return the top row - */ - public Region setRows(int n) { - return setRaster(n, 0); - } - - /** - * store info: this region is divided horizontally into n even columns
- * a preparation for using getCol() - * - * @param n number of columns - * @return the leftmost column - */ - public Region setCols(int n) { - return setRaster(0, n); - } - - /** - * - * @return the number of rows or null - */ - public int getRows() { - return rows; - } - - /** - * - * @return the row height or 0 - */ - public int getRowH() { - return rowH; - } - - /** - * - * @return the number of columns or 0 - */ - public int getCols() { - return cols; - } - - /** - * - * @return the columnwidth or 0 - */ - public int getColW() { - return colW; - } - - /** - * Can be used to check, wether the Region currently has a valid raster - * @return true if it has a valid raster (either getCols or getRows or both would return > 0) - * false otherwise - */ - public boolean isRasterValid() { - return (rows > 0 || cols > 0); - } - - /** - * store info: this region is divided into a raster of even cells
- * a preparation for using getCell()
- * @param r number of rows - * @param c number of columns - * @return the topleft cell - */ - public Region setRaster(int r, int c) { - rows = Math.max(r, h); - cols = Math.max(c, w); - if (r > 0) { - rowH = (int) (h / r); - rowHd = h - r * rowH; - } - if (c > 0) { - colW = (int) (w / c); - colWd = w - c * colW; - } - return getCell(0, 0); - } - - /** - * get the specified row counting from 0, if rows or raster are setup negative counts reverse from the end (last = -1) - * values outside range are 0 or last respectively - * - * @param r row number - * @return the row as new region or the region itself, if no rows are setup - */ - public Region getRow(int r) { - if (rows == 0) { - return this; - } - if (r < 0) { - r = rows + r; - } - r = Math.max(0, r); - r = Math.min(r, rows - 1); - return Region.create(x, y + r * rowH, w, rowH); - } - - public Region getRow(int r, int n) { - return this; - } - - /** - * get the specified column counting from 0, if columns or raster are setup negative counts reverse from the end (last - * = -1) values outside range are 0 or last respectively - * - * @param c column number - * @return the column as new region or the region itself, if no columns are setup - */ - public Region getCol(int c) { - if (cols == 0) { - return this; - } - if (c < 0) { - c = cols + c; - } - c = Math.max(0, c); - c = Math.min(c, cols - 1); - return Region.create(x + c * colW, y, colW, h); - } - - /** - * divide the region in n columns and select column c as new Region - * @param c the column to select counting from 0 or negative to count from the end - * @param n how many columns to devide in - * @return the selected part or the region itself, if parameters are invalid - */ - public Region getCol(int c, int n) { - Region r = new Region(this); - r.setCols(n); - return r.getCol(c); - } - - - /** - * get the specified cell counting from (0, 0), if a raster is setup
- * negative counts reverse from the end (last = -1) values outside range are 0 or last respectively - * - * @param r row number - * @param c column number - * @return the cell as new region or the region itself, if no raster is setup - */ - public Region getCell(int r, int c) { - if (rows == 0) { - return getCol(c); - } - if (cols == 0) { - return getRow(r); - } - if (rows == 0 && cols == 0) { - return this; - } - if (r < 0) { - r = rows - r; - } - if (c < 0) { - c = cols - c; - } - r = Math.max(0, r); - r = Math.min(r, rows - 1); - c = Math.max(0, c); - c = Math.min(c, cols - 1); - return Region.create(x + c * colW, y + r * rowH, colW, rowH); - } -//
- - // - protected void updateSelf() { - if (overlay != null) { - highlight(false, null); - highlight(true, null); - } - } - - protected Region silentHighlight(boolean onOff) { - if (onOff && overlay == null) { - return doHighlight(true, null, true); - } - if (!onOff && overlay != null) { - return doHighlight(true, null, true); - } - return this; - } - - /** - * Toggle the regions Highlight visibility (red frame) - * - * @return the region itself - */ - public Region highlight() { - // Pass true if overlay is null, false otherwise - highlight(overlay == null, null); - return this; - } - - /** - * Toggle the regions Highlight visibility (frame of specified color)
- * allowed color specifications for frame color:
- * - a color name out of: black, blue, cyan, gray, green, magenta, orange, pink, red, white, yellow - * (lowercase and uppercase can be mixed, internally transformed to all uppercase)
- * - these colornames exactly written: lightGray, LIGHT_GRAY, darkGray and DARK_GRAY
- * - a hex value like in HTML: #XXXXXX (max 6 hex digits) - * - an RGB specification as: #rrrgggbbb where rrr, ggg, bbb are integer values in range 0 - 255 - * padded with leading zeros if needed (hence exactly 9 digits) - * @param color Color of frame - * @return the region itself - */ - public Region highlight(String color) { - // Pass true if overlay is null, false otherwise - highlight(overlay == null, color); - return this; - } - - /** - * Sets the regions Highlighting border - * - * @param toEnable set overlay enabled or disabled - * @param color Color of frame (see method highlight(color)) - */ - private Region highlight(boolean toEnable, String color) { - return doHighlight(toEnable, color, false); - } - - private Region doHighlight(boolean toEnable, String color, boolean silent) { - if (isOtherScreen()) { - return this; - } - if (!silent) { - Debug.action("toggle highlight " + toString() + ": " + toEnable + - (color != null ? " color: " + color : "")); - } - if (toEnable) { - overlay = new ScreenHighlighter(getScreen(), color); - overlay.highlight(this); - } else { - if (overlay != null) { - overlay.close(); - overlay = null; - } - } - return this; - } - - - /** - * show the regions Highlight for the given time in seconds (red frame) - * if 0 - use the global Settings.SlowMotionDelay - * - * @param secs time in seconds - * @return the region itself - */ - public Region highlight(float secs) { - return highlight(secs, null); - } - - /** - * show the regions Highlight for the given time in seconds (frame of specified color) - * if 0 - use the global Settings.SlowMotionDelay - * - * @param secs time in seconds - * @param color Color of frame (see method highlight(color)) - * @return the region itself - */ - public Region highlight(float secs, String color) { - if (isOtherScreen()) { - return this; - } - if (secs < 0.1) { - return highlight((int) secs, color); - } - Debug.action("highlight " + toString() + " for " + secs + " secs" + - (color != null ? " color: " + color : "")); - ScreenHighlighter _overlay = new ScreenHighlighter(getScreen(), color); - _overlay.highlight(this, secs); - return this; - } - - /** - * hack to implement the getLastMatch() convenience 0 means same as highlight() < 0 same as highlight(secs) if - * available the last match is highlighted - * - * @param secs seconds - * @return this region - */ - public Region highlight(int secs) { - return highlight(secs, null); - } - - - /** - * Show highlight in selected color - * - * @param secs time in seconds - * @param color Color of frame (see method highlight(color)) - * @return this region - */ - public Region highlight(int secs, String color) { - if (isOtherScreen()) { - return this; - } - if (secs > 0) { - return highlight((float) secs, color); - } - if (lastMatch != null) { - if (secs < 0) { - return lastMatch.highlight((float) -secs, color); - } - return lastMatch.highlight(Settings.DefaultHighlightTime, color); - } - return this; - } - //
- - // - /** - * WARNING: wait(long timeout) is taken by Java Object as final. This method catches any interruptedExceptions - * - * @param timeout The time to wait - */ - public void wait(double timeout) { - try { - Thread.sleep((long) (timeout * 1000L)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - /** - * Returns the image of the given Pattern, String or Image - * - * @param target The Pattern, String or Image - * @return the Image - */ - private Image getImage(PSI target) { - if (target instanceof Pattern) { - return ((Pattern) target).getImage(); - } else if (target instanceof String) { - return Image.get((String) target); - } else if (target instanceof Image) { - return (Image) target; - } else { - return null; - } - } - - /** - * return false to skip
- * return true to try again
- * throw FindFailed to abort - * - * @param target Handles a failed find action - * @throws FindFailed - */ - private boolean handleFindFailed(PSI target) throws FindFailed { - return handleFindFailedShowDialog(target, false); - } - - private boolean handleFindFailedQuietly(PSI target) { - try { - return handleFindFailedShowDialog(target, false); - } catch (FindFailed ex) { - } - return false; - } - - private boolean handleFindFailedImageMissing(PSI target) { - boolean shouldHandle = false; - try { - shouldHandle = handleFindFailedShowDialog(target, true); - } catch (FindFailed ex) { - return false; - } - if (!shouldHandle) { - return false; - } - getRobotForRegion().delay(500); - ScreenImage img = getScreen().userCapture("capture missing image"); - if (img != null) { - String path = ImagePath.getBundlePath(); - if (path == null) { - return false; - } - String imgName = (String) target; - img.getFile(path, imgName); - return true; - } - return false; - } - - private boolean handleFindFailedShowDialog(Object target, boolean shouldCapture) throws FindFailed { - FindFailedResponse response; - if (findFailedResponse == FindFailedResponse.PROMPT) { - FindFailedDialog fd = new FindFailedDialog(target, shouldCapture); - fd.setVisible(true); - response = fd.getResponse(); - fd.dispose(); - wait(0.5); - } else { - response = findFailedResponse; - } - if (response == FindFailedResponse.SKIP) { - return false; - } else if (response == FindFailedResponse.RETRY) { - return true; - } else if (response == FindFailedResponse.ABORT) { - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - throw new FindFailed(String.format("can not find %s in %s", targetStr, this.toStringShort())); - } - return false; - } - - /** - * finds the given Pattern, String or Image in the region and returns the best match. If AutoWaitTimeout - * is set, this is equivalent to wait(). Otherwise only one search attempt will be done. - * - * @param Pattern, String or Image - * @param target A search criteria - * @return If found, the element. null otherwise - * @throws FindFailed if the Find operation failed - */ - public Match find(PSI target) throws FindFailed { - if (autoWaitTimeout > 0) { - return wait(target, autoWaitTimeout); - } - lastMatch = null; - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - while (true) { - try { - log(3, "find: waiting 0 secs for %s to appear in %s", targetStr, this.toStringShort()); - lastMatch = doFind(target, null); - } catch (IOException ex) { - if (ex instanceof IOException) { - if (handleFindFailedImageMissing(target)) { - continue; - } - } - throw new FindFailed(ex.getMessage()); - } - if (lastMatch != null) { - Image img = getImage(target); - lastMatch.setImage(img); - if (img != null) { - img.setLastSeen(lastMatch.getRect(), lastMatch.getScore()); - } - log(lvl, "find: %s has appeared \nat %s", targetStr, lastMatch); - return lastMatch; - } - log(3, "find: %s has not appeared [%d msec]", targetStr, lastFindTime); - if (!handleFindFailed(target)) { - return null; - } - } - } - - /** - * finds all occurences of the given Pattern, String or Image in the region and returns an Iterator of Matches. - * - * - * @param Pattern, String or Image - * @param target A search criteria - * @return All elements matching - * @throws FindFailed if the Find operation failed - */ - public Iterator findAll(PSI target) throws FindFailed { - lastMatches = null; - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - while (true) { - try { - if (autoWaitTimeout > 0) { - RepeatableFindAll rf = new RepeatableFindAll(target); - rf.repeat(autoWaitTimeout); - lastMatches = rf.getMatches(); - } else { - lastMatches = doFindAll(target, null); - } - } catch (Exception ex) { - if (ex instanceof IOException) { - if (handleFindFailedImageMissing(target)) { - continue; - } - } - throw new FindFailed(ex.getMessage()); - } - if (lastMatches != null) { - return lastMatches; - } - if (!handleFindFailed(target)) { - return null; - } - } - } - - public Match[] findAllByRow(PSI target) { - Match[] matches = new Match[0]; - List mList = findAllCollect(target); - if (mList.isEmpty()) { - return null; - } - Collections.sort(mList, new Comparator() { - @Override - public int compare(Match m1, Match m2) { - if (m1.y == m2.y) { - return m1.x - m2.x; - } - return m1.y - m2.y; - } - }); - return mList.toArray(matches); - } - - public Match[] findAllByColumn(PSI target) { - Match[] matches = new Match[0]; - List mList = findAllCollect(target); - if (mList.isEmpty()) { - return null; - } - Collections.sort(mList, new Comparator() { - @Override - public int compare(Match m1, Match m2) { - if (m1.x == m2.x) { - return m1.y - m2.y; - } - return m1.x - m2.x; - } - }); - return mList.toArray(matches); - } - - private List findAllCollect(PSI target) { - Iterator mIter = null; - try { - mIter = findAll(target); - } catch (Exception ex) { - Debug.error("findAllByRow: %s", ex.getMessage()); - return null; - } - List mList = new ArrayList(); - while (mIter.hasNext()) { - mList.add(mIter.next()); - } - return mList; - } - - public Match findBest(Object... args) { - Debug.log(lvl, "findBest: enter"); - Match mResult = null; - List mList = findAnyCollect(args); - if (mList != null) { - Collections.sort(mList, new Comparator() { - @Override - public int compare(Match m1, Match m2) { - double ms = m2.getScore() - m1.getScore(); - if (ms < 0) { - return -1; - } else if (ms > 0) { - return 1; - } - return 0; - } - }); - mResult = mList.get(0); - } - return mResult; - } - - private List findAnyCollect(Object... args) { - if (args == null) return null; - List mList = new ArrayList(); - Match[] mArray = new Match[args.length]; - SubFindRun[] theSubs = new SubFindRun[args.length]; - int nobj = 0; - ScreenImage base = getScreen().capture(this); - for (Object obj : args) { - mArray[nobj] = null; - if (obj instanceof Pattern || obj instanceof String || obj instanceof Image) { - theSubs[nobj] = new SubFindRun(mArray, nobj, base, obj, this); - new Thread(theSubs[nobj]).start(); - } - nobj++; - } - Debug.log(lvl, "findAnyCollect: waiting for SubFindRuns"); - nobj = 0; - boolean all = false; - while (!all) { - all = true; - for (SubFindRun sub : theSubs) { - all &= sub.hasFinished(); - } - } - Debug.log(lvl, "findAnyCollect: SubFindRuns finished"); - nobj = 0; - for (Match match : mArray) { - if (match != null) { - match.setIndex(nobj); - mList.add(match); - } else { - } - nobj++; - } - return mList; - } - - private class SubFindRun implements Runnable { - - Match[] mArray; - ScreenImage base; - Object target; - Region reg; - boolean finished = false; - int subN; - - public SubFindRun(Match[] pMArray, int pSubN, - ScreenImage pBase, Object pTarget, Region pReg) { - subN = pSubN; - base = pBase; - target = pTarget; - reg = pReg; - mArray = pMArray; - } - - @Override - public void run() { - try { - mArray[subN] = reg.findInImage(base, target); - } catch (Exception ex) { - log(-1, "findAnyCollect: image file not found:\n", target); - } - hasFinished(true); - } - - public boolean hasFinished() { - return hasFinished(false); - } - - public synchronized boolean hasFinished(boolean state) { - if (state) { - finished = true; - } - return finished; - } - } - - private Match findInImage(ScreenImage base, Object target) throws IOException { - Finder finder = null; - Match match = null; - boolean findingText = false; - Image img = null; - if (target instanceof String) { - if (((String) target).startsWith("\t") && ((String) target).endsWith("\t")) { - findingText = true; - } else { - img = Image.create((String) target); - if (img.isValid()) { - finder = doCheckLastSeenAndCreateFinder(base, img, 0.0, null); - if (!finder.hasNext()) { - runFinder(finder, img); - } - } else if (img.isText()) { - findingText = true; - } else { - throw new IOException("Region: findInImage: Image not loadable: " + target.toString()); - } - } - if (findingText) { - if (TextRecognizer.getInstance() != null) { - log(lvl, "findInImage: Switching to TextSearch"); - finder = new Finder(getScreen().capture(x, y, w, h), this); - finder.findText((String) target); - } - } - } else if (target instanceof Pattern) { - if (((Pattern) target).isValid()) { - img = ((Pattern) target).getImage(); - finder = doCheckLastSeenAndCreateFinder(base, img, 0.0, (Pattern) target); - if (!finder.hasNext()) { - runFinder(finder, target); - } - } else { - throw new IOException("Region: findInImage: Image not loadable: " + target.toString()); - } - } else if (target instanceof Image) { - if (((Image) target).isValid()) { - img = ((Image) target); - finder = doCheckLastSeenAndCreateFinder(base, img, 0.0, null); - if (!finder.hasNext()) { - runFinder(finder, img); - } - } else { - throw new IOException("Region: findInImage: Image not loadable: " + target.toString()); - } - } else { - log(-1, "findInImage: invalid parameter: %s", target); - return null; - } - if (finder.hasNext()) { - match = finder.next(); - match.setImage(img); - img.setLastSeen(match.getRect(), match.getScore()); - } - return match; - } - - /** - * Waits for the Pattern, String or Image to appear until the AutoWaitTimeout value is exceeded. - * - * @param Pattern, String or Image - * @param target The target to search for - * @return The found Match - * @throws FindFailed if the Find operation finally failed - */ - public Match wait(PSI target) throws FindFailed { - if (target instanceof Float || target instanceof Double) { - wait(0.0 + ((Double) target)); - return null; - } - return wait(target, autoWaitTimeout); - } - - /** - * Waits for the Pattern, String or Image to appear or timeout (in second) is passed - * - * @param Pattern, String or Image - * @param target The target to search for - * @param timeout Timeout in seconds - * @return The found Match - * @throws FindFailed if the Find operation finally failed - */ - public Match wait(PSI target, double timeout) throws FindFailed { - RepeatableFind rf; - lastMatch = null; - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - while (true) { - try { - log(3, "find: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort()); - rf = new RepeatableFind(target); - rf.repeat(timeout); - lastMatch = rf.getMatch(); - } catch (Exception ex) { - if (ex instanceof IOException) { - if (handleFindFailedImageMissing(target)) { - continue; - } - } - throw new FindFailed(ex.getMessage()); - } - if (lastMatch != null) { - lastMatch.setImage(rf._image); - if (rf._image != null) { - rf._image.setLastSeen(lastMatch.getRect(), lastMatch.getScore()); - } - log(lvl, "find: %s has appeared \nat %s", targetStr, lastMatch); - break; - } - log(3, "find: %s has not appeared [%d msec]", targetStr, lastFindTime); - if (!handleFindFailed(target)) { - return null; - } - } - return lastMatch; - } - -//TODO 1.2.0 Region.compare as time optimized Region.exists - /** - * time optimized Region.exists, when image-size == region-size
- * 1.1.x: just using exists(img, 0), sizes not checked - * @param img image file name - * @return the match or null if not equal - */ - public Match compare(String img) { - return compare(Image.create(img)); - } - - /** - * time optimized Region.exists, when image-size == region-size
- * 1.1.x: just using exists(img, 0), sizes not checked - * @param img Image object - * @return the match or null if not equal - */ - public Match compare(Image img) { - return exists(img, 0); - } - - /** - * Check if target exists (with the default autoWaitTimeout) - * - * @param Pattern, String or Image - * @param target Pattern, String or Image - * @return the match (null if not found or image file missing) - */ - public Match exists(PSI target) { - return exists(target, autoWaitTimeout); - } - - /** - * Check if target exists with a specified timeout
- * timout = 0: returns immediately after first search - * - * @param Pattern, String or Image - * @param target The target to search for - * @param timeout Timeout in seconds - * @return the match (null if not found or image file missing) - */ - public Match exists(PSI target, double timeout) { - lastMatch = null; - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - while (true) { - try { - log(3, "exists: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort()); - RepeatableFind rf = new RepeatableFind(target); - if (rf.repeat(timeout)) { - lastMatch = rf.getMatch(); - Image img = rf._image; - lastMatch.setImage(img); - if (img != null) { - img.setLastSeen(lastMatch.getRect(), lastMatch.getScore()); - } - log(lvl, "exists: %s has appeared \nat %s", targetStr, lastMatch); - return lastMatch; - } else { - if (!handleFindFailedQuietly(target)) { - break; - } - } - } catch (Exception ex) { - if (ex instanceof IOException) { - if (!handleFindFailedImageMissing(target)) { - break; - } - } - } - } - log(3, "exists: %s has not appeared [%d msec]", targetStr, lastFindTime); - return null; - } - - /** - * Use findText() instead of find() in cases where the given string could be misinterpreted as an image filename - * - * @param text text - * @param timeout time - * @return the matched region containing the text - * @throws org.sikuli.script.FindFailed if not found - */ - public Match findText(String text, double timeout) throws FindFailed { - // the leading/trailing tab is used to internally switch to text search directly - return wait("\t" + text + "\t", timeout); - } - - /** - * Use findText() instead of find() in cases where the given string could be misinterpreted as an image filename - * - * @param text text - * @return the matched region containing the text - * @throws org.sikuli.script.FindFailed if not found - */ - public Match findText(String text) throws FindFailed { - return findText(text, autoWaitTimeout); - } - - /** - * Use findAllText() instead of findAll() in cases where the given string could be misinterpreted as an image filename - * - * @param text text - * @return the matched region containing the text - * @throws org.sikuli.script.FindFailed if not found - */ - public Iterator findAllText(String text) throws FindFailed { - // the leading/trailing tab is used to internally switch to text search directly - return findAll("\t" + text + "\t"); - } - - /** - * waits until target vanishes or timeout (in seconds) is - * passed (AutoWaitTimeout) - * - * @param Pattern, String or Image - * @param target The target to wait for it to vanish - * @return true if the target vanishes, otherwise returns false. - */ - public boolean waitVanish(PSI target) { - return waitVanish(target, autoWaitTimeout); - } - - /** - * waits until target vanishes or timeout (in seconds) is - * passed - * - * @param Pattern, String or Image - * @param target Pattern, String or Image - * @param timeout time in seconds - * @return true if target vanishes, false otherwise and if imagefile is missing. - */ - public boolean waitVanish(PSI target, double timeout) { - while (true) { - try { - log(lvl, "waiting for " + target + " to vanish"); - RepeatableVanish r = new RepeatableVanish(target); - if (r.repeat(timeout)) { - log(lvl, "" + target + " has vanished"); - return true; - } - log(lvl, "" + target + " has not vanished before timeout"); - return false; - } catch (Exception ex) { - if (ex instanceof IOException) { - if (handleFindFailedImageMissing(target)) { - continue; - } - } - break; - } - } - return false; - } - //
- - // - /** - * Match doFind( Pattern/String/Image ) finds the given pattern on the screen and returns the best match without - * waiting. - */ - private Match doFind(PSI ptn, RepeatableFind repeating) throws IOException { - Finder f = null; - Match m = null; - IScreen s = null; - boolean findingText = false; - lastFindTime = (new Date()).getTime(); - ScreenImage simg; - double findTimeout = autoWaitTimeout; - if (repeating != null) { - findTimeout = repeating.getFindTimeOut(); - } - if (repeating != null && repeating._finder != null) { - simg = getScreen().capture(this); - f = repeating._finder; - f.setScreenImage(simg); - f.setRepeating(); - if (Settings.FindProfiling) { - Debug.logp("[FindProfiling] Region.doFind repeat: %d msec", - new Date().getTime() - lastSearchTimeRepeat); - } - lastSearchTime = (new Date()).getTime(); - f.findRepeat(); - } else { - s = getScreen(); - Image img = null; - if (ptn instanceof String) { - if (((String) ptn).startsWith("\t") && ((String) ptn).endsWith("\t")) { - findingText = true; - } else { - img = Image.create((String) ptn); - if (img.isValid()) { - lastSearchTime = (new Date()).getTime(); - f = checkLastSeenAndCreateFinder(img, findTimeout, null); - if (!f.hasNext()) { - runFinder(f, img); - //f.find(img); - } - } else if (img.isText()) { - findingText = true; - } else { - throw new IOException("Region: doFind: Image not loadable: " + ptn.toString()); - } - } - if (findingText) { - if (TextRecognizer.getInstance() != null) { - log(lvl, "doFind: Switching to TextSearch"); - f = new Finder(getScreen().capture(x, y, w, h), this); - lastSearchTime = (new Date()).getTime(); - f.findText((String) ptn); - } - } - } else if (ptn instanceof Pattern) { - if (((Pattern) ptn).isValid()) { - img = ((Pattern) ptn).getImage(); - lastSearchTime = (new Date()).getTime(); - f = checkLastSeenAndCreateFinder(img, findTimeout, (Pattern) ptn); - if (!f.hasNext()) { - runFinder(f, ptn); - //f.find((Pattern) ptn); - } - } else { - throw new IOException("Region: doFind: Image not loadable: " + ptn.toString()); - } - } else if (ptn instanceof Image) { - if (((Image) ptn).isValid()) { - img = ((Image) ptn); - lastSearchTime = (new Date()).getTime(); - f = checkLastSeenAndCreateFinder(img, findTimeout, null); - if (!f.hasNext()) { - runFinder(f, img); - //f.find(img); - } - } else { - throw new IOException("Region: doFind: Image not loadable: " + ptn.toString()); - } - } else { - log(-1, "doFind: invalid parameter: %s", ptn); - Sikulix.terminate(999); - } - if (repeating != null) { - repeating._finder = f; - repeating._image = img; - } - } - lastSearchTimeRepeat = lastSearchTime; - lastSearchTime = (new Date()).getTime() - lastSearchTime; - lastFindTime = (new Date()).getTime() - lastFindTime; - if (f.hasNext()) { - m = f.next(); - m.setTimes(lastFindTime, lastSearchTime); - if (Settings.FindProfiling) { - Debug.logp("[FindProfiling] Region.doFind final: %d msec", lastSearchTime); - } - } - return m; - } - - private void runFinder(Finder f, Object target) { - if (Debug.shouldHighlight()) { - if (this.scr.getW() > w + 20 && this.scr.getH() > h + 20) - highlight(2, "#000255000"); - } - if (target instanceof Image) { - f.find((Image) target); - } else if (target instanceof Pattern) { - f.find((Pattern) target); - } - } - - private Finder checkLastSeenAndCreateFinder(Image img, double findTimeout, Pattern ptn) { - return doCheckLastSeenAndCreateFinder(null, img, findTimeout, ptn); - } - - private Finder doCheckLastSeenAndCreateFinder(ScreenImage base, Image img, double findTimeout, Pattern ptn) { - if (base == null) { - base = getScreen().capture(this); - } - if (!Settings.UseImageFinder && Settings.CheckLastSeen && null != img.getLastSeen()) { - Region r = Region.create(img.getLastSeen()); - float score = (float) (img.getLastSeenScore() - 0.01); - if (this.contains(r)) { - Finder f = null; - if (this.scr instanceof VNCScreen) { - f = new Finder(new VNCScreen().capture(r), r); - } else { - f = new Finder(base.getSub(r.getRect()), r); - if (Debug.shouldHighlight()) { - if (this.scr.getW() > w + 10 && this.scr.getH() > h + 10) - highlight(2, "#000255000"); - } - } - if (ptn == null) { - f.find(new Pattern(img).similar(score)); - } else { - f.find(new Pattern(ptn).similar(score)); - } - if (f.hasNext()) { - log(lvl, "checkLastSeen: still there"); - return f; - } - log(lvl, "checkLastSeen: not there"); - } - } - if (Settings.UseImageFinder) { - ImageFinder f = new ImageFinder(this); - f.setFindTimeout(findTimeout); - return f; - } else { - return new Finder(base, this); - } - } - - public void saveLastScreenImage() { - ScreenImage simg = getScreen().getLastScreenImageFromScreen(); - if (simg != null) { - simg.saveLastScreenImage(runTime.fSikulixStore); - } - } - - - /** - * Match findAllNow( Pattern/String/Image ) finds all the given pattern on the screen and returns the best matches - * without waiting. - */ - private Iterator doFindAll(PSI ptn, RepeatableFindAll repeating) throws IOException { - boolean findingText = false; - Finder f; - ScreenImage simg = getScreen().capture(x, y, w, h); - if (repeating != null && repeating._finder != null) { - f = repeating._finder; - f.setScreenImage(simg); - f.setRepeating(); - f.findAllRepeat(); - } else { - f = new Finder(simg, this); - Image img = null; - if (ptn instanceof String) { - if (((String) ptn).startsWith("\t") && ((String) ptn).endsWith("\t")) { - findingText = true; - } else { - img = Image.create((String) ptn); - if (img.isValid()) { - f.findAll(img); - } else if (img.isText()) { - findingText = true; - } else { - throw new IOException("Region: doFind: Image not loadable: " + (String) ptn); - } - } - if (findingText) { - if (TextRecognizer.getInstance() != null) { - log(lvl, "doFindAll: Switching to TextSearch"); - f.findAllText((String) ptn); - } - } - } else if (ptn instanceof Pattern) { - if (((Pattern) ptn).isValid()) { - img = ((Pattern) ptn).getImage(); - f.findAll((Pattern) ptn); - } else { - throw new IOException("Region: doFind: Image not loadable: " + (String) ptn); - } - } else if (ptn instanceof Image) { - if (((Image) ptn).isValid()) { - img = ((Image) ptn); - f.findAll((Image) ptn); - } else { - throw new IOException("Region: doFind: Image not loadable: " + (String) ptn); - } - } else { - log(-1, "doFind: invalid parameter: %s", ptn); - Sikulix.terminate(999); - } - if (repeating != null) { - repeating._finder = f; - repeating._image = img; - } - } - if (f.hasNext()) { - return f; - } - return null; - } - - // Repeatable Find //////////////////////////////// - private abstract class Repeatable { - - private double findTimeout; - - abstract void run() throws Exception; - - abstract boolean ifSuccessful(); - - double getFindTimeOut() { - return findTimeout; - } - - // return TRUE if successful before timeout - // return FALSE if otherwise - // throws Exception if any unexpected error occurs - boolean repeat(double timeout) throws Exception { - findTimeout = timeout; - int MaxTimePerScan = (int) (1000.0 / waitScanRate); - int timeoutMilli = (int) (timeout * 1000); - long begin_t = (new Date()).getTime(); - do { - long before_find = (new Date()).getTime(); - run(); - if (ifSuccessful()) { - return true; - } else if (timeoutMilli < MaxTimePerScan || Settings.UseImageFinder) { - // instant return on first search failed if timeout very small or 0 - // or when using new ImageFinder - return false; - } - long after_find = (new Date()).getTime(); - if (after_find - before_find < MaxTimePerScan) { - getRobotForRegion().delay((int) (MaxTimePerScan - (after_find - before_find))); - } else { - getRobotForRegion().delay(10); - } - } while (begin_t + timeout * 1000 > (new Date()).getTime()); - return false; - } - } - - private class RepeatableFind extends Repeatable { - - Object _target; - Match _match = null; - Finder _finder = null; - Image _image = null; - - public RepeatableFind(PSI target) { - _target = target; - } - - public Match getMatch() { - if (_finder != null) { - _finder.destroy(); - } - return (_match == null) ? _match : new Match(_match); - } - - @Override - public void run() throws IOException { - _match = doFind(_target, this); - } - - @Override - boolean ifSuccessful() { - return _match != null; - } - } - - private class RepeatableVanish extends RepeatableFind { - - public RepeatableVanish(PSI target) { - super(target); - } - - @Override - boolean ifSuccessful() { - return _match == null; - } - } - - private class RepeatableFindAll extends Repeatable { - - Object _target; - Iterator _matches = null; - Finder _finder = null; - Image _image = null; - - public RepeatableFindAll(PSI target) { - _target = target; - } - - public Iterator getMatches() { - return _matches; - } - - @Override - public void run() throws IOException { - _matches = doFindAll(_target, this); - } - - @Override - boolean ifSuccessful() { - return _matches != null; - } - } - // - - // -// private Region getRegionFromTarget(PatternStringRegionMatch target) throws FindFailed { -// if (target instanceof Pattern || target instanceof String || target instanceof Image) { -// Match m = find(target); -// if (m != null) { -// return m.setScreen(scr); -// } -// return null; -// } -// if (target instanceof Region) { -// return ((Region) target).setScreen(scr); -// } -// return null; -// } - - private Location getLocationFromTarget(PSIMRL target) throws FindFailed { - if (target instanceof Pattern || target instanceof String || target instanceof Image) { - Match m = find(target); - if (m != null) { - if (isOtherScreen()) { - return m.getTarget().setOtherScreen(scr); - } else { - return m.getTarget(); - } - } - return null; - } - if (target instanceof Match) { - return ((Match) target).getTarget(); - } - if (target instanceof Region) { - return ((Region) target).getCenter(); - } - if (target instanceof Location) { - return new Location((Location) target); - } - return null; - } - // - - // - - protected Observer getObserver() { - if (regionObserver == null) { - regionObserver = new Observer(this); - } - return regionObserver; - } - - /** - * evaluate if at least one event observer is defined for this region (the observer need not be running) - * @return true, if the region has an observer with event observers - */ - public boolean hasObserver() { - if (regionObserver != null) { - return regionObserver.hasObservers(); - } - return false; - } - - /** - * - * @return true if an observer is running for this region - */ - public boolean isObserving() { - return observing; - } - - /** - * - * @return true if any events have happened for this region, false otherwise - */ - public boolean hasEvents() { - return Observing.hasEvents(this); - } - - /** - * the region's events are removed from the list - * @return the region's happened events as array if any (size might be 0) - */ - public ObserveEvent[] getEvents() { - return Observing.getEvents(this); - } - - /** - * the event is removed from the list - * @param name event's name - * @return the named event if happened otherwise null - */ - public ObserveEvent getEvent(String name) { - return Observing.getEvent(name); - } - - /** - * set the observer with the given name inactive (not checked while observing) - * @param name observers name - */ - public void setInactive(String name) { - if (!hasObserver()) { - return; - } - Observing.setActive(name, false); - } - - /** - * set the observer with the given name active (not checked while observing) - * @param name observers name - */ - public void setActive(String name) { - if (!hasObserver()) { - return; - } - Observing.setActive(name, true); - } - - /** - * a subsequently started observer in this region should wait for target - * and notify the given observer about this event
- * for details about the observe event handler: {@link ObserverCallBack}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
- * @param Pattern, String or Image - * @param target Pattern, String or Image - * @param observer ObserverCallBack - * @return the event's name - */ - public String onAppear(PSI target, Object observer) { - return onEvent(target, observer, ObserveEvent.Type.APPEAR); - } - - /** - * a subsequently started observer in this region should wait for target - * success and details about the event can be obtained using @{link Observing}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
- * @param Pattern, String or Image - * @param target Pattern, String or Image - * @return the event's name - */ - public String onAppear(PSI target) { - return onEvent(target, null, ObserveEvent.Type.APPEAR); - } - - private String onEvent(PSIC targetThreshhold, Object observer, ObserveEvent.Type obsType) { - if (observer != null && (observer.getClass().getName().contains("org.python") || - observer.getClass().getName().contains("org.jruby"))) { - observer = new ObserverCallBack(observer, obsType); - } - String name = Observing.add(this, (ObserverCallBack) observer, obsType, targetThreshhold); - log(lvl, "%s: observer %s %s: %s with: %s", toStringShort(), obsType, - (observer == null ? "" : " with callback"), name, targetThreshhold); - return name; - } - - /** - * a subsequently started observer in this region should wait for the target to vanish - * and notify the given observer about this event
- * for details about the observe event handler: {@link ObserverCallBack}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
- * @param Pattern, String or Image - * @param target Pattern, String or Image - * @param observer ObserverCallBack - * @return the event's name - */ - public String onVanish(PSI target, Object observer) { - return onEvent(target, observer, ObserveEvent.Type.VANISH); - } - - /** - * a subsequently started observer in this region should wait for the target to vanish - * success and details about the event can be obtained using @{link Observing}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
- * @param Pattern, String or Image - * @param target Pattern, String or Image - * @return the event's name - */ - public String onVanish(PSI target) { - return onEvent(target, null, ObserveEvent.Type.VANISH); - } - - /** - * a subsequently started observer in this region should wait for changes in the region - * and notify the given observer about this event - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param threshold minimum size of changes (rectangle threshhold x threshold) - * @param observer ObserverCallBack - * @return the event's name - */ - public String onChange(int threshold, Object observer) { - return onEvent( (threshold > 0 ? threshold : Settings.ObserveMinChangedPixels), - observer, ObserveEvent.Type.CHANGE); - } - - /** - * a subsequently started observer in this region should wait for changes in the region - * success and details about the event can be obtained using @{link Observing}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param threshold minimum size of changes (rectangle threshhold x threshold) - * @return the event's name - */ - public String onChange(int threshold) { - return onEvent( (threshold > 0 ? threshold : Settings.ObserveMinChangedPixels), - null, ObserveEvent.Type.CHANGE); - } - - /** - * a subsequently started observer in this region should wait for changes in the region - * and notify the given observer about this event
- * minimum size of changes used: Settings.ObserveMinChangedPixels - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param observer ObserverCallBack - * @return the event's name - */ - public String onChange(Object observer) { - return onEvent(Settings.ObserveMinChangedPixels, observer, ObserveEvent.Type.CHANGE); - } - - /** - * a subsequently started observer in this region should wait for changes in the region - * success and details about the event can be obtained using @{link Observing}
- * minimum size of changes used: Settings.ObserveMinChangedPixels - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @return the event's name - */ - public String onChange() { - return onEvent(Settings.ObserveMinChangedPixels, null, ObserveEvent.Type.CHANGE); - } - -// -// /** -// *INTERNAL USE ONLY: for use with scripting API bridges -// * @param Pattern, String or Image -// * @param target Pattern, String or Image -// * @param observer ObserverCallBack -// * @return the event's name -// */ -// public String onAppearJ(PSI target, Object observer) { -// return onEvent(target, observer, ObserveEvent.Type.APPEAR); -// } -// -// /** -// *INTERNAL USE ONLY: for use with scripting API bridges -// * @param Pattern, String or Image -// * @param target Pattern, String or Image -// * @param observer ObserverCallBack -// * @return the event's name -// */ -// public String onVanishJ(PSI target, Object observer) { -// return onEvent(target, observer, ObserveEvent.Type.VANISH); -// } -// -// /** -// *INTERNAL USE ONLY: for use with scripting API bridges -// * @param threshold min pixel size - 0 = ObserveMinChangedPixels -// * @param observer ObserverCallBack -// * @return the event's name -// */ -// public String onChangeJ(int threshold, Object observer) { -// return onEvent( (threshold > 0 ? threshold : Settings.ObserveMinChangedPixels), -// observer, ObserveEvent.Type.CHANGE); -// } -// -// - - public String onChangeDo(int threshold, Object observer) { - String name = Observing.add(this, (ObserverCallBack) observer, ObserveEvent.Type.CHANGE, threshold); - log(lvl, "%s: onChange%s: %s minSize: %d", toStringShort(), - (observer == null ? "" : " with callback"), name, threshold); - return name; - } - - /** - * start an observer in this region that runs forever (use stopObserving() in handler) - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @return false if not possible, true if events have happened - */ - public boolean observe() { - return observe(Float.POSITIVE_INFINITY); - } - - /** - * start an observer in this region for the given time - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param secs time in seconds the observer should run - * @return false if not possible, true if events have happened - */ - public boolean observe(double secs) { - return observeDo(secs); - } - - /** - *INTERNAL USE ONLY: for use with scripting API bridges - * @param secs time in seconds the observer should run - * @param bg run in background true/false - * @return false if not possible, true if events have happened - */ - public boolean observeJ(double secs, boolean bg) { - if (bg) { - return observeInBackground(secs); - } else { - return observeDo(secs); - } - } - - private boolean observeDo(double secs) { - if (regionObserver == null) { - Debug.error("Region: observe: Nothing to observe (Region might be invalid): " + this.toStringShort()); - return false; - } - if (observing) { - Debug.error("Region: observe: already running for this region. Only one allowed!"); - return false; - } - log(lvl, "observe: starting in " + this.toStringShort() + " for " + secs + " seconds"); - int MaxTimePerScan = (int) (1000.0 / observeScanRate); - long begin_t = (new Date()).getTime(); - long stop_t; - if (secs > Long.MAX_VALUE) { - stop_t = Long.MAX_VALUE; - } else { - stop_t = begin_t + (long) (secs * 1000); - } - regionObserver.initialize(); - observing = true; - Observing.addRunningObserver(this); - while (observing && stop_t > (new Date()).getTime()) { - long before_find = (new Date()).getTime(); - ScreenImage simg = getScreen().capture(x, y, w, h); - if (!regionObserver.update(simg)) { - observing = false; - break; - } - if (!observing) { - break; - } - long after_find = (new Date()).getTime(); - try { - if (after_find - before_find < MaxTimePerScan) { - Thread.sleep((int) (MaxTimePerScan - (after_find - before_find))); - } - } catch (Exception e) { - } - } - boolean observeSuccess = false; - if (observing) { - observing = false; - log(lvl, "observe: stopped due to timeout in " - + this.toStringShort() + " for " + secs + " seconds"); - } else { - log(lvl, "observe: ended successfully: " + this.toStringShort()); - observeSuccess = Observing.hasEvents(this); - } - return observeSuccess; - } - - /** - * start an observer in this region for the given time that runs in background - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param secs time in seconds the observer should run - * @return false if not possible, true otherwise - */ - public boolean observeInBackground(double secs) { - if (observing) { - Debug.error("Region: observeInBackground: already running for this region. Only one allowed!"); - return false; - } - log(lvl, "entering observeInBackground for %f secs", secs); - Thread observeThread = new Thread(new ObserverThread(secs)); - observeThread.start(); - log(lvl, "observeInBackground now running"); - return true; - } - - private class ObserverThread implements Runnable { - private double time; - - ObserverThread(double time) { - this.time = time; - } - - @Override - public void run() { - observe(time); - } - } - - /** - * stops a running observer - */ - public void stopObserver() { - log(lvl, "observe: request to stop observer for " + this.toStringShort()); - observing = false; - } - - /** - * stops a running observer printing an info message - * @param message text - */ - public void stopObserver(String message) { - Debug.info(message); - stopObserver(); - } - //
- - // - public Location checkMatch() { - if (lastMatch != null) { - return lastMatch.getTarget(); - } - return getTarget(); - } - - /** - * move the mouse pointer to region's last successful match
use center if no lastMatch
- * if region is a match: move to targetOffset
same as mouseMove - * - * @return 1 if possible, 0 otherwise - */ - public int hover() { - try { // needed to cut throw chain for FindFailed - return hover(checkMatch()); - } catch (FindFailed ex) { - } - return 0; - } - - /** - * move the mouse pointer to the given target location
same as mouseMove
Pattern or Filename - do a find - * before and use the match
Region - position at center
Match - position at match's targetOffset
Location - * - position at that point
- * - * @param to search: Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int hover(PFRML target) throws FindFailed { - log(lvl, "hover: " + target); - return mouseMove(target); - } - - /** - * left click at the region's last successful match
use center if no lastMatch
if region is a match: click - * targetOffset - * - * @return 1 if possible, 0 otherwise - */ - public int click() { - try { // needed to cut throw chain for FindFailed - return click(checkMatch(), 0); - } catch (FindFailed ex) { - return 0; - } - } - - /** - * left click at the given target location
Pattern or Filename - do a find before and use the match
Region - - * position at center
Match - position at match's targetOffset
- * Location - position at that point
- * - * @param to search: Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int click(PFRML target) throws FindFailed { - return click(target, 0); - } - - /** - * left click at the given target location
holding down the given modifier keys
- * Pattern or Filename - do a find before and use the match
Region - position at center
- * Match - position at match's targetOffset
Location - position at that point
- * - * @param to search: Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param modifiers the value of the resulting bitmask (see KeyModifier) - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int click(PFRML target, Integer modifiers) throws FindFailed { - Location loc = getLocationFromTarget(target); - int ret = Mouse.click(loc, InputEvent.BUTTON1_MASK, modifiers, false, this); - - //TODO SikuliActionManager.getInstance().clickTarget(this, target, _lastScreenImage, _lastMatch); - return ret; - } - - /** - * double click at the region's last successful match
use center if no lastMatch
if region is a match: click - * targetOffset - * - * @return 1 if possible, 0 otherwise - */ - public int doubleClick() { - try { // needed to cut throw chain for FindFailed - return doubleClick(checkMatch(), 0); - } catch (FindFailed ex) { - return 0; - } - } - - /** - * double click at the given target location
Pattern or Filename - do a find before and use the match
Region - - * position at center
Match - position at match's targetOffset
- * Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int doubleClick(PFRML target) throws FindFailed { - return doubleClick(target, 0); - } - - /** - * double click at the given target location
holding down the given modifier keys
- * Pattern or Filename - do a find before and use the match
Region - position at center
Match - position at - * match's targetOffset
Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param modifiers the value of the resulting bitmask (see KeyModifier) - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int doubleClick(PFRML target, Integer modifiers) throws FindFailed { - Location loc = getLocationFromTarget(target); - int ret = Mouse.click(loc, InputEvent.BUTTON1_MASK, modifiers, true, this); - - //TODO SikuliActionManager.getInstance().doubleClickTarget(this, target, _lastScreenImage, _lastMatch); - return ret; - } - - /** - * right click at the region's last successful match
use center if no lastMatch
if region is a match: click - * targetOffset - * - * @return 1 if possible, 0 otherwise - */ - public int rightClick() { - try { // needed to cut throw chain for FindFailed - return rightClick(checkMatch(), 0); - } catch (FindFailed ex) { - return 0; - } - } - - /** - * right click at the given target location
Pattern or Filename - do a find before and use the match
Region - - * position at center
Match - position at match's targetOffset
Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int rightClick(PFRML target) throws FindFailed { - return rightClick(target, 0); - } - - /** - * right click at the given target location
holding down the given modifier keys
- * Pattern or Filename - do a find before and use the match
Region - position at center
Match - position at - * match's targetOffset
Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param modifiers the value of the resulting bitmask (see KeyModifier) - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int rightClick(PFRML target, Integer modifiers) throws FindFailed { - Location loc = getLocationFromTarget(target); - int ret = Mouse.click(loc, InputEvent.BUTTON3_MASK, modifiers, false, this); - - //TODO SikuliActionManager.getInstance().rightClickTarget(this, target, _lastScreenImage, _lastMatch); - return ret; - } - - /** - * time in milliseconds to delay between button down/up at next click only (max 1000) - * - * @param millisecs value - */ - public void delayClick(int millisecs) { - Settings.ClickDelay = millisecs; - } - //
- - // - /** - * Drag from region's last match and drop at given target
applying Settings.DelayAfterDrag and DelayBeforeDrop - *
using left mouse button - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed if the Find operation failed - */ - public int dragDrop(PFRML target) throws FindFailed { - return dragDrop(lastMatch, target); - } - - /** - * Drag from a position and drop to another using left mouse button
applying Settings.DelayAfterDrag and - * DelayBeforeDrop - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param t1 source position - * @param t2 destination position - * @return 1 if possible, 0 otherwise - * @throws FindFailed if the Find operation failed - */ - public int dragDrop(PFRML t1, PFRML t2) throws FindFailed { - Location loc1 = getLocationFromTarget(t1); - Location loc2 = getLocationFromTarget(t2); - if (loc1 != null && loc2 != null) { - IRobot r = loc1.getRobotForPoint("drag"); - if (r == null) { - return 0; - } - Mouse.use(this); - r.smoothMove(loc1); - r.mouseDown(InputEvent.BUTTON1_MASK); - r.delay((int) (Settings.DelayAfterDrag * 1000)); - r = loc2.getRobotForPoint("drop"); - if (r == null) { - Mouse.let(this); - return 0; - } - r.smoothMove(loc2); - r.delay((int) (Settings.DelayBeforeDrop * 1000)); - r.mouseUp(InputEvent.BUTTON1_MASK); - Mouse.let(this); - return 1; - } - return 0; - } - - /** - * Prepare a drag action: move mouse to given target
press and hold left mouse button
wait - * Settings.DelayAfterDrag - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int drag(PFRML target) throws FindFailed { - Location loc = getLocationFromTarget(target); - if (loc != null) { - IRobot r = loc.getRobotForPoint("drag"); - if (r == null) { - return 0; - } - Mouse.use(this); - r.smoothMove(loc); - r.mouseDown(InputEvent.BUTTON1_MASK); - r.delay((int) (Settings.DelayAfterDrag * 1000)); - r.waitForIdle(); - return 1; - } - return 0; - } - - /** - * finalize a drag action with a drop: move mouse to given target
wait Settings.DelayBeforeDrop
release the - * left mouse button - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int dropAt(PFRML target) throws FindFailed { - Location loc = getLocationFromTarget(target); - if (loc != null) { - IRobot r = loc.getRobotForPoint("drop"); - if (r == null) { - return 0; - } - r.smoothMove(loc); - r.delay((int) (Settings.DelayBeforeDrop * 1000)); - r.mouseUp(InputEvent.BUTTON1_MASK); - r.waitForIdle(); - Mouse.let(this); - return 1; - } - return 0; - } - //
- - // - /** - * press and hold the specified buttons - use + to combine Button.LEFT left mouse button Button.MIDDLE middle mouse - * button Button.RIGHT right mouse button - * - * @param buttons spec - */ - public void mouseDown(int buttons) { - Mouse.down(buttons, this); - } - - /** - * release all currently held buttons - */ - public void mouseUp() { - Mouse.up(0, this); - } - - /** - * release the specified mouse buttons (see mouseDown) if buttons==0, all currently held buttons are released - * - * @param buttons spec - */ - public void mouseUp(int buttons) { - Mouse.up(buttons, this); - } - - /** - * move the mouse pointer to the region's last successful match
same as hover
- * - * @return 1 if possible, 0 otherwise - */ - public int mouseMove() { - if (lastMatch != null) { - try { - return mouseMove(lastMatch); - } catch (FindFailed ex) { - return 0; - } - } - return 0; - } - - /** - * move the mouse pointer to the given target location
same as hover
Pattern or Filename - do a find before - * and use the match
Region - position at center
Match - position at match's targetOffset
- * Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int mouseMove(PFRML target) throws FindFailed { - Location loc = getLocationFromTarget(target); - return Mouse.move(loc, this); - } - - /** - * move the mouse from the current position to the offset position given by the parameters - * @param xoff horizontal offset (< 0 left, > 0 right) - * @param yoff vertical offset (< 0 up, > 0 down) - * @return 1 if possible, 0 otherwise - */ - public int mouseMove(int xoff, int yoff) { - try { - return mouseMove(Mouse.at().offset(xoff, yoff)); - } catch (Exception ex) { - return 0; - } - } - - /** - * Move the wheel at the current mouse position
the given steps in the given direction:
Button.WHEEL_DOWN, - * Button.WHEEL_UP - * - * @param direction to move the wheel - * @param steps the number of steps - * @return 1 in any case - */ - public int wheel(int direction, int steps) { - Mouse.wheel(direction, steps, this); - return 1; - } - - /** - * move the mouse pointer to the given target location
and move the wheel the given steps in the given direction: - *
Button.WHEEL_DOWN, Button.WHEEL_UP - * - * @param Pattern, Filename, Text, Region, Match or Location target - * @param target Pattern, Filename, Text, Region, Match or Location - * @param direction to move the wheel - * @param steps the number of steps - * @return 1 if possible, 0 otherwise - * @throws FindFailed if the Find operation failed - */ - public int wheel(PFRML target, int direction, int steps) throws FindFailed { - Location loc = getLocationFromTarget(target); - if (loc != null) { - Mouse.use(this); - Mouse.keep(this); - Mouse.move(loc, this); - Mouse.wheel(direction, steps, this); - Mouse.let(this); - return 1; - } - return 0; - } - - /** - * - * @return current location of mouse pointer - * @deprecated use {@link Mouse#at()} instead - */ - @Deprecated - public static Location atMouse() { - return Mouse.at(); - } - //
- - // - /** - * press and hold the given key use a constant from java.awt.event.KeyEvent which might be special in the current - * machine/system environment - * - * @param keycode Java KeyCode - */ - public void keyDown(int keycode) { - getRobotForRegion().keyDown(keycode); - } - - /** - * press and hold the given keys including modifier keys
use the key constants defined in class Key,
which - * only provides a subset of a US-QWERTY PC keyboard layout
might be mixed with simple characters - *
use + to concatenate Key constants - * - * @param keys valid keys - */ - public void keyDown(String keys) { - getRobotForRegion().keyDown(keys); - } - - /** - * release all currently pressed keys - */ - public void keyUp() { - getRobotForRegion().keyUp(); - } - - /** - * release the given keys (see keyDown(keycode) ) - * - * @param keycode Java KeyCode - */ - public void keyUp(int keycode) { - getRobotForRegion().keyUp(keycode); - } - - /** - * release the given keys (see keyDown(keys) ) - * - * @param keys valid keys - */ - public void keyUp(String keys) { - getRobotForRegion().keyUp(keys); - } - - /** - * Compact alternative for type() with more options
- * - special keys and options are coded as #XN. or #X+ or #X-
- * where X is a refrence for a special key and N is an optional repeat factor
- * A modifier key as #X. modifies the next following key
- * the trailing . ends the special key, the + (press and hold) or - (release) does the same,
- * but signals press-and-hold or release additionally.
- * except #W / #w all special keys are not case-sensitive
- * a #wn. inserts a wait of n millisecs or n secs if n less than 60
- * a #Wn. sets the type delay for the following keys (must be > 60 and denotes millisecs) - * - otherwise taken as normal wait
- * Example: wait 2 secs then type CMD/CTRL - N then wait 1 sec then type DOWN 3 times
- * Windows/Linux: write("#w2.#C.n#W1.#d3.")
- * Mac: write("#w2.#M.n#W1.#D3.")
- * for more details about the special key codes and examples consult the docs
- * @param text a coded text interpreted as a series of key actions (press/hold/release) - * @return 0 for success 1 otherwise - */ - public int write(String text) { - Debug.info("Write: " + text); - char c; - String token, tokenSave; - String modifier = ""; - int k; - IRobot robot = getRobotForRegion(); - int pause = 20 + (Settings.TypeDelay > 1 ? 1000 : (int) (Settings.TypeDelay * 1000)); - Settings.TypeDelay = 0.0; - robot.typeStarts(); - for (int i = 0; i < text.length(); i++) { - log(lvl + 1, "write: (%d) %s", i, text.substring(i)); - c = text.charAt(i); - token = null; - boolean isModifier = false; - if (c == '#') { - if (text.charAt(i + 1) == '#') { - log(3, "write at: %d: %s", i, c); - i += 1; - continue; - } - if (text.charAt(i + 2) == '+' || text.charAt(i + 2) == '-') { - token = text.substring(i, i + 3); - isModifier = true; - } else if (-1 < (k = text.indexOf('.', i))) { - if (k > -1) { - token = text.substring(i, k + 1); - if (token.length() > Key.keyMaxLength || token.substring(1).contains("#")) { - token = null; - } - } - } - } - Integer key = -1; - if (token == null) { - log(lvl + 1, "write: %d: %s", i, c); - } else { - log(lvl + 1, "write: token at %d: %s", i, token); - int repeat = 0; - if (token.toUpperCase().startsWith("#W")) { - if (token.length() > 3) { - i += token.length() - 1; - int t = 0; - try { - t = Integer.parseInt(token.substring(2, token.length() - 1)); - } catch (NumberFormatException ex) { - } - if ((token.startsWith("#w") && t > 60)) { - pause = 20 + (t > 1000 ? 1000 : t); - log(lvl + 1, "write: type delay: " + t); - } else { - log(lvl + 1, "write: wait: " + t); - robot.delay((t < 60 ? t * 1000 : t)); - } - continue; - } - } - tokenSave = token; - token = token.substring(0, 2).toUpperCase() + "."; - if (Key.isRepeatable(token)) { - try { - repeat = Integer.parseInt(tokenSave.substring(2, tokenSave.length() - 1)); - } catch (NumberFormatException ex) { - token = tokenSave; - } - } else if (tokenSave.length() == 3 && Key.isModifier(tokenSave.toUpperCase())) { - i += tokenSave.length() - 1; - modifier += tokenSave.substring(1, 2).toUpperCase(); - continue; - } else { - token = tokenSave; - } - if (-1 < (key = Key.toJavaKeyCodeFromText(token))) { - if (repeat > 0) { - log(lvl + 1, "write: %s Repeating: %d", token, repeat); - } else { - log(lvl + 1, "write: %s", tokenSave); - repeat = 1; - } - i += tokenSave.length() - 1; - if (isModifier) { - if (tokenSave.endsWith("+")) { - robot.keyDown(key); - } else { - robot.keyUp(key); - } - continue; - } - if (repeat > 1) { - for (int n = 0; n < repeat; n++) { - robot.typeKey(key.intValue()); - } - continue; - } - } - } - if (!modifier.isEmpty()) { - log(lvl + 1, "write: modifier + " + modifier); - for (int n = 0; n < modifier.length(); n++) { - robot.keyDown(Key.toJavaKeyCodeFromText(String.format("#%s.", modifier.substring(n, n + 1)))); - } - } - if (key > -1) { - robot.typeKey(key.intValue()); - } else { - robot.typeChar(c, IRobot.KeyMode.PRESS_RELEASE); - } - if (!modifier.isEmpty()) { - log(lvl + 1, "write: modifier - " + modifier); - for (int n = 0; n < modifier.length(); n++) { - robot.keyUp(Key.toJavaKeyCodeFromText(String.format("#%s.", modifier.substring(n, n + 1)))); - } - } - robot.delay(pause); - modifier = ""; - } - - robot.typeEnds(); - robot.waitForIdle(); - return 0; - } - - /** - * enters the given text one character/key after another using keyDown/keyUp - *
about the usable Key constants see keyDown(keys)
Class Key only provides a subset of a US-QWERTY PC - * keyboard layout
the text is entered at the current position of the focus/carret - * - * @param text containing characters and/or Key constants - * @return 1 if possible, 0 otherwise - */ - public int type(String text) { - try { - return keyin(null, text, 0); - } catch (FindFailed ex) { - return 0; - } - } - - /** - * enters the given text one character/key after another using keyDown/keyUp
while holding down the given modifier - * keys
about the usable Key constants see keyDown(keys)
Class Key only provides a subset of a US-QWERTY PC - * keyboard layout
the text is entered at the current position of the focus/carret - * - * @param text containing characters and/or Key constants - * @param modifiers constants according to class KeyModifiers - * @return 1 if possible, 0 otherwise - */ - public int type(String text, int modifiers) { - try { - return keyin(null, text, modifiers); - } catch (FindFailed findFailed) { - return 0; - } - } - - /** - * enters the given text one character/key after another using - * - * keyDown/keyUp
while holding down the given modifier keys
about the usable Key constants see keyDown(keys) - *
Class Key only provides a subset of a US-QWERTY PC keyboard layout
the text is entered at the current - * position of the focus/carret - * - * - * @param text containing characters and/or Key constants - * @param modifiers constants according to class Key - combine using + - * @return 1 if possible, 0 otherwise - */ - public int type(String text, String modifiers) { - String target = null; - int modifiersNew = Key.convertModifiers(modifiers); - if (modifiersNew == 0) { - target = text; - text = modifiers; - } - try { - return keyin(target, text, modifiersNew); - } catch (FindFailed findFailed) { - return 0; - } - } - - /** - * first does a click(target) at the given target position to gain focus/carret
enters the given text one - * character/key after another using keyDown/keyUp
about the usable Key constants see keyDown(keys) - *
Class Key only provides a subset of a US-QWERTY PC keyboard layout - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param text containing characters and/or Key constants - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int type(PFRML target, String text) throws FindFailed { - return keyin(target, text, 0); - } - - /** - * first does a click(target) at the given target position to gain focus/carret
enters the given text one - * character/key after another using keyDown/keyUp
while holding down the given modifier keys
about the usable - * Key constants see keyDown(keys)
Class Key only provides a subset of a US-QWERTY PC keyboard layout - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param text containing characters and/or Key constants - * @param modifiers constants according to class KeyModifiers - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int type(PFRML target, String text, int modifiers) throws FindFailed { - return keyin(target, text, modifiers); - } - - /** - * first does a click(target) at the given target position to gain focus/carret
enters the given text one - * character/key after another using keyDown/keyUp
while holding down the given modifier keys
about the usable - * Key constants see keyDown(keys)
Class Key only provides a subset of a US-QWERTY PC keyboard layout - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param text containing characters and/or Key constants - * @param modifiers constants according to class Key - combine using + - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int type(PFRML target, String text, String modifiers) throws FindFailed { - int modifiersNew = Key.convertModifiers(modifiers); - return keyin(target, text, modifiersNew); - } - - private int keyin(PFRML target, String text, int modifiers) - throws FindFailed { - if (target != null && 0 == click(target, 0)) { - return 0; - } - Debug profiler = Debug.startTimer("Region.type"); - if (text != null && !"".equals(text)) { - String showText = ""; - for (int i = 0; i < text.length(); i++) { - showText += Key.toJavaKeyCodeText(text.charAt(i)); - } - String modText = ""; - String modWindows = null; - if ((modifiers & KeyModifier.WIN) != 0) { - modifiers -= KeyModifier.WIN; - modifiers |= KeyModifier.META; - log(lvl, "Key.WIN as modifier"); - modWindows = "Windows"; - } - if (modifiers != 0) { - modText = String.format("( %s ) ", KeyEvent.getKeyModifiersText(modifiers)); - if (modWindows != null) { - modText = modText.replace("Meta", modWindows); - } - } - Debug.action("%s TYPE \"%s\"", modText, showText); - log(lvl, "%s TYPE \"%s\"", modText, showText); - profiler.lap("before getting Robot"); - IRobot r = getRobotForRegion(); - int pause = 20 + (Settings.TypeDelay > 1 ? 1000 : (int) (Settings.TypeDelay * 1000)); - Settings.TypeDelay = 0.0; - profiler.lap("before typing"); - r.typeStarts(); - for (int i = 0; i < text.length(); i++) { - r.pressModifiers(modifiers); - r.typeChar(text.charAt(i), IRobot.KeyMode.PRESS_RELEASE); - r.releaseModifiers(modifiers); - r.delay(pause); - } - r.typeEnds(); - profiler.lap("after typing, before waitForIdle"); - r.waitForIdle(); - profiler.end(); - return 1; - } - - return 0; - } - - /** - * time in milliseconds to delay between each character at next type only (max 1000) - * - * @param millisecs value - */ - public void delayType(int millisecs) { - Settings.TypeDelay = millisecs; - } - - /** - * pastes the text at the current position of the focus/carret
using the clipboard and strg/ctrl/cmd-v (paste - * keyboard shortcut) - * - * @param text a string, which might contain unicode characters - * @return 0 if possible, 1 otherwise - */ - public int paste(String text) { - try { - return paste(null, text); - } catch (FindFailed ex) { - return 1; - } - } - - /** - * first does a click(target) at the given target position to gain focus/carret
and then pastes the text
- * using the clipboard and strg/ctrl/cmd-v (paste keyboard shortcut) - * - * @param Pattern, Filename, Text, Region, Match or Location target - * @param target Pattern, Filename, Text, Region, Match or Location - * @param text a string, which might contain unicode characters - * @return 0 if possible, 1 otherwise - * @throws FindFailed if not found - */ - public int paste(PFRML target, String text) throws FindFailed { - if (target != null) { - click(target, 0); - } - if (text != null) { - App.setClipboard(text); - int mod = Key.getHotkeyModifier(); - IRobot r = getRobotForRegion(); - r.keyDown(mod); - r.keyDown(KeyEvent.VK_V); - r.keyUp(KeyEvent.VK_V); - r.keyUp(mod); - return 1; - } - return 0; - } - //
- - // - /** - * STILL EXPERIMENTAL: tries to read the text in this region
might contain misread characters, NL characters and - * other stuff, when interpreting contained grafics as text
- * Best results: one line of text with no grafics in the line - * - * @return the text read (utf8 encoded) - */ - public String text() { - if (Settings.OcrTextRead) { - ScreenImage simg = getScreen().capture(x, y, w, h); - TextRecognizer tr = TextRecognizer.getInstance(); - if (tr == null) { - Debug.error("text: text recognition is now switched off"); - return "--- no text ---"; - } - String textRead = tr.recognize(simg); - log(lvl, "text: #(" + textRead + ")#"); - return textRead; - } - Debug.error("text: text recognition is currently switched off"); - return "--- no text ---"; - } - - /** - * VERY EXPERIMENTAL: returns a list of matches, that represent single words, that have been found in this region
- * the match's x,y,w,h the region of the word
Match.getText() returns the word (utf8) at this match
- * Match.getScore() returns a value between 0 ... 1, that represents some OCR-confidence value
(the higher, the - * better the OCR engine thinks the result is) - * - * @return a list of matches - */ - public List listText() { - if (Settings.OcrTextRead) { - ScreenImage simg = getScreen().capture(x, y, w, h); - TextRecognizer tr = TextRecognizer.getInstance(); - if (tr == null) { - Debug.error("text: text recognition is now switched off"); - return null; - } - log(lvl, "listText: scanning %s", this); - return tr.listText(simg, this); - } - Debug.error("text: text recognition is currently switched off"); - return null; - } - //
- - public String saveScreenCapture() { - return getScreen().capture(this).save(); - } - - public String saveScreenCapture(String path) { - return getScreen().capture(this).save(path); - } - - public String saveScreenCapture(String path, String name) { - return getScreen().capture(this).save(path, name); - } -} diff --git a/All/Genesis-NP/Genesis#219/old/Region.java b/All/Genesis-NP/Genesis#219/old/Region.java deleted file mode 100755 index 47aeefa..0000000 --- a/All/Genesis-NP/Genesis#219/old/Region.java +++ /dev/null @@ -1,4302 +0,0 @@ -/* - * Copyright 2010-2014, Sikuli.org, Sikulix.com - * Released under the MIT License. - * - * modified RaiMan - */ -package org.sikuli.script; - -import org.sikuli.util.ScreenHighlighter; -import java.awt.Rectangle; -import java.awt.event.InputEvent; -import java.awt.event.KeyEvent; -import java.io.IOException; -import java.util.Date; -import java.util.Iterator; -import java.util.List; -import org.sikuli.basics.Debug; -import org.sikuli.basics.Settings; - -import edu.unh.iol.dlc.VNCScreen; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; - -/** - * A Region is a rectengular area and lies always completely inside its parent screen - * - */ -public class Region { - - static RunTime runTime = RunTime.get(); - - private static String me = "Region: "; - private static int lvl = 3; - - private static void log(int level, String message, Object... args) { - Debug.logx(level, me + message, args); - } - - /** - * The Screen containing the Region - */ - private IScreen scr; - protected boolean otherScreen = false; - - /** - * The ScreenHighlighter for this Region - */ - private ScreenHighlighter overlay = null; - /** - * X-coordinate of the Region - */ - public int x; - /** - * Y-coordinate of the Region - */ - public int y; - /** - * Width of the Region - */ - public int w; - /** - * Height of the Region - */ - public int h; - /** - * Setting, how to react if an image is not found {@link FindFailed} - */ - private FindFailedResponse findFailedResponse = FindFailed.defaultFindFailedResponse; - /** - * Setting {@link Settings}, if exception is thrown if an image is not found - */ - private boolean throwException = Settings.ThrowException; - /** - * Default time to wait for an image {@link Settings} - */ - private double autoWaitTimeout = Settings.AutoWaitTimeout; - private float waitScanRate = Settings.WaitScanRate; - /** - * Flag, if an observer is running on this region {@link Settings} - */ - private boolean observing = false; - private float observeScanRate = Settings.ObserveScanRate; - private int repeatWaitTime = Settings.RepeatWaitTime; - /** - * The {@link Observer} Singleton instance - */ - private Observer regionObserver = null; - - /** - * The last found {@link Match} in the Region - */ - private Match lastMatch = null; - /** - * The last found {@link Match}es in the Region - */ - private Iterator lastMatches = null; - private long lastSearchTime = -1; - private long lastFindTime = -1; - private boolean isScreenUnion = false; - private boolean isVirtual = false; - private long lastSearchTimeRepeat = -1; - - /** - * in case of not found the total wait time - * @return the duration of the last find op - */ - public long getLastTime() { - return lastFindTime; - } - - /** - * the area constants for use with get() - */ - public static final int NW = 300, NORTH_WEST = NW, TL = NW; - public static final int NM = 301, NORTH_MID = NM, TM = NM; - public static final int NE = 302, NORTH_EAST = NE, TR = NE; - public static final int EM = 312, EAST_MID = EM, RM = EM; - public static final int SE = 322, SOUTH_EAST = SE, BR = SE; - public static final int SM = 321, SOUTH_MID = SM, BM = SM; - public static final int SW = 320, SOUTH_WEST = SW, BL = SW; - public static final int WM = 310, WEST_MID = WM, LM = WM; - public static final int MM = 311, MIDDLE = MM, M3 = MM; - public static final int TT = 200; - public static final int RR = 201; - public static final int BB = 211; - public static final int LL = 210; - public static final int NH = 202, NORTH = NH, TH = NH; - public static final int EH = 221, EAST = EH, RH = EH; - public static final int SH = 212, SOUTH = SH, BH = SH; - public static final int WH = 220, WEST = WH, LH = WH; - public static final int MV = 441, MID_VERTICAL = MV, CV = MV; - public static final int MH = 414, MID_HORIZONTAL = MH, CH = MH; - public static final int M2 = 444, MIDDLE_BIG = M2, C2 = M2; - public static final int EN = NE, EAST_NORTH = NE, RT = TR; - public static final int ES = SE, EAST_SOUTH = SE, RB = BR; - public static final int WN = NW, WEST_NORTH = NW, LT = TL; - public static final int WS = SW, WEST_SOUTH = SW, LB = BL; - - /** - * to support a raster over the region - */ - private int rows; - private int cols = 0; - private int rowH = 0; - private int colW = 0; - private int rowHd = 0; - private int colWd = 0; - - /** - * {@inheritDoc} - * - * @return the description - */ - @Override - public String toString() { - return String.format("R[%d,%d %dx%d]@%s E:%s, T:%.1f", - x, y, w, h, (getScreen() == null ? "Screen null" : getScreen().toStringShort()), - throwException ? "Y" : "N", autoWaitTimeout); - } - - /** - * - * @return a compact description - */ - public String toStringShort() { - return String.format("R[%d,%d %dx%d]@S(%s)", x, y, w, h, (getScreen() == null ? "?" : getScreen().getID())); - } - - public String toJSON() { - return String.format("[\"R\", %d, %d, %d, %d]", x, y, w, h); - } - - // - /* - public Object __enter__() { - Debug.error("Region: with(__enter__): Trying to make it a Jython Region for with: usage"); - IScriptRunner runner = Settings.getScriptRunner("jython", null, null); - if (runner != null) { - Object[] jyreg = new Object[]{this}; - if (runner.doSomethingSpecial("createRegionForWith", jyreg)) { - if (jyreg[0] != null) { - return jyreg[0]; - } - } - } - Debug.error("Region: with(__enter__): Sorry, not possible"); - return null; - } - - public void __exit__(Object type, Object value, Object traceback) { - Debug.error("Region: with(__exit__): Sorry, not a Jython Region and not posssible!"); - } - */ - // - - // - /** - * Detects on which Screen the Region is present. The region is cropped to the intersection with the given screen or - * the screen with the largest intersection - * - * @param iscr The Screen containing the Region - */ - public void initScreen(IScreen iscr) { - // check given screen first - Rectangle rect, screenRect; - IScreen screen, screenOn; - if (iscr != null) { - if (iscr.isOtherScreen()) { - if (x < 0) { - w = w + x; - x = 0; - } - if (y < 0) { - h = h + y; - y = 0; - } - this.scr = iscr; - this.otherScreen = true; - return; - } - if (iscr.getID() > -1) { - rect = regionOnScreen(iscr); - if (rect != null) { - x = rect.x; - y = rect.y; - w = rect.width; - h = rect.height; - this.scr = iscr; - return; - } - } else { - // is ScreenUnion - return; - } - } - // check all possible screens if no screen was given or the region is not on given screen - // crop to the screen with the largest intersection - screenRect = new Rectangle(0, 0, 0, 0); - screenOn = null; - boolean isVNC; - if (iscr == null) { - isVNC = scr instanceof VNCScreen; - } else { - isVNC = iscr instanceof VNCScreen; - } - if (!isVNC) { - for (int i = 0; i < Screen.getNumberScreens(); i++) { - screen = Screen.getScreen(i); - rect = regionOnScreen(screen); - if (rect != null) { - if (rect.width * rect.height > screenRect.width * screenRect.height) { - screenRect = rect; - screenOn = screen; - } - } - } - } else { - for (int i = 0; i < VNCScreen.getNumberScreens(); i++) { - screen = VNCScreen.getScreen(i); - rect = regionOnScreen(screen); - if (rect != null) { - if (rect.width * rect.height > screenRect.width * screenRect.height) { - screenRect = rect; - screenOn = screen; - } - } - } - } - if (screenOn != null) { - x = screenRect.x; - y = screenRect.y; - w = screenRect.width; - h = screenRect.height; - this.scr = screenOn; - } else { - // no screen found - this.scr = null; - Debug.error("Region(%d,%d,%d,%d) outside any screen - subsequent actions might not work as expected", x, y, w, h); - } - } - - private Location checkAndSetRemote(Location loc) { - if (!isOtherScreen()) { - return loc; - } - return loc.setOtherScreen(scr); - } - - public static Region virtual(Rectangle rect) { - Region reg = new Region(); - reg.x = rect.x; - reg.y = rect.y; - reg.w = rect.width; - reg.h = rect.height; - reg.setVirtual(true); - reg.scr = Screen.getPrimaryScreen(); - return reg; - } - - /** - * INTERNAL USE - EXPERIMENTAL - * if true: this region is not bound to any screen - * @return the current state - */ - public boolean isVirtual() { - return isVirtual; - } - - /** - * INTERNAL USE - EXPERIMENTAL - * @param state if true: this region is not bound to any screen - */ - public void setVirtual(boolean state) { - isVirtual = state; - } - - /** - * INTERNAL USE: - * checks wether this region belongs to a non-Desktop screen - * @return true/false - */ - public boolean isOtherScreen() { - return otherScreen; - } - - /** - * INTERNAL USE: - * flags this region as belonging to a non-Desktop screen - */ - public void setOtherScreen() { - otherScreen = true; - } - - /** - * Checks if the Screen contains the Region. - * - * @param screen The Screen in which the Region might be - * @return True, if the Region is on the Screen. False if the Region is not inside the Screen - */ - protected Rectangle regionOnScreen(IScreen screen) { - if (screen == null) { - return null; - } - // get intersection of Region and Screen - Rectangle rect = screen.getRect().intersection(getRect()); - // no Intersection, Region is not on the Screen - if (rect.isEmpty()) { - return null; - } - return rect; - } - - /** - * Check wether thie Region is contained by any of the available screens - * @return true if yes, false otherwise - */ - public boolean isValid() { - return scr != null; - } - // - - // - /** - * Create a region with the provided coordinate / size and screen - * - * @param X X position - * @param Y Y position - * @param W width - * @param H heigth - * @param screenNumber The number of the screen containing the Region - */ - public Region(int X, int Y, int W, int H, int screenNumber) { - this(X, Y, W, H, Screen.getScreen(screenNumber)); - this.rows = 0; - } - - /** - * Create a region with the provided coordinate / size and screen - * - * @param X X position - * @param Y Y position - * @param W width - * @param H heigth - * @param parentScreen the screen containing the Region - */ - public Region(int X, int Y, int W, int H, IScreen parentScreen) { - this.rows = 0; - this.x = X; - this.y = Y; - this.w = W > 1 ? W : 1; - this.h = H > 1 ? H : 1; - initScreen(parentScreen); - } - - /** - * Create a region with the provided coordinate / size - * - * @param X X position - * @param Y Y position - * @param W width - * @param H heigth - */ - public Region(int X, int Y, int W, int H) { - this(X, Y, W, H, null); - this.rows = 0; - log(lvl, "init: (%d, %d, %d, %d)", X, Y, W, H); - } - - /** - * Create a region from a Rectangle - * - * @param r the Rectangle - */ - public Region(Rectangle r) { - this(r.x, r.y, r.width, r.height, null); - this.rows = 0; - } - - /** - * Create a new region from another region
including the region's settings - * - * @param r the region - */ - public Region(Region r) { - this(r.x, r.y, r.w, r.h, r.getScreen()); - this.rows = 0; - autoWaitTimeout = r.autoWaitTimeout; - findFailedResponse = r.findFailedResponse; - throwException = r.throwException; - } - - //
- - // - /** - * internal use only, used for new Screen objects to get the Region behavior - */ - protected Region() { - this.rows = 0; - } - - /** - * internal use only, used for new Screen objects to get the Region behavior - */ - protected Region(boolean isScreenUnion) { - this.isScreenUnion = isScreenUnion; - this.rows = 0; - } - - /** - * Create a region with the provided top left corner and size - * - * @param X top left X position - * @param Y top left Y position - * @param W width - * @param H heigth - * @return then new region - */ - public static Region create(int X, int Y, int W, int H) { - return Region.create(X, Y, W, H, null); - } - - /** - * Create a region with the provided top left corner and size - * - * @param X top left X position - * @param Y top left Y position - * @param W width - * @param H heigth - * @param scr the source screen - * @return the new region - */ - private static Region create(int X, int Y, int W, int H, IScreen scr) { - return new Region(X, Y, W, H, scr); - } - - /** - * Create a region with the provided top left corner and size - * - * @param loc top left corner - * @param w width - * @param h height - * @return then new region - */ - public static Region create(Location loc, int w, int h) { - return Region.create(loc.x, loc.y, w, h, loc.getScreen()); - } - /** - * Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the left corner of - * the new Region. - */ - public final static int CREATE_X_DIRECTION_LEFT = 0; - /** - * Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the right corner of - * the new Region. - */ - public final static int CREATE_X_DIRECTION_RIGHT = 1; - /** - * Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the top corner of the - * new Region. - */ - public final static int CREATE_Y_DIRECTION_TOP = 0; - /** - * Flag for the {@link #create(Location, int, int, int, int)} method. Sets the Location to be on the bottom corner of - * the new Region. - */ - public final static int CREATE_Y_DIRECTION_BOTTOM = 1; - - /** - * create a region with a corner at the given point
as specified with x y
0 0 top left
0 1 bottom left
- * 1 0 top right
1 1 bottom right
- * - * @param loc the refence point - * @param create_x_direction == 0 is left side !=0 is right side - * @param create_y_direction == 0 is top side !=0 is bottom side - * @param w the width - * @param h the height - * @return the new region - */ - public static Region create(Location loc, int create_x_direction, int create_y_direction, int w, int h) { - int X; - int Y; - int W = w; - int H = h; - if (create_x_direction == CREATE_X_DIRECTION_LEFT) { - if (create_y_direction == CREATE_Y_DIRECTION_TOP) { - X = loc.x; - Y = loc.y; - } else { - X = loc.x; - Y = loc.y - h; - } - } else { - if (create_y_direction == CREATE_Y_DIRECTION_TOP) { - X = loc.x - w; - Y = loc.y; - } else { - X = loc.x - w; - Y = loc.y - h; - } - } - return Region.create(X, Y, W, H, loc.getScreen()); - } - - /** - * create a region with a corner at the given point
as specified with x y
0 0 top left
0 1 bottom left
- * 1 0 top right
1 1 bottom right
same as the corresponding create method, here to be naming compatible with - * class Location - * - * @param loc the refence point - * @param x ==0 is left side !=0 is right side - * @param y ==0 is top side !=0 is bottom side - * @param w the width - * @param h the height - * @return the new region - */ - public static Region grow(Location loc, int x, int y, int w, int h) { - return Region.create(loc, x, y, w, h); - } - - /** - * Create a region from a Rectangle - * - * @param r the Rectangle - * @return the new region - */ - public static Region create(Rectangle r) { - return Region.create(r.x, r.y, r.width, r.height, null); - } - - /** - * Create a region from a Rectangle on a given Screen - * - * @param r the Rectangle - * @param parentScreen the new parent screen - * @return the new region - */ - protected static Region create(Rectangle r, IScreen parentScreen) { - return Region.create(r.x, r.y, r.width, r.height, parentScreen); - } - - /** - * Create a region from another region
including the region's settings - * - * @param r the region - * @return then new region - */ - public static Region create(Region r) { - Region reg = Region.create(r.x, r.y, r.w, r.h, r.getScreen()); - reg.autoWaitTimeout = r.autoWaitTimeout; - reg.findFailedResponse = r.findFailedResponse; - reg.throwException = r.throwException; - return reg; - } - - /** - * create a region with the given point as center and the given size - * - * @param loc the center point - * @param w the width - * @param h the height - * @return the new region - */ - public static Region grow(Location loc, int w, int h) { - int X = loc.x - (int) w / 2; - int Y = loc.y - (int) h / 2; - return Region.create(X, Y, w, h, loc.getScreen()); - } - - /** - * create a minimal region at given point with size 1 x 1 - * - * @param loc the point - * @return the new region - */ - public static Region grow(Location loc) { - return Region.create(loc.x, loc.y, 1, 1, loc.getScreen()); - } - - //
- - // - /** - * check if current region contains given point - * - * @param point Point - * @return true/false - */ - public boolean contains(Location point) { - return getRect().contains(point.x, point.y); - } - - /** - * check if mouse pointer is inside current region - * - * @return true/false - */ - public boolean containsMouse() { - return contains(Mouse.at()); - } - - /** - * new region with same offset to current screen's top left on given screen - * - * @param scrID number of screen - * @return new region - */ - public Region copyTo(int scrID) { - return copyTo(Screen.getScreen(scrID)); - } - - /** - * new region with same offset to current screen's top left on given screen - * - * @param screen new parent screen - * @return new region - */ - public Region copyTo(IScreen screen) { - Location o = new Location(getScreen().getBounds().getLocation()); - Location n = new Location(screen.getBounds().getLocation()); - return Region.create(n.x + x - o.x, n.y + y - o.y, w, h, screen); - } - - /** - * used in Observer.callChangeObserving, Finder.next to adjust region relative coordinates of matches to - screen coordinates - * - * @param m - * @return the modified match - */ - protected Match toGlobalCoord(Match m) { - m.x += x; - m.y += y; - return m; - } - // - - // - //TODO should be possible to reset to current global value resetXXX() - /** - * true - (initial setting) should throw exception FindFailed if findX unsuccessful in this region
false - do not - * abort script on FindFailed (might leed to null pointer exceptions later) - * - * @param flag true/false - */ - public void setThrowException(boolean flag) { - throwException = flag; - if (throwException) { - findFailedResponse = FindFailedResponse.ABORT; - } else { - findFailedResponse = FindFailedResponse.SKIP; - } - } - - /** - * current setting for this region (see setThrowException) - * - * @return true/false - */ - public boolean getThrowException() { - return throwException; - } - - /** - * the time in seconds a find operation should wait for the appearence of the target in this region
initial value - * is the global AutoWaitTimeout setting at time of Region creation - * - * @param sec seconds - */ - public void setAutoWaitTimeout(double sec) { - autoWaitTimeout = sec; - } - - /** - * current setting for this region (see setAutoWaitTimeout) - * - * @return value of seconds - */ - public double getAutoWaitTimeout() { - return autoWaitTimeout; - } - - /** - * FindFailedResponse.
ABORT - (initial value) abort script on FindFailed (= setThrowException(true) )
SKIP - - * ignore FindFailed (same as setThrowException(false) )
- * PROMPT - display prompt on FindFailed to let user decide how to proceed
RETRY - continue to wait for appearence - * on FindFailed (caution: endless loop) - * - * @param response the FindFailedResponse - */ - public void setFindFailedResponse(FindFailedResponse response) { - findFailedResponse = response; - } - - /** - * - * @return the current setting (see setFindFailedResponse) - */ - public FindFailedResponse getFindFailedResponse() { - return findFailedResponse; - } - - /** - * - * @return the regions current WaitScanRate - */ - public float getWaitScanRate() { - return waitScanRate; - } - - /** - * set the regions individual WaitScanRate - * - * @param waitScanRate decimal number - */ - public void setWaitScanRate(float waitScanRate) { - this.waitScanRate = waitScanRate; - } - - /** - * - * @return the regions current ObserveScanRate - */ - public float getObserveScanRate() { - return observeScanRate; - } - - /** - * set the regions individual ObserveScanRate - * - * @param observeScanRate decimal number - */ - public void setObserveScanRate(float observeScanRate) { - this.observeScanRate = observeScanRate; - } - - /** - * INTERNAL USE: Observe - * @return the regions current RepeatWaitTime time in seconds - */ - public int getRepeatWaitTime() { - return repeatWaitTime; - } - - /** - * INTERNAL USE: Observe - * set the regions individual WaitForVanish - * - * @param time in seconds - */ - public void setRepeatWaitTime(int time) { - repeatWaitTime = time; - } - - //
- - // - /** - * - * @return the Screen object containing the region - */ - public IScreen getScreen() { - return scr; - } - - // to avoid NPE for Regions being outside any screen - private IRobot getRobotForRegion() { - if (getScreen() == null || isScreenUnion) { - return Screen.getPrimaryScreen().getRobot(); - } - return getScreen().getRobot(); - } - - /** - * - * @return the screen, that contains the top left corner of the region. Returns primary screen if outside of any - * screen. - * @deprecated Only for compatibility, to get the screen containing this region, use {@link #getScreen()} - */ - @Deprecated - public IScreen getScreenContaining() { - return getScreen(); - } - - /** - * Sets a new Screen for this region. - * - * @param scr the containing screen object - * @return the region itself - */ - protected Region setScreen(IScreen scr) { - initScreen(scr); - return this; - } - - /** - * Sets a new Screen for this region. - * - * @param id the containing screen object's id - * @return the region itself - */ - protected Region setScreen(int id) { - return setScreen(Screen.getScreen(id)); - } - - /** - * synonym for showMonitors - */ - public void showScreens() { - Screen.showMonitors(); - } - - /** - * synonym for resetMonitors - */ - public void resetScreens() { - Screen.resetMonitors(); - } - - // ************************************************ - /** - * - * @return the center pixel location of the region - */ - public Location getCenter() { - return checkAndSetRemote(new Location(getX() + getW() / 2, getY() + getH() / 2)); - } - - /** - * convenience method - * - * @return the region's center - */ - public Location getTarget() { - return getCenter(); - } - - /** - * Moves the region to the area, whose center is the given location - * - * @param loc the location which is the new center of the region - * @return the region itself - */ - public Region setCenter(Location loc) { - Location c = getCenter(); - x = x - c.x + loc.x; - y = y - c.y + loc.y; - initScreen(null); - return this; - } - - /** - * - * @return top left corner Location - */ - public Location getTopLeft() { - return checkAndSetRemote(new Location(x, y)); - } - - /** - * Moves the region to the area, whose top left corner is the given location - * - * @param loc the location which is the new top left point of the region - * @return the region itself - */ - public Region setTopLeft(Location loc) { - return setLocation(loc); - } - - /** - * - * @return top right corner Location - */ - public Location getTopRight() { - return checkAndSetRemote(new Location(x + w - 1, y)); - } - - /** - * Moves the region to the area, whose top right corner is the given location - * - * @param loc the location which is the new top right point of the region - * @return the region itself - */ - public Region setTopRight(Location loc) { - Location c = getTopRight(); - x = x - c.x + loc.x; - y = y - c.y + loc.y; - initScreen(null); - return this; - } - - /** - * - * @return bottom left corner Location - */ - public Location getBottomLeft() { - return checkAndSetRemote(new Location(x, y + h - 1)); - } - - /** - * Moves the region to the area, whose bottom left corner is the given location - * - * @param loc the location which is the new bottom left point of the region - * @return the region itself - */ - public Region setBottomLeft(Location loc) { - Location c = getBottomLeft(); - x = x - c.x + loc.x; - y = y - c.y + loc.y; - initScreen(null); - return this; - } - - /** - * - * @return bottom right corner Location - */ - public Location getBottomRight() { - return checkAndSetRemote(new Location(x + w - 1, y + h - 1)); - } - - /** - * Moves the region to the area, whose bottom right corner is the given location - * - * @param loc the location which is the new bottom right point of the region - * @return the region itself - */ - public Region setBottomRight(Location loc) { - Location c = getBottomRight(); - x = x - c.x + loc.x; - y = y - c.y + loc.y; - initScreen(null); - return this; - } - - // ************************************************ - /** - * - * @return x of top left corner - */ - public int getX() { - return x; - } - - /** - * - * @return y of top left corner - */ - public int getY() { - return y; - } - - /** - * - * @return width of region - */ - public int getW() { - return w; - } - - /** - * - * @return height of region - */ - public int getH() { - return h; - } - - /** - * - * @param X new x position of top left corner - */ - public void setX(int X) { - x = X; - initScreen(null); - } - - /** - * - * @param Y new y position of top left corner - */ - public void setY(int Y) { - y = Y; - initScreen(null); - } - - /** - * - * @param W new width - */ - public void setW(int W) { - w = W > 1 ? W : 1; - initScreen(null); - } - - /** - * - * @param H new height - */ - public void setH(int H) { - h = H > 1 ? H : 1; - initScreen(null); - } - - // ************************************************ - /** - * - * @param W new width - * @param H new height - * @return the region itself - */ - public Region setSize(int W, int H) { - w = W > 1 ? W : 1; - h = H > 1 ? H : 1; - initScreen(null); - return this; - } - - /** - * - * @return the AWT Rectangle of the region - */ - public Rectangle getRect() { - return new Rectangle(x, y, w, h); - } - - /** - * set the regions position/size
this might move the region even to another screen - * - * @param r the AWT Rectangle to use for position/size - * @return the region itself - */ - public Region setRect(Rectangle r) { - return setRect(r.x, r.y, r.width, r.height); - } - - /** - * set the regions position/size
this might move the region even to another screen - * - * @param X new x of top left corner - * @param Y new y of top left corner - * @param W new width - * @param H new height - * @return the region itself - */ - public Region setRect(int X, int Y, int W, int H) { - x = X; - y = Y; - w = W > 1 ? W : 1; - h = H > 1 ? H : 1; - initScreen(null); - return this; - } - - /** - * set the regions position/size
this might move the region even to another screen - * - * @param r the region to use for position/size - * @return the region itself - */ - public Region setRect(Region r) { - return setRect(r.x, r.y, r.w, r.h); - } - - // **************************************************** - -/** - * resets this region (usually a Screen object) to the coordinates of the containing screen - * - * Because of the wanted side effect for the containing screen, this should only be used with screen objects. - * For Region objects use setRect() instead. - */ - public void setROI() { - setROI(getScreen().getBounds()); - } - - /** - * resets this region to the given location, and size
this might move the region even to another screen - * - *
Because of the wanted side effect for the containing screen, this should only be used with screen objects. - *
For Region objects use setRect() instead. - * - * @param X new x - * @param Y new y - * @param W new width - * @param H new height - */ - public void setROI(int X, int Y, int W, int H) { - x = X; - y = Y; - w = W > 1 ? W : 1; - h = H > 1 ? H : 1; - initScreen(null); - } - - /** - * resets this region to the given rectangle
this might move the region even to another screen - * - *
Because of the wanted side effect for the containing screen, this should only be used with screen objects. - *
For Region objects use setRect() instead. - * - * @param r AWT Rectangle - */ - public void setROI(Rectangle r) { - setROI(r.x, r.y, r.width, r.height); - } - - /** - * resets this region to the given region
this might move the region even to another screen - * - *
Because of the wanted side effect for the containing screen, this should only be used with screen objects. - *
For Region objects use setRect() instead. - * - * @param reg Region - */ - public void setROI(Region reg) { - setROI(reg.getX(), reg.getY(), reg.getW(), reg.getH()); - } - - /** - * A function only for backward compatibility - Only makes sense with Screen objects - * - * @return the Region being the current ROI of the containing Screen - */ - public Region getROI() { - return new Region(getScreen().getRect()); - } - - // **************************************************** - /** - * - * @return the region itself - * @deprecated only for backward compatibility - */ - @Deprecated - public Region inside() { - return this; - } - - /** - * set the regions position
this might move the region even to another screen - * - * @param loc new top left corner - * @return the region itself - * @deprecated to be like AWT Rectangle API use setLocation() - */ - @Deprecated - public Region moveTo(Location loc) { - return setLocation(loc); - } - - /** - * set the regions position
this might move the region even to another screen - * - * @param loc new top left corner - * @return the region itself - */ - public Region setLocation(Location loc) { - x = loc.x; - y = loc.y; - initScreen(null); - return this; - } - - /** - * set the regions position/size
this might move the region even to another screen - * - * @param r Region - * @return the region itself - * @deprecated to be like AWT Rectangle API use setRect() instead - */ - @Deprecated - public Region morphTo(Region r) { - return setRect(r); - } - - /** - * resize the region using the given padding values
might be negative - * - * @param l padding on left side - * @param r padding on right side - * @param t padding at top side - * @param b padding at bottom side - * @return the region itself - */ - public Region add(int l, int r, int t, int b) { - x = x - l; - y = y - t; - w = w + l + r; - if (w < 1) { - w = 1; - } - h = h + t + b; - if (h < 1) { - h = 1; - } - initScreen(null); - return this; - } - - /** - * extend the region, so it contains the given region
but only the part inside the current screen - * - * @param r the region to include - * @return the region itself - */ - public Region add(Region r) { - Rectangle rect = getRect(); - rect.add(r.getRect()); - setRect(rect); - initScreen(null); - return this; - } - - /** - * extend the region, so it contains the given point
but only the part inside the current screen - * - * @param loc the point to include - * @return the region itself - */ - public Region add(Location loc) { - Rectangle rect = getRect(); - rect.add(loc.x, loc.y); - setRect(rect); - initScreen(null); - return this; - } - - // ************************************************ - /** - * a find operation saves its match on success in the used region object
unchanged if not successful - * - * @return the Match object from last successful find in this region - */ - public Match getLastMatch() { - return lastMatch; - } - - // ************************************************ - /** - * a searchAll operation saves its matches on success in the used region object
unchanged if not successful - * - * @return a Match-Iterator of matches from last successful searchAll in this region - */ - public Iterator getLastMatches() { - return lastMatches; - } - - // ************************************************ - /** - * get the last image taken on this regions screen - * - * @return the stored ScreenImage - */ - public ScreenImage getLastScreenImage() { - return getScreen().getLastScreenImageFromScreen(); - } - - /** - * stores the lastScreenImage in the current bundle path with a created unique name - * - * @return the absolute file name - * @throws java.io.IOException if not possible - */ - public String getLastScreenImageFile() throws IOException { - return getScreen().getLastScreenImageFile(ImagePath.getBundlePath(), null); - } - - /** - * stores the lastScreenImage in the current bundle path with the given name - * - * @param name file name (.png is added if not there) - * @return the absolute file name - * @throws java.io.IOException if not possible - */ - public String getLastScreenImageFile(String name) throws IOException { - return getScreen().getLastScreenImageFromScreen().getFile(ImagePath.getBundlePath(), name); - } - - /** - * stores the lastScreenImage in the given path with the given name - * - * @param path path to use - * @param name file name (.png is added if not there) - * @return the absolute file name - * @throws java.io.IOException if not possible - */ - public String getLastScreenImageFile(String path, String name) throws IOException { - return getScreen().getLastScreenImageFromScreen().getFile(path, name); - } - - //
- - // - /** - * check if current region contains given region - * - * @param region the other Region - * @return true/false - */ - public boolean contains(Region region) { - return getRect().contains(region.getRect()); - } - - /** - * create a Location object, that can be used as an offset taking the width and hight of this Region - * @return a new Location object with width and height as x and y - */ - public Location asOffset() { - return new Location(w, h); - } - - /** - * create region with same size at top left corner offset - * - * @param loc use its x and y to set the offset - * @return the new region - */ - public Region offset(Location loc) { - return Region.create(x + loc.x, y + loc.y, w, h, scr); - } - - /** - * create region with same size at top left corner offset - * - * @param x horizontal offset - * @param y vertical offset - * @return the new region - */ - public Region offset(int x, int y) { - return Region.create(this.x + x, this.y + y, w, h, scr); - } - - /** - * create a region enlarged Settings.DefaultPadding pixels on each side - * - * @return the new region - * @deprecated to be like AWT Rectangle API use grow() instead - */ - @Deprecated - public Region nearby() { - return grow(Settings.DefaultPadding, Settings.DefaultPadding); - } - - /** - * create a region enlarged range pixels on each side - * - * @param range the margin to be added around - * @return the new region - * @deprecated to be like AWT Rectangle API use grow() instaed - */ - @Deprecated - public Region nearby(int range) { - return grow(range, range); - } - - /** - * create a region enlarged n pixels on each side (n = Settings.DefaultPadding = 50 default) - * - * @return the new region - */ - public Region grow() { - return grow(Settings.DefaultPadding, Settings.DefaultPadding); - } - - /** - * create a region enlarged range pixels on each side - * - * @param range the margin to be added around - * @return the new region - */ - public Region grow(int range) { - return grow(range, range); - } - - /** - * create a region enlarged w pixels on left and right side - * and h pixels at top and bottom - * - * @param w pixels horizontally - * @param h pixels vertically - * @return the new region - */ - public Region grow(int w, int h) { - Rectangle r = getRect(); - r.grow(w, h); - return Region.create(r.x, r.y, r.width, r.height, scr); - } - - /** - * create a region enlarged l pixels on left and r pixels right side - * and t pixels at top side and b pixels a bottom side. - * negative values go inside (shrink) - * - * @param l add to the left - * @param r add to right - * @param t add above - * @param b add beneath - * @return the new region - */ - public Region grow(int l, int r, int t, int b) { - return Region.create(x - l, y - t, w + l + r, h + t + b, scr); - } - - /** - * point middle on right edge - * @return point middle on right edge - */ - public Location rightAt() { - return rightAt(0); - } - - /** - * positive offset goes to the right. - * might be off current screen - * - * @param offset pixels - * @return point with given offset horizontally to middle point on right edge - */ - public Location rightAt(int offset) { - return checkAndSetRemote(new Location(x + w + offset, y + h / 2)); - } - - /** - * create a region right of the right side with same height. - * the new region extends to the right screen border
- * use grow() to include the current region - * - * @return the new region - */ - public Region right() { - int distToRightScreenBorder = getScreen().getX() + getScreen().getW() - (getX() + getW()); - return right(distToRightScreenBorder); - } - - /** - * create a region right of the right side with same height and given width. - * negative width creates the right part with width inside the region
- * use grow() to include the current region - * - * @param width pixels - * @return the new region - */ - public Region right(int width) { - int _x; - if (width < 0) { - _x = x + w + width; - } else { - _x = x + w; - } - return Region.create(_x, y, Math.abs(width), h, scr); - } - - /** - * - * @return point middle on left edge - */ - public Location leftAt() { - return leftAt(0); - } - - /** - * negative offset goes to the left
might be off current screen - * - * @param offset pixels - * @return point with given offset horizontally to middle point on left edge - */ - public Location leftAt(int offset) { - return checkAndSetRemote(new Location(x + offset, y + h / 2)); - } - - /** - * create a region left of the left side with same height
the new region extends to the left screen border
use - * grow() to include the current region - * - * @return the new region - */ - public Region left() { - int distToLeftScreenBorder = getX() - getScreen().getX(); - return left(distToLeftScreenBorder); - } - - /** - * create a region left of the left side with same height and given width
- * negative width creates the left part with width inside the region use grow() to include the current region
- * - * @param width pixels - * @return the new region - */ - public Region left(int width) { - int _x; - if (width < 0) { - _x = x; - } else { - _x = x - width; - } - return Region.create(getScreen().getBounds().intersection(new Rectangle(_x, y, Math.abs(width), h)), scr); - } - - /** - * - * @return point middle on top edge - */ - public Location aboveAt() { - return aboveAt(0); - } - - /** - * negative offset goes towards top of screen
might be off current screen - * - * @param offset pixels - * @return point with given offset vertically to middle point on top edge - */ - public Location aboveAt(int offset) { - return checkAndSetRemote(new Location(x + w / 2, y + offset)); - } - - /** - * create a region above the top side with same width
the new region extends to the top screen border
use - * grow() to include the current region - * - * @return the new region - */ - public Region above() { - int distToAboveScreenBorder = getY() - getScreen().getY(); - return above(distToAboveScreenBorder); - } - - /** - * create a region above the top side with same width and given height
- * negative height creates the top part with height inside the region use grow() to include the current region - * - * @param height pixels - * @return the new region - */ - public Region above(int height) { - int _y; - if (height < 0) { - _y = y; - } else { - _y = y - height; - } - return Region.create(getScreen().getBounds().intersection(new Rectangle(x, _y, w, Math.abs(height))), scr); - } - - /** - * - * @return point middle on bottom edge - */ - public Location belowAt() { - return belowAt(0); - } - - /** - * positive offset goes towards bottom of screen
might be off current screen - * - * @param offset pixels - * @return point with given offset vertically to middle point on bottom edge - */ - public Location belowAt(int offset) { - return checkAndSetRemote(new Location(x + w / 2, y + h - offset)); - } - - /** - * create a region below the bottom side with same width
the new region extends to the bottom screen border
- * use grow() to include the current region - * - * @return the new region - */ - public Region below() { - int distToBelowScreenBorder = getScreen().getY() + getScreen().getH() - (getY() + getH()); - return below(distToBelowScreenBorder); - } - - /** - * create a region below the bottom side with same width and given height
- * negative height creates the bottom part with height inside the region use grow() to include the current region - * - * @param height pixels - * @return the new region - */ - public Region below(int height) { - int _y; - if (height < 0) { - _y = y + h + height; - } else { - _y = y + h; - } - return Region.create(x, _y, w, Math.abs(height), scr); - } - - /** - * create a new region containing both regions - * - * @param ur region to unite with - * @return the new region - */ - public Region union(Region ur) { - Rectangle r = getRect().union(ur.getRect()); - return Region.create(r.x, r.y, r.width, r.height, scr); - } - - /** - * create a region that is the intersection of the given regions - * - * @param ir the region to intersect with like AWT Rectangle API - * @return the new region - */ - public Region intersection(Region ir) { - Rectangle r = getRect().intersection(ir.getRect()); - return Region.create(r.x, r.y, r.width, r.height, scr); - } - - //
- - // - /** - * select the specified part of the region. - * - *
Constants for the top parts of a region (Usage: Region.CONSTANT)
- * shown in brackets: possible shortcuts for the part constant
- * NORTH (NH, TH) - upper half
- * NORTH_WEST (NW, TL) - left third in upper third
- * NORTH_MID (NM, TM) - middle third in upper third
- * NORTH_EAST (NE, TR) - right third in upper third
- * ... similar for the other directions:
- * right side: EAST (Ex, Rx)
- * bottom part: SOUTH (Sx, Bx)
- * left side: WEST (Wx, Lx)
- *
- * specials for quartered:
- * TT top left quarter
- * RR top right quarter
- * BB bottom right quarter
- * LL bottom left quarter
- *
- * specials for the center parts:
- * MID_VERTICAL (MV, CV) half of width vertically centered
- * MID_HORIZONTAL (MH, CH) half of height horizontally centered
- * MID_BIG (M2, C2) half of width / half of height centered
- * MID_THIRD (MM, CC) third of width / third of height centered
- *
- * Based on the scheme behind these constants there is another possible usage:
- * specify part as e 3 digit integer - * where the digits xyz have the following meaning
- * 1st x: use a raster of x rows and x columns
- * 2nd y: the row number of the wanted cell
- * 3rd z: the column number of the wanted cell
- * y and z are counting from 0
- * valid numbers: 200 up to 999 (< 200 are invalid and return the region itself)
- * example: get(522) will use a raster of 5 rows and 5 columns and return the cell in the middle
- * special cases:
- * if either y or z are == or > x: returns the respective row or column
- * example: get(525) will use a raster of 5 rows and 5 columns and return the row in the middle
- *
- * internally this is based on {@link #setRaster(int, int) setRaster} - * and {@link #getCell(int, int) getCell}
- *
- * If you need only one row in one column with x rows or - * only one column in one row with x columns you can use {@link #getRow(int, int) getRow} or {@link #getCol(int, int) getCol} - * @param part the part to get (Region.PART long or short) - * @return new region - */ - public Region get(int part) { - return Region.create(getRectangle(getRect(), part)); - } - - protected static Rectangle getRectangle(Rectangle rect, int part) { - if (part < 200 || part > 999) { - return rect; - } - Region r = Region.create(rect); - int pTyp = (int) (part / 100); - int pPos = part - pTyp * 100; - int pRow = (int) (pPos / 10); - int pCol = pPos - pRow * 10; - r.setRaster(pTyp, pTyp); - if (pTyp == 3) { - // NW = 300, NORTH_WEST = NW; - // NM = 301, NORTH_MID = NM; - // NE = 302, NORTH_EAST = NE; - // EM = 312, EAST_MID = EM; - // SE = 322, SOUTH_EAST = SE; - // SM = 321, SOUTH_MID = SM; - // SW = 320, SOUTH_WEST = SW; - // WM = 310, WEST_MID = WM; - // MM = 311, MIDDLE = MM, M3 = MM; - return r.getCell(pRow, pCol).getRect(); - } - if (pTyp == 2) { - // NH = 202, NORTH = NH; - // EH = 221, EAST = EH; - // SH = 212, SOUTH = SH; - // WH = 220, WEST = WH; - if (pRow > 1) { - return r.getCol(pCol).getRect(); - } else if (pCol > 1) { - return r.getRow(pRow).getRect(); - } - return r.getCell(pRow, pCol).getRect(); - } - if (pTyp == 4) { - // MV = 441, MID_VERTICAL = MV; - // MH = 414, MID_HORIZONTAL = MH; - // M2 = 444, MIDDLE_BIG = M2; - if (pRow > 3) { - if (pCol > 3 ) { - return r.getCell(1, 1).union(r.getCell(2, 2)).getRect(); - } - return r.getCell(0, 1).union(r.getCell(3, 2)).getRect(); - } else if (pCol > 3) { - return r.getCell(1, 0).union(r.getCell(2, 3)).getRect(); - } - return r.getCell(pRow, pCol).getRect(); - } - return rect; - } - - /** - * store info: this region is divided vertically into n even rows
- * a preparation for using getRow() - * - * @param n number of rows - * @return the top row - */ - public Region setRows(int n) { - return setRaster(n, 0); - } - - /** - * store info: this region is divided horizontally into n even columns
- * a preparation for using getCol() - * - * @param n number of columns - * @return the leftmost column - */ - public Region setCols(int n) { - return setRaster(0, n); - } - - /** - * - * @return the number of rows or null - */ - public int getRows() { - return rows; - } - - /** - * - * @return the row height or 0 - */ - public int getRowH() { - return rowH; - } - - /** - * - * @return the number of columns or 0 - */ - public int getCols() { - return cols; - } - - /** - * - * @return the columnwidth or 0 - */ - public int getColW() { - return colW; - } - - /** - * Can be used to check, wether the Region currently has a valid raster - * @return true if it has a valid raster (either getCols or getRows or both would return > 0) - * false otherwise - */ - public boolean isRasterValid() { - return (rows > 0 || cols > 0); - } - - /** - * store info: this region is divided into a raster of even cells
- * a preparation for using getCell()
- * @param r number of rows - * @param c number of columns - * @return the topleft cell - */ - public Region setRaster(int r, int c) { - rows = Math.max(r, h); - cols = Math.max(c, w); - if (r > 0) { - rowH = (int) (h / r); - rowHd = h - r * rowH; - } - if (c > 0) { - colW = (int) (w / c); - colWd = w - c * colW; - } - return getCell(0, 0); - } - - /** - * get the specified row counting from 0, if rows or raster are setup negative counts reverse from the end (last = -1) - * values outside range are 0 or last respectively - * - * @param r row number - * @return the row as new region or the region itself, if no rows are setup - */ - public Region getRow(int r) { - if (rows == 0) { - return this; - } - if (r < 0) { - r = rows + r; - } - r = Math.max(0, r); - r = Math.min(r, rows - 1); - return Region.create(x, y + r * rowH, w, rowH); - } - - public Region getRow(int r, int n) { - return this; - } - - /** - * get the specified column counting from 0, if columns or raster are setup negative counts reverse from the end (last - * = -1) values outside range are 0 or last respectively - * - * @param c column number - * @return the column as new region or the region itself, if no columns are setup - */ - public Region getCol(int c) { - if (cols == 0) { - return this; - } - if (c < 0) { - c = cols + c; - } - c = Math.max(0, c); - c = Math.min(c, cols - 1); - return Region.create(x + c * colW, y, colW, h); - } - - /** - * divide the region in n columns and select column c as new Region - * @param c the column to select counting from 0 or negative to count from the end - * @param n how many columns to devide in - * @return the selected part or the region itself, if parameters are invalid - */ - public Region getCol(int c, int n) { - Region r = new Region(this); - r.setCols(n); - return r.getCol(c); - } - - - /** - * get the specified cell counting from (0, 0), if a raster is setup
- * negative counts reverse from the end (last = -1) values outside range are 0 or last respectively - * - * @param r row number - * @param c column number - * @return the cell as new region or the region itself, if no raster is setup - */ - public Region getCell(int r, int c) { - if (rows == 0) { - return getCol(c); - } - if (cols == 0) { - return getRow(r); - } - if (rows == 0 && cols == 0) { - return this; - } - if (r < 0) { - r = rows - r; - } - if (c < 0) { - c = cols - c; - } - r = Math.max(0, r); - r = Math.min(r, rows - 1); - c = Math.max(0, c); - c = Math.min(c, cols - 1); - return Region.create(x + c * colW, y + r * rowH, colW, rowH); - } -//
- - // - protected void updateSelf() { - if (overlay != null) { - highlight(false, null); - highlight(true, null); - } - } - - protected Region silentHighlight(boolean onOff) { - if (onOff && overlay == null) { - return doHighlight(true, null, true); - } - if (!onOff && overlay != null) { - return doHighlight(true, null, true); - } - return this; - } - - /** - * Toggle the regions Highlight visibility (red frame) - * - * @return the region itself - */ - public Region highlight() { - // Pass true if overlay is null, false otherwise - highlight(overlay == null, null); - return this; - } - - /** - * Toggle the regions Highlight visibility (frame of specified color)
- * allowed color specifications for frame color:
- * - a color name out of: black, blue, cyan, gray, green, magenta, orange, pink, red, white, yellow - * (lowercase and uppercase can be mixed, internally transformed to all uppercase)
- * - these colornames exactly written: lightGray, LIGHT_GRAY, darkGray and DARK_GRAY
- * - a hex value like in HTML: #XXXXXX (max 6 hex digits) - * - an RGB specification as: #rrrgggbbb where rrr, ggg, bbb are integer values in range 0 - 255 - * padded with leading zeros if needed (hence exactly 9 digits) - * @param color Color of frame - * @return the region itself - */ - public Region highlight(String color) { - // Pass true if overlay is null, false otherwise - highlight(overlay == null, color); - return this; - } - - /** - * Sets the regions Highlighting border - * - * @param toEnable set overlay enabled or disabled - * @param color Color of frame (see method highlight(color)) - */ - private Region highlight(boolean toEnable, String color) { - return doHighlight(toEnable, color, false); - } - - private Region doHighlight(boolean toEnable, String color, boolean silent) { - if (isOtherScreen()) { - return this; - } - if (!silent) { - Debug.action("toggle highlight " + toString() + ": " + toEnable + - (color != null ? " color: " + color : "")); - } - if (toEnable) { - overlay = new ScreenHighlighter(getScreen(), color); - overlay.highlight(this); - } else { - if (overlay != null) { - overlay.close(); - overlay = null; - } - } - return this; - } - - - /** - * show the regions Highlight for the given time in seconds (red frame) - * if 0 - use the global Settings.SlowMotionDelay - * - * @param secs time in seconds - * @return the region itself - */ - public Region highlight(float secs) { - return highlight(secs, null); - } - - /** - * show the regions Highlight for the given time in seconds (frame of specified color) - * if 0 - use the global Settings.SlowMotionDelay - * - * @param secs time in seconds - * @param color Color of frame (see method highlight(color)) - * @return the region itself - */ - public Region highlight(float secs, String color) { - if (isOtherScreen()) { - return this; - } - if (secs < 0.1) { - return highlight((int) secs, color); - } - Debug.action("highlight " + toString() + " for " + secs + " secs" + - (color != null ? " color: " + color : "")); - ScreenHighlighter _overlay = new ScreenHighlighter(getScreen(), color); - _overlay.highlight(this, secs); - return this; - } - - /** - * hack to implement the getLastMatch() convenience 0 means same as highlight() < 0 same as highlight(secs) if - * available the last match is highlighted - * - * @param secs seconds - * @return this region - */ - public Region highlight(int secs) { - return highlight(secs, null); - } - - - /** - * Show highlight in selected color - * - * @param secs time in seconds - * @param color Color of frame (see method highlight(color)) - * @return this region - */ - public Region highlight(int secs, String color) { - if (isOtherScreen()) { - return this; - } - if (secs > 0) { - return highlight((float) secs, color); - } - if (lastMatch != null) { - if (secs < 0) { - return lastMatch.highlight((float) -secs, color); - } - return lastMatch.highlight(Settings.DefaultHighlightTime, color); - } - return this; - } - //
- - // - /** - * WARNING: wait(long timeout) is taken by Java Object as final. This method catches any interruptedExceptions - * - * @param timeout The time to wait - */ - public void wait(double timeout) { - try { - Thread.sleep((long) (timeout * 1000L)); - } catch (InterruptedException e) { - e.printStackTrace(); - } - } - - /** - * Returns the image of the given Pattern, String or Image - * - * @param target The Pattern, String or Image - * @return the Image - */ - private Image getImage(PSI target) { - if (target instanceof Pattern) { - return ((Pattern) target).getImage(); - } else if (target instanceof String) { - return Image.get((String) target); - } else if (target instanceof Image) { - return (Image) target; - } else { - return null; - } - } - - /** - * return false to skip
- * return true to try again
- * throw FindFailed to abort - * - * @param target Handles a failed find action - * @throws FindFailed - */ - private boolean handleFindFailed(PSI target) throws FindFailed { - return handleFindFailedShowDialog(target, false); - } - - private boolean handleFindFailedQuietly(PSI target) { - try { - return handleFindFailedShowDialog(target, false); - } catch (FindFailed ex) { - } - return false; - } - - private boolean handleFindFailedImageMissing(PSI target) { - boolean shouldHandle = false; - try { - shouldHandle = handleFindFailedShowDialog(target, true); - } catch (FindFailed ex) { - return false; - } - if (!shouldHandle) { - return false; - } - getRobotForRegion().delay(500); - ScreenImage img = getScreen().userCapture("capture missing image"); - if (img != null) { - String path = ImagePath.getBundlePath(); - if (path == null) { - return false; - } - String imgName = (String) target; - img.getFile(path, imgName); - return true; - } - return false; - } - - private boolean handleFindFailedShowDialog(Object target, boolean shouldCapture) throws FindFailed { - FindFailedResponse response; - if (findFailedResponse == FindFailedResponse.PROMPT) { - FindFailedDialog fd = new FindFailedDialog(target, shouldCapture); - fd.setVisible(true); - response = fd.getResponse(); - fd.dispose(); - wait(0.5); - } else { - response = findFailedResponse; - } - if (response == FindFailedResponse.SKIP) { - return false; - } else if (response == FindFailedResponse.RETRY) { - return true; - } else if (response == FindFailedResponse.ABORT) { - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - throw new FindFailed(String.format("can not find %s in %s", targetStr, this.toStringShort())); - } - return false; - } - - /** - * finds the given Pattern, String or Image in the region and returns the best match. If AutoWaitTimeout - * is set, this is equivalent to wait(). Otherwise only one search attempt will be done. - * - * @param Pattern, String or Image - * @param target A search criteria - * @return If found, the element. null otherwise - * @throws FindFailed if the Find operation failed - */ - public Match find(PSI target) throws FindFailed { - if (autoWaitTimeout > 0) { - return wait(target, autoWaitTimeout); - } - lastMatch = null; - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - while (true) { - try { - log(3, "find: waiting 0 secs for %s to appear in %s", targetStr, this.toStringShort()); - lastMatch = doFind(target, null); - } catch (IOException ex) { - if (ex instanceof IOException) { - if (handleFindFailedImageMissing(target)) { - continue; - } - } - throw new FindFailed(ex.getMessage()); - } - if (lastMatch != null) { - Image img = getImage(target); - lastMatch.setImage(img); - if (img != null) { - img.setLastSeen(lastMatch.getRect(), lastMatch.getScore()); - } - log(lvl, "find: %s has appeared \nat %s", targetStr, lastMatch); - return lastMatch; - } - log(3, "find: %s has not appeared [%d msec]", targetStr, lastFindTime); - if (!handleFindFailed(target)) { - return null; - } - } - } - - /** - * finds all occurences of the given Pattern, String or Image in the region and returns an Iterator of Matches. - * - * - * @param Pattern, String or Image - * @param target A search criteria - * @return All elements matching - * @throws FindFailed if the Find operation failed - */ - public Iterator findAll(PSI target) throws FindFailed { - lastMatches = null; - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - while (true) { - try { - if (autoWaitTimeout > 0) { - RepeatableFindAll rf = new RepeatableFindAll(target); - rf.repeat(autoWaitTimeout); - lastMatches = rf.getMatches(); - } else { - lastMatches = doFindAll(target, null); - } - } catch (Exception ex) { - if (ex instanceof IOException) { - if (handleFindFailedImageMissing(target)) { - continue; - } - } - throw new FindFailed(ex.getMessage()); - } - if (lastMatches != null) { - return lastMatches; - } - if (!handleFindFailed(target)) { - return null; - } - } - } - - public Match[] findAllByRow(PSI target) { - Match[] matches = new Match[0]; - List mList = findAllCollect(target); - if (mList.isEmpty()) { - return null; - } - Collections.sort(mList, new Comparator() { - @Override - public int compare(Match m1, Match m2) { - if (m1.y == m2.y) { - return m1.x - m2.x; - } - return m1.y - m2.y; - } - }); - return mList.toArray(matches); - } - - public Match[] findAllByColumn(PSI target) { - Match[] matches = new Match[0]; - List mList = findAllCollect(target); - if (mList.isEmpty()) { - return null; - } - Collections.sort(mList, new Comparator() { - @Override - public int compare(Match m1, Match m2) { - if (m1.x == m2.x) { - return m1.y - m2.y; - } - return m1.x - m2.x; - } - }); - return mList.toArray(matches); - } - - private List findAllCollect(PSI target) { - Iterator mIter = null; - try { - mIter = findAll(target); - } catch (Exception ex) { - Debug.error("findAllByRow: %s", ex.getMessage()); - return null; - } - List mList = new ArrayList(); - while (mIter.hasNext()) { - mList.add(mIter.next()); - } - return mList; - } - - public Match findBest(Object... args) { - Debug.log(lvl, "findBest: enter"); - Match mResult = null; - List mList = findAnyCollect(args); - if (mList != null) { - Collections.sort(mList, new Comparator() { - @Override - public int compare(Match m1, Match m2) { - double ms = m2.getScore() - m1.getScore(); - if (ms < 0) { - return -1; - } else if (ms > 0) { - return 1; - } - return 0; - } - }); - mResult = mList.get(0); - } - return mResult; - } - - private List findAnyCollect(Object... args) { - if (args == null) return null; - List mList = new ArrayList(); - Match[] mArray = new Match[args.length]; - SubFindRun[] theSubs = new SubFindRun[args.length]; - int nobj = 0; - ScreenImage base = getScreen().capture(this); - for (Object obj : args) { - mArray[nobj] = null; - if (obj instanceof Pattern || obj instanceof String || obj instanceof Image) { - theSubs[nobj] = new SubFindRun(mArray, nobj, base, obj, this); - new Thread(theSubs[nobj]).start(); - } - nobj++; - } - Debug.log(lvl, "findAnyCollect: waiting for SubFindRuns"); - nobj = 0; - boolean all = false; - while (!all) { - all = true; - for (SubFindRun sub : theSubs) { - all &= sub.hasFinished(); - } - } - Debug.log(lvl, "findAnyCollect: SubFindRuns finished"); - nobj = 0; - for (Match match : mArray) { - if (match != null) { - match.setIndex(nobj); - mList.add(match); - } else { - } - nobj++; - } - return mList; - } - - private class SubFindRun implements Runnable { - - Match[] mArray; - ScreenImage base; - Object target; - Region reg; - boolean finished = false; - int subN; - - public SubFindRun(Match[] pMArray, int pSubN, - ScreenImage pBase, Object pTarget, Region pReg) { - subN = pSubN; - base = pBase; - target = pTarget; - reg = pReg; - mArray = pMArray; - } - - @Override - public void run() { - try { - mArray[subN] = reg.findInImage(base, target); - } catch (Exception ex) { - log(-1, "findAnyCollect: image file not found:\n", target); - } - hasFinished(true); - } - - public boolean hasFinished() { - return hasFinished(false); - } - - public synchronized boolean hasFinished(boolean state) { - if (state) { - finished = true; - } - return finished; - } - } - - private Match findInImage(ScreenImage base, Object target) throws IOException { - Finder finder = null; - Match match = null; - boolean findingText = false; - Image img = null; - if (target instanceof String) { - if (((String) target).startsWith("\t") && ((String) target).endsWith("\t")) { - findingText = true; - } else { - img = Image.create((String) target); - if (img.isValid()) { - finder = doCheckLastSeenAndCreateFinder(base, img, 0.0, null); - if (!finder.hasNext()) { - runFinder(finder, img); - } - } else if (img.isText()) { - findingText = true; - } else { - throw new IOException("Region: findInImage: Image not loadable: " + target.toString()); - } - } - if (findingText) { - if (TextRecognizer.getInstance() != null) { - log(lvl, "findInImage: Switching to TextSearch"); - finder = new Finder(getScreen().capture(x, y, w, h), this); - finder.findText((String) target); - } - } - } else if (target instanceof Pattern) { - if (((Pattern) target).isValid()) { - img = ((Pattern) target).getImage(); - finder = doCheckLastSeenAndCreateFinder(base, img, 0.0, (Pattern) target); - if (!finder.hasNext()) { - runFinder(finder, target); - } - } else { - throw new IOException("Region: findInImage: Image not loadable: " + target.toString()); - } - } else if (target instanceof Image) { - if (((Image) target).isValid()) { - img = ((Image) target); - finder = doCheckLastSeenAndCreateFinder(base, img, 0.0, null); - if (!finder.hasNext()) { - runFinder(finder, img); - } - } else { - throw new IOException("Region: findInImage: Image not loadable: " + target.toString()); - } - } else { - log(-1, "findInImage: invalid parameter: %s", target); - return null; - } - if (finder.hasNext()) { - match = finder.next(); - match.setImage(img); - img.setLastSeen(match.getRect(), match.getScore()); - } - return match; - } - - /** - * Waits for the Pattern, String or Image to appear until the AutoWaitTimeout value is exceeded. - * - * @param Pattern, String or Image - * @param target The target to search for - * @return The found Match - * @throws FindFailed if the Find operation finally failed - */ - public Match wait(PSI target) throws FindFailed { - if (target instanceof Float || target instanceof Double) { - wait(0.0 + ((Double) target)); - return null; - } - return wait(target, autoWaitTimeout); - } - - /** - * Waits for the Pattern, String or Image to appear or timeout (in second) is passed - * - * @param Pattern, String or Image - * @param target The target to search for - * @param timeout Timeout in seconds - * @return The found Match - * @throws FindFailed if the Find operation finally failed - */ - public Match wait(PSI target, double timeout) throws FindFailed { - RepeatableFind rf; - lastMatch = null; - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - while (true) { - try { - log(3, "find: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort()); - rf = new RepeatableFind(target); - rf.repeat(timeout); - lastMatch = rf.getMatch(); - } catch (Exception ex) { - if (ex instanceof IOException) { - if (handleFindFailedImageMissing(target)) { - continue; - } - } - throw new FindFailed(ex.getMessage()); - } - if (lastMatch != null) { - lastMatch.setImage(rf._image); - if (rf._image != null) { - rf._image.setLastSeen(lastMatch.getRect(), lastMatch.getScore()); - } - log(lvl, "find: %s has appeared \nat %s", targetStr, lastMatch); - break; - } - log(3, "find: %s has not appeared [%d msec]", targetStr, lastFindTime); - if (!handleFindFailed(target)) { - return null; - } - } - return lastMatch; - } - -//TODO 1.2.0 Region.compare as time optimized Region.exists - /** - * time optimized Region.exists, when image-size == region-size
- * 1.1.x: just using exists(img, 0), sizes not checked - * @param img image file name - * @return the match or null if not equal - */ - public Match compare(String img) { - return compare(Image.create(img)); - } - - /** - * time optimized Region.exists, when image-size == region-size
- * 1.1.x: just using exists(img, 0), sizes not checked - * @param img Image object - * @return the match or null if not equal - */ - public Match compare(Image img) { - return exists(img, 0); - } - - /** - * Check if target exists (with the default autoWaitTimeout) - * - * @param Pattern, String or Image - * @param target Pattern, String or Image - * @return the match (null if not found or image file missing) - */ - public Match exists(PSI target) { - return exists(target, autoWaitTimeout); - } - - /** - * Check if target exists with a specified timeout
- * timout = 0: returns immediately after first search - * - * @param Pattern, String or Image - * @param target The target to search for - * @param timeout Timeout in seconds - * @return the match (null if not found or image file missing) - */ - public Match exists(PSI target, double timeout) { - lastMatch = null; - String targetStr = target.toString(); - if (target instanceof String) { - targetStr = targetStr.trim(); - } - while (true) { - try { - log(3, "exists: waiting %.1f secs for %s to appear in %s", timeout, targetStr, this.toStringShort()); - RepeatableFind rf = new RepeatableFind(target); - if (rf.repeat(timeout)) { - lastMatch = rf.getMatch(); - Image img = rf._image; - lastMatch.setImage(img); - if (img != null) { - img.setLastSeen(lastMatch.getRect(), lastMatch.getScore()); - } - log(lvl, "exists: %s has appeared \nat %s", targetStr, lastMatch); - return lastMatch; - } else { - if (!handleFindFailedQuietly(target)) { - break; - } - } - } catch (Exception ex) { - if (ex instanceof IOException) { - if (!handleFindFailedImageMissing(target)) { - break; - } - } - } - } - log(3, "exists: %s has not appeared [%d msec]", targetStr, lastFindTime); - return null; - } - - /** - * Use findText() instead of find() in cases where the given string could be misinterpreted as an image filename - * - * @param text text - * @param timeout time - * @return the matched region containing the text - * @throws org.sikuli.script.FindFailed if not found - */ - public Match findText(String text, double timeout) throws FindFailed { - // the leading/trailing tab is used to internally switch to text search directly - return wait("\t" + text + "\t", timeout); - } - - /** - * Use findText() instead of find() in cases where the given string could be misinterpreted as an image filename - * - * @param text text - * @return the matched region containing the text - * @throws org.sikuli.script.FindFailed if not found - */ - public Match findText(String text) throws FindFailed { - return findText(text, autoWaitTimeout); - } - - /** - * Use findAllText() instead of findAll() in cases where the given string could be misinterpreted as an image filename - * - * @param text text - * @return the matched region containing the text - * @throws org.sikuli.script.FindFailed if not found - */ - public Iterator findAllText(String text) throws FindFailed { - // the leading/trailing tab is used to internally switch to text search directly - return findAll("\t" + text + "\t"); - } - - /** - * waits until target vanishes or timeout (in seconds) is - * passed (AutoWaitTimeout) - * - * @param Pattern, String or Image - * @param target The target to wait for it to vanish - * @return true if the target vanishes, otherwise returns false. - */ - public boolean waitVanish(PSI target) { - return waitVanish(target, autoWaitTimeout); - } - - /** - * waits until target vanishes or timeout (in seconds) is - * passed - * - * @param Pattern, String or Image - * @param target Pattern, String or Image - * @param timeout time in seconds - * @return true if target vanishes, false otherwise and if imagefile is missing. - */ - public boolean waitVanish(PSI target, double timeout) { - while (true) { - try { - log(lvl, "waiting for " + target + " to vanish"); - RepeatableVanish r = new RepeatableVanish(target); - if (r.repeat(timeout)) { - log(lvl, "" + target + " has vanished"); - return true; - } - log(lvl, "" + target + " has not vanished before timeout"); - return false; - } catch (Exception ex) { - if (ex instanceof IOException) { - if (handleFindFailedImageMissing(target)) { - continue; - } - } - break; - } - } - return false; - } - //
- - // - /** - * Match doFind( Pattern/String/Image ) finds the given pattern on the screen and returns the best match without - * waiting. - */ - private Match doFind(PSI ptn, RepeatableFind repeating) throws IOException { - Finder f = null; - Match m = null; - IScreen s = null; - boolean findingText = false; - lastFindTime = (new Date()).getTime(); - ScreenImage simg; - if (repeating != null && repeating._finder != null) { - simg = getScreen().capture(this); - f = repeating._finder; - f.setScreenImage(simg); - f.setRepeating(); - if (Settings.FindProfiling) { - Debug.logp("[FindProfiling] Region.doFind repeat: %d msec", - new Date().getTime() - lastSearchTimeRepeat); - } - lastSearchTime = (new Date()).getTime(); - f.findRepeat(); - } else { - s = getScreen(); - Image img = null; - if (ptn instanceof String) { - if (((String) ptn).startsWith("\t") && ((String) ptn).endsWith("\t")) { - findingText = true; - } else { - img = Image.create((String) ptn); - if (img.isValid()) { - lastSearchTime = (new Date()).getTime(); - f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), null); - if (!f.hasNext()) { - runFinder(f, img); - //f.find(img); - } - } else if (img.isText()) { - findingText = true; - } else { - throw new IOException("Region: doFind: Image not loadable: " + ptn.toString()); - } - } - if (findingText) { - if (TextRecognizer.getInstance() != null) { - log(lvl, "doFind: Switching to TextSearch"); - f = new Finder(getScreen().capture(x, y, w, h), this); - lastSearchTime = (new Date()).getTime(); - f.findText((String) ptn); - } - } - } else if (ptn instanceof Pattern) { - if (((Pattern) ptn).isValid()) { - img = ((Pattern) ptn).getImage(); - lastSearchTime = (new Date()).getTime(); - f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), (Pattern) ptn); - if (!f.hasNext()) { - runFinder(f, ptn); - //f.find((Pattern) ptn); - } - } else { - throw new IOException("Region: doFind: Image not loadable: " + ptn.toString()); - } - } else if (ptn instanceof Image) { - if (((Image) ptn).isValid()) { - img = ((Image) ptn); - lastSearchTime = (new Date()).getTime(); - f = checkLastSeenAndCreateFinder(img, repeating.getFindTimeOut(), null); - if (!f.hasNext()) { - runFinder(f, img); - //f.find(img); - } - } else { - throw new IOException("Region: doFind: Image not loadable: " + ptn.toString()); - } - } else { - log(-1, "doFind: invalid parameter: %s", ptn); - Sikulix.terminate(999); - } - if (repeating != null) { - repeating._finder = f; - repeating._image = img; - } - } - lastSearchTimeRepeat = lastSearchTime; - lastSearchTime = (new Date()).getTime() - lastSearchTime; - lastFindTime = (new Date()).getTime() - lastFindTime; - if (f.hasNext()) { - m = f.next(); - m.setTimes(lastFindTime, lastSearchTime); - if (Settings.FindProfiling) { - Debug.logp("[FindProfiling] Region.doFind final: %d msec", lastSearchTime); - } - } - return m; - } - - private void runFinder(Finder f, Object target) { - if (Debug.shouldHighlight()) { - if (this.scr.getW() > w + 20 && this.scr.getH() > h + 20) - highlight(2, "#000255000"); - } - if (target instanceof Image) { - f.find((Image) target); - } else if (target instanceof Pattern) { - f.find((Pattern) target); - } - } - - private Finder checkLastSeenAndCreateFinder(Image img, double findTimeout, Pattern ptn) { - return doCheckLastSeenAndCreateFinder(null, img, findTimeout, ptn); - } - - private Finder doCheckLastSeenAndCreateFinder(ScreenImage base, Image img, double findTimeout, Pattern ptn) { - if (base == null) { - base = getScreen().capture(this); - } - if (!Settings.UseImageFinder && Settings.CheckLastSeen && null != img.getLastSeen()) { - Region r = Region.create(img.getLastSeen()); - float score = (float) (img.getLastSeenScore() - 0.01); - if (this.contains(r)) { - Finder f = null; - if (this.scr instanceof VNCScreen) { - f = new Finder(new VNCScreen().capture(r), r); - } else { - f = new Finder(base.getSub(r.getRect()), r); - if (Debug.shouldHighlight()) { - if (this.scr.getW() > w + 10 && this.scr.getH() > h + 10) - highlight(2, "#000255000"); - } - } - if (ptn == null) { - f.find(new Pattern(img).similar(score)); - } else { - f.find(new Pattern(ptn).similar(score)); - } - if (f.hasNext()) { - log(lvl, "checkLastSeen: still there"); - return f; - } - log(lvl, "checkLastSeen: not there"); - } - } - if (Settings.UseImageFinder) { - ImageFinder f = new ImageFinder(this); - f.setFindTimeout(findTimeout); - return f; - } else { - return new Finder(base, this); - } - } - - public void saveLastScreenImage() { - ScreenImage simg = getScreen().getLastScreenImageFromScreen(); - if (simg != null) { - simg.saveLastScreenImage(runTime.fSikulixStore); - } - } - - - /** - * Match findAllNow( Pattern/String/Image ) finds all the given pattern on the screen and returns the best matches - * without waiting. - */ - private Iterator doFindAll(PSI ptn, RepeatableFindAll repeating) throws IOException { - boolean findingText = false; - Finder f; - ScreenImage simg = getScreen().capture(x, y, w, h); - if (repeating != null && repeating._finder != null) { - f = repeating._finder; - f.setScreenImage(simg); - f.setRepeating(); - f.findAllRepeat(); - } else { - f = new Finder(simg, this); - Image img = null; - if (ptn instanceof String) { - if (((String) ptn).startsWith("\t") && ((String) ptn).endsWith("\t")) { - findingText = true; - } else { - img = Image.create((String) ptn); - if (img.isValid()) { - f.findAll(img); - } else if (img.isText()) { - findingText = true; - } else { - throw new IOException("Region: doFind: Image not loadable: " + (String) ptn); - } - } - if (findingText) { - if (TextRecognizer.getInstance() != null) { - log(lvl, "doFindAll: Switching to TextSearch"); - f.findAllText((String) ptn); - } - } - } else if (ptn instanceof Pattern) { - if (((Pattern) ptn).isValid()) { - img = ((Pattern) ptn).getImage(); - f.findAll((Pattern) ptn); - } else { - throw new IOException("Region: doFind: Image not loadable: " + (String) ptn); - } - } else if (ptn instanceof Image) { - if (((Image) ptn).isValid()) { - img = ((Image) ptn); - f.findAll((Image) ptn); - } else { - throw new IOException("Region: doFind: Image not loadable: " + (String) ptn); - } - } else { - log(-1, "doFind: invalid parameter: %s", ptn); - Sikulix.terminate(999); - } - if (repeating != null) { - repeating._finder = f; - repeating._image = img; - } - } - if (f.hasNext()) { - return f; - } - return null; - } - - // Repeatable Find //////////////////////////////// - private abstract class Repeatable { - - private double findTimeout; - - abstract void run() throws Exception; - - abstract boolean ifSuccessful(); - - double getFindTimeOut() { - return findTimeout; - } - - // return TRUE if successful before timeout - // return FALSE if otherwise - // throws Exception if any unexpected error occurs - boolean repeat(double timeout) throws Exception { - findTimeout = timeout; - int MaxTimePerScan = (int) (1000.0 / waitScanRate); - int timeoutMilli = (int) (timeout * 1000); - long begin_t = (new Date()).getTime(); - do { - long before_find = (new Date()).getTime(); - run(); - if (ifSuccessful()) { - return true; - } else if (timeoutMilli < MaxTimePerScan || Settings.UseImageFinder) { - // instant return on first search failed if timeout very small or 0 - // or when using new ImageFinder - return false; - } - long after_find = (new Date()).getTime(); - if (after_find - before_find < MaxTimePerScan) { - getRobotForRegion().delay((int) (MaxTimePerScan - (after_find - before_find))); - } else { - getRobotForRegion().delay(10); - } - } while (begin_t + timeout * 1000 > (new Date()).getTime()); - return false; - } - } - - private class RepeatableFind extends Repeatable { - - Object _target; - Match _match = null; - Finder _finder = null; - Image _image = null; - - public RepeatableFind(PSI target) { - _target = target; - } - - public Match getMatch() { - if (_finder != null) { - _finder.destroy(); - } - return (_match == null) ? _match : new Match(_match); - } - - @Override - public void run() throws IOException { - _match = doFind(_target, this); - } - - @Override - boolean ifSuccessful() { - return _match != null; - } - } - - private class RepeatableVanish extends RepeatableFind { - - public RepeatableVanish(PSI target) { - super(target); - } - - @Override - boolean ifSuccessful() { - return _match == null; - } - } - - private class RepeatableFindAll extends Repeatable { - - Object _target; - Iterator _matches = null; - Finder _finder = null; - Image _image = null; - - public RepeatableFindAll(PSI target) { - _target = target; - } - - public Iterator getMatches() { - return _matches; - } - - @Override - public void run() throws IOException { - _matches = doFindAll(_target, this); - } - - @Override - boolean ifSuccessful() { - return _matches != null; - } - } - // - - // -// private Region getRegionFromTarget(PatternStringRegionMatch target) throws FindFailed { -// if (target instanceof Pattern || target instanceof String || target instanceof Image) { -// Match m = find(target); -// if (m != null) { -// return m.setScreen(scr); -// } -// return null; -// } -// if (target instanceof Region) { -// return ((Region) target).setScreen(scr); -// } -// return null; -// } - - private Location getLocationFromTarget(PSIMRL target) throws FindFailed { - if (target instanceof Pattern || target instanceof String || target instanceof Image) { - Match m = find(target); - if (m != null) { - if (isOtherScreen()) { - return m.getTarget().setOtherScreen(scr); - } else { - return m.getTarget(); - } - } - return null; - } - if (target instanceof Match) { - return ((Match) target).getTarget(); - } - if (target instanceof Region) { - return ((Region) target).getCenter(); - } - if (target instanceof Location) { - return new Location((Location) target); - } - return null; - } - // - - // - - protected Observer getObserver() { - if (regionObserver == null) { - regionObserver = new Observer(this); - } - return regionObserver; - } - - /** - * evaluate if at least one event observer is defined for this region (the observer need not be running) - * @return true, if the region has an observer with event observers - */ - public boolean hasObserver() { - if (regionObserver != null) { - return regionObserver.hasObservers(); - } - return false; - } - - /** - * - * @return true if an observer is running for this region - */ - public boolean isObserving() { - return observing; - } - - /** - * - * @return true if any events have happened for this region, false otherwise - */ - public boolean hasEvents() { - return Observing.hasEvents(this); - } - - /** - * the region's events are removed from the list - * @return the region's happened events as array if any (size might be 0) - */ - public ObserveEvent[] getEvents() { - return Observing.getEvents(this); - } - - /** - * the event is removed from the list - * @param name event's name - * @return the named event if happened otherwise null - */ - public ObserveEvent getEvent(String name) { - return Observing.getEvent(name); - } - - /** - * set the observer with the given name inactive (not checked while observing) - * @param name observers name - */ - public void setInactive(String name) { - if (!hasObserver()) { - return; - } - Observing.setActive(name, false); - } - - /** - * set the observer with the given name active (not checked while observing) - * @param name observers name - */ - public void setActive(String name) { - if (!hasObserver()) { - return; - } - Observing.setActive(name, true); - } - - /** - * a subsequently started observer in this region should wait for target - * and notify the given observer about this event
- * for details about the observe event handler: {@link ObserverCallBack}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
- * @param Pattern, String or Image - * @param target Pattern, String or Image - * @param observer ObserverCallBack - * @return the event's name - */ - public String onAppear(PSI target, Object observer) { - return onEvent(target, observer, ObserveEvent.Type.APPEAR); - } - - /** - * a subsequently started observer in this region should wait for target - * success and details about the event can be obtained using @{link Observing}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
- * @param Pattern, String or Image - * @param target Pattern, String or Image - * @return the event's name - */ - public String onAppear(PSI target) { - return onEvent(target, null, ObserveEvent.Type.APPEAR); - } - - private String onEvent(PSIC targetThreshhold, Object observer, ObserveEvent.Type obsType) { - if (observer != null && (observer.getClass().getName().contains("org.python") || - observer.getClass().getName().contains("org.jruby"))) { - observer = new ObserverCallBack(observer, obsType); - } - String name = Observing.add(this, (ObserverCallBack) observer, obsType, targetThreshhold); - log(lvl, "%s: observer %s %s: %s with: %s", toStringShort(), obsType, - (observer == null ? "" : " with callback"), name, targetThreshhold); - return name; - } - - /** - * a subsequently started observer in this region should wait for the target to vanish - * and notify the given observer about this event
- * for details about the observe event handler: {@link ObserverCallBack}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
- * @param Pattern, String or Image - * @param target Pattern, String or Image - * @param observer ObserverCallBack - * @return the event's name - */ - public String onVanish(PSI target, Object observer) { - return onEvent(target, observer, ObserveEvent.Type.VANISH); - } - - /** - * a subsequently started observer in this region should wait for the target to vanish - * success and details about the event can be obtained using @{link Observing}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent}
- * @param Pattern, String or Image - * @param target Pattern, String or Image - * @return the event's name - */ - public String onVanish(PSI target) { - return onEvent(target, null, ObserveEvent.Type.VANISH); - } - - /** - * a subsequently started observer in this region should wait for changes in the region - * and notify the given observer about this event - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param threshold minimum size of changes (rectangle threshhold x threshold) - * @param observer ObserverCallBack - * @return the event's name - */ - public String onChange(int threshold, Object observer) { - return onEvent( (threshold > 0 ? threshold : Settings.ObserveMinChangedPixels), - observer, ObserveEvent.Type.CHANGE); - } - - /** - * a subsequently started observer in this region should wait for changes in the region - * success and details about the event can be obtained using @{link Observing}
- * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param threshold minimum size of changes (rectangle threshhold x threshold) - * @return the event's name - */ - public String onChange(int threshold) { - return onEvent( (threshold > 0 ? threshold : Settings.ObserveMinChangedPixels), - null, ObserveEvent.Type.CHANGE); - } - - /** - * a subsequently started observer in this region should wait for changes in the region - * and notify the given observer about this event
- * minimum size of changes used: Settings.ObserveMinChangedPixels - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param observer ObserverCallBack - * @return the event's name - */ - public String onChange(Object observer) { - return onEvent(Settings.ObserveMinChangedPixels, observer, ObserveEvent.Type.CHANGE); - } - - /** - * a subsequently started observer in this region should wait for changes in the region - * success and details about the event can be obtained using @{link Observing}
- * minimum size of changes used: Settings.ObserveMinChangedPixels - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @return the event's name - */ - public String onChange() { - return onEvent(Settings.ObserveMinChangedPixels, null, ObserveEvent.Type.CHANGE); - } - -// -// /** -// *INTERNAL USE ONLY: for use with scripting API bridges -// * @param Pattern, String or Image -// * @param target Pattern, String or Image -// * @param observer ObserverCallBack -// * @return the event's name -// */ -// public String onAppearJ(PSI target, Object observer) { -// return onEvent(target, observer, ObserveEvent.Type.APPEAR); -// } -// -// /** -// *INTERNAL USE ONLY: for use with scripting API bridges -// * @param Pattern, String or Image -// * @param target Pattern, String or Image -// * @param observer ObserverCallBack -// * @return the event's name -// */ -// public String onVanishJ(PSI target, Object observer) { -// return onEvent(target, observer, ObserveEvent.Type.VANISH); -// } -// -// /** -// *INTERNAL USE ONLY: for use with scripting API bridges -// * @param threshold min pixel size - 0 = ObserveMinChangedPixels -// * @param observer ObserverCallBack -// * @return the event's name -// */ -// public String onChangeJ(int threshold, Object observer) { -// return onEvent( (threshold > 0 ? threshold : Settings.ObserveMinChangedPixels), -// observer, ObserveEvent.Type.CHANGE); -// } -// -// - - public String onChangeDo(int threshold, Object observer) { - String name = Observing.add(this, (ObserverCallBack) observer, ObserveEvent.Type.CHANGE, threshold); - log(lvl, "%s: onChange%s: %s minSize: %d", toStringShort(), - (observer == null ? "" : " with callback"), name, threshold); - return name; - } - - /** - * start an observer in this region that runs forever (use stopObserving() in handler) - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @return false if not possible, true if events have happened - */ - public boolean observe() { - return observe(Float.POSITIVE_INFINITY); - } - - /** - * start an observer in this region for the given time - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param secs time in seconds the observer should run - * @return false if not possible, true if events have happened - */ - public boolean observe(double secs) { - return observeDo(secs); - } - - /** - *INTERNAL USE ONLY: for use with scripting API bridges - * @param secs time in seconds the observer should run - * @param bg run in background true/false - * @return false if not possible, true if events have happened - */ - public boolean observeJ(double secs, boolean bg) { - if (bg) { - return observeInBackground(secs); - } else { - return observeDo(secs); - } - } - - private boolean observeDo(double secs) { - if (regionObserver == null) { - Debug.error("Region: observe: Nothing to observe (Region might be invalid): " + this.toStringShort()); - return false; - } - if (observing) { - Debug.error("Region: observe: already running for this region. Only one allowed!"); - return false; - } - log(lvl, "observe: starting in " + this.toStringShort() + " for " + secs + " seconds"); - int MaxTimePerScan = (int) (1000.0 / observeScanRate); - long begin_t = (new Date()).getTime(); - long stop_t; - if (secs > Long.MAX_VALUE) { - stop_t = Long.MAX_VALUE; - } else { - stop_t = begin_t + (long) (secs * 1000); - } - regionObserver.initialize(); - observing = true; - Observing.addRunningObserver(this); - while (observing && stop_t > (new Date()).getTime()) { - long before_find = (new Date()).getTime(); - ScreenImage simg = getScreen().capture(x, y, w, h); - if (!regionObserver.update(simg)) { - observing = false; - break; - } - if (!observing) { - break; - } - long after_find = (new Date()).getTime(); - try { - if (after_find - before_find < MaxTimePerScan) { - Thread.sleep((int) (MaxTimePerScan - (after_find - before_find))); - } - } catch (Exception e) { - } - } - boolean observeSuccess = false; - if (observing) { - observing = false; - log(lvl, "observe: stopped due to timeout in " - + this.toStringShort() + " for " + secs + " seconds"); - } else { - log(lvl, "observe: ended successfully: " + this.toStringShort()); - observeSuccess = Observing.hasEvents(this); - } - return observeSuccess; - } - - /** - * start an observer in this region for the given time that runs in background - * for details about the observe event handler: {@link ObserverCallBack} - * for details about APPEAR/VANISH/CHANGE events: {@link ObserveEvent} - * @param secs time in seconds the observer should run - * @return false if not possible, true otherwise - */ - public boolean observeInBackground(double secs) { - if (observing) { - Debug.error("Region: observeInBackground: already running for this region. Only one allowed!"); - return false; - } - log(lvl, "entering observeInBackground for %f secs", secs); - Thread observeThread = new Thread(new ObserverThread(secs)); - observeThread.start(); - log(lvl, "observeInBackground now running"); - return true; - } - - private class ObserverThread implements Runnable { - private double time; - - ObserverThread(double time) { - this.time = time; - } - - @Override - public void run() { - observe(time); - } - } - - /** - * stops a running observer - */ - public void stopObserver() { - log(lvl, "observe: request to stop observer for " + this.toStringShort()); - observing = false; - } - - /** - * stops a running observer printing an info message - * @param message text - */ - public void stopObserver(String message) { - Debug.info(message); - stopObserver(); - } - //
- - // - public Location checkMatch() { - if (lastMatch != null) { - return lastMatch.getTarget(); - } - return getTarget(); - } - - /** - * move the mouse pointer to region's last successful match
use center if no lastMatch
- * if region is a match: move to targetOffset
same as mouseMove - * - * @return 1 if possible, 0 otherwise - */ - public int hover() { - try { // needed to cut throw chain for FindFailed - return hover(checkMatch()); - } catch (FindFailed ex) { - } - return 0; - } - - /** - * move the mouse pointer to the given target location
same as mouseMove
Pattern or Filename - do a find - * before and use the match
Region - position at center
Match - position at match's targetOffset
Location - * - position at that point
- * - * @param to search: Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int hover(PFRML target) throws FindFailed { - log(lvl, "hover: " + target); - return mouseMove(target); - } - - /** - * left click at the region's last successful match
use center if no lastMatch
if region is a match: click - * targetOffset - * - * @return 1 if possible, 0 otherwise - */ - public int click() { - try { // needed to cut throw chain for FindFailed - return click(checkMatch(), 0); - } catch (FindFailed ex) { - return 0; - } - } - - /** - * left click at the given target location
Pattern or Filename - do a find before and use the match
Region - - * position at center
Match - position at match's targetOffset
- * Location - position at that point
- * - * @param to search: Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int click(PFRML target) throws FindFailed { - return click(target, 0); - } - - /** - * left click at the given target location
holding down the given modifier keys
- * Pattern or Filename - do a find before and use the match
Region - position at center
- * Match - position at match's targetOffset
Location - position at that point
- * - * @param to search: Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param modifiers the value of the resulting bitmask (see KeyModifier) - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int click(PFRML target, Integer modifiers) throws FindFailed { - Location loc = getLocationFromTarget(target); - int ret = Mouse.click(loc, InputEvent.BUTTON1_MASK, modifiers, false, this); - - //TODO SikuliActionManager.getInstance().clickTarget(this, target, _lastScreenImage, _lastMatch); - return ret; - } - - /** - * double click at the region's last successful match
use center if no lastMatch
if region is a match: click - * targetOffset - * - * @return 1 if possible, 0 otherwise - */ - public int doubleClick() { - try { // needed to cut throw chain for FindFailed - return doubleClick(checkMatch(), 0); - } catch (FindFailed ex) { - return 0; - } - } - - /** - * double click at the given target location
Pattern or Filename - do a find before and use the match
Region - - * position at center
Match - position at match's targetOffset
- * Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int doubleClick(PFRML target) throws FindFailed { - return doubleClick(target, 0); - } - - /** - * double click at the given target location
holding down the given modifier keys
- * Pattern or Filename - do a find before and use the match
Region - position at center
Match - position at - * match's targetOffset
Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param modifiers the value of the resulting bitmask (see KeyModifier) - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int doubleClick(PFRML target, Integer modifiers) throws FindFailed { - Location loc = getLocationFromTarget(target); - int ret = Mouse.click(loc, InputEvent.BUTTON1_MASK, modifiers, true, this); - - //TODO SikuliActionManager.getInstance().doubleClickTarget(this, target, _lastScreenImage, _lastMatch); - return ret; - } - - /** - * right click at the region's last successful match
use center if no lastMatch
if region is a match: click - * targetOffset - * - * @return 1 if possible, 0 otherwise - */ - public int rightClick() { - try { // needed to cut throw chain for FindFailed - return rightClick(checkMatch(), 0); - } catch (FindFailed ex) { - return 0; - } - } - - /** - * right click at the given target location
Pattern or Filename - do a find before and use the match
Region - - * position at center
Match - position at match's targetOffset
Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int rightClick(PFRML target) throws FindFailed { - return rightClick(target, 0); - } - - /** - * right click at the given target location
holding down the given modifier keys
- * Pattern or Filename - do a find before and use the match
Region - position at center
Match - position at - * match's targetOffset
Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param modifiers the value of the resulting bitmask (see KeyModifier) - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int rightClick(PFRML target, Integer modifiers) throws FindFailed { - Location loc = getLocationFromTarget(target); - int ret = Mouse.click(loc, InputEvent.BUTTON3_MASK, modifiers, false, this); - - //TODO SikuliActionManager.getInstance().rightClickTarget(this, target, _lastScreenImage, _lastMatch); - return ret; - } - - /** - * time in milliseconds to delay between button down/up at next click only (max 1000) - * - * @param millisecs value - */ - public void delayClick(int millisecs) { - Settings.ClickDelay = millisecs; - } - //
- - // - /** - * Drag from region's last match and drop at given target
applying Settings.DelayAfterDrag and DelayBeforeDrop - *
using left mouse button - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed if the Find operation failed - */ - public int dragDrop(PFRML target) throws FindFailed { - return dragDrop(lastMatch, target); - } - - /** - * Drag from a position and drop to another using left mouse button
applying Settings.DelayAfterDrag and - * DelayBeforeDrop - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param t1 source position - * @param t2 destination position - * @return 1 if possible, 0 otherwise - * @throws FindFailed if the Find operation failed - */ - public int dragDrop(PFRML t1, PFRML t2) throws FindFailed { - Location loc1 = getLocationFromTarget(t1); - Location loc2 = getLocationFromTarget(t2); - if (loc1 != null && loc2 != null) { - IRobot r = loc1.getRobotForPoint("drag"); - if (r == null) { - return 0; - } - Mouse.use(this); - r.smoothMove(loc1); - r.mouseDown(InputEvent.BUTTON1_MASK); - r.delay((int) (Settings.DelayAfterDrag * 1000)); - r = loc2.getRobotForPoint("drop"); - if (r == null) { - Mouse.let(this); - return 0; - } - r.smoothMove(loc2); - r.delay((int) (Settings.DelayBeforeDrop * 1000)); - r.mouseUp(InputEvent.BUTTON1_MASK); - Mouse.let(this); - return 1; - } - return 0; - } - - /** - * Prepare a drag action: move mouse to given target
press and hold left mouse button
wait - * Settings.DelayAfterDrag - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int drag(PFRML target) throws FindFailed { - Location loc = getLocationFromTarget(target); - if (loc != null) { - IRobot r = loc.getRobotForPoint("drag"); - if (r == null) { - return 0; - } - Mouse.use(this); - r.smoothMove(loc); - r.mouseDown(InputEvent.BUTTON1_MASK); - r.delay((int) (Settings.DelayAfterDrag * 1000)); - r.waitForIdle(); - return 1; - } - return 0; - } - - /** - * finalize a drag action with a drop: move mouse to given target
wait Settings.DelayBeforeDrop
release the - * left mouse button - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int dropAt(PFRML target) throws FindFailed { - Location loc = getLocationFromTarget(target); - if (loc != null) { - IRobot r = loc.getRobotForPoint("drop"); - if (r == null) { - return 0; - } - r.smoothMove(loc); - r.delay((int) (Settings.DelayBeforeDrop * 1000)); - r.mouseUp(InputEvent.BUTTON1_MASK); - r.waitForIdle(); - Mouse.let(this); - return 1; - } - return 0; - } - //
- - // - /** - * press and hold the specified buttons - use + to combine Button.LEFT left mouse button Button.MIDDLE middle mouse - * button Button.RIGHT right mouse button - * - * @param buttons spec - */ - public void mouseDown(int buttons) { - Mouse.down(buttons, this); - } - - /** - * release all currently held buttons - */ - public void mouseUp() { - Mouse.up(0, this); - } - - /** - * release the specified mouse buttons (see mouseDown) if buttons==0, all currently held buttons are released - * - * @param buttons spec - */ - public void mouseUp(int buttons) { - Mouse.up(buttons, this); - } - - /** - * move the mouse pointer to the region's last successful match
same as hover
- * - * @return 1 if possible, 0 otherwise - */ - public int mouseMove() { - if (lastMatch != null) { - try { - return mouseMove(lastMatch); - } catch (FindFailed ex) { - return 0; - } - } - return 0; - } - - /** - * move the mouse pointer to the given target location
same as hover
Pattern or Filename - do a find before - * and use the match
Region - position at center
Match - position at match's targetOffset
- * Location - position at that point
- * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @return 1 if possible, 0 otherwise - * @throws FindFailed for Pattern or Filename - */ - public int mouseMove(PFRML target) throws FindFailed { - Location loc = getLocationFromTarget(target); - return Mouse.move(loc, this); - } - - /** - * move the mouse from the current position to the offset position given by the parameters - * @param xoff horizontal offset (< 0 left, > 0 right) - * @param yoff vertical offset (< 0 up, > 0 down) - * @return 1 if possible, 0 otherwise - */ - public int mouseMove(int xoff, int yoff) { - try { - return mouseMove(Mouse.at().offset(xoff, yoff)); - } catch (Exception ex) { - return 0; - } - } - - /** - * Move the wheel at the current mouse position
the given steps in the given direction:
Button.WHEEL_DOWN, - * Button.WHEEL_UP - * - * @param direction to move the wheel - * @param steps the number of steps - * @return 1 in any case - */ - public int wheel(int direction, int steps) { - Mouse.wheel(direction, steps, this); - return 1; - } - - /** - * move the mouse pointer to the given target location
and move the wheel the given steps in the given direction: - *
Button.WHEEL_DOWN, Button.WHEEL_UP - * - * @param Pattern, Filename, Text, Region, Match or Location target - * @param target Pattern, Filename, Text, Region, Match or Location - * @param direction to move the wheel - * @param steps the number of steps - * @return 1 if possible, 0 otherwise - * @throws FindFailed if the Find operation failed - */ - public int wheel(PFRML target, int direction, int steps) throws FindFailed { - Location loc = getLocationFromTarget(target); - if (loc != null) { - Mouse.use(this); - Mouse.keep(this); - Mouse.move(loc, this); - Mouse.wheel(direction, steps, this); - Mouse.let(this); - return 1; - } - return 0; - } - - /** - * - * @return current location of mouse pointer - * @deprecated use {@link Mouse#at()} instead - */ - @Deprecated - public static Location atMouse() { - return Mouse.at(); - } - //
- - // - /** - * press and hold the given key use a constant from java.awt.event.KeyEvent which might be special in the current - * machine/system environment - * - * @param keycode Java KeyCode - */ - public void keyDown(int keycode) { - getRobotForRegion().keyDown(keycode); - } - - /** - * press and hold the given keys including modifier keys
use the key constants defined in class Key,
which - * only provides a subset of a US-QWERTY PC keyboard layout
might be mixed with simple characters - *
use + to concatenate Key constants - * - * @param keys valid keys - */ - public void keyDown(String keys) { - getRobotForRegion().keyDown(keys); - } - - /** - * release all currently pressed keys - */ - public void keyUp() { - getRobotForRegion().keyUp(); - } - - /** - * release the given keys (see keyDown(keycode) ) - * - * @param keycode Java KeyCode - */ - public void keyUp(int keycode) { - getRobotForRegion().keyUp(keycode); - } - - /** - * release the given keys (see keyDown(keys) ) - * - * @param keys valid keys - */ - public void keyUp(String keys) { - getRobotForRegion().keyUp(keys); - } - - /** - * Compact alternative for type() with more options
- * - special keys and options are coded as #XN. or #X+ or #X-
- * where X is a refrence for a special key and N is an optional repeat factor
- * A modifier key as #X. modifies the next following key
- * the trailing . ends the special key, the + (press and hold) or - (release) does the same,
- * but signals press-and-hold or release additionally.
- * except #W / #w all special keys are not case-sensitive
- * a #wn. inserts a wait of n millisecs or n secs if n less than 60
- * a #Wn. sets the type delay for the following keys (must be > 60 and denotes millisecs) - * - otherwise taken as normal wait
- * Example: wait 2 secs then type CMD/CTRL - N then wait 1 sec then type DOWN 3 times
- * Windows/Linux: write("#w2.#C.n#W1.#d3.")
- * Mac: write("#w2.#M.n#W1.#D3.")
- * for more details about the special key codes and examples consult the docs
- * @param text a coded text interpreted as a series of key actions (press/hold/release) - * @return 0 for success 1 otherwise - */ - public int write(String text) { - Debug.info("Write: " + text); - char c; - String token, tokenSave; - String modifier = ""; - int k; - IRobot robot = getRobotForRegion(); - int pause = 20 + (Settings.TypeDelay > 1 ? 1000 : (int) (Settings.TypeDelay * 1000)); - Settings.TypeDelay = 0.0; - robot.typeStarts(); - for (int i = 0; i < text.length(); i++) { - log(lvl + 1, "write: (%d) %s", i, text.substring(i)); - c = text.charAt(i); - token = null; - boolean isModifier = false; - if (c == '#') { - if (text.charAt(i + 1) == '#') { - log(3, "write at: %d: %s", i, c); - i += 1; - continue; - } - if (text.charAt(i + 2) == '+' || text.charAt(i + 2) == '-') { - token = text.substring(i, i + 3); - isModifier = true; - } else if (-1 < (k = text.indexOf('.', i))) { - if (k > -1) { - token = text.substring(i, k + 1); - if (token.length() > Key.keyMaxLength || token.substring(1).contains("#")) { - token = null; - } - } - } - } - Integer key = -1; - if (token == null) { - log(lvl + 1, "write: %d: %s", i, c); - } else { - log(lvl + 1, "write: token at %d: %s", i, token); - int repeat = 0; - if (token.toUpperCase().startsWith("#W")) { - if (token.length() > 3) { - i += token.length() - 1; - int t = 0; - try { - t = Integer.parseInt(token.substring(2, token.length() - 1)); - } catch (NumberFormatException ex) { - } - if ((token.startsWith("#w") && t > 60)) { - pause = 20 + (t > 1000 ? 1000 : t); - log(lvl + 1, "write: type delay: " + t); - } else { - log(lvl + 1, "write: wait: " + t); - robot.delay((t < 60 ? t * 1000 : t)); - } - continue; - } - } - tokenSave = token; - token = token.substring(0, 2).toUpperCase() + "."; - if (Key.isRepeatable(token)) { - try { - repeat = Integer.parseInt(tokenSave.substring(2, tokenSave.length() - 1)); - } catch (NumberFormatException ex) { - token = tokenSave; - } - } else if (tokenSave.length() == 3 && Key.isModifier(tokenSave.toUpperCase())) { - i += tokenSave.length() - 1; - modifier += tokenSave.substring(1, 2).toUpperCase(); - continue; - } else { - token = tokenSave; - } - if (-1 < (key = Key.toJavaKeyCodeFromText(token))) { - if (repeat > 0) { - log(lvl + 1, "write: %s Repeating: %d", token, repeat); - } else { - log(lvl + 1, "write: %s", tokenSave); - repeat = 1; - } - i += tokenSave.length() - 1; - if (isModifier) { - if (tokenSave.endsWith("+")) { - robot.keyDown(key); - } else { - robot.keyUp(key); - } - continue; - } - if (repeat > 1) { - for (int n = 0; n < repeat; n++) { - robot.typeKey(key.intValue()); - } - continue; - } - } - } - if (!modifier.isEmpty()) { - log(lvl + 1, "write: modifier + " + modifier); - for (int n = 0; n < modifier.length(); n++) { - robot.keyDown(Key.toJavaKeyCodeFromText(String.format("#%s.", modifier.substring(n, n + 1)))); - } - } - if (key > -1) { - robot.typeKey(key.intValue()); - } else { - robot.typeChar(c, IRobot.KeyMode.PRESS_RELEASE); - } - if (!modifier.isEmpty()) { - log(lvl + 1, "write: modifier - " + modifier); - for (int n = 0; n < modifier.length(); n++) { - robot.keyUp(Key.toJavaKeyCodeFromText(String.format("#%s.", modifier.substring(n, n + 1)))); - } - } - robot.delay(pause); - modifier = ""; - } - - robot.typeEnds(); - robot.waitForIdle(); - return 0; - } - - /** - * enters the given text one character/key after another using keyDown/keyUp - *
about the usable Key constants see keyDown(keys)
Class Key only provides a subset of a US-QWERTY PC - * keyboard layout
the text is entered at the current position of the focus/carret - * - * @param text containing characters and/or Key constants - * @return 1 if possible, 0 otherwise - */ - public int type(String text) { - try { - return keyin(null, text, 0); - } catch (FindFailed ex) { - return 0; - } - } - - /** - * enters the given text one character/key after another using keyDown/keyUp
while holding down the given modifier - * keys
about the usable Key constants see keyDown(keys)
Class Key only provides a subset of a US-QWERTY PC - * keyboard layout
the text is entered at the current position of the focus/carret - * - * @param text containing characters and/or Key constants - * @param modifiers constants according to class KeyModifiers - * @return 1 if possible, 0 otherwise - */ - public int type(String text, int modifiers) { - try { - return keyin(null, text, modifiers); - } catch (FindFailed findFailed) { - return 0; - } - } - - /** - * enters the given text one character/key after another using - * - * keyDown/keyUp
while holding down the given modifier keys
about the usable Key constants see keyDown(keys) - *
Class Key only provides a subset of a US-QWERTY PC keyboard layout
the text is entered at the current - * position of the focus/carret - * - * - * @param text containing characters and/or Key constants - * @param modifiers constants according to class Key - combine using + - * @return 1 if possible, 0 otherwise - */ - public int type(String text, String modifiers) { - String target = null; - int modifiersNew = Key.convertModifiers(modifiers); - if (modifiersNew == 0) { - target = text; - text = modifiers; - } - try { - return keyin(target, text, modifiersNew); - } catch (FindFailed findFailed) { - return 0; - } - } - - /** - * first does a click(target) at the given target position to gain focus/carret
enters the given text one - * character/key after another using keyDown/keyUp
about the usable Key constants see keyDown(keys) - *
Class Key only provides a subset of a US-QWERTY PC keyboard layout - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param text containing characters and/or Key constants - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int type(PFRML target, String text) throws FindFailed { - return keyin(target, text, 0); - } - - /** - * first does a click(target) at the given target position to gain focus/carret
enters the given text one - * character/key after another using keyDown/keyUp
while holding down the given modifier keys
about the usable - * Key constants see keyDown(keys)
Class Key only provides a subset of a US-QWERTY PC keyboard layout - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param text containing characters and/or Key constants - * @param modifiers constants according to class KeyModifiers - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int type(PFRML target, String text, int modifiers) throws FindFailed { - return keyin(target, text, modifiers); - } - - /** - * first does a click(target) at the given target position to gain focus/carret
enters the given text one - * character/key after another using keyDown/keyUp
while holding down the given modifier keys
about the usable - * Key constants see keyDown(keys)
Class Key only provides a subset of a US-QWERTY PC keyboard layout - * - * @param Pattern, Filename, Text, Region, Match or Location - * @param target Pattern, Filename, Text, Region, Match or Location - * @param text containing characters and/or Key constants - * @param modifiers constants according to class Key - combine using + - * @return 1 if possible, 0 otherwise - * @throws FindFailed if not found - */ - public int type(PFRML target, String text, String modifiers) throws FindFailed { - int modifiersNew = Key.convertModifiers(modifiers); - return keyin(target, text, modifiersNew); - } - - private int keyin(PFRML target, String text, int modifiers) - throws FindFailed { - if (target != null && 0 == click(target, 0)) { - return 0; - } - Debug profiler = Debug.startTimer("Region.type"); - if (text != null && !"".equals(text)) { - String showText = ""; - for (int i = 0; i < text.length(); i++) { - showText += Key.toJavaKeyCodeText(text.charAt(i)); - } - String modText = ""; - String modWindows = null; - if ((modifiers & KeyModifier.WIN) != 0) { - modifiers -= KeyModifier.WIN; - modifiers |= KeyModifier.META; - log(lvl, "Key.WIN as modifier"); - modWindows = "Windows"; - } - if (modifiers != 0) { - modText = String.format("( %s ) ", KeyEvent.getKeyModifiersText(modifiers)); - if (modWindows != null) { - modText = modText.replace("Meta", modWindows); - } - } - Debug.action("%s TYPE \"%s\"", modText, showText); - log(lvl, "%s TYPE \"%s\"", modText, showText); - profiler.lap("before getting Robot"); - IRobot r = getRobotForRegion(); - int pause = 20 + (Settings.TypeDelay > 1 ? 1000 : (int) (Settings.TypeDelay * 1000)); - Settings.TypeDelay = 0.0; - profiler.lap("before typing"); - r.typeStarts(); - for (int i = 0; i < text.length(); i++) { - r.pressModifiers(modifiers); - r.typeChar(text.charAt(i), IRobot.KeyMode.PRESS_RELEASE); - r.releaseModifiers(modifiers); - r.delay(pause); - } - r.typeEnds(); - profiler.lap("after typing, before waitForIdle"); - r.waitForIdle(); - profiler.end(); - return 1; - } - - return 0; - } - - /** - * time in milliseconds to delay between each character at next type only (max 1000) - * - * @param millisecs value - */ - public void delayType(int millisecs) { - Settings.TypeDelay = millisecs; - } - - /** - * pastes the text at the current position of the focus/carret
using the clipboard and strg/ctrl/cmd-v (paste - * keyboard shortcut) - * - * @param text a string, which might contain unicode characters - * @return 0 if possible, 1 otherwise - */ - public int paste(String text) { - try { - return paste(null, text); - } catch (FindFailed ex) { - return 1; - } - } - - /** - * first does a click(target) at the given target position to gain focus/carret
and then pastes the text
- * using the clipboard and strg/ctrl/cmd-v (paste keyboard shortcut) - * - * @param Pattern, Filename, Text, Region, Match or Location target - * @param target Pattern, Filename, Text, Region, Match or Location - * @param text a string, which might contain unicode characters - * @return 0 if possible, 1 otherwise - * @throws FindFailed if not found - */ - public int paste(PFRML target, String text) throws FindFailed { - if (target != null) { - click(target, 0); - } - if (text != null) { - App.setClipboard(text); - int mod = Key.getHotkeyModifier(); - IRobot r = getRobotForRegion(); - r.keyDown(mod); - r.keyDown(KeyEvent.VK_V); - r.keyUp(KeyEvent.VK_V); - r.keyUp(mod); - return 1; - } - return 0; - } - //
- - // - /** - * STILL EXPERIMENTAL: tries to read the text in this region
might contain misread characters, NL characters and - * other stuff, when interpreting contained grafics as text
- * Best results: one line of text with no grafics in the line - * - * @return the text read (utf8 encoded) - */ - public String text() { - if (Settings.OcrTextRead) { - ScreenImage simg = getScreen().capture(x, y, w, h); - TextRecognizer tr = TextRecognizer.getInstance(); - if (tr == null) { - Debug.error("text: text recognition is now switched off"); - return "--- no text ---"; - } - String textRead = tr.recognize(simg); - log(lvl, "text: #(" + textRead + ")#"); - return textRead; - } - Debug.error("text: text recognition is currently switched off"); - return "--- no text ---"; - } - - /** - * VERY EXPERIMENTAL: returns a list of matches, that represent single words, that have been found in this region
- * the match's x,y,w,h the region of the word
Match.getText() returns the word (utf8) at this match
- * Match.getScore() returns a value between 0 ... 1, that represents some OCR-confidence value
(the higher, the - * better the OCR engine thinks the result is) - * - * @return a list of matches - */ - public List listText() { - if (Settings.OcrTextRead) { - ScreenImage simg = getScreen().capture(x, y, w, h); - TextRecognizer tr = TextRecognizer.getInstance(); - if (tr == null) { - Debug.error("text: text recognition is now switched off"); - return null; - } - log(lvl, "listText: scanning %s", this); - return tr.listText(simg, this); - } - Debug.error("text: text recognition is currently switched off"); - return null; - } - //
- - public String saveScreenCapture() { - return getScreen().capture(this).save(); - } - - public String saveScreenCapture(String path) { - return getScreen().capture(this).save(path); - } - - public String saveScreenCapture(String path, String name) { - return getScreen().capture(this).save(path, name); - } -} diff --git a/All/Genesis-NP/Genesis#219/pair.info b/All/Genesis-NP/Genesis#219/pair.info deleted file mode 100755 index 9d2273f..0000000 --- a/All/Genesis-NP/Genesis#219/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:219 -SATName:Genesis -modifiedFPath:API/src/main/java/org/sikuli/script/Region.java -comSha:194385162409d89eef1714f8325895f424ef26a2 -parentComSha:194385162409d89eef1714f8325895f424ef26a2^1 -githubUrl:https://github.com/RaiMan/SikuliX-2014 -repoName:RaiMan#SikuliX-2014 \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#220/comMsg.txt b/All/Genesis-NP/Genesis#220/comMsg.txt deleted file mode 100755 index 0d27fa5..0000000 --- a/All/Genesis-NP/Genesis#220/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixed: Linux: build on the fly: possible NPE diff --git a/All/Genesis-NP/Genesis#220/diff.diff b/All/Genesis-NP/Genesis#220/diff.diff deleted file mode 100755 index e1c7ff7..0000000 --- a/All/Genesis-NP/Genesis#220/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/API/src/main/java/org/sikuli/util/LinuxSupport.java b/API/src/main/java/org/sikuli/util/LinuxSupport.java -index 839c367..2c5c4d4 100644 ---- a/API/src/main/java/org/sikuli/util/LinuxSupport.java -+++ b/API/src/main/java/org/sikuli/util/LinuxSupport.java -@@ -287 +287 @@ public class LinuxSupport { -- File[] javas = new File[2]; -+ File[] javas = new File[] {null, null} ; -@@ -289 +289,4 @@ public class LinuxSupport { -- javas[1] = new File(System.getenv("JAVA_HOME")); -+ String jhome = System.getenv("JAVA_HOME"); -+ if (jhome != null) { -+ javas[1] = new File(jhome); -+ } diff --git a/All/Genesis-NP/Genesis#220/new/LinuxSupport.java b/All/Genesis-NP/Genesis#220/new/LinuxSupport.java deleted file mode 100755 index 2c5c4d4..0000000 --- a/All/Genesis-NP/Genesis#220/new/LinuxSupport.java +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Copyright 2010-2015, Sikuli.org, sikulix.com - * Released under the MIT License. - * - * RaiMan 2015 - */ -package org.sikuli.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.PrintStream; -import org.sikuli.basics.Debug; -import org.sikuli.basics.FileManager; -import org.sikuli.script.RunTime; - -/** - * INTERNAL USE: all things needed with Linux at setup or runtime - */ -public class LinuxSupport { - - static final RunTime runTime = RunTime.get(); - - // - private static final String me = "LinuxSupport: "; - private static int lvl = 3; - private static boolean isCopiedProvided = false; - private static boolean haveBuilt = false; - public static boolean shouldUseProvided = false; -// private static String osArch; - public static void log(int level, String message, Object... args) { - Debug.logx(level, me + message, args); - } - - private static void logp(String message, Object... args) { - Debug.logx(-3, message, args); - } -// - - static File fWorkDir = null; - private static final String buildFolderSrc = "Build/Source"; - private static final String buildFolderInclude = "Build/Include"; - private static final String buildFolderTarget = "Build/Target"; - static File fLibs = runTime.fLibsFolder; - public static final String slibVision = "VisionProxy"; - public static final String libVision = "lib" + slibVision + ".so"; - public static final String libGrabKey = "libJXGrabKey.so"; - static boolean libSearched = false; - - private static String libOpenCVcore = ""; - private static String libOpenCVimgproc = ""; - private static String libOpenCVhighgui = ""; - private static String libTesseract = ""; - private static boolean opencvAvail = true; - private static boolean tessAvail = true; - private static final String[] libsExport = new String[]{null, null}; - private static final String[] libsCheck = new String[]{null, null}; - - public static String getLinuxDistro() { - if (!runTime.runningLinux) { - return ""; - } - String result = runTime.runcmd("lsb_release -i -r -s"); - String linuxDistro = result.replaceAll("\n", " ").trim(); - if (linuxDistro.contains("*** error ***")) { - log(lvl, "command returns error: lsb_release -i -r -s\n%s", result); - linuxDistro = "???DISTRO???"; - } - return linuxDistro; - } - -// public static void setWorkDir(File workDir) { -// fWorkDir = workDir; -// } - -// public static void setLibsDir(File libsDir) { -// fLibs = libsDir; -// } - - public static boolean existsLibs() { - return new File(runTime.fLibsProvided, libVision).exists() || - new File(runTime.fLibsProvided, libGrabKey).exists(); - } - - public static boolean processLibs(String fpLibsJar) { - boolean shouldBuildVisionNow = false; - if (!fLibs.exists()) { - fLibs.mkdirs(); - } - if (fLibs.exists()) { - if (fpLibsJar != null) { - runTime.extractResourcesToFolderFromJar(fpLibsJar, runTime.fpJarLibs, fLibs, null); - } else { - runTime.extractResourcesToFolder(runTime.fpJarLibs, fWorkDir, null); - } - libsCheck[0] = new File(fLibs, libVision).getAbsolutePath(); - libsCheck[1] = new File(fLibs, libGrabKey).getAbsolutePath(); - File fLibCheck; - for (int i = 0; i < libsCheck.length; i++) { - fLibCheck = new File(libsCheck[i]); - if (fLibCheck.exists()) { - if (!checklibs(fLibCheck)) { -//TODO why? JXGrabKey unresolved: pthread - if (i == 0) { - if (libsExport[i] == null) { - log(-1, "provided %s might not be useable on this Linux - see log", fLibCheck.getName()); - } else { - log(-1, "bundled %s might not be useable on this Linux - see log", fLibCheck.getName()); - } - shouldBuildVisionNow = true; - } - } - } else { - log(-1, "check not possible for\n%s", fLibCheck); - } - } - } else { - log(-1, "check useability of libs: problems with libs folder\n%s", fLibs); - } - return shouldBuildVisionNow; - } - - public static boolean checkNeeded() { - String cmdRet; - boolean checkSuccess = true; - log(lvl, "checking: availability of OpenCV and Tesseract"); - log(lvl, "checking: scanning loader cache (ldconfig -p)"); - cmdRet = runTime.runcmd("ldconfig -p"); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "checking: ldconfig returns error:\ns", cmdRet); - checkSuccess = false; - } else { - String[] libs = cmdRet.split("\n"); - for (String libx : libs) { - libx = libx.trim(); - if (!libx.startsWith("lib")) { - continue; - } - if (libx.startsWith("libopencv_core.so.")) { - libOpenCVcore = libx.split("=>")[1].trim(); - } else if (libx.startsWith("libopencv_highgui.so.")) { - libOpenCVhighgui = libx.split("=>")[1].trim(); - } else if (libx.startsWith("libopencv_imgproc.so.")) { - libOpenCVimgproc = libx.split("=>")[1].trim(); - } else if (libx.startsWith("libtesseract.so.")) { - libTesseract = libx.split("=>")[1].trim(); - } - } - if (libOpenCVcore == null || libOpenCVhighgui == null || libOpenCVimgproc == null) { - log(-1, "checking: OpenCV not in loader cache (see doc-note on OpenCV)"); - opencvAvail = checkSuccess = false; - } else { - log(lvl, "checking: found OpenCV libs:\n%s\n%s\n%s", - libOpenCVcore, libOpenCVhighgui, libOpenCVimgproc); - } - if (libTesseract == null) { - log(-1, "checking: Tesseract not in loader cache (see doc-note on Tesseract)"); - tessAvail = checkSuccess = false; - } else { - log(lvl, "checking: found Tesseract lib:\n%s", libTesseract); - } - } - // checking wmctrl, xdotool - cmdRet = runTime.runcmd("wmctrl -m"); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "checking: wmctrl not available or not working"); - } else { - log(lvl, "checking: wmctrl seems to be available"); - } - cmdRet = runTime.runcmd("xdotool version"); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "checking: xdotool not available or not working"); - } else { - log(lvl, "checking: xdotool seems to be available"); - } - return checkSuccess; - } - - public static boolean runLdd(File lib) { - // ldd -r lib - // undefined symbol: _ZN2cv3MatC1ERKS0_RKNS_5Rect_IiEE (./libVisionProxy.so) - String cmdRet = runTime.runcmd("ldd -r " + lib); - String[] retLines; - boolean success = true; - retLines = cmdRet.split("continued: build on the fly on Linux at runtime: if bundled do not work, looking for provided - if these do not work, try to build. setup not ready yet. \n"); - String libName = lib.getName(); - String libsMissing = ""; - for (String line : retLines) { - if (line.contains("undefined symbol:") && line.contains(libName)) { - line = line.split("symbol:")[1].trim().split("\\s")[0]; - libsMissing += line + ":"; - } - } - if (libsMissing.isEmpty()) { - log(lvl, "checking: should work: %s", libName); - } else { - log(-1, "checking: might not work, has undefined symbols: %s", libName); - log(lvl, "%s", libsMissing); - success = false; - } - return success; - } - - public static boolean checklibs(File lib) { - String cmdRet; - String[] retLines; - boolean checkSuccess = true; - - if (!libSearched) { - checkSuccess = checkNeeded(); - libSearched = true; - } - - log(lvl, "checking\n%s", lib); - // readelf -d lib - // 0x0000000000000001 (NEEDED) Shared library: [libtesseract.so.3] - cmdRet = runTime.runcmd("readelf -d " + lib); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "checking: readelf returns error:\ns", cmdRet); - checkSuccess = false; - } else { - retLines = cmdRet.split("\n"); - String libsNeeded = ""; - for (String line : retLines) { - if (line.contains("(NEEDED)")) { - line = line.split("\\[")[1].replace("]", ""); - libsNeeded += line + ":"; - } - } - log(lvl, libsNeeded); - } - - if (!runLdd(lib)) { - checkSuccess = false; - } - -// return false; // for testing - return checkSuccess; - } - - public static boolean checkAllLibs() { - boolean success = false; - if (!isCopiedProvided && !runTime.useLibsProvided) { - success = true; - String[] allLibs = runTime.fLibsProvided.list(new FilenameFilter() { - @Override - public boolean accept(File folder, String name) { - if (name.toLowerCase().endsWith(".so")) { - return true; - } - return false; - } - }); - if (allLibs != null) { - for (String sLib : allLibs) { - File fSrc = new File(runTime.fLibsProvided, sLib); - File fTgt = new File(runTime.fLibsFolder, sLib); - success &= FileManager.xcopy(fSrc, fTgt); - log(3, "Copy provided lib: %s (%s)", sLib, (success ? "ok" : "did not work")); - } - } - isCopiedProvided = true; - } else if (!haveBuilt) { - haveBuilt = true; - success = true; - log(3, "we have to build libVisionProxy.so"); - success &= checkNeeded(); - if (success) { - success &= buildVision(); - } - } - shouldUseProvided = success; - return success; - } - - public static boolean buildVision() { - File fLibsSaveDir = runTime.fLibsProvided; - fWorkDir = fLibsSaveDir.getParentFile(); - fWorkDir.mkdirs(); - fLibsSaveDir.mkdir(); - File fTarget = new File(fWorkDir, buildFolderTarget); - File fSource = new File(fWorkDir, buildFolderSrc); - File fInclude = new File(fWorkDir, buildFolderInclude); - fInclude.mkdirs(); - - File[] javas = new File[] {null, null} ; - javas[0] = new File(System.getProperty("java.home")); - String jhome = System.getenv("JAVA_HOME"); - if (jhome != null) { - javas[1] = new File(jhome); - } - - log(lvl, "starting inline build: libVisionProxy.so"); - log(lvl, "java.home from java props: %s", javas[0]); - log(lvl, "JAVA_HOME from environment: %s", javas[1]); - - File javaHome = null; - for (File jh : javas) { - if (jh == null) { - continue; - } - if (!new File(jh, "bin/javac").exists()) { - jh = jh.getParentFile(); - } - if (!new File(jh, "bin/javac").exists()) { - jh = null; - } - if (jh != null) { - if (new File(jh, "include/jni.h").exists()) { - javaHome = jh; - break; - } - } - } - if (javaHome == null) { - log(-1, "buildVision: no valid Java JDK available nor found"); - return false; - } - log(lvl, "JDK: found at: %s", javaHome); - - File cmdFile = new File(fWorkDir, "runBuild"); - String libVisionPath = new File(fTarget, libVision).getAbsolutePath(); - String sRunBuild = runTime.extractResourceToString("/Support/Linux", "runBuild", ""); - - sRunBuild = sRunBuild.replace("#jdkdir#", javaHome.getAbsolutePath()); - - String inclUsr = "/usr/include"; - String inclUsrLocal = "/usr/local/include"; - boolean exportIncludeOpenCV = false; - boolean exportIncludeTesseract = false; - - String inclLib = "opencv2"; - if (!new File(inclUsr, inclLib).exists() && !new File(inclUsrLocal, inclLib).exists()) { - log(lvl, "buildVision: opencv-include: not found - using the bundled include files"); - exportIncludeOpenCV = true; - } - - inclLib = "tesseract"; - if (!new File(inclUsr, inclLib).exists() && !new File(inclUsrLocal, inclLib).exists()) { - log(lvl, "buildVision: tesseract-include: not found - using the bundled include files"); - exportIncludeTesseract = true; - } - - boolean success = true; - success &= (null != runTime.extractResourcesToFolder( - "/srcnativelibs/Vision", fSource, null)); - if (exportIncludeOpenCV) { - success &= (null != runTime.extractResourcesToFolder( - "/srcnativelibs/Include/OpenCV", fInclude, null)); - } - if (exportIncludeTesseract) { - success &= (null != runTime.extractResourcesToFolder( - "/srcnativelibs/Include/Tesseract", fInclude, null)); - } - if (!success) { - log(-1, "buildVision: cannot export bundled sources"); - } - - sRunBuild = sRunBuild.replace("#opencvcore#", libOpenCVcore); - sRunBuild = sRunBuild.replace("#opencvimgproc#", libOpenCVimgproc); - sRunBuild = sRunBuild.replace("#opencvhighgui#", libOpenCVhighgui); - sRunBuild = sRunBuild.replace("#tesseractlib#", libTesseract); - sRunBuild = sRunBuild.replace("#work#", fTarget.getParentFile().getAbsolutePath()); - log(lvl, "**** content of build script:\n%s\n**** content end", sRunBuild); - try { - PrintStream psCmdFile = new PrintStream(cmdFile); - psCmdFile.print(sRunBuild); - psCmdFile.close(); - } catch (Exception ex) { - log(-1, "buildVision: problem writing command file:\n%s", cmdFile); - return false; - } - cmdFile.setExecutable(true); - - if (success && opencvAvail && tessAvail) { - log(lvl, "buildVision: running build script"); - String cmdRet = runTime.runcmd(cmdFile.getAbsolutePath()); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "buildVision: build script returns error:\n%s", cmdRet); - return false; - } else { - log(lvl, "buildVision: checking created libVisionProxy.so"); - if (!runLdd(new File(libVisionPath))) { - log(-1, "------- output of the build run\n%s", cmdRet); - return false; - } - } - } else { - log(-1, "buildVision: corrrect the reported problems and try again"); - return false; - } - File providedLib = new File(fLibsSaveDir, libVision); - if (!FileManager.xcopy(new File(libVisionPath), providedLib)) { - log(-1, "buildVision: could not save:\n%s", providedLib); - return false; - } - if (runTime.fLibsFolder.exists()) { - copyProvidedLibs(runTime.fLibsFolder); - } - log(lvl, "buildVision: ending inline build: success:\n%s", providedLib); - return true; - } - - public static boolean copyProvidedLibs(File fLibsFolder) { - String[] toCopy = runTime.fLibsProvided.list(new FilenameFilter() { - @Override - public boolean accept(File folder, String name) { - if (name.endsWith(".so")) { - return true; - } - return false; - } - }); - boolean success = false; - if (toCopy != null) { - for (String aLib : toCopy) { - success |= FileManager.xcopy(new File(runTime.fLibsProvided, aLib), - new File(fLibsFolder, aLib)); - } - } - return success; - } - -} diff --git a/All/Genesis-NP/Genesis#220/old/LinuxSupport.java b/All/Genesis-NP/Genesis#220/old/LinuxSupport.java deleted file mode 100755 index 839c367..0000000 --- a/All/Genesis-NP/Genesis#220/old/LinuxSupport.java +++ /dev/null @@ -1,422 +0,0 @@ -/* - * Copyright 2010-2015, Sikuli.org, sikulix.com - * Released under the MIT License. - * - * RaiMan 2015 - */ -package org.sikuli.util; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.FilenameFilter; -import java.io.IOException; -import java.io.PrintStream; -import org.sikuli.basics.Debug; -import org.sikuli.basics.FileManager; -import org.sikuli.script.RunTime; - -/** - * INTERNAL USE: all things needed with Linux at setup or runtime - */ -public class LinuxSupport { - - static final RunTime runTime = RunTime.get(); - - // - private static final String me = "LinuxSupport: "; - private static int lvl = 3; - private static boolean isCopiedProvided = false; - private static boolean haveBuilt = false; - public static boolean shouldUseProvided = false; -// private static String osArch; - public static void log(int level, String message, Object... args) { - Debug.logx(level, me + message, args); - } - - private static void logp(String message, Object... args) { - Debug.logx(-3, message, args); - } -// - - static File fWorkDir = null; - private static final String buildFolderSrc = "Build/Source"; - private static final String buildFolderInclude = "Build/Include"; - private static final String buildFolderTarget = "Build/Target"; - static File fLibs = runTime.fLibsFolder; - public static final String slibVision = "VisionProxy"; - public static final String libVision = "lib" + slibVision + ".so"; - public static final String libGrabKey = "libJXGrabKey.so"; - static boolean libSearched = false; - - private static String libOpenCVcore = ""; - private static String libOpenCVimgproc = ""; - private static String libOpenCVhighgui = ""; - private static String libTesseract = ""; - private static boolean opencvAvail = true; - private static boolean tessAvail = true; - private static final String[] libsExport = new String[]{null, null}; - private static final String[] libsCheck = new String[]{null, null}; - - public static String getLinuxDistro() { - if (!runTime.runningLinux) { - return ""; - } - String result = runTime.runcmd("lsb_release -i -r -s"); - String linuxDistro = result.replaceAll("\n", " ").trim(); - if (linuxDistro.contains("*** error ***")) { - log(lvl, "command returns error: lsb_release -i -r -s\n%s", result); - linuxDistro = "???DISTRO???"; - } - return linuxDistro; - } - -// public static void setWorkDir(File workDir) { -// fWorkDir = workDir; -// } - -// public static void setLibsDir(File libsDir) { -// fLibs = libsDir; -// } - - public static boolean existsLibs() { - return new File(runTime.fLibsProvided, libVision).exists() || - new File(runTime.fLibsProvided, libGrabKey).exists(); - } - - public static boolean processLibs(String fpLibsJar) { - boolean shouldBuildVisionNow = false; - if (!fLibs.exists()) { - fLibs.mkdirs(); - } - if (fLibs.exists()) { - if (fpLibsJar != null) { - runTime.extractResourcesToFolderFromJar(fpLibsJar, runTime.fpJarLibs, fLibs, null); - } else { - runTime.extractResourcesToFolder(runTime.fpJarLibs, fWorkDir, null); - } - libsCheck[0] = new File(fLibs, libVision).getAbsolutePath(); - libsCheck[1] = new File(fLibs, libGrabKey).getAbsolutePath(); - File fLibCheck; - for (int i = 0; i < libsCheck.length; i++) { - fLibCheck = new File(libsCheck[i]); - if (fLibCheck.exists()) { - if (!checklibs(fLibCheck)) { -//TODO why? JXGrabKey unresolved: pthread - if (i == 0) { - if (libsExport[i] == null) { - log(-1, "provided %s might not be useable on this Linux - see log", fLibCheck.getName()); - } else { - log(-1, "bundled %s might not be useable on this Linux - see log", fLibCheck.getName()); - } - shouldBuildVisionNow = true; - } - } - } else { - log(-1, "check not possible for\n%s", fLibCheck); - } - } - } else { - log(-1, "check useability of libs: problems with libs folder\n%s", fLibs); - } - return shouldBuildVisionNow; - } - - public static boolean checkNeeded() { - String cmdRet; - boolean checkSuccess = true; - log(lvl, "checking: availability of OpenCV and Tesseract"); - log(lvl, "checking: scanning loader cache (ldconfig -p)"); - cmdRet = runTime.runcmd("ldconfig -p"); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "checking: ldconfig returns error:\ns", cmdRet); - checkSuccess = false; - } else { - String[] libs = cmdRet.split("\n"); - for (String libx : libs) { - libx = libx.trim(); - if (!libx.startsWith("lib")) { - continue; - } - if (libx.startsWith("libopencv_core.so.")) { - libOpenCVcore = libx.split("=>")[1].trim(); - } else if (libx.startsWith("libopencv_highgui.so.")) { - libOpenCVhighgui = libx.split("=>")[1].trim(); - } else if (libx.startsWith("libopencv_imgproc.so.")) { - libOpenCVimgproc = libx.split("=>")[1].trim(); - } else if (libx.startsWith("libtesseract.so.")) { - libTesseract = libx.split("=>")[1].trim(); - } - } - if (libOpenCVcore == null || libOpenCVhighgui == null || libOpenCVimgproc == null) { - log(-1, "checking: OpenCV not in loader cache (see doc-note on OpenCV)"); - opencvAvail = checkSuccess = false; - } else { - log(lvl, "checking: found OpenCV libs:\n%s\n%s\n%s", - libOpenCVcore, libOpenCVhighgui, libOpenCVimgproc); - } - if (libTesseract == null) { - log(-1, "checking: Tesseract not in loader cache (see doc-note on Tesseract)"); - tessAvail = checkSuccess = false; - } else { - log(lvl, "checking: found Tesseract lib:\n%s", libTesseract); - } - } - // checking wmctrl, xdotool - cmdRet = runTime.runcmd("wmctrl -m"); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "checking: wmctrl not available or not working"); - } else { - log(lvl, "checking: wmctrl seems to be available"); - } - cmdRet = runTime.runcmd("xdotool version"); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "checking: xdotool not available or not working"); - } else { - log(lvl, "checking: xdotool seems to be available"); - } - return checkSuccess; - } - - public static boolean runLdd(File lib) { - // ldd -r lib - // undefined symbol: _ZN2cv3MatC1ERKS0_RKNS_5Rect_IiEE (./libVisionProxy.so) - String cmdRet = runTime.runcmd("ldd -r " + lib); - String[] retLines; - boolean success = true; - retLines = cmdRet.split("continued: build on the fly on Linux at runtime: if bundled do not work, looking for provided - if these do not work, try to build. setup not ready yet. \n"); - String libName = lib.getName(); - String libsMissing = ""; - for (String line : retLines) { - if (line.contains("undefined symbol:") && line.contains(libName)) { - line = line.split("symbol:")[1].trim().split("\\s")[0]; - libsMissing += line + ":"; - } - } - if (libsMissing.isEmpty()) { - log(lvl, "checking: should work: %s", libName); - } else { - log(-1, "checking: might not work, has undefined symbols: %s", libName); - log(lvl, "%s", libsMissing); - success = false; - } - return success; - } - - public static boolean checklibs(File lib) { - String cmdRet; - String[] retLines; - boolean checkSuccess = true; - - if (!libSearched) { - checkSuccess = checkNeeded(); - libSearched = true; - } - - log(lvl, "checking\n%s", lib); - // readelf -d lib - // 0x0000000000000001 (NEEDED) Shared library: [libtesseract.so.3] - cmdRet = runTime.runcmd("readelf -d " + lib); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "checking: readelf returns error:\ns", cmdRet); - checkSuccess = false; - } else { - retLines = cmdRet.split("\n"); - String libsNeeded = ""; - for (String line : retLines) { - if (line.contains("(NEEDED)")) { - line = line.split("\\[")[1].replace("]", ""); - libsNeeded += line + ":"; - } - } - log(lvl, libsNeeded); - } - - if (!runLdd(lib)) { - checkSuccess = false; - } - -// return false; // for testing - return checkSuccess; - } - - public static boolean checkAllLibs() { - boolean success = false; - if (!isCopiedProvided && !runTime.useLibsProvided) { - success = true; - String[] allLibs = runTime.fLibsProvided.list(new FilenameFilter() { - @Override - public boolean accept(File folder, String name) { - if (name.toLowerCase().endsWith(".so")) { - return true; - } - return false; - } - }); - if (allLibs != null) { - for (String sLib : allLibs) { - File fSrc = new File(runTime.fLibsProvided, sLib); - File fTgt = new File(runTime.fLibsFolder, sLib); - success &= FileManager.xcopy(fSrc, fTgt); - log(3, "Copy provided lib: %s (%s)", sLib, (success ? "ok" : "did not work")); - } - } - isCopiedProvided = true; - } else if (!haveBuilt) { - haveBuilt = true; - success = true; - log(3, "we have to build libVisionProxy.so"); - success &= checkNeeded(); - if (success) { - success &= buildVision(); - } - } - shouldUseProvided = success; - return success; - } - - public static boolean buildVision() { - File fLibsSaveDir = runTime.fLibsProvided; - fWorkDir = fLibsSaveDir.getParentFile(); - fWorkDir.mkdirs(); - fLibsSaveDir.mkdir(); - File fTarget = new File(fWorkDir, buildFolderTarget); - File fSource = new File(fWorkDir, buildFolderSrc); - File fInclude = new File(fWorkDir, buildFolderInclude); - fInclude.mkdirs(); - - File[] javas = new File[2]; - javas[0] = new File(System.getProperty("java.home")); - javas[1] = new File(System.getenv("JAVA_HOME")); - - log(lvl, "starting inline build: libVisionProxy.so"); - log(lvl, "java.home from java props: %s", javas[0]); - log(lvl, "JAVA_HOME from environment: %s", javas[1]); - - File javaHome = null; - for (File jh : javas) { - if (jh == null) { - continue; - } - if (!new File(jh, "bin/javac").exists()) { - jh = jh.getParentFile(); - } - if (!new File(jh, "bin/javac").exists()) { - jh = null; - } - if (jh != null) { - if (new File(jh, "include/jni.h").exists()) { - javaHome = jh; - break; - } - } - } - if (javaHome == null) { - log(-1, "buildVision: no valid Java JDK available nor found"); - return false; - } - log(lvl, "JDK: found at: %s", javaHome); - - File cmdFile = new File(fWorkDir, "runBuild"); - String libVisionPath = new File(fTarget, libVision).getAbsolutePath(); - String sRunBuild = runTime.extractResourceToString("/Support/Linux", "runBuild", ""); - - sRunBuild = sRunBuild.replace("#jdkdir#", javaHome.getAbsolutePath()); - - String inclUsr = "/usr/include"; - String inclUsrLocal = "/usr/local/include"; - boolean exportIncludeOpenCV = false; - boolean exportIncludeTesseract = false; - - String inclLib = "opencv2"; - if (!new File(inclUsr, inclLib).exists() && !new File(inclUsrLocal, inclLib).exists()) { - log(lvl, "buildVision: opencv-include: not found - using the bundled include files"); - exportIncludeOpenCV = true; - } - - inclLib = "tesseract"; - if (!new File(inclUsr, inclLib).exists() && !new File(inclUsrLocal, inclLib).exists()) { - log(lvl, "buildVision: tesseract-include: not found - using the bundled include files"); - exportIncludeTesseract = true; - } - - boolean success = true; - success &= (null != runTime.extractResourcesToFolder( - "/srcnativelibs/Vision", fSource, null)); - if (exportIncludeOpenCV) { - success &= (null != runTime.extractResourcesToFolder( - "/srcnativelibs/Include/OpenCV", fInclude, null)); - } - if (exportIncludeTesseract) { - success &= (null != runTime.extractResourcesToFolder( - "/srcnativelibs/Include/Tesseract", fInclude, null)); - } - if (!success) { - log(-1, "buildVision: cannot export bundled sources"); - } - - sRunBuild = sRunBuild.replace("#opencvcore#", libOpenCVcore); - sRunBuild = sRunBuild.replace("#opencvimgproc#", libOpenCVimgproc); - sRunBuild = sRunBuild.replace("#opencvhighgui#", libOpenCVhighgui); - sRunBuild = sRunBuild.replace("#tesseractlib#", libTesseract); - sRunBuild = sRunBuild.replace("#work#", fTarget.getParentFile().getAbsolutePath()); - log(lvl, "**** content of build script:\n%s\n**** content end", sRunBuild); - try { - PrintStream psCmdFile = new PrintStream(cmdFile); - psCmdFile.print(sRunBuild); - psCmdFile.close(); - } catch (Exception ex) { - log(-1, "buildVision: problem writing command file:\n%s", cmdFile); - return false; - } - cmdFile.setExecutable(true); - - if (success && opencvAvail && tessAvail) { - log(lvl, "buildVision: running build script"); - String cmdRet = runTime.runcmd(cmdFile.getAbsolutePath()); - if (cmdRet.contains(runTime.runCmdError)) { - log(-1, "buildVision: build script returns error:\n%s", cmdRet); - return false; - } else { - log(lvl, "buildVision: checking created libVisionProxy.so"); - if (!runLdd(new File(libVisionPath))) { - log(-1, "------- output of the build run\n%s", cmdRet); - return false; - } - } - } else { - log(-1, "buildVision: corrrect the reported problems and try again"); - return false; - } - File providedLib = new File(fLibsSaveDir, libVision); - if (!FileManager.xcopy(new File(libVisionPath), providedLib)) { - log(-1, "buildVision: could not save:\n%s", providedLib); - return false; - } - if (runTime.fLibsFolder.exists()) { - copyProvidedLibs(runTime.fLibsFolder); - } - log(lvl, "buildVision: ending inline build: success:\n%s", providedLib); - return true; - } - - public static boolean copyProvidedLibs(File fLibsFolder) { - String[] toCopy = runTime.fLibsProvided.list(new FilenameFilter() { - @Override - public boolean accept(File folder, String name) { - if (name.endsWith(".so")) { - return true; - } - return false; - } - }); - boolean success = false; - if (toCopy != null) { - for (String aLib : toCopy) { - success |= FileManager.xcopy(new File(runTime.fLibsProvided, aLib), - new File(fLibsFolder, aLib)); - } - } - return success; - } - -} diff --git a/All/Genesis-NP/Genesis#220/pair.info b/All/Genesis-NP/Genesis#220/pair.info deleted file mode 100755 index b68e5b1..0000000 --- a/All/Genesis-NP/Genesis#220/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:220 -SATName:Genesis -modifiedFPath:API/src/main/java/org/sikuli/util/LinuxSupport.java -comSha:3fcaa6a12f5a160c2b3f04e1e138905475bf53e3 -parentComSha:3fcaa6a12f5a160c2b3f04e1e138905475bf53e3^1 -githubUrl:https://github.com/RaiMan/SikuliX-2014 -repoName:RaiMan#SikuliX-2014 \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#224/comMsg.txt b/All/Genesis-NP/Genesis#224/comMsg.txt deleted file mode 100755 index 206a3fa..0000000 --- a/All/Genesis-NP/Genesis#224/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -to avoid possible NPE in special situations (mouse moved to invalid location) diff --git a/All/Genesis-NP/Genesis#224/diff.diff b/All/Genesis-NP/Genesis#224/diff.diff deleted file mode 100755 index d53cc59..0000000 --- a/All/Genesis-NP/Genesis#224/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/API/src/main/java/org/sikuli/script/Mouse.java b/API/src/main/java/org/sikuli/script/Mouse.java -index 19e9aea..1af4838 100644 ---- a/API/src/main/java/org/sikuli/script/Mouse.java -+++ b/API/src/main/java/org/sikuli/script/Mouse.java -@@ -10,0 +11 @@ import java.awt.Point; -+import java.awt.PointerInfo; -@@ -233,0 +235,2 @@ public class Mouse { -+ PointerInfo mp = MouseInfo.getPointerInfo(); -+ if (mp != null) { -@@ -234,0 +238,3 @@ public class Mouse { -+ } else { -+ Debug.error("Mouse: not possible to get last mouse position (PointerInfo == null)"); -+ } diff --git a/All/Genesis-NP/Genesis#224/new/Mouse.java b/All/Genesis-NP/Genesis#224/new/Mouse.java deleted file mode 100755 index 1af4838..0000000 --- a/All/Genesis-NP/Genesis#224/new/Mouse.java +++ /dev/null @@ -1,547 +0,0 @@ -/* - * Copyright 2010-2014, Sikuli.org, SikuliX.com - * Released under the MIT License. - * - * modified RaiMan - */ -package org.sikuli.script; - -import java.awt.MouseInfo; -import java.awt.Point; -import java.awt.PointerInfo; -import java.awt.event.InputEvent; -import java.awt.event.KeyEvent; -import java.util.Date; -import org.sikuli.basics.Debug; -import org.sikuli.basics.Settings; - -/** - * Main pupose is to coordinate the mouse usage among threads
- * At any one time, the mouse has one owner (usually a Region object)
- * who exclusively uses the mouse, all others wait for the mouse to be free again
- * if more than one possible owner is waiting, the next owner is uncertain
- * It is detected, when the mouse is moved external from the workflow, which can be - * used for appropriate actions (e.g. pause a script)
- * the mouse can be blocked for a longer time, so only this owner can use - * the mouse (like some transactional processing)
- * Currently deadlocks and infinite waits are not detected, but should not happen ;-)
- * Contained are methods to use the mouse (click, move, button down/up) as is - */ -public class Mouse { - - private static Mouse mouse = null; - - private boolean inUse = false; - private boolean keep = false; - private Object owner = null; - private Point lastPos = null; - private static boolean blocked = false; - private static boolean suspended = false; - - public static final int MouseMovedIgnore = 0; - public static final int MouseMovedShow = 1; - public static final int MouseMovedPause = 2; - public static final int MouseMovedAction = 3; - private static int mouseMovedResponse = MouseMovedIgnore; - private static ObserverCallBack callBack; - - protected Location mousePos; - protected boolean clickDouble; - protected int buttons; - protected int beforeWait; - protected int innerWait; - protected int afterWait; - - public static final int LEFT = InputEvent.BUTTON1_MASK; - public static final int MIDDLE = InputEvent.BUTTON2_MASK; - public static final int RIGHT = InputEvent.BUTTON3_MASK; - public static final int WHEEL_UP = -1; - public static int WHEEL_DOWN = 1; - - private Mouse() { - this.lastPos = null; - } - - /** - * To get the one Mouse instance used for synchronisation - * - */ - protected static Mouse get() { - if (mouse == null) { - mouse = new Mouse(); - } - return mouse; - } - - public static void reset() { - if (mouse == null) { - return; - } - unblock(get().getOwner()); - get().let(get().getOwner()); - get().let(get().getOwner()); - up(); - setMouseMovedResponse(MouseMovedIgnore); - mouse = null; - } - - private Object getOwner() { - return owner; - } - - /** - * current setting what to do if mouse is moved outside Sikuli's mouse protection - * - */ - public static int getMouseMovedResponse() { - return mouseMovedResponse; - } - - /** - * what to do if mouse is moved outside Sikuli's mouse protection
- * - Mouse.MouseMovedIgnore (0) ignore it (default)
- * - Mouse.MouseMovedShow (1) show and ignore it
- * - Mouse.MouseMovedPause (2) show it and pause until user says continue
- * (2 not implemented yet - 1 is used) - * @param mouseMovedResponse - */ - public static void setMouseMovedResponse(int mouseMovedResponse) { - if (mouseMovedResponse > -1 && mouseMovedResponse < 3) { - Mouse.mouseMovedResponse = mouseMovedResponse; - } - } - - /** - * what to do if mouse is moved outside Sikuli's mouse protection
- * only 3 is honored:
- * in case of event the user provided callBack.happened is called - * @param mouseMovedResponse - * @param callBack - */ - public static void setMouseMovedResponse(int mouseMovedResponse, ObserverCallBack callBack) { - if (mouseMovedResponse == 3) { - if(callBack != null) { - Mouse.mouseMovedResponse = 3; - Mouse.callBack = callBack; - } - } - } - - /** - * to block the mouse globally
- * only the contained mouse methods without owner will be granted - * - * @return success - */ - public static boolean block() { - return block(null); - } - - /** - * to block the mouse globally for the given owner
- * only the contained mouse methods having the same owner will be granted - * - * @return success - */ - public static boolean block(Object owner) { - if (Mouse.get().use(owner)) { - blocked = true; - return true; - } else { - return false; - } - } - - /** - * free the mouse globally after a block() - * - * @return success (false means: not blocked currently) - */ - public static boolean unblock() { - return unblock(null); - } - - /** - * free the mouse globally for this owner after a block(owner) - * - * @return success (false means: not blocked currently for this owner) - */ - public static boolean unblock(Object owner) { - if (owner == null) { - owner = Mouse.get(); - } else if (owner instanceof Region) { - if (((Region) owner).isOtherScreen()) { - return false; - } - } - if (blocked && Mouse.get().owner == owner) { - blocked = false; - Mouse.get().let(owner); - return true; - } - return false; - } - - private static boolean use() { - return Mouse.get().use(null); - } - - protected synchronized boolean use(Object owner) { - if (owner == null) { - owner = this; - } else if (owner instanceof Region) { - if (((Region) owner).isOtherScreen()) { - return false; - } - } - if ((blocked || inUse) && this.owner == owner) { - return true; - } - while (inUse) { - try { - wait(); - } catch (InterruptedException e) { - } - } - if (!inUse) { - inUse = true; - checkLastPos(); - keep = false; - this.owner = owner; - Debug.log(3, "Mouse: use start: %s", owner); - return true; - } - Debug.error("Mouse: synch problem - use start: %s", owner); - return false; - } - - private static boolean let() { - return Mouse.get().let(null); - } - - protected synchronized boolean let(Object owner) { - if (owner == null) { - owner = this; - } else if (owner instanceof Region) { - if (((Region) owner).isOtherScreen()) { - return false; - } - } - if (inUse && this.owner == owner) { - if (keep) { - keep = false; - return true; - } - PointerInfo mp = MouseInfo.getPointerInfo(); - if (mp != null) { - lastPos = MouseInfo.getPointerInfo().getLocation(); - } else { - Debug.error("Mouse: not possible to get last mouse position (PointerInfo == null)"); - } - inUse = false; - this.owner = null; - notify(); - Debug.log(3, "Mouse: use stop: %s", owner); - return true; - } - return false; - } - - protected synchronized boolean keep(Object owner) { - if (owner == null) { - owner = this; - } else if (owner instanceof Region) { - if (((Region) owner).isOtherScreen()) { - return false; - } - } - if (inUse && this.owner == owner) { - keep = true; - Debug.log(3, "Mouse: use keep: %s", owner); - return true; - } - return false; - } - - private void checkLastPos() { - if (lastPos == null) { - return; - } - Point pos = MouseInfo.getPointerInfo().getLocation(); - if (lastPos.x != pos.x || lastPos.y != pos.y) { - Debug.error("Mouse: moved externally"); - if (mouseMovedResponse > 0) { - showMousePos(pos); - } - if (mouseMovedResponse == 2) { -//TODO implement 2 - return; - } - if (mouseMovedResponse == 3) { -//TODO implement 3 - if (callBack != null) { - callBack.happened(new ObserveEvent("MouseMoved", ObserveEvent.Type.GENERIC, - lastPos, new Location(pos), null, (new Date()).getTime())); - } - } - } - } - - public static boolean hasMoved() { - Point pos = MouseInfo.getPointerInfo().getLocation(); - if (Mouse.get().lastPos.x != pos.x || Mouse.get().lastPos.y != pos.y) { - return true; - } - return false; - } - - private void showMousePos(Point pos) { - Location lPos = new Location(pos); - Region inner = lPos.grow(20).highlight(); - delay(500); - lPos.grow(40).highlight(1); - delay(500); - inner.highlight(); - } - - private static void delay(int time) { - if (time == 0) { - return; - } - if (time < 60) { - time = time * 1000; - } - try { - Thread.sleep(time); - } catch (InterruptedException e) { - } - } - - /** - * to click (left, right, middle - single or double) at the given location using the given button - * only useable for local screens - * - * timing parameters:
- * - one value
- * < 0 wait before mouse down
- * > 0 wait after mouse up
- * - 2 or 3 values - * 1st wait before mouse down
- * 2nd wait after mouse up
- * 3rd inner wait (milli secs, cut to 1000): pause between mouse down and up (Settings.ClickDelay) - * - * wait before and after: > 59 taken as milli secs - < are seconds - * - * @param loc where to click - * @param action L,R,M left, right, middle - D means double click - * @param args timing parameters - * @return the location - */ - public static Location click(Location loc, String action, Integer... args) { - if (suspended || loc.isOtherScreen()) { - return null; - } - getArgsClick(Mouse.get(), loc, action, args); - use(); - delay(Mouse.get().beforeWait); - Settings.ClickDelay = Mouse.get().innerWait / 1000; - click(loc, Mouse.get().buttons, 0, Mouse.get().clickDouble, null); - delay(Mouse.get().afterWait); - let(); - return loc; - } - - private static void getArgsClick(Mouse mouse, Location loc, String action, Integer... args) { - mouse.mousePos = loc; - mouse.clickDouble = false; - action = action.toUpperCase(); - if (action.contains("D")) { - mouse.clickDouble = true; - } - mouse.buttons = 0; - if (action.contains("L")) { - mouse.buttons += LEFT; - } - if (action.contains("M")) { - mouse.buttons += MIDDLE; - } - if (action.contains("R")) { - mouse.buttons += RIGHT; - } - if (mouse.buttons == 0) { - mouse.buttons = LEFT; - } - mouse.beforeWait = 0; - mouse.innerWait = 0; - mouse.afterWait = 0; - if (args.length > 0) { - if (args.length == 1) { - if (args[0] < 0) { - mouse.beforeWait = -args[0]; - } else { - mouse.afterWait = args[0]; - } - } - mouse.beforeWait = args[0]; - if (args.length > 1) { - mouse.afterWait = args[1]; - if (args.length > 2) { - mouse.innerWait = args[2]; - } - } - } - } - - protected static int click(Location loc, int buttons, int modifiers, boolean dblClick, Region region) { - if (loc == null) { - return 0; - } - IRobot r = loc.getRobotForPoint("click"); - if (r == null) { - return 0; - } - get().use(region); - Debug.action(getClickMsg(loc, buttons, modifiers, dblClick)); - r.smoothMove(loc); - r.clickStarts(); - r.pressModifiers(modifiers); - int pause = Settings.ClickDelay > 1 ? 1 : (int) (Settings.ClickDelay * 1000); - Settings.ClickDelay = 0.0; - if (dblClick) { - r.mouseDown(buttons); - r.mouseUp(buttons); - r.mouseDown(buttons); - r.mouseUp(buttons); - } else { - r.mouseDown(buttons); - r.delay(pause); - r.mouseUp(buttons); - } - r.releaseModifiers(modifiers); - r.clickEnds(); - r.waitForIdle(); - get().let(region); - return 1; - } - - private static String getClickMsg(Location loc, int buttons, int modifiers, boolean dblClick) { - String msg = ""; - if (modifiers != 0) { - msg += KeyEvent.getKeyModifiersText(modifiers) + "+"; - } - if (buttons == InputEvent.BUTTON1_MASK && !dblClick) { - msg += "CLICK"; - } - if (buttons == InputEvent.BUTTON1_MASK && dblClick) { - msg += "DOUBLE CLICK"; - } - if (buttons == InputEvent.BUTTON3_MASK) { - msg += "RIGHT CLICK"; - } else if (buttons == InputEvent.BUTTON2_MASK) { - msg += "MID CLICK"; - } - msg += " on " + loc; - return msg; - } - - /** - * move the mouse to the given location (local and remote) - * - * @param loc - * @return 1 for success, 0 otherwise - */ - public static int move(Location loc) { - return move(loc, null); - } - - protected static int move(Location loc, Region region) { - if (suspended) { - return 0; - } - if (loc != null) { - IRobot r = loc.getRobotForPoint("mouseMove"); - if (r == null) { - return 0; - } - if (!r.isRemote()) { - Mouse.get().use(region); - } - r.smoothMove(loc); - r.waitForIdle(); - if (!r.isRemote()) { - Mouse.get().let(region); - } - return 1; - } - return 0; - } - - /** - * press and hold the given buttons - * - * @param buttons - */ - public static void down(int buttons) { - down(buttons, null); - } - - protected static void down(int buttons, Region region) { - if (suspended) { - return; - } - get().use(region); - Screen.getPrimaryScreen().getRobot().mouseDown(buttons); - } - - /** - * release all buttons - * - */ - public static void up() { - up(0, null); - } - - /** - * release the given buttons - * - * @param buttons (0 releases all buttons) - */ - public static void up(int buttons) { - up(buttons, null); - } - - protected static void up(int buttons, Region region) { - if (suspended) { - return; - } - if (0 == Screen.getPrimaryScreen().getRobot().mouseUp(buttons)) { - get().let(region); - } - } - - /** - * move mouse using mouse wheel in the given direction the given steps
- * the result is system dependent - * - * @param direction - * @param steps - */ - public static void wheel(int direction, int steps) { - wheel(direction, steps, null); - } - - protected static void wheel(int direction, int steps, Region region) { - if (suspended) { - return; - } - IRobot r = Screen.getPrimaryScreen().getRobot(); - get().use(region); - Debug.log(3, "Region: wheel: %s steps: %d", - (direction == WHEEL_UP ? "WHEEL_UP" : "WHEEL_DOWN"), steps); - for (int i = 0; i < steps; i++) { - r.mouseWheel(direction); - r.delay(50); - } - get().let(region); - } -} diff --git a/All/Genesis-NP/Genesis#224/old/Mouse.java b/All/Genesis-NP/Genesis#224/old/Mouse.java deleted file mode 100755 index 19e9aea..0000000 --- a/All/Genesis-NP/Genesis#224/old/Mouse.java +++ /dev/null @@ -1,541 +0,0 @@ -/* - * Copyright 2010-2014, Sikuli.org, SikuliX.com - * Released under the MIT License. - * - * modified RaiMan - */ -package org.sikuli.script; - -import java.awt.MouseInfo; -import java.awt.Point; -import java.awt.event.InputEvent; -import java.awt.event.KeyEvent; -import java.util.Date; -import org.sikuli.basics.Debug; -import org.sikuli.basics.Settings; - -/** - * Main pupose is to coordinate the mouse usage among threads
- * At any one time, the mouse has one owner (usually a Region object)
- * who exclusively uses the mouse, all others wait for the mouse to be free again
- * if more than one possible owner is waiting, the next owner is uncertain
- * It is detected, when the mouse is moved external from the workflow, which can be - * used for appropriate actions (e.g. pause a script)
- * the mouse can be blocked for a longer time, so only this owner can use - * the mouse (like some transactional processing)
- * Currently deadlocks and infinite waits are not detected, but should not happen ;-)
- * Contained are methods to use the mouse (click, move, button down/up) as is - */ -public class Mouse { - - private static Mouse mouse = null; - - private boolean inUse = false; - private boolean keep = false; - private Object owner = null; - private Point lastPos = null; - private static boolean blocked = false; - private static boolean suspended = false; - - public static final int MouseMovedIgnore = 0; - public static final int MouseMovedShow = 1; - public static final int MouseMovedPause = 2; - public static final int MouseMovedAction = 3; - private static int mouseMovedResponse = MouseMovedIgnore; - private static ObserverCallBack callBack; - - protected Location mousePos; - protected boolean clickDouble; - protected int buttons; - protected int beforeWait; - protected int innerWait; - protected int afterWait; - - public static final int LEFT = InputEvent.BUTTON1_MASK; - public static final int MIDDLE = InputEvent.BUTTON2_MASK; - public static final int RIGHT = InputEvent.BUTTON3_MASK; - public static final int WHEEL_UP = -1; - public static int WHEEL_DOWN = 1; - - private Mouse() { - this.lastPos = null; - } - - /** - * To get the one Mouse instance used for synchronisation - * - */ - protected static Mouse get() { - if (mouse == null) { - mouse = new Mouse(); - } - return mouse; - } - - public static void reset() { - if (mouse == null) { - return; - } - unblock(get().getOwner()); - get().let(get().getOwner()); - get().let(get().getOwner()); - up(); - setMouseMovedResponse(MouseMovedIgnore); - mouse = null; - } - - private Object getOwner() { - return owner; - } - - /** - * current setting what to do if mouse is moved outside Sikuli's mouse protection - * - */ - public static int getMouseMovedResponse() { - return mouseMovedResponse; - } - - /** - * what to do if mouse is moved outside Sikuli's mouse protection
- * - Mouse.MouseMovedIgnore (0) ignore it (default)
- * - Mouse.MouseMovedShow (1) show and ignore it
- * - Mouse.MouseMovedPause (2) show it and pause until user says continue
- * (2 not implemented yet - 1 is used) - * @param mouseMovedResponse - */ - public static void setMouseMovedResponse(int mouseMovedResponse) { - if (mouseMovedResponse > -1 && mouseMovedResponse < 3) { - Mouse.mouseMovedResponse = mouseMovedResponse; - } - } - - /** - * what to do if mouse is moved outside Sikuli's mouse protection
- * only 3 is honored:
- * in case of event the user provided callBack.happened is called - * @param mouseMovedResponse - * @param callBack - */ - public static void setMouseMovedResponse(int mouseMovedResponse, ObserverCallBack callBack) { - if (mouseMovedResponse == 3) { - if(callBack != null) { - Mouse.mouseMovedResponse = 3; - Mouse.callBack = callBack; - } - } - } - - /** - * to block the mouse globally
- * only the contained mouse methods without owner will be granted - * - * @return success - */ - public static boolean block() { - return block(null); - } - - /** - * to block the mouse globally for the given owner
- * only the contained mouse methods having the same owner will be granted - * - * @return success - */ - public static boolean block(Object owner) { - if (Mouse.get().use(owner)) { - blocked = true; - return true; - } else { - return false; - } - } - - /** - * free the mouse globally after a block() - * - * @return success (false means: not blocked currently) - */ - public static boolean unblock() { - return unblock(null); - } - - /** - * free the mouse globally for this owner after a block(owner) - * - * @return success (false means: not blocked currently for this owner) - */ - public static boolean unblock(Object owner) { - if (owner == null) { - owner = Mouse.get(); - } else if (owner instanceof Region) { - if (((Region) owner).isOtherScreen()) { - return false; - } - } - if (blocked && Mouse.get().owner == owner) { - blocked = false; - Mouse.get().let(owner); - return true; - } - return false; - } - - private static boolean use() { - return Mouse.get().use(null); - } - - protected synchronized boolean use(Object owner) { - if (owner == null) { - owner = this; - } else if (owner instanceof Region) { - if (((Region) owner).isOtherScreen()) { - return false; - } - } - if ((blocked || inUse) && this.owner == owner) { - return true; - } - while (inUse) { - try { - wait(); - } catch (InterruptedException e) { - } - } - if (!inUse) { - inUse = true; - checkLastPos(); - keep = false; - this.owner = owner; - Debug.log(3, "Mouse: use start: %s", owner); - return true; - } - Debug.error("Mouse: synch problem - use start: %s", owner); - return false; - } - - private static boolean let() { - return Mouse.get().let(null); - } - - protected synchronized boolean let(Object owner) { - if (owner == null) { - owner = this; - } else if (owner instanceof Region) { - if (((Region) owner).isOtherScreen()) { - return false; - } - } - if (inUse && this.owner == owner) { - if (keep) { - keep = false; - return true; - } - lastPos = MouseInfo.getPointerInfo().getLocation(); - inUse = false; - this.owner = null; - notify(); - Debug.log(3, "Mouse: use stop: %s", owner); - return true; - } - return false; - } - - protected synchronized boolean keep(Object owner) { - if (owner == null) { - owner = this; - } else if (owner instanceof Region) { - if (((Region) owner).isOtherScreen()) { - return false; - } - } - if (inUse && this.owner == owner) { - keep = true; - Debug.log(3, "Mouse: use keep: %s", owner); - return true; - } - return false; - } - - private void checkLastPos() { - if (lastPos == null) { - return; - } - Point pos = MouseInfo.getPointerInfo().getLocation(); - if (lastPos.x != pos.x || lastPos.y != pos.y) { - Debug.error("Mouse: moved externally"); - if (mouseMovedResponse > 0) { - showMousePos(pos); - } - if (mouseMovedResponse == 2) { -//TODO implement 2 - return; - } - if (mouseMovedResponse == 3) { -//TODO implement 3 - if (callBack != null) { - callBack.happened(new ObserveEvent("MouseMoved", ObserveEvent.Type.GENERIC, - lastPos, new Location(pos), null, (new Date()).getTime())); - } - } - } - } - - public static boolean hasMoved() { - Point pos = MouseInfo.getPointerInfo().getLocation(); - if (Mouse.get().lastPos.x != pos.x || Mouse.get().lastPos.y != pos.y) { - return true; - } - return false; - } - - private void showMousePos(Point pos) { - Location lPos = new Location(pos); - Region inner = lPos.grow(20).highlight(); - delay(500); - lPos.grow(40).highlight(1); - delay(500); - inner.highlight(); - } - - private static void delay(int time) { - if (time == 0) { - return; - } - if (time < 60) { - time = time * 1000; - } - try { - Thread.sleep(time); - } catch (InterruptedException e) { - } - } - - /** - * to click (left, right, middle - single or double) at the given location using the given button - * only useable for local screens - * - * timing parameters:
- * - one value
- * < 0 wait before mouse down
- * > 0 wait after mouse up
- * - 2 or 3 values - * 1st wait before mouse down
- * 2nd wait after mouse up
- * 3rd inner wait (milli secs, cut to 1000): pause between mouse down and up (Settings.ClickDelay) - * - * wait before and after: > 59 taken as milli secs - < are seconds - * - * @param loc where to click - * @param action L,R,M left, right, middle - D means double click - * @param args timing parameters - * @return the location - */ - public static Location click(Location loc, String action, Integer... args) { - if (suspended || loc.isOtherScreen()) { - return null; - } - getArgsClick(Mouse.get(), loc, action, args); - use(); - delay(Mouse.get().beforeWait); - Settings.ClickDelay = Mouse.get().innerWait / 1000; - click(loc, Mouse.get().buttons, 0, Mouse.get().clickDouble, null); - delay(Mouse.get().afterWait); - let(); - return loc; - } - - private static void getArgsClick(Mouse mouse, Location loc, String action, Integer... args) { - mouse.mousePos = loc; - mouse.clickDouble = false; - action = action.toUpperCase(); - if (action.contains("D")) { - mouse.clickDouble = true; - } - mouse.buttons = 0; - if (action.contains("L")) { - mouse.buttons += LEFT; - } - if (action.contains("M")) { - mouse.buttons += MIDDLE; - } - if (action.contains("R")) { - mouse.buttons += RIGHT; - } - if (mouse.buttons == 0) { - mouse.buttons = LEFT; - } - mouse.beforeWait = 0; - mouse.innerWait = 0; - mouse.afterWait = 0; - if (args.length > 0) { - if (args.length == 1) { - if (args[0] < 0) { - mouse.beforeWait = -args[0]; - } else { - mouse.afterWait = args[0]; - } - } - mouse.beforeWait = args[0]; - if (args.length > 1) { - mouse.afterWait = args[1]; - if (args.length > 2) { - mouse.innerWait = args[2]; - } - } - } - } - - protected static int click(Location loc, int buttons, int modifiers, boolean dblClick, Region region) { - if (loc == null) { - return 0; - } - IRobot r = loc.getRobotForPoint("click"); - if (r == null) { - return 0; - } - get().use(region); - Debug.action(getClickMsg(loc, buttons, modifiers, dblClick)); - r.smoothMove(loc); - r.clickStarts(); - r.pressModifiers(modifiers); - int pause = Settings.ClickDelay > 1 ? 1 : (int) (Settings.ClickDelay * 1000); - Settings.ClickDelay = 0.0; - if (dblClick) { - r.mouseDown(buttons); - r.mouseUp(buttons); - r.mouseDown(buttons); - r.mouseUp(buttons); - } else { - r.mouseDown(buttons); - r.delay(pause); - r.mouseUp(buttons); - } - r.releaseModifiers(modifiers); - r.clickEnds(); - r.waitForIdle(); - get().let(region); - return 1; - } - - private static String getClickMsg(Location loc, int buttons, int modifiers, boolean dblClick) { - String msg = ""; - if (modifiers != 0) { - msg += KeyEvent.getKeyModifiersText(modifiers) + "+"; - } - if (buttons == InputEvent.BUTTON1_MASK && !dblClick) { - msg += "CLICK"; - } - if (buttons == InputEvent.BUTTON1_MASK && dblClick) { - msg += "DOUBLE CLICK"; - } - if (buttons == InputEvent.BUTTON3_MASK) { - msg += "RIGHT CLICK"; - } else if (buttons == InputEvent.BUTTON2_MASK) { - msg += "MID CLICK"; - } - msg += " on " + loc; - return msg; - } - - /** - * move the mouse to the given location (local and remote) - * - * @param loc - * @return 1 for success, 0 otherwise - */ - public static int move(Location loc) { - return move(loc, null); - } - - protected static int move(Location loc, Region region) { - if (suspended) { - return 0; - } - if (loc != null) { - IRobot r = loc.getRobotForPoint("mouseMove"); - if (r == null) { - return 0; - } - if (!r.isRemote()) { - Mouse.get().use(region); - } - r.smoothMove(loc); - r.waitForIdle(); - if (!r.isRemote()) { - Mouse.get().let(region); - } - return 1; - } - return 0; - } - - /** - * press and hold the given buttons - * - * @param buttons - */ - public static void down(int buttons) { - down(buttons, null); - } - - protected static void down(int buttons, Region region) { - if (suspended) { - return; - } - get().use(region); - Screen.getPrimaryScreen().getRobot().mouseDown(buttons); - } - - /** - * release all buttons - * - */ - public static void up() { - up(0, null); - } - - /** - * release the given buttons - * - * @param buttons (0 releases all buttons) - */ - public static void up(int buttons) { - up(buttons, null); - } - - protected static void up(int buttons, Region region) { - if (suspended) { - return; - } - if (0 == Screen.getPrimaryScreen().getRobot().mouseUp(buttons)) { - get().let(region); - } - } - - /** - * move mouse using mouse wheel in the given direction the given steps
- * the result is system dependent - * - * @param direction - * @param steps - */ - public static void wheel(int direction, int steps) { - wheel(direction, steps, null); - } - - protected static void wheel(int direction, int steps, Region region) { - if (suspended) { - return; - } - IRobot r = Screen.getPrimaryScreen().getRobot(); - get().use(region); - Debug.log(3, "Region: wheel: %s steps: %d", - (direction == WHEEL_UP ? "WHEEL_UP" : "WHEEL_DOWN"), steps); - for (int i = 0; i < steps; i++) { - r.mouseWheel(direction); - r.delay(50); - } - get().let(region); - } -} diff --git a/All/Genesis-NP/Genesis#224/pair.info b/All/Genesis-NP/Genesis#224/pair.info deleted file mode 100755 index 263e423..0000000 --- a/All/Genesis-NP/Genesis#224/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:224 -SATName:Genesis -modifiedFPath:API/src/main/java/org/sikuli/script/Mouse.java -comSha:89dbc2989edbd0eb8a204f8f4f25766b2100140a -parentComSha:89dbc2989edbd0eb8a204f8f4f25766b2100140a^1 -githubUrl:https://github.com/RaiMan/SikuliX-2014 -repoName:RaiMan#SikuliX-2014 \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#229/comMsg.txt b/All/Genesis-NP/Genesis#229/comMsg.txt deleted file mode 100755 index 1562dcc..0000000 --- a/All/Genesis-NP/Genesis#229/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE in JDBC_PING (https://issues.jboss.org/browse/JGRP-1882) diff --git a/All/Genesis-NP/Genesis#229/diff.diff b/All/Genesis-NP/Genesis#229/diff.diff deleted file mode 100755 index 52f27d5..0000000 --- a/All/Genesis-NP/Genesis#229/diff.diff +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/src/org/jgroups/protocols/JDBC_PING.java b/src/org/jgroups/protocols/JDBC_PING.java -index da28eaf..f6b879f 100644 ---- a/src/org/jgroups/protocols/JDBC_PING.java -+++ b/src/org/jgroups/protocols/JDBC_PING.java -@@ -208 +207,0 @@ public class JDBC_PING extends Discovery { -- PingData data =null; -@@ -210,2 +209,2 @@ public class JDBC_PING extends Discovery { -- data=deserialize(bytes); -- if(members != null && !members.contains(data.getAddress())) -+ PingData data=deserialize(bytes); -+ if(data == null || (members != null && !members.contains(data.getAddress()))) -@@ -213,0 +213,2 @@ public class JDBC_PING extends Discovery { -+ if(local_addr != null && !local_addr.equals(data.getAddress())) -+ addDiscoveryResponseToCaches(data.getAddress(), data.getLogicalName(), data.getPhysicalAddr()); -@@ -225,2 +225,0 @@ public class JDBC_PING extends Discovery { -- if(local_addr != null && !local_addr.equals(data.getAddress())) -- addDiscoveryResponseToCaches(data.getAddress(), data.getLogicalName(), data.getPhysicalAddr()); diff --git a/All/Genesis-NP/Genesis#229/new/JDBC_PING.java b/All/Genesis-NP/Genesis#229/new/JDBC_PING.java deleted file mode 100755 index f6b879f..0000000 --- a/All/Genesis-NP/Genesis#229/new/JDBC_PING.java +++ /dev/null @@ -1,418 +0,0 @@ -package org.jgroups.protocols; - -import org.jgroups.Address; -import org.jgroups.Event; -import org.jgroups.PhysicalAddress; -import org.jgroups.View; -import org.jgroups.annotations.Property; -import org.jgroups.util.Responses; -import org.jgroups.util.UUID; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; -import java.sql.*; -import java.util.List; - -/** - *

Discovery protocol using a JDBC connection to a shared database. - * Connection options can be defined as configuration properties, or the JNDI - * name of a DataSource can be provided (avoid providing both).

- * - *

Both the schema and the used SQL statements can be customized; make sure - * the order of parameters of such customized SQL statements is maintained and - * that compatible types are used for the columns. The recommended schema uses a - * single table, with two String columns being used primary key (local address, - * cluster name) and a third column to store the serialized form of the objects - * needed by JGroups.

- * - *

A default table will be created at first connection, errors during this - * operation are not considered critical. Set the initialize_sql - * to an empty value to prevent this initial table creation, or change it to - * create a customized table.

- * - * @author Sanne Grinovero - * @since 2.12 - */ -public class JDBC_PING extends Discovery { - - /* ----------------------------------------- Properties -------------------------------------------------- */ - - @Property(description = "The JDBC connection URL", writable = false) - protected String connection_url = null; - - @Property(description = "The JDBC connection username", writable = false) - protected String connection_username = null; - - @Property(description = "The JDBC connection password", writable = false,exposeAsManagedAttribute=false) - protected String connection_password = null; - - @Property(description = "The JDBC connection driver name", writable = false) - protected String connection_driver = null; - - @Property(description = "If not empty, this SQL statement will be performed at startup." - + "Customize it to create the needed table on those databases which permit table creation attempt without loosing data, such as " - + "PostgreSQL and MySQL (using IF NOT EXISTS). To allow for creation attempts, errors performing this statement will be logged" - + "but not considered fatal. To avoid any DDL operation, set this to an empty string.") - protected String initialize_sql = - "CREATE TABLE JGROUPSPING (" + - "own_addr varchar(200) NOT NULL, " + - "cluster_name varchar(200) NOT NULL, " + - "ping_data varbinary(5000) DEFAULT NULL, " + - "PRIMARY KEY (own_addr, cluster_name) )"; - - @Property(description = "SQL used to insert a new row. Customizable, but keep the order of parameters and pick compatible types: " + - "1)Own Address, as String 2)Cluster name, as String 3)Serialized PingData as byte[]") - protected String insert_single_sql = "INSERT INTO JGROUPSPING (own_addr, cluster_name, ping_data) values (?, ?, ?)"; - - @Property(description = "SQL used to delete a row. Customizable, but keep the order of parameters and pick compatible types: " + - "1)Own Address, as String 2)Cluster name, as String") - protected String delete_single_sql = "DELETE FROM JGROUPSPING WHERE own_addr=? AND cluster_name=?"; - - @Property(description = "SQL used to fetch all node's PingData. Customizable, but keep the order of parameters and pick compatible types: " + - "only one parameter needed, String compatible, representing the Cluster name. Must return a byte[], the Serialized PingData as" + - " it was stored by the insert_single_sql statement") - protected String select_all_pingdata_sql = "SELECT ping_data FROM JGROUPSPING WHERE cluster_name=?"; - - @Property(description = "To use a DataSource registered in JNDI, specify the JNDI name here. " + - "This is an alternative to all connection_* configuration options: if this property is not empty, then all connection related" + - "properties must be empty.") - protected String datasource_jndi_name; - - /* --------------------------------------------- Fields ------------------------------------------------------ */ - - private DataSource dataSourceFromJNDI = null; - - public boolean isDynamic() {return true;} - - @Override - public void init() throws Exception { - super.init(); - verifyconfigurationParameters(); - if (stringIsEmpty(datasource_jndi_name)) - loadDriver(); - else - dataSourceFromJNDI = getDataSourceFromJNDI(datasource_jndi_name.trim()); - attemptSchemaInitialization(); - Runtime.getRuntime().addShutdownHook(new Thread() { - public void run() { - remove(cluster_name, local_addr); - } - }); - } - - @Override - public void stop() { - try { - deleteSelf(); - } catch (SQLException e) { - log.error("Error while unregistering of our own Address from JDBC_PING database during shutdown", e); - } - super.stop(); - } - - public Object down(Event evt) { - switch(evt.getType()) { - case Event.VIEW_CHANGE: - View old_view=view; - boolean previous_coord=is_coord; - Object retval=super.down(evt); - View new_view=(View)evt.getArg(); - handleView(new_view, old_view, previous_coord != is_coord); - return retval; - } - return super.down(evt); - } - - public void findMembers(final List
members, final boolean initial_discovery, Responses responses) { - readAll(members, cluster_name, responses); - writeOwnInformation(); - } - - - // remove all files which are not from the current members - protected void handleView(View new_view, View old_view, boolean coord_changed) { - if(is_coord && old_view != null && new_view != null) { - Address[][] diff=View.diff(old_view, new_view); - Address[] left_mbrs=diff[1]; - for(Address left_mbr: left_mbrs) - if(left_mbr != null && !new_view.containsMember(left_mbr)) - remove(cluster_name, left_mbr); - } - if(coord_changed) - writeOwnInformation(); - } - - /** Write my own UUID,logical name and physical address to a file */ - protected void writeOwnInformation() { - PhysicalAddress physical_addr=(PhysicalAddress)down(new Event(Event.GET_PHYSICAL_ADDRESS,local_addr)); - PingData data=new PingData(local_addr, is_server, UUID.get(local_addr), physical_addr).coord(is_coord); - writeToDB(data, cluster_name); // write my own data to file - } - - //It's possible that multiple threads in the same cluster node invoke this concurrently; - //Since delete and insert operations are not atomic - //(and there is no SQL standard way to do this without introducing a transaction) - //we need the synchronization or risk a duplicate insertion on same primary key. - //This synchronization should not be a performance problem as this is just a Discovery protocol. - //Many SQL dialects have some "insert or update" expression, but that would need - //additional configuration and testing on each database. See JGRP-1440 - protected synchronized void writeToDB(PingData data, String clustername) { - final String ownAddress = addressAsString(data.getAddress()); - final Connection connection = getConnection(); - if (connection != null) { - try { - delete(connection, clustername, ownAddress); - insert(connection, data, clustername, ownAddress); - } catch (SQLException e) { - log.error("Error updating JDBC_PING table", e); - } finally { - closeConnection(connection); - } - } - else { - log.error("Failed to store PingData in database"); - } - } - - - protected void remove(String clustername, Address addr) { - final String addressAsString = addressAsString(addr); - try { - delete(clustername, addressAsString); - } catch (SQLException e) { - log.error("Error", e); - } - } - - protected void readAll(List
members, String clustername, Responses responses) { - final Connection connection = getConnection(); - if (connection != null) { - try { - readAll(connection, members, clustername, responses); - } catch (SQLException e) { - log.error("Error reading JDBC_PING table", e); - } finally { - closeConnection(connection); - } - } - } - - protected void readAll(Connection connection, List
members, String clustername, Responses rsps) throws SQLException { - PreparedStatement ps = connection.prepareStatement(select_all_pingdata_sql); - try { - ps.setString(1, clustername); - ResultSet resultSet = ps.executeQuery(); - while (resultSet.next()) { - byte[] bytes = resultSet.getBytes(1); - try { - PingData data=deserialize(bytes); - if(data == null || (members != null && !members.contains(data.getAddress()))) - continue; - rsps.addResponse(data, false); - if(local_addr != null && !local_addr.equals(data.getAddress())) - addDiscoveryResponseToCaches(data.getAddress(), data.getLogicalName(), data.getPhysicalAddr()); - } - catch(Exception e) { - int row=resultSet.getRow(); - log.error("%s: failed deserializing row %d: %s; removing it from the table", local_addr, row, e); - try { - resultSet.deleteRow(); - } - catch(Throwable t) { - log.error("%s: failed removing row %d: %s; please delete it manually", local_addr, row, e); - } - } - } - } finally { - ps.close(); - } - } - - - protected void attemptSchemaInitialization() { - if(stringIsEmpty(initialize_sql)) { - log.debug("Table creation step skipped: initialize_sql property is missing"); - return; - } - Connection connection=getConnection(); - if(connection == null) - return; - - try { - connection.prepareStatement(initialize_sql).execute(); - log.debug("Table created for JDBC_PING Discovery Protocol"); - } - catch(SQLException e) { - log.debug("Could not execute initialize_sql statement; not necessarily an error, we always attempt to create the schema. " + - "To suppress this message, set initialize_sql to an empty value. Cause: %s", e.getMessage()); - } - finally { - try { - connection.close(); - } - catch(SQLException e) { - log.error("Error closing connection", e); - } - } - } - - protected void loadDriver() { - if (stringIsEmpty(connection_driver)) - return; - log.debug("Registering JDBC Driver named '%s'", connection_driver); - try { - Class.forName(connection_driver); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("JDBC Driver required for JDBC_PING " - + "protocol could not be loaded: '" + connection_driver + "'"); - } - } - - protected Connection getConnection() { - if (dataSourceFromJNDI == null) { - Connection connection; - try { - connection = DriverManager.getConnection(connection_url, connection_username, connection_password); - } catch (SQLException e) { - log.error("Could not open connection to database", e); - return null; - } - if (connection == null) { - log.error("Received null connection from the DriverManager!"); - } - return connection; - } - else { - try { - return dataSourceFromJNDI.getConnection(); - } catch (SQLException e) { - log.error("Could not open connection to database", e); - return null; - } - } - } - - - - protected synchronized void insert(Connection connection, PingData data, String clustername, String address) throws SQLException { - final byte[] serializedPingData = serializeWithoutView(data); - PreparedStatement ps = connection.prepareStatement(insert_single_sql); - try { - ps.setString(1, address); - ps.setString(2, clustername); - ps.setBytes(3, serializedPingData); - ps.executeUpdate(); - log.debug("Registered %s for clustername %s into database", address, clustername); - } finally { - ps.close(); - } - } - - protected synchronized void delete(Connection connection, String clustername, String addressToDelete) throws SQLException { - PreparedStatement ps = connection.prepareStatement(delete_single_sql); - try { - ps.setString(1, addressToDelete); - ps.setString(2, clustername); - ps.executeUpdate(); - log.debug("Removed %s for clustername %s from database", addressToDelete, clustername); - } finally { - ps.close(); - } - } - - protected void delete(String clustername, String addressToDelete) throws SQLException { - final Connection connection = getConnection(); - if (connection != null) { - try { - delete(connection, clustername, addressToDelete); - } catch (SQLException e) { - log.error("Error updating JDBC_PING table", e); - } finally { - closeConnection(connection); - } - } else { - log.error("Failed to delete PingData in database"); - } - } - - protected void deleteSelf() throws SQLException { - final String ownAddress = addressAsString(local_addr); - delete(cluster_name, ownAddress); - } - - - protected void closeConnection(final Connection connection) { - try { - connection.close(); - } catch (SQLException e) { - log.error("Error closing connection to JDBC_PING database", e); - } - } - - protected DataSource getDataSourceFromJNDI(String name) { - final DataSource dataSource; - InitialContext ctx = null; - try { - ctx = new InitialContext(); - Object wathever = ctx.lookup(name); - if (wathever == null) { - throw new IllegalArgumentException( - "JNDI name " + name + " is not bound"); - } else if (!(wathever instanceof DataSource)) { - throw new IllegalArgumentException( - "JNDI name " + name + " was found but is not a DataSource"); - } else { - dataSource = (DataSource) wathever; - log.debug("Datasource found via JNDI lookup via name: '%s'", name); - return dataSource; - } - } catch (NamingException e) { - throw new IllegalArgumentException( - "Could not lookup datasource " + name, e); - } finally { - if (ctx != null) { - try { - ctx.close(); - } catch (NamingException e) { - log.warn("Failed to close naming context.", e); - } - } - } - } - - protected void verifyconfigurationParameters() { - if (stringIsEmpty(this.connection_url) || - stringIsEmpty(this.connection_driver) || - stringIsEmpty(this.connection_username) ) { - if (stringIsEmpty(this.datasource_jndi_name)) { - throw new IllegalArgumentException("Either the 4 configuration properties starting with 'connection_' or the datasource_jndi_name must be set"); - } - } - if (stringNotEmpty(this.connection_url) || - stringNotEmpty(this.connection_driver) || - stringNotEmpty(this.connection_username) ) { - if (stringNotEmpty(this.datasource_jndi_name)) { - throw new IllegalArgumentException("When using the 'datasource_jndi_name' configuration property, all properties starting with 'connection_' must not be set"); - } - } - if (stringIsEmpty(this.insert_single_sql)) { - throw new IllegalArgumentException("The insert_single_sql configuration property is mandatory"); - } - if (stringIsEmpty(this.delete_single_sql)) { - throw new IllegalArgumentException("The delete_single_sql configuration property is mandatory"); - } - if (stringIsEmpty(this.select_all_pingdata_sql)) { - throw new IllegalArgumentException("The select_all_pingdata_sql configuration property is mandatory"); - } - } - - private static final boolean stringIsEmpty(final String value) { - return value == null || value.trim().isEmpty(); - } - - private static final boolean stringNotEmpty(final String value) { - return !stringIsEmpty(value); - } - -} diff --git a/All/Genesis-NP/Genesis#229/old/JDBC_PING.java b/All/Genesis-NP/Genesis#229/old/JDBC_PING.java deleted file mode 100755 index da28eaf..0000000 --- a/All/Genesis-NP/Genesis#229/old/JDBC_PING.java +++ /dev/null @@ -1,419 +0,0 @@ -package org.jgroups.protocols; - -import org.jgroups.Address; -import org.jgroups.Event; -import org.jgroups.PhysicalAddress; -import org.jgroups.View; -import org.jgroups.annotations.Property; -import org.jgroups.util.Responses; -import org.jgroups.util.UUID; - -import javax.naming.InitialContext; -import javax.naming.NamingException; -import javax.sql.DataSource; -import java.sql.*; -import java.util.List; - -/** - *

Discovery protocol using a JDBC connection to a shared database. - * Connection options can be defined as configuration properties, or the JNDI - * name of a DataSource can be provided (avoid providing both).

- * - *

Both the schema and the used SQL statements can be customized; make sure - * the order of parameters of such customized SQL statements is maintained and - * that compatible types are used for the columns. The recommended schema uses a - * single table, with two String columns being used primary key (local address, - * cluster name) and a third column to store the serialized form of the objects - * needed by JGroups.

- * - *

A default table will be created at first connection, errors during this - * operation are not considered critical. Set the initialize_sql - * to an empty value to prevent this initial table creation, or change it to - * create a customized table.

- * - * @author Sanne Grinovero - * @since 2.12 - */ -public class JDBC_PING extends Discovery { - - /* ----------------------------------------- Properties -------------------------------------------------- */ - - @Property(description = "The JDBC connection URL", writable = false) - protected String connection_url = null; - - @Property(description = "The JDBC connection username", writable = false) - protected String connection_username = null; - - @Property(description = "The JDBC connection password", writable = false,exposeAsManagedAttribute=false) - protected String connection_password = null; - - @Property(description = "The JDBC connection driver name", writable = false) - protected String connection_driver = null; - - @Property(description = "If not empty, this SQL statement will be performed at startup." - + "Customize it to create the needed table on those databases which permit table creation attempt without loosing data, such as " - + "PostgreSQL and MySQL (using IF NOT EXISTS). To allow for creation attempts, errors performing this statement will be logged" - + "but not considered fatal. To avoid any DDL operation, set this to an empty string.") - protected String initialize_sql = - "CREATE TABLE JGROUPSPING (" + - "own_addr varchar(200) NOT NULL, " + - "cluster_name varchar(200) NOT NULL, " + - "ping_data varbinary(5000) DEFAULT NULL, " + - "PRIMARY KEY (own_addr, cluster_name) )"; - - @Property(description = "SQL used to insert a new row. Customizable, but keep the order of parameters and pick compatible types: " + - "1)Own Address, as String 2)Cluster name, as String 3)Serialized PingData as byte[]") - protected String insert_single_sql = "INSERT INTO JGROUPSPING (own_addr, cluster_name, ping_data) values (?, ?, ?)"; - - @Property(description = "SQL used to delete a row. Customizable, but keep the order of parameters and pick compatible types: " + - "1)Own Address, as String 2)Cluster name, as String") - protected String delete_single_sql = "DELETE FROM JGROUPSPING WHERE own_addr=? AND cluster_name=?"; - - @Property(description = "SQL used to fetch all node's PingData. Customizable, but keep the order of parameters and pick compatible types: " + - "only one parameter needed, String compatible, representing the Cluster name. Must return a byte[], the Serialized PingData as" + - " it was stored by the insert_single_sql statement") - protected String select_all_pingdata_sql = "SELECT ping_data FROM JGROUPSPING WHERE cluster_name=?"; - - @Property(description = "To use a DataSource registered in JNDI, specify the JNDI name here. " + - "This is an alternative to all connection_* configuration options: if this property is not empty, then all connection related" + - "properties must be empty.") - protected String datasource_jndi_name; - - /* --------------------------------------------- Fields ------------------------------------------------------ */ - - private DataSource dataSourceFromJNDI = null; - - public boolean isDynamic() {return true;} - - @Override - public void init() throws Exception { - super.init(); - verifyconfigurationParameters(); - if (stringIsEmpty(datasource_jndi_name)) - loadDriver(); - else - dataSourceFromJNDI = getDataSourceFromJNDI(datasource_jndi_name.trim()); - attemptSchemaInitialization(); - Runtime.getRuntime().addShutdownHook(new Thread() { - public void run() { - remove(cluster_name, local_addr); - } - }); - } - - @Override - public void stop() { - try { - deleteSelf(); - } catch (SQLException e) { - log.error("Error while unregistering of our own Address from JDBC_PING database during shutdown", e); - } - super.stop(); - } - - public Object down(Event evt) { - switch(evt.getType()) { - case Event.VIEW_CHANGE: - View old_view=view; - boolean previous_coord=is_coord; - Object retval=super.down(evt); - View new_view=(View)evt.getArg(); - handleView(new_view, old_view, previous_coord != is_coord); - return retval; - } - return super.down(evt); - } - - public void findMembers(final List
members, final boolean initial_discovery, Responses responses) { - readAll(members, cluster_name, responses); - writeOwnInformation(); - } - - - // remove all files which are not from the current members - protected void handleView(View new_view, View old_view, boolean coord_changed) { - if(is_coord && old_view != null && new_view != null) { - Address[][] diff=View.diff(old_view, new_view); - Address[] left_mbrs=diff[1]; - for(Address left_mbr: left_mbrs) - if(left_mbr != null && !new_view.containsMember(left_mbr)) - remove(cluster_name, left_mbr); - } - if(coord_changed) - writeOwnInformation(); - } - - /** Write my own UUID,logical name and physical address to a file */ - protected void writeOwnInformation() { - PhysicalAddress physical_addr=(PhysicalAddress)down(new Event(Event.GET_PHYSICAL_ADDRESS,local_addr)); - PingData data=new PingData(local_addr, is_server, UUID.get(local_addr), physical_addr).coord(is_coord); - writeToDB(data, cluster_name); // write my own data to file - } - - //It's possible that multiple threads in the same cluster node invoke this concurrently; - //Since delete and insert operations are not atomic - //(and there is no SQL standard way to do this without introducing a transaction) - //we need the synchronization or risk a duplicate insertion on same primary key. - //This synchronization should not be a performance problem as this is just a Discovery protocol. - //Many SQL dialects have some "insert or update" expression, but that would need - //additional configuration and testing on each database. See JGRP-1440 - protected synchronized void writeToDB(PingData data, String clustername) { - final String ownAddress = addressAsString(data.getAddress()); - final Connection connection = getConnection(); - if (connection != null) { - try { - delete(connection, clustername, ownAddress); - insert(connection, data, clustername, ownAddress); - } catch (SQLException e) { - log.error("Error updating JDBC_PING table", e); - } finally { - closeConnection(connection); - } - } - else { - log.error("Failed to store PingData in database"); - } - } - - - protected void remove(String clustername, Address addr) { - final String addressAsString = addressAsString(addr); - try { - delete(clustername, addressAsString); - } catch (SQLException e) { - log.error("Error", e); - } - } - - protected void readAll(List
members, String clustername, Responses responses) { - final Connection connection = getConnection(); - if (connection != null) { - try { - readAll(connection, members, clustername, responses); - } catch (SQLException e) { - log.error("Error reading JDBC_PING table", e); - } finally { - closeConnection(connection); - } - } - } - - protected void readAll(Connection connection, List
members, String clustername, Responses rsps) throws SQLException { - PreparedStatement ps = connection.prepareStatement(select_all_pingdata_sql); - try { - ps.setString(1, clustername); - ResultSet resultSet = ps.executeQuery(); - while (resultSet.next()) { - byte[] bytes = resultSet.getBytes(1); - PingData data =null; - try { - data=deserialize(bytes); - if(members != null && !members.contains(data.getAddress())) - continue; - rsps.addResponse(data, false); - } - catch(Exception e) { - int row=resultSet.getRow(); - log.error("%s: failed deserializing row %d: %s; removing it from the table", local_addr, row, e); - try { - resultSet.deleteRow(); - } - catch(Throwable t) { - log.error("%s: failed removing row %d: %s; please delete it manually", local_addr, row, e); - } - } - if(local_addr != null && !local_addr.equals(data.getAddress())) - addDiscoveryResponseToCaches(data.getAddress(), data.getLogicalName(), data.getPhysicalAddr()); - } - } finally { - ps.close(); - } - } - - - protected void attemptSchemaInitialization() { - if(stringIsEmpty(initialize_sql)) { - log.debug("Table creation step skipped: initialize_sql property is missing"); - return; - } - Connection connection=getConnection(); - if(connection == null) - return; - - try { - connection.prepareStatement(initialize_sql).execute(); - log.debug("Table created for JDBC_PING Discovery Protocol"); - } - catch(SQLException e) { - log.debug("Could not execute initialize_sql statement; not necessarily an error, we always attempt to create the schema. " + - "To suppress this message, set initialize_sql to an empty value. Cause: %s", e.getMessage()); - } - finally { - try { - connection.close(); - } - catch(SQLException e) { - log.error("Error closing connection", e); - } - } - } - - protected void loadDriver() { - if (stringIsEmpty(connection_driver)) - return; - log.debug("Registering JDBC Driver named '%s'", connection_driver); - try { - Class.forName(connection_driver); - } catch (ClassNotFoundException e) { - throw new IllegalArgumentException("JDBC Driver required for JDBC_PING " - + "protocol could not be loaded: '" + connection_driver + "'"); - } - } - - protected Connection getConnection() { - if (dataSourceFromJNDI == null) { - Connection connection; - try { - connection = DriverManager.getConnection(connection_url, connection_username, connection_password); - } catch (SQLException e) { - log.error("Could not open connection to database", e); - return null; - } - if (connection == null) { - log.error("Received null connection from the DriverManager!"); - } - return connection; - } - else { - try { - return dataSourceFromJNDI.getConnection(); - } catch (SQLException e) { - log.error("Could not open connection to database", e); - return null; - } - } - } - - - - protected synchronized void insert(Connection connection, PingData data, String clustername, String address) throws SQLException { - final byte[] serializedPingData = serializeWithoutView(data); - PreparedStatement ps = connection.prepareStatement(insert_single_sql); - try { - ps.setString(1, address); - ps.setString(2, clustername); - ps.setBytes(3, serializedPingData); - ps.executeUpdate(); - log.debug("Registered %s for clustername %s into database", address, clustername); - } finally { - ps.close(); - } - } - - protected synchronized void delete(Connection connection, String clustername, String addressToDelete) throws SQLException { - PreparedStatement ps = connection.prepareStatement(delete_single_sql); - try { - ps.setString(1, addressToDelete); - ps.setString(2, clustername); - ps.executeUpdate(); - log.debug("Removed %s for clustername %s from database", addressToDelete, clustername); - } finally { - ps.close(); - } - } - - protected void delete(String clustername, String addressToDelete) throws SQLException { - final Connection connection = getConnection(); - if (connection != null) { - try { - delete(connection, clustername, addressToDelete); - } catch (SQLException e) { - log.error("Error updating JDBC_PING table", e); - } finally { - closeConnection(connection); - } - } else { - log.error("Failed to delete PingData in database"); - } - } - - protected void deleteSelf() throws SQLException { - final String ownAddress = addressAsString(local_addr); - delete(cluster_name, ownAddress); - } - - - protected void closeConnection(final Connection connection) { - try { - connection.close(); - } catch (SQLException e) { - log.error("Error closing connection to JDBC_PING database", e); - } - } - - protected DataSource getDataSourceFromJNDI(String name) { - final DataSource dataSource; - InitialContext ctx = null; - try { - ctx = new InitialContext(); - Object wathever = ctx.lookup(name); - if (wathever == null) { - throw new IllegalArgumentException( - "JNDI name " + name + " is not bound"); - } else if (!(wathever instanceof DataSource)) { - throw new IllegalArgumentException( - "JNDI name " + name + " was found but is not a DataSource"); - } else { - dataSource = (DataSource) wathever; - log.debug("Datasource found via JNDI lookup via name: '%s'", name); - return dataSource; - } - } catch (NamingException e) { - throw new IllegalArgumentException( - "Could not lookup datasource " + name, e); - } finally { - if (ctx != null) { - try { - ctx.close(); - } catch (NamingException e) { - log.warn("Failed to close naming context.", e); - } - } - } - } - - protected void verifyconfigurationParameters() { - if (stringIsEmpty(this.connection_url) || - stringIsEmpty(this.connection_driver) || - stringIsEmpty(this.connection_username) ) { - if (stringIsEmpty(this.datasource_jndi_name)) { - throw new IllegalArgumentException("Either the 4 configuration properties starting with 'connection_' or the datasource_jndi_name must be set"); - } - } - if (stringNotEmpty(this.connection_url) || - stringNotEmpty(this.connection_driver) || - stringNotEmpty(this.connection_username) ) { - if (stringNotEmpty(this.datasource_jndi_name)) { - throw new IllegalArgumentException("When using the 'datasource_jndi_name' configuration property, all properties starting with 'connection_' must not be set"); - } - } - if (stringIsEmpty(this.insert_single_sql)) { - throw new IllegalArgumentException("The insert_single_sql configuration property is mandatory"); - } - if (stringIsEmpty(this.delete_single_sql)) { - throw new IllegalArgumentException("The delete_single_sql configuration property is mandatory"); - } - if (stringIsEmpty(this.select_all_pingdata_sql)) { - throw new IllegalArgumentException("The select_all_pingdata_sql configuration property is mandatory"); - } - } - - private static final boolean stringIsEmpty(final String value) { - return value == null || value.trim().isEmpty(); - } - - private static final boolean stringNotEmpty(final String value) { - return !stringIsEmpty(value); - } - -} diff --git a/All/Genesis-NP/Genesis#229/pair.info b/All/Genesis-NP/Genesis#229/pair.info deleted file mode 100755 index 8a41567..0000000 --- a/All/Genesis-NP/Genesis#229/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:229 -SATName:Genesis -modifiedFPath:src/org/jgroups/protocols/JDBC_PING.java -comSha:2fde0850c7e3ba9bb6c6c31baf8606693dc43372 -parentComSha:2fde0850c7e3ba9bb6c6c31baf8606693dc43372^1 -githubUrl:https://github.com/belaban/JGroups -repoName:belaban#JGroups \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#232/comMsg.txt b/All/Genesis-NP/Genesis#232/comMsg.txt deleted file mode 100755 index 7901de7..0000000 --- a/All/Genesis-NP/Genesis#232/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -JGRP-1848 Avoid NPE when SASL password is not set (e.g. in case of GSSAPI) diff --git a/All/Genesis-NP/Genesis#232/diff.diff b/All/Genesis-NP/Genesis#232/diff.diff deleted file mode 100755 index 32c6e0d..0000000 --- a/All/Genesis-NP/Genesis#232/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/org/jgroups/protocols/SASL.java b/src/org/jgroups/protocols/SASL.java -index 3472f24..2787a76 100644 ---- a/src/org/jgroups/protocols/SASL.java -+++ b/src/org/jgroups/protocols/SASL.java -@@ -180,2 +180,3 @@ public class SASL extends Protocol { -- if (client_callback_handler == null) { -- client_callback_handler = new SaslClientCallbackHandler(client_name, client_password.toCharArray()); -+ char[] client_password_chars = client_password == null ? new char[]{} : client_password.toCharArray(); -+ if (client_callback_handler == null && client_password != null) { -+ client_callback_handler = new SaslClientCallbackHandler(client_name, client_password_chars); -@@ -189 +190 @@ public class SASL extends Protocol { -- LoginContext lc = new LoginContext(login_module_name, new SaslClientCallbackHandler(client_name, client_password.toCharArray())); -+ LoginContext lc = new LoginContext(login_module_name, new SaslClientCallbackHandler(client_name, client_password_chars)); diff --git a/All/Genesis-NP/Genesis#232/new/SASL.java b/All/Genesis-NP/Genesis#232/new/SASL.java deleted file mode 100755 index 2787a76..0000000 --- a/All/Genesis-NP/Genesis#232/new/SASL.java +++ /dev/null @@ -1,413 +0,0 @@ -package org.jgroups.protocols; - -import java.util.HashMap; -import java.util.Map; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.login.LoginContext; -import javax.security.sasl.SaslClientFactory; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServerFactory; - -import org.jgroups.Address; -import org.jgroups.Event; -import org.jgroups.Message; -import org.jgroups.annotations.MBean; -import org.jgroups.annotations.Property; -import org.jgroups.auth.sasl.SaslClientCallbackHandler; -import org.jgroups.auth.sasl.SaslClientContext; -import org.jgroups.auth.sasl.SaslContext; -import org.jgroups.auth.sasl.SaslServerContext; -import org.jgroups.auth.sasl.SaslUtils; -import org.jgroups.conf.ClassConfigurator; -import org.jgroups.conf.PropertyConverters; -import org.jgroups.protocols.pbcast.GMS; -import org.jgroups.protocols.pbcast.GMS.GmsHeader; -import org.jgroups.protocols.pbcast.JoinRsp; -import org.jgroups.stack.Protocol; -import org.jgroups.util.MessageBatch; - -/** - * The SASL protocol implements authentication and, if requested by the mech, encryption - * - * @author Tristan Tarrant - */ -@MBean(description = "Provides SASL authentication") -public class SASL extends Protocol { - public static final short GMS_ID = ClassConfigurator.getProtocolId(GMS.class); - public static final short SASL_ID = ClassConfigurator.getProtocolId(SASL.class); - public static final String SASL_PROTOCOL_NAME = "jgroups"; - - @Property(name = "login_module_name", description = "The name of the JAAS login module to use to obtain a subject for creating the SASL client and server (optional). Only required by some SASL mechs (e.g. GSSAPI)") - protected String login_module_name; - - @Property(name = "client_name", description = "The name to use when a node is acting as a client (i.e. it is not the coordinator. Will also be used to obtain the subject if using a JAAS login module") - protected String client_name; - - @Property(name = "client_password", description = "The password to use when a node is acting as a client (i.e. it is not the coordinator. Will also be used to obtain the subject if using a JAAS login module") - protected String client_password; - - @Property(name = "mech", description = "The name of the mech to require for authentication. Can be any mech supported by your local SASL provider. The JDK comes standard with CRAM-MD5, DIGEST-MD5, GSSAPI, NTLM") - protected String mech; - - @Property(name = "sasl_props", description = "Properties specific to the chosen mech", converter = PropertyConverters.StringProperties.class) - protected Map sasl_props = new HashMap(); - - @Property(name = "server_name", description = "The fully qualified server name") - protected String server_name; - - @Property(name = "timeout", description = "How long to wait (in ms) for a response to a challenge") - protected long timeout = 5000; - - @Property(name = "client_callback_handler", description = "The CallbackHandler to use when a node acts as a client (i.e. it is not the coordinator") - protected CallbackHandler client_callback_handler; - - @Property(name = "server_callback_handler", description = "The CallbackHandler to use when a node acts as a server (i.e. it is the coordinator") - protected CallbackHandler server_callback_handler; - - protected Subject client_subject; - protected Subject server_subject; - - protected Address local_addr; - protected final Map sasl_context = new HashMap(); - private SaslServerFactory saslServerFactory; - private SaslClientFactory saslClientFactory; - - public SASL() { - name = this.getClass().getSimpleName(); - } - - @Property(name = "client_callback_handler_class") - public void setClientCallbackHandlerClass(String handlerClass) throws Exception { - client_callback_handler = Class.forName(handlerClass).asSubclass(CallbackHandler.class).newInstance(); - } - - public String getClientCallbackHandlerClass() { - return client_callback_handler != null ? client_callback_handler.getClass().getName() : null; - } - - public CallbackHandler getClientCallbackHandler() { - return client_callback_handler; - } - - public void setClientCallbackHandler(CallbackHandler client_callback_handler) { - this.client_callback_handler = client_callback_handler; - } - - @Property(name = "server_callback_handler_class") - public void setServerCallbackHandlerClass(String handlerClass) throws Exception { - server_callback_handler = Class.forName(handlerClass).asSubclass(CallbackHandler.class).newInstance(); - } - - public String getServerCallbackHandlerClass() { - return server_callback_handler != null ? server_callback_handler.getClass().getName() : null; - } - - public CallbackHandler getServerCallbackHandler() { - return server_callback_handler; - } - - public void setServerCallbackHandler(CallbackHandler server_callback_handler) { - this.server_callback_handler = server_callback_handler; - } - - public void setLoginModuleName(String login_module_name) { - this.login_module_name = login_module_name; - } - - public String getLoginModulename() { - return login_module_name; - } - - public void setMech(String mech) { - this.mech = mech; - } - - public String getMech() { - return mech; - } - - public void setSaslProps(Map sasl_props) { - this.sasl_props = sasl_props; - } - - public Map getSaslProps() { - return sasl_props; - } - - public void setClientSubject(Subject client_subject) { - this.client_subject = client_subject; - } - - public Subject getClientSubject() { - return client_subject; - } - - public void setServerSubject(Subject server_subject) { - this.server_subject = server_subject; - } - - public Subject getServerSubject() { - return server_subject; - } - - public void setServerName(String server_name) { - this.server_name = server_name; - } - - public String getServerName(String server_name) { - return server_name; - } - - public void setTimeout(long timeout) { - this.timeout = timeout; - } - - public long getTimeout() { - return timeout; - } - - public Address getAddress() { - return local_addr; - } - - @Override - public void init() throws Exception { - super.init(); - saslServerFactory = SaslUtils.getSaslServerFactory(mech, sasl_props); - saslClientFactory = SaslUtils.getSaslClientFactory(mech, sasl_props); - char[] client_password_chars = client_password == null ? new char[]{} : client_password.toCharArray(); - if (client_callback_handler == null && client_password != null) { - client_callback_handler = new SaslClientCallbackHandler(client_name, client_password_chars); - } - if (server_subject == null && login_module_name != null) { - LoginContext lc = new LoginContext(login_module_name); - lc.login(); - server_subject = lc.getSubject(); - } - if (client_subject == null && login_module_name != null) { - LoginContext lc = new LoginContext(login_module_name, new SaslClientCallbackHandler(client_name, client_password_chars)); - lc.login(); - client_subject = lc.getSubject(); - } - } - - @Override - public void stop() { - super.stop(); - cleanup(); - } - - @Override - public void destroy() { - super.destroy(); - cleanup(); - } - - private void cleanup() { - for(SaslContext context : sasl_context.values()) { - context.dispose(); - } - sasl_context.clear(); - } - - @Override - public Object up(Event evt) { - if (evt.getType() == Event.MSG) { - Message msg = (Message) evt.getArg(); - SaslHeader saslHeader = (SaslHeader) msg.getHeader(SASL_ID); - GmsHeader gmsHeader = (GmsHeader) msg.getHeader(GMS_ID); - if (needsAuthentication(gmsHeader)) { - if (saslHeader == null) - throw new IllegalStateException("Found GMS join or merge request but no SASL header"); - if (!serverChallenge(gmsHeader, saslHeader, msg)) - return null; // failed auth, don't pass up - } else if (saslHeader != null) { - Address remoteAddress = msg.getSrc(); - SaslContext saslContext = sasl_context.get(remoteAddress); - if (saslContext == null) { - throw new IllegalStateException(String.format( - "Cannot find server context to challenge SASL request from %s", remoteAddress.toString())); - } - switch (saslHeader.getType()) { - case CHALLENGE: - try { - if (log.isTraceEnabled()) - log.trace("%s: received CHALLENGE from %s", getAddress(), remoteAddress); - Message response = saslContext.nextMessage(remoteAddress, saslHeader); - if (log.isTraceEnabled()) - log.trace("%s: sending RESPONSE to %s", getAddress(), remoteAddress); - down_prot.down(new Event(Event.MSG, response)); - } catch (SaslException e) { - disposeContext(remoteAddress); - if (log.isWarnEnabled()) { - log.warn("failed to validate CHALLENGE from " + remoteAddress + ", token", e); - } - sendRejectionMessage(gmsHeader.getType(), remoteAddress, "authentication failed"); - } - break; - case RESPONSE: - try { - if (log.isTraceEnabled()) - log.trace("%s: received RESPONSE from %s", getAddress(), remoteAddress); - Message challenge = saslContext.nextMessage(remoteAddress, saslHeader); - if (challenge != null) { - if (log.isTraceEnabled()) - log.trace("%s: sending CHALLENGE to %s", getAddress(), remoteAddress); - - down_prot.down(new Event(Event.MSG, challenge)); - } else { - if (log.isTraceEnabled()) - log.trace("%s: authentication complete from %s", getAddress(), remoteAddress); - } - } catch (SaslException e) { - disposeContext(remoteAddress); - if (log.isWarnEnabled()) { - log.warn("failed to validate RESPONSE from " + remoteAddress + ", token", e); - } - } - break; - } - return null; - } - } - - return up_prot.up(evt); - } - - private void disposeContext(Address address) { - SaslContext context = sasl_context.remove(address); - if (context != null) { - context.dispose(); - } - } - - @Override - public void up(MessageBatch batch) { - for (Message msg : batch) { - // If we have a join or merge request --> authenticate, else pass up - GmsHeader gmsHeader = (GmsHeader) msg.getHeader(GMS_ID); - if (needsAuthentication(gmsHeader)) { - SaslHeader saslHeader = (SaslHeader) msg.getHeader(id); - if (saslHeader == null) { - log.warn("Found GMS join or merge request but no SASL header"); - sendRejectionMessage(gmsHeader.getType(), batch.sender(), "join or merge without an SASL header"); - batch.remove(msg); - } else if (!serverChallenge(gmsHeader, saslHeader, msg)) // authentication failed - batch.remove(msg); // don't pass up - } - } - - if (!batch.isEmpty()) - up_prot.up(batch); - } - - @Override - public Object down(Event evt) { - switch (evt.getType()) { - case Event.SET_LOCAL_ADDRESS: - local_addr = (Address) evt.getArg(); - break; - case Event.MSG: - Message msg = (Message) evt.getArg(); - GmsHeader hdr = (GmsHeader) msg.getHeader(GMS_ID); - if (needsAuthentication(hdr)) { - // We are a client who needs to authenticate - SaslClientContext ctx = null; - Address remoteAddress = msg.getDest(); - try { - ctx = new SaslClientContext(saslClientFactory, mech, server_name != null ? server_name : remoteAddress.toString(), client_callback_handler, sasl_props, client_subject); - sasl_context.put(remoteAddress, ctx); - ctx.addHeader(msg, null); - } catch (Exception e) { - if (ctx != null) { - disposeContext(remoteAddress); - } - throw new SecurityException(e); - } - } - break; - } - - return down_prot.down(evt); - } - - protected static boolean needsAuthentication(GmsHeader hdr) { - return (hdr != null) - && (hdr.getType() == GmsHeader.JOIN_REQ || hdr.getType() == GmsHeader.JOIN_REQ_WITH_STATE_TRANSFER || hdr - .getType() == GmsHeader.MERGE_REQ); - } - - protected boolean serverChallenge(GmsHeader gmsHeader, SaslHeader saslHeader, Message msg) { - switch (gmsHeader.getType()) { - case GmsHeader.JOIN_REQ: - case GmsHeader.JOIN_REQ_WITH_STATE_TRANSFER: - case GmsHeader.MERGE_REQ: - Address remoteAddress = msg.getSrc(); - SaslServerContext ctx = null; - try { - ctx = new SaslServerContext(saslServerFactory, mech, server_name != null ? server_name : local_addr.toString(), server_callback_handler, sasl_props, server_subject); - sasl_context.put(remoteAddress, ctx); - this.getDownProtocol().down(new Event(Event.MSG, ctx.nextMessage(remoteAddress, saslHeader))); - ctx.awaitCompletion(timeout); - if (ctx.isSuccessful()) { - if (log.isDebugEnabled()) { - log.debug("Authentication successful for %s", ctx.getAuthorizationID()); - } - return true; - } else { - log.warn("failed to validate SaslHeader from %s, header: %s", msg.getSrc(), saslHeader); - sendRejectionMessage(gmsHeader.getType(), msg.getSrc(), "authentication failed"); - return false; - } - } catch (SaslException e) { - log.warn("failed to validate SaslHeader from %s, header: %s", msg.getSrc(), saslHeader); - sendRejectionMessage(gmsHeader.getType(), msg.getSrc(), "authentication failed"); - } catch (InterruptedException e) { - return false; - } finally { - if (ctx != null && !ctx.needsWrapping()) { - disposeContext(remoteAddress); - } - } - default: - return true; // pass up - } - } - - protected void sendRejectionMessage(byte type, Address dest, String error_msg) { - switch (type) { - case GmsHeader.JOIN_REQ: - case GmsHeader.JOIN_REQ_WITH_STATE_TRANSFER: - sendJoinRejectionMessage(dest, error_msg); - break; - case GmsHeader.MERGE_REQ: - sendMergeRejectionMessage(dest); - break; - default: - log.error("type " + type + " unknown"); - break; - } - } - - protected void sendJoinRejectionMessage(Address dest, String error_msg) { - if (dest == null) - return; - - JoinRsp joinRes = new JoinRsp(error_msg); // specify the error message on the JoinRsp - Message msg = new Message(dest).putHeader(GMS_ID, new GmsHeader(GmsHeader.JOIN_RSP)).setBuffer( - GMS.marshal(joinRes)); - down_prot.down(new Event(Event.MSG, msg)); - } - - protected void sendMergeRejectionMessage(Address dest) { - Message msg = new Message(dest).setFlag(Message.Flag.OOB); - GmsHeader hdr = new GmsHeader(GmsHeader.MERGE_RSP); - hdr.setMergeRejected(true); - msg.putHeader(GMS_ID, hdr); - if (log.isDebugEnabled()) - log.debug("merge response=" + hdr); - down_prot.down(new Event(Event.MSG, msg)); - } -} diff --git a/All/Genesis-NP/Genesis#232/old/SASL.java b/All/Genesis-NP/Genesis#232/old/SASL.java deleted file mode 100755 index 3472f24..0000000 --- a/All/Genesis-NP/Genesis#232/old/SASL.java +++ /dev/null @@ -1,412 +0,0 @@ -package org.jgroups.protocols; - -import java.util.HashMap; -import java.util.Map; - -import javax.security.auth.Subject; -import javax.security.auth.callback.CallbackHandler; -import javax.security.auth.login.LoginContext; -import javax.security.sasl.SaslClientFactory; -import javax.security.sasl.SaslException; -import javax.security.sasl.SaslServerFactory; - -import org.jgroups.Address; -import org.jgroups.Event; -import org.jgroups.Message; -import org.jgroups.annotations.MBean; -import org.jgroups.annotations.Property; -import org.jgroups.auth.sasl.SaslClientCallbackHandler; -import org.jgroups.auth.sasl.SaslClientContext; -import org.jgroups.auth.sasl.SaslContext; -import org.jgroups.auth.sasl.SaslServerContext; -import org.jgroups.auth.sasl.SaslUtils; -import org.jgroups.conf.ClassConfigurator; -import org.jgroups.conf.PropertyConverters; -import org.jgroups.protocols.pbcast.GMS; -import org.jgroups.protocols.pbcast.GMS.GmsHeader; -import org.jgroups.protocols.pbcast.JoinRsp; -import org.jgroups.stack.Protocol; -import org.jgroups.util.MessageBatch; - -/** - * The SASL protocol implements authentication and, if requested by the mech, encryption - * - * @author Tristan Tarrant - */ -@MBean(description = "Provides SASL authentication") -public class SASL extends Protocol { - public static final short GMS_ID = ClassConfigurator.getProtocolId(GMS.class); - public static final short SASL_ID = ClassConfigurator.getProtocolId(SASL.class); - public static final String SASL_PROTOCOL_NAME = "jgroups"; - - @Property(name = "login_module_name", description = "The name of the JAAS login module to use to obtain a subject for creating the SASL client and server (optional). Only required by some SASL mechs (e.g. GSSAPI)") - protected String login_module_name; - - @Property(name = "client_name", description = "The name to use when a node is acting as a client (i.e. it is not the coordinator. Will also be used to obtain the subject if using a JAAS login module") - protected String client_name; - - @Property(name = "client_password", description = "The password to use when a node is acting as a client (i.e. it is not the coordinator. Will also be used to obtain the subject if using a JAAS login module") - protected String client_password; - - @Property(name = "mech", description = "The name of the mech to require for authentication. Can be any mech supported by your local SASL provider. The JDK comes standard with CRAM-MD5, DIGEST-MD5, GSSAPI, NTLM") - protected String mech; - - @Property(name = "sasl_props", description = "Properties specific to the chosen mech", converter = PropertyConverters.StringProperties.class) - protected Map sasl_props = new HashMap(); - - @Property(name = "server_name", description = "The fully qualified server name") - protected String server_name; - - @Property(name = "timeout", description = "How long to wait (in ms) for a response to a challenge") - protected long timeout = 5000; - - @Property(name = "client_callback_handler", description = "The CallbackHandler to use when a node acts as a client (i.e. it is not the coordinator") - protected CallbackHandler client_callback_handler; - - @Property(name = "server_callback_handler", description = "The CallbackHandler to use when a node acts as a server (i.e. it is the coordinator") - protected CallbackHandler server_callback_handler; - - protected Subject client_subject; - protected Subject server_subject; - - protected Address local_addr; - protected final Map sasl_context = new HashMap(); - private SaslServerFactory saslServerFactory; - private SaslClientFactory saslClientFactory; - - public SASL() { - name = this.getClass().getSimpleName(); - } - - @Property(name = "client_callback_handler_class") - public void setClientCallbackHandlerClass(String handlerClass) throws Exception { - client_callback_handler = Class.forName(handlerClass).asSubclass(CallbackHandler.class).newInstance(); - } - - public String getClientCallbackHandlerClass() { - return client_callback_handler != null ? client_callback_handler.getClass().getName() : null; - } - - public CallbackHandler getClientCallbackHandler() { - return client_callback_handler; - } - - public void setClientCallbackHandler(CallbackHandler client_callback_handler) { - this.client_callback_handler = client_callback_handler; - } - - @Property(name = "server_callback_handler_class") - public void setServerCallbackHandlerClass(String handlerClass) throws Exception { - server_callback_handler = Class.forName(handlerClass).asSubclass(CallbackHandler.class).newInstance(); - } - - public String getServerCallbackHandlerClass() { - return server_callback_handler != null ? server_callback_handler.getClass().getName() : null; - } - - public CallbackHandler getServerCallbackHandler() { - return server_callback_handler; - } - - public void setServerCallbackHandler(CallbackHandler server_callback_handler) { - this.server_callback_handler = server_callback_handler; - } - - public void setLoginModuleName(String login_module_name) { - this.login_module_name = login_module_name; - } - - public String getLoginModulename() { - return login_module_name; - } - - public void setMech(String mech) { - this.mech = mech; - } - - public String getMech() { - return mech; - } - - public void setSaslProps(Map sasl_props) { - this.sasl_props = sasl_props; - } - - public Map getSaslProps() { - return sasl_props; - } - - public void setClientSubject(Subject client_subject) { - this.client_subject = client_subject; - } - - public Subject getClientSubject() { - return client_subject; - } - - public void setServerSubject(Subject server_subject) { - this.server_subject = server_subject; - } - - public Subject getServerSubject() { - return server_subject; - } - - public void setServerName(String server_name) { - this.server_name = server_name; - } - - public String getServerName(String server_name) { - return server_name; - } - - public void setTimeout(long timeout) { - this.timeout = timeout; - } - - public long getTimeout() { - return timeout; - } - - public Address getAddress() { - return local_addr; - } - - @Override - public void init() throws Exception { - super.init(); - saslServerFactory = SaslUtils.getSaslServerFactory(mech, sasl_props); - saslClientFactory = SaslUtils.getSaslClientFactory(mech, sasl_props); - if (client_callback_handler == null) { - client_callback_handler = new SaslClientCallbackHandler(client_name, client_password.toCharArray()); - } - if (server_subject == null && login_module_name != null) { - LoginContext lc = new LoginContext(login_module_name); - lc.login(); - server_subject = lc.getSubject(); - } - if (client_subject == null && login_module_name != null) { - LoginContext lc = new LoginContext(login_module_name, new SaslClientCallbackHandler(client_name, client_password.toCharArray())); - lc.login(); - client_subject = lc.getSubject(); - } - } - - @Override - public void stop() { - super.stop(); - cleanup(); - } - - @Override - public void destroy() { - super.destroy(); - cleanup(); - } - - private void cleanup() { - for(SaslContext context : sasl_context.values()) { - context.dispose(); - } - sasl_context.clear(); - } - - @Override - public Object up(Event evt) { - if (evt.getType() == Event.MSG) { - Message msg = (Message) evt.getArg(); - SaslHeader saslHeader = (SaslHeader) msg.getHeader(SASL_ID); - GmsHeader gmsHeader = (GmsHeader) msg.getHeader(GMS_ID); - if (needsAuthentication(gmsHeader)) { - if (saslHeader == null) - throw new IllegalStateException("Found GMS join or merge request but no SASL header"); - if (!serverChallenge(gmsHeader, saslHeader, msg)) - return null; // failed auth, don't pass up - } else if (saslHeader != null) { - Address remoteAddress = msg.getSrc(); - SaslContext saslContext = sasl_context.get(remoteAddress); - if (saslContext == null) { - throw new IllegalStateException(String.format( - "Cannot find server context to challenge SASL request from %s", remoteAddress.toString())); - } - switch (saslHeader.getType()) { - case CHALLENGE: - try { - if (log.isTraceEnabled()) - log.trace("%s: received CHALLENGE from %s", getAddress(), remoteAddress); - Message response = saslContext.nextMessage(remoteAddress, saslHeader); - if (log.isTraceEnabled()) - log.trace("%s: sending RESPONSE to %s", getAddress(), remoteAddress); - down_prot.down(new Event(Event.MSG, response)); - } catch (SaslException e) { - disposeContext(remoteAddress); - if (log.isWarnEnabled()) { - log.warn("failed to validate CHALLENGE from " + remoteAddress + ", token", e); - } - sendRejectionMessage(gmsHeader.getType(), remoteAddress, "authentication failed"); - } - break; - case RESPONSE: - try { - if (log.isTraceEnabled()) - log.trace("%s: received RESPONSE from %s", getAddress(), remoteAddress); - Message challenge = saslContext.nextMessage(remoteAddress, saslHeader); - if (challenge != null) { - if (log.isTraceEnabled()) - log.trace("%s: sending CHALLENGE to %s", getAddress(), remoteAddress); - - down_prot.down(new Event(Event.MSG, challenge)); - } else { - if (log.isTraceEnabled()) - log.trace("%s: authentication complete from %s", getAddress(), remoteAddress); - } - } catch (SaslException e) { - disposeContext(remoteAddress); - if (log.isWarnEnabled()) { - log.warn("failed to validate RESPONSE from " + remoteAddress + ", token", e); - } - } - break; - } - return null; - } - } - - return up_prot.up(evt); - } - - private void disposeContext(Address address) { - SaslContext context = sasl_context.remove(address); - if (context != null) { - context.dispose(); - } - } - - @Override - public void up(MessageBatch batch) { - for (Message msg : batch) { - // If we have a join or merge request --> authenticate, else pass up - GmsHeader gmsHeader = (GmsHeader) msg.getHeader(GMS_ID); - if (needsAuthentication(gmsHeader)) { - SaslHeader saslHeader = (SaslHeader) msg.getHeader(id); - if (saslHeader == null) { - log.warn("Found GMS join or merge request but no SASL header"); - sendRejectionMessage(gmsHeader.getType(), batch.sender(), "join or merge without an SASL header"); - batch.remove(msg); - } else if (!serverChallenge(gmsHeader, saslHeader, msg)) // authentication failed - batch.remove(msg); // don't pass up - } - } - - if (!batch.isEmpty()) - up_prot.up(batch); - } - - @Override - public Object down(Event evt) { - switch (evt.getType()) { - case Event.SET_LOCAL_ADDRESS: - local_addr = (Address) evt.getArg(); - break; - case Event.MSG: - Message msg = (Message) evt.getArg(); - GmsHeader hdr = (GmsHeader) msg.getHeader(GMS_ID); - if (needsAuthentication(hdr)) { - // We are a client who needs to authenticate - SaslClientContext ctx = null; - Address remoteAddress = msg.getDest(); - try { - ctx = new SaslClientContext(saslClientFactory, mech, server_name != null ? server_name : remoteAddress.toString(), client_callback_handler, sasl_props, client_subject); - sasl_context.put(remoteAddress, ctx); - ctx.addHeader(msg, null); - } catch (Exception e) { - if (ctx != null) { - disposeContext(remoteAddress); - } - throw new SecurityException(e); - } - } - break; - } - - return down_prot.down(evt); - } - - protected static boolean needsAuthentication(GmsHeader hdr) { - return (hdr != null) - && (hdr.getType() == GmsHeader.JOIN_REQ || hdr.getType() == GmsHeader.JOIN_REQ_WITH_STATE_TRANSFER || hdr - .getType() == GmsHeader.MERGE_REQ); - } - - protected boolean serverChallenge(GmsHeader gmsHeader, SaslHeader saslHeader, Message msg) { - switch (gmsHeader.getType()) { - case GmsHeader.JOIN_REQ: - case GmsHeader.JOIN_REQ_WITH_STATE_TRANSFER: - case GmsHeader.MERGE_REQ: - Address remoteAddress = msg.getSrc(); - SaslServerContext ctx = null; - try { - ctx = new SaslServerContext(saslServerFactory, mech, server_name != null ? server_name : local_addr.toString(), server_callback_handler, sasl_props, server_subject); - sasl_context.put(remoteAddress, ctx); - this.getDownProtocol().down(new Event(Event.MSG, ctx.nextMessage(remoteAddress, saslHeader))); - ctx.awaitCompletion(timeout); - if (ctx.isSuccessful()) { - if (log.isDebugEnabled()) { - log.debug("Authentication successful for %s", ctx.getAuthorizationID()); - } - return true; - } else { - log.warn("failed to validate SaslHeader from %s, header: %s", msg.getSrc(), saslHeader); - sendRejectionMessage(gmsHeader.getType(), msg.getSrc(), "authentication failed"); - return false; - } - } catch (SaslException e) { - log.warn("failed to validate SaslHeader from %s, header: %s", msg.getSrc(), saslHeader); - sendRejectionMessage(gmsHeader.getType(), msg.getSrc(), "authentication failed"); - } catch (InterruptedException e) { - return false; - } finally { - if (ctx != null && !ctx.needsWrapping()) { - disposeContext(remoteAddress); - } - } - default: - return true; // pass up - } - } - - protected void sendRejectionMessage(byte type, Address dest, String error_msg) { - switch (type) { - case GmsHeader.JOIN_REQ: - case GmsHeader.JOIN_REQ_WITH_STATE_TRANSFER: - sendJoinRejectionMessage(dest, error_msg); - break; - case GmsHeader.MERGE_REQ: - sendMergeRejectionMessage(dest); - break; - default: - log.error("type " + type + " unknown"); - break; - } - } - - protected void sendJoinRejectionMessage(Address dest, String error_msg) { - if (dest == null) - return; - - JoinRsp joinRes = new JoinRsp(error_msg); // specify the error message on the JoinRsp - Message msg = new Message(dest).putHeader(GMS_ID, new GmsHeader(GmsHeader.JOIN_RSP)).setBuffer( - GMS.marshal(joinRes)); - down_prot.down(new Event(Event.MSG, msg)); - } - - protected void sendMergeRejectionMessage(Address dest) { - Message msg = new Message(dest).setFlag(Message.Flag.OOB); - GmsHeader hdr = new GmsHeader(GmsHeader.MERGE_RSP); - hdr.setMergeRejected(true); - msg.putHeader(GMS_ID, hdr); - if (log.isDebugEnabled()) - log.debug("merge response=" + hdr); - down_prot.down(new Event(Event.MSG, msg)); - } -} diff --git a/All/Genesis-NP/Genesis#232/pair.info b/All/Genesis-NP/Genesis#232/pair.info deleted file mode 100755 index 7e92e14..0000000 --- a/All/Genesis-NP/Genesis#232/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:232 -SATName:Genesis -modifiedFPath:src/org/jgroups/protocols/SASL.java -comSha:70ca68c222f97ff8f07be41d8546d9ed2094d406 -parentComSha:70ca68c222f97ff8f07be41d8546d9ed2094d406^1 -githubUrl:https://github.com/belaban/JGroups -repoName:belaban#JGroups \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#235/comMsg.txt b/All/Genesis-NP/Genesis#235/comMsg.txt deleted file mode 100755 index ea68208..0000000 --- a/All/Genesis-NP/Genesis#235/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE diff --git a/All/Genesis-NP/Genesis#235/diff.diff b/All/Genesis-NP/Genesis#235/diff.diff deleted file mode 100755 index 30fae5a..0000000 --- a/All/Genesis-NP/Genesis#235/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/org/jgroups/protocols/pbcast/NAKACK2.java b/src/org/jgroups/protocols/pbcast/NAKACK2.java -index 6442f5e..e71a544 100644 ---- a/src/org/jgroups/protocols/pbcast/NAKACK2.java -+++ b/src/org/jgroups/protocols/pbcast/NAKACK2.java -@@ -14,4 +14 @@ import java.util.*; --import java.util.concurrent.ConcurrentMap; --import java.util.concurrent.Executor; --import java.util.concurrent.Future; --import java.util.concurrent.TimeUnit; -+import java.util.concurrent.*; -@@ -176 +173 @@ public class NAKACK2 extends Protocol implements DiagnosticsHandler.ProbeHandler -- protected final Map xmit_task_map=new HashMap(); -+ protected final Map xmit_task_map=new ConcurrentHashMap(); diff --git a/All/Genesis-NP/Genesis#235/new/NAKACK2.java b/All/Genesis-NP/Genesis#235/new/NAKACK2.java deleted file mode 100755 index e71a544..0000000 --- a/All/Genesis-NP/Genesis#235/new/NAKACK2.java +++ /dev/null @@ -1,1483 +0,0 @@ -package org.jgroups.protocols.pbcast; - -import org.jgroups.Address; -import org.jgroups.Event; -import org.jgroups.Message; -import org.jgroups.View; -import org.jgroups.annotations.*; -import org.jgroups.protocols.TP; -import org.jgroups.stack.DiagnosticsHandler; -import org.jgroups.stack.Protocol; -import org.jgroups.util.*; - -import java.util.*; -import java.util.concurrent.*; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - - -/** - * Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically - * increasing sequence number (seqno). Receivers deliver messages ordered - * according to seqno and request retransmission of missing messages.
- * Retransmit requests are usually sent to the original sender of a message, but - * this can be changed by xmit_from_random_member (send to random member) or - * use_mcast_xmit_req (send to everyone). Responses can also be sent to everyone - * instead of the requester by setting use_mcast_xmit to true. - * - * @author Bela Ban - */ -@MBean(description="Reliable transmission multipoint FIFO protocol") -public class NAKACK2 extends Protocol implements DiagnosticsHandler.ProbeHandler { - protected static final int NUM_REBROADCAST_MSGS=3; - - /* ----------------------------------------------------- Properties --------------------- ------------------------------------ */ - - - - @Property(description="Max number of messages to be removed from a RingBuffer. This property might " + - "get removed anytime, so don't use it !") - protected int max_msg_batch_size=100; - - /** - * Retransmit messages using multicast rather than unicast. This has the advantage that, if many receivers - * lost a message, the sender only retransmits once - */ - @Property(description="Retransmit retransmit responses (messages) using multicast rather than unicast") - protected boolean use_mcast_xmit=true; - - /** - * Use a multicast to request retransmission of missing messages. This may - * be costly as every member in the cluster will send a response - */ - @Property(description="Use a multicast to request retransmission of missing messages") - protected boolean use_mcast_xmit_req=false; - - - /** - * Ask a random member for retransmission of a missing message. If set to - * true, discard_delivered_msgs will be set to false - */ - @Property(description="Ask a random member for retransmission of a missing message. Default is false") - protected boolean xmit_from_random_member=false; - - - /** - * Messages that have been received in order are sent up the stack (= delivered to the application). - * Delivered messages are removed from the retransmission buffer, so they can get GC'ed by the JVM. When this - * property is true, everyone (except the sender of a message) removes the message from their retransission - * buffers as soon as it has been delivered to the application - */ - @Property(description="Should messages delivered to application be discarded") - protected boolean discard_delivered_msgs=true; - - @Property(description="Timeout to rebroadcast messages. Default is 2000 msec") - protected long max_rebroadcast_timeout=2000; - - /** - * When not finding a message on an XMIT request, include the last N - * stability messages in the error message - */ - @Property(description="Should stability history be printed if we fail in retransmission. Default is false") - protected boolean print_stability_history_on_failed_xmit=false; - - - /** If true, logs messages discarded because received from other members */ - @Property(description="discards warnings about promiscuous traffic") - protected boolean log_discard_msgs=true; - - @Property(description="If true, trashes warnings about retransmission messages not found in the xmit_table (used for testing)") - protected boolean log_not_found_msgs=true; - - @Property(description="Interval (in milliseconds) at which missing messages (from all retransmit buffers) " + - "are retransmitted") - protected long xmit_interval=1000; - - @Property(description="Number of rows of the matrix in the retransmission table (only for experts)",writable=false) - protected int xmit_table_num_rows=50; - - @Property(description="Number of elements of a row of the matrix in the retransmission table (only for experts). " + - "The capacity of the matrix is xmit_table_num_rows * xmit_table_msgs_per_row",writable=false) - protected int xmit_table_msgs_per_row=10000; - - @Property(description="Resize factor of the matrix in the retransmission table (only for experts)",writable=false) - protected double xmit_table_resize_factor=1.2; - - @Property(description="Number of milliseconds after which the matrix in the retransmission table " + - "is compacted (only for experts)",writable=false) - protected long xmit_table_max_compaction_time=10000; - - @Property(description="Size of the queue to hold messages received after creating the channel, but before being " + - "connected (is_server=false). After becoming the server, the messages in the queue are fed into up() and the " + - "queue is cleared. The motivation is to avoid retransmissions (see https://issues.jboss.org/browse/JGRP-1509 " + - "for details). 0 disables the queue.") - protected int become_server_queue_size=50; - - @Property(description="Time during which identical warnings about messages from a non member will be suppressed. " + - "0 disables this (every warning will be logged). Setting the log level to ERROR also disables this.") - protected long suppress_time_non_member_warnings=60000; - - /* -------------------------------------------------- JMX ---------------------------------------------------------- */ - - - - @ManagedAttribute(description="Number of retransmit requests received") - protected final AtomicLong xmit_reqs_received=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit requests sent") - protected final AtomicLong xmit_reqs_sent=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit responses received") - protected final AtomicLong xmit_rsps_received=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit responses sent") - protected final AtomicLong xmit_rsps_sent=new AtomicLong(0); - - @ManagedAttribute(description="Is the retransmit task running") - public boolean isXmitTaskRunning() {return xmit_task != null && !xmit_task.isDone();} - - @ManagedAttribute(description="Number of messages sent") - protected int num_messages_sent=0; - - @ManagedAttribute(description="Number of messages received") - protected int num_messages_received=0; - - @ManagedAttribute(description="Number of messages from non-members") - public int getNonMemberMessages() { - return suppress_log_non_member != null? suppress_log_non_member.getCache().size() : 0; - } - - @ManagedOperation(description="Clears the cache for messages from non-members") - public void clearNonMemberCache() { - if(suppress_log_non_member != null) - suppress_log_non_member.getCache().clear(); - } - - - /* ------------------------------------------------- Fields ------------------------------------------------------------------------- */ - protected volatile boolean is_server=false; - protected Address local_addr=null; - protected volatile List
members=new ArrayList
(); - protected volatile View view; - private final AtomicLong seqno=new AtomicLong(0); // current message sequence number (starts with 1) - - /** Map to store sent and received messages (keyed by sender) */ - protected final ConcurrentMap> xmit_table=Util.createConcurrentMap(); - - /** RetransmitTask running every xmit_interval ms */ - protected Future xmit_task; - /** Used by the retransmit task to keep the last retransmitted seqno per sender (https://issues.jboss.org/browse/JGRP-1539) */ - protected final Map xmit_task_map=new ConcurrentHashMap(); - - protected volatile boolean leaving=false; - protected volatile boolean running=false; - protected TimeScheduler timer=null; - - protected final Lock rebroadcast_lock=new ReentrantLock(); - protected final Condition rebroadcast_done=rebroadcast_lock.newCondition(); - - // set during processing of a rebroadcast event - protected volatile boolean rebroadcasting=false; - protected final Lock rebroadcast_digest_lock=new ReentrantLock(); - @GuardedBy("rebroadcast_digest_lock") - protected Digest rebroadcast_digest=null; - - /** Keeps the last N stability messages */ - protected final BoundedList stability_msgs=new BoundedList(10); - - /** Keeps a bounded list of the last N digest sets */ - protected final BoundedList digest_history=new BoundedList(10); - - protected BoundedList become_server_queue; - - /** Log to suppress identical warnings for messages from non-members */ - protected SuppressLog
suppress_log_non_member; - - - public long getXmitRequestsReceived() {return xmit_reqs_received.get();} - public long getXmitRequestsSent() {return xmit_reqs_sent.get();} - public long getXmitResponsesReceived() {return xmit_rsps_received.get();} - public long getXmitResponsesSent() {return xmit_rsps_sent.get();} - public boolean isUseMcastXmit() {return use_mcast_xmit;} - public boolean isXmitFromRandomMember() {return xmit_from_random_member;} - public boolean isDiscardDeliveredMsgs() {return discard_delivered_msgs;} - public boolean getLogDiscardMessages() {return log_discard_msgs;} - public void setUseMcastXmit(boolean use_mcast_xmit) {this.use_mcast_xmit=use_mcast_xmit;} - public void setUseMcastXmitReq(boolean flag) {this.use_mcast_xmit_req=flag;} - public void setLogDiscardMessages(boolean flag) {log_discard_msgs=flag;} - public void setLogNotFoundMessages(boolean flag) {log_not_found_msgs=flag;} - public void setXmitFromRandomMember(boolean xmit_from_random_member) { - this.xmit_from_random_member=xmit_from_random_member; - } - public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) { - this.discard_delivered_msgs=discard_delivered_msgs; - } - - @ManagedAttribute(description="Actual size of the become_server_queue") - public int getBecomeServerQueueSizeActual() { - return become_server_queue != null? become_server_queue.size() : -1; - } - - /** Returns the receive window for sender; only used for testing. Do not use ! */ - public Table getWindow(Address sender) { - return xmit_table.get(sender); - } - - - /** Only used for unit tests, don't use ! */ - public void setTimer(TimeScheduler timer) {this.timer=timer;} - - - @ManagedAttribute(description="Total number of undelivered messages in all retransmit buffers") - public int getXmitTableUndeliveredMsgs() { - int num=0; - for(Table buf: xmit_table.values()) - num+=buf.size(); - return num; - } - - @ManagedAttribute(description="Total number of missing (= not received) messages in all retransmit buffers") - public int getXmitTableMissingMessages() { - int num=0; - for(Table buf: xmit_table.values()) - num+=buf.getNumMissing(); - return num; - } - - @ManagedAttribute(description="Capacity of the retransmit buffer. Computed as xmit_table_num_rows * xmit_table_msgs_per_row") - public long getXmitTableCapacity() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.capacity() : 0; - } - - @ManagedAttribute(description="Prints the number of rows currently allocated in the matrix. This value will not " + - "be lower than xmit_table_now_rows") - public int getXmitTableNumCurrentRows() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumRows() : 0; - } - - @ManagedAttribute(description="Returns the number of bytes of all messages in all retransmit buffers. " + - "To compute the size, Message.getLength() is used") - public long getSizeOfAllMessages() { - long retval=0; - for(Table buf: xmit_table.values()) - retval+=sizeOfAllMessages(buf,false); - return retval; - } - - @ManagedAttribute(description="Returns the number of bytes of all messages in all retransmit buffers. " + - "To compute the size, Message.size() is used") - public long getSizeOfAllMessagesInclHeaders() { - long retval=0; - for(Table buf: xmit_table.values()) - retval+=sizeOfAllMessages(buf, true); - return retval; - } - - @ManagedAttribute(description="Number of retransmit table compactions") - public int getXmitTableNumCompactions() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumCompactions() : 0; - } - - @ManagedAttribute(description="Number of retransmit table moves") - public int getXmitTableNumMoves() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumMoves() : 0; - } - - @ManagedAttribute(description="Number of retransmit table resizes") - public int getXmitTableNumResizes() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumResizes(): 0; - } - - @ManagedAttribute(description="Number of retransmit table purges") - public int getXmitTableNumPurges() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumPurges(): 0; - } - - @ManagedOperation(description="Prints the contents of the receiver windows for all members") - public String printMessages() { - StringBuilder ret=new StringBuilder(local_addr + ":\n"); - for(Map.Entry> entry: xmit_table.entrySet()) { - Address addr=entry.getKey(); - Table buf=entry.getValue(); - ret.append(addr).append(": ").append(buf.toString()).append('\n'); - } - return ret.toString(); - } - - @ManagedAttribute public long getCurrentSeqno() {return seqno.get();} - - @ManagedOperation(description="Prints the stability messages received") - public String printStabilityMessages() { - StringBuilder sb=new StringBuilder(); - sb.append(Util.printListWithDelimiter(stability_msgs, "\n")); - return sb.toString(); - } - - @ManagedOperation(description="Keeps information about the last N times a digest was set or merged") - public String printDigestHistory() { - StringBuilder sb=new StringBuilder(local_addr + ":\n"); - for(String tmp: digest_history) - sb.append(tmp).append("\n"); - return sb.toString(); - } - - @ManagedOperation(description="Compacts the retransmit buffer") - public void compact() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - if(table != null) - table.compact(); - } - - @ManagedOperation(description="Prints the number of rows currently allocated in the matrix for all members. " + - "This value will not be lower than xmit_table_now_rows") - public String dumpXmitTablesNumCurrentRows() { - StringBuilder sb=new StringBuilder(); - for(Map.Entry> entry: xmit_table.entrySet()) { - sb.append(entry.getKey()).append(": ").append(entry.getValue().getNumRows()).append("\n"); - } - return sb.toString(); - } - - @ManagedOperation(description="Resets all statistics") - public void resetStats() { - num_messages_sent=num_messages_received=0; - xmit_reqs_received.set(0); - xmit_reqs_sent.set(0); - xmit_rsps_received.set(0); - xmit_rsps_sent.set(0); - stability_msgs.clear(); - digest_history.clear(); - Table table=local_addr != null? xmit_table.get(local_addr) : null; - if(table != null) - table.resetStats(); - } - - public void init() throws Exception { - if(xmit_from_random_member) { - if(discard_delivered_msgs) { - discard_delivered_msgs=false; - log.debug("%s: xmit_from_random_member set to true: changed discard_delivered_msgs to false", local_addr); - } - } - - TP transport=getTransport(); - if(transport != null) { - transport.registerProbeHandler(this); - if(!transport.supportsMulticasting()) { - if(use_mcast_xmit) { - log.warn("use_mcast_xmit should not be used because the transport (" + transport.getName() + - ") does not support IP multicasting; setting use_mcast_xmit to false"); - use_mcast_xmit=false; - } - if(use_mcast_xmit_req) { - log.warn("use_mcast_xmit_req should not be used because the transport (" + transport.getName() + - ") does not support IP multicasting; setting use_mcast_xmit_req to false"); - use_mcast_xmit_req=false; - } - } - } - - if(become_server_queue_size > 0) - become_server_queue=new BoundedList(become_server_queue_size); - - if(suppress_time_non_member_warnings > 0) - suppress_log_non_member=new SuppressLog
(log, "MsgDroppedNak", "SuppressMsg"); - } - - - public Map dumpStats() { - Map retval=super.dumpStats(); - retval.put("msgs", printMessages()); - return retval; - } - - public String printStats() { - StringBuilder sb=new StringBuilder(); - sb.append("\nStability messages received\n"); - sb.append(printStabilityMessages()).append("\n"); - - return sb.toString(); - } - - - - public String printStabilityHistory() { - StringBuilder sb=new StringBuilder(); - int i=1; - for(String digest: stability_msgs) - sb.append(i++).append(": ").append(digest).append("\n"); - return sb.toString(); - } - - - - public List providedUpServices() { - return Arrays.asList(Event.GET_DIGEST,Event.SET_DIGEST,Event.OVERWRITE_DIGEST,Event.MERGE_DIGEST); - } - - - public void start() throws Exception { - timer=getTransport().getTimer(); - if(timer == null) - throw new Exception("timer is null"); - running=true; - leaving=false; - startRetransmitTask(); - } - - - public void stop() { - running=false; - is_server=false; - if(become_server_queue != null) - become_server_queue.clear(); - stopRetransmitTask(); - xmit_task_map.clear(); - reset(); - } - - - /** - * Callback. Called by superclass when event may be handled.

Do not use down_prot.down() in this - * method as the event is passed down by default by the superclass after this method returns ! - */ - public Object down(Event evt) { - switch(evt.getType()) { - - case Event.MSG: - Message msg=(Message)evt.getArg(); - Address dest=msg.getDest(); - if(dest != null || msg.isFlagSet(Message.Flag.NO_RELIABILITY)) - break; // unicast address: not null and not mcast, pass down unchanged - - send(evt, msg); - return null; // don't pass down the stack - - case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg - stable((Digest)evt.getArg()); - return null; // do not pass down further (Bela Aug 7 2001) - - case Event.GET_DIGEST: - return getDigest((Address)evt.getArg()); - - case Event.SET_DIGEST: - setDigest((Digest)evt.getArg()); - return null; - - case Event.OVERWRITE_DIGEST: - overwriteDigest((Digest)evt.getArg()); - return null; - - case Event.MERGE_DIGEST: - mergeDigest((Digest)evt.getArg()); - return null; - - case Event.TMP_VIEW: - View tmp_view=(View)evt.getArg(); - members=tmp_view.getMembers(); - break; - - case Event.VIEW_CHANGE: - tmp_view=(View)evt.getArg(); - List

mbrs=tmp_view.getMembers(); - members=mbrs; - view=tmp_view; - adjustReceivers(mbrs); - is_server=true; // check vids from now on - if(suppress_log_non_member != null) - suppress_log_non_member.removeExpired(suppress_time_non_member_warnings); - xmit_task_map.keySet().retainAll(mbrs); - break; - - case Event.BECOME_SERVER: - is_server=true; - flushBecomeServerQueue(); - break; - - case Event.SET_LOCAL_ADDRESS: - local_addr=(Address)evt.getArg(); - break; - - case Event.DISCONNECT: - leaving=true; - reset(); - break; - - case Event.REBROADCAST: - rebroadcasting=true; - rebroadcast_digest=(Digest)evt.getArg(); - try { - rebroadcastMessages(); - } - finally { - rebroadcasting=false; - rebroadcast_digest_lock.lock(); - try { - rebroadcast_digest=null; - } - finally { - rebroadcast_digest_lock.unlock(); - } - } - return null; - } - - return down_prot.down(evt); - } - - - - - /** - * Callback. Called by superclass when event may be handled.

Do not use PassUp in this - * method as the event is passed up by default by the superclass after this method returns ! - */ - public Object up(Event evt) { - switch(evt.getType()) { - - case Event.MSG: - Message msg=(Message)evt.getArg(); - if(msg.isFlagSet(Message.Flag.NO_RELIABILITY)) - break; - NakAckHeader2 hdr=(NakAckHeader2)msg.getHeader(this.id); - if(hdr == null) - break; // pass up (e.g. unicast msg) - - if(!is_server) { // discard messages while not yet server (i.e., until JOIN has returned) - if(become_server_queue != null) { - become_server_queue.add(msg); - log.trace("%s: message %s::%d was added to queue (not yet server)", local_addr, msg.getSrc(), hdr.seqno); - } - else - log.trace("%s: message %s::%d was discarded (not yet server)", local_addr, msg.getSrc(), hdr.seqno); - return null; - } - - // Changed by bela Jan 29 2003: we must not remove the header, otherwise further xmit requests will fail ! - //hdr=(NakAckHeader2)msg.removeHeader(getName()); - - switch(hdr.type) { - - case NakAckHeader2.MSG: - handleMessage(msg, hdr); - return null; // transmitter passes message up for us ! - - case NakAckHeader2.XMIT_REQ: - SeqnoList missing=(SeqnoList)msg.getObject(); - if(missing == null) - return null; - handleXmitReq(msg.getSrc(), missing, hdr.sender); - return null; - - case NakAckHeader2.XMIT_RSP: - handleXmitRsp(msg, hdr); - return null; - - default: - log.error("%s: header type %s not known", local_addr, hdr.type); - return null; - } - - case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg - stable((Digest)evt.getArg()); - return null; // do not pass up further (Bela Aug 7 2001) - - case Event.SUSPECT: - // release the promise if rebroadcasting is in progress... otherwise we wait forever. there will be a new - // flush round anyway - if(rebroadcasting) - cancelRebroadcasting(); - break; - } - return up_prot.up(evt); - } - - - public void up(MessageBatch batch) { - int size=batch.size(); - boolean got_retransmitted_msg=false; // if at least 1 XMIT-RSP was received - List> msgs=null; // regular or retransmitted messages - - for(Iterator it=batch.iterator(); it.hasNext();) { - final Message msg=it.next(); - if(msg == null || msg.isFlagSet(Message.Flag.NO_RELIABILITY)) - continue; - NakAckHeader2 hdr=(NakAckHeader2)msg.getHeader(id); - if(hdr == null) - continue; - it.remove(); // remove the message from the batch, so it won't be passed up the stack - - if(!is_server) { // discard messages while not yet server (i.e., until JOIN has returned) - if(become_server_queue != null) { - become_server_queue.add(msg); - log.trace("%s: message %s::%d was added to queue (not yet server)", local_addr, msg.getSrc(), hdr.seqno); - } - else - log.trace("%s: message %s::%d was discarded (not yet server)", local_addr, msg.getSrc(), hdr.seqno); - continue; - } - - switch(hdr.type) { - case NakAckHeader2.MSG: - if(msgs == null) - msgs=new ArrayList>(size); - msgs.add(new Tuple(hdr.seqno, msg)); - break; - case NakAckHeader2.XMIT_REQ: - SeqnoList missing=(SeqnoList)msg.getObject(); - if(missing != null) - handleXmitReq(msg.getSrc(), missing, hdr.sender); - break; - case NakAckHeader2.XMIT_RSP: - Message xmitted_msg=msgFromXmitRsp(msg, hdr); - if(xmitted_msg != null) { - if(msgs == null) - msgs=new ArrayList>(size); - msgs.add(new Tuple(hdr.seqno, xmitted_msg)); - got_retransmitted_msg=true; - } - break; - default: - log.error("%s: header type %s not known", local_addr, hdr.type); - } - } - - // Process (new and retransmitted) messages: - if(msgs != null) - handleMessages(batch.sender(), msgs, batch.mode() == MessageBatch.Mode.OOB, batch.clusterName()); - - // received XMIT-RSPs: - if(got_retransmitted_msg && rebroadcasting) - checkForRebroadcasts(); - - if(!batch.isEmpty()) - up_prot.up(batch); - } - - // ProbeHandler interface - public Map handleProbe(String... keys) { - Map retval=new HashMap(); - for(String key: keys) { - if(key.equals("digest-history")) - retval.put(key, printDigestHistory()); - if(key.equals("dump-digest")) - retval.put(key, "\n" + printMessages()); - } - - return retval; - } - - // ProbeHandler interface - public String[] supportedKeys() { - return new String[]{"digest-history", "dump-digest"}; - } - - - - - /* --------------------------------- Private Methods --------------------------------------- */ - - /** - * Adds the message to the sent_msgs table and then passes it down the stack. Change Bela Ban May 26 2002: we don't - * store a copy of the message, but a reference ! This saves us a lot of memory. However, this also means that a - * message should not be changed after storing it in the sent-table ! See protocols/DESIGN for details. - * Made seqno increment and adding to sent_msgs atomic, e.g. seqno won't get incremented if adding to - * sent_msgs fails e.g. due to an OOM (see http://jira.jboss.com/jira/browse/JGRP-179). bela Jan 13 2006 - */ - protected void send(Event evt, Message msg) { - if(msg == null) - throw new NullPointerException("msg is null; event is " + evt); - - if(!running) { - log.trace("%s: discarded message as we're not in the 'running' state, message: %s", local_addr, msg); - return; - } - - long msg_id; - Table buf=xmit_table.get(local_addr); - if(buf == null) // discard message if there is no entry for local_addr - return; - - if(msg.getSrc() == null) - msg.setSrc(local_addr); // this needs to be done so we can check whether the message sender is the local_addr - - msg_id=seqno.incrementAndGet(); - long sleep=10; - while(running) { - try { - msg.putHeader(this.id, NakAckHeader2.createMessageHeader(msg_id)); - buf.add(msg_id, msg); - break; - } - catch(Throwable t) { - if(!running) - break; - Util.sleep(sleep); - sleep=Math.min(5000, sleep*2); - } - } - - // moved down_prot.down() out of synchronized clause (bela Sept 7 2006) http://jira.jboss.com/jira/browse/JGRP-300 - if(log.isTraceEnabled()) - log.trace("%s: sending %s#%d", local_addr, local_addr, msg_id); - down_prot.down(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted - num_messages_sent++; - } - - - - /** - * Finds the corresponding retransmit buffer and adds the message to it (according to seqno). Then removes as many - * messages as possible and passes them up the stack. Discards messages from non-members. - */ - protected void handleMessage(Message msg, NakAckHeader2 hdr) { - Address sender=msg.getSrc(); - Table buf=xmit_table.get(sender); - if(buf == null) { // discard message if there is no entry for sender - if(leaving) - return; - if(log.isWarnEnabled() && log_discard_msgs) { - if(suppress_log_non_member != null) - suppress_log_non_member.log(SuppressLog.Level.warn, sender, suppress_time_non_member_warnings, - local_addr, hdr.seqno, sender, view); - else - log.warn(Util.getMessage("MsgDroppedNak"), local_addr, hdr.seqno, sender, view); - } - return; - } - - num_messages_received++; - boolean loopback=local_addr.equals(sender); - boolean added=loopback || buf.add(hdr.seqno, msg); - - if(added && log.isTraceEnabled()) - log.trace("%s: received %s#%d", local_addr, sender, hdr.seqno); - - - // OOB msg is passed up. When removed, we discard it. Affects ordering: http://jira.jboss.com/jira/browse/JGRP-379 - if(added && msg.isFlagSet(Message.Flag.OOB)) { - if(loopback) - msg=buf.get(hdr.seqno); // we *have* to get a message, because loopback means we didn't add it to win ! - if(msg != null && msg.isFlagSet(Message.Flag.OOB)) { - if(msg.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED)) { - if(log.isTraceEnabled()) - log.trace("%s: delivering %s#%d", local_addr, sender, hdr.seqno); - try { - up_prot.up(new Event(Event.MSG, msg)); - } - catch(Throwable t) { - log.error("%s: failed to deliver OOB message %s: %t", local_addr, msg, t); - } - } - } - } - - removeAndPassUp(buf, sender, loopback, null); // at most 1 thread will execute this at any given time - } - - - protected void handleMessages(Address sender, List> msgs, boolean oob, String cluster_name) { - Table buf=xmit_table.get(sender); - if(buf == null) { // discard message if there is no entry for sender - if(leaving) - return; - if(log.isWarnEnabled() && log_discard_msgs) { - if(suppress_log_non_member != null) - suppress_log_non_member.log(SuppressLog.Level.warn, sender, suppress_time_non_member_warnings, - local_addr, "batch", sender, view); - else - log.warn(Util.getMessage("MsgDroppedNak"), local_addr, "batch", sender, view); - } - return; - } - int size=msgs.size(); - num_messages_received+=size; - boolean loopback=local_addr.equals(sender); - boolean added=loopback || (oob ? buf.add(msgs, true) : buf.add(msgs)); - - if(added && log.isTraceEnabled()) - log.trace("%s: received %s#%d - #%d (%d messages)", - local_addr, sender, msgs.get(0).getVal1(), msgs.get(size-1).getVal1(), msgs.size()); - - - // OOB msg is passed up. When removed, we discard it. Affects ordering: http://jira.jboss.com/jira/browse/JGRP-379 - if(added && oob) { - for(Tuple tuple: msgs) { - long seq=tuple.getVal1(); - Message msg=loopback? buf.get(seq) : tuple.getVal2(); // we *have* to get the message, because loopback means we didn't add it to win ! - if(msg != null && msg.isFlagSet(Message.Flag.OOB)) { - if(msg.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED)) { - if(log.isTraceEnabled()) - log.trace("%s: delivering %s#%d", local_addr, sender, seq); - try { - up_prot.up(new Event(Event.MSG, msg)); - } - catch(Throwable t) { - log.error("%s: failed to deliver OOB message %s: %s", local_addr, msg, t); - } - } - } - } - } - - removeAndPassUp(buf,sender,loopback,cluster_name); // at most 1 thread will execute this at any given time - } - - - /** Efficient way of checking whether another thread is already processing messages from sender. If that's the case, - * we return immediately and let the existing thread process our message (https://jira.jboss.org/jira/browse/JGRP-829). - * Benefit: fewer threads blocked on the same lock, these threads an be returned to the thread pool */ - protected void removeAndPassUp(Table buf, Address sender, boolean loopback, String cluster_name) { - final AtomicBoolean processing=buf.getProcessing(); - if(!processing.compareAndSet(false, true)) - return; - - boolean remove_msgs=discard_delivered_msgs && !loopback; - boolean released_processing=false; - try { - while(true) { - // we're removing a msg and set processing to false (if null) *atomically* (wrt to add()) - List msgs=buf.removeMany(processing, remove_msgs, max_msg_batch_size); - if(msgs == null || msgs.isEmpty()) { - released_processing=true; - if(rebroadcasting) - checkForRebroadcasts(); - return; - } - - MessageBatch batch=new MessageBatch(null, sender, cluster_name, true, msgs); - for(Message msg_to_deliver: batch) { - // discard OOB msg if it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-379) - if(msg_to_deliver.isFlagSet(Message.Flag.OOB) && !msg_to_deliver.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED)) - batch.remove(msg_to_deliver); - } - if(batch.isEmpty()) - continue; - - try { - if(log.isTraceEnabled()) { - Message first=batch.first(), last=batch.last(); - StringBuilder sb=new StringBuilder(local_addr + ": delivering"); - if(first != null && last != null) { - NakAckHeader2 hdr1=(NakAckHeader2)first.getHeader(id), hdr2=(NakAckHeader2)last.getHeader(id); - sb.append(" #").append(hdr1.seqno).append(" - #").append(hdr2.seqno); - } - sb.append(" (" + batch.size()).append(" messages)"); - log.trace(sb); - } - up_prot.up(batch); - } - catch(Throwable t) { - log.error("%s: failed to deliver batch %s: %t", local_addr, batch, t); - } - } - } - finally { - // processing is always set in win.remove(processing) above and never here ! This code is just a - // 2nd line of defense should there be an exception before win.remove(processing) sets processing - if(!released_processing) - processing.set(false); - } - } - - - - /** - * Retransmits messsages first_seqno to last_seqno from original_sender from xmit_table to xmit_requester, - * called when XMIT_REQ is received. - * @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address - * @param missing_msgs A list of seqnos that have to be retransmitted - * @param original_sender The member who originally sent the messsage. Guaranteed to be non-null - */ - protected void handleXmitReq(Address xmit_requester, SeqnoList missing_msgs, Address original_sender) { - log.trace("%s: received xmit request from %s for %s%s", local_addr, xmit_requester, original_sender, missing_msgs); - - if(stats) - xmit_reqs_received.addAndGet(missing_msgs.size()); - - Table buf=xmit_table.get(original_sender); - if(buf == null) { - if(log.isErrorEnabled()) { - StringBuilder sb=new StringBuilder(); - sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); - sb.append(") ").append(original_sender).append(" not found in retransmission table"); - // don't print the table unless we are in trace mode because it can be LARGE - if(log.isTraceEnabled()) - sb.append(":\n").append(printMessages()); - if(print_stability_history_on_failed_xmit) - sb.append(" (stability history:\n").append(printStabilityHistory()); - log.error(sb.toString()); - } - return; - } - - for(long i: missing_msgs) { - Message msg=buf.get(i); - if(msg == null) { - if(log.isWarnEnabled() && log_not_found_msgs && !local_addr.equals(xmit_requester) && i > buf.getLow()) { - StringBuilder sb=new StringBuilder(); - sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); - sb.append(") message ").append(original_sender).append("::").append(i); - sb.append(" not found in retransmission table of ").append(original_sender).append(":\n").append(buf); - if(print_stability_history_on_failed_xmit) - sb.append(" (stability history:\n").append(printStabilityHistory()); - log.warn(sb.toString()); - } - continue; - } - if(log.isTraceEnabled()) - log.trace(local_addr + ": resending " + original_sender + "::" + i); - sendXmitRsp(xmit_requester, msg); - } - } - - - /** - * Flushes the queue. Done in a separate thread as we don't want to block the - * {@link ClientGmsImpl#installView(org.jgroups.View,org.jgroups.util.Digest)} method (called when a view is installed). - */ - protected void flushBecomeServerQueue() { - if(become_server_queue != null && !become_server_queue.isEmpty()) { - log.trace("%s: flushing become_server_queue (%d elements)", local_addr, become_server_queue.size()); - - TP transport=getTransport(); - Executor thread_pool=transport.getDefaultThreadPool(), oob_thread_pool=transport.getOOBThreadPool(); - - for(final Message msg: become_server_queue) { - Executor pool=msg.isFlagSet(Message.Flag.OOB)? oob_thread_pool : thread_pool; - pool.execute(new Runnable() { - public void run() { - try { - up(new Event(Event.MSG, msg)); - } - finally { - become_server_queue.remove(msg); - } - } - }); - } - } - } - - - protected void cancelRebroadcasting() { - rebroadcast_lock.lock(); - try { - rebroadcasting=false; - rebroadcast_done.signalAll(); - } - finally { - rebroadcast_lock.unlock(); - } - } - - - - - /** - * Sends a message msg to the requester. We have to wrap the original message into a retransmit message, as we need - * to preserve the original message's properties, such as src, headers etc. - * @param dest - * @param msg - */ - protected void sendXmitRsp(Address dest, Message msg) { - if(msg == null) - return; - - if(stats) - xmit_rsps_sent.incrementAndGet(); - - if(msg.getSrc() == null) - msg.setSrc(local_addr); - - if(use_mcast_xmit) { // we simply send the original multicast message - down_prot.down(new Event(Event.MSG, msg)); - return; - } - - Message xmit_msg=msg.copy(true, true).dest(dest).setFlag(Message.Flag.INTERNAL); // copy payload and headers - NakAckHeader2 hdr=(NakAckHeader2)xmit_msg.getHeader(id); - NakAckHeader2 newhdr=hdr.copy(); - newhdr.type=NakAckHeader2.XMIT_RSP; // change the type in the copy from MSG --> XMIT_RSP - xmit_msg.putHeader(id, newhdr); - down_prot.down(new Event(Event.MSG,xmit_msg)); - } - - - protected void handleXmitRsp(Message msg, NakAckHeader2 hdr) { - if(msg == null) - return; - - try { - if(stats) - xmit_rsps_received.incrementAndGet(); - - msg.setDest(null); - NakAckHeader2 newhdr=hdr.copy(); - newhdr.type=NakAckHeader2.MSG; // change the type back from XMIT_RSP --> MSG - msg.putHeader(id, newhdr); - up(new Event(Event.MSG, msg)); - if(rebroadcasting) - checkForRebroadcasts(); - } - catch(Exception ex) { - log.error("%s: failed handling retransmitted message: ", local_addr, ex); - } - } - - protected Message msgFromXmitRsp(Message msg, NakAckHeader2 hdr) { - if(msg == null) - return null; - - if(stats) - xmit_rsps_received.incrementAndGet(); - - msg.setDest(null); - NakAckHeader2 newhdr=hdr.copy(); - newhdr.type=NakAckHeader2.MSG; // change the type back from XMIT_RSP --> MSG - msg.putHeader(id,newhdr); - return msg; - } - - - /** - * Takes the argument highest_seqnos and compares it to the current digest. If the current digest has fewer messages, - * then send retransmit messages for the missing messages. Return when all missing messages have been received. If - * we're waiting for a missing message from P, and P crashes while waiting, we need to exclude P from the wait set. - */ - protected void rebroadcastMessages() { - Digest their_digest; - long sleep=max_rebroadcast_timeout / NUM_REBROADCAST_MSGS; - long wait_time=max_rebroadcast_timeout, start=System.currentTimeMillis(); - - while(wait_time > 0) { - rebroadcast_digest_lock.lock(); - try { - if(rebroadcast_digest == null) - break; - their_digest=rebroadcast_digest.copy(); - } - finally { - rebroadcast_digest_lock.unlock(); - } - Digest my_digest=getDigest(); - boolean xmitted=false; - - for(Digest.Entry entry: their_digest) { - Address member=entry.getMember(); - long[] my_entry=my_digest.get(member); - if(my_entry == null) - continue; - long their_high=entry.getHighest(); - - // Cannot ask for 0 to be retransmitted because the first seqno in NAKACK2 and UNICAST(2) is always 1 ! - // Also, we need to ask for retransmission of my_high+1, because we already *have* my_high, and don't - // need it, so the retransmission range is [my_high+1 .. their_high]: *exclude* my_high, but *include* - // their_high - long my_high=Math.max(my_entry[0], my_entry[1]); - if(their_high > my_high) { - log.trace("%s: fetching %d-%d from %s", local_addr, my_high, their_high, member); - retransmit(my_high+1, their_high, member, true); // use multicast to send retransmit request - xmitted=true; - } - } - if(!xmitted) - return; // we're done; no retransmissions are needed anymore. our digest is >= rebroadcast_digest - - rebroadcast_lock.lock(); - try { - try { - my_digest=getDigest(); - rebroadcast_digest_lock.lock(); - try { - if(!rebroadcasting || isGreaterThanOrEqual(my_digest, rebroadcast_digest)) - return; - } - finally { - rebroadcast_digest_lock.unlock(); - } - rebroadcast_done.await(sleep, TimeUnit.MILLISECONDS); - wait_time-=(System.currentTimeMillis() - start); - } - catch(InterruptedException e) { - } - } - finally { - rebroadcast_lock.unlock(); - } - } - } - - protected void checkForRebroadcasts() { - Digest tmp=getDigest(); - boolean cancel_rebroadcasting; - rebroadcast_digest_lock.lock(); - try { - cancel_rebroadcasting=isGreaterThanOrEqual(tmp, rebroadcast_digest); - } - finally { - rebroadcast_digest_lock.unlock(); - } - if(cancel_rebroadcasting) { - cancelRebroadcasting(); - } - } - - /** - * Returns true if all senders of the current digest have their seqnos >= the ones from other - */ - protected static boolean isGreaterThanOrEqual(Digest first, Digest other) { - if(other == null) - return true; - - for(Digest.Entry entry: first) { - Address sender=entry.getMember(); - long[] their_entry=other.get(sender); - if(their_entry == null) - continue; - long my_highest=entry.getHighest(); - long their_highest=Math.max(their_entry[0],their_entry[1]); - if(my_highest < their_highest) - return false; - } - return true; - } - - - /** - * Removes old members from xmit-table and adds new members to xmit-table (at seqnos hd=0, hr=0). - * This method is not called concurrently - */ - protected void adjustReceivers(List

members) { - Set
keys=xmit_table.keySet(); - - // remove members which left - for(Address member: keys) { - if(!members.contains(member)) { - if(local_addr != null && local_addr.equals(member)) - continue; - Table buf=xmit_table.remove(member); - if(buf != null) - log.debug("%s: removed %s from xmit_table (not member anymore)", local_addr, member); - } - } - - for(Address member: members) - if(!keys.contains(member)) - xmit_table.putIfAbsent(member, createTable(0)); - } - - - /** - * Returns a message digest: for each member P the highest delivered and received seqno is added - */ - public Digest getDigest() { - final Map map=new HashMap(); - for(Map.Entry> entry: xmit_table.entrySet()) { - Address sender=entry.getKey(); // guaranteed to be non-null (CCHM) - Table buf=entry.getValue(); // guaranteed to be non-null (CCHM) - long[] seqnos=buf.getDigest(); - map.put(sender, seqnos); - } - return new Digest(map); - } - - - public Digest getDigest(Address mbr) { - if(mbr == null) - return getDigest(); - Table buf=xmit_table.get(mbr); - if(buf == null) - return null; - long[] seqnos=buf.getDigest(); - return new Digest(mbr, seqnos[0], seqnos[1]); - } - - - /** - * Creates a retransmit buffer for each sender in the digest according to the sender's seqno. - * If a buffer already exists, it resets it. - */ - protected void setDigest(Digest digest) { - setDigest(digest,false); - } - - - /** - * For all members of the digest, adjust the retransmit buffers in xmit_table. If no entry - * exists, create one with the initial seqno set to the seqno of the member in the digest. If the member already - * exists, and is not the local address, replace it with the new entry (http://jira.jboss.com/jira/browse/JGRP-699) - * if the digest's seqno is greater than the seqno in the window. - */ - protected void mergeDigest(Digest digest) { - setDigest(digest,true); - } - - /** - * Overwrites existing entries, but does NOT remove entries not found in the digest - * @param digest - */ - protected void overwriteDigest(Digest digest) { - if(digest == null) - return; - - StringBuilder sb=new StringBuilder("\n[overwriteDigest()]\n"); - sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest); - - for(Digest.Entry entry: digest) { - Address member=entry.getMember(); - if(member == null) - continue; - - long highest_delivered_seqno=entry.getHighestDeliveredSeqno(); - - Table buf=xmit_table.get(member); - if(buf != null) { - if(local_addr.equals(member)) { - // Adjust the highest_delivered seqno (to send msgs again): https://jira.jboss.org/browse/JGRP-1251 - buf.setHighestDelivered(highest_delivered_seqno); - continue; // don't destroy my own window - } - xmit_table.remove(member); - } - buf=createTable(highest_delivered_seqno); - xmit_table.put(member, buf); - } - sb.append("\n").append("resulting digest: " + getDigest().toString(digest)); - digest_history.add(sb.toString()); - if(log.isDebugEnabled()) - log.debug(sb.toString()); - } - - - /** - * Sets or merges the digest. If there is no entry for a given member in xmit_table, create a new buffer. - * Else skip the existing entry, unless it is a merge. In this case, skip the existing entry if its seqno is - * greater than or equal to the one in the digest, or reset the window and create a new one if not. - * @param digest The digest - * @param merge Whether to merge the new digest with our own, or not - */ - protected void setDigest(Digest digest, boolean merge) { - if(digest == null) - return; - - StringBuilder sb=log.isDebugEnabled()? - new StringBuilder(merge? "\n[" + local_addr + " mergeDigest()]\n" : "\n["+local_addr + " setDigest()]\n") - .append("existing digest: " + getDigest()).append("\nnew digest: " + digest) : null; - - boolean set_own_seqno=false; - for(Digest.Entry entry: digest) { - Address member=entry.getMember(); - if(member == null) - continue; - - long highest_delivered_seqno=entry.getHighestDeliveredSeqno(); - - Table buf=xmit_table.get(member); - if(buf != null) { - // We only reset the window if its seqno is lower than the seqno shipped with the digest. Also, we - // don't reset our own window (https://jira.jboss.org/jira/browse/JGRP-948, comment 20/Apr/09 03:39 AM) - if(!merge - || (local_addr != null && local_addr.equals(member)) // never overwrite our own entry - || buf.getHighestDelivered() >= highest_delivered_seqno) // my seqno is >= digest's seqno for sender - continue; - - xmit_table.remove(member); - // to get here, merge must be false ! - if(member.equals(local_addr)) { // Adjust the seqno: https://jira.jboss.org/browse/JGRP-1251 - seqno.set(highest_delivered_seqno); - set_own_seqno=true; - } - } - buf=createTable(highest_delivered_seqno); - xmit_table.put(member, buf); - } - if(sb != null) - sb.append("\n").append("resulting digest: " + getDigest().toString(digest)); - if(set_own_seqno && sb != null) - sb.append("\nnew seqno for " + local_addr + ": " + seqno); - if(sb != null) - digest_history.add(sb.toString()); - if(log.isDebugEnabled()) - log.debug(sb.toString()); - } - - - protected Table createTable(long initial_seqno) { - return new Table(xmit_table_num_rows, xmit_table_msgs_per_row, - initial_seqno, xmit_table_resize_factor, xmit_table_max_compaction_time); - } - - - - /** - * Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest - * which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update xmit_table: - * for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the - * retransmit buffer corresponding to P which are <= seqno at digest[P]. - */ - protected void stable(Digest digest) { - if(members == null || local_addr == null || digest == null) - return; - - log.trace("%s: received stable digest %s", local_addr, digest); - stability_msgs.add(digest.toString()); - - for(Digest.Entry entry: digest) { - Address member=entry.getMember(); - if(member == null) - continue; - long hd=entry.getHighestDeliveredSeqno(); - long hr=entry.getHighestReceivedSeqno(); - - // check whether the last seqno received for a sender P in the stability digest is > last seqno - // received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic in DESIGN) - Table buf=xmit_table.get(member); - if(buf != null) { - long my_hr=buf.getHighestReceived(); - if(hr >= 0 && hr > my_hr) { - log.trace("%s: my_highest_rcvd (%) < stability_highest_rcvd (%): requesting retransmission of %s", - local_addr, my_hr, hr, member + "#" + hr); - retransmit(hr, hr, member); - } - } - - // delete *delivered* msgs that are stable (all messages with seqnos <= seqno) - if(hd >= 0 && buf != null) { - log.trace("%s: deleting msgs <= %s from %s", local_addr, hd, member); - buf.purge(hd); - } - } - } - - - protected void retransmit(long first_seqno, long last_seqno, Address sender) { - if(first_seqno <= last_seqno) - retransmit(first_seqno,last_seqno,sender,false); - } - - - - protected void retransmit(long first_seqno, long last_seqno, final Address sender, boolean multicast_xmit_request) { - retransmit(new SeqnoList(first_seqno,last_seqno),sender,multicast_xmit_request); - } - - protected void retransmit(SeqnoList missing_msgs, final Address sender, boolean multicast_xmit_request) { - Address dest=(multicast_xmit_request || this.use_mcast_xmit_req)? null : sender; // to whom do we send the XMIT request ? - - if(xmit_from_random_member && !local_addr.equals(sender)) { - Address random_member=Util.pickRandomElement(members); - if(random_member != null && !local_addr.equals(random_member)) - dest=random_member; - } - - Message retransmit_msg=new Message(dest, missing_msgs).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL) - .putHeader(this.id, NakAckHeader2.createXmitRequestHeader(sender)); - - log.trace("%s: sending XMIT_REQ (%s) to %s", local_addr, missing_msgs, dest); - down_prot.down(new Event(Event.MSG, retransmit_msg)); - if(stats) - xmit_reqs_sent.addAndGet(missing_msgs.size()); - } - - - protected void reset() { - seqno.set(0); - xmit_table.clear(); - } - - - - protected static long sizeOfAllMessages(Table buf, boolean include_headers) { - Counter counter=new Counter(include_headers); - buf.forEach(buf.getHighestDelivered() + 1,buf.getHighestReceived(),counter); - return counter.getResult(); - } - - protected void startRetransmitTask() { - if(xmit_task == null || xmit_task.isDone()) - xmit_task=timer.scheduleWithFixedDelay(new RetransmitTask(), 0, xmit_interval, TimeUnit.MILLISECONDS); - } - - protected void stopRetransmitTask() { - if(xmit_task != null) { - xmit_task.cancel(true); - xmit_task=null; - } - } - - - - /** - * Retransmitter task which periodically (every xmit_interval ms) looks at all the retransmit tables and - * sends retransmit request to all members from which we have missing messages - */ - protected class RetransmitTask implements Runnable { - public void run() { - triggerXmit(); - } - - public String toString() { - return NAKACK2.class.getSimpleName() + ": RetransmitTask (interval=" + xmit_interval + " ms)"; - } - } - - @ManagedOperation(description="Triggers the retransmission task, asking all senders for missing messages") - public void triggerXmit() { - SeqnoList missing; - - for(Map.Entry> entry: xmit_table.entrySet()) { - Address target=entry.getKey(); // target to send retransmit requests to - Table buf=entry.getValue(); - - if(buf != null && buf.getNumMissing() > 0 && (missing=buf.getMissing()) != null) { // getNumMissing() is fast - long highest=missing.getLast(); - Long prev_seqno=xmit_task_map.get(target); - if(prev_seqno == null) { - xmit_task_map.put(target, highest); // no retransmission - } - else { - missing.removeHigherThan(prev_seqno); // we only retransmit the 'previous batch' - if(highest > prev_seqno) - xmit_task_map.put(target, highest); - if(missing.size() > 0) - retransmit(missing, target, false); - } - } - else if(!xmit_task_map.isEmpty()) - xmit_task_map.remove(target); // no current gaps for target - } - } - - - - - protected static class Counter implements Table.Visitor { - protected final boolean count_size; // use size() or length() - protected long result=0; - - public Counter(boolean count_size) { - this.count_size=count_size; - } - - public long getResult() {return result;} - - public boolean visit(long seqno, Message element, int row, int column) { - if(element != null) - result+=count_size? element.size() : element.getLength(); - return true; - } - } - - - -} diff --git a/All/Genesis-NP/Genesis#235/old/NAKACK2.java b/All/Genesis-NP/Genesis#235/old/NAKACK2.java deleted file mode 100755 index 6442f5e..0000000 --- a/All/Genesis-NP/Genesis#235/old/NAKACK2.java +++ /dev/null @@ -1,1486 +0,0 @@ -package org.jgroups.protocols.pbcast; - -import org.jgroups.Address; -import org.jgroups.Event; -import org.jgroups.Message; -import org.jgroups.View; -import org.jgroups.annotations.*; -import org.jgroups.protocols.TP; -import org.jgroups.stack.DiagnosticsHandler; -import org.jgroups.stack.Protocol; -import org.jgroups.util.*; - -import java.util.*; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Executor; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.locks.Condition; -import java.util.concurrent.locks.Lock; -import java.util.concurrent.locks.ReentrantLock; - - -/** - * Negative AcKnowledgement layer (NAKs). Messages are assigned a monotonically - * increasing sequence number (seqno). Receivers deliver messages ordered - * according to seqno and request retransmission of missing messages.
- * Retransmit requests are usually sent to the original sender of a message, but - * this can be changed by xmit_from_random_member (send to random member) or - * use_mcast_xmit_req (send to everyone). Responses can also be sent to everyone - * instead of the requester by setting use_mcast_xmit to true. - * - * @author Bela Ban - */ -@MBean(description="Reliable transmission multipoint FIFO protocol") -public class NAKACK2 extends Protocol implements DiagnosticsHandler.ProbeHandler { - protected static final int NUM_REBROADCAST_MSGS=3; - - /* ----------------------------------------------------- Properties --------------------- ------------------------------------ */ - - - - @Property(description="Max number of messages to be removed from a RingBuffer. This property might " + - "get removed anytime, so don't use it !") - protected int max_msg_batch_size=100; - - /** - * Retransmit messages using multicast rather than unicast. This has the advantage that, if many receivers - * lost a message, the sender only retransmits once - */ - @Property(description="Retransmit retransmit responses (messages) using multicast rather than unicast") - protected boolean use_mcast_xmit=true; - - /** - * Use a multicast to request retransmission of missing messages. This may - * be costly as every member in the cluster will send a response - */ - @Property(description="Use a multicast to request retransmission of missing messages") - protected boolean use_mcast_xmit_req=false; - - - /** - * Ask a random member for retransmission of a missing message. If set to - * true, discard_delivered_msgs will be set to false - */ - @Property(description="Ask a random member for retransmission of a missing message. Default is false") - protected boolean xmit_from_random_member=false; - - - /** - * Messages that have been received in order are sent up the stack (= delivered to the application). - * Delivered messages are removed from the retransmission buffer, so they can get GC'ed by the JVM. When this - * property is true, everyone (except the sender of a message) removes the message from their retransission - * buffers as soon as it has been delivered to the application - */ - @Property(description="Should messages delivered to application be discarded") - protected boolean discard_delivered_msgs=true; - - @Property(description="Timeout to rebroadcast messages. Default is 2000 msec") - protected long max_rebroadcast_timeout=2000; - - /** - * When not finding a message on an XMIT request, include the last N - * stability messages in the error message - */ - @Property(description="Should stability history be printed if we fail in retransmission. Default is false") - protected boolean print_stability_history_on_failed_xmit=false; - - - /** If true, logs messages discarded because received from other members */ - @Property(description="discards warnings about promiscuous traffic") - protected boolean log_discard_msgs=true; - - @Property(description="If true, trashes warnings about retransmission messages not found in the xmit_table (used for testing)") - protected boolean log_not_found_msgs=true; - - @Property(description="Interval (in milliseconds) at which missing messages (from all retransmit buffers) " + - "are retransmitted") - protected long xmit_interval=1000; - - @Property(description="Number of rows of the matrix in the retransmission table (only for experts)",writable=false) - protected int xmit_table_num_rows=50; - - @Property(description="Number of elements of a row of the matrix in the retransmission table (only for experts). " + - "The capacity of the matrix is xmit_table_num_rows * xmit_table_msgs_per_row",writable=false) - protected int xmit_table_msgs_per_row=10000; - - @Property(description="Resize factor of the matrix in the retransmission table (only for experts)",writable=false) - protected double xmit_table_resize_factor=1.2; - - @Property(description="Number of milliseconds after which the matrix in the retransmission table " + - "is compacted (only for experts)",writable=false) - protected long xmit_table_max_compaction_time=10000; - - @Property(description="Size of the queue to hold messages received after creating the channel, but before being " + - "connected (is_server=false). After becoming the server, the messages in the queue are fed into up() and the " + - "queue is cleared. The motivation is to avoid retransmissions (see https://issues.jboss.org/browse/JGRP-1509 " + - "for details). 0 disables the queue.") - protected int become_server_queue_size=50; - - @Property(description="Time during which identical warnings about messages from a non member will be suppressed. " + - "0 disables this (every warning will be logged). Setting the log level to ERROR also disables this.") - protected long suppress_time_non_member_warnings=60000; - - /* -------------------------------------------------- JMX ---------------------------------------------------------- */ - - - - @ManagedAttribute(description="Number of retransmit requests received") - protected final AtomicLong xmit_reqs_received=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit requests sent") - protected final AtomicLong xmit_reqs_sent=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit responses received") - protected final AtomicLong xmit_rsps_received=new AtomicLong(0); - - @ManagedAttribute(description="Number of retransmit responses sent") - protected final AtomicLong xmit_rsps_sent=new AtomicLong(0); - - @ManagedAttribute(description="Is the retransmit task running") - public boolean isXmitTaskRunning() {return xmit_task != null && !xmit_task.isDone();} - - @ManagedAttribute(description="Number of messages sent") - protected int num_messages_sent=0; - - @ManagedAttribute(description="Number of messages received") - protected int num_messages_received=0; - - @ManagedAttribute(description="Number of messages from non-members") - public int getNonMemberMessages() { - return suppress_log_non_member != null? suppress_log_non_member.getCache().size() : 0; - } - - @ManagedOperation(description="Clears the cache for messages from non-members") - public void clearNonMemberCache() { - if(suppress_log_non_member != null) - suppress_log_non_member.getCache().clear(); - } - - - /* ------------------------------------------------- Fields ------------------------------------------------------------------------- */ - protected volatile boolean is_server=false; - protected Address local_addr=null; - protected volatile List
members=new ArrayList
(); - protected volatile View view; - private final AtomicLong seqno=new AtomicLong(0); // current message sequence number (starts with 1) - - /** Map to store sent and received messages (keyed by sender) */ - protected final ConcurrentMap> xmit_table=Util.createConcurrentMap(); - - /** RetransmitTask running every xmit_interval ms */ - protected Future xmit_task; - /** Used by the retransmit task to keep the last retransmitted seqno per sender (https://issues.jboss.org/browse/JGRP-1539) */ - protected final Map xmit_task_map=new HashMap(); - - protected volatile boolean leaving=false; - protected volatile boolean running=false; - protected TimeScheduler timer=null; - - protected final Lock rebroadcast_lock=new ReentrantLock(); - protected final Condition rebroadcast_done=rebroadcast_lock.newCondition(); - - // set during processing of a rebroadcast event - protected volatile boolean rebroadcasting=false; - protected final Lock rebroadcast_digest_lock=new ReentrantLock(); - @GuardedBy("rebroadcast_digest_lock") - protected Digest rebroadcast_digest=null; - - /** Keeps the last N stability messages */ - protected final BoundedList stability_msgs=new BoundedList(10); - - /** Keeps a bounded list of the last N digest sets */ - protected final BoundedList digest_history=new BoundedList(10); - - protected BoundedList become_server_queue; - - /** Log to suppress identical warnings for messages from non-members */ - protected SuppressLog
suppress_log_non_member; - - - public long getXmitRequestsReceived() {return xmit_reqs_received.get();} - public long getXmitRequestsSent() {return xmit_reqs_sent.get();} - public long getXmitResponsesReceived() {return xmit_rsps_received.get();} - public long getXmitResponsesSent() {return xmit_rsps_sent.get();} - public boolean isUseMcastXmit() {return use_mcast_xmit;} - public boolean isXmitFromRandomMember() {return xmit_from_random_member;} - public boolean isDiscardDeliveredMsgs() {return discard_delivered_msgs;} - public boolean getLogDiscardMessages() {return log_discard_msgs;} - public void setUseMcastXmit(boolean use_mcast_xmit) {this.use_mcast_xmit=use_mcast_xmit;} - public void setUseMcastXmitReq(boolean flag) {this.use_mcast_xmit_req=flag;} - public void setLogDiscardMessages(boolean flag) {log_discard_msgs=flag;} - public void setLogNotFoundMessages(boolean flag) {log_not_found_msgs=flag;} - public void setXmitFromRandomMember(boolean xmit_from_random_member) { - this.xmit_from_random_member=xmit_from_random_member; - } - public void setDiscardDeliveredMsgs(boolean discard_delivered_msgs) { - this.discard_delivered_msgs=discard_delivered_msgs; - } - - @ManagedAttribute(description="Actual size of the become_server_queue") - public int getBecomeServerQueueSizeActual() { - return become_server_queue != null? become_server_queue.size() : -1; - } - - /** Returns the receive window for sender; only used for testing. Do not use ! */ - public Table getWindow(Address sender) { - return xmit_table.get(sender); - } - - - /** Only used for unit tests, don't use ! */ - public void setTimer(TimeScheduler timer) {this.timer=timer;} - - - @ManagedAttribute(description="Total number of undelivered messages in all retransmit buffers") - public int getXmitTableUndeliveredMsgs() { - int num=0; - for(Table buf: xmit_table.values()) - num+=buf.size(); - return num; - } - - @ManagedAttribute(description="Total number of missing (= not received) messages in all retransmit buffers") - public int getXmitTableMissingMessages() { - int num=0; - for(Table buf: xmit_table.values()) - num+=buf.getNumMissing(); - return num; - } - - @ManagedAttribute(description="Capacity of the retransmit buffer. Computed as xmit_table_num_rows * xmit_table_msgs_per_row") - public long getXmitTableCapacity() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.capacity() : 0; - } - - @ManagedAttribute(description="Prints the number of rows currently allocated in the matrix. This value will not " + - "be lower than xmit_table_now_rows") - public int getXmitTableNumCurrentRows() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumRows() : 0; - } - - @ManagedAttribute(description="Returns the number of bytes of all messages in all retransmit buffers. " + - "To compute the size, Message.getLength() is used") - public long getSizeOfAllMessages() { - long retval=0; - for(Table buf: xmit_table.values()) - retval+=sizeOfAllMessages(buf,false); - return retval; - } - - @ManagedAttribute(description="Returns the number of bytes of all messages in all retransmit buffers. " + - "To compute the size, Message.size() is used") - public long getSizeOfAllMessagesInclHeaders() { - long retval=0; - for(Table buf: xmit_table.values()) - retval+=sizeOfAllMessages(buf, true); - return retval; - } - - @ManagedAttribute(description="Number of retransmit table compactions") - public int getXmitTableNumCompactions() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumCompactions() : 0; - } - - @ManagedAttribute(description="Number of retransmit table moves") - public int getXmitTableNumMoves() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumMoves() : 0; - } - - @ManagedAttribute(description="Number of retransmit table resizes") - public int getXmitTableNumResizes() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumResizes(): 0; - } - - @ManagedAttribute(description="Number of retransmit table purges") - public int getXmitTableNumPurges() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - return table != null? table.getNumPurges(): 0; - } - - @ManagedOperation(description="Prints the contents of the receiver windows for all members") - public String printMessages() { - StringBuilder ret=new StringBuilder(local_addr + ":\n"); - for(Map.Entry> entry: xmit_table.entrySet()) { - Address addr=entry.getKey(); - Table buf=entry.getValue(); - ret.append(addr).append(": ").append(buf.toString()).append('\n'); - } - return ret.toString(); - } - - @ManagedAttribute public long getCurrentSeqno() {return seqno.get();} - - @ManagedOperation(description="Prints the stability messages received") - public String printStabilityMessages() { - StringBuilder sb=new StringBuilder(); - sb.append(Util.printListWithDelimiter(stability_msgs, "\n")); - return sb.toString(); - } - - @ManagedOperation(description="Keeps information about the last N times a digest was set or merged") - public String printDigestHistory() { - StringBuilder sb=new StringBuilder(local_addr + ":\n"); - for(String tmp: digest_history) - sb.append(tmp).append("\n"); - return sb.toString(); - } - - @ManagedOperation(description="Compacts the retransmit buffer") - public void compact() { - Table table=local_addr != null? xmit_table.get(local_addr) : null; - if(table != null) - table.compact(); - } - - @ManagedOperation(description="Prints the number of rows currently allocated in the matrix for all members. " + - "This value will not be lower than xmit_table_now_rows") - public String dumpXmitTablesNumCurrentRows() { - StringBuilder sb=new StringBuilder(); - for(Map.Entry> entry: xmit_table.entrySet()) { - sb.append(entry.getKey()).append(": ").append(entry.getValue().getNumRows()).append("\n"); - } - return sb.toString(); - } - - @ManagedOperation(description="Resets all statistics") - public void resetStats() { - num_messages_sent=num_messages_received=0; - xmit_reqs_received.set(0); - xmit_reqs_sent.set(0); - xmit_rsps_received.set(0); - xmit_rsps_sent.set(0); - stability_msgs.clear(); - digest_history.clear(); - Table table=local_addr != null? xmit_table.get(local_addr) : null; - if(table != null) - table.resetStats(); - } - - public void init() throws Exception { - if(xmit_from_random_member) { - if(discard_delivered_msgs) { - discard_delivered_msgs=false; - log.debug("%s: xmit_from_random_member set to true: changed discard_delivered_msgs to false", local_addr); - } - } - - TP transport=getTransport(); - if(transport != null) { - transport.registerProbeHandler(this); - if(!transport.supportsMulticasting()) { - if(use_mcast_xmit) { - log.warn("use_mcast_xmit should not be used because the transport (" + transport.getName() + - ") does not support IP multicasting; setting use_mcast_xmit to false"); - use_mcast_xmit=false; - } - if(use_mcast_xmit_req) { - log.warn("use_mcast_xmit_req should not be used because the transport (" + transport.getName() + - ") does not support IP multicasting; setting use_mcast_xmit_req to false"); - use_mcast_xmit_req=false; - } - } - } - - if(become_server_queue_size > 0) - become_server_queue=new BoundedList(become_server_queue_size); - - if(suppress_time_non_member_warnings > 0) - suppress_log_non_member=new SuppressLog
(log, "MsgDroppedNak", "SuppressMsg"); - } - - - public Map dumpStats() { - Map retval=super.dumpStats(); - retval.put("msgs", printMessages()); - return retval; - } - - public String printStats() { - StringBuilder sb=new StringBuilder(); - sb.append("\nStability messages received\n"); - sb.append(printStabilityMessages()).append("\n"); - - return sb.toString(); - } - - - - public String printStabilityHistory() { - StringBuilder sb=new StringBuilder(); - int i=1; - for(String digest: stability_msgs) - sb.append(i++).append(": ").append(digest).append("\n"); - return sb.toString(); - } - - - - public List providedUpServices() { - return Arrays.asList(Event.GET_DIGEST,Event.SET_DIGEST,Event.OVERWRITE_DIGEST,Event.MERGE_DIGEST); - } - - - public void start() throws Exception { - timer=getTransport().getTimer(); - if(timer == null) - throw new Exception("timer is null"); - running=true; - leaving=false; - startRetransmitTask(); - } - - - public void stop() { - running=false; - is_server=false; - if(become_server_queue != null) - become_server_queue.clear(); - stopRetransmitTask(); - xmit_task_map.clear(); - reset(); - } - - - /** - * Callback. Called by superclass when event may be handled.

Do not use down_prot.down() in this - * method as the event is passed down by default by the superclass after this method returns ! - */ - public Object down(Event evt) { - switch(evt.getType()) { - - case Event.MSG: - Message msg=(Message)evt.getArg(); - Address dest=msg.getDest(); - if(dest != null || msg.isFlagSet(Message.Flag.NO_RELIABILITY)) - break; // unicast address: not null and not mcast, pass down unchanged - - send(evt, msg); - return null; // don't pass down the stack - - case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg - stable((Digest)evt.getArg()); - return null; // do not pass down further (Bela Aug 7 2001) - - case Event.GET_DIGEST: - return getDigest((Address)evt.getArg()); - - case Event.SET_DIGEST: - setDigest((Digest)evt.getArg()); - return null; - - case Event.OVERWRITE_DIGEST: - overwriteDigest((Digest)evt.getArg()); - return null; - - case Event.MERGE_DIGEST: - mergeDigest((Digest)evt.getArg()); - return null; - - case Event.TMP_VIEW: - View tmp_view=(View)evt.getArg(); - members=tmp_view.getMembers(); - break; - - case Event.VIEW_CHANGE: - tmp_view=(View)evt.getArg(); - List

mbrs=tmp_view.getMembers(); - members=mbrs; - view=tmp_view; - adjustReceivers(mbrs); - is_server=true; // check vids from now on - if(suppress_log_non_member != null) - suppress_log_non_member.removeExpired(suppress_time_non_member_warnings); - xmit_task_map.keySet().retainAll(mbrs); - break; - - case Event.BECOME_SERVER: - is_server=true; - flushBecomeServerQueue(); - break; - - case Event.SET_LOCAL_ADDRESS: - local_addr=(Address)evt.getArg(); - break; - - case Event.DISCONNECT: - leaving=true; - reset(); - break; - - case Event.REBROADCAST: - rebroadcasting=true; - rebroadcast_digest=(Digest)evt.getArg(); - try { - rebroadcastMessages(); - } - finally { - rebroadcasting=false; - rebroadcast_digest_lock.lock(); - try { - rebroadcast_digest=null; - } - finally { - rebroadcast_digest_lock.unlock(); - } - } - return null; - } - - return down_prot.down(evt); - } - - - - - /** - * Callback. Called by superclass when event may be handled.

Do not use PassUp in this - * method as the event is passed up by default by the superclass after this method returns ! - */ - public Object up(Event evt) { - switch(evt.getType()) { - - case Event.MSG: - Message msg=(Message)evt.getArg(); - if(msg.isFlagSet(Message.Flag.NO_RELIABILITY)) - break; - NakAckHeader2 hdr=(NakAckHeader2)msg.getHeader(this.id); - if(hdr == null) - break; // pass up (e.g. unicast msg) - - if(!is_server) { // discard messages while not yet server (i.e., until JOIN has returned) - if(become_server_queue != null) { - become_server_queue.add(msg); - log.trace("%s: message %s::%d was added to queue (not yet server)", local_addr, msg.getSrc(), hdr.seqno); - } - else - log.trace("%s: message %s::%d was discarded (not yet server)", local_addr, msg.getSrc(), hdr.seqno); - return null; - } - - // Changed by bela Jan 29 2003: we must not remove the header, otherwise further xmit requests will fail ! - //hdr=(NakAckHeader2)msg.removeHeader(getName()); - - switch(hdr.type) { - - case NakAckHeader2.MSG: - handleMessage(msg, hdr); - return null; // transmitter passes message up for us ! - - case NakAckHeader2.XMIT_REQ: - SeqnoList missing=(SeqnoList)msg.getObject(); - if(missing == null) - return null; - handleXmitReq(msg.getSrc(), missing, hdr.sender); - return null; - - case NakAckHeader2.XMIT_RSP: - handleXmitRsp(msg, hdr); - return null; - - default: - log.error("%s: header type %s not known", local_addr, hdr.type); - return null; - } - - case Event.STABLE: // generated by STABLE layer. Delete stable messages passed in arg - stable((Digest)evt.getArg()); - return null; // do not pass up further (Bela Aug 7 2001) - - case Event.SUSPECT: - // release the promise if rebroadcasting is in progress... otherwise we wait forever. there will be a new - // flush round anyway - if(rebroadcasting) - cancelRebroadcasting(); - break; - } - return up_prot.up(evt); - } - - - public void up(MessageBatch batch) { - int size=batch.size(); - boolean got_retransmitted_msg=false; // if at least 1 XMIT-RSP was received - List> msgs=null; // regular or retransmitted messages - - for(Iterator it=batch.iterator(); it.hasNext();) { - final Message msg=it.next(); - if(msg == null || msg.isFlagSet(Message.Flag.NO_RELIABILITY)) - continue; - NakAckHeader2 hdr=(NakAckHeader2)msg.getHeader(id); - if(hdr == null) - continue; - it.remove(); // remove the message from the batch, so it won't be passed up the stack - - if(!is_server) { // discard messages while not yet server (i.e., until JOIN has returned) - if(become_server_queue != null) { - become_server_queue.add(msg); - log.trace("%s: message %s::%d was added to queue (not yet server)", local_addr, msg.getSrc(), hdr.seqno); - } - else - log.trace("%s: message %s::%d was discarded (not yet server)", local_addr, msg.getSrc(), hdr.seqno); - continue; - } - - switch(hdr.type) { - case NakAckHeader2.MSG: - if(msgs == null) - msgs=new ArrayList>(size); - msgs.add(new Tuple(hdr.seqno, msg)); - break; - case NakAckHeader2.XMIT_REQ: - SeqnoList missing=(SeqnoList)msg.getObject(); - if(missing != null) - handleXmitReq(msg.getSrc(), missing, hdr.sender); - break; - case NakAckHeader2.XMIT_RSP: - Message xmitted_msg=msgFromXmitRsp(msg, hdr); - if(xmitted_msg != null) { - if(msgs == null) - msgs=new ArrayList>(size); - msgs.add(new Tuple(hdr.seqno, xmitted_msg)); - got_retransmitted_msg=true; - } - break; - default: - log.error("%s: header type %s not known", local_addr, hdr.type); - } - } - - // Process (new and retransmitted) messages: - if(msgs != null) - handleMessages(batch.sender(), msgs, batch.mode() == MessageBatch.Mode.OOB, batch.clusterName()); - - // received XMIT-RSPs: - if(got_retransmitted_msg && rebroadcasting) - checkForRebroadcasts(); - - if(!batch.isEmpty()) - up_prot.up(batch); - } - - // ProbeHandler interface - public Map handleProbe(String... keys) { - Map retval=new HashMap(); - for(String key: keys) { - if(key.equals("digest-history")) - retval.put(key, printDigestHistory()); - if(key.equals("dump-digest")) - retval.put(key, "\n" + printMessages()); - } - - return retval; - } - - // ProbeHandler interface - public String[] supportedKeys() { - return new String[]{"digest-history", "dump-digest"}; - } - - - - - /* --------------------------------- Private Methods --------------------------------------- */ - - /** - * Adds the message to the sent_msgs table and then passes it down the stack. Change Bela Ban May 26 2002: we don't - * store a copy of the message, but a reference ! This saves us a lot of memory. However, this also means that a - * message should not be changed after storing it in the sent-table ! See protocols/DESIGN for details. - * Made seqno increment and adding to sent_msgs atomic, e.g. seqno won't get incremented if adding to - * sent_msgs fails e.g. due to an OOM (see http://jira.jboss.com/jira/browse/JGRP-179). bela Jan 13 2006 - */ - protected void send(Event evt, Message msg) { - if(msg == null) - throw new NullPointerException("msg is null; event is " + evt); - - if(!running) { - log.trace("%s: discarded message as we're not in the 'running' state, message: %s", local_addr, msg); - return; - } - - long msg_id; - Table buf=xmit_table.get(local_addr); - if(buf == null) // discard message if there is no entry for local_addr - return; - - if(msg.getSrc() == null) - msg.setSrc(local_addr); // this needs to be done so we can check whether the message sender is the local_addr - - msg_id=seqno.incrementAndGet(); - long sleep=10; - while(running) { - try { - msg.putHeader(this.id, NakAckHeader2.createMessageHeader(msg_id)); - buf.add(msg_id, msg); - break; - } - catch(Throwable t) { - if(!running) - break; - Util.sleep(sleep); - sleep=Math.min(5000, sleep*2); - } - } - - // moved down_prot.down() out of synchronized clause (bela Sept 7 2006) http://jira.jboss.com/jira/browse/JGRP-300 - if(log.isTraceEnabled()) - log.trace("%s: sending %s#%d", local_addr, local_addr, msg_id); - down_prot.down(evt); // if this fails, since msg is in sent_msgs, it can be retransmitted - num_messages_sent++; - } - - - - /** - * Finds the corresponding retransmit buffer and adds the message to it (according to seqno). Then removes as many - * messages as possible and passes them up the stack. Discards messages from non-members. - */ - protected void handleMessage(Message msg, NakAckHeader2 hdr) { - Address sender=msg.getSrc(); - Table buf=xmit_table.get(sender); - if(buf == null) { // discard message if there is no entry for sender - if(leaving) - return; - if(log.isWarnEnabled() && log_discard_msgs) { - if(suppress_log_non_member != null) - suppress_log_non_member.log(SuppressLog.Level.warn, sender, suppress_time_non_member_warnings, - local_addr, hdr.seqno, sender, view); - else - log.warn(Util.getMessage("MsgDroppedNak"), local_addr, hdr.seqno, sender, view); - } - return; - } - - num_messages_received++; - boolean loopback=local_addr.equals(sender); - boolean added=loopback || buf.add(hdr.seqno, msg); - - if(added && log.isTraceEnabled()) - log.trace("%s: received %s#%d", local_addr, sender, hdr.seqno); - - - // OOB msg is passed up. When removed, we discard it. Affects ordering: http://jira.jboss.com/jira/browse/JGRP-379 - if(added && msg.isFlagSet(Message.Flag.OOB)) { - if(loopback) - msg=buf.get(hdr.seqno); // we *have* to get a message, because loopback means we didn't add it to win ! - if(msg != null && msg.isFlagSet(Message.Flag.OOB)) { - if(msg.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED)) { - if(log.isTraceEnabled()) - log.trace("%s: delivering %s#%d", local_addr, sender, hdr.seqno); - try { - up_prot.up(new Event(Event.MSG, msg)); - } - catch(Throwable t) { - log.error("%s: failed to deliver OOB message %s: %t", local_addr, msg, t); - } - } - } - } - - removeAndPassUp(buf, sender, loopback, null); // at most 1 thread will execute this at any given time - } - - - protected void handleMessages(Address sender, List> msgs, boolean oob, String cluster_name) { - Table buf=xmit_table.get(sender); - if(buf == null) { // discard message if there is no entry for sender - if(leaving) - return; - if(log.isWarnEnabled() && log_discard_msgs) { - if(suppress_log_non_member != null) - suppress_log_non_member.log(SuppressLog.Level.warn, sender, suppress_time_non_member_warnings, - local_addr, "batch", sender, view); - else - log.warn(Util.getMessage("MsgDroppedNak"), local_addr, "batch", sender, view); - } - return; - } - int size=msgs.size(); - num_messages_received+=size; - boolean loopback=local_addr.equals(sender); - boolean added=loopback || (oob ? buf.add(msgs, true) : buf.add(msgs)); - - if(added && log.isTraceEnabled()) - log.trace("%s: received %s#%d - #%d (%d messages)", - local_addr, sender, msgs.get(0).getVal1(), msgs.get(size-1).getVal1(), msgs.size()); - - - // OOB msg is passed up. When removed, we discard it. Affects ordering: http://jira.jboss.com/jira/browse/JGRP-379 - if(added && oob) { - for(Tuple tuple: msgs) { - long seq=tuple.getVal1(); - Message msg=loopback? buf.get(seq) : tuple.getVal2(); // we *have* to get the message, because loopback means we didn't add it to win ! - if(msg != null && msg.isFlagSet(Message.Flag.OOB)) { - if(msg.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED)) { - if(log.isTraceEnabled()) - log.trace("%s: delivering %s#%d", local_addr, sender, seq); - try { - up_prot.up(new Event(Event.MSG, msg)); - } - catch(Throwable t) { - log.error("%s: failed to deliver OOB message %s: %s", local_addr, msg, t); - } - } - } - } - } - - removeAndPassUp(buf,sender,loopback,cluster_name); // at most 1 thread will execute this at any given time - } - - - /** Efficient way of checking whether another thread is already processing messages from sender. If that's the case, - * we return immediately and let the existing thread process our message (https://jira.jboss.org/jira/browse/JGRP-829). - * Benefit: fewer threads blocked on the same lock, these threads an be returned to the thread pool */ - protected void removeAndPassUp(Table buf, Address sender, boolean loopback, String cluster_name) { - final AtomicBoolean processing=buf.getProcessing(); - if(!processing.compareAndSet(false, true)) - return; - - boolean remove_msgs=discard_delivered_msgs && !loopback; - boolean released_processing=false; - try { - while(true) { - // we're removing a msg and set processing to false (if null) *atomically* (wrt to add()) - List msgs=buf.removeMany(processing, remove_msgs, max_msg_batch_size); - if(msgs == null || msgs.isEmpty()) { - released_processing=true; - if(rebroadcasting) - checkForRebroadcasts(); - return; - } - - MessageBatch batch=new MessageBatch(null, sender, cluster_name, true, msgs); - for(Message msg_to_deliver: batch) { - // discard OOB msg if it has already been delivered (http://jira.jboss.com/jira/browse/JGRP-379) - if(msg_to_deliver.isFlagSet(Message.Flag.OOB) && !msg_to_deliver.setTransientFlagIfAbsent(Message.TransientFlag.OOB_DELIVERED)) - batch.remove(msg_to_deliver); - } - if(batch.isEmpty()) - continue; - - try { - if(log.isTraceEnabled()) { - Message first=batch.first(), last=batch.last(); - StringBuilder sb=new StringBuilder(local_addr + ": delivering"); - if(first != null && last != null) { - NakAckHeader2 hdr1=(NakAckHeader2)first.getHeader(id), hdr2=(NakAckHeader2)last.getHeader(id); - sb.append(" #").append(hdr1.seqno).append(" - #").append(hdr2.seqno); - } - sb.append(" (" + batch.size()).append(" messages)"); - log.trace(sb); - } - up_prot.up(batch); - } - catch(Throwable t) { - log.error("%s: failed to deliver batch %s: %t", local_addr, batch, t); - } - } - } - finally { - // processing is always set in win.remove(processing) above and never here ! This code is just a - // 2nd line of defense should there be an exception before win.remove(processing) sets processing - if(!released_processing) - processing.set(false); - } - } - - - - /** - * Retransmits messsages first_seqno to last_seqno from original_sender from xmit_table to xmit_requester, - * called when XMIT_REQ is received. - * @param xmit_requester The sender of the XMIT_REQ, we have to send the requested copy of the message to this address - * @param missing_msgs A list of seqnos that have to be retransmitted - * @param original_sender The member who originally sent the messsage. Guaranteed to be non-null - */ - protected void handleXmitReq(Address xmit_requester, SeqnoList missing_msgs, Address original_sender) { - log.trace("%s: received xmit request from %s for %s%s", local_addr, xmit_requester, original_sender, missing_msgs); - - if(stats) - xmit_reqs_received.addAndGet(missing_msgs.size()); - - Table buf=xmit_table.get(original_sender); - if(buf == null) { - if(log.isErrorEnabled()) { - StringBuilder sb=new StringBuilder(); - sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); - sb.append(") ").append(original_sender).append(" not found in retransmission table"); - // don't print the table unless we are in trace mode because it can be LARGE - if(log.isTraceEnabled()) - sb.append(":\n").append(printMessages()); - if(print_stability_history_on_failed_xmit) - sb.append(" (stability history:\n").append(printStabilityHistory()); - log.error(sb.toString()); - } - return; - } - - for(long i: missing_msgs) { - Message msg=buf.get(i); - if(msg == null) { - if(log.isWarnEnabled() && log_not_found_msgs && !local_addr.equals(xmit_requester) && i > buf.getLow()) { - StringBuilder sb=new StringBuilder(); - sb.append("(requester=").append(xmit_requester).append(", local_addr=").append(this.local_addr); - sb.append(") message ").append(original_sender).append("::").append(i); - sb.append(" not found in retransmission table of ").append(original_sender).append(":\n").append(buf); - if(print_stability_history_on_failed_xmit) - sb.append(" (stability history:\n").append(printStabilityHistory()); - log.warn(sb.toString()); - } - continue; - } - if(log.isTraceEnabled()) - log.trace(local_addr + ": resending " + original_sender + "::" + i); - sendXmitRsp(xmit_requester, msg); - } - } - - - /** - * Flushes the queue. Done in a separate thread as we don't want to block the - * {@link ClientGmsImpl#installView(org.jgroups.View,org.jgroups.util.Digest)} method (called when a view is installed). - */ - protected void flushBecomeServerQueue() { - if(become_server_queue != null && !become_server_queue.isEmpty()) { - log.trace("%s: flushing become_server_queue (%d elements)", local_addr, become_server_queue.size()); - - TP transport=getTransport(); - Executor thread_pool=transport.getDefaultThreadPool(), oob_thread_pool=transport.getOOBThreadPool(); - - for(final Message msg: become_server_queue) { - Executor pool=msg.isFlagSet(Message.Flag.OOB)? oob_thread_pool : thread_pool; - pool.execute(new Runnable() { - public void run() { - try { - up(new Event(Event.MSG, msg)); - } - finally { - become_server_queue.remove(msg); - } - } - }); - } - } - } - - - protected void cancelRebroadcasting() { - rebroadcast_lock.lock(); - try { - rebroadcasting=false; - rebroadcast_done.signalAll(); - } - finally { - rebroadcast_lock.unlock(); - } - } - - - - - /** - * Sends a message msg to the requester. We have to wrap the original message into a retransmit message, as we need - * to preserve the original message's properties, such as src, headers etc. - * @param dest - * @param msg - */ - protected void sendXmitRsp(Address dest, Message msg) { - if(msg == null) - return; - - if(stats) - xmit_rsps_sent.incrementAndGet(); - - if(msg.getSrc() == null) - msg.setSrc(local_addr); - - if(use_mcast_xmit) { // we simply send the original multicast message - down_prot.down(new Event(Event.MSG, msg)); - return; - } - - Message xmit_msg=msg.copy(true, true).dest(dest).setFlag(Message.Flag.INTERNAL); // copy payload and headers - NakAckHeader2 hdr=(NakAckHeader2)xmit_msg.getHeader(id); - NakAckHeader2 newhdr=hdr.copy(); - newhdr.type=NakAckHeader2.XMIT_RSP; // change the type in the copy from MSG --> XMIT_RSP - xmit_msg.putHeader(id, newhdr); - down_prot.down(new Event(Event.MSG,xmit_msg)); - } - - - protected void handleXmitRsp(Message msg, NakAckHeader2 hdr) { - if(msg == null) - return; - - try { - if(stats) - xmit_rsps_received.incrementAndGet(); - - msg.setDest(null); - NakAckHeader2 newhdr=hdr.copy(); - newhdr.type=NakAckHeader2.MSG; // change the type back from XMIT_RSP --> MSG - msg.putHeader(id, newhdr); - up(new Event(Event.MSG, msg)); - if(rebroadcasting) - checkForRebroadcasts(); - } - catch(Exception ex) { - log.error("%s: failed handling retransmitted message: ", local_addr, ex); - } - } - - protected Message msgFromXmitRsp(Message msg, NakAckHeader2 hdr) { - if(msg == null) - return null; - - if(stats) - xmit_rsps_received.incrementAndGet(); - - msg.setDest(null); - NakAckHeader2 newhdr=hdr.copy(); - newhdr.type=NakAckHeader2.MSG; // change the type back from XMIT_RSP --> MSG - msg.putHeader(id,newhdr); - return msg; - } - - - /** - * Takes the argument highest_seqnos and compares it to the current digest. If the current digest has fewer messages, - * then send retransmit messages for the missing messages. Return when all missing messages have been received. If - * we're waiting for a missing message from P, and P crashes while waiting, we need to exclude P from the wait set. - */ - protected void rebroadcastMessages() { - Digest their_digest; - long sleep=max_rebroadcast_timeout / NUM_REBROADCAST_MSGS; - long wait_time=max_rebroadcast_timeout, start=System.currentTimeMillis(); - - while(wait_time > 0) { - rebroadcast_digest_lock.lock(); - try { - if(rebroadcast_digest == null) - break; - their_digest=rebroadcast_digest.copy(); - } - finally { - rebroadcast_digest_lock.unlock(); - } - Digest my_digest=getDigest(); - boolean xmitted=false; - - for(Digest.Entry entry: their_digest) { - Address member=entry.getMember(); - long[] my_entry=my_digest.get(member); - if(my_entry == null) - continue; - long their_high=entry.getHighest(); - - // Cannot ask for 0 to be retransmitted because the first seqno in NAKACK2 and UNICAST(2) is always 1 ! - // Also, we need to ask for retransmission of my_high+1, because we already *have* my_high, and don't - // need it, so the retransmission range is [my_high+1 .. their_high]: *exclude* my_high, but *include* - // their_high - long my_high=Math.max(my_entry[0], my_entry[1]); - if(their_high > my_high) { - log.trace("%s: fetching %d-%d from %s", local_addr, my_high, their_high, member); - retransmit(my_high+1, their_high, member, true); // use multicast to send retransmit request - xmitted=true; - } - } - if(!xmitted) - return; // we're done; no retransmissions are needed anymore. our digest is >= rebroadcast_digest - - rebroadcast_lock.lock(); - try { - try { - my_digest=getDigest(); - rebroadcast_digest_lock.lock(); - try { - if(!rebroadcasting || isGreaterThanOrEqual(my_digest, rebroadcast_digest)) - return; - } - finally { - rebroadcast_digest_lock.unlock(); - } - rebroadcast_done.await(sleep, TimeUnit.MILLISECONDS); - wait_time-=(System.currentTimeMillis() - start); - } - catch(InterruptedException e) { - } - } - finally { - rebroadcast_lock.unlock(); - } - } - } - - protected void checkForRebroadcasts() { - Digest tmp=getDigest(); - boolean cancel_rebroadcasting; - rebroadcast_digest_lock.lock(); - try { - cancel_rebroadcasting=isGreaterThanOrEqual(tmp, rebroadcast_digest); - } - finally { - rebroadcast_digest_lock.unlock(); - } - if(cancel_rebroadcasting) { - cancelRebroadcasting(); - } - } - - /** - * Returns true if all senders of the current digest have their seqnos >= the ones from other - */ - protected static boolean isGreaterThanOrEqual(Digest first, Digest other) { - if(other == null) - return true; - - for(Digest.Entry entry: first) { - Address sender=entry.getMember(); - long[] their_entry=other.get(sender); - if(their_entry == null) - continue; - long my_highest=entry.getHighest(); - long their_highest=Math.max(their_entry[0],their_entry[1]); - if(my_highest < their_highest) - return false; - } - return true; - } - - - /** - * Removes old members from xmit-table and adds new members to xmit-table (at seqnos hd=0, hr=0). - * This method is not called concurrently - */ - protected void adjustReceivers(List

members) { - Set
keys=xmit_table.keySet(); - - // remove members which left - for(Address member: keys) { - if(!members.contains(member)) { - if(local_addr != null && local_addr.equals(member)) - continue; - Table buf=xmit_table.remove(member); - if(buf != null) - log.debug("%s: removed %s from xmit_table (not member anymore)", local_addr, member); - } - } - - for(Address member: members) - if(!keys.contains(member)) - xmit_table.putIfAbsent(member, createTable(0)); - } - - - /** - * Returns a message digest: for each member P the highest delivered and received seqno is added - */ - public Digest getDigest() { - final Map map=new HashMap(); - for(Map.Entry> entry: xmit_table.entrySet()) { - Address sender=entry.getKey(); // guaranteed to be non-null (CCHM) - Table buf=entry.getValue(); // guaranteed to be non-null (CCHM) - long[] seqnos=buf.getDigest(); - map.put(sender, seqnos); - } - return new Digest(map); - } - - - public Digest getDigest(Address mbr) { - if(mbr == null) - return getDigest(); - Table buf=xmit_table.get(mbr); - if(buf == null) - return null; - long[] seqnos=buf.getDigest(); - return new Digest(mbr, seqnos[0], seqnos[1]); - } - - - /** - * Creates a retransmit buffer for each sender in the digest according to the sender's seqno. - * If a buffer already exists, it resets it. - */ - protected void setDigest(Digest digest) { - setDigest(digest,false); - } - - - /** - * For all members of the digest, adjust the retransmit buffers in xmit_table. If no entry - * exists, create one with the initial seqno set to the seqno of the member in the digest. If the member already - * exists, and is not the local address, replace it with the new entry (http://jira.jboss.com/jira/browse/JGRP-699) - * if the digest's seqno is greater than the seqno in the window. - */ - protected void mergeDigest(Digest digest) { - setDigest(digest,true); - } - - /** - * Overwrites existing entries, but does NOT remove entries not found in the digest - * @param digest - */ - protected void overwriteDigest(Digest digest) { - if(digest == null) - return; - - StringBuilder sb=new StringBuilder("\n[overwriteDigest()]\n"); - sb.append("existing digest: " + getDigest()).append("\nnew digest: " + digest); - - for(Digest.Entry entry: digest) { - Address member=entry.getMember(); - if(member == null) - continue; - - long highest_delivered_seqno=entry.getHighestDeliveredSeqno(); - - Table buf=xmit_table.get(member); - if(buf != null) { - if(local_addr.equals(member)) { - // Adjust the highest_delivered seqno (to send msgs again): https://jira.jboss.org/browse/JGRP-1251 - buf.setHighestDelivered(highest_delivered_seqno); - continue; // don't destroy my own window - } - xmit_table.remove(member); - } - buf=createTable(highest_delivered_seqno); - xmit_table.put(member, buf); - } - sb.append("\n").append("resulting digest: " + getDigest().toString(digest)); - digest_history.add(sb.toString()); - if(log.isDebugEnabled()) - log.debug(sb.toString()); - } - - - /** - * Sets or merges the digest. If there is no entry for a given member in xmit_table, create a new buffer. - * Else skip the existing entry, unless it is a merge. In this case, skip the existing entry if its seqno is - * greater than or equal to the one in the digest, or reset the window and create a new one if not. - * @param digest The digest - * @param merge Whether to merge the new digest with our own, or not - */ - protected void setDigest(Digest digest, boolean merge) { - if(digest == null) - return; - - StringBuilder sb=log.isDebugEnabled()? - new StringBuilder(merge? "\n[" + local_addr + " mergeDigest()]\n" : "\n["+local_addr + " setDigest()]\n") - .append("existing digest: " + getDigest()).append("\nnew digest: " + digest) : null; - - boolean set_own_seqno=false; - for(Digest.Entry entry: digest) { - Address member=entry.getMember(); - if(member == null) - continue; - - long highest_delivered_seqno=entry.getHighestDeliveredSeqno(); - - Table buf=xmit_table.get(member); - if(buf != null) { - // We only reset the window if its seqno is lower than the seqno shipped with the digest. Also, we - // don't reset our own window (https://jira.jboss.org/jira/browse/JGRP-948, comment 20/Apr/09 03:39 AM) - if(!merge - || (local_addr != null && local_addr.equals(member)) // never overwrite our own entry - || buf.getHighestDelivered() >= highest_delivered_seqno) // my seqno is >= digest's seqno for sender - continue; - - xmit_table.remove(member); - // to get here, merge must be false ! - if(member.equals(local_addr)) { // Adjust the seqno: https://jira.jboss.org/browse/JGRP-1251 - seqno.set(highest_delivered_seqno); - set_own_seqno=true; - } - } - buf=createTable(highest_delivered_seqno); - xmit_table.put(member, buf); - } - if(sb != null) - sb.append("\n").append("resulting digest: " + getDigest().toString(digest)); - if(set_own_seqno && sb != null) - sb.append("\nnew seqno for " + local_addr + ": " + seqno); - if(sb != null) - digest_history.add(sb.toString()); - if(log.isDebugEnabled()) - log.debug(sb.toString()); - } - - - protected Table createTable(long initial_seqno) { - return new Table(xmit_table_num_rows, xmit_table_msgs_per_row, - initial_seqno, xmit_table_resize_factor, xmit_table_max_compaction_time); - } - - - - /** - * Garbage collect messages that have been seen by all members. Update sent_msgs: for the sender P in the digest - * which is equal to the local address, garbage collect all messages <= seqno at digest[P]. Update xmit_table: - * for each sender P in the digest and its highest seqno seen SEQ, garbage collect all delivered_msgs in the - * retransmit buffer corresponding to P which are <= seqno at digest[P]. - */ - protected void stable(Digest digest) { - if(members == null || local_addr == null || digest == null) - return; - - log.trace("%s: received stable digest %s", local_addr, digest); - stability_msgs.add(digest.toString()); - - for(Digest.Entry entry: digest) { - Address member=entry.getMember(); - if(member == null) - continue; - long hd=entry.getHighestDeliveredSeqno(); - long hr=entry.getHighestReceivedSeqno(); - - // check whether the last seqno received for a sender P in the stability digest is > last seqno - // received for P in my digest. if yes, request retransmission (see "Last Message Dropped" topic in DESIGN) - Table buf=xmit_table.get(member); - if(buf != null) { - long my_hr=buf.getHighestReceived(); - if(hr >= 0 && hr > my_hr) { - log.trace("%s: my_highest_rcvd (%) < stability_highest_rcvd (%): requesting retransmission of %s", - local_addr, my_hr, hr, member + "#" + hr); - retransmit(hr, hr, member); - } - } - - // delete *delivered* msgs that are stable (all messages with seqnos <= seqno) - if(hd >= 0 && buf != null) { - log.trace("%s: deleting msgs <= %s from %s", local_addr, hd, member); - buf.purge(hd); - } - } - } - - - protected void retransmit(long first_seqno, long last_seqno, Address sender) { - if(first_seqno <= last_seqno) - retransmit(first_seqno,last_seqno,sender,false); - } - - - - protected void retransmit(long first_seqno, long last_seqno, final Address sender, boolean multicast_xmit_request) { - retransmit(new SeqnoList(first_seqno,last_seqno),sender,multicast_xmit_request); - } - - protected void retransmit(SeqnoList missing_msgs, final Address sender, boolean multicast_xmit_request) { - Address dest=(multicast_xmit_request || this.use_mcast_xmit_req)? null : sender; // to whom do we send the XMIT request ? - - if(xmit_from_random_member && !local_addr.equals(sender)) { - Address random_member=Util.pickRandomElement(members); - if(random_member != null && !local_addr.equals(random_member)) - dest=random_member; - } - - Message retransmit_msg=new Message(dest, missing_msgs).setFlag(Message.Flag.OOB, Message.Flag.INTERNAL) - .putHeader(this.id, NakAckHeader2.createXmitRequestHeader(sender)); - - log.trace("%s: sending XMIT_REQ (%s) to %s", local_addr, missing_msgs, dest); - down_prot.down(new Event(Event.MSG, retransmit_msg)); - if(stats) - xmit_reqs_sent.addAndGet(missing_msgs.size()); - } - - - protected void reset() { - seqno.set(0); - xmit_table.clear(); - } - - - - protected static long sizeOfAllMessages(Table buf, boolean include_headers) { - Counter counter=new Counter(include_headers); - buf.forEach(buf.getHighestDelivered() + 1,buf.getHighestReceived(),counter); - return counter.getResult(); - } - - protected void startRetransmitTask() { - if(xmit_task == null || xmit_task.isDone()) - xmit_task=timer.scheduleWithFixedDelay(new RetransmitTask(), 0, xmit_interval, TimeUnit.MILLISECONDS); - } - - protected void stopRetransmitTask() { - if(xmit_task != null) { - xmit_task.cancel(true); - xmit_task=null; - } - } - - - - /** - * Retransmitter task which periodically (every xmit_interval ms) looks at all the retransmit tables and - * sends retransmit request to all members from which we have missing messages - */ - protected class RetransmitTask implements Runnable { - public void run() { - triggerXmit(); - } - - public String toString() { - return NAKACK2.class.getSimpleName() + ": RetransmitTask (interval=" + xmit_interval + " ms)"; - } - } - - @ManagedOperation(description="Triggers the retransmission task, asking all senders for missing messages") - public void triggerXmit() { - SeqnoList missing; - - for(Map.Entry> entry: xmit_table.entrySet()) { - Address target=entry.getKey(); // target to send retransmit requests to - Table buf=entry.getValue(); - - if(buf != null && buf.getNumMissing() > 0 && (missing=buf.getMissing()) != null) { // getNumMissing() is fast - long highest=missing.getLast(); - Long prev_seqno=xmit_task_map.get(target); - if(prev_seqno == null) { - xmit_task_map.put(target, highest); // no retransmission - } - else { - missing.removeHigherThan(prev_seqno); // we only retransmit the 'previous batch' - if(highest > prev_seqno) - xmit_task_map.put(target, highest); - if(missing.size() > 0) - retransmit(missing, target, false); - } - } - else if(!xmit_task_map.isEmpty()) - xmit_task_map.remove(target); // no current gaps for target - } - } - - - - - protected static class Counter implements Table.Visitor { - protected final boolean count_size; // use size() or length() - protected long result=0; - - public Counter(boolean count_size) { - this.count_size=count_size; - } - - public long getResult() {return result;} - - public boolean visit(long seqno, Message element, int row, int column) { - if(element != null) - result+=count_size? element.size() : element.getLength(); - return true; - } - } - - - -} diff --git a/All/Genesis-NP/Genesis#235/pair.info b/All/Genesis-NP/Genesis#235/pair.info deleted file mode 100755 index aa8ea6a..0000000 --- a/All/Genesis-NP/Genesis#235/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:235 -SATName:Genesis -modifiedFPath:src/org/jgroups/protocols/pbcast/NAKACK2.java -comSha:bd0b8479b59414a854234205d128b85a613b9b04 -parentComSha:bd0b8479b59414a854234205d128b85a613b9b04^1 -githubUrl:https://github.com/belaban/JGroups -repoName:belaban#JGroups \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#237/comMsg.txt b/All/Genesis-NP/Genesis#237/comMsg.txt deleted file mode 100755 index beb35c2..0000000 --- a/All/Genesis-NP/Genesis#237/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE when listener is not set diff --git a/All/Genesis-NP/Genesis#237/diff.diff b/All/Genesis-NP/Genesis#237/diff.diff deleted file mode 100755 index e26dd7d..0000000 --- a/All/Genesis-NP/Genesis#237/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/org/jgroups/protocols/relay/Relayer.java b/src/org/jgroups/protocols/relay/Relayer.java -index 3418d91..62bed31 100644 ---- a/src/org/jgroups/protocols/relay/Relayer.java -+++ b/src/org/jgroups/protocols/relay/Relayer.java -@@ -287,0 +288 @@ public class Relayer { -+ if(up != null) -@@ -307,0 +309 @@ public class Relayer { -+ if(listener != null) { -@@ -311,0 +314 @@ public class Relayer { -+ } diff --git a/All/Genesis-NP/Genesis#237/new/Relayer.java b/All/Genesis-NP/Genesis#237/new/Relayer.java deleted file mode 100755 index 62bed31..0000000 --- a/All/Genesis-NP/Genesis#237/new/Relayer.java +++ /dev/null @@ -1,349 +0,0 @@ -package org.jgroups.protocols.relay; - -import org.jgroups.*; -import org.jgroups.logging.Log; -import org.jgroups.protocols.relay.config.RelayConfig; -import org.jgroups.stack.AddressGenerator; -import org.jgroups.util.UUID; -import org.jgroups.util.Util; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ConcurrentMap; - -/** - * Maintains bridges and routing table. Does the routing of outgoing messages and dispatches incoming messages to - * the right members.

- * A Relayer cannot be reused once it is stopped, but a new Relayer instance must be created. - * @author Bela Ban - * @since 3.2 - */ -public class Relayer { - /** The routing table. Site IDs are the keys (e.g. "sfo", and list of routes are the values */ - protected ConcurrentMap> routes=new ConcurrentHashMap>(5); - - /** The bridges which are used to connect to different sites */ - protected final Queue bridges=new ConcurrentLinkedQueue(); - - protected final Log log; - - protected final RELAY2 relay; - - /** Flag set when stop() is called. Since a Relayer should not be used after stop() has been called, a new - * instance needs to be created */ - protected volatile boolean done; - - protected boolean stats; - - // Used to store messages for a site with status UNKNOWN. Messages will be flushed when the status changes to UP, or - // a SITE-UNREACHABLE message will be sent to each member *once* when the status changes to DOWN - // protected final ConcurrentMap> fwd_queue=new ConcurrentHashMap>(); - -// /** Map to store tasks which set the status of a site from UNKNOWN to DOWN. These are started when a site is -// * set to UNKNOWN, but they need to be cancelled when the status goes from UNKNOWN back to UP before -// * they kick in.*/ -// protected final ConcurrentMap> down_tasks=new ConcurrentHashMap>(); -// - - - public Relayer(RELAY2 relay, Log log) { - this.relay=relay; - this.stats=relay.statsEnabled(); - this.log=log; - } - - - public boolean done() {return done;} - - - /** - * Creates all bridges from site_config and connects them (joining the bridge clusters) - * @param bridge_configs A list of bridge configurations - * @param bridge_name The name of the local bridge channel, prefixed with '_'. - * @param my_site_id The ID of this site - * @throws Throwable - */ - public void start(List bridge_configs, String bridge_name, final String my_site_id) - throws Throwable { - if(done) { - if(log.isTraceEnabled()) - log.trace(relay.getLocalAddress() + ": will not start the Relayer as stop() has been called"); - return; - } - try { - for(RelayConfig.BridgeConfig bridge_config: bridge_configs) { - Bridge bridge=new Bridge(bridge_config.createChannel(), bridge_config.getClusterName(), bridge_name, - new AddressGenerator() { - public Address generateAddress() { - UUID uuid=UUID.randomUUID(); - return new SiteUUID(uuid, null, my_site_id); - } - }); - bridges.add(bridge); - } - for(Bridge bridge: bridges) - bridge.start(); - } - catch(Throwable t) { - stop(); - throw t; - } - finally { - if(done) { - if(log.isTraceEnabled()) - log.trace(relay.getLocalAddress() + ": stop() was called while starting the relayer; stopping the relayer now"); - stop(); - } - } - } - - - - /** - * Disconnects and destroys all bridges - */ - public void stop() { - done=true; - for(Bridge bridge: bridges) - bridge.stop(); - bridges.clear(); - } - - - public synchronized String printRoutes() { - StringBuilder sb=new StringBuilder(); - for(Map.Entry> entry: routes.entrySet()) { - List list=entry.getValue(); - if(list != null && !list.isEmpty()) - sb.append(entry.getKey() + " --> ").append(Util.print(list)).append("\n"); - } - return sb.toString(); - } - - - - /** - * Grabs a random route - * @param site - * @return - */ - protected synchronized Route getRoute(String site) { - List list=routes.get(site); - return list == null? null : Util.pickRandomElement(list); - } - - protected List getSiteNames() { - return new ArrayList(routes.keySet()); - } - - protected synchronized List getRoutes(String ... excluded_sites) { - List retval=new ArrayList(routes.size()); - for(List list: routes.values()) { - for(Route route: list) { - if(route != null) { - if(!isExcluded(route, excluded_sites)) { - retval.add(route); - break; - } - } - } - } - return retval; - } - - protected View getBridgeView(String cluster_name) { - if(cluster_name == null || bridges == null) - return null; - for(Bridge bridge: bridges) { - if(bridge.cluster_name != null && bridge.cluster_name.equals(cluster_name)) - return bridge.view; - } - return null; - } - - protected static boolean isExcluded(Route route, String... excluded_sites) { - if(excluded_sites == null) - return false; - String site=((SiteUUID)route.site_master).getSite(); - for(String excluded_site: excluded_sites) - if(site.equals(excluded_site)) - return true; - return false; - } - - - - - /** - * Includes information about the site master of the route and the channel to be used - */ - public class Route implements Comparable { - /** SiteUUID: address of the site master */ - protected final Address site_master; - protected final JChannel bridge; - - public Route(Address site_master, JChannel bridge) { - this.site_master=site_master; - this.bridge=bridge; - } - - public JChannel bridge() {return bridge;} - public Address siteMaster() {return site_master;} - - public void send(Address final_destination, Address original_sender, final Message msg) { - if(log.isTraceEnabled()) - log.trace("routing message to " + final_destination + " via " + site_master); - long start=stats? System.nanoTime() : 0; - try { - Message copy=createMessage(site_master, final_destination, original_sender, msg); - bridge.send(copy); - if(stats) { - relay.addToRelayedTime(System.nanoTime() - start); - relay.incrementRelayed(); - } - } - catch(Exception e) { - log.error("failure relaying message", e); - } - } - - public int compareTo(Route o) { - return site_master.compareTo(o.siteMaster()); - } - - public boolean equals(Object obj) { - return compareTo((Route)obj) == 0; - } - - public int hashCode() { - return site_master.hashCode(); - } - - public String toString() { - return (site_master != null? site_master.toString() : ""); - } - - protected Message createMessage(Address target, Address final_destination, Address original_sender, final Message msg) { - Message copy=relay.copy(msg).dest(target).src(null); - RELAY2.Relay2Header hdr=new RELAY2.Relay2Header(RELAY2.Relay2Header.DATA, final_destination, original_sender); - copy.putHeader(relay.getId(), hdr); - return copy; - } - } - - - protected class Bridge extends ReceiverAdapter { - protected JChannel channel; - protected final String cluster_name; - protected View view; - - protected Bridge(final JChannel ch, final String cluster_name, String channel_name, AddressGenerator addr_generator) throws Exception { - this.channel=ch; - channel.setName(channel_name); - channel.setReceiver(this); - channel.setAddressGenerator(addr_generator); - this.cluster_name=cluster_name; - } - - protected void start() throws Exception { - channel.connect(cluster_name); - } - - protected void stop() { - Util.close(channel); - } - - public void receive(Message msg) { - RELAY2.Relay2Header hdr=(RELAY2.Relay2Header)msg.getHeader(relay.getId()); - if(hdr == null) { - log.warn("received a message without a relay header; discarding it"); - return; - } - relay.handleRelayMessage(hdr, msg); - } - - /** The view contains a list of SiteUUIDs. Adjust the routing table based on the SiteUUIDs UUID and site - */ - public void viewAccepted(View new_view) { - this.view=new_view; - if(log.isTraceEnabled()) - log.trace("[Relayer " + channel.getAddress() + "] view: " + new_view); - - RouteStatusListener listener=relay.getRouteStatusListener(); - Map> tmp=extract(new_view); - Set down=listener != null? new HashSet(routes.keySet()) : null; - Set up=listener != null? new HashSet() : null; - - if(listener != null) - down.removeAll(tmp.keySet()); - - routes.keySet().retainAll(tmp.keySet()); // remove all sites which are not in the view - - for(Map.Entry> entry: tmp.entrySet()) { - String key=entry.getKey(); - List

val=entry.getValue(); - if(!routes.containsKey(key)) { - routes.put(key, new ArrayList()); - if(up != null) - up.add(key); - } - - List list=routes.get(key); - - // Remove routes not in the view anymore: - for(Iterator it=list.iterator(); it.hasNext();) { - Route route=it.next(); - if(!val.contains(route.siteMaster())) - it.remove(); - } - - // Add routes that aren't yet in the routing table: - for(Address addr: val) { - if(!contains(list, addr)) - list.add(new Route(addr, channel)); - } - - if(list.isEmpty()) { - routes.remove(key); - if(listener != null) { - down.add(key); - up.remove(key); - } - } - } - - if(listener != null) { - if(!down.isEmpty()) - listener.sitesDown(down.toArray(new String[down.size()])); - if(!up.isEmpty()) - listener.sitesUp(up.toArray(new String[up.size()])); - } - } - - protected boolean contains(List routes, Address addr) { - for(Route route: routes) { - if(route.siteMaster().equals(addr)) - return true; - } - return false; - } - - /** Returns a map containing the site keys and addresses as values */ - protected Map> extract(View view) { - Map> map=new HashMap>(view.size()); - for(Address mbr: view) { - SiteAddress member=(SiteAddress)mbr; - String key=member.getSite(); - List
list=map.get(key); - if(list == null) { - list=new ArrayList
(); - map.put(key, list); - } - if(!list.contains(member)) - list.add(member); - } - return map; - } - } -} diff --git a/All/Genesis-NP/Genesis#237/old/Relayer.java b/All/Genesis-NP/Genesis#237/old/Relayer.java deleted file mode 100755 index 3418d91..0000000 --- a/All/Genesis-NP/Genesis#237/old/Relayer.java +++ /dev/null @@ -1,346 +0,0 @@ -package org.jgroups.protocols.relay; - -import org.jgroups.*; -import org.jgroups.logging.Log; -import org.jgroups.protocols.relay.config.RelayConfig; -import org.jgroups.stack.AddressGenerator; -import org.jgroups.util.UUID; -import org.jgroups.util.Util; - -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.ConcurrentMap; - -/** - * Maintains bridges and routing table. Does the routing of outgoing messages and dispatches incoming messages to - * the right members.

- * A Relayer cannot be reused once it is stopped, but a new Relayer instance must be created. - * @author Bela Ban - * @since 3.2 - */ -public class Relayer { - /** The routing table. Site IDs are the keys (e.g. "sfo", and list of routes are the values */ - protected ConcurrentMap> routes=new ConcurrentHashMap>(5); - - /** The bridges which are used to connect to different sites */ - protected final Queue bridges=new ConcurrentLinkedQueue(); - - protected final Log log; - - protected final RELAY2 relay; - - /** Flag set when stop() is called. Since a Relayer should not be used after stop() has been called, a new - * instance needs to be created */ - protected volatile boolean done; - - protected boolean stats; - - // Used to store messages for a site with status UNKNOWN. Messages will be flushed when the status changes to UP, or - // a SITE-UNREACHABLE message will be sent to each member *once* when the status changes to DOWN - // protected final ConcurrentMap> fwd_queue=new ConcurrentHashMap>(); - -// /** Map to store tasks which set the status of a site from UNKNOWN to DOWN. These are started when a site is -// * set to UNKNOWN, but they need to be cancelled when the status goes from UNKNOWN back to UP before -// * they kick in.*/ -// protected final ConcurrentMap> down_tasks=new ConcurrentHashMap>(); -// - - - public Relayer(RELAY2 relay, Log log) { - this.relay=relay; - this.stats=relay.statsEnabled(); - this.log=log; - } - - - public boolean done() {return done;} - - - /** - * Creates all bridges from site_config and connects them (joining the bridge clusters) - * @param bridge_configs A list of bridge configurations - * @param bridge_name The name of the local bridge channel, prefixed with '_'. - * @param my_site_id The ID of this site - * @throws Throwable - */ - public void start(List bridge_configs, String bridge_name, final String my_site_id) - throws Throwable { - if(done) { - if(log.isTraceEnabled()) - log.trace(relay.getLocalAddress() + ": will not start the Relayer as stop() has been called"); - return; - } - try { - for(RelayConfig.BridgeConfig bridge_config: bridge_configs) { - Bridge bridge=new Bridge(bridge_config.createChannel(), bridge_config.getClusterName(), bridge_name, - new AddressGenerator() { - public Address generateAddress() { - UUID uuid=UUID.randomUUID(); - return new SiteUUID(uuid, null, my_site_id); - } - }); - bridges.add(bridge); - } - for(Bridge bridge: bridges) - bridge.start(); - } - catch(Throwable t) { - stop(); - throw t; - } - finally { - if(done) { - if(log.isTraceEnabled()) - log.trace(relay.getLocalAddress() + ": stop() was called while starting the relayer; stopping the relayer now"); - stop(); - } - } - } - - - - /** - * Disconnects and destroys all bridges - */ - public void stop() { - done=true; - for(Bridge bridge: bridges) - bridge.stop(); - bridges.clear(); - } - - - public synchronized String printRoutes() { - StringBuilder sb=new StringBuilder(); - for(Map.Entry> entry: routes.entrySet()) { - List list=entry.getValue(); - if(list != null && !list.isEmpty()) - sb.append(entry.getKey() + " --> ").append(Util.print(list)).append("\n"); - } - return sb.toString(); - } - - - - /** - * Grabs a random route - * @param site - * @return - */ - protected synchronized Route getRoute(String site) { - List list=routes.get(site); - return list == null? null : Util.pickRandomElement(list); - } - - protected List getSiteNames() { - return new ArrayList(routes.keySet()); - } - - protected synchronized List getRoutes(String ... excluded_sites) { - List retval=new ArrayList(routes.size()); - for(List list: routes.values()) { - for(Route route: list) { - if(route != null) { - if(!isExcluded(route, excluded_sites)) { - retval.add(route); - break; - } - } - } - } - return retval; - } - - protected View getBridgeView(String cluster_name) { - if(cluster_name == null || bridges == null) - return null; - for(Bridge bridge: bridges) { - if(bridge.cluster_name != null && bridge.cluster_name.equals(cluster_name)) - return bridge.view; - } - return null; - } - - protected static boolean isExcluded(Route route, String... excluded_sites) { - if(excluded_sites == null) - return false; - String site=((SiteUUID)route.site_master).getSite(); - for(String excluded_site: excluded_sites) - if(site.equals(excluded_site)) - return true; - return false; - } - - - - - /** - * Includes information about the site master of the route and the channel to be used - */ - public class Route implements Comparable { - /** SiteUUID: address of the site master */ - protected final Address site_master; - protected final JChannel bridge; - - public Route(Address site_master, JChannel bridge) { - this.site_master=site_master; - this.bridge=bridge; - } - - public JChannel bridge() {return bridge;} - public Address siteMaster() {return site_master;} - - public void send(Address final_destination, Address original_sender, final Message msg) { - if(log.isTraceEnabled()) - log.trace("routing message to " + final_destination + " via " + site_master); - long start=stats? System.nanoTime() : 0; - try { - Message copy=createMessage(site_master, final_destination, original_sender, msg); - bridge.send(copy); - if(stats) { - relay.addToRelayedTime(System.nanoTime() - start); - relay.incrementRelayed(); - } - } - catch(Exception e) { - log.error("failure relaying message", e); - } - } - - public int compareTo(Route o) { - return site_master.compareTo(o.siteMaster()); - } - - public boolean equals(Object obj) { - return compareTo((Route)obj) == 0; - } - - public int hashCode() { - return site_master.hashCode(); - } - - public String toString() { - return (site_master != null? site_master.toString() : ""); - } - - protected Message createMessage(Address target, Address final_destination, Address original_sender, final Message msg) { - Message copy=relay.copy(msg).dest(target).src(null); - RELAY2.Relay2Header hdr=new RELAY2.Relay2Header(RELAY2.Relay2Header.DATA, final_destination, original_sender); - copy.putHeader(relay.getId(), hdr); - return copy; - } - } - - - protected class Bridge extends ReceiverAdapter { - protected JChannel channel; - protected final String cluster_name; - protected View view; - - protected Bridge(final JChannel ch, final String cluster_name, String channel_name, AddressGenerator addr_generator) throws Exception { - this.channel=ch; - channel.setName(channel_name); - channel.setReceiver(this); - channel.setAddressGenerator(addr_generator); - this.cluster_name=cluster_name; - } - - protected void start() throws Exception { - channel.connect(cluster_name); - } - - protected void stop() { - Util.close(channel); - } - - public void receive(Message msg) { - RELAY2.Relay2Header hdr=(RELAY2.Relay2Header)msg.getHeader(relay.getId()); - if(hdr == null) { - log.warn("received a message without a relay header; discarding it"); - return; - } - relay.handleRelayMessage(hdr, msg); - } - - /** The view contains a list of SiteUUIDs. Adjust the routing table based on the SiteUUIDs UUID and site - */ - public void viewAccepted(View new_view) { - this.view=new_view; - if(log.isTraceEnabled()) - log.trace("[Relayer " + channel.getAddress() + "] view: " + new_view); - - RouteStatusListener listener=relay.getRouteStatusListener(); - Map> tmp=extract(new_view); - Set down=listener != null? new HashSet(routes.keySet()) : null; - Set up=listener != null? new HashSet() : null; - - if(listener != null) - down.removeAll(tmp.keySet()); - - routes.keySet().retainAll(tmp.keySet()); // remove all sites which are not in the view - - for(Map.Entry> entry: tmp.entrySet()) { - String key=entry.getKey(); - List

val=entry.getValue(); - if(!routes.containsKey(key)) { - routes.put(key, new ArrayList()); - up.add(key); - } - - List list=routes.get(key); - - // Remove routes not in the view anymore: - for(Iterator it=list.iterator(); it.hasNext();) { - Route route=it.next(); - if(!val.contains(route.siteMaster())) - it.remove(); - } - - // Add routes that aren't yet in the routing table: - for(Address addr: val) { - if(!contains(list, addr)) - list.add(new Route(addr, channel)); - } - - if(list.isEmpty()) { - routes.remove(key); - down.add(key); - up.remove(key); - } - } - - if(listener != null) { - if(!down.isEmpty()) - listener.sitesDown(down.toArray(new String[down.size()])); - if(!up.isEmpty()) - listener.sitesUp(up.toArray(new String[up.size()])); - } - } - - protected boolean contains(List routes, Address addr) { - for(Route route: routes) { - if(route.siteMaster().equals(addr)) - return true; - } - return false; - } - - /** Returns a map containing the site keys and addresses as values */ - protected Map> extract(View view) { - Map> map=new HashMap>(view.size()); - for(Address mbr: view) { - SiteAddress member=(SiteAddress)mbr; - String key=member.getSite(); - List
list=map.get(key); - if(list == null) { - list=new ArrayList
(); - map.put(key, list); - } - if(!list.contains(member)) - list.add(member); - } - return map; - } - } -} diff --git a/All/Genesis-NP/Genesis#237/pair.info b/All/Genesis-NP/Genesis#237/pair.info deleted file mode 100755 index 16390e2..0000000 --- a/All/Genesis-NP/Genesis#237/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:237 -SATName:Genesis -modifiedFPath:src/org/jgroups/protocols/relay/Relayer.java -comSha:3bad93123117bdf3091dd12b3aae334bac22a6b3 -parentComSha:3bad93123117bdf3091dd12b3aae334bac22a6b3^1 -githubUrl:https://github.com/belaban/JGroups -repoName:belaban#JGroups \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#24/comMsg.txt b/All/Genesis-NP/Genesis#24/comMsg.txt deleted file mode 100755 index 4817e6b..0000000 --- a/All/Genesis-NP/Genesis#24/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix not to throw NPE if username or password is null diff --git a/All/Genesis-NP/Genesis#24/diff.diff b/All/Genesis-NP/Genesis#24/diff.diff deleted file mode 100755 index 0fd73ff..0000000 --- a/All/Genesis-NP/Genesis#24/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/hikaricp/src/main/java/com/zaxxer/hikari/HikariDataSource.java b/hikaricp/src/main/java/com/zaxxer/hikari/HikariDataSource.java -index f55aa0f..40319ab 100644 ---- a/hikaricp/src/main/java/com/zaxxer/hikari/HikariDataSource.java -+++ b/hikaricp/src/main/java/com/zaxxer/hikari/HikariDataSource.java -@@ -276 +276 @@ public class HikariDataSource extends HikariConfig implements DataSource, Closea -- else if (!username.equals(otherKey.username)) { -+ else if (username != otherKey.username) { -@@ -282 +282 @@ public class HikariDataSource extends HikariConfig implements DataSource, Closea -- else if (!password.equals(otherKey.password)) { -+ else if (password != otherKey.password) { diff --git a/All/Genesis-NP/Genesis#24/new/HikariDataSource.java b/All/Genesis-NP/Genesis#24/new/HikariDataSource.java deleted file mode 100755 index 40319ab..0000000 --- a/All/Genesis-NP/Genesis#24/new/HikariDataSource.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (C) 2013 Brett Wooldridge - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.zaxxer.hikari; - -import java.io.Closeable; -import java.io.PrintWriter; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.util.HashMap; - -import javax.sql.DataSource; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.zaxxer.hikari.pool.HikariPool; -import com.zaxxer.hikari.proxy.IHikariConnectionProxy; -import com.zaxxer.hikari.util.DriverDataSource; - -/** - * The HikariCP pooled DataSource. - * - * @author Brett Wooldridge - */ -public class HikariDataSource extends HikariConfig implements DataSource, Closeable -{ - private static final Logger LOGGER = LoggerFactory.getLogger(HikariDataSource.class); - - // We use a concrete HashMap rather than Map to avoid an invokeinterface callsite - private final HashMap multiPool; - - private volatile boolean isShutdown; - private int loginTimeout; - - /* Package scopped for testing */ - private final HikariPool fastPathPool; - private volatile HikariPool pool; - - /** - * Default constructor. Setters be used to configure the pool. Using - * this constructor vs. {@link #HikariDataSource(HikariConfig)} will - * result in {@link #getConnection()} performance that is slightly lower - * due to lazy initialization checks. - */ - public HikariDataSource() - { - super(); - fastPathPool = null; - multiPool = new HashMap(); - } - - /** - * Construct a HikariDataSource with the specified configuration. - * - * @param configuration a HikariConfig instance - */ - public HikariDataSource(HikariConfig configuration) - { - configuration.validate(); - configuration.copyState(this); - multiPool = new HashMap(); - - LOGGER.info("HikariCP pool {} is starting.", configuration.getPoolName()); - pool = fastPathPool = new HikariPool(this); - multiPool.put(new MultiPoolKey(getUsername(), getPassword()), pool); - } - - /** {@inheritDoc} */ - @Override - public Connection getConnection() throws SQLException - { - if (isShutdown) { - throw new SQLException("Pool has been shutdown"); - } - - if (fastPathPool != null) { - return fastPathPool.getConnection(); - } - - // See http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java - HikariPool result = pool; - if (result == null) { - synchronized (this) { - result = pool; - if (result == null) { - validate(); - LOGGER.info("HikariCP pool {} is starting.", getPoolName()); - pool = result = new HikariPool(this); - multiPool.put(new MultiPoolKey(getUsername(), getPassword()), pool); - } - } - } - - return result.getConnection(); - } - - /** {@inheritDoc} */ - @Override - public Connection getConnection(String username, String password) throws SQLException - { - if (isShutdown) { - throw new SQLException("Pool has been shutdown"); - } - - final MultiPoolKey key = new MultiPoolKey(username, password); - - HikariPool hikariPool; - synchronized (multiPool) { - hikariPool = multiPool.get(key); - if (hikariPool == null) { - hikariPool = new HikariPool(this, username, password); - multiPool.put(key, hikariPool); - } - } - - return hikariPool.getConnection(); - } - - /** {@inheritDoc} */ - @Override - public PrintWriter getLogWriter() throws SQLException - { - return (pool.getDataSource() != null ? pool.getDataSource().getLogWriter() : null); - } - - /** {@inheritDoc} */ - @Override - public void setLogWriter(PrintWriter out) throws SQLException - { - if (pool.getDataSource() != null) { - pool.getDataSource().setLogWriter(out); - } - } - - /** {@inheritDoc} */ - @Override - public void setLoginTimeout(int seconds) throws SQLException - { - this.loginTimeout = seconds; - } - - /** {@inheritDoc} */ - @Override - public int getLoginTimeout() throws SQLException - { - return loginTimeout; - } - - /** {@inheritDoc} */ - public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException - { - throw new SQLFeatureNotSupportedException(); - } - - /** {@inheritDoc} */ - @Override - @SuppressWarnings("unchecked") - public T unwrap(Class iface) throws SQLException - { - if (pool != null && iface.isInstance(pool.getDataSource())) { - return (T) pool.getDataSource(); - } - - throw new SQLException("Wrapped connection is not an instance of " + iface); - } - - /** {@inheritDoc} */ - @Override - public boolean isWrapperFor(Class iface) throws SQLException - { - return (pool != null && pool.getDataSource().getClass().isAssignableFrom(iface)); - } - - /** - * Evict a connection from the pool. Use caution using this method, if you - * evict the same connection more than one time, the internal pool accounting - * will become invalid and the pool may stop functioning. - * - * @param connection the connection to evict from the pool - */ - public void evictConnection(Connection connection) - { - if (!isShutdown && pool != null && connection instanceof IHikariConnectionProxy) { - pool.closeConnection((IHikariConnectionProxy) connection); - } - } - - /** - * close() and shutdown() are synonymous. - */ - public void close() - { - shutdown(); - } - - /** - * Shutdown the DataSource and its associated pool. - */ - public void shutdown() - { - if (isShutdown) { - return; - } - - isShutdown = true; - - if (fastPathPool != null) { - shutdownHelper(fastPathPool); - } - - for (HikariPool hikariPool : multiPool.values()) { - shutdownHelper(hikariPool); - } - } - - /** {@inheritDoc} */ - @Override - public String toString() - { - return String.format("HikariDataSource (%s)", pool); - } - - private void shutdownHelper(HikariPool hPool) - { - try { - hPool.shutdown(); - } - catch (InterruptedException e) { - LoggerFactory.getLogger(getClass()).warn("Interrupted during shutdown", e); - } - - if (hPool.getDataSource() instanceof DriverDataSource) { - ((DriverDataSource) hPool.getDataSource()).shutdown(); - } - } - - private static class MultiPoolKey - { - private String username; - private String password; - - MultiPoolKey(String username, String password) - { - this.username = username; - this.password = password; - } - - @Override - public int hashCode() - { - return (password == null ? 0 : password.hashCode()); - } - - @Override - public boolean equals(Object obj) - { - MultiPoolKey otherKey = ((MultiPoolKey) obj); - if (username != null && !username.equals(otherKey.username)) { - return false; - } - else if (username != otherKey.username) { - return false; - } - else if (password != null && !password.equals(otherKey.password)) { - return false; - } - else if (password != otherKey.password) { - return false; - } - - return true; - } - } -} diff --git a/All/Genesis-NP/Genesis#24/old/HikariDataSource.java b/All/Genesis-NP/Genesis#24/old/HikariDataSource.java deleted file mode 100755 index f55aa0f..0000000 --- a/All/Genesis-NP/Genesis#24/old/HikariDataSource.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright (C) 2013 Brett Wooldridge - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.zaxxer.hikari; - -import java.io.Closeable; -import java.io.PrintWriter; -import java.sql.Connection; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.util.HashMap; - -import javax.sql.DataSource; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.zaxxer.hikari.pool.HikariPool; -import com.zaxxer.hikari.proxy.IHikariConnectionProxy; -import com.zaxxer.hikari.util.DriverDataSource; - -/** - * The HikariCP pooled DataSource. - * - * @author Brett Wooldridge - */ -public class HikariDataSource extends HikariConfig implements DataSource, Closeable -{ - private static final Logger LOGGER = LoggerFactory.getLogger(HikariDataSource.class); - - // We use a concrete HashMap rather than Map to avoid an invokeinterface callsite - private final HashMap multiPool; - - private volatile boolean isShutdown; - private int loginTimeout; - - /* Package scopped for testing */ - private final HikariPool fastPathPool; - private volatile HikariPool pool; - - /** - * Default constructor. Setters be used to configure the pool. Using - * this constructor vs. {@link #HikariDataSource(HikariConfig)} will - * result in {@link #getConnection()} performance that is slightly lower - * due to lazy initialization checks. - */ - public HikariDataSource() - { - super(); - fastPathPool = null; - multiPool = new HashMap(); - } - - /** - * Construct a HikariDataSource with the specified configuration. - * - * @param configuration a HikariConfig instance - */ - public HikariDataSource(HikariConfig configuration) - { - configuration.validate(); - configuration.copyState(this); - multiPool = new HashMap(); - - LOGGER.info("HikariCP pool {} is starting.", configuration.getPoolName()); - pool = fastPathPool = new HikariPool(this); - multiPool.put(new MultiPoolKey(getUsername(), getPassword()), pool); - } - - /** {@inheritDoc} */ - @Override - public Connection getConnection() throws SQLException - { - if (isShutdown) { - throw new SQLException("Pool has been shutdown"); - } - - if (fastPathPool != null) { - return fastPathPool.getConnection(); - } - - // See http://en.wikipedia.org/wiki/Double-checked_locking#Usage_in_Java - HikariPool result = pool; - if (result == null) { - synchronized (this) { - result = pool; - if (result == null) { - validate(); - LOGGER.info("HikariCP pool {} is starting.", getPoolName()); - pool = result = new HikariPool(this); - multiPool.put(new MultiPoolKey(getUsername(), getPassword()), pool); - } - } - } - - return result.getConnection(); - } - - /** {@inheritDoc} */ - @Override - public Connection getConnection(String username, String password) throws SQLException - { - if (isShutdown) { - throw new SQLException("Pool has been shutdown"); - } - - final MultiPoolKey key = new MultiPoolKey(username, password); - - HikariPool hikariPool; - synchronized (multiPool) { - hikariPool = multiPool.get(key); - if (hikariPool == null) { - hikariPool = new HikariPool(this, username, password); - multiPool.put(key, hikariPool); - } - } - - return hikariPool.getConnection(); - } - - /** {@inheritDoc} */ - @Override - public PrintWriter getLogWriter() throws SQLException - { - return (pool.getDataSource() != null ? pool.getDataSource().getLogWriter() : null); - } - - /** {@inheritDoc} */ - @Override - public void setLogWriter(PrintWriter out) throws SQLException - { - if (pool.getDataSource() != null) { - pool.getDataSource().setLogWriter(out); - } - } - - /** {@inheritDoc} */ - @Override - public void setLoginTimeout(int seconds) throws SQLException - { - this.loginTimeout = seconds; - } - - /** {@inheritDoc} */ - @Override - public int getLoginTimeout() throws SQLException - { - return loginTimeout; - } - - /** {@inheritDoc} */ - public java.util.logging.Logger getParentLogger() throws SQLFeatureNotSupportedException - { - throw new SQLFeatureNotSupportedException(); - } - - /** {@inheritDoc} */ - @Override - @SuppressWarnings("unchecked") - public T unwrap(Class iface) throws SQLException - { - if (pool != null && iface.isInstance(pool.getDataSource())) { - return (T) pool.getDataSource(); - } - - throw new SQLException("Wrapped connection is not an instance of " + iface); - } - - /** {@inheritDoc} */ - @Override - public boolean isWrapperFor(Class iface) throws SQLException - { - return (pool != null && pool.getDataSource().getClass().isAssignableFrom(iface)); - } - - /** - * Evict a connection from the pool. Use caution using this method, if you - * evict the same connection more than one time, the internal pool accounting - * will become invalid and the pool may stop functioning. - * - * @param connection the connection to evict from the pool - */ - public void evictConnection(Connection connection) - { - if (!isShutdown && pool != null && connection instanceof IHikariConnectionProxy) { - pool.closeConnection((IHikariConnectionProxy) connection); - } - } - - /** - * close() and shutdown() are synonymous. - */ - public void close() - { - shutdown(); - } - - /** - * Shutdown the DataSource and its associated pool. - */ - public void shutdown() - { - if (isShutdown) { - return; - } - - isShutdown = true; - - if (fastPathPool != null) { - shutdownHelper(fastPathPool); - } - - for (HikariPool hikariPool : multiPool.values()) { - shutdownHelper(hikariPool); - } - } - - /** {@inheritDoc} */ - @Override - public String toString() - { - return String.format("HikariDataSource (%s)", pool); - } - - private void shutdownHelper(HikariPool hPool) - { - try { - hPool.shutdown(); - } - catch (InterruptedException e) { - LoggerFactory.getLogger(getClass()).warn("Interrupted during shutdown", e); - } - - if (hPool.getDataSource() instanceof DriverDataSource) { - ((DriverDataSource) hPool.getDataSource()).shutdown(); - } - } - - private static class MultiPoolKey - { - private String username; - private String password; - - MultiPoolKey(String username, String password) - { - this.username = username; - this.password = password; - } - - @Override - public int hashCode() - { - return (password == null ? 0 : password.hashCode()); - } - - @Override - public boolean equals(Object obj) - { - MultiPoolKey otherKey = ((MultiPoolKey) obj); - if (username != null && !username.equals(otherKey.username)) { - return false; - } - else if (!username.equals(otherKey.username)) { - return false; - } - else if (password != null && !password.equals(otherKey.password)) { - return false; - } - else if (!password.equals(otherKey.password)) { - return false; - } - - return true; - } - } -} diff --git a/All/Genesis-NP/Genesis#24/pair.info b/All/Genesis-NP/Genesis#24/pair.info deleted file mode 100755 index 3a49727..0000000 --- a/All/Genesis-NP/Genesis#24/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:24 -SATName:Genesis -modifiedFPath:hikaricp/src/main/java/com/zaxxer/hikari/HikariDataSource.java -comSha:d1138e6e5f75f9358be6d00a96dbb94b840c5c81 -parentComSha:d1138e6e5f75f9358be6d00a96dbb94b840c5c81^1 -githubUrl:https://github.com/brettwooldridge/HikariCP -repoName:brettwooldridge#HikariCP \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#253/comMsg.txt b/All/Genesis-NP/Genesis#253/comMsg.txt deleted file mode 100755 index 87e2a16..0000000 --- a/All/Genesis-NP/Genesis#253/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Using fixed reflection instantiation to avoid NPE when using Objenesis. Closes #583 diff --git a/All/Genesis-NP/Genesis#253/diff.diff b/All/Genesis-NP/Genesis#253/diff.diff deleted file mode 100755 index 51baf96..0000000 --- a/All/Genesis-NP/Genesis#253/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/vraptor-core/src/main/java/br/com/caelum/vraptor/validator/DIConstraintValidatorFactory.java b/vraptor-core/src/main/java/br/com/caelum/vraptor/validator/DIConstraintValidatorFactory.java -index 168ea22..8ab04f8 100644 ---- a/vraptor-core/src/main/java/br/com/caelum/vraptor/validator/DIConstraintValidatorFactory.java -+++ b/vraptor-core/src/main/java/br/com/caelum/vraptor/validator/DIConstraintValidatorFactory.java -@@ -11 +11 @@ import br.com.caelum.vraptor.ioc.Container; --import br.com.caelum.vraptor.proxy.InstanceCreator; -+import br.com.caelum.vraptor.proxy.ReflectionInstanceCreator; -@@ -36 +36,2 @@ public class DIConstraintValidatorFactory -- return container.instanceFor(InstanceCreator.class).instanceFor(key); -+ // GH583 - we need to use reflection to instantiate constraints -+ return container.instanceFor(ReflectionInstanceCreator.class).instanceFor(key); diff --git a/All/Genesis-NP/Genesis#253/new/DIConstraintValidatorFactory.java b/All/Genesis-NP/Genesis#253/new/DIConstraintValidatorFactory.java deleted file mode 100755 index 8ab04f8..0000000 --- a/All/Genesis-NP/Genesis#253/new/DIConstraintValidatorFactory.java +++ /dev/null @@ -1,43 +0,0 @@ -package br.com.caelum.vraptor.validator; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ioc.ApplicationScoped; -import br.com.caelum.vraptor.ioc.Container; -import br.com.caelum.vraptor.proxy.ReflectionInstanceCreator; - -/** - * Create a custom {@link ConstraintValidatorFactory} to allow users to use constraints that uses components. - * - * @author Otávio Scherer Garcia - * @since 3.5.2 - */ -@ApplicationScoped -public class DIConstraintValidatorFactory - implements ConstraintValidatorFactory { - - private static final Logger logger = LoggerFactory.getLogger(DIConstraintValidatorFactory.class); - private final Container container; - - public DIConstraintValidatorFactory(Container container) { - this.container = container; - } - - public > T getInstance(Class key) { - if (container.canProvide(key)) { - logger.debug("we can provide instance for ConstraintValidator {}", key); - return container.instanceFor(key); - } - - // GH583 - we need to use reflection to instantiate constraints - return container.instanceFor(ReflectionInstanceCreator.class).instanceFor(key); - } - - public void releaseInstance(ConstraintValidator key) { - // we don't need this - } -} diff --git a/All/Genesis-NP/Genesis#253/old/DIConstraintValidatorFactory.java b/All/Genesis-NP/Genesis#253/old/DIConstraintValidatorFactory.java deleted file mode 100755 index 168ea22..0000000 --- a/All/Genesis-NP/Genesis#253/old/DIConstraintValidatorFactory.java +++ /dev/null @@ -1,42 +0,0 @@ -package br.com.caelum.vraptor.validator; - -import javax.validation.ConstraintValidator; -import javax.validation.ConstraintValidatorFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import br.com.caelum.vraptor.ioc.ApplicationScoped; -import br.com.caelum.vraptor.ioc.Container; -import br.com.caelum.vraptor.proxy.InstanceCreator; - -/** - * Create a custom {@link ConstraintValidatorFactory} to allow users to use constraints that uses components. - * - * @author Otávio Scherer Garcia - * @since 3.5.2 - */ -@ApplicationScoped -public class DIConstraintValidatorFactory - implements ConstraintValidatorFactory { - - private static final Logger logger = LoggerFactory.getLogger(DIConstraintValidatorFactory.class); - private final Container container; - - public DIConstraintValidatorFactory(Container container) { - this.container = container; - } - - public > T getInstance(Class key) { - if (container.canProvide(key)) { - logger.debug("we can provide instance for ConstraintValidator {}", key); - return container.instanceFor(key); - } - - return container.instanceFor(InstanceCreator.class).instanceFor(key); - } - - public void releaseInstance(ConstraintValidator key) { - // we don't need this - } -} diff --git a/All/Genesis-NP/Genesis#253/pair.info b/All/Genesis-NP/Genesis#253/pair.info deleted file mode 100755 index c1d79d2..0000000 --- a/All/Genesis-NP/Genesis#253/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:253 -SATName:Genesis -modifiedFPath:vraptor-core/src/main/java/br/com/caelum/vraptor/validator/DIConstraintValidatorFactory.java -comSha:18d0d4a3cb6efb1d345a03040cd53a72f8971fd3 -parentComSha:18d0d4a3cb6efb1d345a03040cd53a72f8971fd3^1 -githubUrl:https://github.com/caelum/vraptor -repoName:caelum#vraptor \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#258/comMsg.txt b/All/Genesis-NP/Genesis#258/comMsg.txt deleted file mode 100755 index 715fb46..0000000 --- a/All/Genesis-NP/Genesis#258/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix NPE in join-query compilation when using salted tables diff --git a/All/Genesis-NP/Genesis#258/diff.diff b/All/Genesis-NP/Genesis#258/diff.diff deleted file mode 100755 index 0c6add4..0000000 --- a/All/Genesis-NP/Genesis#258/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/com/salesforce/phoenix/compile/JoinCompiler.java b/src/main/java/com/salesforce/phoenix/compile/JoinCompiler.java -index 00ad54d..f9c4317 100644 ---- a/src/main/java/com/salesforce/phoenix/compile/JoinCompiler.java -+++ b/src/main/java/com/salesforce/phoenix/compile/JoinCompiler.java -@@ -29,0 +30,2 @@ package com.salesforce.phoenix.compile; -+import static com.salesforce.phoenix.schema.SaltingUtil.SALTING_COLUMN; -+ -@@ -280,0 +283,3 @@ public class JoinCompiler { -+ if (sourceColumn == SALTING_COLUMN) -+ return; -+ diff --git a/All/Genesis-NP/Genesis#258/new/JoinCompiler.java b/All/Genesis-NP/Genesis#258/new/JoinCompiler.java deleted file mode 100755 index f9c4317..0000000 --- a/All/Genesis-NP/Genesis#258/new/JoinCompiler.java +++ /dev/null @@ -1,1096 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ -package com.salesforce.phoenix.compile; - -import static com.salesforce.phoenix.schema.SaltingUtil.SALTING_COLUMN; - -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.hadoop.hbase.client.Scan; -import org.apache.hadoop.hbase.util.Pair; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Lists; -import com.salesforce.phoenix.exception.SQLExceptionCode; -import com.salesforce.phoenix.exception.SQLExceptionInfo; -import com.salesforce.phoenix.expression.AndExpression; -import com.salesforce.phoenix.expression.CoerceExpression; -import com.salesforce.phoenix.expression.Expression; -import com.salesforce.phoenix.expression.LiteralExpression; -import com.salesforce.phoenix.jdbc.PhoenixStatement; -import com.salesforce.phoenix.join.ScanProjector; -import com.salesforce.phoenix.parse.AliasedNode; -import com.salesforce.phoenix.parse.AndParseNode; -import com.salesforce.phoenix.parse.BetweenParseNode; -import com.salesforce.phoenix.parse.BindTableNode; -import com.salesforce.phoenix.parse.CaseParseNode; -import com.salesforce.phoenix.parse.CastParseNode; -import com.salesforce.phoenix.parse.ColumnParseNode; -import com.salesforce.phoenix.parse.ComparisonParseNode; -import com.salesforce.phoenix.parse.ConcreteTableNode; -import com.salesforce.phoenix.parse.DerivedTableNode; -import com.salesforce.phoenix.parse.EqualParseNode; -import com.salesforce.phoenix.parse.FunctionParseNode; -import com.salesforce.phoenix.parse.InListParseNode; -import com.salesforce.phoenix.parse.IsNullParseNode; -import com.salesforce.phoenix.parse.JoinTableNode; -import com.salesforce.phoenix.parse.JoinTableNode.JoinType; -import com.salesforce.phoenix.parse.LikeParseNode; -import com.salesforce.phoenix.parse.NamedTableNode; -import com.salesforce.phoenix.parse.NotParseNode; -import com.salesforce.phoenix.parse.OrParseNode; -import com.salesforce.phoenix.parse.OrderByNode; -import com.salesforce.phoenix.parse.ParseNode; -import com.salesforce.phoenix.parse.ParseNodeFactory; -import com.salesforce.phoenix.parse.SelectStatement; -import com.salesforce.phoenix.parse.StatelessTraverseAllParseNodeVisitor; -import com.salesforce.phoenix.parse.TableName; -import com.salesforce.phoenix.parse.TableNode; -import com.salesforce.phoenix.parse.TableNodeVisitor; -import com.salesforce.phoenix.parse.TraverseNoParseNodeVisitor; -import com.salesforce.phoenix.parse.WildcardParseNode; -import com.salesforce.phoenix.schema.AmbiguousColumnException; -import com.salesforce.phoenix.schema.ColumnNotFoundException; -import com.salesforce.phoenix.schema.ColumnRef; -import com.salesforce.phoenix.schema.PColumn; -import com.salesforce.phoenix.schema.PColumnImpl; -import com.salesforce.phoenix.schema.PDataType; -import com.salesforce.phoenix.schema.PName; -import com.salesforce.phoenix.schema.PNameFactory; -import com.salesforce.phoenix.schema.PTable; -import com.salesforce.phoenix.schema.PTableImpl; -import com.salesforce.phoenix.schema.PTableType; -import com.salesforce.phoenix.schema.TableRef; -import com.salesforce.phoenix.util.SchemaUtil; - - -public class JoinCompiler { - - public static class JoinSpec { - private TableRef mainTable; - private List select; // all basic nodes related to mainTable, no aggregation. - private List preFilters; - private List postFilters; - private List joinTables; - private Set columnRefs; - - private JoinSpec(SelectStatement statement, ColumnResolver resolver) throws SQLException { - List selectList = statement.getSelect(); - List tableNodes = statement.getFrom(); - assert (tableNodes.size() > 1); - Iterator iter = tableNodes.iterator(); - Iterator tableRefIter = resolver.getTables().iterator(); - iter.next(); - this.mainTable = tableRefIter.next(); - this.select = extractFromSelect(selectList, mainTable, resolver); - this.joinTables = new ArrayList(tableNodes.size() - 1); - this.preFilters = new ArrayList(); - this.postFilters = new ArrayList(); - ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); - boolean hasRightJoin = false; - TableNode tableNode = null; - while (iter.hasNext()) { - tableNode = iter.next(); - if (!(tableNode instanceof JoinTableNode)) - throw new SQLFeatureNotSupportedException("Full joins not supported."); - JoinTableNode joinTableNode = (JoinTableNode) tableNode; - JoinTable joinTable = new JoinTable(joinTableNode, tableRefIter.next(), selectList, resolver); - joinTables.add(joinTable); - joinTableNode.getOnNode().accept(visitor); - if (joinTable.getType() == JoinType.Right) { - hasRightJoin = true; - } - } - if (statement.getWhere() != null) { - if (hasRightJoin) { - // conditions can't be pushed down to the scan filter. - postFilters.add(statement.getWhere()); - } else { - statement.getWhere().accept(new WhereNodeVisitor(resolver)); - } - } - for (AliasedNode node : selectList) { - node.getNode().accept(visitor); - } - if (statement.getWhere() != null) { - statement.getWhere().accept(visitor); - } - if (statement.getGroupBy() != null) { - for (ParseNode node : statement.getGroupBy()) { - node.accept(visitor); - } - } - if (statement.getHaving() != null) { - statement.getHaving().accept(visitor); - } - if (statement.getOrderBy() != null) { - for (OrderByNode node : statement.getOrderBy()) { - node.getNode().accept(visitor); - } - } - this.columnRefs = visitor.getColumnRefMap().keySet(); - } - - private JoinSpec(TableRef table, List select, List preFilters, - List postFilters, List joinTables, Set columnRefs) { - this.mainTable = table; - this.select = select; - this.preFilters = preFilters; - this.postFilters = postFilters; - this.joinTables = joinTables; - this.columnRefs = columnRefs; - } - - public TableRef getMainTable() { - return mainTable; - } - - public List getSelect() { - return select; - } - - public List getPreFilters() { - return preFilters; - } - - public List getPostFilters() { - return postFilters; - } - - public List getJoinTables() { - return joinTables; - } - - public ParseNode getPreFiltersCombined() { - if (preFilters == null || preFilters.isEmpty()) - return null; - - if (preFilters.size() == 1) - return preFilters.get(0); - - return NODE_FACTORY.and(preFilters); - } - - public Expression compilePostFilterExpression(StatementContext context) throws SQLException { - if (postFilters == null || postFilters.isEmpty()) - return null; - - ExpressionCompiler expressionCompiler = new ExpressionCompiler(context); - List expressions = new ArrayList(postFilters.size()); - for (ParseNode postFilter : postFilters) { - expressionCompiler.reset(); - Expression expression = postFilter.accept(expressionCompiler); - expressions.add(expression); - } - - if (expressions.size() == 1) - return expressions.get(0); - - return new AndExpression(expressions); - } - - public void projectColumns(Scan scan, TableRef table) { - if (isWildCardSelect(select)) { - scan.getFamilyMap().clear(); - return; - } - for (ColumnRef columnRef : columnRefs) { - if (columnRef.getTableRef().equals(table) - && !SchemaUtil.isPKColumn(columnRef.getColumn())) { - scan.addColumn(columnRef.getColumn().getFamilyName().getBytes(), columnRef.getColumn().getName().getBytes()); - } - } - } - - public ProjectedPTableWrapper createProjectedTable(TableRef tableRef, boolean retainPKColumns) throws SQLException { - List projectedColumns = new ArrayList(); - List sourceExpressions = new ArrayList(); - ListMultimap columnNameMap = ArrayListMultimap.create(); - PTable table = tableRef.getTable(); - boolean hasSaltingColumn = retainPKColumns && table.getBucketNum() != null; - if (hasSaltingColumn) { - // This serves a place-holder for the SALTING_COLUMN - sourceExpressions.add(LiteralExpression.NULL_EXPRESSION); - } - if (retainPKColumns) { - for (PColumn column : table.getPKColumns()) { - addProjectedColumn(projectedColumns, sourceExpressions, columnNameMap, - column, tableRef, column.getFamilyName(), hasSaltingColumn); - } - } - if (isWildCardSelect(select)) { - for (PColumn column : table.getColumns()) { - if (!retainPKColumns || !SchemaUtil.isPKColumn(column)) { - addProjectedColumn(projectedColumns, sourceExpressions, columnNameMap, - column, tableRef, PNameFactory.newName(ScanProjector.VALUE_COLUMN_FAMILY), hasSaltingColumn); - } - } - } else { - for (ColumnRef columnRef : columnRefs) { - if (columnRef.getTableRef().equals(tableRef) - && (!retainPKColumns || !SchemaUtil.isPKColumn(columnRef.getColumn()))) { - PColumn column = columnRef.getColumn(); - addProjectedColumn(projectedColumns, sourceExpressions, columnNameMap, - column, tableRef, PNameFactory.newName(ScanProjector.VALUE_COLUMN_FAMILY), hasSaltingColumn); - } - } - } - - PTable t = PTableImpl.makePTable(PNameFactory.newName(PROJECTED_TABLE_SCHEMA), table.getName(), PTableType.JOIN, table.getIndexState(), table.getTimeStamp(), table.getSequenceNumber(), table.getPKName(), retainPKColumns ? table.getBucketNum() : null, projectedColumns, table.getParentTableName(), table.getIndexes(), table.isImmutableRows(), null, null, null, table.isWALDisabled()); - return new ProjectedPTableWrapper(t, columnNameMap, sourceExpressions); - } - - private static void addProjectedColumn(List projectedColumns, List sourceExpressions, - ListMultimap columnNameMap, PColumn sourceColumn, TableRef sourceTable, PName familyName, boolean hasSaltingColumn) - throws SQLException { - if (sourceColumn == SALTING_COLUMN) - return; - - int position = projectedColumns.size() + (hasSaltingColumn ? 1 : 0); - PTable table = sourceTable.getTable(); - PName colName = sourceColumn.getName(); - PName name = getProjectedColumnName(table.getSchemaName(), table.getTableName(), colName); - columnNameMap.put(colName.getString(), name.getString()); - if (sourceTable.getTableAlias() != null) { - columnNameMap.put(getProjectedColumnName(null, sourceTable.getTableAlias(), colName.getString()), name.getString()); - } - PColumnImpl column = new PColumnImpl(name, familyName, sourceColumn.getDataType(), - sourceColumn.getMaxLength(), sourceColumn.getScale(), sourceColumn.isNullable(), - position, sourceColumn.getColumnModifier()); - Expression sourceExpression = new ColumnRef(sourceTable, sourceColumn.getPosition()).newColumnExpression(); - projectedColumns.add(column); - sourceExpressions.add(sourceExpression); - } - - private class WhereNodeVisitor extends TraverseNoParseNodeVisitor { - private ColumnResolver resolver; - - public WhereNodeVisitor(ColumnResolver resolver) { - this.resolver = resolver; - } - - private Void leaveBooleanNode(ParseNode node, - List l) throws SQLException { - ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); - node.accept(visitor); - ColumnParseNodeVisitor.ContentType type = visitor.getContentType(mainTable); - if (type == ColumnParseNodeVisitor.ContentType.NONE - || type == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - preFilters.add(node); - } else { - postFilters.add(node); - } - return null; - } - - @Override - public Void visitLeave(LikeParseNode node, - List l) throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public boolean visitEnter(AndParseNode node) { - return true; - } - - @Override - public Void visitLeave(OrParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(ComparisonParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(NotParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(InListParseNode node, - List l) throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(IsNullParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(FunctionParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(BetweenParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(CaseParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(CastParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - } - } - - public static JoinSpec getSubJoinSpecWithoutPostFilters(JoinSpec join) { - return new JoinSpec(join.mainTable, join.select, join.preFilters, new ArrayList(), - join.joinTables.subList(0, join.joinTables.size() - 1), join.columnRefs); - } - - public static class JoinTable { - private JoinType type; - private TableNode tableNode; // original table node - private TableRef table; - private List select; // all basic nodes related to this table, no aggregation. - private List preFilters; - private List conditions; - private SelectStatement subquery; - - private Set leftTableRefs; - - public JoinTable(JoinTableNode node, TableRef tableRef, List select, ColumnResolver resolver) throws SQLException { - if (!(node.getTable() instanceof ConcreteTableNode)) - throw new SQLFeatureNotSupportedException("Subqueries not supported."); - - this.type = node.getType(); - this.tableNode = node.getTable(); - this.table = tableRef; - this.select = extractFromSelect(select,tableRef,resolver); - this.preFilters = new ArrayList(); - this.conditions = new ArrayList(); - this.leftTableRefs = new HashSet(); - node.getOnNode().accept(new OnNodeVisitor(resolver)); - } - - public JoinType getType() { - return type; - } - - public TableNode getTableNode() { - return tableNode; - } - - public TableRef getTable() { - return table; - } - - public List getSelect() { - return select; - } - - public List getPreFilters() { - return preFilters; - } - - public List getJoinConditions() { - return conditions; - } - - public SelectStatement getSubquery() { - return subquery; - } - - public Set getLeftTableRefs() { - return leftTableRefs; - } - - public ParseNode getPreFiltersCombined() { - if (preFilters == null || preFilters.isEmpty()) - return null; - - if (preFilters.size() == 1) - return preFilters.get(0); - - return NODE_FACTORY.and(preFilters); - } - - public SelectStatement getAsSubquery() { - if (subquery != null) - return subquery; - - List from = new ArrayList(1); - from.add(tableNode); - return NODE_FACTORY.select(from, null, false, select, getPreFiltersCombined(), null, null, null, null, 0, false); - } - - public Pair, List> compileJoinConditions(StatementContext context, ColumnResolver leftResolver, ColumnResolver rightResolver) throws SQLException { - ColumnResolver resolver = context.getResolver(); - List> compiled = new ArrayList>(conditions.size()); - context.setResolver(leftResolver); - ExpressionCompiler expressionCompiler = new ExpressionCompiler(context); - for (ParseNode condition : conditions) { - assert (condition instanceof EqualParseNode); - EqualParseNode equalNode = (EqualParseNode) condition; - expressionCompiler.reset(); - Expression left = equalNode.getLHS().accept(expressionCompiler); - compiled.add(new Pair(left, null)); - } - context.setResolver(rightResolver); - expressionCompiler = new ExpressionCompiler(context); - Iterator> iter = compiled.iterator(); - for (ParseNode condition : conditions) { - Pair p = iter.next(); - EqualParseNode equalNode = (EqualParseNode) condition; - expressionCompiler.reset(); - Expression right = equalNode.getRHS().accept(expressionCompiler); - Expression left = p.getFirst(); - PDataType toType = getCommonType(left.getDataType(), right.getDataType()); - if (left.getDataType() != toType) { - left = CoerceExpression.create(left, toType); - p.setFirst(left); - } - if (right.getDataType() != toType) { - right = CoerceExpression.create(right, toType); - } - p.setSecond(right); - } - context.setResolver(resolver); // recover the resolver - Collections.sort(compiled, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - Expression e1 = o1.getFirst(); - Expression e2 = o2.getFirst(); - boolean isFixed1 = e1.getDataType().isFixedWidth(); - boolean isFixed2 = e2.getDataType().isFixedWidth(); - boolean isFixedNullable1 = e1.isNullable() &&isFixed1; - boolean isFixedNullable2 = e2.isNullable() && isFixed2; - if (isFixedNullable1 == isFixedNullable2) { - if (isFixed1 == isFixed2) { - return 0; - } else if (isFixed1) { - return -1; - } else { - return 1; - } - } else if (isFixedNullable1) { - return 1; - } else { - return -1; - } - } - }); - List lConditions = new ArrayList(compiled.size()); - List rConditions = new ArrayList(compiled.size()); - for (Pair pair : compiled) { - lConditions.add(pair.getFirst()); - rConditions.add(pair.getSecond()); - } - - return new Pair, List>(lConditions, rConditions); - } - - private PDataType getCommonType(PDataType lType, PDataType rType) throws SQLException { - if (lType == rType) - return lType; - - if (!lType.isComparableTo(rType)) - throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_CONVERT_TYPE) - .setMessage("On-clause LHS expression and RHS expression must be comparable. LHS type: " + lType + ", RHS type: " + rType) - .build().buildException(); - - // TODO: Does the type need to be nullable? - - if ((lType == null || lType.isCoercibleTo(PDataType.TINYINT)) - && (rType == null || rType.isCoercibleTo(PDataType.TINYINT))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.SMALLINT)) - && (rType == null || rType.isCoercibleTo(PDataType.SMALLINT))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.INTEGER)) - && (rType == null || rType.isCoercibleTo(PDataType.INTEGER))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.LONG)) - && (rType == null || rType.isCoercibleTo(PDataType.LONG))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.DECIMAL)) - && (rType == null || rType.isCoercibleTo(PDataType.DECIMAL))) { - return PDataType.DECIMAL; - } - - if ((lType == null || lType.isCoercibleTo(PDataType.DATE)) - && (rType == null || rType.isCoercibleTo(PDataType.DATE))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.TIMESTAMP)) - && (rType == null || rType.isCoercibleTo(PDataType.TIMESTAMP))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.VARCHAR)) - && (rType == null || rType.isCoercibleTo(PDataType.VARCHAR))) { - return PDataType.VARCHAR; - } - - if ((lType == null || lType.isCoercibleTo(PDataType.BOOLEAN)) - && (rType == null || rType.isCoercibleTo(PDataType.BOOLEAN))) { - return PDataType.BOOLEAN; - } - - return PDataType.VARBINARY; - } - - private class OnNodeVisitor extends TraverseNoParseNodeVisitor { - private ColumnResolver resolver; - - public OnNodeVisitor(ColumnResolver resolver) { - this.resolver = resolver; - } - - private Void leaveNonEqBooleanNode(ParseNode node, - List l) throws SQLException { - ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); - node.accept(visitor); - ColumnParseNodeVisitor.ContentType type = visitor.getContentType(table); - if (type == ColumnParseNodeVisitor.ContentType.NONE - || type == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - preFilters.add(node); - } else { - throwUnsupportedJoinConditionException(); - } - return null; - } - - @Override - public Void visitLeave(LikeParseNode node, - List l) throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public boolean visitEnter(AndParseNode node) { - return true; - } - - @Override - public Void visitLeave(OrParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(ComparisonParseNode node, List l) - throws SQLException { - if (!(node instanceof EqualParseNode)) - return leaveNonEqBooleanNode(node, l); - ColumnParseNodeVisitor lhsVisitor = new ColumnParseNodeVisitor(resolver); - ColumnParseNodeVisitor rhsVisitor = new ColumnParseNodeVisitor(resolver); - node.getLHS().accept(lhsVisitor); - node.getRHS().accept(rhsVisitor); - ColumnParseNodeVisitor.ContentType lhsType = lhsVisitor.getContentType(table); - ColumnParseNodeVisitor.ContentType rhsType = rhsVisitor.getContentType(table); - if ((lhsType == ColumnParseNodeVisitor.ContentType.SELF_ONLY || lhsType == ColumnParseNodeVisitor.ContentType.NONE) - && (rhsType == ColumnParseNodeVisitor.ContentType.SELF_ONLY || rhsType == ColumnParseNodeVisitor.ContentType.NONE)) { - preFilters.add(node); - } else if (lhsType == ColumnParseNodeVisitor.ContentType.FOREIGN_ONLY - && rhsType == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - conditions.add(node); - leftTableRefs.addAll(lhsVisitor.getTableRefSet()); - } else if (rhsType == ColumnParseNodeVisitor.ContentType.FOREIGN_ONLY - && lhsType == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - conditions.add(NODE_FACTORY.equal(node.getRHS(), node.getLHS())); - leftTableRefs.addAll(rhsVisitor.getTableRefSet()); - } else { - throwUnsupportedJoinConditionException(); - } - return null; - } - - @Override - public Void visitLeave(NotParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(InListParseNode node, - List l) throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(IsNullParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(FunctionParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(BetweenParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(CaseParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(CastParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - /* - * Conditions in the ON clause can only be: - * 1) an equal test between a self table expression and a foreign - * table expression. - * 2) a boolean condition referencing to the self table only. - * Otherwise, it can be ambiguous. - */ - private void throwUnsupportedJoinConditionException() - throws SQLFeatureNotSupportedException { - throw new SQLFeatureNotSupportedException("Does not support non-standard or non-equi join conditions."); - } - } - } - - private static class ColumnParseNodeVisitor extends StatelessTraverseAllParseNodeVisitor { - public enum ContentType {NONE, SELF_ONLY, FOREIGN_ONLY, COMPLEX}; - - private ColumnResolver resolver; - private final Set tableRefSet; - private final Map columnRefMap; - - public ColumnParseNodeVisitor(ColumnResolver resolver) { - this.resolver = resolver; - this.tableRefSet = new HashSet(); - this.columnRefMap = new HashMap(); - } - - public void reset() { - this.tableRefSet.clear(); - this.columnRefMap.clear(); - } - - @Override - public Void visit(ColumnParseNode node) throws SQLException { - ColumnRef columnRef = resolver.resolveColumn(node.getSchemaName(), node.getTableName(), node.getName()); - columnRefMap.put(columnRef, node); - tableRefSet.add(columnRef.getTableRef()); - return null; - } - - public Set getTableRefSet() { - return tableRefSet; - } - - public Map getColumnRefMap() { - return columnRefMap; - } - - public ContentType getContentType(TableRef selfTable) { - if (tableRefSet.isEmpty()) - return ContentType.NONE; - if (tableRefSet.size() > 1) - return ContentType.COMPLEX; - if (tableRefSet.contains(selfTable)) - return ContentType.SELF_ONLY; - return ContentType.FOREIGN_ONLY; - } - } - - private static String PROJECTED_TABLE_SCHEMA = "."; - // for creation of new statements - private static ParseNodeFactory NODE_FACTORY = new ParseNodeFactory(); - - private static boolean isWildCardSelect(List select) { - return (select.size() == 1 && select.get(0).getNode() == WildcardParseNode.INSTANCE); - } - - private static List extractFromSelect(List select, TableRef table, ColumnResolver resolver) throws SQLException { - List ret = new ArrayList(); - if (isWildCardSelect(select)) { - ret.add(NODE_FACTORY.aliasedNode(null, WildcardParseNode.INSTANCE)); - return ret; - } - - ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); - for (AliasedNode node : select) { - node.getNode().accept(visitor); - ColumnParseNodeVisitor.ContentType type = visitor.getContentType(table); - if (type == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - ret.add(node); - } else if (type == ColumnParseNodeVisitor.ContentType.COMPLEX) { - for (Map.Entry entry : visitor.getColumnRefMap().entrySet()) { - if (entry.getKey().getTableRef().equals(table)) { - ret.add(NODE_FACTORY.aliasedNode(null, entry.getValue())); - } - } - } - visitor.reset(); - } - return ret; - } - - public static JoinSpec getJoinSpec(StatementContext context, SelectStatement statement) throws SQLException { - return new JoinSpec(statement, context.getResolver()); - } - - public static SelectStatement optimize(StatementContext context, SelectStatement select, PhoenixStatement statement) throws SQLException { - ColumnResolver resolver = context.getResolver(); - JoinSpec join = new JoinSpec(select, resolver); - Map replacement = new HashMap(); - List from = select.getFrom(); - List newFrom = Lists.newArrayListWithExpectedSize(from.size()); - - class TableNodeRewriter implements TableNodeVisitor { - private TableRef table; - private TableNode replaced; - - TableNodeRewriter(TableRef table) { - this.table = table; - } - - public TableNode getReplacedTableNode() { - return replaced; - } - - @Override - public void visit(BindTableNode boundTableNode) throws SQLException { - replaced = NODE_FACTORY.bindTable(boundTableNode.getAlias(), getReplacedTableName()); - } - - @Override - public void visit(JoinTableNode joinNode) throws SQLException { - joinNode.getTable().accept(this); - replaced = NODE_FACTORY.join(joinNode.getType(), joinNode.getOnNode(), replaced); - } - - @Override - public void visit(NamedTableNode namedTableNode) - throws SQLException { - replaced = NODE_FACTORY.namedTable(namedTableNode.getAlias(), getReplacedTableName(), namedTableNode.getDynamicColumns()); - } - - @Override - public void visit(DerivedTableNode subselectNode) - throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - private TableName getReplacedTableName() { - String schemaName = table.getTable().getSchemaName().getString(); - schemaName = schemaName.length() == 0 ? null : '"' + schemaName + '"'; - String tableName = '"' + table.getTable().getTableName().getString() + '"'; - return NODE_FACTORY.table(schemaName, tableName); - } - }; - - // get optimized plans for join tables - for (int i = 1; i < from.size(); i++) { - TableNode jNode = from.get(i); - assert (jNode instanceof JoinTableNode); - TableNode tNode = ((JoinTableNode) jNode).getTable(); - for (JoinTable jTable : join.getJoinTables()) { - if (jTable.getTableNode() != tNode) - continue; - TableRef table = jTable.getTable(); - SelectStatement stmt = getSubqueryForOptimizedPlan(select, table, join.columnRefs, jTable.getPreFiltersCombined()); - QueryPlan plan = context.getConnection().getQueryServices().getOptimizer().optimize(stmt, statement); - if (!plan.getTableRef().equals(table)) { - TableNodeRewriter rewriter = new TableNodeRewriter(plan.getTableRef()); - jNode.accept(rewriter); - newFrom.add(rewriter.getReplacedTableNode()); - replacement.put(table, plan.getTableRef()); - } else { - newFrom.add(jNode); - } - } - } - // get optimized plan for main table - TableRef table = join.getMainTable(); - SelectStatement stmt = getSubqueryForOptimizedPlan(select, table, join.columnRefs, join.getPreFiltersCombined()); - QueryPlan plan = context.getConnection().getQueryServices().getOptimizer().optimize(stmt, statement); - if (!plan.getTableRef().equals(table)) { - TableNodeRewriter rewriter = new TableNodeRewriter(plan.getTableRef()); - from.get(0).accept(rewriter); - newFrom.add(0, rewriter.getReplacedTableNode()); - replacement.put(table, plan.getTableRef()); - } else { - newFrom.add(0, from.get(0)); - } - - if (replacement.isEmpty()) - return select; - - return IndexStatementRewriter.translate(NODE_FACTORY.select(select, newFrom), resolver, replacement); - } - - private static SelectStatement getSubqueryForOptimizedPlan(SelectStatement select, TableRef table, Set columnRefs, ParseNode where) { - TableName tName = NODE_FACTORY.table(table.getTable().getSchemaName().getString(), table.getTable().getTableName().getString()); - List selectList = new ArrayList(); - if (isWildCardSelect(select.getSelect())) { - selectList.add(NODE_FACTORY.aliasedNode(null, WildcardParseNode.INSTANCE)); - } else { - for (ColumnRef colRef : columnRefs) { - if (colRef.getTableRef().equals(table)) { - selectList.add(NODE_FACTORY.aliasedNode(null, NODE_FACTORY.column(tName, colRef.getColumn().getName().getString(), null))); - } - } - } - List from = Collections.singletonList(NODE_FACTORY.namedTable(table.getTableAlias(), tName)); - - return NODE_FACTORY.select(from, select.getHint(), false, selectList, where, null, null, null, null, 0, false); - } - - /** - * Returns a boolean vector indicating whether the evaluation of join expressions - * can be evaluated at an early stage if the input JoinSpec can be taken as a - * star join. Otherwise returns null. - * @param join the JoinSpec - * @return a boolean vector for a star join; or null for non star join. - */ - public static boolean[] getStarJoinVector(JoinSpec join) { - assert(!join.getJoinTables().isEmpty()); - - int count = join.getJoinTables().size(); - boolean[] vector = new boolean[count]; - for (int i = 0; i < count; i++) { - JoinTable joinTable = join.getJoinTables().get(i); - if (joinTable.getType() != JoinType.Left - && joinTable.getType() != JoinType.Inner) - return null; - vector[i] = true; - Iterator iter = joinTable.getLeftTableRefs().iterator(); - while (vector[i] == true && iter.hasNext()) { - TableRef tableRef = iter.next(); - if (!tableRef.equals(join.getMainTable())) { - vector[i] = false; - } - } - } - - return vector; - } - - public static SelectStatement getSubqueryWithoutJoin(SelectStatement statement, JoinSpec join) { - return NODE_FACTORY.select(statement.getFrom().subList(0, 1), statement.getHint(), statement.isDistinct(), statement.getSelect(), join.getPreFiltersCombined(), statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate()); - } - - // Get the last join table select statement with fixed-up select and where nodes. - // Currently does NOT support last join table as a subquery. - public static SelectStatement getSubqueryForLastJoinTable(SelectStatement statement, JoinSpec join) throws SQLException { - List joinTables = join.getJoinTables(); - int count = joinTables.size(); - assert (count > 0); - JoinTable lastJoinTable = joinTables.get(count - 1); - if (lastJoinTable.getSubquery() != null) { - throw new SQLFeatureNotSupportedException("Subqueries not supported."); - } - List from = new ArrayList(1); - from.add(lastJoinTable.getTableNode()); - - return NODE_FACTORY.select(from, statement.getHint(), statement.isDistinct(), statement.getSelect(), lastJoinTable.getPreFiltersCombined(), statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate()); - } - - // Get subquery with fixed select and where nodes - public static SelectStatement getSubQueryWithoutLastJoin(SelectStatement statement, JoinSpec join) { - List from = statement.getFrom(); - assert(from.size() > 1); - List joinTables = join.getJoinTables(); - int count = joinTables.size(); - assert (count > 0); - List select = new ArrayList(); - select.addAll(join.getSelect()); - for (int i = 0; i < count - 1; i++) { - select.addAll(joinTables.get(i).getSelect()); - } - - return NODE_FACTORY.select(from.subList(0, from.size() - 1), statement.getHint(), false, select, join.getPreFiltersCombined(), null, null, null, null, statement.getBindCount(), false); - } - - public static PTableWrapper mergeProjectedTables(PTableWrapper lWrapper, PTableWrapper rWrapper, boolean innerJoin) throws SQLException { - PTable left = lWrapper.getTable(); - PTable right = rWrapper.getTable(); - List merged = new ArrayList(); - merged.addAll(left.getColumns()); - int position = merged.size(); - for (PColumn c : right.getColumns()) { - if (!SchemaUtil.isPKColumn(c)) { - PColumnImpl column = new PColumnImpl(c.getName(), - PNameFactory.newName(ScanProjector.VALUE_COLUMN_FAMILY), c.getDataType(), - c.getMaxLength(), c.getScale(), innerJoin ? c.isNullable() : true, position++, - c.getColumnModifier()); - merged.add(column); - } - } - if (left.getBucketNum() != null) { - merged.remove(0); - } - PTable t = PTableImpl.makePTable(left.getSchemaName(), PNameFactory.newName(SchemaUtil.getTableName(left.getName().getString(), right.getName().getString())), left.getType(), left.getIndexState(), left.getTimeStamp(), left.getSequenceNumber(), left.getPKName(), left.getBucketNum(), merged, left.getParentTableName(), left.getIndexes(), left.isImmutableRows(), null, null, null, PTable.DEFAULT_DISABLE_WAL); - - ListMultimap mergedMap = ArrayListMultimap.create(); - mergedMap.putAll(lWrapper.getColumnNameMap()); - mergedMap.putAll(rWrapper.getColumnNameMap()); - - return new PTableWrapper(t, mergedMap); - } - - public static ScanProjector getScanProjector(ProjectedPTableWrapper table) { - return new ScanProjector(table); - } - - public static class PTableWrapper { - protected PTable table; - protected ListMultimap columnNameMap; - - protected PTableWrapper(PTable table, ListMultimap columnNameMap) { - this.table = table; - this.columnNameMap = columnNameMap; - } - - public PTable getTable() { - return table; - } - - public ListMultimap getColumnNameMap() { - return columnNameMap; - } - - public List getMappedColumnName(String name) { - return columnNameMap.get(name); - } - } - - public static class ProjectedPTableWrapper extends PTableWrapper { - private List sourceExpressions; - - protected ProjectedPTableWrapper(PTable table, ListMultimap columnNameMap, List sourceExpressions) { - super(table, columnNameMap); - this.sourceExpressions = sourceExpressions; - } - - public Expression getSourceExpression(PColumn column) { - return sourceExpressions.get(column.getPosition()); - } - } - - public static ColumnResolver getColumnResolver(PTableWrapper table) { - return new JoinedTableColumnResolver(table); - } - - public static class JoinedTableColumnResolver implements ColumnResolver { - private PTableWrapper table; - private List tableRefs; - - private JoinedTableColumnResolver(PTableWrapper table) { - this.table = table; - TableRef tableRef = new TableRef(null, table.getTable(), 0, false); - this.tableRefs = ImmutableList.of(tableRef); - } - - @Override - public List getTables() { - return tableRefs; - } - - public PTableWrapper getPTableWrapper() { - return table; - } - - @Override - public ColumnRef resolveColumn(String schemaName, String tableName, - String colName) throws SQLException { - String name = getProjectedColumnName(schemaName, tableName, colName); - TableRef tableRef = tableRefs.get(0); - try { - PColumn column = tableRef.getTable().getColumn(name); - return new ColumnRef(tableRef, column.getPosition()); - } catch (ColumnNotFoundException e) { - List names = table.getMappedColumnName(name); - if (names.size() == 1) { - PColumn column = tableRef.getTable().getColumn(names.get(0)); - return new ColumnRef(tableRef, column.getPosition()); - } - - if (names.size() > 1) { - throw new AmbiguousColumnException(name); - } - - throw e; - } - } - } - - private static String getProjectedColumnName(String schemaName, String tableName, - String colName) { - return SchemaUtil.getColumnName(SchemaUtil.getTableName(schemaName, tableName), colName); - } - - private static PName getProjectedColumnName(PName schemaName, PName tableName, - PName colName) { - String name = getProjectedColumnName(schemaName.getString(), tableName.getString(), colName.getString()); - return PNameFactory.newName(name); - } -} diff --git a/All/Genesis-NP/Genesis#258/old/JoinCompiler.java b/All/Genesis-NP/Genesis#258/old/JoinCompiler.java deleted file mode 100755 index 00ad54d..0000000 --- a/All/Genesis-NP/Genesis#258/old/JoinCompiler.java +++ /dev/null @@ -1,1091 +0,0 @@ -/******************************************************************************* - * Copyright (c) 2013, Salesforce.com, Inc. - * All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * Redistributions of source code must retain the above copyright notice, - * this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - * this list of conditions and the following disclaimer in the documentation - * and/or other materials provided with the distribution. - * Neither the name of Salesforce.com nor the names of its contributors may - * be used to endorse or promote products derived from this software without - * specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER - * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, - * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - ******************************************************************************/ -package com.salesforce.phoenix.compile; - -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.hadoop.hbase.client.Scan; -import org.apache.hadoop.hbase.util.Pair; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ListMultimap; -import com.google.common.collect.Lists; -import com.salesforce.phoenix.exception.SQLExceptionCode; -import com.salesforce.phoenix.exception.SQLExceptionInfo; -import com.salesforce.phoenix.expression.AndExpression; -import com.salesforce.phoenix.expression.CoerceExpression; -import com.salesforce.phoenix.expression.Expression; -import com.salesforce.phoenix.expression.LiteralExpression; -import com.salesforce.phoenix.jdbc.PhoenixStatement; -import com.salesforce.phoenix.join.ScanProjector; -import com.salesforce.phoenix.parse.AliasedNode; -import com.salesforce.phoenix.parse.AndParseNode; -import com.salesforce.phoenix.parse.BetweenParseNode; -import com.salesforce.phoenix.parse.BindTableNode; -import com.salesforce.phoenix.parse.CaseParseNode; -import com.salesforce.phoenix.parse.CastParseNode; -import com.salesforce.phoenix.parse.ColumnParseNode; -import com.salesforce.phoenix.parse.ComparisonParseNode; -import com.salesforce.phoenix.parse.ConcreteTableNode; -import com.salesforce.phoenix.parse.DerivedTableNode; -import com.salesforce.phoenix.parse.EqualParseNode; -import com.salesforce.phoenix.parse.FunctionParseNode; -import com.salesforce.phoenix.parse.InListParseNode; -import com.salesforce.phoenix.parse.IsNullParseNode; -import com.salesforce.phoenix.parse.JoinTableNode; -import com.salesforce.phoenix.parse.JoinTableNode.JoinType; -import com.salesforce.phoenix.parse.LikeParseNode; -import com.salesforce.phoenix.parse.NamedTableNode; -import com.salesforce.phoenix.parse.NotParseNode; -import com.salesforce.phoenix.parse.OrParseNode; -import com.salesforce.phoenix.parse.OrderByNode; -import com.salesforce.phoenix.parse.ParseNode; -import com.salesforce.phoenix.parse.ParseNodeFactory; -import com.salesforce.phoenix.parse.SelectStatement; -import com.salesforce.phoenix.parse.StatelessTraverseAllParseNodeVisitor; -import com.salesforce.phoenix.parse.TableName; -import com.salesforce.phoenix.parse.TableNode; -import com.salesforce.phoenix.parse.TableNodeVisitor; -import com.salesforce.phoenix.parse.TraverseNoParseNodeVisitor; -import com.salesforce.phoenix.parse.WildcardParseNode; -import com.salesforce.phoenix.schema.AmbiguousColumnException; -import com.salesforce.phoenix.schema.ColumnNotFoundException; -import com.salesforce.phoenix.schema.ColumnRef; -import com.salesforce.phoenix.schema.PColumn; -import com.salesforce.phoenix.schema.PColumnImpl; -import com.salesforce.phoenix.schema.PDataType; -import com.salesforce.phoenix.schema.PName; -import com.salesforce.phoenix.schema.PNameFactory; -import com.salesforce.phoenix.schema.PTable; -import com.salesforce.phoenix.schema.PTableImpl; -import com.salesforce.phoenix.schema.PTableType; -import com.salesforce.phoenix.schema.TableRef; -import com.salesforce.phoenix.util.SchemaUtil; - - -public class JoinCompiler { - - public static class JoinSpec { - private TableRef mainTable; - private List select; // all basic nodes related to mainTable, no aggregation. - private List preFilters; - private List postFilters; - private List joinTables; - private Set columnRefs; - - private JoinSpec(SelectStatement statement, ColumnResolver resolver) throws SQLException { - List selectList = statement.getSelect(); - List tableNodes = statement.getFrom(); - assert (tableNodes.size() > 1); - Iterator iter = tableNodes.iterator(); - Iterator tableRefIter = resolver.getTables().iterator(); - iter.next(); - this.mainTable = tableRefIter.next(); - this.select = extractFromSelect(selectList, mainTable, resolver); - this.joinTables = new ArrayList(tableNodes.size() - 1); - this.preFilters = new ArrayList(); - this.postFilters = new ArrayList(); - ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); - boolean hasRightJoin = false; - TableNode tableNode = null; - while (iter.hasNext()) { - tableNode = iter.next(); - if (!(tableNode instanceof JoinTableNode)) - throw new SQLFeatureNotSupportedException("Full joins not supported."); - JoinTableNode joinTableNode = (JoinTableNode) tableNode; - JoinTable joinTable = new JoinTable(joinTableNode, tableRefIter.next(), selectList, resolver); - joinTables.add(joinTable); - joinTableNode.getOnNode().accept(visitor); - if (joinTable.getType() == JoinType.Right) { - hasRightJoin = true; - } - } - if (statement.getWhere() != null) { - if (hasRightJoin) { - // conditions can't be pushed down to the scan filter. - postFilters.add(statement.getWhere()); - } else { - statement.getWhere().accept(new WhereNodeVisitor(resolver)); - } - } - for (AliasedNode node : selectList) { - node.getNode().accept(visitor); - } - if (statement.getWhere() != null) { - statement.getWhere().accept(visitor); - } - if (statement.getGroupBy() != null) { - for (ParseNode node : statement.getGroupBy()) { - node.accept(visitor); - } - } - if (statement.getHaving() != null) { - statement.getHaving().accept(visitor); - } - if (statement.getOrderBy() != null) { - for (OrderByNode node : statement.getOrderBy()) { - node.getNode().accept(visitor); - } - } - this.columnRefs = visitor.getColumnRefMap().keySet(); - } - - private JoinSpec(TableRef table, List select, List preFilters, - List postFilters, List joinTables, Set columnRefs) { - this.mainTable = table; - this.select = select; - this.preFilters = preFilters; - this.postFilters = postFilters; - this.joinTables = joinTables; - this.columnRefs = columnRefs; - } - - public TableRef getMainTable() { - return mainTable; - } - - public List getSelect() { - return select; - } - - public List getPreFilters() { - return preFilters; - } - - public List getPostFilters() { - return postFilters; - } - - public List getJoinTables() { - return joinTables; - } - - public ParseNode getPreFiltersCombined() { - if (preFilters == null || preFilters.isEmpty()) - return null; - - if (preFilters.size() == 1) - return preFilters.get(0); - - return NODE_FACTORY.and(preFilters); - } - - public Expression compilePostFilterExpression(StatementContext context) throws SQLException { - if (postFilters == null || postFilters.isEmpty()) - return null; - - ExpressionCompiler expressionCompiler = new ExpressionCompiler(context); - List expressions = new ArrayList(postFilters.size()); - for (ParseNode postFilter : postFilters) { - expressionCompiler.reset(); - Expression expression = postFilter.accept(expressionCompiler); - expressions.add(expression); - } - - if (expressions.size() == 1) - return expressions.get(0); - - return new AndExpression(expressions); - } - - public void projectColumns(Scan scan, TableRef table) { - if (isWildCardSelect(select)) { - scan.getFamilyMap().clear(); - return; - } - for (ColumnRef columnRef : columnRefs) { - if (columnRef.getTableRef().equals(table) - && !SchemaUtil.isPKColumn(columnRef.getColumn())) { - scan.addColumn(columnRef.getColumn().getFamilyName().getBytes(), columnRef.getColumn().getName().getBytes()); - } - } - } - - public ProjectedPTableWrapper createProjectedTable(TableRef tableRef, boolean retainPKColumns) throws SQLException { - List projectedColumns = new ArrayList(); - List sourceExpressions = new ArrayList(); - ListMultimap columnNameMap = ArrayListMultimap.create(); - PTable table = tableRef.getTable(); - boolean hasSaltingColumn = retainPKColumns && table.getBucketNum() != null; - if (hasSaltingColumn) { - // This serves a place-holder for the SALTING_COLUMN - sourceExpressions.add(LiteralExpression.NULL_EXPRESSION); - } - if (retainPKColumns) { - for (PColumn column : table.getPKColumns()) { - addProjectedColumn(projectedColumns, sourceExpressions, columnNameMap, - column, tableRef, column.getFamilyName(), hasSaltingColumn); - } - } - if (isWildCardSelect(select)) { - for (PColumn column : table.getColumns()) { - if (!retainPKColumns || !SchemaUtil.isPKColumn(column)) { - addProjectedColumn(projectedColumns, sourceExpressions, columnNameMap, - column, tableRef, PNameFactory.newName(ScanProjector.VALUE_COLUMN_FAMILY), hasSaltingColumn); - } - } - } else { - for (ColumnRef columnRef : columnRefs) { - if (columnRef.getTableRef().equals(tableRef) - && (!retainPKColumns || !SchemaUtil.isPKColumn(columnRef.getColumn()))) { - PColumn column = columnRef.getColumn(); - addProjectedColumn(projectedColumns, sourceExpressions, columnNameMap, - column, tableRef, PNameFactory.newName(ScanProjector.VALUE_COLUMN_FAMILY), hasSaltingColumn); - } - } - } - - PTable t = PTableImpl.makePTable(PNameFactory.newName(PROJECTED_TABLE_SCHEMA), table.getName(), PTableType.JOIN, table.getIndexState(), table.getTimeStamp(), table.getSequenceNumber(), table.getPKName(), retainPKColumns ? table.getBucketNum() : null, projectedColumns, table.getParentTableName(), table.getIndexes(), table.isImmutableRows(), null, null, null, table.isWALDisabled()); - return new ProjectedPTableWrapper(t, columnNameMap, sourceExpressions); - } - - private static void addProjectedColumn(List projectedColumns, List sourceExpressions, - ListMultimap columnNameMap, PColumn sourceColumn, TableRef sourceTable, PName familyName, boolean hasSaltingColumn) - throws SQLException { - int position = projectedColumns.size() + (hasSaltingColumn ? 1 : 0); - PTable table = sourceTable.getTable(); - PName colName = sourceColumn.getName(); - PName name = getProjectedColumnName(table.getSchemaName(), table.getTableName(), colName); - columnNameMap.put(colName.getString(), name.getString()); - if (sourceTable.getTableAlias() != null) { - columnNameMap.put(getProjectedColumnName(null, sourceTable.getTableAlias(), colName.getString()), name.getString()); - } - PColumnImpl column = new PColumnImpl(name, familyName, sourceColumn.getDataType(), - sourceColumn.getMaxLength(), sourceColumn.getScale(), sourceColumn.isNullable(), - position, sourceColumn.getColumnModifier()); - Expression sourceExpression = new ColumnRef(sourceTable, sourceColumn.getPosition()).newColumnExpression(); - projectedColumns.add(column); - sourceExpressions.add(sourceExpression); - } - - private class WhereNodeVisitor extends TraverseNoParseNodeVisitor { - private ColumnResolver resolver; - - public WhereNodeVisitor(ColumnResolver resolver) { - this.resolver = resolver; - } - - private Void leaveBooleanNode(ParseNode node, - List l) throws SQLException { - ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); - node.accept(visitor); - ColumnParseNodeVisitor.ContentType type = visitor.getContentType(mainTable); - if (type == ColumnParseNodeVisitor.ContentType.NONE - || type == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - preFilters.add(node); - } else { - postFilters.add(node); - } - return null; - } - - @Override - public Void visitLeave(LikeParseNode node, - List l) throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public boolean visitEnter(AndParseNode node) { - return true; - } - - @Override - public Void visitLeave(OrParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(ComparisonParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(NotParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(InListParseNode node, - List l) throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(IsNullParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(FunctionParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(BetweenParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(CaseParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - - @Override - public Void visitLeave(CastParseNode node, List l) - throws SQLException { - return leaveBooleanNode(node, l); - } - } - } - - public static JoinSpec getSubJoinSpecWithoutPostFilters(JoinSpec join) { - return new JoinSpec(join.mainTable, join.select, join.preFilters, new ArrayList(), - join.joinTables.subList(0, join.joinTables.size() - 1), join.columnRefs); - } - - public static class JoinTable { - private JoinType type; - private TableNode tableNode; // original table node - private TableRef table; - private List select; // all basic nodes related to this table, no aggregation. - private List preFilters; - private List conditions; - private SelectStatement subquery; - - private Set leftTableRefs; - - public JoinTable(JoinTableNode node, TableRef tableRef, List select, ColumnResolver resolver) throws SQLException { - if (!(node.getTable() instanceof ConcreteTableNode)) - throw new SQLFeatureNotSupportedException("Subqueries not supported."); - - this.type = node.getType(); - this.tableNode = node.getTable(); - this.table = tableRef; - this.select = extractFromSelect(select,tableRef,resolver); - this.preFilters = new ArrayList(); - this.conditions = new ArrayList(); - this.leftTableRefs = new HashSet(); - node.getOnNode().accept(new OnNodeVisitor(resolver)); - } - - public JoinType getType() { - return type; - } - - public TableNode getTableNode() { - return tableNode; - } - - public TableRef getTable() { - return table; - } - - public List getSelect() { - return select; - } - - public List getPreFilters() { - return preFilters; - } - - public List getJoinConditions() { - return conditions; - } - - public SelectStatement getSubquery() { - return subquery; - } - - public Set getLeftTableRefs() { - return leftTableRefs; - } - - public ParseNode getPreFiltersCombined() { - if (preFilters == null || preFilters.isEmpty()) - return null; - - if (preFilters.size() == 1) - return preFilters.get(0); - - return NODE_FACTORY.and(preFilters); - } - - public SelectStatement getAsSubquery() { - if (subquery != null) - return subquery; - - List from = new ArrayList(1); - from.add(tableNode); - return NODE_FACTORY.select(from, null, false, select, getPreFiltersCombined(), null, null, null, null, 0, false); - } - - public Pair, List> compileJoinConditions(StatementContext context, ColumnResolver leftResolver, ColumnResolver rightResolver) throws SQLException { - ColumnResolver resolver = context.getResolver(); - List> compiled = new ArrayList>(conditions.size()); - context.setResolver(leftResolver); - ExpressionCompiler expressionCompiler = new ExpressionCompiler(context); - for (ParseNode condition : conditions) { - assert (condition instanceof EqualParseNode); - EqualParseNode equalNode = (EqualParseNode) condition; - expressionCompiler.reset(); - Expression left = equalNode.getLHS().accept(expressionCompiler); - compiled.add(new Pair(left, null)); - } - context.setResolver(rightResolver); - expressionCompiler = new ExpressionCompiler(context); - Iterator> iter = compiled.iterator(); - for (ParseNode condition : conditions) { - Pair p = iter.next(); - EqualParseNode equalNode = (EqualParseNode) condition; - expressionCompiler.reset(); - Expression right = equalNode.getRHS().accept(expressionCompiler); - Expression left = p.getFirst(); - PDataType toType = getCommonType(left.getDataType(), right.getDataType()); - if (left.getDataType() != toType) { - left = CoerceExpression.create(left, toType); - p.setFirst(left); - } - if (right.getDataType() != toType) { - right = CoerceExpression.create(right, toType); - } - p.setSecond(right); - } - context.setResolver(resolver); // recover the resolver - Collections.sort(compiled, new Comparator>() { - @Override - public int compare(Pair o1, Pair o2) { - Expression e1 = o1.getFirst(); - Expression e2 = o2.getFirst(); - boolean isFixed1 = e1.getDataType().isFixedWidth(); - boolean isFixed2 = e2.getDataType().isFixedWidth(); - boolean isFixedNullable1 = e1.isNullable() &&isFixed1; - boolean isFixedNullable2 = e2.isNullable() && isFixed2; - if (isFixedNullable1 == isFixedNullable2) { - if (isFixed1 == isFixed2) { - return 0; - } else if (isFixed1) { - return -1; - } else { - return 1; - } - } else if (isFixedNullable1) { - return 1; - } else { - return -1; - } - } - }); - List lConditions = new ArrayList(compiled.size()); - List rConditions = new ArrayList(compiled.size()); - for (Pair pair : compiled) { - lConditions.add(pair.getFirst()); - rConditions.add(pair.getSecond()); - } - - return new Pair, List>(lConditions, rConditions); - } - - private PDataType getCommonType(PDataType lType, PDataType rType) throws SQLException { - if (lType == rType) - return lType; - - if (!lType.isComparableTo(rType)) - throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_CONVERT_TYPE) - .setMessage("On-clause LHS expression and RHS expression must be comparable. LHS type: " + lType + ", RHS type: " + rType) - .build().buildException(); - - // TODO: Does the type need to be nullable? - - if ((lType == null || lType.isCoercibleTo(PDataType.TINYINT)) - && (rType == null || rType.isCoercibleTo(PDataType.TINYINT))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.SMALLINT)) - && (rType == null || rType.isCoercibleTo(PDataType.SMALLINT))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.INTEGER)) - && (rType == null || rType.isCoercibleTo(PDataType.INTEGER))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.LONG)) - && (rType == null || rType.isCoercibleTo(PDataType.LONG))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.DECIMAL)) - && (rType == null || rType.isCoercibleTo(PDataType.DECIMAL))) { - return PDataType.DECIMAL; - } - - if ((lType == null || lType.isCoercibleTo(PDataType.DATE)) - && (rType == null || rType.isCoercibleTo(PDataType.DATE))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.TIMESTAMP)) - && (rType == null || rType.isCoercibleTo(PDataType.TIMESTAMP))) { - return lType == null ? rType : lType; // to preserve UNSIGNED type - } - - if ((lType == null || lType.isCoercibleTo(PDataType.VARCHAR)) - && (rType == null || rType.isCoercibleTo(PDataType.VARCHAR))) { - return PDataType.VARCHAR; - } - - if ((lType == null || lType.isCoercibleTo(PDataType.BOOLEAN)) - && (rType == null || rType.isCoercibleTo(PDataType.BOOLEAN))) { - return PDataType.BOOLEAN; - } - - return PDataType.VARBINARY; - } - - private class OnNodeVisitor extends TraverseNoParseNodeVisitor { - private ColumnResolver resolver; - - public OnNodeVisitor(ColumnResolver resolver) { - this.resolver = resolver; - } - - private Void leaveNonEqBooleanNode(ParseNode node, - List l) throws SQLException { - ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); - node.accept(visitor); - ColumnParseNodeVisitor.ContentType type = visitor.getContentType(table); - if (type == ColumnParseNodeVisitor.ContentType.NONE - || type == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - preFilters.add(node); - } else { - throwUnsupportedJoinConditionException(); - } - return null; - } - - @Override - public Void visitLeave(LikeParseNode node, - List l) throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public boolean visitEnter(AndParseNode node) { - return true; - } - - @Override - public Void visitLeave(OrParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(ComparisonParseNode node, List l) - throws SQLException { - if (!(node instanceof EqualParseNode)) - return leaveNonEqBooleanNode(node, l); - ColumnParseNodeVisitor lhsVisitor = new ColumnParseNodeVisitor(resolver); - ColumnParseNodeVisitor rhsVisitor = new ColumnParseNodeVisitor(resolver); - node.getLHS().accept(lhsVisitor); - node.getRHS().accept(rhsVisitor); - ColumnParseNodeVisitor.ContentType lhsType = lhsVisitor.getContentType(table); - ColumnParseNodeVisitor.ContentType rhsType = rhsVisitor.getContentType(table); - if ((lhsType == ColumnParseNodeVisitor.ContentType.SELF_ONLY || lhsType == ColumnParseNodeVisitor.ContentType.NONE) - && (rhsType == ColumnParseNodeVisitor.ContentType.SELF_ONLY || rhsType == ColumnParseNodeVisitor.ContentType.NONE)) { - preFilters.add(node); - } else if (lhsType == ColumnParseNodeVisitor.ContentType.FOREIGN_ONLY - && rhsType == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - conditions.add(node); - leftTableRefs.addAll(lhsVisitor.getTableRefSet()); - } else if (rhsType == ColumnParseNodeVisitor.ContentType.FOREIGN_ONLY - && lhsType == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - conditions.add(NODE_FACTORY.equal(node.getRHS(), node.getLHS())); - leftTableRefs.addAll(rhsVisitor.getTableRefSet()); - } else { - throwUnsupportedJoinConditionException(); - } - return null; - } - - @Override - public Void visitLeave(NotParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(InListParseNode node, - List l) throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(IsNullParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(FunctionParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(BetweenParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(CaseParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - @Override - public Void visitLeave(CastParseNode node, List l) - throws SQLException { - return leaveNonEqBooleanNode(node, l); - } - - /* - * Conditions in the ON clause can only be: - * 1) an equal test between a self table expression and a foreign - * table expression. - * 2) a boolean condition referencing to the self table only. - * Otherwise, it can be ambiguous. - */ - private void throwUnsupportedJoinConditionException() - throws SQLFeatureNotSupportedException { - throw new SQLFeatureNotSupportedException("Does not support non-standard or non-equi join conditions."); - } - } - } - - private static class ColumnParseNodeVisitor extends StatelessTraverseAllParseNodeVisitor { - public enum ContentType {NONE, SELF_ONLY, FOREIGN_ONLY, COMPLEX}; - - private ColumnResolver resolver; - private final Set tableRefSet; - private final Map columnRefMap; - - public ColumnParseNodeVisitor(ColumnResolver resolver) { - this.resolver = resolver; - this.tableRefSet = new HashSet(); - this.columnRefMap = new HashMap(); - } - - public void reset() { - this.tableRefSet.clear(); - this.columnRefMap.clear(); - } - - @Override - public Void visit(ColumnParseNode node) throws SQLException { - ColumnRef columnRef = resolver.resolveColumn(node.getSchemaName(), node.getTableName(), node.getName()); - columnRefMap.put(columnRef, node); - tableRefSet.add(columnRef.getTableRef()); - return null; - } - - public Set getTableRefSet() { - return tableRefSet; - } - - public Map getColumnRefMap() { - return columnRefMap; - } - - public ContentType getContentType(TableRef selfTable) { - if (tableRefSet.isEmpty()) - return ContentType.NONE; - if (tableRefSet.size() > 1) - return ContentType.COMPLEX; - if (tableRefSet.contains(selfTable)) - return ContentType.SELF_ONLY; - return ContentType.FOREIGN_ONLY; - } - } - - private static String PROJECTED_TABLE_SCHEMA = "."; - // for creation of new statements - private static ParseNodeFactory NODE_FACTORY = new ParseNodeFactory(); - - private static boolean isWildCardSelect(List select) { - return (select.size() == 1 && select.get(0).getNode() == WildcardParseNode.INSTANCE); - } - - private static List extractFromSelect(List select, TableRef table, ColumnResolver resolver) throws SQLException { - List ret = new ArrayList(); - if (isWildCardSelect(select)) { - ret.add(NODE_FACTORY.aliasedNode(null, WildcardParseNode.INSTANCE)); - return ret; - } - - ColumnParseNodeVisitor visitor = new ColumnParseNodeVisitor(resolver); - for (AliasedNode node : select) { - node.getNode().accept(visitor); - ColumnParseNodeVisitor.ContentType type = visitor.getContentType(table); - if (type == ColumnParseNodeVisitor.ContentType.SELF_ONLY) { - ret.add(node); - } else if (type == ColumnParseNodeVisitor.ContentType.COMPLEX) { - for (Map.Entry entry : visitor.getColumnRefMap().entrySet()) { - if (entry.getKey().getTableRef().equals(table)) { - ret.add(NODE_FACTORY.aliasedNode(null, entry.getValue())); - } - } - } - visitor.reset(); - } - return ret; - } - - public static JoinSpec getJoinSpec(StatementContext context, SelectStatement statement) throws SQLException { - return new JoinSpec(statement, context.getResolver()); - } - - public static SelectStatement optimize(StatementContext context, SelectStatement select, PhoenixStatement statement) throws SQLException { - ColumnResolver resolver = context.getResolver(); - JoinSpec join = new JoinSpec(select, resolver); - Map replacement = new HashMap(); - List from = select.getFrom(); - List newFrom = Lists.newArrayListWithExpectedSize(from.size()); - - class TableNodeRewriter implements TableNodeVisitor { - private TableRef table; - private TableNode replaced; - - TableNodeRewriter(TableRef table) { - this.table = table; - } - - public TableNode getReplacedTableNode() { - return replaced; - } - - @Override - public void visit(BindTableNode boundTableNode) throws SQLException { - replaced = NODE_FACTORY.bindTable(boundTableNode.getAlias(), getReplacedTableName()); - } - - @Override - public void visit(JoinTableNode joinNode) throws SQLException { - joinNode.getTable().accept(this); - replaced = NODE_FACTORY.join(joinNode.getType(), joinNode.getOnNode(), replaced); - } - - @Override - public void visit(NamedTableNode namedTableNode) - throws SQLException { - replaced = NODE_FACTORY.namedTable(namedTableNode.getAlias(), getReplacedTableName(), namedTableNode.getDynamicColumns()); - } - - @Override - public void visit(DerivedTableNode subselectNode) - throws SQLException { - throw new SQLFeatureNotSupportedException(); - } - - private TableName getReplacedTableName() { - String schemaName = table.getTable().getSchemaName().getString(); - schemaName = schemaName.length() == 0 ? null : '"' + schemaName + '"'; - String tableName = '"' + table.getTable().getTableName().getString() + '"'; - return NODE_FACTORY.table(schemaName, tableName); - } - }; - - // get optimized plans for join tables - for (int i = 1; i < from.size(); i++) { - TableNode jNode = from.get(i); - assert (jNode instanceof JoinTableNode); - TableNode tNode = ((JoinTableNode) jNode).getTable(); - for (JoinTable jTable : join.getJoinTables()) { - if (jTable.getTableNode() != tNode) - continue; - TableRef table = jTable.getTable(); - SelectStatement stmt = getSubqueryForOptimizedPlan(select, table, join.columnRefs, jTable.getPreFiltersCombined()); - QueryPlan plan = context.getConnection().getQueryServices().getOptimizer().optimize(stmt, statement); - if (!plan.getTableRef().equals(table)) { - TableNodeRewriter rewriter = new TableNodeRewriter(plan.getTableRef()); - jNode.accept(rewriter); - newFrom.add(rewriter.getReplacedTableNode()); - replacement.put(table, plan.getTableRef()); - } else { - newFrom.add(jNode); - } - } - } - // get optimized plan for main table - TableRef table = join.getMainTable(); - SelectStatement stmt = getSubqueryForOptimizedPlan(select, table, join.columnRefs, join.getPreFiltersCombined()); - QueryPlan plan = context.getConnection().getQueryServices().getOptimizer().optimize(stmt, statement); - if (!plan.getTableRef().equals(table)) { - TableNodeRewriter rewriter = new TableNodeRewriter(plan.getTableRef()); - from.get(0).accept(rewriter); - newFrom.add(0, rewriter.getReplacedTableNode()); - replacement.put(table, plan.getTableRef()); - } else { - newFrom.add(0, from.get(0)); - } - - if (replacement.isEmpty()) - return select; - - return IndexStatementRewriter.translate(NODE_FACTORY.select(select, newFrom), resolver, replacement); - } - - private static SelectStatement getSubqueryForOptimizedPlan(SelectStatement select, TableRef table, Set columnRefs, ParseNode where) { - TableName tName = NODE_FACTORY.table(table.getTable().getSchemaName().getString(), table.getTable().getTableName().getString()); - List selectList = new ArrayList(); - if (isWildCardSelect(select.getSelect())) { - selectList.add(NODE_FACTORY.aliasedNode(null, WildcardParseNode.INSTANCE)); - } else { - for (ColumnRef colRef : columnRefs) { - if (colRef.getTableRef().equals(table)) { - selectList.add(NODE_FACTORY.aliasedNode(null, NODE_FACTORY.column(tName, colRef.getColumn().getName().getString(), null))); - } - } - } - List from = Collections.singletonList(NODE_FACTORY.namedTable(table.getTableAlias(), tName)); - - return NODE_FACTORY.select(from, select.getHint(), false, selectList, where, null, null, null, null, 0, false); - } - - /** - * Returns a boolean vector indicating whether the evaluation of join expressions - * can be evaluated at an early stage if the input JoinSpec can be taken as a - * star join. Otherwise returns null. - * @param join the JoinSpec - * @return a boolean vector for a star join; or null for non star join. - */ - public static boolean[] getStarJoinVector(JoinSpec join) { - assert(!join.getJoinTables().isEmpty()); - - int count = join.getJoinTables().size(); - boolean[] vector = new boolean[count]; - for (int i = 0; i < count; i++) { - JoinTable joinTable = join.getJoinTables().get(i); - if (joinTable.getType() != JoinType.Left - && joinTable.getType() != JoinType.Inner) - return null; - vector[i] = true; - Iterator iter = joinTable.getLeftTableRefs().iterator(); - while (vector[i] == true && iter.hasNext()) { - TableRef tableRef = iter.next(); - if (!tableRef.equals(join.getMainTable())) { - vector[i] = false; - } - } - } - - return vector; - } - - public static SelectStatement getSubqueryWithoutJoin(SelectStatement statement, JoinSpec join) { - return NODE_FACTORY.select(statement.getFrom().subList(0, 1), statement.getHint(), statement.isDistinct(), statement.getSelect(), join.getPreFiltersCombined(), statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate()); - } - - // Get the last join table select statement with fixed-up select and where nodes. - // Currently does NOT support last join table as a subquery. - public static SelectStatement getSubqueryForLastJoinTable(SelectStatement statement, JoinSpec join) throws SQLException { - List joinTables = join.getJoinTables(); - int count = joinTables.size(); - assert (count > 0); - JoinTable lastJoinTable = joinTables.get(count - 1); - if (lastJoinTable.getSubquery() != null) { - throw new SQLFeatureNotSupportedException("Subqueries not supported."); - } - List from = new ArrayList(1); - from.add(lastJoinTable.getTableNode()); - - return NODE_FACTORY.select(from, statement.getHint(), statement.isDistinct(), statement.getSelect(), lastJoinTable.getPreFiltersCombined(), statement.getGroupBy(), statement.getHaving(), statement.getOrderBy(), statement.getLimit(), statement.getBindCount(), statement.isAggregate()); - } - - // Get subquery with fixed select and where nodes - public static SelectStatement getSubQueryWithoutLastJoin(SelectStatement statement, JoinSpec join) { - List from = statement.getFrom(); - assert(from.size() > 1); - List joinTables = join.getJoinTables(); - int count = joinTables.size(); - assert (count > 0); - List select = new ArrayList(); - select.addAll(join.getSelect()); - for (int i = 0; i < count - 1; i++) { - select.addAll(joinTables.get(i).getSelect()); - } - - return NODE_FACTORY.select(from.subList(0, from.size() - 1), statement.getHint(), false, select, join.getPreFiltersCombined(), null, null, null, null, statement.getBindCount(), false); - } - - public static PTableWrapper mergeProjectedTables(PTableWrapper lWrapper, PTableWrapper rWrapper, boolean innerJoin) throws SQLException { - PTable left = lWrapper.getTable(); - PTable right = rWrapper.getTable(); - List merged = new ArrayList(); - merged.addAll(left.getColumns()); - int position = merged.size(); - for (PColumn c : right.getColumns()) { - if (!SchemaUtil.isPKColumn(c)) { - PColumnImpl column = new PColumnImpl(c.getName(), - PNameFactory.newName(ScanProjector.VALUE_COLUMN_FAMILY), c.getDataType(), - c.getMaxLength(), c.getScale(), innerJoin ? c.isNullable() : true, position++, - c.getColumnModifier()); - merged.add(column); - } - } - if (left.getBucketNum() != null) { - merged.remove(0); - } - PTable t = PTableImpl.makePTable(left.getSchemaName(), PNameFactory.newName(SchemaUtil.getTableName(left.getName().getString(), right.getName().getString())), left.getType(), left.getIndexState(), left.getTimeStamp(), left.getSequenceNumber(), left.getPKName(), left.getBucketNum(), merged, left.getParentTableName(), left.getIndexes(), left.isImmutableRows(), null, null, null, PTable.DEFAULT_DISABLE_WAL); - - ListMultimap mergedMap = ArrayListMultimap.create(); - mergedMap.putAll(lWrapper.getColumnNameMap()); - mergedMap.putAll(rWrapper.getColumnNameMap()); - - return new PTableWrapper(t, mergedMap); - } - - public static ScanProjector getScanProjector(ProjectedPTableWrapper table) { - return new ScanProjector(table); - } - - public static class PTableWrapper { - protected PTable table; - protected ListMultimap columnNameMap; - - protected PTableWrapper(PTable table, ListMultimap columnNameMap) { - this.table = table; - this.columnNameMap = columnNameMap; - } - - public PTable getTable() { - return table; - } - - public ListMultimap getColumnNameMap() { - return columnNameMap; - } - - public List getMappedColumnName(String name) { - return columnNameMap.get(name); - } - } - - public static class ProjectedPTableWrapper extends PTableWrapper { - private List sourceExpressions; - - protected ProjectedPTableWrapper(PTable table, ListMultimap columnNameMap, List sourceExpressions) { - super(table, columnNameMap); - this.sourceExpressions = sourceExpressions; - } - - public Expression getSourceExpression(PColumn column) { - return sourceExpressions.get(column.getPosition()); - } - } - - public static ColumnResolver getColumnResolver(PTableWrapper table) { - return new JoinedTableColumnResolver(table); - } - - public static class JoinedTableColumnResolver implements ColumnResolver { - private PTableWrapper table; - private List tableRefs; - - private JoinedTableColumnResolver(PTableWrapper table) { - this.table = table; - TableRef tableRef = new TableRef(null, table.getTable(), 0, false); - this.tableRefs = ImmutableList.of(tableRef); - } - - @Override - public List getTables() { - return tableRefs; - } - - public PTableWrapper getPTableWrapper() { - return table; - } - - @Override - public ColumnRef resolveColumn(String schemaName, String tableName, - String colName) throws SQLException { - String name = getProjectedColumnName(schemaName, tableName, colName); - TableRef tableRef = tableRefs.get(0); - try { - PColumn column = tableRef.getTable().getColumn(name); - return new ColumnRef(tableRef, column.getPosition()); - } catch (ColumnNotFoundException e) { - List names = table.getMappedColumnName(name); - if (names.size() == 1) { - PColumn column = tableRef.getTable().getColumn(names.get(0)); - return new ColumnRef(tableRef, column.getPosition()); - } - - if (names.size() > 1) { - throw new AmbiguousColumnException(name); - } - - throw e; - } - } - } - - private static String getProjectedColumnName(String schemaName, String tableName, - String colName) { - return SchemaUtil.getColumnName(SchemaUtil.getTableName(schemaName, tableName), colName); - } - - private static PName getProjectedColumnName(PName schemaName, PName tableName, - PName colName) { - String name = getProjectedColumnName(schemaName.getString(), tableName.getString(), colName.getString()); - return PNameFactory.newName(name); - } -} diff --git a/All/Genesis-NP/Genesis#258/pair.info b/All/Genesis-NP/Genesis#258/pair.info deleted file mode 100755 index ee80313..0000000 --- a/All/Genesis-NP/Genesis#258/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:258 -SATName:Genesis -modifiedFPath:src/main/java/com/salesforce/phoenix/compile/JoinCompiler.java -comSha:a5fe9eb35903b702bad1308a84959a639302877a -parentComSha:a5fe9eb35903b702bad1308a84959a639302877a^1 -githubUrl:https://github.com/forcedotcom/phoenix -repoName:forcedotcom#phoenix \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#263/comMsg.txt b/All/Genesis-NP/Genesis#263/comMsg.txt deleted file mode 100755 index 098afe1..0000000 --- a/All/Genesis-NP/Genesis#263/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE when getting query parameters without a value: ?nothing=&some=thing diff --git a/All/Genesis-NP/Genesis#263/diff.diff b/All/Genesis-NP/Genesis#263/diff.diff deleted file mode 100755 index d63a441..0000000 --- a/All/Genesis-NP/Genesis#263/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/src/main/java/org/webbitserver/helpers/QueryParameters.java b/src/main/java/org/webbitserver/helpers/QueryParameters.java -index 1cefeff..177d0e3 100644 ---- a/src/main/java/org/webbitserver/helpers/QueryParameters.java -+++ b/src/main/java/org/webbitserver/helpers/QueryParameters.java -@@ -24 +24 @@ public class QueryParameters { -- String value = URLDecoder.decode(pair[1], "UTF-8"); -+ String value = pair.length == 1 ? null : URLDecoder.decode(pair[1], "UTF-8"); diff --git a/All/Genesis-NP/Genesis#263/new/HISTORY.md b/All/Genesis-NP/Genesis#263/new/HISTORY.md deleted file mode 100755 index 59eaf44..0000000 --- a/All/Genesis-NP/Genesis#263/new/HISTORY.md +++ /dev/null @@ -1,26 +0,0 @@ -0.1.12 (In Git) -================== - -* Fixed NPE when getting query parameters without a value: ?nothing=&some=thing (Aslak Hellesøy) -* Added EventSourceConnection.send(EventSourceMessage) (Aslak Hellesøy) - -0.1.11 (2011-03-30) -================== - -* Fixed a bug where static (embedded) resources were served improperly if they were of a certain size (Aslak Hellesøy) - -0.1.10 (2011-03-30) -================== - -* Added support for [Server-Sent Events/EventSource](http://dev.w3.org/html5/eventsource/) (#18 Aslak Hellesøy) -* Requests with full url as request uri (and not only path) are correctly matched. (Aslak Hellesøy) -* Added HttpRequest.queryParam(String key) and HttpRequest.queryParams(String key) (#20 Aslak Hellesøy) -* Added new AliasHandler for forwarding requests. (Aslak Hellesøy) -* Made it possible to call NettyHttpResponse.content() more than once. (Aslak Hellesøy) -* Added support for cookies. (#19 Aslak Hellesøy) -* Added HttpRequest.body() method. (Aslak Hellesøy) - -0.1.1 (2011-02-19) -================== - -* First release \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#263/new/QueryParameters.java b/All/Genesis-NP/Genesis#263/new/QueryParameters.java deleted file mode 100755 index 177d0e3..0000000 --- a/All/Genesis-NP/Genesis#263/new/QueryParameters.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.webbitserver.helpers; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.*; - -public class QueryParameters { - private final Map> params = new HashMap>(); - private static final List EMPTY = Collections.emptyList(); - - public QueryParameters(String query) { - if (query != null) { - parse(query); - } - } - - private void parse(String query) { - try { - // StringTokenizer is faster than split. http://www.javamex.com/tutorials/regular_expressions/splitting_tokenisation_performance.shtml - StringTokenizer st = new StringTokenizer(query, "&"); - while (st.hasMoreTokens()) { - String[] pair = st.nextToken().split("="); - String key = URLDecoder.decode(pair[0], "UTF-8"); - String value = pair.length == 1 ? null : URLDecoder.decode(pair[1], "UTF-8"); - List values = params.get(key); - if (values == null) { - values = new ArrayList(); - params.put(key, values); - } - values.add(value); - } - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("Couldn't parse query string: " + query, e); - } - } - - public String first(String key) { - List all = all(key); - return all.isEmpty() ? null : all.get(0); - } - - public List all(String key) { - return params.containsKey(key) ? params.get(key) : EMPTY; - } - - public Set keys() { - return params.keySet(); - } -} diff --git a/All/Genesis-NP/Genesis#263/old/HISTORY.md b/All/Genesis-NP/Genesis#263/old/HISTORY.md deleted file mode 100755 index 30f54b4..0000000 --- a/All/Genesis-NP/Genesis#263/old/HISTORY.md +++ /dev/null @@ -1,25 +0,0 @@ -0.1.12 (In Git) -================== - -* Added EventSourceConnection.send(EventSourceMessage) (Aslak Hellesøy) - -0.1.11 (2011-03-30) -================== - -* Fixed a bug where static (embedded) resources were served improperly if they were of a certain size (Aslak Hellesøy) - -0.1.10 (2011-03-30) -================== - -* Added support for [Server-Sent Events/EventSource](http://dev.w3.org/html5/eventsource/) (#18 Aslak Hellesøy) -* Requests with full url as request uri (and not only path) are correctly matched. (Aslak Hellesøy) -* Added HttpRequest.queryParam(String key) and HttpRequest.queryParams(String key) (#20 Aslak Hellesøy) -* Added new AliasHandler for forwarding requests. (Aslak Hellesøy) -* Made it possible to call NettyHttpResponse.content() more than once. (Aslak Hellesøy) -* Added support for cookies. (#19 Aslak Hellesøy) -* Added HttpRequest.body() method. (Aslak Hellesøy) - -0.1.1 (2011-02-19) -================== - -* First release \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#263/old/QueryParameters.java b/All/Genesis-NP/Genesis#263/old/QueryParameters.java deleted file mode 100755 index 1cefeff..0000000 --- a/All/Genesis-NP/Genesis#263/old/QueryParameters.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.webbitserver.helpers; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.util.*; - -public class QueryParameters { - private final Map> params = new HashMap>(); - private static final List EMPTY = Collections.emptyList(); - - public QueryParameters(String query) { - if (query != null) { - parse(query); - } - } - - private void parse(String query) { - try { - // StringTokenizer is faster than split. http://www.javamex.com/tutorials/regular_expressions/splitting_tokenisation_performance.shtml - StringTokenizer st = new StringTokenizer(query, "&"); - while (st.hasMoreTokens()) { - String[] pair = st.nextToken().split("="); - String key = URLDecoder.decode(pair[0], "UTF-8"); - String value = URLDecoder.decode(pair[1], "UTF-8"); - List values = params.get(key); - if (values == null) { - values = new ArrayList(); - params.put(key, values); - } - values.add(value); - } - } catch (UnsupportedEncodingException e) { - throw new RuntimeException("Couldn't parse query string: " + query, e); - } - } - - public String first(String key) { - List all = all(key); - return all.isEmpty() ? null : all.get(0); - } - - public List all(String key) { - return params.containsKey(key) ? params.get(key) : EMPTY; - } - - public Set keys() { - return params.keySet(); - } -} diff --git a/All/Genesis-NP/Genesis#263/pair.info b/All/Genesis-NP/Genesis#263/pair.info deleted file mode 100755 index 2d79a90..0000000 --- a/All/Genesis-NP/Genesis#263/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:263 -SATName:Genesis -modifiedFPath:src/main/java/org/webbitserver/helpers/QueryParameters.java -comSha:9063bbb61f9a732925fcab0e20de188ccaca6c9e -parentComSha:9063bbb61f9a732925fcab0e20de188ccaca6c9e^1 -githubUrl:https://github.com/webbit/webbit -repoName:webbit#webbit \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#266/comMsg.txt b/All/Genesis-NP/Genesis#266/comMsg.txt deleted file mode 100755 index 743b74a..0000000 --- a/All/Genesis-NP/Genesis#266/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE in DisruptorCommandBus diff --git a/All/Genesis-NP/Genesis#266/diff.diff b/All/Genesis-NP/Genesis#266/diff.diff deleted file mode 100755 index e289edb..0000000 --- a/All/Genesis-NP/Genesis#266/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/core/src/main/java/org/axonframework/commandhandling/disruptor/EventPublisher.java b/core/src/main/java/org/axonframework/commandhandling/disruptor/EventPublisher.java -index 936177f..d4a1d75 100644 ---- a/core/src/main/java/org/axonframework/commandhandling/disruptor/EventPublisher.java -+++ b/core/src/main/java/org/axonframework/commandhandling/disruptor/EventPublisher.java -@@ -196,0 +197 @@ private Throwable performCommit(DisruptorUnitOfWork unitOfWork, EventSourcedAggr -+ try { -@@ -199,0 +201,4 @@ private Throwable performCommit(DisruptorUnitOfWork unitOfWork, EventSourcedAggr -+ } catch (Exception te) { -+ logger.info("Failed to explicitly rollback the transaction: ", te); -+ } -+ if (aggregate != null) { -@@ -200,0 +206,3 @@ private Throwable performCommit(DisruptorUnitOfWork unitOfWork, EventSourcedAggr -+ } else { -+ exceptionResult = e; -+ } diff --git a/All/Genesis-NP/Genesis#266/new/EventPublisher.java b/All/Genesis-NP/Genesis#266/new/EventPublisher.java deleted file mode 100755 index d4a1d75..0000000 --- a/All/Genesis-NP/Genesis#266/new/EventPublisher.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * Copyright (c) 2010-2014. Axon Framework - * - * 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.axonframework.commandhandling.disruptor; - -import com.lmax.disruptor.EventHandler; -import org.axonframework.commandhandling.CommandCallback; -import org.axonframework.commandhandling.CommandMessage; -import org.axonframework.commandhandling.RollbackConfiguration; -import org.axonframework.domain.DomainEventStream; -import org.axonframework.domain.EventMessage; -import org.axonframework.eventhandling.EventBus; -import org.axonframework.eventsourcing.EventSourcedAggregateRoot; -import org.axonframework.eventstore.EventStore; -import org.axonframework.repository.AggregateNotFoundException; -import org.axonframework.unitofwork.CurrentUnitOfWork; -import org.axonframework.unitofwork.TransactionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.WeakHashMap; -import java.util.concurrent.Executor; - -import static java.lang.String.format; - -/** - * Component of the DisruptorCommandBus that stores and publishes events generated by the command's execution. - * - * @author Allard Buijze - * @since 2.0 - */ -public class EventPublisher implements EventHandler { - - private static final Logger logger = LoggerFactory.getLogger(DisruptorCommandBus.class); - - private final EventStore eventStore; - private final EventBus eventBus; - private final Executor executor; - private final RollbackConfiguration rollbackConfiguration; - private final int segmentId; - private final Set blackListedAggregates = new HashSet(); - private final Map failedCreateCommands = new WeakHashMap(); - private final TransactionManager transactionManager; - - /** - * Initializes the EventPublisher to publish Events to the given eventStore and eventBus - * for aggregate of given aggregateType. - * - * @param eventStore The EventStore persisting the generated events - * @param eventBus The EventBus to publish events on - * @param executor The executor which schedules response reporting - * @param transactionManager The transaction manager that manages the transaction around event storage and - * publication - * @param rollbackConfiguration The configuration that indicates which exceptions should result in a UnitOfWork - * @param segmentId The ID of the segment this publisher should handle - */ - public EventPublisher(EventStore eventStore, EventBus eventBus, Executor executor, - TransactionManager transactionManager, RollbackConfiguration rollbackConfiguration, - int segmentId) { - this.eventStore = eventStore; - this.eventBus = eventBus; - this.executor = executor; - this.transactionManager = transactionManager; - this.rollbackConfiguration = rollbackConfiguration; - this.segmentId = segmentId; - } - - @SuppressWarnings({"unchecked", "ThrowableResultOfMethodCallIgnored"}) - @Override - public void onEvent(CommandHandlingEntry entry, long sequence, boolean endOfBatch) throws Exception { - if (entry.isRecoverEntry()) { - recoverAggregate(entry); - } else if (entry.getPublisherId() == segmentId) { - if (entry.getExceptionResult() instanceof AggregateNotFoundException - && failedCreateCommands.remove(entry.getCommand()) == null) { - // the command failed for the first time - reschedule(entry); - } else { - DisruptorUnitOfWork unitOfWork = entry.getUnitOfWork(); - CurrentUnitOfWork.set(unitOfWork); - try { - EventSourcedAggregateRoot aggregate = unitOfWork.getAggregate(); - if (aggregate != null && blackListedAggregates.contains(aggregate.getIdentifier())) { - rejectExecution(entry, unitOfWork, entry.getAggregateIdentifier()); - } else { - processPublication(entry, unitOfWork, aggregate); - } - } finally { - CurrentUnitOfWork.clear(unitOfWork); - } - } - } - } - - @SuppressWarnings("unchecked") - private void reschedule(CommandHandlingEntry entry) { - failedCreateCommands.put(entry.getCommand(), logger); - executor.execute(new ReportResultTask( - entry.getCallback(), null, - new AggregateStateCorruptedException( - entry.getAggregateIdentifier(), "Rescheduling command for execution. " - + "It was executed against a potentially recently created command"))); - } - - private void recoverAggregate(CommandHandlingEntry entry) { - if (blackListedAggregates.remove(entry.getAggregateIdentifier())) { - logger.info("Reset notification for {} received. The aggregate is removed from the blacklist", - entry.getAggregateIdentifier()); - } - } - - @SuppressWarnings("unchecked") - private void rejectExecution(CommandHandlingEntry entry, DisruptorUnitOfWork unitOfWork, - Object aggregateIdentifier) { - executor.execute(new ReportResultTask( - entry.getCallback(), null, - new AggregateStateCorruptedException( - unitOfWork.getAggregate(), - format("Aggregate %s has been blacklisted and will be ignored until " - + "its state has been recovered.", - aggregateIdentifier)))); - } - - @SuppressWarnings("unchecked") - private void processPublication(CommandHandlingEntry entry, DisruptorUnitOfWork unitOfWork, - EventSourcedAggregateRoot aggregate) { - invokeInterceptorChain(entry); - Throwable exceptionResult = entry.getExceptionResult(); - try { - if (exceptionResult != null && rollbackConfiguration.rollBackOn(exceptionResult)) { - exceptionResult = performRollback(unitOfWork, entry.getAggregateIdentifier(), exceptionResult); - } else { - exceptionResult = performCommit(unitOfWork, aggregate, exceptionResult); - } - } finally { - unitOfWork.onCleanup(); - } - if (exceptionResult != null || entry.getCallback().hasDelegate()) { - executor.execute(new ReportResultTask(entry.getCallback(), entry.getResult(), exceptionResult)); - } - } - - private void invokeInterceptorChain(CommandHandlingEntry entry) { - try { - entry.setResult(entry.getPublisherInterceptorChain().proceed(entry.getCommand())); - } catch (Throwable throwable) { - entry.setExceptionResult(throwable); - } - } - - private Throwable performRollback(DisruptorUnitOfWork unitOfWork, Object aggregateIdentifier, - Throwable exceptionResult) { - unitOfWork.onRollback(exceptionResult); - if (aggregateIdentifier != null) { - exceptionResult = notifyBlacklisted(unitOfWork, aggregateIdentifier, exceptionResult); - } - return exceptionResult; - } - - @SuppressWarnings("unchecked") - private Throwable performCommit(DisruptorUnitOfWork unitOfWork, EventSourcedAggregateRoot aggregate, - Throwable exceptionResult) { - unitOfWork.onPrepareCommit(); - Object transaction = null; - try { - if (exceptionResult != null && rollbackConfiguration.rollBackOn(exceptionResult)) { - unitOfWork.rollback(exceptionResult); - } else { - if (transactionManager != null) { - transaction = transactionManager.startTransaction(); - } - storeAndPublish(unitOfWork); - if (transaction != null) { - unitOfWork.onPrepareTransactionCommit(transaction); - transactionManager.commitTransaction(transaction); - } - unitOfWork.onAfterCommit(); - } - } catch (Exception e) { - try { - if (transaction != null) { - transactionManager.rollbackTransaction(transaction); - } - } catch (Exception te) { - logger.info("Failed to explicitly rollback the transaction: ", te); - } - if (aggregate != null) { - exceptionResult = notifyBlacklisted(unitOfWork, aggregate.getIdentifier(), e); - } else { - exceptionResult = e; - } - } - return exceptionResult; - } - - private void storeAndPublish(DisruptorUnitOfWork unitOfWork) { - DomainEventStream eventsToStore = unitOfWork.getEventsToStore(); - if (eventsToStore.hasNext()) { - eventStore.appendEvents(unitOfWork.getAggregateType(), eventsToStore); - } - List eventMessages = unitOfWork.getEventsToPublish(); - EventMessage[] eventsToPublish = eventMessages.toArray(new EventMessage[eventMessages.size()]); - if (eventBus != null && eventsToPublish.length > 0) { - eventBus.publish(eventsToPublish); - } - } - - private Throwable notifyBlacklisted(DisruptorUnitOfWork unitOfWork, Object aggregateIdentifier, - Throwable cause) { - Throwable exceptionResult; - blackListedAggregates.add(aggregateIdentifier); - exceptionResult = new AggregateBlacklistedException( - aggregateIdentifier, - format("Aggregate %s state corrupted. " - + "Blacklisting the aggregate until a reset message has been received", - aggregateIdentifier), cause); - unitOfWork.onRollback(exceptionResult); - return exceptionResult; - } - - private static class ReportResultTask implements Runnable { - - private final CommandCallback callback; - private final R result; - private final Throwable exceptionResult; - - public ReportResultTask(CommandCallback callback, R result, Throwable exceptionResult) { - this.callback = callback; - this.result = result; - this.exceptionResult = exceptionResult; - } - - @Override - public void run() { - if (exceptionResult != null) { - callback.onFailure(exceptionResult); - } else { - callback.onSuccess(result); - } - } - } -} diff --git a/All/Genesis-NP/Genesis#266/old/EventPublisher.java b/All/Genesis-NP/Genesis#266/old/EventPublisher.java deleted file mode 100755 index 936177f..0000000 --- a/All/Genesis-NP/Genesis#266/old/EventPublisher.java +++ /dev/null @@ -1,251 +0,0 @@ -/* - * Copyright (c) 2010-2014. Axon Framework - * - * 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.axonframework.commandhandling.disruptor; - -import com.lmax.disruptor.EventHandler; -import org.axonframework.commandhandling.CommandCallback; -import org.axonframework.commandhandling.CommandMessage; -import org.axonframework.commandhandling.RollbackConfiguration; -import org.axonframework.domain.DomainEventStream; -import org.axonframework.domain.EventMessage; -import org.axonframework.eventhandling.EventBus; -import org.axonframework.eventsourcing.EventSourcedAggregateRoot; -import org.axonframework.eventstore.EventStore; -import org.axonframework.repository.AggregateNotFoundException; -import org.axonframework.unitofwork.CurrentUnitOfWork; -import org.axonframework.unitofwork.TransactionManager; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.WeakHashMap; -import java.util.concurrent.Executor; - -import static java.lang.String.format; - -/** - * Component of the DisruptorCommandBus that stores and publishes events generated by the command's execution. - * - * @author Allard Buijze - * @since 2.0 - */ -public class EventPublisher implements EventHandler { - - private static final Logger logger = LoggerFactory.getLogger(DisruptorCommandBus.class); - - private final EventStore eventStore; - private final EventBus eventBus; - private final Executor executor; - private final RollbackConfiguration rollbackConfiguration; - private final int segmentId; - private final Set blackListedAggregates = new HashSet(); - private final Map failedCreateCommands = new WeakHashMap(); - private final TransactionManager transactionManager; - - /** - * Initializes the EventPublisher to publish Events to the given eventStore and eventBus - * for aggregate of given aggregateType. - * - * @param eventStore The EventStore persisting the generated events - * @param eventBus The EventBus to publish events on - * @param executor The executor which schedules response reporting - * @param transactionManager The transaction manager that manages the transaction around event storage and - * publication - * @param rollbackConfiguration The configuration that indicates which exceptions should result in a UnitOfWork - * @param segmentId The ID of the segment this publisher should handle - */ - public EventPublisher(EventStore eventStore, EventBus eventBus, Executor executor, - TransactionManager transactionManager, RollbackConfiguration rollbackConfiguration, - int segmentId) { - this.eventStore = eventStore; - this.eventBus = eventBus; - this.executor = executor; - this.transactionManager = transactionManager; - this.rollbackConfiguration = rollbackConfiguration; - this.segmentId = segmentId; - } - - @SuppressWarnings({"unchecked", "ThrowableResultOfMethodCallIgnored"}) - @Override - public void onEvent(CommandHandlingEntry entry, long sequence, boolean endOfBatch) throws Exception { - if (entry.isRecoverEntry()) { - recoverAggregate(entry); - } else if (entry.getPublisherId() == segmentId) { - if (entry.getExceptionResult() instanceof AggregateNotFoundException - && failedCreateCommands.remove(entry.getCommand()) == null) { - // the command failed for the first time - reschedule(entry); - } else { - DisruptorUnitOfWork unitOfWork = entry.getUnitOfWork(); - CurrentUnitOfWork.set(unitOfWork); - try { - EventSourcedAggregateRoot aggregate = unitOfWork.getAggregate(); - if (aggregate != null && blackListedAggregates.contains(aggregate.getIdentifier())) { - rejectExecution(entry, unitOfWork, entry.getAggregateIdentifier()); - } else { - processPublication(entry, unitOfWork, aggregate); - } - } finally { - CurrentUnitOfWork.clear(unitOfWork); - } - } - } - } - - @SuppressWarnings("unchecked") - private void reschedule(CommandHandlingEntry entry) { - failedCreateCommands.put(entry.getCommand(), logger); - executor.execute(new ReportResultTask( - entry.getCallback(), null, - new AggregateStateCorruptedException( - entry.getAggregateIdentifier(), "Rescheduling command for execution. " - + "It was executed against a potentially recently created command"))); - } - - private void recoverAggregate(CommandHandlingEntry entry) { - if (blackListedAggregates.remove(entry.getAggregateIdentifier())) { - logger.info("Reset notification for {} received. The aggregate is removed from the blacklist", - entry.getAggregateIdentifier()); - } - } - - @SuppressWarnings("unchecked") - private void rejectExecution(CommandHandlingEntry entry, DisruptorUnitOfWork unitOfWork, - Object aggregateIdentifier) { - executor.execute(new ReportResultTask( - entry.getCallback(), null, - new AggregateStateCorruptedException( - unitOfWork.getAggregate(), - format("Aggregate %s has been blacklisted and will be ignored until " - + "its state has been recovered.", - aggregateIdentifier)))); - } - - @SuppressWarnings("unchecked") - private void processPublication(CommandHandlingEntry entry, DisruptorUnitOfWork unitOfWork, - EventSourcedAggregateRoot aggregate) { - invokeInterceptorChain(entry); - Throwable exceptionResult = entry.getExceptionResult(); - try { - if (exceptionResult != null && rollbackConfiguration.rollBackOn(exceptionResult)) { - exceptionResult = performRollback(unitOfWork, entry.getAggregateIdentifier(), exceptionResult); - } else { - exceptionResult = performCommit(unitOfWork, aggregate, exceptionResult); - } - } finally { - unitOfWork.onCleanup(); - } - if (exceptionResult != null || entry.getCallback().hasDelegate()) { - executor.execute(new ReportResultTask(entry.getCallback(), entry.getResult(), exceptionResult)); - } - } - - private void invokeInterceptorChain(CommandHandlingEntry entry) { - try { - entry.setResult(entry.getPublisherInterceptorChain().proceed(entry.getCommand())); - } catch (Throwable throwable) { - entry.setExceptionResult(throwable); - } - } - - private Throwable performRollback(DisruptorUnitOfWork unitOfWork, Object aggregateIdentifier, - Throwable exceptionResult) { - unitOfWork.onRollback(exceptionResult); - if (aggregateIdentifier != null) { - exceptionResult = notifyBlacklisted(unitOfWork, aggregateIdentifier, exceptionResult); - } - return exceptionResult; - } - - @SuppressWarnings("unchecked") - private Throwable performCommit(DisruptorUnitOfWork unitOfWork, EventSourcedAggregateRoot aggregate, - Throwable exceptionResult) { - unitOfWork.onPrepareCommit(); - Object transaction = null; - try { - if (exceptionResult != null && rollbackConfiguration.rollBackOn(exceptionResult)) { - unitOfWork.rollback(exceptionResult); - } else { - if (transactionManager != null) { - transaction = transactionManager.startTransaction(); - } - storeAndPublish(unitOfWork); - if (transaction != null) { - unitOfWork.onPrepareTransactionCommit(transaction); - transactionManager.commitTransaction(transaction); - } - unitOfWork.onAfterCommit(); - } - } catch (Exception e) { - if (transaction != null) { - transactionManager.rollbackTransaction(transaction); - } - exceptionResult = notifyBlacklisted(unitOfWork, aggregate.getIdentifier(), e); - } - return exceptionResult; - } - - private void storeAndPublish(DisruptorUnitOfWork unitOfWork) { - DomainEventStream eventsToStore = unitOfWork.getEventsToStore(); - if (eventsToStore.hasNext()) { - eventStore.appendEvents(unitOfWork.getAggregateType(), eventsToStore); - } - List eventMessages = unitOfWork.getEventsToPublish(); - EventMessage[] eventsToPublish = eventMessages.toArray(new EventMessage[eventMessages.size()]); - if (eventBus != null && eventsToPublish.length > 0) { - eventBus.publish(eventsToPublish); - } - } - - private Throwable notifyBlacklisted(DisruptorUnitOfWork unitOfWork, Object aggregateIdentifier, - Throwable cause) { - Throwable exceptionResult; - blackListedAggregates.add(aggregateIdentifier); - exceptionResult = new AggregateBlacklistedException( - aggregateIdentifier, - format("Aggregate %s state corrupted. " - + "Blacklisting the aggregate until a reset message has been received", - aggregateIdentifier), cause); - unitOfWork.onRollback(exceptionResult); - return exceptionResult; - } - - private static class ReportResultTask implements Runnable { - - private final CommandCallback callback; - private final R result; - private final Throwable exceptionResult; - - public ReportResultTask(CommandCallback callback, R result, Throwable exceptionResult) { - this.callback = callback; - this.result = result; - this.exceptionResult = exceptionResult; - } - - @Override - public void run() { - if (exceptionResult != null) { - callback.onFailure(exceptionResult); - } else { - callback.onSuccess(result); - } - } - } -} diff --git a/All/Genesis-NP/Genesis#266/pair.info b/All/Genesis-NP/Genesis#266/pair.info deleted file mode 100755 index 33d5566..0000000 --- a/All/Genesis-NP/Genesis#266/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:266 -SATName:Genesis -modifiedFPath:core/src/main/java/org/axonframework/commandhandling/disruptor/EventPublisher.java -comSha:ae24bd391ee13a5f0ca28df4e42a5e9b9adbba81 -parentComSha:ae24bd391ee13a5f0ca28df4e42a5e9b9adbba81^1 -githubUrl:https://github.com/AxonFramework/AxonFramework -repoName:AxonFramework#AxonFramework \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#269/comMsg.txt b/All/Genesis-NP/Genesis#269/comMsg.txt deleted file mode 100755 index 3c13245..0000000 --- a/All/Genesis-NP/Genesis#269/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Avoid another NPE in Partial.with diff --git a/All/Genesis-NP/Genesis#269/diff.diff b/All/Genesis-NP/Genesis#269/diff.diff deleted file mode 100755 index e7f3783..0000000 --- a/All/Genesis-NP/Genesis#269/diff.diff +++ /dev/null @@ -1,8 +0,0 @@ -diff --git a/src/main/java/org/joda/time/Partial.java b/src/main/java/org/joda/time/Partial.java -index 6ff2771..6e29af9 100644 ---- a/src/main/java/org/joda/time/Partial.java -+++ b/src/main/java/org/joda/time/Partial.java -@@ -460,0 +461,3 @@ public final class Partial -+ if (loopType.getRangeDurationType() == null) { -+ continue; -+ } diff --git a/All/Genesis-NP/Genesis#269/new/Partial.java b/All/Genesis-NP/Genesis#269/new/Partial.java deleted file mode 100755 index 6e29af9..0000000 --- a/All/Genesis-NP/Genesis#269/new/Partial.java +++ /dev/null @@ -1,1015 +0,0 @@ -/* - * Copyright 2001-2013 Stephen Colebourne - * - * 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.joda.time; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -import org.joda.time.base.AbstractPartial; -import org.joda.time.field.AbstractPartialFieldProperty; -import org.joda.time.field.FieldUtils; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -/** - * Partial is an immutable partial datetime supporting any set of datetime fields. - *

- * A Partial instance can be used to hold any combination of fields. - * The instance does not contain a time zone, so any datetime is local. - *

- * A Partial can be matched against an instant using {@link #isMatch(ReadableInstant)}. - * This method compares each field on this partial with those of the instant - * and determines if the partial matches the instant. - * Given this definition, an empty Partial instance represents any datetime - * and always matches. - *

- * Calculations on Partial are performed using a {@link Chronology}. - * This chronology is set to be in the UTC time zone for all calculations. - *

- * Each individual field can be queried in two ways: - *

    - *
  • get(DateTimeFieldType.monthOfYear()) - *
  • property(DateTimeFieldType.monthOfYear()).get() - *
- * The second technique also provides access to other useful methods on the - * field: - *
    - *
  • numeric value - monthOfYear().get() - *
  • text value - monthOfYear().getAsText() - *
  • short text value - monthOfYear().getAsShortText() - *
  • maximum/minimum values - monthOfYear().getMaximumValue() - *
  • add/subtract - monthOfYear().addToCopy() - *
  • set - monthOfYear().setCopy() - *
- *

- * Partial is thread-safe and immutable, provided that the Chronology is as well. - * All standard Chronology classes supplied are thread-safe and immutable. - * - * @author Stephen Colebourne - * @since 1.1 - */ -public final class Partial - extends AbstractPartial - implements ReadablePartial, Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 12324121189002L; - - /** The chronology in use. */ - private final Chronology iChronology; - /** The set of field types. */ - private final DateTimeFieldType[] iTypes; - /** The values of each field in this partial. */ - private final int[] iValues; - /** The formatter to use, [0] may miss some fields, [1] doesn't miss any fields. */ - private transient DateTimeFormatter[] iFormatter; - - // Constructors - //----------------------------------------------------------------------- - /** - * Constructs a Partial with no fields or values, which can be considered - * to represent any date. - *

- * This is most useful when constructing partials, for example: - *

-     * Partial p = new Partial()
-     *     .with(DateTimeFieldType.dayOfWeek(), 5)
-     *     .with(DateTimeFieldType.hourOfDay(), 12)
-     *     .with(DateTimeFieldType.minuteOfHour(), 20);
-     * 
- * Note that, although this is a clean way to write code, it is fairly - * inefficient internally. - *

- * The constructor uses the default ISO chronology. - */ - public Partial() { - this((Chronology) null); - } - - /** - * Constructs a Partial with no fields or values, which can be considered - * to represent any date. - *

- * This is most useful when constructing partials, for example: - *

-     * Partial p = new Partial(chrono)
-     *     .with(DateTimeFieldType.dayOfWeek(), 5)
-     *     .with(DateTimeFieldType.hourOfDay(), 12)
-     *     .with(DateTimeFieldType.minuteOfHour(), 20);
-     * 
- * Note that, although this is a clean way to write code, it is fairly - * inefficient internally. - * - * @param chrono the chronology, null means ISO - */ - public Partial(Chronology chrono) { - super(); - iChronology = DateTimeUtils.getChronology(chrono).withUTC(); - iTypes = new DateTimeFieldType[0]; - iValues = new int[0]; - } - - /** - * Constructs a Partial with the specified field and value. - *

- * The constructor uses the default ISO chronology. - * - * @param type the single type to create the partial from, not null - * @param value the value to store - * @throws IllegalArgumentException if the type or value is invalid - */ - public Partial(DateTimeFieldType type, int value) { - this(type, value, null); - } - - /** - * Constructs a Partial with the specified field and value. - *

- * The constructor uses the specified chronology. - * - * @param type the single type to create the partial from, not null - * @param value the value to store - * @param chronology the chronology, null means ISO - * @throws IllegalArgumentException if the type or value is invalid - */ - public Partial(DateTimeFieldType type, int value, Chronology chronology) { - super(); - chronology = DateTimeUtils.getChronology(chronology).withUTC(); - iChronology = chronology; - if (type == null) { - throw new IllegalArgumentException("The field type must not be null"); - } - iTypes = new DateTimeFieldType[] {type}; - iValues = new int[] {value}; - chronology.validate(this, iValues); - } - - /** - * Constructs a Partial with the specified fields and values. - * The fields must be specified in the order largest to smallest. - *

- * The constructor uses the specified chronology. - * - * @param types the types to create the partial from, not null - * @param values the values to store, not null - * @throws IllegalArgumentException if the types or values are invalid - */ - public Partial(DateTimeFieldType[] types, int[] values) { - this(types, values, null); - } - - /** - * Constructs a Partial with the specified fields and values. - * The fields must be specified in the order largest to smallest. - *

- * The constructor uses the specified chronology. - * - * @param types the types to create the partial from, not null - * @param values the values to store, not null - * @param chronology the chronology, null means ISO - * @throws IllegalArgumentException if the types or values are invalid - */ - public Partial(DateTimeFieldType[] types, int[] values, Chronology chronology) { - super(); - chronology = DateTimeUtils.getChronology(chronology).withUTC(); - iChronology = chronology; - if (types == null) { - throw new IllegalArgumentException("Types array must not be null"); - } - if (values == null) { - throw new IllegalArgumentException("Values array must not be null"); - } - if (values.length != types.length) { - throw new IllegalArgumentException("Values array must be the same length as the types array"); - } - if (types.length == 0) { - iTypes = types; - iValues = values; - return; - } - for (int i = 0; i < types.length; i++) { - if (types[i] == null) { - throw new IllegalArgumentException("Types array must not contain null: index " + i); - } - } - DurationField lastUnitField = null; - for (int i = 0; i < types.length; i++) { - DateTimeFieldType loopType = types[i]; - DurationField loopUnitField = loopType.getDurationType().getField(iChronology); - if (i > 0) { - if (loopUnitField.isSupported() == false) { - if (lastUnitField.isSupported()) { - throw new IllegalArgumentException("Types array must be in order largest-smallest: " + - types[i - 1].getName() + " < " + loopType.getName()); - } else { - throw new IllegalArgumentException("Types array must not contain duplicate unsupported: " + - types[i - 1].getName() + " and " + loopType.getName()); - } - } - int compare = lastUnitField.compareTo(loopUnitField); - if (compare < 0) { - throw new IllegalArgumentException("Types array must be in order largest-smallest: " + - types[i - 1].getName() + " < " + loopType.getName()); - } else if (compare == 0 && lastUnitField.equals(loopUnitField)) { - if (types[i - 1].getRangeDurationType() == null) { - if (loopType.getRangeDurationType() == null) { - throw new IllegalArgumentException("Types array must not contain duplicate: " + - types[i - 1].getName() + " and " + loopType.getName()); - } - } else { - if (loopType.getRangeDurationType() == null) { - throw new IllegalArgumentException("Types array must be in order largest-smallest: " + - types[i - 1].getName() + " < " + loopType.getName()); - } - DurationField lastRangeField = types[i - 1].getRangeDurationType().getField(iChronology); - DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology); - if (lastRangeField.compareTo(loopRangeField) < 0) { - throw new IllegalArgumentException("Types array must be in order largest-smallest: " + - types[i - 1].getName() + " < " + loopType.getName()); - } - if (lastRangeField.compareTo(loopRangeField) == 0) { - throw new IllegalArgumentException("Types array must not contain duplicate: " + - types[i - 1].getName() + " and " + loopType.getName()); - } - } - } - } - lastUnitField = loopUnitField; - } - - iTypes = (DateTimeFieldType[]) types.clone(); - chronology.validate(this, values); - iValues = (int[]) values.clone(); - } - - /** - * Constructs a Partial by copying all the fields and types from - * another partial. - *

- * This is most useful when copying from a YearMonthDay or TimeOfDay. - */ - public Partial(ReadablePartial partial) { - super(); - if (partial == null) { - throw new IllegalArgumentException("The partial must not be null"); - } - iChronology = DateTimeUtils.getChronology(partial.getChronology()).withUTC(); - iTypes = new DateTimeFieldType[partial.size()]; - iValues = new int[partial.size()]; - for (int i = 0; i < partial.size(); i++) { - iTypes[i] = partial.getFieldType(i); - iValues[i] = partial.getValue(i); - } - } - - /** - * Constructs a Partial with the specified values. - * This constructor assigns and performs no validation. - * - * @param partial the partial to copy - * @param values the values to store - * @throws IllegalArgumentException if the types or values are invalid - */ - Partial(Partial partial, int[] values) { - super(); - iChronology = partial.iChronology; - iTypes = partial.iTypes; - iValues = values; - } - - /** - * Constructs a Partial with the specified chronology, fields and values. - * This constructor assigns and performs no validation. - * - * @param chronology the chronology - * @param types the types to create the partial from - * @param values the values to store - * @throws IllegalArgumentException if the types or values are invalid - */ - Partial(Chronology chronology, DateTimeFieldType[] types, int[] values) { - super(); - iChronology = chronology; - iTypes = types; - iValues = values; - } - - //----------------------------------------------------------------------- - /** - * Gets the number of fields in this partial. - * - * @return the field count - */ - public int size() { - return iTypes.length; - } - - /** - * Gets the chronology of the partial which is never null. - *

- * The {@link Chronology} is the calculation engine behind the partial and - * provides conversion and validation of the fields in a particular calendar system. - * - * @return the chronology, never null - */ - public Chronology getChronology() { - return iChronology; - } - - /** - * Gets the field for a specific index in the chronology specified. - * - * @param index the index to retrieve - * @param chrono the chronology to use - * @return the field - * @throws IndexOutOfBoundsException if the index is invalid - */ - protected DateTimeField getField(int index, Chronology chrono) { - return iTypes[index].getField(chrono); - } - - /** - * Gets the field type at the specified index. - * - * @param index the index to retrieve - * @return the field at the specified index - * @throws IndexOutOfBoundsException if the index is invalid - */ - public DateTimeFieldType getFieldType(int index) { - return iTypes[index]; - } - - /** - * Gets an array of the field type of each of the fields that - * this partial supports. - *

- * The fields are returned largest to smallest. - * - * @return the array of field types (cloned), largest to smallest - */ - public DateTimeFieldType[] getFieldTypes() { - return (DateTimeFieldType[]) iTypes.clone(); - } - - //----------------------------------------------------------------------- - /** - * Gets the value of the field at the specifed index. - * - * @param index the index - * @return the value - * @throws IndexOutOfBoundsException if the index is invalid - */ - public int getValue(int index) { - return iValues[index]; - } - - /** - * Gets an array of the value of each of the fields that - * this partial supports. - *

- * The fields are returned largest to smallest. - * Each value corresponds to the same array index as getFieldTypes() - * - * @return the current values of each field (cloned), largest to smallest - */ - public int[] getValues() { - return (int[]) iValues.clone(); - } - - //----------------------------------------------------------------------- - /** - * Creates a new Partial instance with the specified chronology. - * This instance is immutable and unaffected by this method call. - *

- * This method retains the values of the fields, thus the result will - * typically refer to a different instant. - *

- * The time zone of the specified chronology is ignored, as Partial - * operates without a time zone. - * - * @param newChronology the new chronology, null means ISO - * @return a copy of this datetime with a different chronology - * @throws IllegalArgumentException if the values are invalid for the new chronology - */ - public Partial withChronologyRetainFields(Chronology newChronology) { - newChronology = DateTimeUtils.getChronology(newChronology); - newChronology = newChronology.withUTC(); - if (newChronology == getChronology()) { - return this; - } else { - Partial newPartial = new Partial(newChronology, iTypes, iValues); - newChronology.validate(newPartial, iValues); - return newPartial; - } - } - - //----------------------------------------------------------------------- - /** - * Gets a copy of this date with the specified field set to a new value. - *

- * If this partial did not previously support the field, the new one will. - * Contrast this behaviour with {@link #withField(DateTimeFieldType, int)}. - *

- * For example, if the field type is dayOfMonth then the day - * would be changed/added in the returned instance. - * - * @param fieldType the field type to set, not null - * @param value the value to set - * @return a copy of this instance with the field set - * @throws IllegalArgumentException if the value is null or invalid - */ - public Partial with(DateTimeFieldType fieldType, int value) { - if (fieldType == null) { - throw new IllegalArgumentException("The field type must not be null"); - } - int index = indexOf(fieldType); - if (index == -1) { - DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1]; - int[] newValues = new int[newTypes.length]; - - // find correct insertion point to keep largest-smallest order - int i = 0; - DurationField unitField = fieldType.getDurationType().getField(iChronology); - if (unitField.isSupported()) { - for (; i < iTypes.length; i++) { - DateTimeFieldType loopType = iTypes[i]; - DurationField loopUnitField = loopType.getDurationType().getField(iChronology); - if (loopUnitField.isSupported()) { - int compare = unitField.compareTo(loopUnitField); - if (compare > 0) { - break; - } else if (compare == 0) { - if (fieldType.getRangeDurationType() == null) { - break; - } - if (loopType.getRangeDurationType() == null) { - continue; - } - DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology); - DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology); - if (rangeField.compareTo(loopRangeField) > 0) { - break; - } - } - } - } - } - System.arraycopy(iTypes, 0, newTypes, 0, i); - System.arraycopy(iValues, 0, newValues, 0, i); - newTypes[i] = fieldType; - newValues[i] = value; - System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1); - System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1); - // use public constructor to ensure full validation - // this isn't overly efficient, but is safe - Partial newPartial = new Partial(newTypes, newValues, iChronology); - iChronology.validate(newPartial, newValues); - return newPartial; - } - if (value == getValue(index)) { - return this; - } - int[] newValues = getValues(); - newValues = getField(index).set(this, index, newValues, value); - return new Partial(this, newValues); - } - - /** - * Gets a copy of this date with the specified field removed. - *

- * If this partial did not previously support the field, no error occurs. - * - * @param fieldType the field type to remove, may be null - * @return a copy of this instance with the field removed - */ - public Partial without(DateTimeFieldType fieldType) { - int index = indexOf(fieldType); - if (index != -1) { - DateTimeFieldType[] newTypes = new DateTimeFieldType[size() - 1]; - int[] newValues = new int[size() - 1]; - System.arraycopy(iTypes, 0, newTypes, 0, index); - System.arraycopy(iTypes, index + 1, newTypes, index, newTypes.length - index); - System.arraycopy(iValues, 0, newValues, 0, index); - System.arraycopy(iValues, index + 1, newValues, index, newValues.length - index); - Partial newPartial = new Partial(iChronology, newTypes, newValues); - iChronology.validate(newPartial, newValues); - return newPartial; - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets a copy of this Partial with the specified field set to a new value. - *

- * If this partial does not support the field, an exception is thrown. - * Contrast this behaviour with {@link #with(DateTimeFieldType, int)}. - *

- * For example, if the field type is dayOfMonth then the day - * would be changed in the returned instance if supported. - * - * @param fieldType the field type to set, not null - * @param value the value to set - * @return a copy of this instance with the field set - * @throws IllegalArgumentException if the value is null or invalid - */ - public Partial withField(DateTimeFieldType fieldType, int value) { - int index = indexOfSupported(fieldType); - if (value == getValue(index)) { - return this; - } - int[] newValues = getValues(); - newValues = getField(index).set(this, index, newValues, value); - return new Partial(this, newValues); - } - - /** - * Gets a copy of this Partial with the value of the specified field increased. - * If this partial does not support the field, an exception is thrown. - *

- * If the addition is zero, then this is returned. - * The addition will overflow into larger fields (eg. minute to hour). - * However, it will not wrap around if the top maximum is reached. - * - * @param fieldType the field type to add to, not null - * @param amount the amount to add - * @return a copy of this instance with the field updated - * @throws IllegalArgumentException if the value is null or invalid - * @throws ArithmeticException if the new datetime exceeds the capacity - */ - public Partial withFieldAdded(DurationFieldType fieldType, int amount) { - int index = indexOfSupported(fieldType); - if (amount == 0) { - return this; - } - int[] newValues = getValues(); - newValues = getField(index).add(this, index, newValues, amount); - return new Partial(this, newValues); - } - - /** - * Gets a copy of this Partial with the value of the specified field increased. - * If this partial does not support the field, an exception is thrown. - *

- * If the addition is zero, then this is returned. - * The addition will overflow into larger fields (eg. minute to hour). - * If the maximum is reached, the addition will wra. - * - * @param fieldType the field type to add to, not null - * @param amount the amount to add - * @return a copy of this instance with the field updated - * @throws IllegalArgumentException if the value is null or invalid - * @throws ArithmeticException if the new datetime exceeds the capacity - */ - public Partial withFieldAddWrapped(DurationFieldType fieldType, int amount) { - int index = indexOfSupported(fieldType); - if (amount == 0) { - return this; - } - int[] newValues = getValues(); - newValues = getField(index).addWrapPartial(this, index, newValues, amount); - return new Partial(this, newValues); - } - - /** - * Gets a copy of this Partial with the specified period added. - *

- * If the addition is zero, then this is returned. - * Fields in the period that aren't present in the partial are ignored. - *

- * This method is typically used to add multiple copies of complex - * period instances. Adding one field is best achieved using the method - * {@link #withFieldAdded(DurationFieldType, int)}. - * - * @param period the period to add to this one, null means zero - * @param scalar the amount of times to add, such as -1 to subtract once - * @return a copy of this instance with the period added - * @throws ArithmeticException if the new datetime exceeds the capacity - */ - public Partial withPeriodAdded(ReadablePeriod period, int scalar) { - if (period == null || scalar == 0) { - return this; - } - int[] newValues = getValues(); - for (int i = 0; i < period.size(); i++) { - DurationFieldType fieldType = period.getFieldType(i); - int index = indexOf(fieldType); - if (index >= 0) { - newValues = getField(index).add(this, index, newValues, - FieldUtils.safeMultiply(period.getValue(i), scalar)); - } - } - return new Partial(this, newValues); - } - - /** - * Gets a copy of this instance with the specified period added. - *

- * If the amount is zero or null, then this is returned. - * - * @param period the duration to add to this one, null means zero - * @return a copy of this instance with the period added - * @throws ArithmeticException if the new datetime exceeds the capacity of a long - */ - public Partial plus(ReadablePeriod period) { - return withPeriodAdded(period, 1); - } - - /** - * Gets a copy of this instance with the specified period take away. - *

- * If the amount is zero or null, then this is returned. - * - * @param period the period to reduce this instant by - * @return a copy of this instance with the period taken away - * @throws ArithmeticException if the new datetime exceeds the capacity of a long - */ - public Partial minus(ReadablePeriod period) { - return withPeriodAdded(period, -1); - } - - //----------------------------------------------------------------------- - /** - * Gets the property object for the specified type, which contains - * many useful methods for getting and manipulating the partial. - *

- * See also {@link ReadablePartial#get(DateTimeFieldType)}. - * - * @param type the field type to get the property for, not null - * @return the property object - * @throws IllegalArgumentException if the field is null or unsupported - */ - public Property property(DateTimeFieldType type) { - return new Property(this, indexOfSupported(type)); - } - - //----------------------------------------------------------------------- - /** - * Does this partial match the specified instant. - *

- * A match occurs when all the fields of this partial are the same as the - * corresponding fields on the specified instant. - * - * @param instant an instant to check against, null means now in default zone - * @return true if this partial matches the specified instant - */ - public boolean isMatch(ReadableInstant instant) { - long millis = DateTimeUtils.getInstantMillis(instant); - Chronology chrono = DateTimeUtils.getInstantChronology(instant); - for (int i = 0; i < iTypes.length; i++) { - int value = iTypes[i].getField(chrono).get(millis); - if (value != iValues[i]) { - return false; - } - } - return true; - } - - /** - * Does this partial match the specified partial. - *

- * A match occurs when all the fields of this partial are the same as the - * corresponding fields on the specified partial. - * - * @param partial a partial to check against, must not be null - * @return true if this partial matches the specified partial - * @throws IllegalArgumentException if the partial is null - * @throws IllegalArgumentException if the fields of the two partials do not match - * @since 1.5 - */ - public boolean isMatch(ReadablePartial partial) { - if (partial == null) { - throw new IllegalArgumentException("The partial must not be null"); - } - for (int i = 0; i < iTypes.length; i++) { - int value = partial.get(iTypes[i]); - if (value != iValues[i]) { - return false; - } - } - return true; - } - - //----------------------------------------------------------------------- - /** - * Gets a formatter suitable for the fields in this partial. - *

- * If there is no appropriate ISO format, null is returned. - * This method may return a formatter that does not display all the - * fields of the partial. This might occur when you have overlapping - * fields, such as dayOfWeek and dayOfMonth. - * - * @return a formatter suitable for the fields in this partial, null - * if none is suitable - */ - public DateTimeFormatter getFormatter() { - DateTimeFormatter[] f = iFormatter; - if (f == null) { - if (size() == 0) { - return null; - } - f = new DateTimeFormatter[2]; - try { - List list = new ArrayList(Arrays.asList(iTypes)); - f[0] = ISODateTimeFormat.forFields(list, true, false); - if (list.size() == 0) { - f[1] = f[0]; - } - } catch (IllegalArgumentException ex) { - // ignore - } - iFormatter = f; - } - return f[0]; - } - - //----------------------------------------------------------------------- - /** - * Output the date in an appropriate ISO8601 format. - *

- * This method will output the partial in one of two ways. - * If {@link #getFormatter()} - *

- * If there is no appropriate ISO format a dump of the fields is output - * via {@link #toStringList()}. - * - * @return ISO8601 formatted string - */ - public String toString() { - DateTimeFormatter[] f = iFormatter; - if (f == null) { - getFormatter(); - f = iFormatter; - if (f == null) { - return toStringList(); - } - } - DateTimeFormatter f1 = f[1]; - if (f1 == null) { - return toStringList(); - } - return f1.print(this); - } - - /** - * Gets a string version of the partial that lists all the fields. - *

- * This method exists to provide a better debugging toString than - * the standard toString. This method lists all the fields and their - * values in a style similar to the collections framework. - * - * @return a toString format that lists all the fields - */ - public String toStringList() { - int size = size(); - StringBuilder buf = new StringBuilder(20 * size); - buf.append('['); - for (int i = 0; i < size; i++) { - if (i > 0) { - buf.append(',').append(' '); - } - buf.append(iTypes[i].getName()); - buf.append('='); - buf.append(iValues[i]); - } - buf.append(']'); - return buf.toString(); - } - - /** - * Output the date using the specified format pattern. - * Unsupported fields will appear as special unicode characters. - * - * @param pattern the pattern specification, null means use toString - * @see org.joda.time.format.DateTimeFormat - */ - public String toString(String pattern) { - if (pattern == null) { - return toString(); - } - return DateTimeFormat.forPattern(pattern).print(this); - } - - /** - * Output the date using the specified format pattern. - * Unsupported fields will appear as special unicode characters. - * - * @param pattern the pattern specification, null means use toString - * @param locale Locale to use, null means default - * @see org.joda.time.format.DateTimeFormat - */ - public String toString(String pattern, Locale locale) { - if (pattern == null) { - return toString(); - } - return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); - } - - //----------------------------------------------------------------------- - /** - * The property class for Partial. - *

- * This class binds a Partial to a DateTimeField. - * - * @author Stephen Colebourne - * @since 1.1 - */ - public static class Property extends AbstractPartialFieldProperty implements Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 53278362873888L; - - /** The partial */ - private final Partial iPartial; - /** The field index */ - private final int iFieldIndex; - - /** - * Constructs a property. - * - * @param partial the partial instance - * @param fieldIndex the index in the partial - */ - Property(Partial partial, int fieldIndex) { - super(); - iPartial = partial; - iFieldIndex = fieldIndex; - } - - /** - * Gets the field that this property uses. - * - * @return the field - */ - public DateTimeField getField() { - return iPartial.getField(iFieldIndex); - } - - /** - * Gets the partial that this property belongs to. - * - * @return the partial - */ - protected ReadablePartial getReadablePartial() { - return iPartial; - } - - /** - * Gets the partial that this property belongs to. - * - * @return the partial - */ - public Partial getPartial() { - return iPartial; - } - - /** - * Gets the value of this field. - * - * @return the field value - */ - public int get() { - return iPartial.getValue(iFieldIndex); - } - - //----------------------------------------------------------------------- - /** - * Adds to the value of this field in a copy of this Partial. - *

- * The value will be added to this field. If the value is too large to be - * added solely to this field then it will affect larger fields. - * Smaller fields are unaffected. - *

- * If the result would be too large, beyond the maximum year, then an - * IllegalArgumentException is thrown. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param valueToAdd the value to add to the field in the copy - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the value isn't valid - */ - public Partial addToCopy(int valueToAdd) { - int[] newValues = iPartial.getValues(); - newValues = getField().add(iPartial, iFieldIndex, newValues, valueToAdd); - return new Partial(iPartial, newValues); - } - - /** - * Adds to the value of this field in a copy of this Partial wrapping - * within this field if the maximum value is reached. - *

- * The value will be added to this field. If the value is too large to be - * added solely to this field then it wraps within this field. - * Other fields are unaffected. - *

- * For example, - * 2004-12-20 addWrapField one month returns 2004-01-20. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param valueToAdd the value to add to the field in the copy - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the value isn't valid - */ - public Partial addWrapFieldToCopy(int valueToAdd) { - int[] newValues = iPartial.getValues(); - newValues = getField().addWrapField(iPartial, iFieldIndex, newValues, valueToAdd); - return new Partial(iPartial, newValues); - } - - //----------------------------------------------------------------------- - /** - * Sets this field in a copy of the Partial. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param value the value to set the field in the copy to - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the value isn't valid - */ - public Partial setCopy(int value) { - int[] newValues = iPartial.getValues(); - newValues = getField().set(iPartial, iFieldIndex, newValues, value); - return new Partial(iPartial, newValues); - } - - /** - * Sets this field in a copy of the Partial to a parsed text value. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param text the text value to set - * @param locale optional locale to use for selecting a text symbol - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the text value isn't valid - */ - public Partial setCopy(String text, Locale locale) { - int[] newValues = iPartial.getValues(); - newValues = getField().set(iPartial, iFieldIndex, newValues, text, locale); - return new Partial(iPartial, newValues); - } - - /** - * Sets this field in a copy of the Partial to a parsed text value. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param text the text value to set - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the text value isn't valid - */ - public Partial setCopy(String text) { - return setCopy(text, null); - } - - //----------------------------------------------------------------------- - /** - * Returns a new Partial with this field set to the maximum value - * for this field. - *

- * The Partial attached to this property is unchanged by this call. - * - * @return a copy of the Partial with this field set to its maximum - * @since 1.2 - */ - public Partial withMaximumValue() { - return setCopy(getMaximumValue()); - } - - /** - * Returns a new Partial with this field set to the minimum value - * for this field. - *

- * The Partial attached to this property is unchanged by this call. - * - * @return a copy of the Partial with this field set to its minimum - * @since 1.2 - */ - public Partial withMinimumValue() { - return setCopy(getMinimumValue()); - } - } - -} diff --git a/All/Genesis-NP/Genesis#269/old/Partial.java b/All/Genesis-NP/Genesis#269/old/Partial.java deleted file mode 100755 index 6ff2771..0000000 --- a/All/Genesis-NP/Genesis#269/old/Partial.java +++ /dev/null @@ -1,1012 +0,0 @@ -/* - * Copyright 2001-2013 Stephen Colebourne - * - * 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.joda.time; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Locale; - -import org.joda.time.base.AbstractPartial; -import org.joda.time.field.AbstractPartialFieldProperty; -import org.joda.time.field.FieldUtils; -import org.joda.time.format.DateTimeFormat; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -/** - * Partial is an immutable partial datetime supporting any set of datetime fields. - *

- * A Partial instance can be used to hold any combination of fields. - * The instance does not contain a time zone, so any datetime is local. - *

- * A Partial can be matched against an instant using {@link #isMatch(ReadableInstant)}. - * This method compares each field on this partial with those of the instant - * and determines if the partial matches the instant. - * Given this definition, an empty Partial instance represents any datetime - * and always matches. - *

- * Calculations on Partial are performed using a {@link Chronology}. - * This chronology is set to be in the UTC time zone for all calculations. - *

- * Each individual field can be queried in two ways: - *

    - *
  • get(DateTimeFieldType.monthOfYear()) - *
  • property(DateTimeFieldType.monthOfYear()).get() - *
- * The second technique also provides access to other useful methods on the - * field: - *
    - *
  • numeric value - monthOfYear().get() - *
  • text value - monthOfYear().getAsText() - *
  • short text value - monthOfYear().getAsShortText() - *
  • maximum/minimum values - monthOfYear().getMaximumValue() - *
  • add/subtract - monthOfYear().addToCopy() - *
  • set - monthOfYear().setCopy() - *
- *

- * Partial is thread-safe and immutable, provided that the Chronology is as well. - * All standard Chronology classes supplied are thread-safe and immutable. - * - * @author Stephen Colebourne - * @since 1.1 - */ -public final class Partial - extends AbstractPartial - implements ReadablePartial, Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 12324121189002L; - - /** The chronology in use. */ - private final Chronology iChronology; - /** The set of field types. */ - private final DateTimeFieldType[] iTypes; - /** The values of each field in this partial. */ - private final int[] iValues; - /** The formatter to use, [0] may miss some fields, [1] doesn't miss any fields. */ - private transient DateTimeFormatter[] iFormatter; - - // Constructors - //----------------------------------------------------------------------- - /** - * Constructs a Partial with no fields or values, which can be considered - * to represent any date. - *

- * This is most useful when constructing partials, for example: - *

-     * Partial p = new Partial()
-     *     .with(DateTimeFieldType.dayOfWeek(), 5)
-     *     .with(DateTimeFieldType.hourOfDay(), 12)
-     *     .with(DateTimeFieldType.minuteOfHour(), 20);
-     * 
- * Note that, although this is a clean way to write code, it is fairly - * inefficient internally. - *

- * The constructor uses the default ISO chronology. - */ - public Partial() { - this((Chronology) null); - } - - /** - * Constructs a Partial with no fields or values, which can be considered - * to represent any date. - *

- * This is most useful when constructing partials, for example: - *

-     * Partial p = new Partial(chrono)
-     *     .with(DateTimeFieldType.dayOfWeek(), 5)
-     *     .with(DateTimeFieldType.hourOfDay(), 12)
-     *     .with(DateTimeFieldType.minuteOfHour(), 20);
-     * 
- * Note that, although this is a clean way to write code, it is fairly - * inefficient internally. - * - * @param chrono the chronology, null means ISO - */ - public Partial(Chronology chrono) { - super(); - iChronology = DateTimeUtils.getChronology(chrono).withUTC(); - iTypes = new DateTimeFieldType[0]; - iValues = new int[0]; - } - - /** - * Constructs a Partial with the specified field and value. - *

- * The constructor uses the default ISO chronology. - * - * @param type the single type to create the partial from, not null - * @param value the value to store - * @throws IllegalArgumentException if the type or value is invalid - */ - public Partial(DateTimeFieldType type, int value) { - this(type, value, null); - } - - /** - * Constructs a Partial with the specified field and value. - *

- * The constructor uses the specified chronology. - * - * @param type the single type to create the partial from, not null - * @param value the value to store - * @param chronology the chronology, null means ISO - * @throws IllegalArgumentException if the type or value is invalid - */ - public Partial(DateTimeFieldType type, int value, Chronology chronology) { - super(); - chronology = DateTimeUtils.getChronology(chronology).withUTC(); - iChronology = chronology; - if (type == null) { - throw new IllegalArgumentException("The field type must not be null"); - } - iTypes = new DateTimeFieldType[] {type}; - iValues = new int[] {value}; - chronology.validate(this, iValues); - } - - /** - * Constructs a Partial with the specified fields and values. - * The fields must be specified in the order largest to smallest. - *

- * The constructor uses the specified chronology. - * - * @param types the types to create the partial from, not null - * @param values the values to store, not null - * @throws IllegalArgumentException if the types or values are invalid - */ - public Partial(DateTimeFieldType[] types, int[] values) { - this(types, values, null); - } - - /** - * Constructs a Partial with the specified fields and values. - * The fields must be specified in the order largest to smallest. - *

- * The constructor uses the specified chronology. - * - * @param types the types to create the partial from, not null - * @param values the values to store, not null - * @param chronology the chronology, null means ISO - * @throws IllegalArgumentException if the types or values are invalid - */ - public Partial(DateTimeFieldType[] types, int[] values, Chronology chronology) { - super(); - chronology = DateTimeUtils.getChronology(chronology).withUTC(); - iChronology = chronology; - if (types == null) { - throw new IllegalArgumentException("Types array must not be null"); - } - if (values == null) { - throw new IllegalArgumentException("Values array must not be null"); - } - if (values.length != types.length) { - throw new IllegalArgumentException("Values array must be the same length as the types array"); - } - if (types.length == 0) { - iTypes = types; - iValues = values; - return; - } - for (int i = 0; i < types.length; i++) { - if (types[i] == null) { - throw new IllegalArgumentException("Types array must not contain null: index " + i); - } - } - DurationField lastUnitField = null; - for (int i = 0; i < types.length; i++) { - DateTimeFieldType loopType = types[i]; - DurationField loopUnitField = loopType.getDurationType().getField(iChronology); - if (i > 0) { - if (loopUnitField.isSupported() == false) { - if (lastUnitField.isSupported()) { - throw new IllegalArgumentException("Types array must be in order largest-smallest: " + - types[i - 1].getName() + " < " + loopType.getName()); - } else { - throw new IllegalArgumentException("Types array must not contain duplicate unsupported: " + - types[i - 1].getName() + " and " + loopType.getName()); - } - } - int compare = lastUnitField.compareTo(loopUnitField); - if (compare < 0) { - throw new IllegalArgumentException("Types array must be in order largest-smallest: " + - types[i - 1].getName() + " < " + loopType.getName()); - } else if (compare == 0 && lastUnitField.equals(loopUnitField)) { - if (types[i - 1].getRangeDurationType() == null) { - if (loopType.getRangeDurationType() == null) { - throw new IllegalArgumentException("Types array must not contain duplicate: " + - types[i - 1].getName() + " and " + loopType.getName()); - } - } else { - if (loopType.getRangeDurationType() == null) { - throw new IllegalArgumentException("Types array must be in order largest-smallest: " + - types[i - 1].getName() + " < " + loopType.getName()); - } - DurationField lastRangeField = types[i - 1].getRangeDurationType().getField(iChronology); - DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology); - if (lastRangeField.compareTo(loopRangeField) < 0) { - throw new IllegalArgumentException("Types array must be in order largest-smallest: " + - types[i - 1].getName() + " < " + loopType.getName()); - } - if (lastRangeField.compareTo(loopRangeField) == 0) { - throw new IllegalArgumentException("Types array must not contain duplicate: " + - types[i - 1].getName() + " and " + loopType.getName()); - } - } - } - } - lastUnitField = loopUnitField; - } - - iTypes = (DateTimeFieldType[]) types.clone(); - chronology.validate(this, values); - iValues = (int[]) values.clone(); - } - - /** - * Constructs a Partial by copying all the fields and types from - * another partial. - *

- * This is most useful when copying from a YearMonthDay or TimeOfDay. - */ - public Partial(ReadablePartial partial) { - super(); - if (partial == null) { - throw new IllegalArgumentException("The partial must not be null"); - } - iChronology = DateTimeUtils.getChronology(partial.getChronology()).withUTC(); - iTypes = new DateTimeFieldType[partial.size()]; - iValues = new int[partial.size()]; - for (int i = 0; i < partial.size(); i++) { - iTypes[i] = partial.getFieldType(i); - iValues[i] = partial.getValue(i); - } - } - - /** - * Constructs a Partial with the specified values. - * This constructor assigns and performs no validation. - * - * @param partial the partial to copy - * @param values the values to store - * @throws IllegalArgumentException if the types or values are invalid - */ - Partial(Partial partial, int[] values) { - super(); - iChronology = partial.iChronology; - iTypes = partial.iTypes; - iValues = values; - } - - /** - * Constructs a Partial with the specified chronology, fields and values. - * This constructor assigns and performs no validation. - * - * @param chronology the chronology - * @param types the types to create the partial from - * @param values the values to store - * @throws IllegalArgumentException if the types or values are invalid - */ - Partial(Chronology chronology, DateTimeFieldType[] types, int[] values) { - super(); - iChronology = chronology; - iTypes = types; - iValues = values; - } - - //----------------------------------------------------------------------- - /** - * Gets the number of fields in this partial. - * - * @return the field count - */ - public int size() { - return iTypes.length; - } - - /** - * Gets the chronology of the partial which is never null. - *

- * The {@link Chronology} is the calculation engine behind the partial and - * provides conversion and validation of the fields in a particular calendar system. - * - * @return the chronology, never null - */ - public Chronology getChronology() { - return iChronology; - } - - /** - * Gets the field for a specific index in the chronology specified. - * - * @param index the index to retrieve - * @param chrono the chronology to use - * @return the field - * @throws IndexOutOfBoundsException if the index is invalid - */ - protected DateTimeField getField(int index, Chronology chrono) { - return iTypes[index].getField(chrono); - } - - /** - * Gets the field type at the specified index. - * - * @param index the index to retrieve - * @return the field at the specified index - * @throws IndexOutOfBoundsException if the index is invalid - */ - public DateTimeFieldType getFieldType(int index) { - return iTypes[index]; - } - - /** - * Gets an array of the field type of each of the fields that - * this partial supports. - *

- * The fields are returned largest to smallest. - * - * @return the array of field types (cloned), largest to smallest - */ - public DateTimeFieldType[] getFieldTypes() { - return (DateTimeFieldType[]) iTypes.clone(); - } - - //----------------------------------------------------------------------- - /** - * Gets the value of the field at the specifed index. - * - * @param index the index - * @return the value - * @throws IndexOutOfBoundsException if the index is invalid - */ - public int getValue(int index) { - return iValues[index]; - } - - /** - * Gets an array of the value of each of the fields that - * this partial supports. - *

- * The fields are returned largest to smallest. - * Each value corresponds to the same array index as getFieldTypes() - * - * @return the current values of each field (cloned), largest to smallest - */ - public int[] getValues() { - return (int[]) iValues.clone(); - } - - //----------------------------------------------------------------------- - /** - * Creates a new Partial instance with the specified chronology. - * This instance is immutable and unaffected by this method call. - *

- * This method retains the values of the fields, thus the result will - * typically refer to a different instant. - *

- * The time zone of the specified chronology is ignored, as Partial - * operates without a time zone. - * - * @param newChronology the new chronology, null means ISO - * @return a copy of this datetime with a different chronology - * @throws IllegalArgumentException if the values are invalid for the new chronology - */ - public Partial withChronologyRetainFields(Chronology newChronology) { - newChronology = DateTimeUtils.getChronology(newChronology); - newChronology = newChronology.withUTC(); - if (newChronology == getChronology()) { - return this; - } else { - Partial newPartial = new Partial(newChronology, iTypes, iValues); - newChronology.validate(newPartial, iValues); - return newPartial; - } - } - - //----------------------------------------------------------------------- - /** - * Gets a copy of this date with the specified field set to a new value. - *

- * If this partial did not previously support the field, the new one will. - * Contrast this behaviour with {@link #withField(DateTimeFieldType, int)}. - *

- * For example, if the field type is dayOfMonth then the day - * would be changed/added in the returned instance. - * - * @param fieldType the field type to set, not null - * @param value the value to set - * @return a copy of this instance with the field set - * @throws IllegalArgumentException if the value is null or invalid - */ - public Partial with(DateTimeFieldType fieldType, int value) { - if (fieldType == null) { - throw new IllegalArgumentException("The field type must not be null"); - } - int index = indexOf(fieldType); - if (index == -1) { - DateTimeFieldType[] newTypes = new DateTimeFieldType[iTypes.length + 1]; - int[] newValues = new int[newTypes.length]; - - // find correct insertion point to keep largest-smallest order - int i = 0; - DurationField unitField = fieldType.getDurationType().getField(iChronology); - if (unitField.isSupported()) { - for (; i < iTypes.length; i++) { - DateTimeFieldType loopType = iTypes[i]; - DurationField loopUnitField = loopType.getDurationType().getField(iChronology); - if (loopUnitField.isSupported()) { - int compare = unitField.compareTo(loopUnitField); - if (compare > 0) { - break; - } else if (compare == 0) { - if (fieldType.getRangeDurationType() == null) { - break; - } - DurationField rangeField = fieldType.getRangeDurationType().getField(iChronology); - DurationField loopRangeField = loopType.getRangeDurationType().getField(iChronology); - if (rangeField.compareTo(loopRangeField) > 0) { - break; - } - } - } - } - } - System.arraycopy(iTypes, 0, newTypes, 0, i); - System.arraycopy(iValues, 0, newValues, 0, i); - newTypes[i] = fieldType; - newValues[i] = value; - System.arraycopy(iTypes, i, newTypes, i + 1, newTypes.length - i - 1); - System.arraycopy(iValues, i, newValues, i + 1, newValues.length - i - 1); - // use public constructor to ensure full validation - // this isn't overly efficient, but is safe - Partial newPartial = new Partial(newTypes, newValues, iChronology); - iChronology.validate(newPartial, newValues); - return newPartial; - } - if (value == getValue(index)) { - return this; - } - int[] newValues = getValues(); - newValues = getField(index).set(this, index, newValues, value); - return new Partial(this, newValues); - } - - /** - * Gets a copy of this date with the specified field removed. - *

- * If this partial did not previously support the field, no error occurs. - * - * @param fieldType the field type to remove, may be null - * @return a copy of this instance with the field removed - */ - public Partial without(DateTimeFieldType fieldType) { - int index = indexOf(fieldType); - if (index != -1) { - DateTimeFieldType[] newTypes = new DateTimeFieldType[size() - 1]; - int[] newValues = new int[size() - 1]; - System.arraycopy(iTypes, 0, newTypes, 0, index); - System.arraycopy(iTypes, index + 1, newTypes, index, newTypes.length - index); - System.arraycopy(iValues, 0, newValues, 0, index); - System.arraycopy(iValues, index + 1, newValues, index, newValues.length - index); - Partial newPartial = new Partial(iChronology, newTypes, newValues); - iChronology.validate(newPartial, newValues); - return newPartial; - } - return this; - } - - //----------------------------------------------------------------------- - /** - * Gets a copy of this Partial with the specified field set to a new value. - *

- * If this partial does not support the field, an exception is thrown. - * Contrast this behaviour with {@link #with(DateTimeFieldType, int)}. - *

- * For example, if the field type is dayOfMonth then the day - * would be changed in the returned instance if supported. - * - * @param fieldType the field type to set, not null - * @param value the value to set - * @return a copy of this instance with the field set - * @throws IllegalArgumentException if the value is null or invalid - */ - public Partial withField(DateTimeFieldType fieldType, int value) { - int index = indexOfSupported(fieldType); - if (value == getValue(index)) { - return this; - } - int[] newValues = getValues(); - newValues = getField(index).set(this, index, newValues, value); - return new Partial(this, newValues); - } - - /** - * Gets a copy of this Partial with the value of the specified field increased. - * If this partial does not support the field, an exception is thrown. - *

- * If the addition is zero, then this is returned. - * The addition will overflow into larger fields (eg. minute to hour). - * However, it will not wrap around if the top maximum is reached. - * - * @param fieldType the field type to add to, not null - * @param amount the amount to add - * @return a copy of this instance with the field updated - * @throws IllegalArgumentException if the value is null or invalid - * @throws ArithmeticException if the new datetime exceeds the capacity - */ - public Partial withFieldAdded(DurationFieldType fieldType, int amount) { - int index = indexOfSupported(fieldType); - if (amount == 0) { - return this; - } - int[] newValues = getValues(); - newValues = getField(index).add(this, index, newValues, amount); - return new Partial(this, newValues); - } - - /** - * Gets a copy of this Partial with the value of the specified field increased. - * If this partial does not support the field, an exception is thrown. - *

- * If the addition is zero, then this is returned. - * The addition will overflow into larger fields (eg. minute to hour). - * If the maximum is reached, the addition will wra. - * - * @param fieldType the field type to add to, not null - * @param amount the amount to add - * @return a copy of this instance with the field updated - * @throws IllegalArgumentException if the value is null or invalid - * @throws ArithmeticException if the new datetime exceeds the capacity - */ - public Partial withFieldAddWrapped(DurationFieldType fieldType, int amount) { - int index = indexOfSupported(fieldType); - if (amount == 0) { - return this; - } - int[] newValues = getValues(); - newValues = getField(index).addWrapPartial(this, index, newValues, amount); - return new Partial(this, newValues); - } - - /** - * Gets a copy of this Partial with the specified period added. - *

- * If the addition is zero, then this is returned. - * Fields in the period that aren't present in the partial are ignored. - *

- * This method is typically used to add multiple copies of complex - * period instances. Adding one field is best achieved using the method - * {@link #withFieldAdded(DurationFieldType, int)}. - * - * @param period the period to add to this one, null means zero - * @param scalar the amount of times to add, such as -1 to subtract once - * @return a copy of this instance with the period added - * @throws ArithmeticException if the new datetime exceeds the capacity - */ - public Partial withPeriodAdded(ReadablePeriod period, int scalar) { - if (period == null || scalar == 0) { - return this; - } - int[] newValues = getValues(); - for (int i = 0; i < period.size(); i++) { - DurationFieldType fieldType = period.getFieldType(i); - int index = indexOf(fieldType); - if (index >= 0) { - newValues = getField(index).add(this, index, newValues, - FieldUtils.safeMultiply(period.getValue(i), scalar)); - } - } - return new Partial(this, newValues); - } - - /** - * Gets a copy of this instance with the specified period added. - *

- * If the amount is zero or null, then this is returned. - * - * @param period the duration to add to this one, null means zero - * @return a copy of this instance with the period added - * @throws ArithmeticException if the new datetime exceeds the capacity of a long - */ - public Partial plus(ReadablePeriod period) { - return withPeriodAdded(period, 1); - } - - /** - * Gets a copy of this instance with the specified period take away. - *

- * If the amount is zero or null, then this is returned. - * - * @param period the period to reduce this instant by - * @return a copy of this instance with the period taken away - * @throws ArithmeticException if the new datetime exceeds the capacity of a long - */ - public Partial minus(ReadablePeriod period) { - return withPeriodAdded(period, -1); - } - - //----------------------------------------------------------------------- - /** - * Gets the property object for the specified type, which contains - * many useful methods for getting and manipulating the partial. - *

- * See also {@link ReadablePartial#get(DateTimeFieldType)}. - * - * @param type the field type to get the property for, not null - * @return the property object - * @throws IllegalArgumentException if the field is null or unsupported - */ - public Property property(DateTimeFieldType type) { - return new Property(this, indexOfSupported(type)); - } - - //----------------------------------------------------------------------- - /** - * Does this partial match the specified instant. - *

- * A match occurs when all the fields of this partial are the same as the - * corresponding fields on the specified instant. - * - * @param instant an instant to check against, null means now in default zone - * @return true if this partial matches the specified instant - */ - public boolean isMatch(ReadableInstant instant) { - long millis = DateTimeUtils.getInstantMillis(instant); - Chronology chrono = DateTimeUtils.getInstantChronology(instant); - for (int i = 0; i < iTypes.length; i++) { - int value = iTypes[i].getField(chrono).get(millis); - if (value != iValues[i]) { - return false; - } - } - return true; - } - - /** - * Does this partial match the specified partial. - *

- * A match occurs when all the fields of this partial are the same as the - * corresponding fields on the specified partial. - * - * @param partial a partial to check against, must not be null - * @return true if this partial matches the specified partial - * @throws IllegalArgumentException if the partial is null - * @throws IllegalArgumentException if the fields of the two partials do not match - * @since 1.5 - */ - public boolean isMatch(ReadablePartial partial) { - if (partial == null) { - throw new IllegalArgumentException("The partial must not be null"); - } - for (int i = 0; i < iTypes.length; i++) { - int value = partial.get(iTypes[i]); - if (value != iValues[i]) { - return false; - } - } - return true; - } - - //----------------------------------------------------------------------- - /** - * Gets a formatter suitable for the fields in this partial. - *

- * If there is no appropriate ISO format, null is returned. - * This method may return a formatter that does not display all the - * fields of the partial. This might occur when you have overlapping - * fields, such as dayOfWeek and dayOfMonth. - * - * @return a formatter suitable for the fields in this partial, null - * if none is suitable - */ - public DateTimeFormatter getFormatter() { - DateTimeFormatter[] f = iFormatter; - if (f == null) { - if (size() == 0) { - return null; - } - f = new DateTimeFormatter[2]; - try { - List list = new ArrayList(Arrays.asList(iTypes)); - f[0] = ISODateTimeFormat.forFields(list, true, false); - if (list.size() == 0) { - f[1] = f[0]; - } - } catch (IllegalArgumentException ex) { - // ignore - } - iFormatter = f; - } - return f[0]; - } - - //----------------------------------------------------------------------- - /** - * Output the date in an appropriate ISO8601 format. - *

- * This method will output the partial in one of two ways. - * If {@link #getFormatter()} - *

- * If there is no appropriate ISO format a dump of the fields is output - * via {@link #toStringList()}. - * - * @return ISO8601 formatted string - */ - public String toString() { - DateTimeFormatter[] f = iFormatter; - if (f == null) { - getFormatter(); - f = iFormatter; - if (f == null) { - return toStringList(); - } - } - DateTimeFormatter f1 = f[1]; - if (f1 == null) { - return toStringList(); - } - return f1.print(this); - } - - /** - * Gets a string version of the partial that lists all the fields. - *

- * This method exists to provide a better debugging toString than - * the standard toString. This method lists all the fields and their - * values in a style similar to the collections framework. - * - * @return a toString format that lists all the fields - */ - public String toStringList() { - int size = size(); - StringBuilder buf = new StringBuilder(20 * size); - buf.append('['); - for (int i = 0; i < size; i++) { - if (i > 0) { - buf.append(',').append(' '); - } - buf.append(iTypes[i].getName()); - buf.append('='); - buf.append(iValues[i]); - } - buf.append(']'); - return buf.toString(); - } - - /** - * Output the date using the specified format pattern. - * Unsupported fields will appear as special unicode characters. - * - * @param pattern the pattern specification, null means use toString - * @see org.joda.time.format.DateTimeFormat - */ - public String toString(String pattern) { - if (pattern == null) { - return toString(); - } - return DateTimeFormat.forPattern(pattern).print(this); - } - - /** - * Output the date using the specified format pattern. - * Unsupported fields will appear as special unicode characters. - * - * @param pattern the pattern specification, null means use toString - * @param locale Locale to use, null means default - * @see org.joda.time.format.DateTimeFormat - */ - public String toString(String pattern, Locale locale) { - if (pattern == null) { - return toString(); - } - return DateTimeFormat.forPattern(pattern).withLocale(locale).print(this); - } - - //----------------------------------------------------------------------- - /** - * The property class for Partial. - *

- * This class binds a Partial to a DateTimeField. - * - * @author Stephen Colebourne - * @since 1.1 - */ - public static class Property extends AbstractPartialFieldProperty implements Serializable { - - /** Serialization version */ - private static final long serialVersionUID = 53278362873888L; - - /** The partial */ - private final Partial iPartial; - /** The field index */ - private final int iFieldIndex; - - /** - * Constructs a property. - * - * @param partial the partial instance - * @param fieldIndex the index in the partial - */ - Property(Partial partial, int fieldIndex) { - super(); - iPartial = partial; - iFieldIndex = fieldIndex; - } - - /** - * Gets the field that this property uses. - * - * @return the field - */ - public DateTimeField getField() { - return iPartial.getField(iFieldIndex); - } - - /** - * Gets the partial that this property belongs to. - * - * @return the partial - */ - protected ReadablePartial getReadablePartial() { - return iPartial; - } - - /** - * Gets the partial that this property belongs to. - * - * @return the partial - */ - public Partial getPartial() { - return iPartial; - } - - /** - * Gets the value of this field. - * - * @return the field value - */ - public int get() { - return iPartial.getValue(iFieldIndex); - } - - //----------------------------------------------------------------------- - /** - * Adds to the value of this field in a copy of this Partial. - *

- * The value will be added to this field. If the value is too large to be - * added solely to this field then it will affect larger fields. - * Smaller fields are unaffected. - *

- * If the result would be too large, beyond the maximum year, then an - * IllegalArgumentException is thrown. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param valueToAdd the value to add to the field in the copy - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the value isn't valid - */ - public Partial addToCopy(int valueToAdd) { - int[] newValues = iPartial.getValues(); - newValues = getField().add(iPartial, iFieldIndex, newValues, valueToAdd); - return new Partial(iPartial, newValues); - } - - /** - * Adds to the value of this field in a copy of this Partial wrapping - * within this field if the maximum value is reached. - *

- * The value will be added to this field. If the value is too large to be - * added solely to this field then it wraps within this field. - * Other fields are unaffected. - *

- * For example, - * 2004-12-20 addWrapField one month returns 2004-01-20. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param valueToAdd the value to add to the field in the copy - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the value isn't valid - */ - public Partial addWrapFieldToCopy(int valueToAdd) { - int[] newValues = iPartial.getValues(); - newValues = getField().addWrapField(iPartial, iFieldIndex, newValues, valueToAdd); - return new Partial(iPartial, newValues); - } - - //----------------------------------------------------------------------- - /** - * Sets this field in a copy of the Partial. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param value the value to set the field in the copy to - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the value isn't valid - */ - public Partial setCopy(int value) { - int[] newValues = iPartial.getValues(); - newValues = getField().set(iPartial, iFieldIndex, newValues, value); - return new Partial(iPartial, newValues); - } - - /** - * Sets this field in a copy of the Partial to a parsed text value. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param text the text value to set - * @param locale optional locale to use for selecting a text symbol - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the text value isn't valid - */ - public Partial setCopy(String text, Locale locale) { - int[] newValues = iPartial.getValues(); - newValues = getField().set(iPartial, iFieldIndex, newValues, text, locale); - return new Partial(iPartial, newValues); - } - - /** - * Sets this field in a copy of the Partial to a parsed text value. - *

- * The Partial attached to this property is unchanged by this call. - * Instead, a new instance is returned. - * - * @param text the text value to set - * @return a copy of the Partial with the field value changed - * @throws IllegalArgumentException if the text value isn't valid - */ - public Partial setCopy(String text) { - return setCopy(text, null); - } - - //----------------------------------------------------------------------- - /** - * Returns a new Partial with this field set to the maximum value - * for this field. - *

- * The Partial attached to this property is unchanged by this call. - * - * @return a copy of the Partial with this field set to its maximum - * @since 1.2 - */ - public Partial withMaximumValue() { - return setCopy(getMaximumValue()); - } - - /** - * Returns a new Partial with this field set to the minimum value - * for this field. - *

- * The Partial attached to this property is unchanged by this call. - * - * @return a copy of the Partial with this field set to its minimum - * @since 1.2 - */ - public Partial withMinimumValue() { - return setCopy(getMinimumValue()); - } - } - -} diff --git a/All/Genesis-NP/Genesis#269/pair.info b/All/Genesis-NP/Genesis#269/pair.info deleted file mode 100755 index d3d78b1..0000000 --- a/All/Genesis-NP/Genesis#269/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:269 -SATName:Genesis -modifiedFPath:src/main/java/org/joda/time/Partial.java -comSha:4058d725e2b886e429233aa02bc45c3acf374471 -parentComSha:4058d725e2b886e429233aa02bc45c3acf374471^1 -githubUrl:https://github.com/JodaOrg/joda-time -repoName:JodaOrg#joda-time \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#270/comMsg.txt b/All/Genesis-NP/Genesis#270/comMsg.txt deleted file mode 100755 index 11d5776..0000000 --- a/All/Genesis-NP/Genesis#270/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix NPE in DateTimeUtils.isContiguous with weird partials [#89] diff --git a/All/Genesis-NP/Genesis#270/diff.diff b/All/Genesis-NP/Genesis#270/diff.diff deleted file mode 100755 index af547d2..0000000 --- a/All/Genesis-NP/Genesis#270/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/org/joda/time/DateTimeUtils.java b/src/main/java/org/joda/time/DateTimeUtils.java -index 4059c54..391cafd 100644 ---- a/src/main/java/org/joda/time/DateTimeUtils.java -+++ b/src/main/java/org/joda/time/DateTimeUtils.java -@@ -2 +2 @@ -- * Copyright 2001-2012 Stephen Colebourne -+ * Copyright 2001-2013 Stephen Colebourne -@@ -373 +373 @@ public class DateTimeUtils { -- if (loopField.getRangeDurationField().getType() != lastType) { -+ if (loopField.getRangeDurationField() == null || loopField.getRangeDurationField().getType() != lastType) { diff --git a/All/Genesis-NP/Genesis#270/new/DateTimeUtils.java b/All/Genesis-NP/Genesis#270/new/DateTimeUtils.java deleted file mode 100755 index 391cafd..0000000 --- a/All/Genesis-NP/Genesis#270/new/DateTimeUtils.java +++ /dev/null @@ -1,584 +0,0 @@ -/* - * Copyright 2001-2013 Stephen Colebourne - * - * 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.joda.time; - -import java.lang.reflect.Method; -import java.text.DateFormatSymbols; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; - -import org.joda.time.chrono.ISOChronology; - -/** - * DateTimeUtils provide public utility methods for the date-time library. - *

- * DateTimeUtils uses shared static variables which are declared as volatile - * for thread-safety. These can be changed during the lifetime of the application - * however doing so is generally a bad idea. - * - * @author Stephen Colebourne - * @since 1.0 - */ -public class DateTimeUtils { - - /** The singleton instance of the system millisecond provider. */ - private static final SystemMillisProvider SYSTEM_MILLIS_PROVIDER = new SystemMillisProvider(); - /** The millisecond provider currently in use. */ - private static volatile MillisProvider cMillisProvider = SYSTEM_MILLIS_PROVIDER; - /** The millisecond provider currently in use. */ - private static volatile Map cZoneNames; - static { - // names from RFC-822 / JDK - // this is all very US-centric and dubious, but perhaps it will help some - Map map = new LinkedHashMap(); - map.put("UT", DateTimeZone.UTC); - map.put("UTC", DateTimeZone.UTC); - map.put("GMT", DateTimeZone.UTC); - put(map, "EST", "America/New_York"); - put(map, "EDT", "America/New_York"); - put(map, "CST", "America/Chicago"); - put(map, "CDT", "America/Chicago"); - put(map, "MST", "America/Denver"); - put(map, "MDT", "America/Denver"); - put(map, "PST", "America/Los_Angeles"); - put(map, "PDT", "America/Los_Angeles"); - cZoneNames = Collections.unmodifiableMap(map); - } - private static void put(Map map, String name, String id) { - try { - map.put(name, DateTimeZone.forID(id)); - } catch (RuntimeException ex) { - // ignore - } - } - - /** - * Restrictive constructor - */ - protected DateTimeUtils() { - super(); - } - - //----------------------------------------------------------------------- - /** - * Gets the current time in milliseconds. - *

- * By default this returns System.currentTimeMillis(). - * This may be changed using other methods in this class. - * - * @return the current time in milliseconds from 1970-01-01T00:00:00Z - */ - public static final long currentTimeMillis() { - return cMillisProvider.getMillis(); - } - - /** - * Resets the current time to return the system time. - *

- * This method changes the behaviour of {@link #currentTimeMillis()}. - * Whenever the current time is queried, {@link System#currentTimeMillis()} is used. - * - * @throws SecurityException if the application does not have sufficient security rights - */ - public static final void setCurrentMillisSystem() throws SecurityException { - checkPermission(); - cMillisProvider = SYSTEM_MILLIS_PROVIDER; - } - - /** - * Sets the current time to return a fixed millisecond time. - *

- * This method changes the behaviour of {@link #currentTimeMillis()}. - * Whenever the current time is queried, the same millisecond time will be returned. - * - * @param fixedMillis the fixed millisecond time to use - * @throws SecurityException if the application does not have sufficient security rights - */ - public static final void setCurrentMillisFixed(long fixedMillis) throws SecurityException { - checkPermission(); - cMillisProvider = new FixedMillisProvider(fixedMillis); - } - - /** - * Sets the current time to return the system time plus an offset. - *

- * This method changes the behaviour of {@link #currentTimeMillis()}. - * Whenever the current time is queried, {@link System#currentTimeMillis()} is used - * and then offset by adding the millisecond value specified here. - * - * @param offsetMillis the fixed millisecond time to use - * @throws SecurityException if the application does not have sufficient security rights - */ - public static final void setCurrentMillisOffset(long offsetMillis) throws SecurityException { - checkPermission(); - if (offsetMillis == 0) { - cMillisProvider = SYSTEM_MILLIS_PROVIDER; - } else { - cMillisProvider = new OffsetMillisProvider(offsetMillis); - } - } - - /** - * Sets the provider of the current time to class specified. - *

- * This method changes the behaviour of {@link #currentTimeMillis()}. - * Whenever the current time is queried, the specified class will be called. - * - * @param millisProvider the provider of the current time to use, not null - * @throws SecurityException if the application does not have sufficient security rights - * @since 2.0 - */ - public static final void setCurrentMillisProvider(MillisProvider millisProvider) throws SecurityException { - if (millisProvider == null) { - throw new IllegalArgumentException("The MillisProvider must not be null"); - } - checkPermission(); - cMillisProvider = millisProvider; - } - - /** - * Checks whether the provider may be changed using permission 'CurrentTime.setProvider'. - * - * @throws SecurityException if the provider may not be changed - */ - private static void checkPermission() throws SecurityException { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new JodaTimePermission("CurrentTime.setProvider")); - } - } - - //----------------------------------------------------------------------- - /** - * Gets the millisecond instant from the specified instant object handling null. - *

- * If the instant object is null, the {@link #currentTimeMillis()} - * will be returned. Otherwise, the millis from the object are returned. - * - * @param instant the instant to examine, null means now - * @return the time in milliseconds from 1970-01-01T00:00:00Z - */ - public static final long getInstantMillis(ReadableInstant instant) { - if (instant == null) { - return DateTimeUtils.currentTimeMillis(); - } - return instant.getMillis(); - } - - //----------------------------------------------------------------------- - /** - * Gets the chronology from the specified instant object handling null. - *

- * If the instant object is null, or the instant's chronology is - * null, {@link ISOChronology#getInstance()} will be returned. - * Otherwise, the chronology from the object is returned. - * - * @param instant the instant to examine, null means ISO in the default zone - * @return the chronology, never null - */ - public static final Chronology getInstantChronology(ReadableInstant instant) { - if (instant == null) { - return ISOChronology.getInstance(); - } - Chronology chrono = instant.getChronology(); - if (chrono == null) { - return ISOChronology.getInstance(); - } - return chrono; - } - - //----------------------------------------------------------------------- - /** - * Gets the chronology from the specified instant based interval handling null. - *

- * The chronology is obtained from the start if that is not null, or from the - * end if the start is null. The result is additionally checked, and if still - * null then {@link ISOChronology#getInstance()} will be returned. - * - * @param start the instant to examine and use as the primary source of the chronology - * @param end the instant to examine and use as the secondary source of the chronology - * @return the chronology, never null - */ - public static final Chronology getIntervalChronology(ReadableInstant start, ReadableInstant end) { - Chronology chrono = null; - if (start != null) { - chrono = start.getChronology(); - } else if (end != null) { - chrono = end.getChronology(); - } - if (chrono == null) { - chrono = ISOChronology.getInstance(); - } - return chrono; - } - - //----------------------------------------------------------------------- - /** - * Gets the chronology from the specified interval object handling null. - *

- * If the interval object is null, or the interval's chronology is - * null, {@link ISOChronology#getInstance()} will be returned. - * Otherwise, the chronology from the object is returned. - * - * @param interval the interval to examine, null means ISO in the default zone - * @return the chronology, never null - */ - public static final Chronology getIntervalChronology(ReadableInterval interval) { - if (interval == null) { - return ISOChronology.getInstance(); - } - Chronology chrono = interval.getChronology(); - if (chrono == null) { - return ISOChronology.getInstance(); - } - return chrono; - } - - //----------------------------------------------------------------------- - /** - * Gets the interval handling null. - *

- * If the interval is null, an interval representing now - * to now in the {@link ISOChronology#getInstance() ISOChronology} - * will be returned. Otherwise, the interval specified is returned. - * - * @param interval the interval to use, null means now to now - * @return the interval, never null - * @since 1.1 - */ - public static final ReadableInterval getReadableInterval(ReadableInterval interval) { - if (interval == null) { - long now = DateTimeUtils.currentTimeMillis(); - interval = new Interval(now, now); - } - return interval; - } - - //----------------------------------------------------------------------- - /** - * Gets the chronology handling null. - *

- * If the chronology is null, {@link ISOChronology#getInstance()} - * will be returned. Otherwise, the chronology is returned. - * - * @param chrono the chronology to use, null means ISO in the default zone - * @return the chronology, never null - */ - public static final Chronology getChronology(Chronology chrono) { - if (chrono == null) { - return ISOChronology.getInstance(); - } - return chrono; - } - - //----------------------------------------------------------------------- - /** - * Gets the zone handling null. - *

- * If the zone is null, {@link DateTimeZone#getDefault()} - * will be returned. Otherwise, the zone specified is returned. - * - * @param zone the time zone to use, null means the default zone - * @return the time zone, never null - */ - public static final DateTimeZone getZone(DateTimeZone zone) { - if (zone == null) { - return DateTimeZone.getDefault(); - } - return zone; - } - - //----------------------------------------------------------------------- - /** - * Gets the period type handling null. - *

- * If the zone is null, {@link PeriodType#standard()} - * will be returned. Otherwise, the type specified is returned. - * - * @param type the time zone to use, null means the standard type - * @return the type to use, never null - */ - public static final PeriodType getPeriodType(PeriodType type) { - if (type == null) { - return PeriodType.standard(); - } - return type; - } - - //----------------------------------------------------------------------- - /** - * Gets the millisecond duration from the specified duration object handling null. - *

- * If the duration object is null, zero will be returned. - * Otherwise, the millis from the object are returned. - * - * @param duration the duration to examine, null means zero - * @return the duration in milliseconds - */ - public static final long getDurationMillis(ReadableDuration duration) { - if (duration == null) { - return 0L; - } - return duration.getMillis(); - } - - //----------------------------------------------------------------------- - /** - * Checks whether the partial is contiguous. - *

- * A partial is contiguous if one field starts where another ends. - *

- * For example LocalDate is contiguous because DayOfMonth has - * the same range (Month) as the unit of the next field (MonthOfYear), and - * MonthOfYear has the same range (Year) as the unit of the next field (Year). - *

- * Similarly, LocalTime is contiguous, as it consists of - * MillisOfSecond, SecondOfMinute, MinuteOfHour and HourOfDay (note how - * the names of each field 'join up'). - *

- * However, a Year/HourOfDay partial is not contiguous because the range - * field Day is not equal to the next field Year. - * Similarly, a DayOfWeek/DayOfMonth partial is not contiguous because - * the range Month is not equal to the next field Day. - * - * @param partial the partial to check - * @return true if the partial is contiguous - * @throws IllegalArgumentException if the partial is null - * @since 1.1 - */ - public static final boolean isContiguous(ReadablePartial partial) { - if (partial == null) { - throw new IllegalArgumentException("Partial must not be null"); - } - DurationFieldType lastType = null; - for (int i = 0; i < partial.size(); i++) { - DateTimeField loopField = partial.getField(i); - if (i > 0) { - if (loopField.getRangeDurationField() == null || loopField.getRangeDurationField().getType() != lastType) { - return false; - } - } - lastType = loopField.getDurationField().getType(); - } - return true; - } - - //----------------------------------------------------------------------- - /** - * Gets the {@link DateFormatSymbols} based on the given locale. - *

- * If JDK 6 or newer is being used, DateFormatSymbols.getInstance(locale) will - * be used in order to allow the use of locales defined as extensions. - * Otherwise, new DateFormatSymbols(locale) will be used. - * See JDK 6 {@link DateFormatSymbols} for further information. - * - * @param locale the {@link Locale} used to get the correct {@link DateFormatSymbols} - * @return the symbols - * @since 2.0 - */ - public static final DateFormatSymbols getDateFormatSymbols(Locale locale) { - try { - Method method = DateFormatSymbols.class.getMethod("getInstance", new Class[] {Locale.class}); - return (DateFormatSymbols) method.invoke(null, new Object[] {locale}); - } catch (Exception ex) { - return new DateFormatSymbols(locale); - } - } - - //----------------------------------------------------------------------- - /** - * Gets the default map of time zone names. - *

- * This can be changed by {@link #setDefaultTimeZoneNames}. - *

- * The default set of short time zone names is as follows: - *

    - *
  • UT - UTC - *
  • UTC - UTC - *
  • GMT - UTC - *
  • EST - America/New_York - *
  • EDT - America/New_York - *
  • CST - America/Chicago - *
  • CDT - America/Chicago - *
  • MST - America/Denver - *
  • MDT - America/Denver - *
  • PST - America/Los_Angeles - *
  • PDT - America/Los_Angeles - *
- * - * @return the unmodifiable map of abbreviations to zones, not null - * @since 2.2 - */ - public static final Map getDefaultTimeZoneNames() { - return cZoneNames; - } - - /** - * Sets the default map of time zone names. - *

- * The map is copied before storage. - * - * @param names the map of abbreviations to zones, not null - * @since 2.2 - */ - public static final void setDefaultTimeZoneNames(Map names) { - cZoneNames = Collections.unmodifiableMap(new HashMap(names)); - } - - //------------------------------------------------------------------------- - /** - * Calculates the astronomical Julian Day for an instant. - *

- * The Julian day is a well-known - * system of time measurement for scientific use by the astronomy community. - * It expresses the interval of time in days and fractions of a day since - * January 1, 4713 BC (Julian) Greenwich noon. - *

- * Each day starts at midday (not midnight) and time is expressed as a fraction. - * Thus the fraction 0.25 is 18:00. equal to one quarter of the day from midday to midday. - *

- * Note that this method has nothing to do with the day-of-year. - * - * @param epochMillis the epoch millis from 1970-01-01Z - * @return the astronomical Julian Day represented by the specified instant - * @since 2.2 - */ - public static final double toJulianDay(long epochMillis) { - // useful links - // http://en.wikipedia.org/wiki/Julian_day#cite_note-13 - Wikipedia - // http://aa.usno.navy.mil/data/docs/JulianDate.php" - USNO - // http://users.zoominternet.net/~matto/Java/Julian%20Date%20Converter.htm - Julian Date Converter by Matt Oltersdorf - // http://ssd.jpl.nasa.gov/tc.cgi#top - CalTech - double epochDay = epochMillis / 86400000d; - return epochDay + 2440587.5d; - } - - /** - * Calculates the astronomical Julian Day Number for an instant. - *

- * The {@link #toJulianDay(long)} method calculates the astronomical Julian Day - * with a fraction based on days starting at midday. - * This method calculates the variant where days start at midnight. - * JDN 0 is used for the date equivalent to Monday January 1, 4713 BC (Julian). - * Thus these days start 12 hours before those of the fractional Julian Day. - *

- * Note that this method has nothing to do with the day-of-year. - * - * @param epochMillis the epoch millis from 1970-01-01Z - * @return the astronomical Julian Day represented by the specified instant - * @since 2.2 - */ - public static final long toJulianDayNumber(long epochMillis) { - return (long) Math.floor(toJulianDay(epochMillis) + 0.5d); - } - - /** - * Creates a date-time from a Julian Day. - *

- * Returns the {@code DateTime} object equal to the specified Julian Day. - * - * @param julianDay the Julian Day - * @return the epoch millis from 1970-01-01Z - * @since 2.2 - */ - public static final long fromJulianDay(double julianDay) { - double epochDay = julianDay - 2440587.5d; - return (long) (epochDay * 86400000d); - } - - //----------------------------------------------------------------------- - /** - * A millisecond provider, allowing control of the system clock. - * - * @author Stephen Colebourne - * @since 2.0 (previously private) - */ - public static interface MillisProvider { - /** - * Gets the current time. - *

- * Implementations of this method must be thread-safe. - * - * @return the current time in milliseconds - */ - long getMillis(); - } - - /** - * System millis provider. - */ - static class SystemMillisProvider implements MillisProvider { - /** - * Gets the current time. - * @return the current time in millis - */ - public long getMillis() { - return System.currentTimeMillis(); - } - } - - /** - * Fixed millisecond provider. - */ - static class FixedMillisProvider implements MillisProvider { - /** The fixed millis value. */ - private final long iMillis; - - /** - * Constructor. - * @param offsetMillis the millis offset - */ - FixedMillisProvider(long fixedMillis) { - iMillis = fixedMillis; - } - - /** - * Gets the current time. - * @return the current time in millis - */ - public long getMillis() { - return iMillis; - } - } - - /** - * Offset from system millis provider. - */ - static class OffsetMillisProvider implements MillisProvider { - /** The millis offset. */ - private final long iMillis; - - /** - * Constructor. - * @param offsetMillis the millis offset - */ - OffsetMillisProvider(long offsetMillis) { - iMillis = offsetMillis; - } - - /** - * Gets the current time. - * @return the current time in millis - */ - public long getMillis() { - return System.currentTimeMillis() + iMillis; - } - } - -} diff --git a/All/Genesis-NP/Genesis#270/new/RELEASE-NOTES.txt b/All/Genesis-NP/Genesis#270/new/RELEASE-NOTES.txt deleted file mode 100755 index 69ff24b..0000000 --- a/All/Genesis-NP/Genesis#270/new/RELEASE-NOTES.txt +++ /dev/null @@ -1,97 +0,0 @@ -Joda-Time version 2.4 ---------------------- - -Joda-Time is a date and time handling library that seeks to replace the JDK -Date and Calendar classes. - -This release contains enhancements, bug fixes and a time zone update. -The release runs on JDK 5 or later. - -Joda-Time is licensed under the business-friendly Apache License Version 2. -This is the same license as all of Apache, plus other open source projects such as Spring. -The intent is to make the code available to the Java community with the minimum -of restrictions. If the license causes you problems please contact the mailing list. - -** Please also check out our related projects ** -** http://www.joda.org/joda-time/related.html ** - - -Enhancements since 2.3 ----------------------- -- Duration.multipliedBy(), .dividedBy(), .negated() - Additional methods on Duration - -- LocalDate.hashCode() - Remove unnecessary volatile on instance variable [#68] - LocalDate hash code meets criteria of the racy single-check idiom - - -Compatibility with 2.3 ----------------------- -Build system - Yes - -Binary compatible - Yes - -Source compatible - Yes - -Serialization compatible - Yes - -Data compatible - Yes, except - - DateTimeZone data updated to version 2013d - -Semantic compatible - Yes, except -- DateTimeField duration fields have been fixed - For example, yearOfEra() now has a range of eras() rather than null - The DurationField instances now compare using equals() correctly - - -Deprecations since 2.3 ----------------------- - - -Bug fixes since 2.3 -------------------- -- DateTimeField.getDurationField() / DateTimeField.getRangeDurationField() [#92] - Previously some of the complex cases were wrong, notably around centuries and eras - For example, yearOfEra() returned a range of null when it should be eras() - A slew of tests were added and a variety of bugs fixed - This affects DateTimeField.getDurationField() and DateTimeField.getRangeDurationField() - -- DateTimeUtils.isContiguous(ReadablePartial) [#89] - The isContiguous() method could throw a NullPointerException when evaluating weird partials - -- Period.normalizedStandard(PeriodType) [#79] - Fix handling of PeriodType when either years or months missing - -- Better Javadoc for parsing of numbers in format patterns [#60] - -- Remove uncaughtException calls [#59] - Previously the code called ThreadGroup.uncaughtException() which was invalid - -- Better Javadoc for thread saefty of DateTimeUtils [#67] - -- Better Javadoc for DateTimeComparator [#73] - -- Fix the links to the IANA time zone database [#83] - -- Better Javadoc for DateTimeFormatter parsing [#78] - -- Better Javadoc for DateTimeFormat fraction of second [#62] - - -Scala --------- -Joda-Time uses annotations from Joda-Convert. -In the Java programming language, this dependency is optional, however in Scala it is not. -Scala users must manually add the Joda-Convert v1.2 dependency. - - -Feedback --------- -Feedback is best received using GitHub issues and Pull Requests. -https://github.com/JodaOrg/joda-time/ - -Feedback is also welcomed via the joda-interest mailing list. - -The Joda team -http://www.joda.org/joda-time/ diff --git a/All/Genesis-NP/Genesis#270/old/DateTimeUtils.java b/All/Genesis-NP/Genesis#270/old/DateTimeUtils.java deleted file mode 100755 index 4059c54..0000000 --- a/All/Genesis-NP/Genesis#270/old/DateTimeUtils.java +++ /dev/null @@ -1,584 +0,0 @@ -/* - * Copyright 2001-2012 Stephen Colebourne - * - * 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.joda.time; - -import java.lang.reflect.Method; -import java.text.DateFormatSymbols; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; - -import org.joda.time.chrono.ISOChronology; - -/** - * DateTimeUtils provide public utility methods for the date-time library. - *

- * DateTimeUtils uses shared static variables which are declared as volatile - * for thread-safety. These can be changed during the lifetime of the application - * however doing so is generally a bad idea. - * - * @author Stephen Colebourne - * @since 1.0 - */ -public class DateTimeUtils { - - /** The singleton instance of the system millisecond provider. */ - private static final SystemMillisProvider SYSTEM_MILLIS_PROVIDER = new SystemMillisProvider(); - /** The millisecond provider currently in use. */ - private static volatile MillisProvider cMillisProvider = SYSTEM_MILLIS_PROVIDER; - /** The millisecond provider currently in use. */ - private static volatile Map cZoneNames; - static { - // names from RFC-822 / JDK - // this is all very US-centric and dubious, but perhaps it will help some - Map map = new LinkedHashMap(); - map.put("UT", DateTimeZone.UTC); - map.put("UTC", DateTimeZone.UTC); - map.put("GMT", DateTimeZone.UTC); - put(map, "EST", "America/New_York"); - put(map, "EDT", "America/New_York"); - put(map, "CST", "America/Chicago"); - put(map, "CDT", "America/Chicago"); - put(map, "MST", "America/Denver"); - put(map, "MDT", "America/Denver"); - put(map, "PST", "America/Los_Angeles"); - put(map, "PDT", "America/Los_Angeles"); - cZoneNames = Collections.unmodifiableMap(map); - } - private static void put(Map map, String name, String id) { - try { - map.put(name, DateTimeZone.forID(id)); - } catch (RuntimeException ex) { - // ignore - } - } - - /** - * Restrictive constructor - */ - protected DateTimeUtils() { - super(); - } - - //----------------------------------------------------------------------- - /** - * Gets the current time in milliseconds. - *

- * By default this returns System.currentTimeMillis(). - * This may be changed using other methods in this class. - * - * @return the current time in milliseconds from 1970-01-01T00:00:00Z - */ - public static final long currentTimeMillis() { - return cMillisProvider.getMillis(); - } - - /** - * Resets the current time to return the system time. - *

- * This method changes the behaviour of {@link #currentTimeMillis()}. - * Whenever the current time is queried, {@link System#currentTimeMillis()} is used. - * - * @throws SecurityException if the application does not have sufficient security rights - */ - public static final void setCurrentMillisSystem() throws SecurityException { - checkPermission(); - cMillisProvider = SYSTEM_MILLIS_PROVIDER; - } - - /** - * Sets the current time to return a fixed millisecond time. - *

- * This method changes the behaviour of {@link #currentTimeMillis()}. - * Whenever the current time is queried, the same millisecond time will be returned. - * - * @param fixedMillis the fixed millisecond time to use - * @throws SecurityException if the application does not have sufficient security rights - */ - public static final void setCurrentMillisFixed(long fixedMillis) throws SecurityException { - checkPermission(); - cMillisProvider = new FixedMillisProvider(fixedMillis); - } - - /** - * Sets the current time to return the system time plus an offset. - *

- * This method changes the behaviour of {@link #currentTimeMillis()}. - * Whenever the current time is queried, {@link System#currentTimeMillis()} is used - * and then offset by adding the millisecond value specified here. - * - * @param offsetMillis the fixed millisecond time to use - * @throws SecurityException if the application does not have sufficient security rights - */ - public static final void setCurrentMillisOffset(long offsetMillis) throws SecurityException { - checkPermission(); - if (offsetMillis == 0) { - cMillisProvider = SYSTEM_MILLIS_PROVIDER; - } else { - cMillisProvider = new OffsetMillisProvider(offsetMillis); - } - } - - /** - * Sets the provider of the current time to class specified. - *

- * This method changes the behaviour of {@link #currentTimeMillis()}. - * Whenever the current time is queried, the specified class will be called. - * - * @param millisProvider the provider of the current time to use, not null - * @throws SecurityException if the application does not have sufficient security rights - * @since 2.0 - */ - public static final void setCurrentMillisProvider(MillisProvider millisProvider) throws SecurityException { - if (millisProvider == null) { - throw new IllegalArgumentException("The MillisProvider must not be null"); - } - checkPermission(); - cMillisProvider = millisProvider; - } - - /** - * Checks whether the provider may be changed using permission 'CurrentTime.setProvider'. - * - * @throws SecurityException if the provider may not be changed - */ - private static void checkPermission() throws SecurityException { - SecurityManager sm = System.getSecurityManager(); - if (sm != null) { - sm.checkPermission(new JodaTimePermission("CurrentTime.setProvider")); - } - } - - //----------------------------------------------------------------------- - /** - * Gets the millisecond instant from the specified instant object handling null. - *

- * If the instant object is null, the {@link #currentTimeMillis()} - * will be returned. Otherwise, the millis from the object are returned. - * - * @param instant the instant to examine, null means now - * @return the time in milliseconds from 1970-01-01T00:00:00Z - */ - public static final long getInstantMillis(ReadableInstant instant) { - if (instant == null) { - return DateTimeUtils.currentTimeMillis(); - } - return instant.getMillis(); - } - - //----------------------------------------------------------------------- - /** - * Gets the chronology from the specified instant object handling null. - *

- * If the instant object is null, or the instant's chronology is - * null, {@link ISOChronology#getInstance()} will be returned. - * Otherwise, the chronology from the object is returned. - * - * @param instant the instant to examine, null means ISO in the default zone - * @return the chronology, never null - */ - public static final Chronology getInstantChronology(ReadableInstant instant) { - if (instant == null) { - return ISOChronology.getInstance(); - } - Chronology chrono = instant.getChronology(); - if (chrono == null) { - return ISOChronology.getInstance(); - } - return chrono; - } - - //----------------------------------------------------------------------- - /** - * Gets the chronology from the specified instant based interval handling null. - *

- * The chronology is obtained from the start if that is not null, or from the - * end if the start is null. The result is additionally checked, and if still - * null then {@link ISOChronology#getInstance()} will be returned. - * - * @param start the instant to examine and use as the primary source of the chronology - * @param end the instant to examine and use as the secondary source of the chronology - * @return the chronology, never null - */ - public static final Chronology getIntervalChronology(ReadableInstant start, ReadableInstant end) { - Chronology chrono = null; - if (start != null) { - chrono = start.getChronology(); - } else if (end != null) { - chrono = end.getChronology(); - } - if (chrono == null) { - chrono = ISOChronology.getInstance(); - } - return chrono; - } - - //----------------------------------------------------------------------- - /** - * Gets the chronology from the specified interval object handling null. - *

- * If the interval object is null, or the interval's chronology is - * null, {@link ISOChronology#getInstance()} will be returned. - * Otherwise, the chronology from the object is returned. - * - * @param interval the interval to examine, null means ISO in the default zone - * @return the chronology, never null - */ - public static final Chronology getIntervalChronology(ReadableInterval interval) { - if (interval == null) { - return ISOChronology.getInstance(); - } - Chronology chrono = interval.getChronology(); - if (chrono == null) { - return ISOChronology.getInstance(); - } - return chrono; - } - - //----------------------------------------------------------------------- - /** - * Gets the interval handling null. - *

- * If the interval is null, an interval representing now - * to now in the {@link ISOChronology#getInstance() ISOChronology} - * will be returned. Otherwise, the interval specified is returned. - * - * @param interval the interval to use, null means now to now - * @return the interval, never null - * @since 1.1 - */ - public static final ReadableInterval getReadableInterval(ReadableInterval interval) { - if (interval == null) { - long now = DateTimeUtils.currentTimeMillis(); - interval = new Interval(now, now); - } - return interval; - } - - //----------------------------------------------------------------------- - /** - * Gets the chronology handling null. - *

- * If the chronology is null, {@link ISOChronology#getInstance()} - * will be returned. Otherwise, the chronology is returned. - * - * @param chrono the chronology to use, null means ISO in the default zone - * @return the chronology, never null - */ - public static final Chronology getChronology(Chronology chrono) { - if (chrono == null) { - return ISOChronology.getInstance(); - } - return chrono; - } - - //----------------------------------------------------------------------- - /** - * Gets the zone handling null. - *

- * If the zone is null, {@link DateTimeZone#getDefault()} - * will be returned. Otherwise, the zone specified is returned. - * - * @param zone the time zone to use, null means the default zone - * @return the time zone, never null - */ - public static final DateTimeZone getZone(DateTimeZone zone) { - if (zone == null) { - return DateTimeZone.getDefault(); - } - return zone; - } - - //----------------------------------------------------------------------- - /** - * Gets the period type handling null. - *

- * If the zone is null, {@link PeriodType#standard()} - * will be returned. Otherwise, the type specified is returned. - * - * @param type the time zone to use, null means the standard type - * @return the type to use, never null - */ - public static final PeriodType getPeriodType(PeriodType type) { - if (type == null) { - return PeriodType.standard(); - } - return type; - } - - //----------------------------------------------------------------------- - /** - * Gets the millisecond duration from the specified duration object handling null. - *

- * If the duration object is null, zero will be returned. - * Otherwise, the millis from the object are returned. - * - * @param duration the duration to examine, null means zero - * @return the duration in milliseconds - */ - public static final long getDurationMillis(ReadableDuration duration) { - if (duration == null) { - return 0L; - } - return duration.getMillis(); - } - - //----------------------------------------------------------------------- - /** - * Checks whether the partial is contiguous. - *

- * A partial is contiguous if one field starts where another ends. - *

- * For example LocalDate is contiguous because DayOfMonth has - * the same range (Month) as the unit of the next field (MonthOfYear), and - * MonthOfYear has the same range (Year) as the unit of the next field (Year). - *

- * Similarly, LocalTime is contiguous, as it consists of - * MillisOfSecond, SecondOfMinute, MinuteOfHour and HourOfDay (note how - * the names of each field 'join up'). - *

- * However, a Year/HourOfDay partial is not contiguous because the range - * field Day is not equal to the next field Year. - * Similarly, a DayOfWeek/DayOfMonth partial is not contiguous because - * the range Month is not equal to the next field Day. - * - * @param partial the partial to check - * @return true if the partial is contiguous - * @throws IllegalArgumentException if the partial is null - * @since 1.1 - */ - public static final boolean isContiguous(ReadablePartial partial) { - if (partial == null) { - throw new IllegalArgumentException("Partial must not be null"); - } - DurationFieldType lastType = null; - for (int i = 0; i < partial.size(); i++) { - DateTimeField loopField = partial.getField(i); - if (i > 0) { - if (loopField.getRangeDurationField().getType() != lastType) { - return false; - } - } - lastType = loopField.getDurationField().getType(); - } - return true; - } - - //----------------------------------------------------------------------- - /** - * Gets the {@link DateFormatSymbols} based on the given locale. - *

- * If JDK 6 or newer is being used, DateFormatSymbols.getInstance(locale) will - * be used in order to allow the use of locales defined as extensions. - * Otherwise, new DateFormatSymbols(locale) will be used. - * See JDK 6 {@link DateFormatSymbols} for further information. - * - * @param locale the {@link Locale} used to get the correct {@link DateFormatSymbols} - * @return the symbols - * @since 2.0 - */ - public static final DateFormatSymbols getDateFormatSymbols(Locale locale) { - try { - Method method = DateFormatSymbols.class.getMethod("getInstance", new Class[] {Locale.class}); - return (DateFormatSymbols) method.invoke(null, new Object[] {locale}); - } catch (Exception ex) { - return new DateFormatSymbols(locale); - } - } - - //----------------------------------------------------------------------- - /** - * Gets the default map of time zone names. - *

- * This can be changed by {@link #setDefaultTimeZoneNames}. - *

- * The default set of short time zone names is as follows: - *

    - *
  • UT - UTC - *
  • UTC - UTC - *
  • GMT - UTC - *
  • EST - America/New_York - *
  • EDT - America/New_York - *
  • CST - America/Chicago - *
  • CDT - America/Chicago - *
  • MST - America/Denver - *
  • MDT - America/Denver - *
  • PST - America/Los_Angeles - *
  • PDT - America/Los_Angeles - *
- * - * @return the unmodifiable map of abbreviations to zones, not null - * @since 2.2 - */ - public static final Map getDefaultTimeZoneNames() { - return cZoneNames; - } - - /** - * Sets the default map of time zone names. - *

- * The map is copied before storage. - * - * @param names the map of abbreviations to zones, not null - * @since 2.2 - */ - public static final void setDefaultTimeZoneNames(Map names) { - cZoneNames = Collections.unmodifiableMap(new HashMap(names)); - } - - //------------------------------------------------------------------------- - /** - * Calculates the astronomical Julian Day for an instant. - *

- * The Julian day is a well-known - * system of time measurement for scientific use by the astronomy community. - * It expresses the interval of time in days and fractions of a day since - * January 1, 4713 BC (Julian) Greenwich noon. - *

- * Each day starts at midday (not midnight) and time is expressed as a fraction. - * Thus the fraction 0.25 is 18:00. equal to one quarter of the day from midday to midday. - *

- * Note that this method has nothing to do with the day-of-year. - * - * @param epochMillis the epoch millis from 1970-01-01Z - * @return the astronomical Julian Day represented by the specified instant - * @since 2.2 - */ - public static final double toJulianDay(long epochMillis) { - // useful links - // http://en.wikipedia.org/wiki/Julian_day#cite_note-13 - Wikipedia - // http://aa.usno.navy.mil/data/docs/JulianDate.php" - USNO - // http://users.zoominternet.net/~matto/Java/Julian%20Date%20Converter.htm - Julian Date Converter by Matt Oltersdorf - // http://ssd.jpl.nasa.gov/tc.cgi#top - CalTech - double epochDay = epochMillis / 86400000d; - return epochDay + 2440587.5d; - } - - /** - * Calculates the astronomical Julian Day Number for an instant. - *

- * The {@link #toJulianDay(long)} method calculates the astronomical Julian Day - * with a fraction based on days starting at midday. - * This method calculates the variant where days start at midnight. - * JDN 0 is used for the date equivalent to Monday January 1, 4713 BC (Julian). - * Thus these days start 12 hours before those of the fractional Julian Day. - *

- * Note that this method has nothing to do with the day-of-year. - * - * @param epochMillis the epoch millis from 1970-01-01Z - * @return the astronomical Julian Day represented by the specified instant - * @since 2.2 - */ - public static final long toJulianDayNumber(long epochMillis) { - return (long) Math.floor(toJulianDay(epochMillis) + 0.5d); - } - - /** - * Creates a date-time from a Julian Day. - *

- * Returns the {@code DateTime} object equal to the specified Julian Day. - * - * @param julianDay the Julian Day - * @return the epoch millis from 1970-01-01Z - * @since 2.2 - */ - public static final long fromJulianDay(double julianDay) { - double epochDay = julianDay - 2440587.5d; - return (long) (epochDay * 86400000d); - } - - //----------------------------------------------------------------------- - /** - * A millisecond provider, allowing control of the system clock. - * - * @author Stephen Colebourne - * @since 2.0 (previously private) - */ - public static interface MillisProvider { - /** - * Gets the current time. - *

- * Implementations of this method must be thread-safe. - * - * @return the current time in milliseconds - */ - long getMillis(); - } - - /** - * System millis provider. - */ - static class SystemMillisProvider implements MillisProvider { - /** - * Gets the current time. - * @return the current time in millis - */ - public long getMillis() { - return System.currentTimeMillis(); - } - } - - /** - * Fixed millisecond provider. - */ - static class FixedMillisProvider implements MillisProvider { - /** The fixed millis value. */ - private final long iMillis; - - /** - * Constructor. - * @param offsetMillis the millis offset - */ - FixedMillisProvider(long fixedMillis) { - iMillis = fixedMillis; - } - - /** - * Gets the current time. - * @return the current time in millis - */ - public long getMillis() { - return iMillis; - } - } - - /** - * Offset from system millis provider. - */ - static class OffsetMillisProvider implements MillisProvider { - /** The millis offset. */ - private final long iMillis; - - /** - * Constructor. - * @param offsetMillis the millis offset - */ - OffsetMillisProvider(long offsetMillis) { - iMillis = offsetMillis; - } - - /** - * Gets the current time. - * @return the current time in millis - */ - public long getMillis() { - return System.currentTimeMillis() + iMillis; - } - } - -} diff --git a/All/Genesis-NP/Genesis#270/old/RELEASE-NOTES.txt b/All/Genesis-NP/Genesis#270/old/RELEASE-NOTES.txt deleted file mode 100755 index d8817cc..0000000 --- a/All/Genesis-NP/Genesis#270/old/RELEASE-NOTES.txt +++ /dev/null @@ -1,94 +0,0 @@ -Joda-Time version 2.4 ---------------------- - -Joda-Time is a date and time handling library that seeks to replace the JDK -Date and Calendar classes. - -This release contains enhancements, bug fixes and a time zone update. -The release runs on JDK 5 or later. - -Joda-Time is licensed under the business-friendly Apache License Version 2. -This is the same license as all of Apache, plus other open source projects such as Spring. -The intent is to make the code available to the Java community with the minimum -of restrictions. If the license causes you problems please contact the mailing list. - -** Please also check out our related projects ** -** http://www.joda.org/joda-time/related.html ** - - -Enhancements since 2.3 ----------------------- -- Duration.multipliedBy(), .dividedBy(), .negated() - Additional methods on Duration - -- LocalDate.hashCode() - Remove unnecessary volatile on instance variable [#68] - LocalDate hash code meets criteria of the racy single-check idiom - - -Compatibility with 2.3 ----------------------- -Build system - Yes - -Binary compatible - Yes - -Source compatible - Yes - -Serialization compatible - Yes - -Data compatible - Yes, except - - DateTimeZone data updated to version 2013d - -Semantic compatible - Yes, except -- DateTimeField duration fields have been fixed - For example, yearOfEra() now has a range of eras() rather than null - The DurationField instances now compare using equals() correctly - - -Deprecations since 2.3 ----------------------- - - -Bug fixes since 2.3 -------------------- -- DateTimeField.getDurationField() / DateTimeField.getRangeDurationField() [#92] - Previously some of the complex cases were wrong, notably around centuries and eras - For example, yearOfEra() returned a range of null when it should be eras() - A slew of tests were added and a variety of bugs fixed - This affects DateTimeField.getDurationField() and DateTimeField.getRangeDurationField() - -- Period.normalizedStandard(PeriodType) [#79] - Fix handling of PeriodType when either years or months missing - -- Better Javadoc for parsing of numbers in format patterns [#60] - -- Remove uncaughtException calls [#59] - Previously the code called ThreadGroup.uncaughtException() which was invalid - -- Better Javadoc for thread saefty of DateTimeUtils [#67] - -- Better Javadoc for DateTimeComparator [#73] - -- Fix the links to the IANA time zone database [#83] - -- Better Javadoc for DateTimeFormatter parsing [#78] - -- Better Javadoc for DateTimeFormat fraction of second [#62] - - -Scala --------- -Joda-Time uses annotations from Joda-Convert. -In the Java programming language, this dependency is optional, however in Scala it is not. -Scala users must manually add the Joda-Convert v1.2 dependency. - - -Feedback --------- -Feedback is best received using GitHub issues and Pull Requests. -https://github.com/JodaOrg/joda-time/ - -Feedback is also welcomed via the joda-interest mailing list. - -The Joda team -http://www.joda.org/joda-time/ diff --git a/All/Genesis-NP/Genesis#270/pair.info b/All/Genesis-NP/Genesis#270/pair.info deleted file mode 100755 index c41e4d2..0000000 --- a/All/Genesis-NP/Genesis#270/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:270 -SATName:Genesis -modifiedFPath:src/main/java/org/joda/time/DateTimeUtils.java -comSha:bcb044669b4d1f8d334861ccbd169924d6ef3b54 -parentComSha:bcb044669b4d1f8d334861ccbd169924d6ef3b54^1 -githubUrl:https://github.com/JodaOrg/joda-time -repoName:JodaOrg#joda-time \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#273/comMsg.txt b/All/Genesis-NP/Genesis#273/comMsg.txt deleted file mode 100755 index dbc930f..0000000 --- a/All/Genesis-NP/Genesis#273/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -TIKA-1956 -- prevent NPE when trying to get embedded image offset in WordParser diff --git a/All/Genesis-NP/Genesis#273/diff.diff b/All/Genesis-NP/Genesis#273/diff.diff deleted file mode 100755 index 401250a..0000000 --- a/All/Genesis-NP/Genesis#273/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java b/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java -index 15984fe..4c950fa 100644 ---- a/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java -+++ b/tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java -@@ -18,0 +19,2 @@ package org.apache.tika.parser.microsoft; -+import static java.nio.charset.StandardCharsets.UTF_8; -+ -@@ -56,2 +57,0 @@ import org.xml.sax.helpers.AttributesImpl; --import static java.nio.charset.StandardCharsets.UTF_8; -- -@@ -311 +311,6 @@ public class WordExtractor extends AbstractPOIFSExtractor { -- String id = "_" + field.getMarkSeparatorCharacterRun(r).getPicOffset(); -+ String id = "_unknown_id"; -+ //this can return null (TIKA-1956) -+ CharacterRun mscr = field.getMarkSeparatorCharacterRun(r); -+ if (mscr != null) { -+ id = "_" + mscr.getPicOffset(); -+ } diff --git a/All/Genesis-NP/Genesis#273/new/WordExtractor.java b/All/Genesis-NP/Genesis#273/new/WordExtractor.java deleted file mode 100755 index 4c950fa..0000000 --- a/All/Genesis-NP/Genesis#273/new/WordExtractor.java +++ /dev/null @@ -1,716 +0,0 @@ -/* - * 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.tika.parser.microsoft; - -import static java.nio.charset.StandardCharsets.UTF_8; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFOldDocument; -import org.apache.poi.hwpf.OldWordFileFormatException; -import org.apache.poi.hwpf.extractor.Word6Extractor; -import org.apache.poi.hwpf.model.FieldsDocumentPart; -import org.apache.poi.hwpf.model.PicturesTable; -import org.apache.poi.hwpf.model.StyleDescription; -import org.apache.poi.hwpf.usermodel.CharacterRun; -import org.apache.poi.hwpf.usermodel.Field; -import org.apache.poi.hwpf.usermodel.HeaderStories; -import org.apache.poi.hwpf.usermodel.Paragraph; -import org.apache.poi.hwpf.usermodel.Picture; -import org.apache.poi.hwpf.usermodel.Range; -import org.apache.poi.hwpf.usermodel.Table; -import org.apache.poi.hwpf.usermodel.TableCell; -import org.apache.poi.hwpf.usermodel.TableRow; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.tika.exception.TikaException; -import org.apache.tika.io.TikaInputStream; -import org.apache.tika.parser.ParseContext; -import org.apache.tika.sax.XHTMLContentHandler; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.AttributesImpl; - -public class WordExtractor extends AbstractPOIFSExtractor { - - private static final char UNICODECHAR_NONBREAKING_HYPHEN = '\u2011'; - private static final char UNICODECHAR_ZERO_WIDTH_SPACE = '\u200b'; - // could be improved by using the real delimiter in xchFollow [MS-DOC], v20140721, 2.4.6.3, Part 3, Step 3 - private static final String LIST_DELIMITER = " "; - private static final Map fixedParagraphStyles = new HashMap(); - private static final TagAndStyle defaultParagraphStyle = new TagAndStyle("p", null); - - static { - fixedParagraphStyles.put("Default", defaultParagraphStyle); - fixedParagraphStyles.put("Normal", defaultParagraphStyle); - fixedParagraphStyles.put("heading", new TagAndStyle("h1", null)); - fixedParagraphStyles.put("Heading", new TagAndStyle("h1", null)); - fixedParagraphStyles.put("Title", new TagAndStyle("h1", "title")); - fixedParagraphStyles.put("Subtitle", new TagAndStyle("h2", "subtitle")); - fixedParagraphStyles.put("HTML Preformatted", new TagAndStyle("pre", null)); - } - - // True if we are currently in the named style tag: - private boolean curStrikeThrough; - private boolean curBold; - private boolean curItalic; - - public WordExtractor(ParseContext context) { - super(context); - } - - private static int countParagraphs(Range... ranges) { - int count = 0; - for (Range r : ranges) { - if (r != null) { - count += r.numParagraphs(); - } - } - return count; - } - - /** - * Given a style name, return what tag should be used, and - * what style should be applied to it. - */ - public static TagAndStyle buildParagraphTagAndStyle(String styleName, boolean isTable) { - TagAndStyle tagAndStyle = fixedParagraphStyles.get(styleName); - if (tagAndStyle != null) { - return tagAndStyle; - } - - if (styleName.equals("Table Contents") && isTable) { - return defaultParagraphStyle; - } - - String tag = "p"; - String styleClass = null; - - if (styleName.startsWith("heading") || styleName.startsWith("Heading")) { - // "Heading 3" or "Heading2" or "heading 4" - int num = 1; - try { - num = Integer.parseInt( - styleName.substring(styleName.length() - 1) - ); - } catch (NumberFormatException e) { - } - // Turn it into a H1 - H6 (H7+ isn't valid!) - tag = "h" + Math.min(num, 6); - } else { - styleClass = styleName.replace(' ', '_'); - styleClass = styleClass.substring(0, 1).toLowerCase(Locale.ROOT) + - styleClass.substring(1); - } - - return new TagAndStyle(tag, styleClass); - } - - protected void parse( - NPOIFSFileSystem filesystem, XHTMLContentHandler xhtml) - throws IOException, SAXException, TikaException { - parse(filesystem.getRoot(), xhtml); - } - - protected void parse( - DirectoryNode root, XHTMLContentHandler xhtml) - throws IOException, SAXException, TikaException { - HWPFDocument document; - try { - document = new HWPFDocument(root); - } catch (OldWordFileFormatException e) { - parseWord6(root, xhtml); - return; - } - org.apache.poi.hwpf.extractor.WordExtractor wordExtractor = - new org.apache.poi.hwpf.extractor.WordExtractor(document); - HeaderStories headerFooter = new HeaderStories(document); - - // Grab the list of pictures. As far as we can tell, - // the pictures should be in order, and may be directly - // placed or referenced from an anchor - PicturesTable pictureTable = document.getPicturesTable(); - PicturesSource pictures = new PicturesSource(document); - - // Do any headers, if present - Range[] headers = new Range[]{headerFooter.getFirstHeaderSubrange(), - headerFooter.getEvenHeaderSubrange(), headerFooter.getOddHeaderSubrange()}; - handleHeaderFooter(headers, "header", document, pictures, pictureTable, xhtml); - - // Do the main paragraph text - Range r = document.getRange(); - ListManager listManager = new ListManager(document); - for (int i = 0; i < r.numParagraphs(); i++) { - Paragraph p = r.getParagraph(i); - i += handleParagraph(p, 0, r, document, FieldsDocumentPart.MAIN, pictures, pictureTable, listManager, xhtml); - } - - // Do everything else - for (String paragraph : wordExtractor.getMainTextboxText()) { - xhtml.element("p", paragraph); - } - - for (String paragraph : wordExtractor.getFootnoteText()) { - xhtml.element("p", paragraph); - } - - for (String paragraph : wordExtractor.getCommentsText()) { - xhtml.element("p", paragraph); - } - - for (String paragraph : wordExtractor.getEndnoteText()) { - xhtml.element("p", paragraph); - } - - // Do any footers, if present - Range[] footers = new Range[]{headerFooter.getFirstFooterSubrange(), - headerFooter.getEvenFooterSubrange(), headerFooter.getOddFooterSubrange()}; - handleHeaderFooter(footers, "footer", document, pictures, pictureTable, xhtml); - - // Handle any pictures that we haven't output yet - for (Picture p = pictures.nextUnclaimed(); p != null; ) { - handlePictureCharacterRun( - null, p, pictures, xhtml - ); - p = pictures.nextUnclaimed(); - } - - // Handle any embeded office documents - try { - DirectoryEntry op = (DirectoryEntry) root.getEntry("ObjectPool"); - for (Entry entry : op) { - if (entry.getName().startsWith("_") - && entry instanceof DirectoryEntry) { - handleEmbeddedOfficeDoc((DirectoryEntry) entry, xhtml); - } - } - } catch (FileNotFoundException e) { - } - } - - private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, - PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) - throws SAXException, IOException, TikaException { - if (countParagraphs(ranges) > 0) { - xhtml.startElement("div", "class", type); - ListManager listManager = new ListManager(document); - for (Range r : ranges) { - if (r != null) { - for (int i = 0; i < r.numParagraphs(); i++) { - Paragraph p = r.getParagraph(i); - - i += handleParagraph(p, 0, r, document, - FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); - } - } - } - xhtml.endElement("div"); - } - } - - private int handleParagraph(Paragraph p, int parentTableLevel, Range r, HWPFDocument document, - FieldsDocumentPart docPart, PicturesSource pictures, PicturesTable pictureTable, ListManager listManager, - XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { - // Note - a poi bug means we can't currently properly recurse - // into nested tables, so currently we don't - if (p.isInTable() && p.getTableLevel() > parentTableLevel && parentTableLevel == 0) { - Table t = r.getTable(p); - xhtml.startElement("table"); - xhtml.startElement("tbody"); - for (int rn = 0; rn < t.numRows(); rn++) { - TableRow row = t.getRow(rn); - xhtml.startElement("tr"); - for (int cn = 0; cn < row.numCells(); cn++) { - TableCell cell = row.getCell(cn); - xhtml.startElement("td"); - - for (int pn = 0; pn < cell.numParagraphs(); pn++) { - Paragraph cellP = cell.getParagraph(pn); - handleParagraph(cellP, p.getTableLevel(), cell, document, docPart, pictures, pictureTable, listManager, xhtml); - } - xhtml.endElement("td"); - } - xhtml.endElement("tr"); - } - xhtml.endElement("tbody"); - xhtml.endElement("table"); - return (t.numParagraphs() - 1); - } - - String text = p.text(); - if (text.replaceAll("[\\r\\n\\s]+", "").isEmpty()) { - // Skip empty paragraphs - return 0; - } - - TagAndStyle tas; - String numbering = null; - - if (document.getStyleSheet().numStyles() > p.getStyleIndex()) { - StyleDescription style = - document.getStyleSheet().getStyleDescription(p.getStyleIndex()); - if (style != null && style.getName() != null && style.getName().length() > 0) { - if (p.isInList()) { - numbering = listManager.getFormattedNumber(p); - } - tas = buildParagraphTagAndStyle(style.getName(), (parentTableLevel > 0)); - } else { - tas = new TagAndStyle("p", null); - } - } else { - tas = new TagAndStyle("p", null); - } - - if (tas.getStyleClass() != null) { - xhtml.startElement(tas.getTag(), "class", tas.getStyleClass()); - } else { - xhtml.startElement(tas.getTag()); - } - - if (numbering != null) { - xhtml.characters(numbering); - } - - for (int j = 0; j < p.numCharacterRuns(); j++) { - CharacterRun cr = p.getCharacterRun(j); - - // FIELD_BEGIN_MARK: - if (cr.text().getBytes(UTF_8)[0] == 0x13) { - Field field = document.getFields().getFieldByStartOffset(docPart, cr.getStartOffset()); - // 58 is an embedded document - // 56 is a document link - if (field != null && (field.getType() == 58 || field.getType() == 56)) { - // Embedded Object: add a

so consumer can see where - // in the main text each embedded document - // occurred: - String id = "_unknown_id"; - //this can return null (TIKA-1956) - CharacterRun mscr = field.getMarkSeparatorCharacterRun(r); - if (mscr != null) { - id = "_" + mscr.getPicOffset(); - } - AttributesImpl attributes = new AttributesImpl(); - attributes.addAttribute("", "class", "class", "CDATA", "embedded"); - attributes.addAttribute("", "id", "id", "CDATA", id); - xhtml.startElement("div", attributes); - xhtml.endElement("div"); - } - } - - if (cr.text().equals("\u0013")) { - j += handleSpecialCharacterRuns(p, j, tas.isHeading(), pictures, xhtml); - } else if (cr.text().startsWith("\u0008")) { - // Floating Picture(s) - for (int pn = 0; pn < cr.text().length(); pn++) { - // Assume they're in the order from the unclaimed list... - Picture picture = pictures.nextUnclaimed(); - - // Output - handlePictureCharacterRun(cr, picture, pictures, xhtml); - } - } else if (pictureTable.hasPicture(cr)) { - // Inline Picture - Picture picture = pictures.getFor(cr); - handlePictureCharacterRun(cr, picture, pictures, xhtml); - } else { - handleCharacterRun(cr, tas.isHeading(), xhtml); - } - } - - // Close any still open style tags - if (curStrikeThrough) { - xhtml.endElement("s"); - curStrikeThrough = false; - } - if (curItalic) { - xhtml.endElement("i"); - curItalic = false; - } - if (curBold) { - xhtml.endElement("b"); - curBold = false; - } - - xhtml.endElement(tas.getTag()); - - return 0; - } - - private void handleCharacterRun(CharacterRun cr, boolean skipStyling, XHTMLContentHandler xhtml) - throws SAXException { - // Skip trailing newlines - if (!isRendered(cr) || cr.text().equals("\r")) - return; - - if (!skipStyling) { - if (cr.isBold() != curBold) { - // Enforce nesting -- must close s and i tags - if (curStrikeThrough) { - xhtml.endElement("s"); - curStrikeThrough = false; - } - if (curItalic) { - xhtml.endElement("i"); - curItalic = false; - } - if (cr.isBold()) { - xhtml.startElement("b"); - } else { - xhtml.endElement("b"); - } - curBold = cr.isBold(); - } - - if (cr.isItalic() != curItalic) { - // Enforce nesting -- must close s tag - if (curStrikeThrough) { - xhtml.endElement("s"); - curStrikeThrough = false; - } - if (cr.isItalic()) { - xhtml.startElement("i"); - } else { - xhtml.endElement("i"); - } - curItalic = cr.isItalic(); - } - - if (cr.isStrikeThrough() != curStrikeThrough) { - if (cr.isStrikeThrough()) { - xhtml.startElement("s"); - } else { - xhtml.endElement("s"); - } - curStrikeThrough = cr.isStrikeThrough(); - } - } - - // Clean up the text - String text = cr.text(); - text = text.replace('\r', '\n'); - if (text.endsWith("\u0007")) { - // Strip the table cell end marker - text = text.substring(0, text.length() - 1); - } - - // Copied from POI's org/apache/poi/hwpf/converter/AbstractWordConverter.processCharacters: - - // Non-breaking hyphens are returned as char 30 - text = text.replace((char) 30, UNICODECHAR_NONBREAKING_HYPHEN); - - // Non-required hyphens to zero-width space - text = text.replace((char) 31, UNICODECHAR_ZERO_WIDTH_SPACE); - - // Control characters as line break - text = text.replaceAll("[\u0000-\u001f]", "\n"); - xhtml.characters(text); - } - - /** - * Can be \13..text..\15 or \13..control..\14..text..\15 . - * Nesting is allowed - */ - private int handleSpecialCharacterRuns(Paragraph p, int index, boolean skipStyling, - PicturesSource pictures, XHTMLContentHandler xhtml) throws SAXException, TikaException, IOException { - List controls = new ArrayList(); - List texts = new ArrayList(); - boolean has14 = false; - - // Split it into before and after the 14 - int i; - for (i = index + 1; i < p.numCharacterRuns(); i++) { - CharacterRun cr = p.getCharacterRun(i); - if (cr.text().equals("\u0013")) { - // Nested, oh joy... - int increment = handleSpecialCharacterRuns(p, i + 1, skipStyling, pictures, xhtml); - i += increment; - } else if (cr.text().equals("\u0014")) { - has14 = true; - } else if (cr.text().equals("\u0015")) { - if (!has14) { - texts = controls; - controls = new ArrayList(); - } - break; - } else { - if (has14) { - texts.add(cr); - } else { - controls.add(cr); - } - } - } - - // Do we need to do something special with this? - if (controls.size() > 0) { - String text = controls.get(0).text(); - for (int j = 1; j < controls.size(); j++) { - text += controls.get(j).text(); - } - - if ((text.startsWith("HYPERLINK") || text.startsWith(" HYPERLINK")) - && text.indexOf('"') > -1) { - int start = text.indexOf('"') + 1; - int end = findHyperlinkEnd(text, start); - String url = ""; - if (start >= 0 && start < end && end <= text.length()) { - url = text.substring(start, end); - } - - xhtml.startElement("a", "href", url); - for (CharacterRun cr : texts) { - handleCharacterRun(cr, skipStyling, xhtml); - } - xhtml.endElement("a"); - } else { - // Just output the text ones - for (CharacterRun cr : texts) { - if (pictures.hasPicture(cr)) { - Picture picture = pictures.getFor(cr); - handlePictureCharacterRun(cr, picture, pictures, xhtml); - } else { - handleCharacterRun(cr, skipStyling, xhtml); - } - } - } - } else { - // We only had text - // Output as-is - for (CharacterRun cr : texts) { - handleCharacterRun(cr, skipStyling, xhtml); - } - } - - // Tell them how many to skip over - return i - index; - } - - //temporary work around for TIKA-1512 - private int findHyperlinkEnd(String text, int start) { - int end = text.lastIndexOf('"'); - if (end > start) { - return end; - } - end = text.lastIndexOf('\u201D');//smart right double quote - if (end > start) { - return end; - } - end = text.lastIndexOf('\r'); - if (end > start) { - return end; - } - //if nothing so far, take the full length of the string - //If the full string is > 256 characters, it appears - //that the url is truncated in the .doc file. This - //will return the value as it is in the file, which - //may be incorrect; but it is the same behavior as opening - //the link in MSWord. - //This code does not currently check that length is actually >= 256. - //we might want to add that? - return text.length(); - } - - private void handlePictureCharacterRun(CharacterRun cr, Picture picture, PicturesSource pictures, XHTMLContentHandler xhtml) - throws SAXException, IOException, TikaException { - if (!isRendered(cr) || picture == null) { - // Oh dear, we've run out... - // Probably caused by multiple \u0008 images referencing - // the same real image - return; - } - - // Which one is it? - String extension = picture.suggestFileExtension(); - int pictureNumber = pictures.pictureNumber(picture); - - // Make up a name for the picture - // There isn't one in the file, but we need to be able to reference - // the picture from the img tag and the embedded resource - String filename = "image" + pictureNumber + (extension.length() > 0 ? "." + extension : ""); - - // Grab the mime type for the picture - String mimeType = picture.getMimeType(); - - // Output the img tag - AttributesImpl attr = new AttributesImpl(); - attr.addAttribute("", "src", "src", "CDATA", "embedded:" + filename); - attr.addAttribute("", "alt", "alt", "CDATA", filename); - xhtml.startElement("img", attr); - xhtml.endElement("img"); - - // Have we already output this one? - // (Only expose each individual image once) - if (!pictures.hasOutput(picture)) { - TikaInputStream stream = TikaInputStream.get(picture.getContent()); - handleEmbeddedResource(stream, filename, null, mimeType, xhtml, false); - pictures.recordOutput(picture); - } - } - - /** - * Outputs a section of text if the given text is non-empty. - * - * @param xhtml XHTML content handler - * @param section the class of the <div/> section emitted - * @param text text to be emitted, if any - * @throws SAXException if an error occurs - */ - private void addTextIfAny( - XHTMLContentHandler xhtml, String section, String text) - throws SAXException { - if (text != null && text.length() > 0) { - xhtml.startElement("div", "class", section); - xhtml.element("p", text); - xhtml.endElement("div"); - } - } - - protected void parseWord6( - NPOIFSFileSystem filesystem, XHTMLContentHandler xhtml) - throws IOException, SAXException, TikaException { - parseWord6(filesystem.getRoot(), xhtml); - } - - protected void parseWord6( - DirectoryNode root, XHTMLContentHandler xhtml) - throws IOException, SAXException, TikaException { - HWPFOldDocument doc = new HWPFOldDocument(root); - Word6Extractor extractor = new Word6Extractor(doc); - - for (String p : extractor.getParagraphText()) { - xhtml.element("p", p); - } - } - - /** - * Determines if character run should be included in the extraction. - * - * @param cr character run. - * @return true if character run should be included in extraction. - */ - private boolean isRendered(final CharacterRun cr) { - return cr == null || !cr.isMarkedDeleted(); - } - - public static class TagAndStyle { - private String tag; - private String styleClass; - - public TagAndStyle(String tag, String styleClass) { - this.tag = tag; - this.styleClass = styleClass; - } - - public String getTag() { - return tag; - } - - public String getStyleClass() { - return styleClass; - } - - public boolean isHeading() { - return tag.length() == 2 && tag.startsWith("h"); - } - } - - /** - * Provides access to the pictures both by offset, iteration - * over the un-claimed, and peeking forward - */ - private static class PicturesSource { - private PicturesTable picturesTable; - private Set output = new HashSet(); - private Map lookup; - private List nonU1based; - private List all; - private int pn = 0; - - private PicturesSource(HWPFDocument doc) { - picturesTable = doc.getPicturesTable(); - all = picturesTable.getAllPictures(); - - // Build the Offset-Picture lookup map - lookup = new HashMap(); - for (Picture p : all) { - lookup.put(p.getStartOffset(), p); - } - - // Work out which Pictures aren't referenced by - // a \u0001 in the main text - // These are \u0008 escher floating ones, ones - // found outside the normal text, and who - // knows what else... - nonU1based = new ArrayList(); - nonU1based.addAll(all); - Range r = doc.getRange(); - for (int i = 0; i < r.numCharacterRuns(); i++) { - CharacterRun cr = r.getCharacterRun(i); - if (picturesTable.hasPicture(cr)) { - Picture p = getFor(cr); - int at = nonU1based.indexOf(p); - nonU1based.set(at, null); - } - } - } - - private boolean hasPicture(CharacterRun cr) { - return picturesTable.hasPicture(cr); - } - - private void recordOutput(Picture picture) { - output.add(picture); - } - - private boolean hasOutput(Picture picture) { - return output.contains(picture); - } - - private int pictureNumber(Picture picture) { - return all.indexOf(picture) + 1; - } - - private Picture getFor(CharacterRun cr) { - return lookup.get(cr.getPicOffset()); - } - - /** - * Return the next unclaimed one, used towards - * the end - */ - private Picture nextUnclaimed() { - Picture p = null; - while (pn < nonU1based.size()) { - p = nonU1based.get(pn); - pn++; - if (p != null) return p; - } - return null; - } - } -} diff --git a/All/Genesis-NP/Genesis#273/old/WordExtractor.java b/All/Genesis-NP/Genesis#273/old/WordExtractor.java deleted file mode 100755 index 15984fe..0000000 --- a/All/Genesis-NP/Genesis#273/old/WordExtractor.java +++ /dev/null @@ -1,711 +0,0 @@ -/* - * 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.tika.parser.microsoft; - -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - -import org.apache.poi.hwpf.HWPFDocument; -import org.apache.poi.hwpf.HWPFOldDocument; -import org.apache.poi.hwpf.OldWordFileFormatException; -import org.apache.poi.hwpf.extractor.Word6Extractor; -import org.apache.poi.hwpf.model.FieldsDocumentPart; -import org.apache.poi.hwpf.model.PicturesTable; -import org.apache.poi.hwpf.model.StyleDescription; -import org.apache.poi.hwpf.usermodel.CharacterRun; -import org.apache.poi.hwpf.usermodel.Field; -import org.apache.poi.hwpf.usermodel.HeaderStories; -import org.apache.poi.hwpf.usermodel.Paragraph; -import org.apache.poi.hwpf.usermodel.Picture; -import org.apache.poi.hwpf.usermodel.Range; -import org.apache.poi.hwpf.usermodel.Table; -import org.apache.poi.hwpf.usermodel.TableCell; -import org.apache.poi.hwpf.usermodel.TableRow; -import org.apache.poi.poifs.filesystem.DirectoryEntry; -import org.apache.poi.poifs.filesystem.DirectoryNode; -import org.apache.poi.poifs.filesystem.Entry; -import org.apache.poi.poifs.filesystem.NPOIFSFileSystem; -import org.apache.tika.exception.TikaException; -import org.apache.tika.io.TikaInputStream; -import org.apache.tika.parser.ParseContext; -import org.apache.tika.sax.XHTMLContentHandler; -import org.xml.sax.SAXException; -import org.xml.sax.helpers.AttributesImpl; - -import static java.nio.charset.StandardCharsets.UTF_8; - -public class WordExtractor extends AbstractPOIFSExtractor { - - private static final char UNICODECHAR_NONBREAKING_HYPHEN = '\u2011'; - private static final char UNICODECHAR_ZERO_WIDTH_SPACE = '\u200b'; - // could be improved by using the real delimiter in xchFollow [MS-DOC], v20140721, 2.4.6.3, Part 3, Step 3 - private static final String LIST_DELIMITER = " "; - private static final Map fixedParagraphStyles = new HashMap(); - private static final TagAndStyle defaultParagraphStyle = new TagAndStyle("p", null); - - static { - fixedParagraphStyles.put("Default", defaultParagraphStyle); - fixedParagraphStyles.put("Normal", defaultParagraphStyle); - fixedParagraphStyles.put("heading", new TagAndStyle("h1", null)); - fixedParagraphStyles.put("Heading", new TagAndStyle("h1", null)); - fixedParagraphStyles.put("Title", new TagAndStyle("h1", "title")); - fixedParagraphStyles.put("Subtitle", new TagAndStyle("h2", "subtitle")); - fixedParagraphStyles.put("HTML Preformatted", new TagAndStyle("pre", null)); - } - - // True if we are currently in the named style tag: - private boolean curStrikeThrough; - private boolean curBold; - private boolean curItalic; - - public WordExtractor(ParseContext context) { - super(context); - } - - private static int countParagraphs(Range... ranges) { - int count = 0; - for (Range r : ranges) { - if (r != null) { - count += r.numParagraphs(); - } - } - return count; - } - - /** - * Given a style name, return what tag should be used, and - * what style should be applied to it. - */ - public static TagAndStyle buildParagraphTagAndStyle(String styleName, boolean isTable) { - TagAndStyle tagAndStyle = fixedParagraphStyles.get(styleName); - if (tagAndStyle != null) { - return tagAndStyle; - } - - if (styleName.equals("Table Contents") && isTable) { - return defaultParagraphStyle; - } - - String tag = "p"; - String styleClass = null; - - if (styleName.startsWith("heading") || styleName.startsWith("Heading")) { - // "Heading 3" or "Heading2" or "heading 4" - int num = 1; - try { - num = Integer.parseInt( - styleName.substring(styleName.length() - 1) - ); - } catch (NumberFormatException e) { - } - // Turn it into a H1 - H6 (H7+ isn't valid!) - tag = "h" + Math.min(num, 6); - } else { - styleClass = styleName.replace(' ', '_'); - styleClass = styleClass.substring(0, 1).toLowerCase(Locale.ROOT) + - styleClass.substring(1); - } - - return new TagAndStyle(tag, styleClass); - } - - protected void parse( - NPOIFSFileSystem filesystem, XHTMLContentHandler xhtml) - throws IOException, SAXException, TikaException { - parse(filesystem.getRoot(), xhtml); - } - - protected void parse( - DirectoryNode root, XHTMLContentHandler xhtml) - throws IOException, SAXException, TikaException { - HWPFDocument document; - try { - document = new HWPFDocument(root); - } catch (OldWordFileFormatException e) { - parseWord6(root, xhtml); - return; - } - org.apache.poi.hwpf.extractor.WordExtractor wordExtractor = - new org.apache.poi.hwpf.extractor.WordExtractor(document); - HeaderStories headerFooter = new HeaderStories(document); - - // Grab the list of pictures. As far as we can tell, - // the pictures should be in order, and may be directly - // placed or referenced from an anchor - PicturesTable pictureTable = document.getPicturesTable(); - PicturesSource pictures = new PicturesSource(document); - - // Do any headers, if present - Range[] headers = new Range[]{headerFooter.getFirstHeaderSubrange(), - headerFooter.getEvenHeaderSubrange(), headerFooter.getOddHeaderSubrange()}; - handleHeaderFooter(headers, "header", document, pictures, pictureTable, xhtml); - - // Do the main paragraph text - Range r = document.getRange(); - ListManager listManager = new ListManager(document); - for (int i = 0; i < r.numParagraphs(); i++) { - Paragraph p = r.getParagraph(i); - i += handleParagraph(p, 0, r, document, FieldsDocumentPart.MAIN, pictures, pictureTable, listManager, xhtml); - } - - // Do everything else - for (String paragraph : wordExtractor.getMainTextboxText()) { - xhtml.element("p", paragraph); - } - - for (String paragraph : wordExtractor.getFootnoteText()) { - xhtml.element("p", paragraph); - } - - for (String paragraph : wordExtractor.getCommentsText()) { - xhtml.element("p", paragraph); - } - - for (String paragraph : wordExtractor.getEndnoteText()) { - xhtml.element("p", paragraph); - } - - // Do any footers, if present - Range[] footers = new Range[]{headerFooter.getFirstFooterSubrange(), - headerFooter.getEvenFooterSubrange(), headerFooter.getOddFooterSubrange()}; - handleHeaderFooter(footers, "footer", document, pictures, pictureTable, xhtml); - - // Handle any pictures that we haven't output yet - for (Picture p = pictures.nextUnclaimed(); p != null; ) { - handlePictureCharacterRun( - null, p, pictures, xhtml - ); - p = pictures.nextUnclaimed(); - } - - // Handle any embeded office documents - try { - DirectoryEntry op = (DirectoryEntry) root.getEntry("ObjectPool"); - for (Entry entry : op) { - if (entry.getName().startsWith("_") - && entry instanceof DirectoryEntry) { - handleEmbeddedOfficeDoc((DirectoryEntry) entry, xhtml); - } - } - } catch (FileNotFoundException e) { - } - } - - private void handleHeaderFooter(Range[] ranges, String type, HWPFDocument document, - PicturesSource pictures, PicturesTable pictureTable, XHTMLContentHandler xhtml) - throws SAXException, IOException, TikaException { - if (countParagraphs(ranges) > 0) { - xhtml.startElement("div", "class", type); - ListManager listManager = new ListManager(document); - for (Range r : ranges) { - if (r != null) { - for (int i = 0; i < r.numParagraphs(); i++) { - Paragraph p = r.getParagraph(i); - - i += handleParagraph(p, 0, r, document, - FieldsDocumentPart.HEADER, pictures, pictureTable, listManager, xhtml); - } - } - } - xhtml.endElement("div"); - } - } - - private int handleParagraph(Paragraph p, int parentTableLevel, Range r, HWPFDocument document, - FieldsDocumentPart docPart, PicturesSource pictures, PicturesTable pictureTable, ListManager listManager, - XHTMLContentHandler xhtml) throws SAXException, IOException, TikaException { - // Note - a poi bug means we can't currently properly recurse - // into nested tables, so currently we don't - if (p.isInTable() && p.getTableLevel() > parentTableLevel && parentTableLevel == 0) { - Table t = r.getTable(p); - xhtml.startElement("table"); - xhtml.startElement("tbody"); - for (int rn = 0; rn < t.numRows(); rn++) { - TableRow row = t.getRow(rn); - xhtml.startElement("tr"); - for (int cn = 0; cn < row.numCells(); cn++) { - TableCell cell = row.getCell(cn); - xhtml.startElement("td"); - - for (int pn = 0; pn < cell.numParagraphs(); pn++) { - Paragraph cellP = cell.getParagraph(pn); - handleParagraph(cellP, p.getTableLevel(), cell, document, docPart, pictures, pictureTable, listManager, xhtml); - } - xhtml.endElement("td"); - } - xhtml.endElement("tr"); - } - xhtml.endElement("tbody"); - xhtml.endElement("table"); - return (t.numParagraphs() - 1); - } - - String text = p.text(); - if (text.replaceAll("[\\r\\n\\s]+", "").isEmpty()) { - // Skip empty paragraphs - return 0; - } - - TagAndStyle tas; - String numbering = null; - - if (document.getStyleSheet().numStyles() > p.getStyleIndex()) { - StyleDescription style = - document.getStyleSheet().getStyleDescription(p.getStyleIndex()); - if (style != null && style.getName() != null && style.getName().length() > 0) { - if (p.isInList()) { - numbering = listManager.getFormattedNumber(p); - } - tas = buildParagraphTagAndStyle(style.getName(), (parentTableLevel > 0)); - } else { - tas = new TagAndStyle("p", null); - } - } else { - tas = new TagAndStyle("p", null); - } - - if (tas.getStyleClass() != null) { - xhtml.startElement(tas.getTag(), "class", tas.getStyleClass()); - } else { - xhtml.startElement(tas.getTag()); - } - - if (numbering != null) { - xhtml.characters(numbering); - } - - for (int j = 0; j < p.numCharacterRuns(); j++) { - CharacterRun cr = p.getCharacterRun(j); - - // FIELD_BEGIN_MARK: - if (cr.text().getBytes(UTF_8)[0] == 0x13) { - Field field = document.getFields().getFieldByStartOffset(docPart, cr.getStartOffset()); - // 58 is an embedded document - // 56 is a document link - if (field != null && (field.getType() == 58 || field.getType() == 56)) { - // Embedded Object: add a
so consumer can see where - // in the main text each embedded document - // occurred: - String id = "_" + field.getMarkSeparatorCharacterRun(r).getPicOffset(); - AttributesImpl attributes = new AttributesImpl(); - attributes.addAttribute("", "class", "class", "CDATA", "embedded"); - attributes.addAttribute("", "id", "id", "CDATA", id); - xhtml.startElement("div", attributes); - xhtml.endElement("div"); - } - } - - if (cr.text().equals("\u0013")) { - j += handleSpecialCharacterRuns(p, j, tas.isHeading(), pictures, xhtml); - } else if (cr.text().startsWith("\u0008")) { - // Floating Picture(s) - for (int pn = 0; pn < cr.text().length(); pn++) { - // Assume they're in the order from the unclaimed list... - Picture picture = pictures.nextUnclaimed(); - - // Output - handlePictureCharacterRun(cr, picture, pictures, xhtml); - } - } else if (pictureTable.hasPicture(cr)) { - // Inline Picture - Picture picture = pictures.getFor(cr); - handlePictureCharacterRun(cr, picture, pictures, xhtml); - } else { - handleCharacterRun(cr, tas.isHeading(), xhtml); - } - } - - // Close any still open style tags - if (curStrikeThrough) { - xhtml.endElement("s"); - curStrikeThrough = false; - } - if (curItalic) { - xhtml.endElement("i"); - curItalic = false; - } - if (curBold) { - xhtml.endElement("b"); - curBold = false; - } - - xhtml.endElement(tas.getTag()); - - return 0; - } - - private void handleCharacterRun(CharacterRun cr, boolean skipStyling, XHTMLContentHandler xhtml) - throws SAXException { - // Skip trailing newlines - if (!isRendered(cr) || cr.text().equals("\r")) - return; - - if (!skipStyling) { - if (cr.isBold() != curBold) { - // Enforce nesting -- must close s and i tags - if (curStrikeThrough) { - xhtml.endElement("s"); - curStrikeThrough = false; - } - if (curItalic) { - xhtml.endElement("i"); - curItalic = false; - } - if (cr.isBold()) { - xhtml.startElement("b"); - } else { - xhtml.endElement("b"); - } - curBold = cr.isBold(); - } - - if (cr.isItalic() != curItalic) { - // Enforce nesting -- must close s tag - if (curStrikeThrough) { - xhtml.endElement("s"); - curStrikeThrough = false; - } - if (cr.isItalic()) { - xhtml.startElement("i"); - } else { - xhtml.endElement("i"); - } - curItalic = cr.isItalic(); - } - - if (cr.isStrikeThrough() != curStrikeThrough) { - if (cr.isStrikeThrough()) { - xhtml.startElement("s"); - } else { - xhtml.endElement("s"); - } - curStrikeThrough = cr.isStrikeThrough(); - } - } - - // Clean up the text - String text = cr.text(); - text = text.replace('\r', '\n'); - if (text.endsWith("\u0007")) { - // Strip the table cell end marker - text = text.substring(0, text.length() - 1); - } - - // Copied from POI's org/apache/poi/hwpf/converter/AbstractWordConverter.processCharacters: - - // Non-breaking hyphens are returned as char 30 - text = text.replace((char) 30, UNICODECHAR_NONBREAKING_HYPHEN); - - // Non-required hyphens to zero-width space - text = text.replace((char) 31, UNICODECHAR_ZERO_WIDTH_SPACE); - - // Control characters as line break - text = text.replaceAll("[\u0000-\u001f]", "\n"); - xhtml.characters(text); - } - - /** - * Can be \13..text..\15 or \13..control..\14..text..\15 . - * Nesting is allowed - */ - private int handleSpecialCharacterRuns(Paragraph p, int index, boolean skipStyling, - PicturesSource pictures, XHTMLContentHandler xhtml) throws SAXException, TikaException, IOException { - List controls = new ArrayList(); - List texts = new ArrayList(); - boolean has14 = false; - - // Split it into before and after the 14 - int i; - for (i = index + 1; i < p.numCharacterRuns(); i++) { - CharacterRun cr = p.getCharacterRun(i); - if (cr.text().equals("\u0013")) { - // Nested, oh joy... - int increment = handleSpecialCharacterRuns(p, i + 1, skipStyling, pictures, xhtml); - i += increment; - } else if (cr.text().equals("\u0014")) { - has14 = true; - } else if (cr.text().equals("\u0015")) { - if (!has14) { - texts = controls; - controls = new ArrayList(); - } - break; - } else { - if (has14) { - texts.add(cr); - } else { - controls.add(cr); - } - } - } - - // Do we need to do something special with this? - if (controls.size() > 0) { - String text = controls.get(0).text(); - for (int j = 1; j < controls.size(); j++) { - text += controls.get(j).text(); - } - - if ((text.startsWith("HYPERLINK") || text.startsWith(" HYPERLINK")) - && text.indexOf('"') > -1) { - int start = text.indexOf('"') + 1; - int end = findHyperlinkEnd(text, start); - String url = ""; - if (start >= 0 && start < end && end <= text.length()) { - url = text.substring(start, end); - } - - xhtml.startElement("a", "href", url); - for (CharacterRun cr : texts) { - handleCharacterRun(cr, skipStyling, xhtml); - } - xhtml.endElement("a"); - } else { - // Just output the text ones - for (CharacterRun cr : texts) { - if (pictures.hasPicture(cr)) { - Picture picture = pictures.getFor(cr); - handlePictureCharacterRun(cr, picture, pictures, xhtml); - } else { - handleCharacterRun(cr, skipStyling, xhtml); - } - } - } - } else { - // We only had text - // Output as-is - for (CharacterRun cr : texts) { - handleCharacterRun(cr, skipStyling, xhtml); - } - } - - // Tell them how many to skip over - return i - index; - } - - //temporary work around for TIKA-1512 - private int findHyperlinkEnd(String text, int start) { - int end = text.lastIndexOf('"'); - if (end > start) { - return end; - } - end = text.lastIndexOf('\u201D');//smart right double quote - if (end > start) { - return end; - } - end = text.lastIndexOf('\r'); - if (end > start) { - return end; - } - //if nothing so far, take the full length of the string - //If the full string is > 256 characters, it appears - //that the url is truncated in the .doc file. This - //will return the value as it is in the file, which - //may be incorrect; but it is the same behavior as opening - //the link in MSWord. - //This code does not currently check that length is actually >= 256. - //we might want to add that? - return text.length(); - } - - private void handlePictureCharacterRun(CharacterRun cr, Picture picture, PicturesSource pictures, XHTMLContentHandler xhtml) - throws SAXException, IOException, TikaException { - if (!isRendered(cr) || picture == null) { - // Oh dear, we've run out... - // Probably caused by multiple \u0008 images referencing - // the same real image - return; - } - - // Which one is it? - String extension = picture.suggestFileExtension(); - int pictureNumber = pictures.pictureNumber(picture); - - // Make up a name for the picture - // There isn't one in the file, but we need to be able to reference - // the picture from the img tag and the embedded resource - String filename = "image" + pictureNumber + (extension.length() > 0 ? "." + extension : ""); - - // Grab the mime type for the picture - String mimeType = picture.getMimeType(); - - // Output the img tag - AttributesImpl attr = new AttributesImpl(); - attr.addAttribute("", "src", "src", "CDATA", "embedded:" + filename); - attr.addAttribute("", "alt", "alt", "CDATA", filename); - xhtml.startElement("img", attr); - xhtml.endElement("img"); - - // Have we already output this one? - // (Only expose each individual image once) - if (!pictures.hasOutput(picture)) { - TikaInputStream stream = TikaInputStream.get(picture.getContent()); - handleEmbeddedResource(stream, filename, null, mimeType, xhtml, false); - pictures.recordOutput(picture); - } - } - - /** - * Outputs a section of text if the given text is non-empty. - * - * @param xhtml XHTML content handler - * @param section the class of the <div/> section emitted - * @param text text to be emitted, if any - * @throws SAXException if an error occurs - */ - private void addTextIfAny( - XHTMLContentHandler xhtml, String section, String text) - throws SAXException { - if (text != null && text.length() > 0) { - xhtml.startElement("div", "class", section); - xhtml.element("p", text); - xhtml.endElement("div"); - } - } - - protected void parseWord6( - NPOIFSFileSystem filesystem, XHTMLContentHandler xhtml) - throws IOException, SAXException, TikaException { - parseWord6(filesystem.getRoot(), xhtml); - } - - protected void parseWord6( - DirectoryNode root, XHTMLContentHandler xhtml) - throws IOException, SAXException, TikaException { - HWPFOldDocument doc = new HWPFOldDocument(root); - Word6Extractor extractor = new Word6Extractor(doc); - - for (String p : extractor.getParagraphText()) { - xhtml.element("p", p); - } - } - - /** - * Determines if character run should be included in the extraction. - * - * @param cr character run. - * @return true if character run should be included in extraction. - */ - private boolean isRendered(final CharacterRun cr) { - return cr == null || !cr.isMarkedDeleted(); - } - - public static class TagAndStyle { - private String tag; - private String styleClass; - - public TagAndStyle(String tag, String styleClass) { - this.tag = tag; - this.styleClass = styleClass; - } - - public String getTag() { - return tag; - } - - public String getStyleClass() { - return styleClass; - } - - public boolean isHeading() { - return tag.length() == 2 && tag.startsWith("h"); - } - } - - /** - * Provides access to the pictures both by offset, iteration - * over the un-claimed, and peeking forward - */ - private static class PicturesSource { - private PicturesTable picturesTable; - private Set output = new HashSet(); - private Map lookup; - private List nonU1based; - private List all; - private int pn = 0; - - private PicturesSource(HWPFDocument doc) { - picturesTable = doc.getPicturesTable(); - all = picturesTable.getAllPictures(); - - // Build the Offset-Picture lookup map - lookup = new HashMap(); - for (Picture p : all) { - lookup.put(p.getStartOffset(), p); - } - - // Work out which Pictures aren't referenced by - // a \u0001 in the main text - // These are \u0008 escher floating ones, ones - // found outside the normal text, and who - // knows what else... - nonU1based = new ArrayList(); - nonU1based.addAll(all); - Range r = doc.getRange(); - for (int i = 0; i < r.numCharacterRuns(); i++) { - CharacterRun cr = r.getCharacterRun(i); - if (picturesTable.hasPicture(cr)) { - Picture p = getFor(cr); - int at = nonU1based.indexOf(p); - nonU1based.set(at, null); - } - } - } - - private boolean hasPicture(CharacterRun cr) { - return picturesTable.hasPicture(cr); - } - - private void recordOutput(Picture picture) { - output.add(picture); - } - - private boolean hasOutput(Picture picture) { - return output.contains(picture); - } - - private int pictureNumber(Picture picture) { - return all.indexOf(picture) + 1; - } - - private Picture getFor(CharacterRun cr) { - return lookup.get(cr.getPicOffset()); - } - - /** - * Return the next unclaimed one, used towards - * the end - */ - private Picture nextUnclaimed() { - Picture p = null; - while (pn < nonU1based.size()) { - p = nonU1based.get(pn); - pn++; - if (p != null) return p; - } - return null; - } - } -} diff --git a/All/Genesis-NP/Genesis#273/pair.info b/All/Genesis-NP/Genesis#273/pair.info deleted file mode 100755 index b9b0174..0000000 --- a/All/Genesis-NP/Genesis#273/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:273 -SATName:Genesis -modifiedFPath:tika-parsers/src/main/java/org/apache/tika/parser/microsoft/WordExtractor.java -comSha:dab10395ab59a36be52529d3afa7ed370ce60eef -parentComSha:dab10395ab59a36be52529d3afa7ed370ce60eef^1 -githubUrl:https://github.com/apache/tika -repoName:apache#tika \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#276/comMsg.txt b/All/Genesis-NP/Genesis#276/comMsg.txt deleted file mode 100755 index 2e6b056..0000000 --- a/All/Genesis-NP/Genesis#276/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix NPE in Standard Changelog History Service in certain cases diff --git a/All/Genesis-NP/Genesis#276/diff.diff b/All/Genesis-NP/Genesis#276/diff.diff deleted file mode 100755 index 9901350..0000000 --- a/All/Genesis-NP/Genesis#276/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/liquibase-core/src/main/java/liquibase/changelog/StandardChangeLogHistoryService.java b/liquibase-core/src/main/java/liquibase/changelog/StandardChangeLogHistoryService.java -index 1cd27b4..3442b1a 100644 ---- a/liquibase-core/src/main/java/liquibase/changelog/StandardChangeLogHistoryService.java -+++ b/liquibase-core/src/main/java/liquibase/changelog/StandardChangeLogHistoryService.java -@@ -108 +108,3 @@ public class StandardChangeLogHistoryService extends AbstractChangeLogHistorySer -- Integer columnSize = changeLogTable.getColumn("LIQUIBASE").getType().getColumnSize(); -+ Column liquibaseColumn = changeLogTable.getColumn("LIQUIBASE"); -+ if (liquibaseColumn != null) { -+ Integer columnSize = liquibaseColumn.getType().getColumnSize(); -@@ -110,0 +113 @@ public class StandardChangeLogHistoryService extends AbstractChangeLogHistorySer -+ } -@@ -114 +117,3 @@ public class StandardChangeLogHistoryService extends AbstractChangeLogHistorySer -- Integer columnSize = changeLogTable.getColumn("MD5SUM").getType().getColumnSize(); -+ Column md5SumColumn = changeLogTable.getColumn("MD5SUM"); -+ if (md5SumColumn != null) { -+ Integer columnSize = md5SumColumn.getType().getColumnSize(); -@@ -116,0 +122 @@ public class StandardChangeLogHistoryService extends AbstractChangeLogHistorySer -+ } diff --git a/All/Genesis-NP/Genesis#276/new/StandardChangeLogHistoryService.java b/All/Genesis-NP/Genesis#276/new/StandardChangeLogHistoryService.java deleted file mode 100755 index 3442b1a..0000000 --- a/All/Genesis-NP/Genesis#276/new/StandardChangeLogHistoryService.java +++ /dev/null @@ -1,406 +0,0 @@ -package liquibase.changelog; - -import liquibase.ContextExpression; -import liquibase.Contexts; -import liquibase.LabelExpression; -import liquibase.Labels; -import liquibase.change.CheckSum; -import liquibase.change.ColumnConfig; -import liquibase.database.Database; -import liquibase.database.core.DB2Database; -import liquibase.database.core.SQLiteDatabase; -import liquibase.exception.DatabaseException; -import liquibase.exception.DatabaseHistoryException; -import liquibase.exception.LiquibaseException; -import liquibase.exception.UnexpectedLiquibaseException; -import liquibase.executor.Executor; -import liquibase.executor.ExecutorService; -import liquibase.logging.LogFactory; -import liquibase.snapshot.InvalidExampleException; -import liquibase.snapshot.SnapshotControl; -import liquibase.snapshot.SnapshotGeneratorFactory; -import liquibase.sqlgenerator.SqlGeneratorFactory; -import liquibase.statement.SqlStatement; -import liquibase.statement.core.*; -import liquibase.structure.core.Column; -import liquibase.structure.core.Table; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; - -public class StandardChangeLogHistoryService extends AbstractChangeLogHistoryService { - - private List ranChangeSetList; - private boolean serviceInitialized = false; - private Boolean hasDatabaseChangeLogTable = null; - private Integer lastChangeSetSequenceValue; - - @Override - public int getPriority() { - return PRIORITY_DEFAULT; - } - - @Override - public boolean supports(Database database) { - return true; - } - - public String getDatabaseChangeLogTableName() { - return getDatabase().getDatabaseChangeLogTableName(); - } - - public String getLiquibaseSchemaName() { - return getDatabase().getLiquibaseSchemaName(); - } - - public String getLiquibaseCatalogName() { - return getDatabase().getLiquibaseCatalogName(); - } - - public boolean canCreateChangeLogTable() throws DatabaseException { - return true; - } - - public void reset() { - this.ranChangeSetList = null; - this.serviceInitialized = false; - } - - public boolean hasDatabaseChangeLogTable() throws DatabaseException { - if (hasDatabaseChangeLogTable == null) { - try { - hasDatabaseChangeLogTable = SnapshotGeneratorFactory.getInstance().hasDatabaseChangeLogTable(getDatabase()); - } catch (LiquibaseException e) { - throw new UnexpectedLiquibaseException(e); - } - } - return hasDatabaseChangeLogTable; - } - - public void init() throws DatabaseException { - if (serviceInitialized) { - return; - } - Database database = getDatabase(); - Executor executor = ExecutorService.getInstance().getExecutor(database); - - Table changeLogTable = null; - try { - changeLogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database); - } catch (LiquibaseException e) { - throw new UnexpectedLiquibaseException(e); - } - - List statementsToExecute = new ArrayList(); - - boolean changeLogCreateAttempted = false; - if (changeLogTable != null) { - boolean hasDescription = changeLogTable.getColumn("DESCRIPTION") != null; - boolean hasComments = changeLogTable.getColumn("COMMENTS") != null; - boolean hasTag = changeLogTable.getColumn("TAG") != null; - boolean hasLiquibase = changeLogTable.getColumn("LIQUIBASE") != null; - boolean hasContexts = changeLogTable.getColumn("CONTEXTS") != null; - boolean hasLabels = changeLogTable.getColumn("LABELS") != null; - boolean liquibaseColumnNotRightSize = false; - if (!(this.getDatabase() instanceof SQLiteDatabase)) { - Column liquibaseColumn = changeLogTable.getColumn("LIQUIBASE"); - if (liquibaseColumn != null) { - Integer columnSize = liquibaseColumn.getType().getColumnSize(); - liquibaseColumnNotRightSize = columnSize != null && columnSize < 20; - } - } - boolean hasOrderExecuted = changeLogTable.getColumn("ORDEREXECUTED") != null; - boolean checksumNotRightSize = false; - if (!this.getDatabase().getConnection().getDatabaseProductName().equals("SQLite")) { - Column md5SumColumn = changeLogTable.getColumn("MD5SUM"); - if (md5SumColumn != null) { - Integer columnSize = md5SumColumn.getType().getColumnSize(); - checksumNotRightSize = columnSize != null && columnSize < 35; - } - } - boolean hasExecTypeColumn = changeLogTable.getColumn("EXECTYPE") != null; - boolean hasDeploymentIdColumn = changeLogTable.getColumn("DEPLOYMENT_ID") != null; - - if (!hasDescription) { - executor.comment("Adding missing databasechangelog.description column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DESCRIPTION", "VARCHAR(255)", null)); - } - if (!hasTag) { - executor.comment("Adding missing databasechangelog.tag column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "TAG", "VARCHAR(255)", null)); - } - if (!hasComments) { - executor.comment("Adding missing databasechangelog.comments column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "COMMENTS", "VARCHAR(255)", null)); - } - if (!hasLiquibase) { - executor.comment("Adding missing databasechangelog.liquibase column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", "VARCHAR(255)", null)); - } - if (!hasOrderExecuted) { - executor.comment("Adding missing databasechangelog.orderexecuted column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "INT", null)); - statementsToExecute.add(new UpdateStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()).addNewColumnValue("ORDEREXECUTED", -1)); - statementsToExecute.add(new SetNullableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "INT", false)); - } - if (checksumNotRightSize) { - executor.comment("Modifying size of databasechangelog.md5sum column"); - - statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "MD5SUM", "VARCHAR(35)")); - } - if (liquibaseColumnNotRightSize) { - executor.comment("Modifying size of databasechangelog.liquibase column"); - - statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", "VARCHAR(20)")); - } - if (!hasExecTypeColumn) { - executor.comment("Adding missing databasechangelog.exectype column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", "VARCHAR(10)", null)); - statementsToExecute.add(new UpdateStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()).addNewColumnValue("EXECTYPE", "EXECUTED")); - statementsToExecute.add(new SetNullableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", "VARCHAR(10)", false)); - } - - if (hasContexts) { - Integer columnSize = changeLogTable.getColumn("CONTEXTS").getType().getColumnSize(); - if (columnSize != null && columnSize < Integer.valueOf(getContextsSize())) { - executor.comment("Modifying size of databasechangelog.contexts column"); - statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", "VARCHAR("+getContextsSize()+")")); - } - } else { - executor.comment("Adding missing databasechangelog.contexts column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", "VARCHAR("+getContextsSize()+")", null)); - } - - if (hasLabels) { - Integer columnSize = changeLogTable.getColumn("LABELS").getType().getColumnSize(); - if (columnSize != null && columnSize < Integer.valueOf(getLabelsSize())) { - executor.comment("Modifying size of databasechangelog.labels column"); - statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", "VARCHAR("+getContextsSize()+")")); - } - } else { - executor.comment("Adding missing databasechangelog.labels column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", "VARCHAR("+getLabelsSize()+")", null)); - } - - if (!hasDeploymentIdColumn) { - executor.comment("Adding missing databasechangelog.deployment_id column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DEPLOYMENT_ID", "VARCHAR(10)", null)); - if (database instanceof DB2Database) { - statementsToExecute.add(new ReorganizeTableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName())); - } - } - - List> md5sumRS = ExecutorService.getInstance().getExecutor(database).queryForList(new SelectFromDatabaseChangeLogStatement(new SelectFromDatabaseChangeLogStatement.ByNotNullCheckSum(), new ColumnConfig().setName("MD5SUM")).setLimit(1)); - if (md5sumRS.size() > 0) { - String md5sum = md5sumRS.get(0).get("MD5SUM").toString(); - if (!md5sum.startsWith(CheckSum.getCurrentVersion() + ":")) { - executor.comment("DatabaseChangeLog checksums are an incompatible version. Setting them to null so they will be updated on next database update"); - statementsToExecute.add(new RawSqlStatement("UPDATE " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " SET MD5SUM=null")); - } - } - - - } else if (!changeLogCreateAttempted) { - executor.comment("Create Database Change Log Table"); - SqlStatement createTableStatement = new CreateDatabaseChangeLogTableStatement(); - if (!canCreateChangeLogTable()) { - throw new DatabaseException("Cannot create " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " table for your getDatabase().\n\n" + - "Please construct it manually using the following SQL as a base and re-run Liquibase:\n\n" + - createTableStatement); - } - // If there is no table in the database for recording change history create one. - statementsToExecute.add(createTableStatement); - LogFactory.getLogger().info("Creating database history table with name: " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName())); - } - - for (SqlStatement sql : statementsToExecute) { - if (SqlGeneratorFactory.getInstance().supports(sql, database)) { - executor.execute(sql); - getDatabase().commit(); - } else { - LogFactory.getLogger().info("Cannot run "+sql.getClass().getSimpleName()+" on "+getDatabase().getShortName()+" when checking databasechangelog table"); - } - } - serviceInitialized = true; - } - - protected String getLabelsSize() { - return "255"; - } - - protected String getContextsSize() { - return "255"; - } - - public void upgradeChecksums(final DatabaseChangeLog databaseChangeLog, final Contexts contexts, LabelExpression labels) throws DatabaseException { - super.upgradeChecksums(databaseChangeLog, contexts, labels); - getDatabase().commit(); - } - - /** - * Returns the ChangeSets that have been run against the current getDatabase(). - */ - public List getRanChangeSets() throws DatabaseException { - if (this.ranChangeSetList == null) { - Database database = getDatabase(); - String databaseChangeLogTableName = getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()); - List ranChangeSetList = new ArrayList(); - if (hasDatabaseChangeLogTable()) { - LogFactory.getLogger().info("Reading from " + databaseChangeLogTableName); - List> results = queryDatabaseChangeLogTable(database); - for (Map rs : results) { - String fileName = rs.get("FILENAME").toString(); - String author = rs.get("AUTHOR").toString(); - String id = rs.get("ID").toString(); - String md5sum = rs.get("MD5SUM") == null ? null : rs.get("MD5SUM").toString(); - String description = rs.get("DESCRIPTION") == null ? null : rs.get("DESCRIPTION").toString(); - String comments = rs.get("COMMENTS") == null ? null : rs.get("COMMENTS").toString(); - Object tmpDateExecuted = rs.get("DATEEXECUTED"); - Date dateExecuted = null; - if (tmpDateExecuted instanceof Date) { - dateExecuted = (Date) tmpDateExecuted; - } else { - DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - try { - dateExecuted = df.parse((String) tmpDateExecuted); - } catch (ParseException e) { - } - } - String tmpOrderExecuted = rs.get("ORDEREXECUTED").toString(); - Integer orderExecuted = (tmpOrderExecuted == null ? null : new Integer(tmpOrderExecuted)); - String tag = rs.get("TAG") == null ? null : rs.get("TAG").toString(); - String execType = rs.get("EXECTYPE") == null ? null : rs.get("EXECTYPE").toString(); - ContextExpression contexts = new ContextExpression((String) rs.get("CONTEXTS")); - Labels labels = new Labels((String) rs.get("LABELS")); - String deploymentId = (String) rs.get("DEPLOYMENT_ID"); - - try { - RanChangeSet ranChangeSet = new RanChangeSet(fileName, id, author, CheckSum.parse(md5sum), dateExecuted, tag, ChangeSet.ExecType.valueOf(execType), description, comments, contexts, labels, deploymentId); - ranChangeSet.setOrderExecuted(orderExecuted); - ranChangeSetList.add(ranChangeSet); - } catch (IllegalArgumentException e) { - LogFactory.getLogger().severe("Unknown EXECTYPE from database: " + execType); - throw e; - } - } - } - - this.ranChangeSetList = ranChangeSetList; - } - return Collections.unmodifiableList(ranChangeSetList); - } - - public List> queryDatabaseChangeLogTable(Database database) throws DatabaseException { - SelectFromDatabaseChangeLogStatement select = new SelectFromDatabaseChangeLogStatement(new ColumnConfig().setName("*").setComputed(true)).setOrderBy("DATEEXECUTED ASC", "ORDEREXECUTED ASC"); - return ExecutorService.getInstance().getExecutor(database).queryForList(select); - } - - @Override - protected void replaceChecksum(ChangeSet changeSet) throws DatabaseException { - ExecutorService.getInstance().getExecutor(getDatabase()).execute(new UpdateChangeSetChecksumStatement(changeSet)); - - getDatabase().commit(); - reset(); - } - - @Override - public RanChangeSet getRanChangeSet(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException { - if (!hasDatabaseChangeLogTable()) { - return null; - } - - return super.getRanChangeSet(changeSet); - } - - @Override - public void setExecType(ChangeSet changeSet, ChangeSet.ExecType execType) throws DatabaseException { - Database database = getDatabase(); - - ExecutorService.getInstance().getExecutor(database).execute(new MarkChangeSetRanStatement(changeSet, execType)); - getDatabase().commit(); - if (this.ranChangeSetList != null) { - this.ranChangeSetList.add(new RanChangeSet(changeSet, execType, null, null)); - } - - } - - @Override - public void removeFromHistory(final ChangeSet changeSet) throws DatabaseException { - Database database = getDatabase(); - ExecutorService.getInstance().getExecutor(database).execute(new RemoveChangeSetRanStatusStatement(changeSet)); - getDatabase().commit(); - - if (this.ranChangeSetList != null) { - this.ranChangeSetList.remove(new RanChangeSet(changeSet)); - } - } - - @Override - public int getNextSequenceValue() throws LiquibaseException { - if (lastChangeSetSequenceValue == null) { - if (getDatabase().getConnection() == null) { - lastChangeSetSequenceValue = 0; - } else { - lastChangeSetSequenceValue = ExecutorService.getInstance().getExecutor(getDatabase()).queryForInt(new GetNextChangeSetSequenceValueStatement()); - } - } - - return ++lastChangeSetSequenceValue; - } - - /** - * Tags the database changelog with the given string. - */ - @Override - public void tag(final String tagString) throws DatabaseException { - Database database = getDatabase(); - Executor executor = ExecutorService.getInstance().getExecutor(database); - try { - int totalRows = ExecutorService.getInstance().getExecutor(database).queryForInt(new SelectFromDatabaseChangeLogStatement(new ColumnConfig().setName("COUNT(*)", true))); - if (totalRows == 0) { - ChangeSet emptyChangeSet = new ChangeSet(String.valueOf(new Date().getTime()), "liquibase", false, false, "liquibase-internal", null, null, getDatabase().getObjectQuotingStrategy(), null); - this.setExecType(emptyChangeSet, ChangeSet.ExecType.EXECUTED); - } - -// Timestamp lastExecutedDate = (Timestamp) this.getExecutor().queryForObject(createChangeToTagSQL(), Timestamp.class); - executor.execute(new TagDatabaseStatement(tagString)); - getDatabase().commit(); - - if (this.ranChangeSetList != null) { - ranChangeSetList.get(ranChangeSetList.size() - 1).setTag(tagString); - } - } catch (Exception e) { - throw new DatabaseException(e); - } - } - - @Override - public boolean tagExists(final String tag) throws DatabaseException { - int count = ExecutorService.getInstance().getExecutor(getDatabase()).queryForInt(new SelectFromDatabaseChangeLogStatement(new SelectFromDatabaseChangeLogStatement.ByTag(tag), new ColumnConfig().setName("COUNT(*)", true))); - return count > 0; - } - - @Override - public void clearAllCheckSums() throws LiquibaseException { - Database database = getDatabase(); - UpdateStatement updateStatement = new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName()); - updateStatement.addNewColumnValue("MD5SUM", null); - ExecutorService.getInstance().getExecutor(database).execute(updateStatement); - database.commit(); - } - - @Override - public void destroy() throws DatabaseException { - Database database = getDatabase(); - try { - if (SnapshotGeneratorFactory.getInstance().has(new Table().setName(database.getDatabaseChangeLogTableName()).setSchema(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName()), database)) { - ExecutorService.getInstance().getExecutor(database).execute(new DropTableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName(), false)); - } - reset(); - } catch (InvalidExampleException e) { - throw new UnexpectedLiquibaseException(e); - } - } -} diff --git a/All/Genesis-NP/Genesis#276/old/StandardChangeLogHistoryService.java b/All/Genesis-NP/Genesis#276/old/StandardChangeLogHistoryService.java deleted file mode 100755 index 1cd27b4..0000000 --- a/All/Genesis-NP/Genesis#276/old/StandardChangeLogHistoryService.java +++ /dev/null @@ -1,400 +0,0 @@ -package liquibase.changelog; - -import liquibase.ContextExpression; -import liquibase.Contexts; -import liquibase.LabelExpression; -import liquibase.Labels; -import liquibase.change.CheckSum; -import liquibase.change.ColumnConfig; -import liquibase.database.Database; -import liquibase.database.core.DB2Database; -import liquibase.database.core.SQLiteDatabase; -import liquibase.exception.DatabaseException; -import liquibase.exception.DatabaseHistoryException; -import liquibase.exception.LiquibaseException; -import liquibase.exception.UnexpectedLiquibaseException; -import liquibase.executor.Executor; -import liquibase.executor.ExecutorService; -import liquibase.logging.LogFactory; -import liquibase.snapshot.InvalidExampleException; -import liquibase.snapshot.SnapshotControl; -import liquibase.snapshot.SnapshotGeneratorFactory; -import liquibase.sqlgenerator.SqlGeneratorFactory; -import liquibase.statement.SqlStatement; -import liquibase.statement.core.*; -import liquibase.structure.core.Column; -import liquibase.structure.core.Table; - -import java.text.DateFormat; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.*; - -public class StandardChangeLogHistoryService extends AbstractChangeLogHistoryService { - - private List ranChangeSetList; - private boolean serviceInitialized = false; - private Boolean hasDatabaseChangeLogTable = null; - private Integer lastChangeSetSequenceValue; - - @Override - public int getPriority() { - return PRIORITY_DEFAULT; - } - - @Override - public boolean supports(Database database) { - return true; - } - - public String getDatabaseChangeLogTableName() { - return getDatabase().getDatabaseChangeLogTableName(); - } - - public String getLiquibaseSchemaName() { - return getDatabase().getLiquibaseSchemaName(); - } - - public String getLiquibaseCatalogName() { - return getDatabase().getLiquibaseCatalogName(); - } - - public boolean canCreateChangeLogTable() throws DatabaseException { - return true; - } - - public void reset() { - this.ranChangeSetList = null; - this.serviceInitialized = false; - } - - public boolean hasDatabaseChangeLogTable() throws DatabaseException { - if (hasDatabaseChangeLogTable == null) { - try { - hasDatabaseChangeLogTable = SnapshotGeneratorFactory.getInstance().hasDatabaseChangeLogTable(getDatabase()); - } catch (LiquibaseException e) { - throw new UnexpectedLiquibaseException(e); - } - } - return hasDatabaseChangeLogTable; - } - - public void init() throws DatabaseException { - if (serviceInitialized) { - return; - } - Database database = getDatabase(); - Executor executor = ExecutorService.getInstance().getExecutor(database); - - Table changeLogTable = null; - try { - changeLogTable = SnapshotGeneratorFactory.getInstance().getDatabaseChangeLogTable(new SnapshotControl(database, false, Table.class, Column.class), database); - } catch (LiquibaseException e) { - throw new UnexpectedLiquibaseException(e); - } - - List statementsToExecute = new ArrayList(); - - boolean changeLogCreateAttempted = false; - if (changeLogTable != null) { - boolean hasDescription = changeLogTable.getColumn("DESCRIPTION") != null; - boolean hasComments = changeLogTable.getColumn("COMMENTS") != null; - boolean hasTag = changeLogTable.getColumn("TAG") != null; - boolean hasLiquibase = changeLogTable.getColumn("LIQUIBASE") != null; - boolean hasContexts = changeLogTable.getColumn("CONTEXTS") != null; - boolean hasLabels = changeLogTable.getColumn("LABELS") != null; - boolean liquibaseColumnNotRightSize = false; - if (!(this.getDatabase() instanceof SQLiteDatabase)) { - Integer columnSize = changeLogTable.getColumn("LIQUIBASE").getType().getColumnSize(); - liquibaseColumnNotRightSize = columnSize != null && columnSize < 20; - } - boolean hasOrderExecuted = changeLogTable.getColumn("ORDEREXECUTED") != null; - boolean checksumNotRightSize = false; - if (!this.getDatabase().getConnection().getDatabaseProductName().equals("SQLite")) { - Integer columnSize = changeLogTable.getColumn("MD5SUM").getType().getColumnSize(); - checksumNotRightSize = columnSize != null && columnSize < 35; - } - boolean hasExecTypeColumn = changeLogTable.getColumn("EXECTYPE") != null; - boolean hasDeploymentIdColumn = changeLogTable.getColumn("DEPLOYMENT_ID") != null; - - if (!hasDescription) { - executor.comment("Adding missing databasechangelog.description column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DESCRIPTION", "VARCHAR(255)", null)); - } - if (!hasTag) { - executor.comment("Adding missing databasechangelog.tag column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "TAG", "VARCHAR(255)", null)); - } - if (!hasComments) { - executor.comment("Adding missing databasechangelog.comments column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "COMMENTS", "VARCHAR(255)", null)); - } - if (!hasLiquibase) { - executor.comment("Adding missing databasechangelog.liquibase column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", "VARCHAR(255)", null)); - } - if (!hasOrderExecuted) { - executor.comment("Adding missing databasechangelog.orderexecuted column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "INT", null)); - statementsToExecute.add(new UpdateStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()).addNewColumnValue("ORDEREXECUTED", -1)); - statementsToExecute.add(new SetNullableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "ORDEREXECUTED", "INT", false)); - } - if (checksumNotRightSize) { - executor.comment("Modifying size of databasechangelog.md5sum column"); - - statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "MD5SUM", "VARCHAR(35)")); - } - if (liquibaseColumnNotRightSize) { - executor.comment("Modifying size of databasechangelog.liquibase column"); - - statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LIQUIBASE", "VARCHAR(20)")); - } - if (!hasExecTypeColumn) { - executor.comment("Adding missing databasechangelog.exectype column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", "VARCHAR(10)", null)); - statementsToExecute.add(new UpdateStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()).addNewColumnValue("EXECTYPE", "EXECUTED")); - statementsToExecute.add(new SetNullableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "EXECTYPE", "VARCHAR(10)", false)); - } - - if (hasContexts) { - Integer columnSize = changeLogTable.getColumn("CONTEXTS").getType().getColumnSize(); - if (columnSize != null && columnSize < Integer.valueOf(getContextsSize())) { - executor.comment("Modifying size of databasechangelog.contexts column"); - statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", "VARCHAR("+getContextsSize()+")")); - } - } else { - executor.comment("Adding missing databasechangelog.contexts column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "CONTEXTS", "VARCHAR("+getContextsSize()+")", null)); - } - - if (hasLabels) { - Integer columnSize = changeLogTable.getColumn("LABELS").getType().getColumnSize(); - if (columnSize != null && columnSize < Integer.valueOf(getLabelsSize())) { - executor.comment("Modifying size of databasechangelog.labels column"); - statementsToExecute.add(new ModifyDataTypeStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", "VARCHAR("+getContextsSize()+")")); - } - } else { - executor.comment("Adding missing databasechangelog.labels column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "LABELS", "VARCHAR("+getLabelsSize()+")", null)); - } - - if (!hasDeploymentIdColumn) { - executor.comment("Adding missing databasechangelog.deployment_id column"); - statementsToExecute.add(new AddColumnStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName(), "DEPLOYMENT_ID", "VARCHAR(10)", null)); - if (database instanceof DB2Database) { - statementsToExecute.add(new ReorganizeTableStatement(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName())); - } - } - - List> md5sumRS = ExecutorService.getInstance().getExecutor(database).queryForList(new SelectFromDatabaseChangeLogStatement(new SelectFromDatabaseChangeLogStatement.ByNotNullCheckSum(), new ColumnConfig().setName("MD5SUM")).setLimit(1)); - if (md5sumRS.size() > 0) { - String md5sum = md5sumRS.get(0).get("MD5SUM").toString(); - if (!md5sum.startsWith(CheckSum.getCurrentVersion() + ":")) { - executor.comment("DatabaseChangeLog checksums are an incompatible version. Setting them to null so they will be updated on next database update"); - statementsToExecute.add(new RawSqlStatement("UPDATE " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " SET MD5SUM=null")); - } - } - - - } else if (!changeLogCreateAttempted) { - executor.comment("Create Database Change Log Table"); - SqlStatement createTableStatement = new CreateDatabaseChangeLogTableStatement(); - if (!canCreateChangeLogTable()) { - throw new DatabaseException("Cannot create " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()) + " table for your getDatabase().\n\n" + - "Please construct it manually using the following SQL as a base and re-run Liquibase:\n\n" + - createTableStatement); - } - // If there is no table in the database for recording change history create one. - statementsToExecute.add(createTableStatement); - LogFactory.getLogger().info("Creating database history table with name: " + getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName())); - } - - for (SqlStatement sql : statementsToExecute) { - if (SqlGeneratorFactory.getInstance().supports(sql, database)) { - executor.execute(sql); - getDatabase().commit(); - } else { - LogFactory.getLogger().info("Cannot run "+sql.getClass().getSimpleName()+" on "+getDatabase().getShortName()+" when checking databasechangelog table"); - } - } - serviceInitialized = true; - } - - protected String getLabelsSize() { - return "255"; - } - - protected String getContextsSize() { - return "255"; - } - - public void upgradeChecksums(final DatabaseChangeLog databaseChangeLog, final Contexts contexts, LabelExpression labels) throws DatabaseException { - super.upgradeChecksums(databaseChangeLog, contexts, labels); - getDatabase().commit(); - } - - /** - * Returns the ChangeSets that have been run against the current getDatabase(). - */ - public List getRanChangeSets() throws DatabaseException { - if (this.ranChangeSetList == null) { - Database database = getDatabase(); - String databaseChangeLogTableName = getDatabase().escapeTableName(getLiquibaseCatalogName(), getLiquibaseSchemaName(), getDatabaseChangeLogTableName()); - List ranChangeSetList = new ArrayList(); - if (hasDatabaseChangeLogTable()) { - LogFactory.getLogger().info("Reading from " + databaseChangeLogTableName); - List> results = queryDatabaseChangeLogTable(database); - for (Map rs : results) { - String fileName = rs.get("FILENAME").toString(); - String author = rs.get("AUTHOR").toString(); - String id = rs.get("ID").toString(); - String md5sum = rs.get("MD5SUM") == null ? null : rs.get("MD5SUM").toString(); - String description = rs.get("DESCRIPTION") == null ? null : rs.get("DESCRIPTION").toString(); - String comments = rs.get("COMMENTS") == null ? null : rs.get("COMMENTS").toString(); - Object tmpDateExecuted = rs.get("DATEEXECUTED"); - Date dateExecuted = null; - if (tmpDateExecuted instanceof Date) { - dateExecuted = (Date) tmpDateExecuted; - } else { - DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - try { - dateExecuted = df.parse((String) tmpDateExecuted); - } catch (ParseException e) { - } - } - String tmpOrderExecuted = rs.get("ORDEREXECUTED").toString(); - Integer orderExecuted = (tmpOrderExecuted == null ? null : new Integer(tmpOrderExecuted)); - String tag = rs.get("TAG") == null ? null : rs.get("TAG").toString(); - String execType = rs.get("EXECTYPE") == null ? null : rs.get("EXECTYPE").toString(); - ContextExpression contexts = new ContextExpression((String) rs.get("CONTEXTS")); - Labels labels = new Labels((String) rs.get("LABELS")); - String deploymentId = (String) rs.get("DEPLOYMENT_ID"); - - try { - RanChangeSet ranChangeSet = new RanChangeSet(fileName, id, author, CheckSum.parse(md5sum), dateExecuted, tag, ChangeSet.ExecType.valueOf(execType), description, comments, contexts, labels, deploymentId); - ranChangeSet.setOrderExecuted(orderExecuted); - ranChangeSetList.add(ranChangeSet); - } catch (IllegalArgumentException e) { - LogFactory.getLogger().severe("Unknown EXECTYPE from database: " + execType); - throw e; - } - } - } - - this.ranChangeSetList = ranChangeSetList; - } - return Collections.unmodifiableList(ranChangeSetList); - } - - public List> queryDatabaseChangeLogTable(Database database) throws DatabaseException { - SelectFromDatabaseChangeLogStatement select = new SelectFromDatabaseChangeLogStatement(new ColumnConfig().setName("*").setComputed(true)).setOrderBy("DATEEXECUTED ASC", "ORDEREXECUTED ASC"); - return ExecutorService.getInstance().getExecutor(database).queryForList(select); - } - - @Override - protected void replaceChecksum(ChangeSet changeSet) throws DatabaseException { - ExecutorService.getInstance().getExecutor(getDatabase()).execute(new UpdateChangeSetChecksumStatement(changeSet)); - - getDatabase().commit(); - reset(); - } - - @Override - public RanChangeSet getRanChangeSet(final ChangeSet changeSet) throws DatabaseException, DatabaseHistoryException { - if (!hasDatabaseChangeLogTable()) { - return null; - } - - return super.getRanChangeSet(changeSet); - } - - @Override - public void setExecType(ChangeSet changeSet, ChangeSet.ExecType execType) throws DatabaseException { - Database database = getDatabase(); - - ExecutorService.getInstance().getExecutor(database).execute(new MarkChangeSetRanStatement(changeSet, execType)); - getDatabase().commit(); - if (this.ranChangeSetList != null) { - this.ranChangeSetList.add(new RanChangeSet(changeSet, execType, null, null)); - } - - } - - @Override - public void removeFromHistory(final ChangeSet changeSet) throws DatabaseException { - Database database = getDatabase(); - ExecutorService.getInstance().getExecutor(database).execute(new RemoveChangeSetRanStatusStatement(changeSet)); - getDatabase().commit(); - - if (this.ranChangeSetList != null) { - this.ranChangeSetList.remove(new RanChangeSet(changeSet)); - } - } - - @Override - public int getNextSequenceValue() throws LiquibaseException { - if (lastChangeSetSequenceValue == null) { - if (getDatabase().getConnection() == null) { - lastChangeSetSequenceValue = 0; - } else { - lastChangeSetSequenceValue = ExecutorService.getInstance().getExecutor(getDatabase()).queryForInt(new GetNextChangeSetSequenceValueStatement()); - } - } - - return ++lastChangeSetSequenceValue; - } - - /** - * Tags the database changelog with the given string. - */ - @Override - public void tag(final String tagString) throws DatabaseException { - Database database = getDatabase(); - Executor executor = ExecutorService.getInstance().getExecutor(database); - try { - int totalRows = ExecutorService.getInstance().getExecutor(database).queryForInt(new SelectFromDatabaseChangeLogStatement(new ColumnConfig().setName("COUNT(*)", true))); - if (totalRows == 0) { - ChangeSet emptyChangeSet = new ChangeSet(String.valueOf(new Date().getTime()), "liquibase", false, false, "liquibase-internal", null, null, getDatabase().getObjectQuotingStrategy(), null); - this.setExecType(emptyChangeSet, ChangeSet.ExecType.EXECUTED); - } - -// Timestamp lastExecutedDate = (Timestamp) this.getExecutor().queryForObject(createChangeToTagSQL(), Timestamp.class); - executor.execute(new TagDatabaseStatement(tagString)); - getDatabase().commit(); - - if (this.ranChangeSetList != null) { - ranChangeSetList.get(ranChangeSetList.size() - 1).setTag(tagString); - } - } catch (Exception e) { - throw new DatabaseException(e); - } - } - - @Override - public boolean tagExists(final String tag) throws DatabaseException { - int count = ExecutorService.getInstance().getExecutor(getDatabase()).queryForInt(new SelectFromDatabaseChangeLogStatement(new SelectFromDatabaseChangeLogStatement.ByTag(tag), new ColumnConfig().setName("COUNT(*)", true))); - return count > 0; - } - - @Override - public void clearAllCheckSums() throws LiquibaseException { - Database database = getDatabase(); - UpdateStatement updateStatement = new UpdateStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName()); - updateStatement.addNewColumnValue("MD5SUM", null); - ExecutorService.getInstance().getExecutor(database).execute(updateStatement); - database.commit(); - } - - @Override - public void destroy() throws DatabaseException { - Database database = getDatabase(); - try { - if (SnapshotGeneratorFactory.getInstance().has(new Table().setName(database.getDatabaseChangeLogTableName()).setSchema(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName()), database)) { - ExecutorService.getInstance().getExecutor(database).execute(new DropTableStatement(database.getLiquibaseCatalogName(), database.getLiquibaseSchemaName(), database.getDatabaseChangeLogTableName(), false)); - } - reset(); - } catch (InvalidExampleException e) { - throw new UnexpectedLiquibaseException(e); - } - } -} diff --git a/All/Genesis-NP/Genesis#276/pair.info b/All/Genesis-NP/Genesis#276/pair.info deleted file mode 100755 index f68399d..0000000 --- a/All/Genesis-NP/Genesis#276/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:276 -SATName:Genesis -modifiedFPath:liquibase-core/src/main/java/liquibase/changelog/StandardChangeLogHistoryService.java -comSha:459f2db82b3d2a84d2473392988045e9be0b864c -parentComSha:459f2db82b3d2a84d2473392988045e9be0b864c^1 -githubUrl:https://github.com/liquibase/liquibase -repoName:liquibase#liquibase \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#286/comMsg.txt b/All/Genesis-NP/Genesis#286/comMsg.txt deleted file mode 100755 index 81eb9f8..0000000 --- a/All/Genesis-NP/Genesis#286/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -CORE-2088 outputDefaultSchema and outputDefaultCatalog command line parameters not respected diff --git a/All/Genesis-NP/Genesis#286/diff.diff b/All/Genesis-NP/Genesis#286/diff.diff deleted file mode 100755 index 103b863..0000000 --- a/All/Genesis-NP/Genesis#286/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java b/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java -index 4dba659..e6413f0 100644 ---- a/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java -+++ b/liquibase-core/src/main/java/liquibase/integration/commandline/Main.java -@@ -70 +70 @@ public class Main { -- protected String defaultsFile; -+ protected String defaultsFile = "liquibase.properties"; diff --git a/All/Genesis-NP/Genesis#286/new/Main.java b/All/Genesis-NP/Genesis#286/new/Main.java deleted file mode 100755 index e6413f0..0000000 --- a/All/Genesis-NP/Genesis#286/new/Main.java +++ /dev/null @@ -1,1204 +0,0 @@ -package liquibase.integration.commandline; - -import liquibase.CatalogAndSchema; -import liquibase.Contexts; -import liquibase.LabelExpression; -import liquibase.Liquibase; -import liquibase.change.CheckSum; -import liquibase.command.ExecuteSqlCommand; -import liquibase.command.SnapshotCommand; -import liquibase.configuration.LiquibaseConfiguration; -import liquibase.configuration.GlobalConfiguration; -import liquibase.database.Database; -import liquibase.diff.compare.CompareControl; -import liquibase.diff.output.DiffOutputControl; -import liquibase.exception.CommandLineParsingException; -import liquibase.exception.DatabaseException; -import liquibase.exception.LiquibaseException; -import liquibase.exception.ValidationFailedException; -import liquibase.lockservice.LockService; -import liquibase.lockservice.LockServiceFactory; -import liquibase.logging.LogFactory; -import liquibase.logging.LogLevel; -import liquibase.logging.Logger; -import liquibase.resource.ClassLoaderResourceAccessor; -import liquibase.resource.CompositeResourceAccessor; -import liquibase.resource.FileSystemResourceAccessor; -import liquibase.servicelocator.ServiceLocator; -import liquibase.util.ISODateFormat; -import liquibase.util.LiquibaseUtil; -import liquibase.util.StreamUtil; -import liquibase.util.StringUtils; - -import java.io.*; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.text.ParseException; -import java.util.*; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -/** - * Class for executing Liquibase via the command line. - */ -public class Main { - protected ClassLoader classLoader; - - protected String driver; - protected String username; - protected String password; - protected String url; - protected String databaseClass; - protected String defaultSchemaName; - protected String outputDefaultSchema; - protected String outputDefaultCatalog; - protected String liquibaseCatalogName; - protected String liquibaseSchemaName; - protected String defaultCatalogName; - protected String changeLogFile; - protected String classpath; - protected String contexts; - protected String labels; - protected String driverPropertiesFile; - protected String propertyProviderClass = null; - protected Boolean promptForNonLocalDatabase = null; - protected Boolean includeSystemClasspath; - protected Boolean strict = Boolean.TRUE; - protected String defaultsFile = "liquibase.properties"; - - protected String diffTypes; - protected String changeSetAuthor; - protected String changeSetContext; - protected String dataOutputDirectory; - - protected String referenceDriver; - protected String referenceUrl; - protected String referenceUsername; - protected String referencePassword; - - protected String currentDateTimeFunction; - - protected String command; - protected Set commandParams = new LinkedHashSet(); - - protected String logLevel; - protected String logFile; - - protected Map changeLogParameters = new HashMap(); - - protected String outputFile; - - public static void main(String args[]) throws CommandLineParsingException, IOException { - try { - run(args); - } catch (LiquibaseException e) { - System.exit(-1); - } - System.exit(0); - } - - public static void run(String args[]) throws CommandLineParsingException, IOException, LiquibaseException { - try { - GlobalConfiguration globalConfiguration = LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class); - - if (!globalConfiguration.getShouldRun()) { - System.err.println("Liquibase did not run because '" + LiquibaseConfiguration.getInstance().describeValueLookupLogic(globalConfiguration.getProperty(GlobalConfiguration.SHOULD_RUN)) + " was set to false"); - return; - } - -// if (!System.getProperties().contains("file.encoding")) { -// System.setProperty("file.encoding", "UTF-8"); -// } - - Main main = new Main(); - if (args.length == 1 && "--help".equals(args[0])) { - main.printHelp(System.err); - return; - } else if (args.length == 1 && "--version".equals(args[0])) { - System.err.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator()); - return; - } - - try { - main.parseOptions(args); - } catch (CommandLineParsingException e) { - // Print the help before throwing the exception - main.printHelp(Arrays.asList(e.getMessage()), System.err); - throw e; - } - - File propertiesFile = new File(main.defaultsFile); - String localDefaultsPathName = main.defaultsFile.replaceFirst("(\\.[^\\.]+)$", ".local$1"); - File localPropertiesFile = new File(localDefaultsPathName); - - if (localPropertiesFile.exists()) { - FileInputStream stream = new FileInputStream(localPropertiesFile); - try { - main.parsePropertiesFile(stream); - } finally { - stream.close(); - } - } else { - InputStream resourceAsStream = main.getClass().getClassLoader().getResourceAsStream(localDefaultsPathName); - if (resourceAsStream != null) { - try { - main.parsePropertiesFile(resourceAsStream); - } finally { - resourceAsStream.close(); - } - } - } - if (propertiesFile.exists()) { - FileInputStream stream = new FileInputStream(propertiesFile); - main.parsePropertiesFile(stream); - } else { - InputStream resourceAsStream = main.getClass().getClassLoader().getResourceAsStream(main.defaultsFile); - if (resourceAsStream != null) { - try { - main.parsePropertiesFile(resourceAsStream); - } finally { - resourceAsStream.close(); - } - } - - } - - List setupMessages = main.checkSetup(); - if (setupMessages.size() > 0) { - main.printHelp(setupMessages, System.err); - return; - } - - main.applyDefaults(); - main.configureClassLoader(); - main.doMigration(); - - if ("update".equals(main.command)) { - System.err.println("Liquibase Update Successful"); - } else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) { - System.err.println("Liquibase Rollback Successful"); - } else if (!main.command.endsWith("SQL")) { - System.err.println("Liquibase '"+main.command+"' Successful"); - } - } catch (Throwable e) { - String message = e.getMessage(); - if ( e.getCause() != null ) { - message = e.getCause().getMessage(); - } - if ( message == null ) { - message = "Unknown Reason"; - } - // At a minimum, log the message. We don't need to print the stack - // trace because the logger already did that upstream. - try { - if ( e.getCause() instanceof ValidationFailedException ) { - ((ValidationFailedException)e.getCause()).printDescriptiveError(System.out); - } else { - System.err.println("Unexpected error running Liquibase: " + message + "\n"); - LogFactory.getInstance().getLog().severe(message, e); - System.err.println(generateLogLevelWarningMessage()); - } - } catch (Exception e1) { - e.printStackTrace(); - } - throw new LiquibaseException("Unexpected error running Liquibase: " + message, e); - } - } - - private static String generateLogLevelWarningMessage() { - Logger logger = LogFactory.getInstance().getLog(); - if (logger != null && logger.getLogLevel() != null && (logger.getLogLevel().equals(LogLevel.OFF))) { - return ""; - } else { - return "\n\nFor more information, use the --logLevel flag"; - } - } - - /** - * On windows machines, it splits args on '=' signs. Put it back like it was. - */ - protected String[] fixupArgs(String[] args) { - List fixedArgs = new ArrayList(); - - for (int i = 0; i < args.length; i++) { - String arg = args[i]; - if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { - String nextArg = null; - if (i + 1 < args.length) { - nextArg = args[i + 1]; - } - if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) { - arg = arg + "=" + nextArg; - i++; - } - } - fixedArgs.add(arg); - } - - return fixedArgs.toArray(new String[fixedArgs.size()]); - } - - protected List checkSetup() { - List messages = new ArrayList(); - if (command == null) { - messages.add("Command not passed"); - } else if (!isCommand(command)) { - messages.add("Unknown command: " + command); - } else { - if (url == null) { - messages.add("--url is required"); - } - - if (isChangeLogRequired(command) && changeLogFile == null) { - messages.add("--changeLogFile is required"); - } - - if (isNoArgCommand(command) && !commandParams.isEmpty()) { - messages.add("unexpected command parameters: "+commandParams); - } else { - validateCommandParameters(messages); - } - } - return messages; - } - - private void checkForUnexpectedCommandParameter(List messages) { - if ("updateCount".equalsIgnoreCase(command) - || "updateCountSQL".equalsIgnoreCase(command) - || "rollback".equalsIgnoreCase(command) - || "rollbackToDate".equalsIgnoreCase(command) - || "rollbackCount".equalsIgnoreCase(command) - || "rollbackSQL".equalsIgnoreCase(command) - || "rollbackToDateSQL".equalsIgnoreCase(command) - || "rollbackCountSQL".equalsIgnoreCase(command) - || "calculateCheckSum".equalsIgnoreCase(command) - || "dbDoc".equalsIgnoreCase(command) - || "tag".equalsIgnoreCase(command)) { - - if (commandParams.size() > 0 && commandParams.iterator().next().startsWith("-")) { - messages.add("unexpected command parameters: "+commandParams); - } - } else if ("status".equalsIgnoreCase(command) - || "unexpectedChangeSets".equalsIgnoreCase(command)) { - if (commandParams.size() > 0 && !commandParams.iterator().next().equalsIgnoreCase("--verbose")) { - messages.add("unexpected command parameters: "+commandParams); - } - } else if ("diff".equalsIgnoreCase(command) - || "diffChangeLog".equalsIgnoreCase(command)) { - if (commandParams.size() > 0) { - for (String cmdParm : commandParams) { - if (!cmdParm.startsWith("--referenceUsername") - && !cmdParm.startsWith("--referencePassword") - && !cmdParm.startsWith("--referenceDriver") - && !cmdParm.startsWith("--referenceDefaultCatalogName") - && !cmdParm.startsWith("--referenceDefaultSchemaName") - && !cmdParm.startsWith("--includeSchema") - && !cmdParm.startsWith("--includeCatalog") - && !cmdParm.startsWith("--includeTablespace") - && !cmdParm.startsWith("--schemas") - && !cmdParm.startsWith("--referenceUrl") - && !cmdParm.startsWith("--diffTypes")) { - messages.add("unexpected command parameter: "+cmdParm); - } - } - } - } - - } - - private void validateCommandParameters(final List messages) { - checkForUnexpectedCommandParameter(messages); - checkForMissingCommandParameters(messages); - checkForMalformedCommandParameters(messages); - } - - private void checkForMissingCommandParameters(final List messages) { - if (commandParams.isEmpty() || commandParams.iterator().next().startsWith("-")) { - if ("calculateCheckSum".equalsIgnoreCase(command)) { - messages.add("missing changeSet identifier"); - } - } - } - - private void checkForMalformedCommandParameters(final List messages) { - if (!commandParams.isEmpty()) { - if ("calculateCheckSum".equalsIgnoreCase(command)) { - for (final String param : commandParams) { - assert param != null; - if (param != null && !param.startsWith("-")) { - final String[] parts = param.split("::"); - if (parts == null || parts.length < 3) { - messages.add("changeSet identifier must be of the form filepath::id::author"); - break; - } - } - } - } - } - } - - private boolean isChangeLogRequired(String command) { - return command.toLowerCase().startsWith("update") - || command.toLowerCase().startsWith("rollback") - || "calculateCheckSum".equalsIgnoreCase(command) - || "status".equalsIgnoreCase(command) - || "validate".equalsIgnoreCase(command) - || "changeLogSync".equalsIgnoreCase(command) - || "changeLogSyncSql".equalsIgnoreCase(command) - || "generateChangeLog".equalsIgnoreCase(command); - } - - private boolean isCommand(String arg) { - return "migrate".equals(arg) - || "migrateSQL".equalsIgnoreCase(arg) - || "update".equalsIgnoreCase(arg) - || "updateSQL".equalsIgnoreCase(arg) - || "updateCount".equalsIgnoreCase(arg) - || "updateCountSQL".equalsIgnoreCase(arg) - || "rollback".equalsIgnoreCase(arg) - || "rollbackToDate".equalsIgnoreCase(arg) - || "rollbackCount".equalsIgnoreCase(arg) - || "rollbackSQL".equalsIgnoreCase(arg) - || "rollbackToDateSQL".equalsIgnoreCase(arg) - || "rollbackCountSQL".equalsIgnoreCase(arg) - || "futureRollbackSQL".equalsIgnoreCase(arg) - || "futureRollbackCountSQL".equalsIgnoreCase(arg) - || "updateTestingRollback".equalsIgnoreCase(arg) - || "tag".equalsIgnoreCase(arg) - || "listLocks".equalsIgnoreCase(arg) - || "dropAll".equalsIgnoreCase(arg) - || "releaseLocks".equalsIgnoreCase(arg) - || "status".equalsIgnoreCase(arg) - || "unexpectedChangeSets".equalsIgnoreCase(arg) - || "validate".equalsIgnoreCase(arg) - || "help".equalsIgnoreCase(arg) - || "diff".equalsIgnoreCase(arg) - || "diffChangeLog".equalsIgnoreCase(arg) - || "generateChangeLog".equalsIgnoreCase(arg) - || "snapshot".equalsIgnoreCase(arg) - || "snapshotReference".equalsIgnoreCase(arg) - || "executeSql".equalsIgnoreCase(arg) - || "calculateCheckSum".equalsIgnoreCase(arg) - || "clearCheckSums".equalsIgnoreCase(arg) - || "dbDoc".equalsIgnoreCase(arg) - || "changelogSync".equalsIgnoreCase(arg) - || "changelogSyncSQL".equalsIgnoreCase(arg) - || "markNextChangeSetRan".equalsIgnoreCase(arg) - || "markNextChangeSetRanSQL".equalsIgnoreCase(arg); - } - - private boolean isNoArgCommand(String arg) { - return "migrate".equals(arg) - || "migrateSQL".equalsIgnoreCase(arg) - || "update".equalsIgnoreCase(arg) - || "updateSQL".equalsIgnoreCase(arg) - || "futureRollbackSQL".equalsIgnoreCase(arg) - || "updateTestingRollback".equalsIgnoreCase(arg) - || "listLocks".equalsIgnoreCase(arg) - || "dropAll".equalsIgnoreCase(arg) - || "releaseLocks".equalsIgnoreCase(arg) - || "validate".equalsIgnoreCase(arg) - || "help".equalsIgnoreCase(arg) - || "clearCheckSums".equalsIgnoreCase(arg) - || "changelogSync".equalsIgnoreCase(arg) - || "changelogSyncSQL".equalsIgnoreCase(arg) - || "markNextChangeSetRan".equalsIgnoreCase(arg) - || "markNextChangeSetRanSQL".equalsIgnoreCase(arg); - } - - - - protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { - Properties props = new Properties(); - props.load(propertiesInputStream); - if(props.containsKey("strict")){ - strict = Boolean.valueOf(props.getProperty("strict")); - } - - for (Map.Entry entry : props.entrySet()) { - try { - if (entry.getKey().equals("promptOnNonLocalDatabase")) { - continue; - } - if (((String) entry.getKey()).startsWith("parameter.")) { - changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); - } else { - Field field = getClass().getDeclaredField((String) entry.getKey()); - Object currentValue = field.get(this); - - if (currentValue == null) { - String value = entry.getValue().toString().trim(); - if (field.getType().equals(Boolean.class)) { - field.set(this, Boolean.valueOf(value)); - } else { - field.set(this, value); - } - } - } - } catch (NoSuchFieldException nsfe){ - if(strict){ - throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); - } else { - LogFactory.getInstance().getLog().info("Ignored parameter: " + entry.getKey()); - } - } catch (Exception e) { - throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); - } - } - } - - protected void printHelp(List errorMessages, PrintStream stream) { - stream.println("Errors:"); - for (String message : errorMessages) { - stream.println(" " + message); - } - stream.println(); - printHelp(stream); - } - - protected void printWarning(List warningMessages, PrintStream stream) { - stream.println("Warnings:"); - for (String message : warningMessages) { - stream.println(" " + message); - } - stream.println(); - } - - - protected void printHelp(PrintStream stream) { - stream.println("Usage: java -jar liquibase.jar [options] [command]"); - stream.println(""); - stream.println("Standard Commands:"); - stream.println(" update Updates database to current version"); - stream.println(" updateSQL Writes SQL to update database to current"); - stream.println(" version to STDOUT"); - stream.println(" updateCount Applies next NUM changes to the database"); - stream.println(" updateCountSQL Writes SQL to apply next NUM changes"); - stream.println(" to the database"); - stream.println(" rollback Rolls back the database to the the state is was"); - stream.println(" when the tag was applied"); - stream.println(" rollbackSQL Writes SQL to roll back the database to that"); - stream.println(" state it was in when the tag was applied"); - stream.println(" to STDOUT"); - stream.println(" rollbackToDate Rolls back the database to the the state is was"); - stream.println(" at the given date/time."); - stream.println(" Date Format: yyyy-MM-dd'T'HH:mm:ss"); - stream.println(" rollbackToDateSQL Writes SQL to roll back the database to that"); - stream.println(" state it was in at the given date/time version"); - stream.println(" to STDOUT"); - stream.println(" rollbackCount Rolls back the last change sets"); - stream.println(" applied to the database"); - stream.println(" rollbackCountSQL Writes SQL to roll back the last"); - stream.println(" change sets to STDOUT"); - stream.println(" applied to the database"); - stream.println(" futureRollbackSQL Writes SQL to roll back the database to the "); - stream.println(" current state after the changes in the "); - stream.println(" changeslog have been applied"); - stream.println(" futureRollbackSQL Writes SQL to roll back the database to the "); - stream.println(" current state after changes in the "); - stream.println(" changeslog have been applied"); - stream.println(" updateTestingRollback Updates database, then rolls back changes before"); - stream.println(" updating again. Useful for testing"); - stream.println(" rollback support"); - stream.println(" generateChangeLog Writes Change Log XML to copy the current state"); - stream.println(" of the database to standard out"); - stream.println(" snapshot Writes the current state"); - stream.println(" of the database to standard out"); - stream.println(" snapshotReference Writes the current state"); - stream.println(" of the referenceUrl database to standard out"); - stream.println(""); - stream.println("Diff Commands"); - stream.println(" diff [diff parameters] Writes description of differences"); - stream.println(" to standard out"); - stream.println(" diffChangeLog [diff parameters] Writes Change Log XML to update"); - stream.println(" the database"); - stream.println(" to the reference database to standard out"); - stream.println(""); - stream.println("Documentation Commands"); - stream.println(" dbDoc Generates Javadoc-like documentation"); - stream.println(" based on current database and change log"); - stream.println(""); - stream.println("Maintenance Commands"); - stream.println(" tag 'Tags' the current database state for future rollback"); - stream.println(" status [--verbose] Outputs count (list if --verbose) of unrun changesets"); - stream.println(" unexpectedChangeSets [--verbose]"); - stream.println(" Outputs count (list if --verbose) of changesets run"); - stream.println(" in the database that do not exist in the changelog."); - stream.println(" validate Checks changelog for errors"); - stream.println(" calculateCheckSum Calculates and prints a checksum for the changeset"); - stream.println(" with the given id in the format filepath::id::author."); - stream.println(" clearCheckSums Removes all saved checksums from database log."); - stream.println(" Useful for 'MD5Sum Check Failed' errors"); - stream.println(" changelogSync Mark all changes as executed in the database"); - stream.println(" changelogSyncSQL Writes SQL to mark all changes as executed "); - stream.println(" in the database to STDOUT"); - stream.println(" markNextChangeSetRan Mark the next change changes as executed "); - stream.println(" in the database"); - stream.println(" markNextChangeSetRanSQL Writes SQL to mark the next change "); - stream.println(" as executed in the database to STDOUT"); - stream.println(" listLocks Lists who currently has locks on the"); - stream.println(" database changelog"); - stream.println(" releaseLocks Releases all locks on the database changelog"); - stream.println(" dropAll Drop all database objects owned by user"); - stream.println(""); - stream.println("Required Parameters:"); - stream.println(" --changeLogFile= Migration file"); - stream.println(" --username= Database username"); - stream.println(" --password= Database password. If values"); - stream.println(" is PROMPT, Liquibase will"); - stream.println(" prompt for a password"); - stream.println(" --url= Database URL"); - stream.println(""); - stream.println("Optional Parameters:"); - stream.println(" --classpath= Classpath containing"); - stream.println(" migration files and JDBC Driver"); - stream.println(" --driver= Database driver class name"); - stream.println(" --databaseClass= custom liquibase.database.Database"); - stream.println(" implementation to use"); - stream.println(" --propertyProviderClass= custom Properties"); - stream.println(" implementation to use"); - stream.println(" --defaultSchemaName= Default database schema to use"); - stream.println(" --contexts= ChangeSet contexts to execute"); - stream.println(" --labels= Expression defining labeled"); - stream.println(" ChangeSet to execute"); - stream.println(" --defaultsFile= File with default option values"); - stream.println(" (default: ./liquibase.properties)"); - stream.println(" --driverPropertiesFile= File with custom properties"); - stream.println(" to be set on the JDBC connection"); - stream.println(" to be created"); - stream.println(" --liquibaseCatalogName= The name of the catalog with the"); - stream.println(" liquibase tables"); - stream.println(" --liquibaseSchemaName= The name of the schema with the"); - stream.println(" liquibase tables"); - stream.println(" --includeSystemClasspath= Include the system classpath"); - stream.println(" in the Liquibase classpath"); - stream.println(" (default: true)"); - stream.println(" --promptForNonLocalDatabase= Prompt if non-localhost"); - stream.println(" databases (default: false)"); - stream.println(" --logLevel= Execution log level"); - stream.println(" (debug, info, warning, severe, off"); - stream.println(" --logFile= Log file"); - stream.println(" --currentDateTimeFunction= Overrides current date time function"); - stream.println(" used in SQL."); - stream.println(" Useful for unsupported databases"); - stream.println(" --outputDefaultSchema= If true, SQL object references"); - stream.println(" include the schema name, even if"); - stream.println(" it is the default schema. "); - stream.println(" Defaults to true"); - stream.println(" --outputDefaultCatalog= If true, SQL object references"); - stream.println(" include the catalog name, even if"); - stream.println(" it is the default catalog."); - stream.println(" Defaults to true"); - stream.println(" --outputFile= File to write output to for commands"); - stream.println(" that write output, e.g. updateSQL."); - stream.println(" If not specified, writes to sysout."); - stream.println(" --help Prints this message"); - stream.println(" --version Prints this version information"); - stream.println(""); - stream.println("Required Diff Parameters:"); - stream.println(" --referenceUsername= Reference Database username"); - stream.println(" --referencePassword= Reference Database password. If"); - stream.println(" value is PROMPT, Liquibase will"); - stream.println(" prompt for a password"); - stream.println(" --referenceUrl= Reference Database URL"); - stream.println(""); - stream.println("Optional Diff Parameters:"); - stream.println(" --defaultCatalogName= Default database catalog to use"); - stream.println(" --defaultSchemaName= Default database schema to use"); - stream.println(" --referenceDefaultCatalogName= Reference database catalog to use"); - stream.println(" --referenceDefaultSchemaName= Reference database schema to use"); - stream.println(" --schemas= Database schemas to include"); - stream.println(" objects from in comparison"); - stream.println(" --includeCatalog= If true, the catalog will be"); - stream.println(" included in generated changeSets"); - stream.println(" Defaults to false"); - stream.println(" --includeSchema= If true, the schema will be"); - stream.println(" included in generated changeSets"); - stream.println(" Defaults to false"); - stream.println(" --referenceDriver= Reference database driver class name"); - stream.println(" --dataOutputDirectory=DIR Output data as CSV in the given "); - stream.println(" directory"); - stream.println(" --diffTypes List of diff types to include in"); - stream.println(" Change Log expressed as a comma"); - stream.println(" separated list from: tables, views,"); - stream.println(" columns, indexes, foreignkeys,"); - stream.println(" primarykeys, uniqueconstraints"); - stream.println(" data."); - stream.println(" If this is null then the default"); - stream.println(" types will be: tables, views,"); - stream.println(" columns, indexes, foreignkeys,"); - stream.println(" primarykeys, uniqueconstraints."); - stream.println(""); - stream.println("Change Log Properties:"); - stream.println(" -D= Pass a name/value pair for"); - stream.println(" substitution in the change log(s)"); - stream.println(""); - stream.println("Default value for parameters can be stored in a file called"); - stream.println("'liquibase.properties' that is read from the current working directory."); - stream.println(""); - stream.println("Full documentation is available at"); - stream.println("http://www.liquibase.org/documentation/command_line.html"); - stream.println(""); - } - - public Main() { -// options = createOptions(); - } - - protected void parseOptions(String[] args) throws CommandLineParsingException { - args = fixupArgs(args); - - boolean seenCommand = false; - for (String arg : args) { - if (isCommand(arg)) { - this.command = arg; - if (this.command.equalsIgnoreCase("migrate")) { - this.command = "update"; - } else if (this.command.equalsIgnoreCase("migrateSQL")) { - this.command = "updateSQL"; - } - seenCommand = true; - } else if (seenCommand) { - if (arg.startsWith("-D")) { - String[] splitArg = splitArg(arg); - - String attributeName = splitArg[0].replaceFirst("^-D", ""); - String value = splitArg[1]; - - changeLogParameters.put(attributeName, value); - } else { - commandParams.add(arg); - } - } else if (arg.startsWith("--")) { - String[] splitArg = splitArg(arg); - - String attributeName = splitArg[0]; - String value = splitArg[1]; - - if (StringUtils.trimToEmpty(value).equalsIgnoreCase("PROMPT")) { - Console c = System.console(); - if (c == null) { - throw new CommandLineParsingException("Console unavailable"); - } - //Prompt for value - if (attributeName.toLowerCase().contains("password")) { - value = new String(c.readPassword(attributeName+": ")); - } else { - value = new String(c.readLine(attributeName+": ")); - } - } - - try { - Field field = getClass().getDeclaredField(attributeName); - if (field.getType().equals(Boolean.class)) { - field.set(this, Boolean.valueOf(value)); - } else { - field.set(this, value); - } - } catch (Exception e) { - throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); - } -// } else if(arg.equals("-p")) { -// //Prompt for password -// password = new String(System.console().readPassword("DB Password:")); -// } else if(arg.equals("-rp")) { -// //Prompt for reference password -// referencePassword = new String(System.console().readPassword("Reference DB Password:")); - } else { - throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); - } - } - - } - - private String[] splitArg(String arg) throws CommandLineParsingException { - String[] splitArg = arg.split("=", 2); - if (splitArg.length < 2) { - throw new CommandLineParsingException("Could not parse '" + arg + "'"); - } - - splitArg[0] = splitArg[0].replaceFirst("--", ""); - return splitArg; - } - - protected void applyDefaults() { - if (this.promptForNonLocalDatabase == null) { - this.promptForNonLocalDatabase = Boolean.FALSE; - } - if (this.logLevel == null) { - this.logLevel = "off"; - } - if (this.includeSystemClasspath == null) { - this.includeSystemClasspath = Boolean.TRUE; - } - - if (this.outputDefaultCatalog == null) { - this.outputDefaultCatalog = "true"; - } - if (this.outputDefaultSchema == null) { - this.outputDefaultSchema = "true"; - } - if (this.defaultsFile == null) { - this.defaultsFile = "liquibase.properties"; - } - - - } - - protected void configureClassLoader() throws CommandLineParsingException { - final List urls = new ArrayList(); - if (this.classpath != null) { - String[] classpath; - if (isWindows()) { - classpath = this.classpath.split(";"); - } else { - classpath = this.classpath.split(":"); - } - - for (String classpathEntry : classpath) { - File classPathFile = new File(classpathEntry); - if (!classPathFile.exists()) { - throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist"); - } - try { - if (classpathEntry.endsWith(".war")) { - addWarFileClasspathEntries(classPathFile, urls); - } else if (classpathEntry.endsWith(".ear")) { - JarFile earZip = new JarFile(classPathFile); - - Enumeration entries = earZip.entries(); - while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); - if (entry.getName().toLowerCase().endsWith(".jar")) { - File jar = extract(earZip, entry); - urls.add(new URL("jar:" + jar.toURL() + "!/")); - jar.deleteOnExit(); - } else if (entry.getName().toLowerCase().endsWith("war")) { - File warFile = extract(earZip, entry); - addWarFileClasspathEntries(warFile, urls); - } - } - - } else { - urls.add(new File(classpathEntry).toURL()); - } - } catch (Exception e) { - throw new CommandLineParsingException(e); - } - } - } - if (includeSystemClasspath) { - classLoader = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public URLClassLoader run() { - return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); - } - }); - - } else { - classLoader = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public URLClassLoader run() { - return new URLClassLoader(urls.toArray(new URL[urls.size()])); - } - }); - } - - ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader)); - Thread.currentThread().setContextClassLoader(classLoader); - } - - private void addWarFileClasspathEntries(File classPathFile, List urls) throws IOException { - URL url = new URL("jar:" + classPathFile.toURL() + "!/WEB-INF/classes/"); - urls.add(url); - JarFile warZip = new JarFile(classPathFile); - Enumeration entries = warZip.entries(); - while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); - if (entry.getName().startsWith("WEB-INF/lib") - && entry.getName().toLowerCase().endsWith(".jar")) { - File jar = extract(warZip, entry); - urls.add(new URL("jar:" + jar.toURL() + "!/")); - jar.deleteOnExit(); - } - } - } - - - private File extract(JarFile jar, JarEntry entry) throws IOException { - // expand to temp dir and add to list - File tempFile = File.createTempFile("liquibase.tmp", null); - // read from jar and write to the tempJar file - BufferedInputStream inStream = null; - - BufferedOutputStream outStream = null; - try { - inStream = new BufferedInputStream(jar.getInputStream(entry)); - outStream = new BufferedOutputStream( - new FileOutputStream(tempFile)); - int status; - while ((status = inStream.read()) != -1) { - outStream.write(status); - } - } finally { - if (outStream != null) { - try { - outStream.close(); - } catch (IOException ioe) { - ; - } - } - if (inStream != null) { - try { - inStream.close(); - } catch (IOException ioe) { - ; - } - } - } - - return tempFile; - } - - protected void doMigration() throws Exception { - if ("help".equalsIgnoreCase(command)) { - printHelp(System.err); - return; - } - - try { - if (null != logFile) { - LogFactory.getInstance().getLog().setLogLevel(logLevel, logFile); - } else { - LogFactory.getInstance().getLog().setLogLevel(logLevel); - } - } catch (IllegalArgumentException e) { - throw new CommandLineParsingException(e.getMessage(), e); - } - - FileSystemResourceAccessor fsOpener = new FileSystemResourceAccessor(); - CommandLineResourceAccessor clOpener = new CommandLineResourceAccessor(classLoader); - Database database = CommandLineUtils.createDatabaseObject(classLoader, this.url, - this.username, this.password, this.driver, this.defaultCatalogName,this.defaultSchemaName, Boolean.parseBoolean(outputDefaultCatalog), Boolean.parseBoolean(outputDefaultSchema), this.databaseClass, this.driverPropertiesFile, this.propertyProviderClass, this.liquibaseCatalogName, this.liquibaseSchemaName); - try { - - - CompositeResourceAccessor fileOpener = new CompositeResourceAccessor(fsOpener, clOpener); - - boolean includeCatalog = Boolean.parseBoolean(getCommandParam("includeCatalog", "false")); - boolean includeSchema = Boolean.parseBoolean(getCommandParam("includeSchema", "false")); - boolean includeTablespace = Boolean.parseBoolean(getCommandParam("includeTablespace", "false")); - DiffOutputControl diffOutputControl = new DiffOutputControl(includeCatalog, includeSchema, includeTablespace); - - String referenceSchemaNames = getCommandParam("schemas", null); - CompareControl.SchemaComparison[] finalSchemaComparisons; - CatalogAndSchema[] finalSchemas; - if (referenceSchemaNames == null) { - finalSchemaComparisons = new CompareControl.SchemaComparison[] {new CompareControl.SchemaComparison(new CatalogAndSchema(defaultCatalogName, defaultSchemaName), new CatalogAndSchema(defaultCatalogName, defaultSchemaName))}; - finalSchemas = new CatalogAndSchema[] {new CatalogAndSchema(defaultCatalogName, defaultSchemaName)}; - } else { - List schemaComparisons = new ArrayList(); - List schemas = new ArrayList(); - for (String schema : referenceSchemaNames.split(",")) { - CatalogAndSchema correctedSchema = new CatalogAndSchema(null, schema).customize(database); - schemaComparisons.add(new CompareControl.SchemaComparison(correctedSchema, correctedSchema)); - schemas.add(correctedSchema); - diffOutputControl.addIncludedSchema(correctedSchema); - } - finalSchemaComparisons = schemaComparisons.toArray(new CompareControl.SchemaComparison[schemaComparisons.size()]); - finalSchemas = schemas.toArray(new CatalogAndSchema[schemas.size()]); - } - - for (CompareControl.SchemaComparison schema : finalSchemaComparisons) { - diffOutputControl.addIncludedSchema(schema.getReferenceSchema()); - diffOutputControl.addIncludedSchema(schema.getComparisonSchema()); - } - - if ("diff".equalsIgnoreCase(command)) { - CommandLineUtils.doDiff(createReferenceDatabaseFromCommandParams(commandParams), database, StringUtils.trimToNull(diffTypes), finalSchemaComparisons); - return; - } else if ("diffChangeLog".equalsIgnoreCase(command)) { - CommandLineUtils.doDiffToChangeLog(changeLogFile, createReferenceDatabaseFromCommandParams(commandParams), database, diffOutputControl, StringUtils.trimToNull(diffTypes), finalSchemaComparisons); - return; - } else if ("generateChangeLog".equalsIgnoreCase(command)) { - String changeLogFile = this.changeLogFile; - if (changeLogFile == null) { - changeLogFile = ""; //will output to stdout - } - // By default the generateChangeLog command is destructive, and - // Liquibase's attempt to append doesn't work properly. Just - // fail the build if the file already exists. - File file = new File(changeLogFile); - if ( file.exists() ) { - throw new LiquibaseException("ChangeLogFile " + changeLogFile + " already exists!"); - } - - CommandLineUtils.doGenerateChangeLog(changeLogFile, database, finalSchemas, StringUtils.trimToNull(diffTypes), StringUtils.trimToNull(changeSetAuthor), StringUtils.trimToNull(changeSetContext), StringUtils.trimToNull(dataOutputDirectory), diffOutputControl); - return; - } else if ("snapshot".equalsIgnoreCase(command)) { - SnapshotCommand command = new SnapshotCommand(); - command.setDatabase(database); - command.setSchemas(getCommandParam("schemas", database.getDefaultSchema().getSchemaName())); - System.out.println(command.execute()); - return; - } else if ("executeSql".equalsIgnoreCase(command)) { - ExecuteSqlCommand command = new ExecuteSqlCommand(); - command.setDatabase(database); - command.setSql(getCommandParam("sql", null)); - command.setSqlFile(getCommandParam("sqlFile", null)); - System.out.println(command.execute()); - return; - } else if ("snapshotReference".equalsIgnoreCase(command)) { - SnapshotCommand command = new SnapshotCommand(); - Database referenceDatabase = createReferenceDatabaseFromCommandParams(commandParams); - command.setDatabase(referenceDatabase); - command.setSchemas(getCommandParam("schemas", referenceDatabase.getDefaultSchema().getSchemaName())); - System.out.println(command.execute()); - return; - } - - - Liquibase liquibase = new Liquibase(changeLogFile, fileOpener, database); - liquibase.setCurrentDateTimeFunction(currentDateTimeFunction); - for (Map.Entry entry : changeLogParameters.entrySet()) { - liquibase.setChangeLogParameter(entry.getKey(), entry.getValue()); - } - - if ("listLocks".equalsIgnoreCase(command)) { - liquibase.reportLocks(System.err); - return; - } else if ("releaseLocks".equalsIgnoreCase(command)) { - LockService lockService = LockServiceFactory.getInstance().getLockService(database); - lockService.forceReleaseLock(); - System.err.println("Successfully released all database change log locks for " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()); - return; - } else if ("tag".equalsIgnoreCase(command)) { - liquibase.tag(commandParams.iterator().next()); - System.err.println("Successfully tagged " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()); - return; - } else if ("dropAll".equals(command)) { - liquibase.dropAll(); - System.err.println("All objects dropped from " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()); - return; - } else if ("status".equalsIgnoreCase(command)) { - boolean runVerbose = false; - - if (commandParams.contains("--verbose")) { - runVerbose = true; - } - liquibase.reportStatus(runVerbose, new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - return; - } else if ("unexpectedChangeSets".equalsIgnoreCase(command)) { - boolean runVerbose = false; - - if (commandParams.contains("--verbose")) { - runVerbose = true; - } - liquibase.reportUnexpectedChangeSets(runVerbose, contexts, getOutputWriter()); - return; - } else if ("validate".equalsIgnoreCase(command)) { - try { - liquibase.validate(); - } catch (ValidationFailedException e) { - e.printDescriptiveError(System.err); - return; - } - System.err.println("No validation errors found"); - return; - } else if ("clearCheckSums".equalsIgnoreCase(command)) { - liquibase.clearCheckSums(); - return; - } else if ("calculateCheckSum".equalsIgnoreCase(command)) { - CheckSum checkSum = null; - checkSum = liquibase.calculateCheckSum(commandParams.iterator().next()); - System.out.println(checkSum); - return; - } else if ("dbdoc".equalsIgnoreCase(command)) { - if (commandParams.size() == 0) { - throw new CommandLineParsingException("dbdoc requires an output directory"); - } - if (changeLogFile == null) { - throw new CommandLineParsingException("dbdoc requires a changeLog parameter"); - } - liquibase.generateDocumentation(commandParams.iterator().next(), contexts); - return; - } - - try { - if ("update".equalsIgnoreCase(command)) { - liquibase.update(new Contexts(contexts), new LabelExpression(labels)); - } else if ("changelogSync".equalsIgnoreCase(command)) { - liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels)); - } else if ("changelogSyncSQL".equalsIgnoreCase(command)) { - liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("markNextChangeSetRan".equalsIgnoreCase(command)) { - liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels)); - } else if ("markNextChangeSetRanSQL".equalsIgnoreCase(command)) { - liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("updateCount".equalsIgnoreCase(command)) { - liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels)); - } else if ("updateCountSQL".equalsIgnoreCase(command)) { - liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("updateSQL".equalsIgnoreCase(command)) { - liquibase.update(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("rollback".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollback requires a rollback tag"); - } - liquibase.rollback(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels)); - } else if ("rollbackToDate".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollback requires a rollback date"); - } - liquibase.rollback(new ISODateFormat().parse(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels)); - } else if ("rollbackCount".equalsIgnoreCase(command)) { - liquibase.rollback(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels)); - - } else if ("rollbackSQL".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollbackSQL requires a rollback tag"); - } - liquibase.rollback(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("rollbackToDateSQL".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollbackToDateSQL requires a rollback date"); - } - liquibase.rollback(new ISODateFormat().parse(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("rollbackCountSQL".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollbackCountSQL requires a rollback tag"); - } - - liquibase.rollback(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("futureRollbackSQL".equalsIgnoreCase(command)) { - liquibase.futureRollbackSQL(null, new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("futureRollbackCountSQL".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("futureRollbackCountSQL requires a rollback count"); - } - - liquibase.futureRollbackSQL(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("updateTestingRollback".equalsIgnoreCase(command)) { - liquibase.updateTestingRollback(new Contexts(contexts), new LabelExpression(labels)); - } else { - throw new CommandLineParsingException("Unknown command: " + command); - } - } catch (ParseException e) { - throw new CommandLineParsingException("Unexpected date/time format. Use 'yyyy-MM-dd'T'HH:mm:ss'"); - } - } finally { - try { - database.rollback(); - database.close(); - } catch (DatabaseException e) { - LogFactory.getInstance().getLog().warning("problem closing connection", e); - } - } - } - - private String getCommandParam(String paramName, String defaultValue) throws CommandLineParsingException { - for (String param : commandParams) { - if (!param.contains("=")) { - return null; - } - String[] splitArg = splitArg(param); - - String attributeName = splitArg[0]; - String value = splitArg[1]; - if (attributeName.equalsIgnoreCase(paramName)) { - return value; - } - } - - return defaultValue; - } - - private Database createReferenceDatabaseFromCommandParams(Set commandParams) throws CommandLineParsingException, DatabaseException { - String driver = referenceDriver; - String url = referenceUrl; - String username = referenceUsername; - String password = referencePassword; - String defaultSchemaName = this.defaultSchemaName; - String defaultCatalogName = this.defaultCatalogName; - - for (String param : commandParams) { - String[] splitArg = splitArg(param); - - String attributeName = splitArg[0]; - String value = splitArg[1]; - if ("referenceDriver".equalsIgnoreCase(attributeName)) { - driver = value; - } else if ("referenceUrl".equalsIgnoreCase(attributeName)) { - url = value; - } else if ("referenceUsername".equalsIgnoreCase(attributeName)) { - username = value; - } else if ("referencePassword".equalsIgnoreCase(attributeName)) { - password = value; - } else if ("referenceDefaultCatalogName".equalsIgnoreCase(attributeName)) { - defaultCatalogName = value; - } else if ("referenceDefaultSchemaName".equalsIgnoreCase(attributeName)) { - defaultSchemaName = value; - } else if ("dataOutputDirectory".equalsIgnoreCase(attributeName)) { - dataOutputDirectory = value; - } - } - -// if (driver == null) { -// driver = DatabaseFactory.getWriteExecutor().findDefaultDriver(url); -// } - - if (url == null) { - throw new CommandLineParsingException("referenceUrl parameter missing"); - } - - return CommandLineUtils.createDatabaseObject(classLoader, url, username, password, driver, defaultCatalogName, defaultSchemaName, Boolean.parseBoolean(outputDefaultCatalog), Boolean.parseBoolean(outputDefaultSchema), null, null, this.propertyProviderClass, this.liquibaseCatalogName, this.liquibaseSchemaName); -// Driver driverObject; -// try { -// driverObject = (Driver) Class.forName(driver, true, classLoader).newInstance(); -// } catch (Exception e) { -// throw new RuntimeException("Cannot find database driver: " + e.getMessage()); -// } -// -// Properties info = new Properties(); -// info.put("user", username); -// info.put("password", password); -// -// Connection connection; -// try { -// connection = driverObject.connect(url, info); -// } catch (SQLException e) { -// throw new DatabaseException("Connection could not be created to " + url + ": " + e.getMessage(), e); -// } -// if (connection == null) { -// throw new DatabaseException("Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL"); -// } -// -// Database database = DatabaseFactory.getWriteExecutor().findCorrectDatabaseImplementation(connection); -// database.setDefaultSchemaName(defaultSchemaName); -// -// return database; - } - - private Writer getOutputWriter() throws UnsupportedEncodingException, IOException { - String charsetName = LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding(); - - if (outputFile != null) { - try { - FileOutputStream fileOut = new FileOutputStream(outputFile, false); - return new OutputStreamWriter(fileOut, charsetName); - } catch (IOException e) { - System.err.printf("Could not create output file %s\n", outputFile); - throw e; - } - } else { - return new OutputStreamWriter(System.out, charsetName); - } - } - - public boolean isWindows() { - return System.getProperty("os.name").startsWith("Windows "); - } -} diff --git a/All/Genesis-NP/Genesis#286/old/Main.java b/All/Genesis-NP/Genesis#286/old/Main.java deleted file mode 100755 index 4dba659..0000000 --- a/All/Genesis-NP/Genesis#286/old/Main.java +++ /dev/null @@ -1,1204 +0,0 @@ -package liquibase.integration.commandline; - -import liquibase.CatalogAndSchema; -import liquibase.Contexts; -import liquibase.LabelExpression; -import liquibase.Liquibase; -import liquibase.change.CheckSum; -import liquibase.command.ExecuteSqlCommand; -import liquibase.command.SnapshotCommand; -import liquibase.configuration.LiquibaseConfiguration; -import liquibase.configuration.GlobalConfiguration; -import liquibase.database.Database; -import liquibase.diff.compare.CompareControl; -import liquibase.diff.output.DiffOutputControl; -import liquibase.exception.CommandLineParsingException; -import liquibase.exception.DatabaseException; -import liquibase.exception.LiquibaseException; -import liquibase.exception.ValidationFailedException; -import liquibase.lockservice.LockService; -import liquibase.lockservice.LockServiceFactory; -import liquibase.logging.LogFactory; -import liquibase.logging.LogLevel; -import liquibase.logging.Logger; -import liquibase.resource.ClassLoaderResourceAccessor; -import liquibase.resource.CompositeResourceAccessor; -import liquibase.resource.FileSystemResourceAccessor; -import liquibase.servicelocator.ServiceLocator; -import liquibase.util.ISODateFormat; -import liquibase.util.LiquibaseUtil; -import liquibase.util.StreamUtil; -import liquibase.util.StringUtils; - -import java.io.*; -import java.lang.reflect.Field; -import java.net.URL; -import java.net.URLClassLoader; -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.text.ParseException; -import java.util.*; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -/** - * Class for executing Liquibase via the command line. - */ -public class Main { - protected ClassLoader classLoader; - - protected String driver; - protected String username; - protected String password; - protected String url; - protected String databaseClass; - protected String defaultSchemaName; - protected String outputDefaultSchema; - protected String outputDefaultCatalog; - protected String liquibaseCatalogName; - protected String liquibaseSchemaName; - protected String defaultCatalogName; - protected String changeLogFile; - protected String classpath; - protected String contexts; - protected String labels; - protected String driverPropertiesFile; - protected String propertyProviderClass = null; - protected Boolean promptForNonLocalDatabase = null; - protected Boolean includeSystemClasspath; - protected Boolean strict = Boolean.TRUE; - protected String defaultsFile; - - protected String diffTypes; - protected String changeSetAuthor; - protected String changeSetContext; - protected String dataOutputDirectory; - - protected String referenceDriver; - protected String referenceUrl; - protected String referenceUsername; - protected String referencePassword; - - protected String currentDateTimeFunction; - - protected String command; - protected Set commandParams = new LinkedHashSet(); - - protected String logLevel; - protected String logFile; - - protected Map changeLogParameters = new HashMap(); - - protected String outputFile; - - public static void main(String args[]) throws CommandLineParsingException, IOException { - try { - run(args); - } catch (LiquibaseException e) { - System.exit(-1); - } - System.exit(0); - } - - public static void run(String args[]) throws CommandLineParsingException, IOException, LiquibaseException { - try { - GlobalConfiguration globalConfiguration = LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class); - - if (!globalConfiguration.getShouldRun()) { - System.err.println("Liquibase did not run because '" + LiquibaseConfiguration.getInstance().describeValueLookupLogic(globalConfiguration.getProperty(GlobalConfiguration.SHOULD_RUN)) + " was set to false"); - return; - } - -// if (!System.getProperties().contains("file.encoding")) { -// System.setProperty("file.encoding", "UTF-8"); -// } - - Main main = new Main(); - if (args.length == 1 && "--help".equals(args[0])) { - main.printHelp(System.err); - return; - } else if (args.length == 1 && "--version".equals(args[0])) { - System.err.println("Liquibase Version: " + LiquibaseUtil.getBuildVersion() + StreamUtil.getLineSeparator()); - return; - } - - try { - main.parseOptions(args); - } catch (CommandLineParsingException e) { - // Print the help before throwing the exception - main.printHelp(Arrays.asList(e.getMessage()), System.err); - throw e; - } - - File propertiesFile = new File(main.defaultsFile); - String localDefaultsPathName = main.defaultsFile.replaceFirst("(\\.[^\\.]+)$", ".local$1"); - File localPropertiesFile = new File(localDefaultsPathName); - - if (localPropertiesFile.exists()) { - FileInputStream stream = new FileInputStream(localPropertiesFile); - try { - main.parsePropertiesFile(stream); - } finally { - stream.close(); - } - } else { - InputStream resourceAsStream = main.getClass().getClassLoader().getResourceAsStream(localDefaultsPathName); - if (resourceAsStream != null) { - try { - main.parsePropertiesFile(resourceAsStream); - } finally { - resourceAsStream.close(); - } - } - } - if (propertiesFile.exists()) { - FileInputStream stream = new FileInputStream(propertiesFile); - main.parsePropertiesFile(stream); - } else { - InputStream resourceAsStream = main.getClass().getClassLoader().getResourceAsStream(main.defaultsFile); - if (resourceAsStream != null) { - try { - main.parsePropertiesFile(resourceAsStream); - } finally { - resourceAsStream.close(); - } - } - - } - - List setupMessages = main.checkSetup(); - if (setupMessages.size() > 0) { - main.printHelp(setupMessages, System.err); - return; - } - - main.applyDefaults(); - main.configureClassLoader(); - main.doMigration(); - - if ("update".equals(main.command)) { - System.err.println("Liquibase Update Successful"); - } else if (main.command.startsWith("rollback") && !main.command.endsWith("SQL")) { - System.err.println("Liquibase Rollback Successful"); - } else if (!main.command.endsWith("SQL")) { - System.err.println("Liquibase '"+main.command+"' Successful"); - } - } catch (Throwable e) { - String message = e.getMessage(); - if ( e.getCause() != null ) { - message = e.getCause().getMessage(); - } - if ( message == null ) { - message = "Unknown Reason"; - } - // At a minimum, log the message. We don't need to print the stack - // trace because the logger already did that upstream. - try { - if ( e.getCause() instanceof ValidationFailedException ) { - ((ValidationFailedException)e.getCause()).printDescriptiveError(System.out); - } else { - System.err.println("Unexpected error running Liquibase: " + message + "\n"); - LogFactory.getInstance().getLog().severe(message, e); - System.err.println(generateLogLevelWarningMessage()); - } - } catch (Exception e1) { - e.printStackTrace(); - } - throw new LiquibaseException("Unexpected error running Liquibase: " + message, e); - } - } - - private static String generateLogLevelWarningMessage() { - Logger logger = LogFactory.getInstance().getLog(); - if (logger != null && logger.getLogLevel() != null && (logger.getLogLevel().equals(LogLevel.OFF))) { - return ""; - } else { - return "\n\nFor more information, use the --logLevel flag"; - } - } - - /** - * On windows machines, it splits args on '=' signs. Put it back like it was. - */ - protected String[] fixupArgs(String[] args) { - List fixedArgs = new ArrayList(); - - for (int i = 0; i < args.length; i++) { - String arg = args[i]; - if ((arg.startsWith("--") || arg.startsWith("-D")) && !arg.contains("=")) { - String nextArg = null; - if (i + 1 < args.length) { - nextArg = args[i + 1]; - } - if (nextArg != null && !nextArg.startsWith("--") && !isCommand(nextArg)) { - arg = arg + "=" + nextArg; - i++; - } - } - fixedArgs.add(arg); - } - - return fixedArgs.toArray(new String[fixedArgs.size()]); - } - - protected List checkSetup() { - List messages = new ArrayList(); - if (command == null) { - messages.add("Command not passed"); - } else if (!isCommand(command)) { - messages.add("Unknown command: " + command); - } else { - if (url == null) { - messages.add("--url is required"); - } - - if (isChangeLogRequired(command) && changeLogFile == null) { - messages.add("--changeLogFile is required"); - } - - if (isNoArgCommand(command) && !commandParams.isEmpty()) { - messages.add("unexpected command parameters: "+commandParams); - } else { - validateCommandParameters(messages); - } - } - return messages; - } - - private void checkForUnexpectedCommandParameter(List messages) { - if ("updateCount".equalsIgnoreCase(command) - || "updateCountSQL".equalsIgnoreCase(command) - || "rollback".equalsIgnoreCase(command) - || "rollbackToDate".equalsIgnoreCase(command) - || "rollbackCount".equalsIgnoreCase(command) - || "rollbackSQL".equalsIgnoreCase(command) - || "rollbackToDateSQL".equalsIgnoreCase(command) - || "rollbackCountSQL".equalsIgnoreCase(command) - || "calculateCheckSum".equalsIgnoreCase(command) - || "dbDoc".equalsIgnoreCase(command) - || "tag".equalsIgnoreCase(command)) { - - if (commandParams.size() > 0 && commandParams.iterator().next().startsWith("-")) { - messages.add("unexpected command parameters: "+commandParams); - } - } else if ("status".equalsIgnoreCase(command) - || "unexpectedChangeSets".equalsIgnoreCase(command)) { - if (commandParams.size() > 0 && !commandParams.iterator().next().equalsIgnoreCase("--verbose")) { - messages.add("unexpected command parameters: "+commandParams); - } - } else if ("diff".equalsIgnoreCase(command) - || "diffChangeLog".equalsIgnoreCase(command)) { - if (commandParams.size() > 0) { - for (String cmdParm : commandParams) { - if (!cmdParm.startsWith("--referenceUsername") - && !cmdParm.startsWith("--referencePassword") - && !cmdParm.startsWith("--referenceDriver") - && !cmdParm.startsWith("--referenceDefaultCatalogName") - && !cmdParm.startsWith("--referenceDefaultSchemaName") - && !cmdParm.startsWith("--includeSchema") - && !cmdParm.startsWith("--includeCatalog") - && !cmdParm.startsWith("--includeTablespace") - && !cmdParm.startsWith("--schemas") - && !cmdParm.startsWith("--referenceUrl") - && !cmdParm.startsWith("--diffTypes")) { - messages.add("unexpected command parameter: "+cmdParm); - } - } - } - } - - } - - private void validateCommandParameters(final List messages) { - checkForUnexpectedCommandParameter(messages); - checkForMissingCommandParameters(messages); - checkForMalformedCommandParameters(messages); - } - - private void checkForMissingCommandParameters(final List messages) { - if (commandParams.isEmpty() || commandParams.iterator().next().startsWith("-")) { - if ("calculateCheckSum".equalsIgnoreCase(command)) { - messages.add("missing changeSet identifier"); - } - } - } - - private void checkForMalformedCommandParameters(final List messages) { - if (!commandParams.isEmpty()) { - if ("calculateCheckSum".equalsIgnoreCase(command)) { - for (final String param : commandParams) { - assert param != null; - if (param != null && !param.startsWith("-")) { - final String[] parts = param.split("::"); - if (parts == null || parts.length < 3) { - messages.add("changeSet identifier must be of the form filepath::id::author"); - break; - } - } - } - } - } - } - - private boolean isChangeLogRequired(String command) { - return command.toLowerCase().startsWith("update") - || command.toLowerCase().startsWith("rollback") - || "calculateCheckSum".equalsIgnoreCase(command) - || "status".equalsIgnoreCase(command) - || "validate".equalsIgnoreCase(command) - || "changeLogSync".equalsIgnoreCase(command) - || "changeLogSyncSql".equalsIgnoreCase(command) - || "generateChangeLog".equalsIgnoreCase(command); - } - - private boolean isCommand(String arg) { - return "migrate".equals(arg) - || "migrateSQL".equalsIgnoreCase(arg) - || "update".equalsIgnoreCase(arg) - || "updateSQL".equalsIgnoreCase(arg) - || "updateCount".equalsIgnoreCase(arg) - || "updateCountSQL".equalsIgnoreCase(arg) - || "rollback".equalsIgnoreCase(arg) - || "rollbackToDate".equalsIgnoreCase(arg) - || "rollbackCount".equalsIgnoreCase(arg) - || "rollbackSQL".equalsIgnoreCase(arg) - || "rollbackToDateSQL".equalsIgnoreCase(arg) - || "rollbackCountSQL".equalsIgnoreCase(arg) - || "futureRollbackSQL".equalsIgnoreCase(arg) - || "futureRollbackCountSQL".equalsIgnoreCase(arg) - || "updateTestingRollback".equalsIgnoreCase(arg) - || "tag".equalsIgnoreCase(arg) - || "listLocks".equalsIgnoreCase(arg) - || "dropAll".equalsIgnoreCase(arg) - || "releaseLocks".equalsIgnoreCase(arg) - || "status".equalsIgnoreCase(arg) - || "unexpectedChangeSets".equalsIgnoreCase(arg) - || "validate".equalsIgnoreCase(arg) - || "help".equalsIgnoreCase(arg) - || "diff".equalsIgnoreCase(arg) - || "diffChangeLog".equalsIgnoreCase(arg) - || "generateChangeLog".equalsIgnoreCase(arg) - || "snapshot".equalsIgnoreCase(arg) - || "snapshotReference".equalsIgnoreCase(arg) - || "executeSql".equalsIgnoreCase(arg) - || "calculateCheckSum".equalsIgnoreCase(arg) - || "clearCheckSums".equalsIgnoreCase(arg) - || "dbDoc".equalsIgnoreCase(arg) - || "changelogSync".equalsIgnoreCase(arg) - || "changelogSyncSQL".equalsIgnoreCase(arg) - || "markNextChangeSetRan".equalsIgnoreCase(arg) - || "markNextChangeSetRanSQL".equalsIgnoreCase(arg); - } - - private boolean isNoArgCommand(String arg) { - return "migrate".equals(arg) - || "migrateSQL".equalsIgnoreCase(arg) - || "update".equalsIgnoreCase(arg) - || "updateSQL".equalsIgnoreCase(arg) - || "futureRollbackSQL".equalsIgnoreCase(arg) - || "updateTestingRollback".equalsIgnoreCase(arg) - || "listLocks".equalsIgnoreCase(arg) - || "dropAll".equalsIgnoreCase(arg) - || "releaseLocks".equalsIgnoreCase(arg) - || "validate".equalsIgnoreCase(arg) - || "help".equalsIgnoreCase(arg) - || "clearCheckSums".equalsIgnoreCase(arg) - || "changelogSync".equalsIgnoreCase(arg) - || "changelogSyncSQL".equalsIgnoreCase(arg) - || "markNextChangeSetRan".equalsIgnoreCase(arg) - || "markNextChangeSetRanSQL".equalsIgnoreCase(arg); - } - - - - protected void parsePropertiesFile(InputStream propertiesInputStream) throws IOException, CommandLineParsingException { - Properties props = new Properties(); - props.load(propertiesInputStream); - if(props.containsKey("strict")){ - strict = Boolean.valueOf(props.getProperty("strict")); - } - - for (Map.Entry entry : props.entrySet()) { - try { - if (entry.getKey().equals("promptOnNonLocalDatabase")) { - continue; - } - if (((String) entry.getKey()).startsWith("parameter.")) { - changeLogParameters.put(((String) entry.getKey()).replaceFirst("^parameter.", ""), entry.getValue()); - } else { - Field field = getClass().getDeclaredField((String) entry.getKey()); - Object currentValue = field.get(this); - - if (currentValue == null) { - String value = entry.getValue().toString().trim(); - if (field.getType().equals(Boolean.class)) { - field.set(this, Boolean.valueOf(value)); - } else { - field.set(this, value); - } - } - } - } catch (NoSuchFieldException nsfe){ - if(strict){ - throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); - } else { - LogFactory.getInstance().getLog().info("Ignored parameter: " + entry.getKey()); - } - } catch (Exception e) { - throw new CommandLineParsingException("Unknown parameter: '" + entry.getKey() + "'"); - } - } - } - - protected void printHelp(List errorMessages, PrintStream stream) { - stream.println("Errors:"); - for (String message : errorMessages) { - stream.println(" " + message); - } - stream.println(); - printHelp(stream); - } - - protected void printWarning(List warningMessages, PrintStream stream) { - stream.println("Warnings:"); - for (String message : warningMessages) { - stream.println(" " + message); - } - stream.println(); - } - - - protected void printHelp(PrintStream stream) { - stream.println("Usage: java -jar liquibase.jar [options] [command]"); - stream.println(""); - stream.println("Standard Commands:"); - stream.println(" update Updates database to current version"); - stream.println(" updateSQL Writes SQL to update database to current"); - stream.println(" version to STDOUT"); - stream.println(" updateCount Applies next NUM changes to the database"); - stream.println(" updateCountSQL Writes SQL to apply next NUM changes"); - stream.println(" to the database"); - stream.println(" rollback Rolls back the database to the the state is was"); - stream.println(" when the tag was applied"); - stream.println(" rollbackSQL Writes SQL to roll back the database to that"); - stream.println(" state it was in when the tag was applied"); - stream.println(" to STDOUT"); - stream.println(" rollbackToDate Rolls back the database to the the state is was"); - stream.println(" at the given date/time."); - stream.println(" Date Format: yyyy-MM-dd'T'HH:mm:ss"); - stream.println(" rollbackToDateSQL Writes SQL to roll back the database to that"); - stream.println(" state it was in at the given date/time version"); - stream.println(" to STDOUT"); - stream.println(" rollbackCount Rolls back the last change sets"); - stream.println(" applied to the database"); - stream.println(" rollbackCountSQL Writes SQL to roll back the last"); - stream.println(" change sets to STDOUT"); - stream.println(" applied to the database"); - stream.println(" futureRollbackSQL Writes SQL to roll back the database to the "); - stream.println(" current state after the changes in the "); - stream.println(" changeslog have been applied"); - stream.println(" futureRollbackSQL Writes SQL to roll back the database to the "); - stream.println(" current state after changes in the "); - stream.println(" changeslog have been applied"); - stream.println(" updateTestingRollback Updates database, then rolls back changes before"); - stream.println(" updating again. Useful for testing"); - stream.println(" rollback support"); - stream.println(" generateChangeLog Writes Change Log XML to copy the current state"); - stream.println(" of the database to standard out"); - stream.println(" snapshot Writes the current state"); - stream.println(" of the database to standard out"); - stream.println(" snapshotReference Writes the current state"); - stream.println(" of the referenceUrl database to standard out"); - stream.println(""); - stream.println("Diff Commands"); - stream.println(" diff [diff parameters] Writes description of differences"); - stream.println(" to standard out"); - stream.println(" diffChangeLog [diff parameters] Writes Change Log XML to update"); - stream.println(" the database"); - stream.println(" to the reference database to standard out"); - stream.println(""); - stream.println("Documentation Commands"); - stream.println(" dbDoc Generates Javadoc-like documentation"); - stream.println(" based on current database and change log"); - stream.println(""); - stream.println("Maintenance Commands"); - stream.println(" tag 'Tags' the current database state for future rollback"); - stream.println(" status [--verbose] Outputs count (list if --verbose) of unrun changesets"); - stream.println(" unexpectedChangeSets [--verbose]"); - stream.println(" Outputs count (list if --verbose) of changesets run"); - stream.println(" in the database that do not exist in the changelog."); - stream.println(" validate Checks changelog for errors"); - stream.println(" calculateCheckSum Calculates and prints a checksum for the changeset"); - stream.println(" with the given id in the format filepath::id::author."); - stream.println(" clearCheckSums Removes all saved checksums from database log."); - stream.println(" Useful for 'MD5Sum Check Failed' errors"); - stream.println(" changelogSync Mark all changes as executed in the database"); - stream.println(" changelogSyncSQL Writes SQL to mark all changes as executed "); - stream.println(" in the database to STDOUT"); - stream.println(" markNextChangeSetRan Mark the next change changes as executed "); - stream.println(" in the database"); - stream.println(" markNextChangeSetRanSQL Writes SQL to mark the next change "); - stream.println(" as executed in the database to STDOUT"); - stream.println(" listLocks Lists who currently has locks on the"); - stream.println(" database changelog"); - stream.println(" releaseLocks Releases all locks on the database changelog"); - stream.println(" dropAll Drop all database objects owned by user"); - stream.println(""); - stream.println("Required Parameters:"); - stream.println(" --changeLogFile= Migration file"); - stream.println(" --username= Database username"); - stream.println(" --password= Database password. If values"); - stream.println(" is PROMPT, Liquibase will"); - stream.println(" prompt for a password"); - stream.println(" --url= Database URL"); - stream.println(""); - stream.println("Optional Parameters:"); - stream.println(" --classpath= Classpath containing"); - stream.println(" migration files and JDBC Driver"); - stream.println(" --driver= Database driver class name"); - stream.println(" --databaseClass= custom liquibase.database.Database"); - stream.println(" implementation to use"); - stream.println(" --propertyProviderClass= custom Properties"); - stream.println(" implementation to use"); - stream.println(" --defaultSchemaName= Default database schema to use"); - stream.println(" --contexts= ChangeSet contexts to execute"); - stream.println(" --labels= Expression defining labeled"); - stream.println(" ChangeSet to execute"); - stream.println(" --defaultsFile= File with default option values"); - stream.println(" (default: ./liquibase.properties)"); - stream.println(" --driverPropertiesFile= File with custom properties"); - stream.println(" to be set on the JDBC connection"); - stream.println(" to be created"); - stream.println(" --liquibaseCatalogName= The name of the catalog with the"); - stream.println(" liquibase tables"); - stream.println(" --liquibaseSchemaName= The name of the schema with the"); - stream.println(" liquibase tables"); - stream.println(" --includeSystemClasspath= Include the system classpath"); - stream.println(" in the Liquibase classpath"); - stream.println(" (default: true)"); - stream.println(" --promptForNonLocalDatabase= Prompt if non-localhost"); - stream.println(" databases (default: false)"); - stream.println(" --logLevel= Execution log level"); - stream.println(" (debug, info, warning, severe, off"); - stream.println(" --logFile= Log file"); - stream.println(" --currentDateTimeFunction= Overrides current date time function"); - stream.println(" used in SQL."); - stream.println(" Useful for unsupported databases"); - stream.println(" --outputDefaultSchema= If true, SQL object references"); - stream.println(" include the schema name, even if"); - stream.println(" it is the default schema. "); - stream.println(" Defaults to true"); - stream.println(" --outputDefaultCatalog= If true, SQL object references"); - stream.println(" include the catalog name, even if"); - stream.println(" it is the default catalog."); - stream.println(" Defaults to true"); - stream.println(" --outputFile= File to write output to for commands"); - stream.println(" that write output, e.g. updateSQL."); - stream.println(" If not specified, writes to sysout."); - stream.println(" --help Prints this message"); - stream.println(" --version Prints this version information"); - stream.println(""); - stream.println("Required Diff Parameters:"); - stream.println(" --referenceUsername= Reference Database username"); - stream.println(" --referencePassword= Reference Database password. If"); - stream.println(" value is PROMPT, Liquibase will"); - stream.println(" prompt for a password"); - stream.println(" --referenceUrl= Reference Database URL"); - stream.println(""); - stream.println("Optional Diff Parameters:"); - stream.println(" --defaultCatalogName= Default database catalog to use"); - stream.println(" --defaultSchemaName= Default database schema to use"); - stream.println(" --referenceDefaultCatalogName= Reference database catalog to use"); - stream.println(" --referenceDefaultSchemaName= Reference database schema to use"); - stream.println(" --schemas= Database schemas to include"); - stream.println(" objects from in comparison"); - stream.println(" --includeCatalog= If true, the catalog will be"); - stream.println(" included in generated changeSets"); - stream.println(" Defaults to false"); - stream.println(" --includeSchema= If true, the schema will be"); - stream.println(" included in generated changeSets"); - stream.println(" Defaults to false"); - stream.println(" --referenceDriver= Reference database driver class name"); - stream.println(" --dataOutputDirectory=DIR Output data as CSV in the given "); - stream.println(" directory"); - stream.println(" --diffTypes List of diff types to include in"); - stream.println(" Change Log expressed as a comma"); - stream.println(" separated list from: tables, views,"); - stream.println(" columns, indexes, foreignkeys,"); - stream.println(" primarykeys, uniqueconstraints"); - stream.println(" data."); - stream.println(" If this is null then the default"); - stream.println(" types will be: tables, views,"); - stream.println(" columns, indexes, foreignkeys,"); - stream.println(" primarykeys, uniqueconstraints."); - stream.println(""); - stream.println("Change Log Properties:"); - stream.println(" -D= Pass a name/value pair for"); - stream.println(" substitution in the change log(s)"); - stream.println(""); - stream.println("Default value for parameters can be stored in a file called"); - stream.println("'liquibase.properties' that is read from the current working directory."); - stream.println(""); - stream.println("Full documentation is available at"); - stream.println("http://www.liquibase.org/documentation/command_line.html"); - stream.println(""); - } - - public Main() { -// options = createOptions(); - } - - protected void parseOptions(String[] args) throws CommandLineParsingException { - args = fixupArgs(args); - - boolean seenCommand = false; - for (String arg : args) { - if (isCommand(arg)) { - this.command = arg; - if (this.command.equalsIgnoreCase("migrate")) { - this.command = "update"; - } else if (this.command.equalsIgnoreCase("migrateSQL")) { - this.command = "updateSQL"; - } - seenCommand = true; - } else if (seenCommand) { - if (arg.startsWith("-D")) { - String[] splitArg = splitArg(arg); - - String attributeName = splitArg[0].replaceFirst("^-D", ""); - String value = splitArg[1]; - - changeLogParameters.put(attributeName, value); - } else { - commandParams.add(arg); - } - } else if (arg.startsWith("--")) { - String[] splitArg = splitArg(arg); - - String attributeName = splitArg[0]; - String value = splitArg[1]; - - if (StringUtils.trimToEmpty(value).equalsIgnoreCase("PROMPT")) { - Console c = System.console(); - if (c == null) { - throw new CommandLineParsingException("Console unavailable"); - } - //Prompt for value - if (attributeName.toLowerCase().contains("password")) { - value = new String(c.readPassword(attributeName+": ")); - } else { - value = new String(c.readLine(attributeName+": ")); - } - } - - try { - Field field = getClass().getDeclaredField(attributeName); - if (field.getType().equals(Boolean.class)) { - field.set(this, Boolean.valueOf(value)); - } else { - field.set(this, value); - } - } catch (Exception e) { - throw new CommandLineParsingException("Unknown parameter: '" + attributeName + "'"); - } -// } else if(arg.equals("-p")) { -// //Prompt for password -// password = new String(System.console().readPassword("DB Password:")); -// } else if(arg.equals("-rp")) { -// //Prompt for reference password -// referencePassword = new String(System.console().readPassword("Reference DB Password:")); - } else { - throw new CommandLineParsingException("Unexpected value " + arg + ": parameters must start with a '--'"); - } - } - - } - - private String[] splitArg(String arg) throws CommandLineParsingException { - String[] splitArg = arg.split("=", 2); - if (splitArg.length < 2) { - throw new CommandLineParsingException("Could not parse '" + arg + "'"); - } - - splitArg[0] = splitArg[0].replaceFirst("--", ""); - return splitArg; - } - - protected void applyDefaults() { - if (this.promptForNonLocalDatabase == null) { - this.promptForNonLocalDatabase = Boolean.FALSE; - } - if (this.logLevel == null) { - this.logLevel = "off"; - } - if (this.includeSystemClasspath == null) { - this.includeSystemClasspath = Boolean.TRUE; - } - - if (this.outputDefaultCatalog == null) { - this.outputDefaultCatalog = "true"; - } - if (this.outputDefaultSchema == null) { - this.outputDefaultSchema = "true"; - } - if (this.defaultsFile == null) { - this.defaultsFile = "liquibase.properties"; - } - - - } - - protected void configureClassLoader() throws CommandLineParsingException { - final List urls = new ArrayList(); - if (this.classpath != null) { - String[] classpath; - if (isWindows()) { - classpath = this.classpath.split(";"); - } else { - classpath = this.classpath.split(":"); - } - - for (String classpathEntry : classpath) { - File classPathFile = new File(classpathEntry); - if (!classPathFile.exists()) { - throw new CommandLineParsingException(classPathFile.getAbsolutePath() + " does not exist"); - } - try { - if (classpathEntry.endsWith(".war")) { - addWarFileClasspathEntries(classPathFile, urls); - } else if (classpathEntry.endsWith(".ear")) { - JarFile earZip = new JarFile(classPathFile); - - Enumeration entries = earZip.entries(); - while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); - if (entry.getName().toLowerCase().endsWith(".jar")) { - File jar = extract(earZip, entry); - urls.add(new URL("jar:" + jar.toURL() + "!/")); - jar.deleteOnExit(); - } else if (entry.getName().toLowerCase().endsWith("war")) { - File warFile = extract(earZip, entry); - addWarFileClasspathEntries(warFile, urls); - } - } - - } else { - urls.add(new File(classpathEntry).toURL()); - } - } catch (Exception e) { - throw new CommandLineParsingException(e); - } - } - } - if (includeSystemClasspath) { - classLoader = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public URLClassLoader run() { - return new URLClassLoader(urls.toArray(new URL[urls.size()]), Thread.currentThread().getContextClassLoader()); - } - }); - - } else { - classLoader = AccessController.doPrivileged(new PrivilegedAction() { - @Override - public URLClassLoader run() { - return new URLClassLoader(urls.toArray(new URL[urls.size()])); - } - }); - } - - ServiceLocator.getInstance().setResourceAccessor(new ClassLoaderResourceAccessor(classLoader)); - Thread.currentThread().setContextClassLoader(classLoader); - } - - private void addWarFileClasspathEntries(File classPathFile, List urls) throws IOException { - URL url = new URL("jar:" + classPathFile.toURL() + "!/WEB-INF/classes/"); - urls.add(url); - JarFile warZip = new JarFile(classPathFile); - Enumeration entries = warZip.entries(); - while (entries.hasMoreElements()) { - JarEntry entry = entries.nextElement(); - if (entry.getName().startsWith("WEB-INF/lib") - && entry.getName().toLowerCase().endsWith(".jar")) { - File jar = extract(warZip, entry); - urls.add(new URL("jar:" + jar.toURL() + "!/")); - jar.deleteOnExit(); - } - } - } - - - private File extract(JarFile jar, JarEntry entry) throws IOException { - // expand to temp dir and add to list - File tempFile = File.createTempFile("liquibase.tmp", null); - // read from jar and write to the tempJar file - BufferedInputStream inStream = null; - - BufferedOutputStream outStream = null; - try { - inStream = new BufferedInputStream(jar.getInputStream(entry)); - outStream = new BufferedOutputStream( - new FileOutputStream(tempFile)); - int status; - while ((status = inStream.read()) != -1) { - outStream.write(status); - } - } finally { - if (outStream != null) { - try { - outStream.close(); - } catch (IOException ioe) { - ; - } - } - if (inStream != null) { - try { - inStream.close(); - } catch (IOException ioe) { - ; - } - } - } - - return tempFile; - } - - protected void doMigration() throws Exception { - if ("help".equalsIgnoreCase(command)) { - printHelp(System.err); - return; - } - - try { - if (null != logFile) { - LogFactory.getInstance().getLog().setLogLevel(logLevel, logFile); - } else { - LogFactory.getInstance().getLog().setLogLevel(logLevel); - } - } catch (IllegalArgumentException e) { - throw new CommandLineParsingException(e.getMessage(), e); - } - - FileSystemResourceAccessor fsOpener = new FileSystemResourceAccessor(); - CommandLineResourceAccessor clOpener = new CommandLineResourceAccessor(classLoader); - Database database = CommandLineUtils.createDatabaseObject(classLoader, this.url, - this.username, this.password, this.driver, this.defaultCatalogName,this.defaultSchemaName, Boolean.parseBoolean(outputDefaultCatalog), Boolean.parseBoolean(outputDefaultSchema), this.databaseClass, this.driverPropertiesFile, this.propertyProviderClass, this.liquibaseCatalogName, this.liquibaseSchemaName); - try { - - - CompositeResourceAccessor fileOpener = new CompositeResourceAccessor(fsOpener, clOpener); - - boolean includeCatalog = Boolean.parseBoolean(getCommandParam("includeCatalog", "false")); - boolean includeSchema = Boolean.parseBoolean(getCommandParam("includeSchema", "false")); - boolean includeTablespace = Boolean.parseBoolean(getCommandParam("includeTablespace", "false")); - DiffOutputControl diffOutputControl = new DiffOutputControl(includeCatalog, includeSchema, includeTablespace); - - String referenceSchemaNames = getCommandParam("schemas", null); - CompareControl.SchemaComparison[] finalSchemaComparisons; - CatalogAndSchema[] finalSchemas; - if (referenceSchemaNames == null) { - finalSchemaComparisons = new CompareControl.SchemaComparison[] {new CompareControl.SchemaComparison(new CatalogAndSchema(defaultCatalogName, defaultSchemaName), new CatalogAndSchema(defaultCatalogName, defaultSchemaName))}; - finalSchemas = new CatalogAndSchema[] {new CatalogAndSchema(defaultCatalogName, defaultSchemaName)}; - } else { - List schemaComparisons = new ArrayList(); - List schemas = new ArrayList(); - for (String schema : referenceSchemaNames.split(",")) { - CatalogAndSchema correctedSchema = new CatalogAndSchema(null, schema).customize(database); - schemaComparisons.add(new CompareControl.SchemaComparison(correctedSchema, correctedSchema)); - schemas.add(correctedSchema); - diffOutputControl.addIncludedSchema(correctedSchema); - } - finalSchemaComparisons = schemaComparisons.toArray(new CompareControl.SchemaComparison[schemaComparisons.size()]); - finalSchemas = schemas.toArray(new CatalogAndSchema[schemas.size()]); - } - - for (CompareControl.SchemaComparison schema : finalSchemaComparisons) { - diffOutputControl.addIncludedSchema(schema.getReferenceSchema()); - diffOutputControl.addIncludedSchema(schema.getComparisonSchema()); - } - - if ("diff".equalsIgnoreCase(command)) { - CommandLineUtils.doDiff(createReferenceDatabaseFromCommandParams(commandParams), database, StringUtils.trimToNull(diffTypes), finalSchemaComparisons); - return; - } else if ("diffChangeLog".equalsIgnoreCase(command)) { - CommandLineUtils.doDiffToChangeLog(changeLogFile, createReferenceDatabaseFromCommandParams(commandParams), database, diffOutputControl, StringUtils.trimToNull(diffTypes), finalSchemaComparisons); - return; - } else if ("generateChangeLog".equalsIgnoreCase(command)) { - String changeLogFile = this.changeLogFile; - if (changeLogFile == null) { - changeLogFile = ""; //will output to stdout - } - // By default the generateChangeLog command is destructive, and - // Liquibase's attempt to append doesn't work properly. Just - // fail the build if the file already exists. - File file = new File(changeLogFile); - if ( file.exists() ) { - throw new LiquibaseException("ChangeLogFile " + changeLogFile + " already exists!"); - } - - CommandLineUtils.doGenerateChangeLog(changeLogFile, database, finalSchemas, StringUtils.trimToNull(diffTypes), StringUtils.trimToNull(changeSetAuthor), StringUtils.trimToNull(changeSetContext), StringUtils.trimToNull(dataOutputDirectory), diffOutputControl); - return; - } else if ("snapshot".equalsIgnoreCase(command)) { - SnapshotCommand command = new SnapshotCommand(); - command.setDatabase(database); - command.setSchemas(getCommandParam("schemas", database.getDefaultSchema().getSchemaName())); - System.out.println(command.execute()); - return; - } else if ("executeSql".equalsIgnoreCase(command)) { - ExecuteSqlCommand command = new ExecuteSqlCommand(); - command.setDatabase(database); - command.setSql(getCommandParam("sql", null)); - command.setSqlFile(getCommandParam("sqlFile", null)); - System.out.println(command.execute()); - return; - } else if ("snapshotReference".equalsIgnoreCase(command)) { - SnapshotCommand command = new SnapshotCommand(); - Database referenceDatabase = createReferenceDatabaseFromCommandParams(commandParams); - command.setDatabase(referenceDatabase); - command.setSchemas(getCommandParam("schemas", referenceDatabase.getDefaultSchema().getSchemaName())); - System.out.println(command.execute()); - return; - } - - - Liquibase liquibase = new Liquibase(changeLogFile, fileOpener, database); - liquibase.setCurrentDateTimeFunction(currentDateTimeFunction); - for (Map.Entry entry : changeLogParameters.entrySet()) { - liquibase.setChangeLogParameter(entry.getKey(), entry.getValue()); - } - - if ("listLocks".equalsIgnoreCase(command)) { - liquibase.reportLocks(System.err); - return; - } else if ("releaseLocks".equalsIgnoreCase(command)) { - LockService lockService = LockServiceFactory.getInstance().getLockService(database); - lockService.forceReleaseLock(); - System.err.println("Successfully released all database change log locks for " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()); - return; - } else if ("tag".equalsIgnoreCase(command)) { - liquibase.tag(commandParams.iterator().next()); - System.err.println("Successfully tagged " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()); - return; - } else if ("dropAll".equals(command)) { - liquibase.dropAll(); - System.err.println("All objects dropped from " + liquibase.getDatabase().getConnection().getConnectionUserName() + "@" + liquibase.getDatabase().getConnection().getURL()); - return; - } else if ("status".equalsIgnoreCase(command)) { - boolean runVerbose = false; - - if (commandParams.contains("--verbose")) { - runVerbose = true; - } - liquibase.reportStatus(runVerbose, new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - return; - } else if ("unexpectedChangeSets".equalsIgnoreCase(command)) { - boolean runVerbose = false; - - if (commandParams.contains("--verbose")) { - runVerbose = true; - } - liquibase.reportUnexpectedChangeSets(runVerbose, contexts, getOutputWriter()); - return; - } else if ("validate".equalsIgnoreCase(command)) { - try { - liquibase.validate(); - } catch (ValidationFailedException e) { - e.printDescriptiveError(System.err); - return; - } - System.err.println("No validation errors found"); - return; - } else if ("clearCheckSums".equalsIgnoreCase(command)) { - liquibase.clearCheckSums(); - return; - } else if ("calculateCheckSum".equalsIgnoreCase(command)) { - CheckSum checkSum = null; - checkSum = liquibase.calculateCheckSum(commandParams.iterator().next()); - System.out.println(checkSum); - return; - } else if ("dbdoc".equalsIgnoreCase(command)) { - if (commandParams.size() == 0) { - throw new CommandLineParsingException("dbdoc requires an output directory"); - } - if (changeLogFile == null) { - throw new CommandLineParsingException("dbdoc requires a changeLog parameter"); - } - liquibase.generateDocumentation(commandParams.iterator().next(), contexts); - return; - } - - try { - if ("update".equalsIgnoreCase(command)) { - liquibase.update(new Contexts(contexts), new LabelExpression(labels)); - } else if ("changelogSync".equalsIgnoreCase(command)) { - liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels)); - } else if ("changelogSyncSQL".equalsIgnoreCase(command)) { - liquibase.changeLogSync(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("markNextChangeSetRan".equalsIgnoreCase(command)) { - liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels)); - } else if ("markNextChangeSetRanSQL".equalsIgnoreCase(command)) { - liquibase.markNextChangeSetRan(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("updateCount".equalsIgnoreCase(command)) { - liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels)); - } else if ("updateCountSQL".equalsIgnoreCase(command)) { - liquibase.update(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("updateSQL".equalsIgnoreCase(command)) { - liquibase.update(new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("rollback".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollback requires a rollback tag"); - } - liquibase.rollback(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels)); - } else if ("rollbackToDate".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollback requires a rollback date"); - } - liquibase.rollback(new ISODateFormat().parse(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels)); - } else if ("rollbackCount".equalsIgnoreCase(command)) { - liquibase.rollback(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels)); - - } else if ("rollbackSQL".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollbackSQL requires a rollback tag"); - } - liquibase.rollback(commandParams.iterator().next(), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("rollbackToDateSQL".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollbackToDateSQL requires a rollback date"); - } - liquibase.rollback(new ISODateFormat().parse(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("rollbackCountSQL".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("rollbackCountSQL requires a rollback tag"); - } - - liquibase.rollback(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("futureRollbackSQL".equalsIgnoreCase(command)) { - liquibase.futureRollbackSQL(null, new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("futureRollbackCountSQL".equalsIgnoreCase(command)) { - if (commandParams == null || commandParams.size() == 0) { - throw new CommandLineParsingException("futureRollbackCountSQL requires a rollback count"); - } - - liquibase.futureRollbackSQL(Integer.parseInt(commandParams.iterator().next()), new Contexts(contexts), new LabelExpression(labels), getOutputWriter()); - } else if ("updateTestingRollback".equalsIgnoreCase(command)) { - liquibase.updateTestingRollback(new Contexts(contexts), new LabelExpression(labels)); - } else { - throw new CommandLineParsingException("Unknown command: " + command); - } - } catch (ParseException e) { - throw new CommandLineParsingException("Unexpected date/time format. Use 'yyyy-MM-dd'T'HH:mm:ss'"); - } - } finally { - try { - database.rollback(); - database.close(); - } catch (DatabaseException e) { - LogFactory.getInstance().getLog().warning("problem closing connection", e); - } - } - } - - private String getCommandParam(String paramName, String defaultValue) throws CommandLineParsingException { - for (String param : commandParams) { - if (!param.contains("=")) { - return null; - } - String[] splitArg = splitArg(param); - - String attributeName = splitArg[0]; - String value = splitArg[1]; - if (attributeName.equalsIgnoreCase(paramName)) { - return value; - } - } - - return defaultValue; - } - - private Database createReferenceDatabaseFromCommandParams(Set commandParams) throws CommandLineParsingException, DatabaseException { - String driver = referenceDriver; - String url = referenceUrl; - String username = referenceUsername; - String password = referencePassword; - String defaultSchemaName = this.defaultSchemaName; - String defaultCatalogName = this.defaultCatalogName; - - for (String param : commandParams) { - String[] splitArg = splitArg(param); - - String attributeName = splitArg[0]; - String value = splitArg[1]; - if ("referenceDriver".equalsIgnoreCase(attributeName)) { - driver = value; - } else if ("referenceUrl".equalsIgnoreCase(attributeName)) { - url = value; - } else if ("referenceUsername".equalsIgnoreCase(attributeName)) { - username = value; - } else if ("referencePassword".equalsIgnoreCase(attributeName)) { - password = value; - } else if ("referenceDefaultCatalogName".equalsIgnoreCase(attributeName)) { - defaultCatalogName = value; - } else if ("referenceDefaultSchemaName".equalsIgnoreCase(attributeName)) { - defaultSchemaName = value; - } else if ("dataOutputDirectory".equalsIgnoreCase(attributeName)) { - dataOutputDirectory = value; - } - } - -// if (driver == null) { -// driver = DatabaseFactory.getWriteExecutor().findDefaultDriver(url); -// } - - if (url == null) { - throw new CommandLineParsingException("referenceUrl parameter missing"); - } - - return CommandLineUtils.createDatabaseObject(classLoader, url, username, password, driver, defaultCatalogName, defaultSchemaName, Boolean.parseBoolean(outputDefaultCatalog), Boolean.parseBoolean(outputDefaultSchema), null, null, this.propertyProviderClass, this.liquibaseCatalogName, this.liquibaseSchemaName); -// Driver driverObject; -// try { -// driverObject = (Driver) Class.forName(driver, true, classLoader).newInstance(); -// } catch (Exception e) { -// throw new RuntimeException("Cannot find database driver: " + e.getMessage()); -// } -// -// Properties info = new Properties(); -// info.put("user", username); -// info.put("password", password); -// -// Connection connection; -// try { -// connection = driverObject.connect(url, info); -// } catch (SQLException e) { -// throw new DatabaseException("Connection could not be created to " + url + ": " + e.getMessage(), e); -// } -// if (connection == null) { -// throw new DatabaseException("Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ". Possibly the wrong driver for the given database URL"); -// } -// -// Database database = DatabaseFactory.getWriteExecutor().findCorrectDatabaseImplementation(connection); -// database.setDefaultSchemaName(defaultSchemaName); -// -// return database; - } - - private Writer getOutputWriter() throws UnsupportedEncodingException, IOException { - String charsetName = LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding(); - - if (outputFile != null) { - try { - FileOutputStream fileOut = new FileOutputStream(outputFile, false); - return new OutputStreamWriter(fileOut, charsetName); - } catch (IOException e) { - System.err.printf("Could not create output file %s\n", outputFile); - throw e; - } - } else { - return new OutputStreamWriter(System.out, charsetName); - } - } - - public boolean isWindows() { - return System.getProperty("os.name").startsWith("Windows "); - } -} diff --git a/All/Genesis-NP/Genesis#286/pair.info b/All/Genesis-NP/Genesis#286/pair.info deleted file mode 100755 index f5f1141..0000000 --- a/All/Genesis-NP/Genesis#286/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:286 -SATName:Genesis -modifiedFPath:liquibase-core/src/main/java/liquibase/integration/commandline/Main.java -comSha:35e47daa75ae1b198f14a6cda524677cd44a654c -parentComSha:35e47daa75ae1b198f14a6cda524677cd44a654c^1 -githubUrl:https://github.com/liquibase/liquibase -repoName:liquibase#liquibase \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#289/comMsg.txt b/All/Genesis-NP/Genesis#289/comMsg.txt deleted file mode 100755 index 249ef16..0000000 --- a/All/Genesis-NP/Genesis#289/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixing NPE in the ChangeLogSyncVisitor when no listener is given at the time of construction. Unit tests created to test problem and verify solution. diff --git a/All/Genesis-NP/Genesis#289/diff.diff b/All/Genesis-NP/Genesis#289/diff.diff deleted file mode 100755 index ee2815e..0000000 --- a/All/Genesis-NP/Genesis#289/diff.diff +++ /dev/null @@ -1,8 +0,0 @@ -diff --git a/liquibase-core/src/main/java/liquibase/changelog/visitor/ChangeLogSyncVisitor.java b/liquibase-core/src/main/java/liquibase/changelog/visitor/ChangeLogSyncVisitor.java -index 760efc9..00e50be 100644 ---- a/liquibase-core/src/main/java/liquibase/changelog/visitor/ChangeLogSyncVisitor.java -+++ b/liquibase-core/src/main/java/liquibase/changelog/visitor/ChangeLogSyncVisitor.java -@@ -32,0 +33 @@ public class ChangeLogSyncVisitor implements ChangeSetVisitor { -+ if(listener != null) { -@@ -35,0 +37 @@ public class ChangeLogSyncVisitor implements ChangeSetVisitor { -+} diff --git a/All/Genesis-NP/Genesis#289/new/ChangeLogSyncVisitor.java b/All/Genesis-NP/Genesis#289/new/ChangeLogSyncVisitor.java deleted file mode 100755 index 00e50be..0000000 --- a/All/Genesis-NP/Genesis#289/new/ChangeLogSyncVisitor.java +++ /dev/null @@ -1,37 +0,0 @@ -package liquibase.changelog.visitor; - -import liquibase.changelog.ChangeSet; -import liquibase.changelog.DatabaseChangeLog; -import liquibase.changelog.filter.ChangeSetFilterResult; -import liquibase.database.Database; -import liquibase.exception.LiquibaseException; - -import java.util.Set; - -public class ChangeLogSyncVisitor implements ChangeSetVisitor { - - private Database database; - private ChangeLogSyncListener listener; - - public ChangeLogSyncVisitor(Database database) { - this.database = database; - } - - public ChangeLogSyncVisitor(Database database, ChangeLogSyncListener listener) { - this.database = database; - this.listener = listener; - } - - @Override - public Direction getDirection() { - return ChangeSetVisitor.Direction.FORWARD; - } - - @Override - public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, Set filterResults) throws LiquibaseException { - this.database.markChangeSetExecStatus(changeSet, ChangeSet.ExecType.EXECUTED); - if(listener != null) { - listener.markedRan(changeSet, databaseChangeLog, database); - } - } -} diff --git a/All/Genesis-NP/Genesis#289/old/ChangeLogSyncVisitor.java b/All/Genesis-NP/Genesis#289/old/ChangeLogSyncVisitor.java deleted file mode 100755 index 760efc9..0000000 --- a/All/Genesis-NP/Genesis#289/old/ChangeLogSyncVisitor.java +++ /dev/null @@ -1,35 +0,0 @@ -package liquibase.changelog.visitor; - -import liquibase.changelog.ChangeSet; -import liquibase.changelog.DatabaseChangeLog; -import liquibase.changelog.filter.ChangeSetFilterResult; -import liquibase.database.Database; -import liquibase.exception.LiquibaseException; - -import java.util.Set; - -public class ChangeLogSyncVisitor implements ChangeSetVisitor { - - private Database database; - private ChangeLogSyncListener listener; - - public ChangeLogSyncVisitor(Database database) { - this.database = database; - } - - public ChangeLogSyncVisitor(Database database, ChangeLogSyncListener listener) { - this.database = database; - this.listener = listener; - } - - @Override - public Direction getDirection() { - return ChangeSetVisitor.Direction.FORWARD; - } - - @Override - public void visit(ChangeSet changeSet, DatabaseChangeLog databaseChangeLog, Database database, Set filterResults) throws LiquibaseException { - this.database.markChangeSetExecStatus(changeSet, ChangeSet.ExecType.EXECUTED); - listener.markedRan(changeSet, databaseChangeLog, database); - } -} diff --git a/All/Genesis-NP/Genesis#289/pair.info b/All/Genesis-NP/Genesis#289/pair.info deleted file mode 100755 index 741a3e1..0000000 --- a/All/Genesis-NP/Genesis#289/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:289 -SATName:Genesis -modifiedFPath:liquibase-core/src/main/java/liquibase/changelog/visitor/ChangeLogSyncVisitor.java -comSha:fdbe2076b1d923b6faa10d354dbc554e1ae4abfb -parentComSha:fdbe2076b1d923b6faa10d354dbc554e1ae4abfb^1 -githubUrl:https://github.com/liquibase/liquibase -repoName:liquibase#liquibase \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#29/comMsg.txt b/All/Genesis-NP/Genesis#29/comMsg.txt deleted file mode 100755 index abfc661..0000000 --- a/All/Genesis-NP/Genesis#29/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -#293: fix NPE in OidcClient diff --git a/All/Genesis-NP/Genesis#29/diff.diff b/All/Genesis-NP/Genesis#29/diff.diff deleted file mode 100755 index 957523a..0000000 --- a/All/Genesis-NP/Genesis#29/diff.diff +++ /dev/null @@ -1,27 +0,0 @@ -diff --git a/pac4j-oidc/src/main/java/org/pac4j/oidc/client/OidcClient.java b/pac4j-oidc/src/main/java/org/pac4j/oidc/client/OidcClient.java -index 011434f..3c9c469 100644 ---- a/pac4j-oidc/src/main/java/org/pac4j/oidc/client/OidcClient.java -+++ b/pac4j-oidc/src/main/java/org/pac4j/oidc/client/OidcClient.java -@@ -282,0 +283,4 @@ public class OidcClient extends IndirectClient { -+ // Create Oidc profile -+ OidcProfile profile = new OidcProfile(accessToken); -+ profile.setIdTokenString(oidcTokens.getIDTokenString()); -+ -@@ -299,0 +304,3 @@ public class OidcClient extends IndirectClient { -+ if(userInfo != null){ -+ profile.addAttributes(userInfo.toJWTClaimsSet().getClaims()); -+ } -@@ -304,0 +312,5 @@ public class OidcClient extends IndirectClient { -+ if(claimsSet != null){ -+ profile.setId(claimsSet.getSubject()); -+ profile.addAttributes(claimsSet.getClaims()); -+ } -+ -@@ -314,7 +325,0 @@ public class OidcClient extends IndirectClient { -- // Return profile with Claims Set, User Info and Access Token -- OidcProfile profile = new OidcProfile(accessToken); -- profile.setId(claimsSet.getSubject()); -- profile.setIdTokenString(oidcTokens.getIDTokenString()); -- profile.addAttributes(claimsSet.getClaims()); -- profile.addAttributes(userInfo.toJWTClaimsSet().getClaims()); -- diff --git a/All/Genesis-NP/Genesis#29/new/OidcClient.java b/All/Genesis-NP/Genesis#29/new/OidcClient.java deleted file mode 100755 index 3c9c469..0000000 --- a/All/Genesis-NP/Genesis#29/new/OidcClient.java +++ /dev/null @@ -1,417 +0,0 @@ -/* - Copyright 2012 - 2015 pac4j organization - - 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.pac4j.oidc.client; - -import java.net.URI; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.openid.connect.sdk.*; -import com.nimbusds.openid.connect.sdk.token.OIDCTokens; -import org.pac4j.core.client.IndirectClient; -import org.pac4j.core.client.ClientType; -import org.pac4j.core.client.RedirectAction; -import org.pac4j.core.context.WebContext; -import org.pac4j.core.exception.RequiresHttpAction; -import org.pac4j.core.exception.TechnicalException; -import org.pac4j.core.util.CommonHelper; -import org.pac4j.oidc.credentials.OidcCredentials; -import org.pac4j.oidc.profile.OidcProfile; - -import com.nimbusds.jose.JWEDecrypter; -import com.nimbusds.jose.JWSVerifier; -import com.nimbusds.jose.crypto.ECDSAVerifier; -import com.nimbusds.jose.crypto.RSADecrypter; -import com.nimbusds.jose.crypto.RSASSAVerifier; -import com.nimbusds.jose.jwk.ECKey; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.jwk.KeyUse; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.oauth2.sdk.AuthorizationCode; -import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; -import com.nimbusds.oauth2.sdk.ParseException; -import com.nimbusds.oauth2.sdk.TokenErrorResponse; -import com.nimbusds.oauth2.sdk.TokenRequest; -import com.nimbusds.oauth2.sdk.TokenResponse; -import com.nimbusds.oauth2.sdk.auth.ClientAuthentication; -import com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod; -import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic; -import com.nimbusds.oauth2.sdk.auth.ClientSecretPost; -import com.nimbusds.oauth2.sdk.auth.Secret; -import com.nimbusds.oauth2.sdk.http.HTTPResponse; -import com.nimbusds.oauth2.sdk.id.ClientID; -import com.nimbusds.oauth2.sdk.id.State; -import com.nimbusds.oauth2.sdk.token.BearerAccessToken; -import com.nimbusds.openid.connect.sdk.claims.UserInfo; -import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata; -import com.nimbusds.openid.connect.sdk.util.DefaultJWTDecoder; -import com.nimbusds.openid.connect.sdk.util.DefaultResourceRetriever; - -/** - * This class is the client to authenticate users with an OpenID Connect 1.0 provider. - * By default, this implementation relies on the - * "code" response type. (http://openid.net/specs/openid-connect-core-1_0.html). - * - * @author Michael Remond - * @since 1.7.0 - */ -public class OidcClient extends IndirectClient { - - /* Parameter to indicate to send nonce in the authentication request */ - private static final String USE_NONCE_PARAM = "useNonce"; - - /* state attribute name in session */ - private static final String STATE_ATTRIBUTE = "oidcStateAttribute"; - - /* nonce attribute name in session */ - private static final String NONCE_ATTRIBUTE = "oidcNonceAttribute"; - - /* OpenID client_id */ - private String clientId; - - /* OpenID secret */ - private String secret; - - /* OpenID redirect_uri */ - private URI redirectURI; - - /* discovery URI for fetching OP metadata (http://openid.net/specs/openid-connect-discovery-1_0.html) */ - private String discoveryURI; - - /* Decoder for the JWT ID Token */ - private DefaultJWTDecoder jwtDecoder; - - /* OIDC metadata */ - private OIDCProviderMetadata oidcProvider; - - /* Map containing the parameters for configuring all aspects of the OpenID Connect integration */ - private Map authParams; - - /* Map containing user defined parameters */ - private final Map customParams = new HashMap(); - - /* client authentication object at the token End Point (basic, form or JWT) */ - private ClientAuthentication clientAuthentication; - - /* clientID object */ - private ClientID _clientID; - - /* secret object */ - private Secret _secret; - - @Override - public ClientType getClientType() { - return ClientType.OPENID_CONNECT_PROTOCOL; - } - - public void setDiscoveryURI(final String discoveryURI) { - this.discoveryURI = discoveryURI; - } - - public void setClientID(final String clientID) { - this.clientId = clientID; - } - - public void setSecret(final String secret) { - this.secret = secret; - } - - public void addCustomParam(final String key, final String value) { - this.customParams.put(key, value); - } - - @Override - protected void internalInit() { - - CommonHelper.assertNotBlank(this.clientId, "clientID cannot be blank"); - CommonHelper.assertNotBlank(this.secret, "secret cannot be blank"); - CommonHelper.assertNotBlank(this.discoveryURI, "discoveryURI cannot be blank"); - - this.authParams = new HashMap(); - // default values - this.authParams.put("scope", "openid profile email"); - this.authParams.put("response_type", "code"); - this.authParams.put("redirect_uri", getCallbackUrl()); - // add custom values - this.authParams.putAll(this.customParams); - // Override with required values - this.authParams.put("client_id", this.clientId); - this.authParams.put("client_secret", this.secret); - - this._clientID = new ClientID(this.clientId); - this._secret = new Secret(this.secret); - - JWKSet jwkSet; - // Download OIDC metadata and Json Web Key Set - try { - DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(); - this.oidcProvider = OIDCProviderMetadata.parse(resourceRetriever.retrieveResource( - new URL(this.discoveryURI)).getContent()); - jwkSet = JWKSet.parse(resourceRetriever.retrieveResource(this.oidcProvider.getJWKSetURI().toURL()) - .getContent()); - - this.redirectURI = new URI(getCallbackUrl()); - } catch (Exception e) { - throw new TechnicalException(e); - } - // Get available client authentication method - ClientAuthenticationMethod method = getClientAuthenticationMethod(); - this.clientAuthentication = getClientAuthentication(method); - // Init JWT decoder - this.jwtDecoder = new DefaultJWTDecoder(); - initJwtDecoder(this.jwtDecoder, jwkSet); - - } - - @Override - protected IndirectClient newClient() { - OidcClient client = new OidcClient(); - client.setClientID(this.clientId); - client.setSecret(this.secret); - client.setDiscoveryURI(this.discoveryURI); - client.setAuthParams(this.authParams); - - return client; - } - - @Override - protected boolean isDirectRedirection() { - return true; - } - - @Override - protected RedirectAction retrieveRedirectAction(final WebContext context) { - - Map params = new HashMap(this.authParams); - - // Init state for CSRF mitigation - State state = new State(); - params.put("state", state.getValue()); - context.setSessionAttribute(STATE_ATTRIBUTE, state); - // Init nonce for replay attack mitigation - if (useNonce()) { - Nonce nonce = new Nonce(); - params.put("nonce", nonce.getValue()); - context.setSessionAttribute(NONCE_ATTRIBUTE, nonce.getValue()); - } - - // Build authentication request query string - String queryString; - try { - queryString = AuthenticationRequest.parse(params).toQueryString(); - } catch (Exception e) { - throw new TechnicalException(e); - } - String location = this.oidcProvider.getAuthorizationEndpointURI().toString() + "?" + queryString; - logger.debug("Authentication request url : {}", location); - - return RedirectAction.redirect(location); - } - - @Override - protected OidcCredentials retrieveCredentials(final WebContext context) throws RequiresHttpAction { - - // Parse authentication response parameters - Map parameters = toSingleParameter(context.getRequestParameters()); - AuthenticationResponse response; - try { - response = AuthenticationResponseParser.parse(this.redirectURI, parameters); - } catch (ParseException e) { - throw new TechnicalException(e); - } - - if (response instanceof AuthenticationErrorResponse) { - logger.error("Bad authentication response, error={}", - ((AuthenticationErrorResponse) response).getErrorObject()); - return null; - } - - logger.debug("Authentication response successful, get authorization code"); - AuthenticationSuccessResponse successResponse = (AuthenticationSuccessResponse) response; - - // state value must be equal - if (!successResponse.getState().equals(context.getSessionAttribute(STATE_ATTRIBUTE))) { - throw new TechnicalException("State parameter is different from the one sent in authentication request. " - + "Session expired or possible threat of cross-site request forgery"); - } - // Get authorization code - AuthorizationCode code = successResponse.getAuthorizationCode(); - - return new OidcCredentials(code); - } - - @Override - protected OidcProfile retrieveUserProfile(final OidcCredentials credentials, final WebContext context) { - - final TokenRequest request = new TokenRequest(this.oidcProvider.getTokenEndpointURI(), this.clientAuthentication, - new AuthorizationCodeGrant(credentials.getCode(), this.redirectURI)); - HTTPResponse httpResponse; - try { - // Token request - httpResponse = request.toHTTPRequest().send(); - logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), - httpResponse.getContent()); - - final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse); - if (response instanceof TokenErrorResponse) { - logger.error("Bad token response, error={}", ((TokenErrorResponse) response).getErrorObject()); - return null; - } - logger.debug("Token response successful"); - final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response; - final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens(); - final BearerAccessToken accessToken = (BearerAccessToken) oidcTokens.getAccessToken(); - - // Create Oidc profile - OidcProfile profile = new OidcProfile(accessToken); - profile.setIdTokenString(oidcTokens.getIDTokenString()); - - // User Info request - UserInfo userInfo = null; - if (this.oidcProvider.getUserInfoEndpointURI() != null) { - UserInfoRequest userInfoRequest = new UserInfoRequest(this.oidcProvider.getUserInfoEndpointURI(), - accessToken); - httpResponse = userInfoRequest.toHTTPRequest().send(); - logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), - httpResponse.getContent()); - - UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse); - - if (userInfoResponse instanceof UserInfoErrorResponse) { - logger.error("Bad User Info response, error={}", - ((UserInfoErrorResponse) userInfoResponse).getErrorObject()); - } else { - UserInfoSuccessResponse userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse; - userInfo = userInfoSuccessResponse.getUserInfo(); - if(userInfo != null){ - profile.addAttributes(userInfo.toJWTClaimsSet().getClaims()); - } - } - } - - // Check ID Token - final JWTClaimsSet claimsSet = this.jwtDecoder.decodeJWT(oidcTokens.getIDToken()); - if(claimsSet != null){ - profile.setId(claimsSet.getSubject()); - profile.addAttributes(claimsSet.getClaims()); - } - - if (useNonce()) { - String nonce = claimsSet.getStringClaim("nonce"); - if (nonce == null || !nonce.equals(context.getSessionAttribute(NONCE_ATTRIBUTE))) { - throw new TechnicalException( - "A nonce was sent in the authentication request but it is missing or different in the ID Token. " - + "Session expired or possible threat of cross-site request forgery"); - } - } - - return profile; - - } catch (Exception e) { - throw new TechnicalException(e); - } - - } - - /** - * Returns the first available authentication method from the OP. - * - * @return - */ - private ClientAuthenticationMethod getClientAuthenticationMethod() { - return this.oidcProvider.getTokenEndpointAuthMethods() != null - && this.oidcProvider.getTokenEndpointAuthMethods().size() > 0 ? this.oidcProvider - .getTokenEndpointAuthMethods().get(0) : ClientAuthenticationMethod.getDefault(); - } - - /** - * Returns true if we want to use a nonce. - * - * @return - */ - private boolean useNonce() { - return Boolean.parseBoolean(this.authParams.get(USE_NONCE_PARAM)); - } - - /** - * Add the required verifiers and decrypters to the JWT Decoder based on the JWK set from the OP. - * - * @param jwtDecoder - * @param jwkSet - */ - private void initJwtDecoder(final DefaultJWTDecoder jwtDecoder, final JWKSet jwkSet) { - try { - for (JWK key : jwkSet.getKeys()) { - if (key.getKeyUse() == KeyUse.SIGNATURE) { - jwtDecoder.addJWSVerifier(getVerifier(key)); - } else if (key.getKeyUse() == KeyUse.ENCRYPTION) { - jwtDecoder.addJWEDecrypter(getDecrypter(key)); - } - } - } catch (Exception e) { - throw new TechnicalException(e); - } - } - - private JWEDecrypter getDecrypter(final JWK key) throws JOSEException { - if (key instanceof RSAKey) { - return new RSADecrypter(((RSAKey) key).toRSAPrivateKey()); - } - return null; - } - - private JWSVerifier getVerifier(final JWK key) throws JOSEException { - if (key instanceof RSAKey) { - return new RSASSAVerifier(((RSAKey) key).toRSAPublicKey()); - } else if (key instanceof ECKey) { - ECKey ecKey = (ECKey) key; - return new ECDSAVerifier(ecKey); - } - return null; - } - - /** - * Returns a configured Client Authentication with method, client_id and secret for the token End Point. - * - * @param method - * @return - */ - private ClientAuthentication getClientAuthentication(final ClientAuthenticationMethod method) { - if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(method)) { - return new ClientSecretPost(this._clientID, this._secret); - } else if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(method)) { - return new ClientSecretBasic(this._clientID, this._secret); - } - return null; - } - - private Map toSingleParameter(final Map requestParameters) { - Map map = new HashMap(); - for (Entry entry : requestParameters.entrySet()) { - map.put(entry.getKey(), entry.getValue()[0]); - } - return map; - } - - private void setAuthParams(final Map authParams) { - this.authParams = authParams; - } -} diff --git a/All/Genesis-NP/Genesis#29/old/OidcClient.java b/All/Genesis-NP/Genesis#29/old/OidcClient.java deleted file mode 100755 index 011434f..0000000 --- a/All/Genesis-NP/Genesis#29/old/OidcClient.java +++ /dev/null @@ -1,412 +0,0 @@ -/* - Copyright 2012 - 2015 pac4j organization - - 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.pac4j.oidc.client; - -import java.net.URI; -import java.net.URL; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import com.nimbusds.jose.JOSEException; -import com.nimbusds.jwt.JWTClaimsSet; -import com.nimbusds.openid.connect.sdk.*; -import com.nimbusds.openid.connect.sdk.token.OIDCTokens; -import org.pac4j.core.client.IndirectClient; -import org.pac4j.core.client.ClientType; -import org.pac4j.core.client.RedirectAction; -import org.pac4j.core.context.WebContext; -import org.pac4j.core.exception.RequiresHttpAction; -import org.pac4j.core.exception.TechnicalException; -import org.pac4j.core.util.CommonHelper; -import org.pac4j.oidc.credentials.OidcCredentials; -import org.pac4j.oidc.profile.OidcProfile; - -import com.nimbusds.jose.JWEDecrypter; -import com.nimbusds.jose.JWSVerifier; -import com.nimbusds.jose.crypto.ECDSAVerifier; -import com.nimbusds.jose.crypto.RSADecrypter; -import com.nimbusds.jose.crypto.RSASSAVerifier; -import com.nimbusds.jose.jwk.ECKey; -import com.nimbusds.jose.jwk.JWK; -import com.nimbusds.jose.jwk.JWKSet; -import com.nimbusds.jose.jwk.KeyUse; -import com.nimbusds.jose.jwk.RSAKey; -import com.nimbusds.oauth2.sdk.AuthorizationCode; -import com.nimbusds.oauth2.sdk.AuthorizationCodeGrant; -import com.nimbusds.oauth2.sdk.ParseException; -import com.nimbusds.oauth2.sdk.TokenErrorResponse; -import com.nimbusds.oauth2.sdk.TokenRequest; -import com.nimbusds.oauth2.sdk.TokenResponse; -import com.nimbusds.oauth2.sdk.auth.ClientAuthentication; -import com.nimbusds.oauth2.sdk.auth.ClientAuthenticationMethod; -import com.nimbusds.oauth2.sdk.auth.ClientSecretBasic; -import com.nimbusds.oauth2.sdk.auth.ClientSecretPost; -import com.nimbusds.oauth2.sdk.auth.Secret; -import com.nimbusds.oauth2.sdk.http.HTTPResponse; -import com.nimbusds.oauth2.sdk.id.ClientID; -import com.nimbusds.oauth2.sdk.id.State; -import com.nimbusds.oauth2.sdk.token.BearerAccessToken; -import com.nimbusds.openid.connect.sdk.claims.UserInfo; -import com.nimbusds.openid.connect.sdk.op.OIDCProviderMetadata; -import com.nimbusds.openid.connect.sdk.util.DefaultJWTDecoder; -import com.nimbusds.openid.connect.sdk.util.DefaultResourceRetriever; - -/** - * This class is the client to authenticate users with an OpenID Connect 1.0 provider. - * By default, this implementation relies on the - * "code" response type. (http://openid.net/specs/openid-connect-core-1_0.html). - * - * @author Michael Remond - * @since 1.7.0 - */ -public class OidcClient extends IndirectClient { - - /* Parameter to indicate to send nonce in the authentication request */ - private static final String USE_NONCE_PARAM = "useNonce"; - - /* state attribute name in session */ - private static final String STATE_ATTRIBUTE = "oidcStateAttribute"; - - /* nonce attribute name in session */ - private static final String NONCE_ATTRIBUTE = "oidcNonceAttribute"; - - /* OpenID client_id */ - private String clientId; - - /* OpenID secret */ - private String secret; - - /* OpenID redirect_uri */ - private URI redirectURI; - - /* discovery URI for fetching OP metadata (http://openid.net/specs/openid-connect-discovery-1_0.html) */ - private String discoveryURI; - - /* Decoder for the JWT ID Token */ - private DefaultJWTDecoder jwtDecoder; - - /* OIDC metadata */ - private OIDCProviderMetadata oidcProvider; - - /* Map containing the parameters for configuring all aspects of the OpenID Connect integration */ - private Map authParams; - - /* Map containing user defined parameters */ - private final Map customParams = new HashMap(); - - /* client authentication object at the token End Point (basic, form or JWT) */ - private ClientAuthentication clientAuthentication; - - /* clientID object */ - private ClientID _clientID; - - /* secret object */ - private Secret _secret; - - @Override - public ClientType getClientType() { - return ClientType.OPENID_CONNECT_PROTOCOL; - } - - public void setDiscoveryURI(final String discoveryURI) { - this.discoveryURI = discoveryURI; - } - - public void setClientID(final String clientID) { - this.clientId = clientID; - } - - public void setSecret(final String secret) { - this.secret = secret; - } - - public void addCustomParam(final String key, final String value) { - this.customParams.put(key, value); - } - - @Override - protected void internalInit() { - - CommonHelper.assertNotBlank(this.clientId, "clientID cannot be blank"); - CommonHelper.assertNotBlank(this.secret, "secret cannot be blank"); - CommonHelper.assertNotBlank(this.discoveryURI, "discoveryURI cannot be blank"); - - this.authParams = new HashMap(); - // default values - this.authParams.put("scope", "openid profile email"); - this.authParams.put("response_type", "code"); - this.authParams.put("redirect_uri", getCallbackUrl()); - // add custom values - this.authParams.putAll(this.customParams); - // Override with required values - this.authParams.put("client_id", this.clientId); - this.authParams.put("client_secret", this.secret); - - this._clientID = new ClientID(this.clientId); - this._secret = new Secret(this.secret); - - JWKSet jwkSet; - // Download OIDC metadata and Json Web Key Set - try { - DefaultResourceRetriever resourceRetriever = new DefaultResourceRetriever(); - this.oidcProvider = OIDCProviderMetadata.parse(resourceRetriever.retrieveResource( - new URL(this.discoveryURI)).getContent()); - jwkSet = JWKSet.parse(resourceRetriever.retrieveResource(this.oidcProvider.getJWKSetURI().toURL()) - .getContent()); - - this.redirectURI = new URI(getCallbackUrl()); - } catch (Exception e) { - throw new TechnicalException(e); - } - // Get available client authentication method - ClientAuthenticationMethod method = getClientAuthenticationMethod(); - this.clientAuthentication = getClientAuthentication(method); - // Init JWT decoder - this.jwtDecoder = new DefaultJWTDecoder(); - initJwtDecoder(this.jwtDecoder, jwkSet); - - } - - @Override - protected IndirectClient newClient() { - OidcClient client = new OidcClient(); - client.setClientID(this.clientId); - client.setSecret(this.secret); - client.setDiscoveryURI(this.discoveryURI); - client.setAuthParams(this.authParams); - - return client; - } - - @Override - protected boolean isDirectRedirection() { - return true; - } - - @Override - protected RedirectAction retrieveRedirectAction(final WebContext context) { - - Map params = new HashMap(this.authParams); - - // Init state for CSRF mitigation - State state = new State(); - params.put("state", state.getValue()); - context.setSessionAttribute(STATE_ATTRIBUTE, state); - // Init nonce for replay attack mitigation - if (useNonce()) { - Nonce nonce = new Nonce(); - params.put("nonce", nonce.getValue()); - context.setSessionAttribute(NONCE_ATTRIBUTE, nonce.getValue()); - } - - // Build authentication request query string - String queryString; - try { - queryString = AuthenticationRequest.parse(params).toQueryString(); - } catch (Exception e) { - throw new TechnicalException(e); - } - String location = this.oidcProvider.getAuthorizationEndpointURI().toString() + "?" + queryString; - logger.debug("Authentication request url : {}", location); - - return RedirectAction.redirect(location); - } - - @Override - protected OidcCredentials retrieveCredentials(final WebContext context) throws RequiresHttpAction { - - // Parse authentication response parameters - Map parameters = toSingleParameter(context.getRequestParameters()); - AuthenticationResponse response; - try { - response = AuthenticationResponseParser.parse(this.redirectURI, parameters); - } catch (ParseException e) { - throw new TechnicalException(e); - } - - if (response instanceof AuthenticationErrorResponse) { - logger.error("Bad authentication response, error={}", - ((AuthenticationErrorResponse) response).getErrorObject()); - return null; - } - - logger.debug("Authentication response successful, get authorization code"); - AuthenticationSuccessResponse successResponse = (AuthenticationSuccessResponse) response; - - // state value must be equal - if (!successResponse.getState().equals(context.getSessionAttribute(STATE_ATTRIBUTE))) { - throw new TechnicalException("State parameter is different from the one sent in authentication request. " - + "Session expired or possible threat of cross-site request forgery"); - } - // Get authorization code - AuthorizationCode code = successResponse.getAuthorizationCode(); - - return new OidcCredentials(code); - } - - @Override - protected OidcProfile retrieveUserProfile(final OidcCredentials credentials, final WebContext context) { - - final TokenRequest request = new TokenRequest(this.oidcProvider.getTokenEndpointURI(), this.clientAuthentication, - new AuthorizationCodeGrant(credentials.getCode(), this.redirectURI)); - HTTPResponse httpResponse; - try { - // Token request - httpResponse = request.toHTTPRequest().send(); - logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), - httpResponse.getContent()); - - final TokenResponse response = OIDCTokenResponseParser.parse(httpResponse); - if (response instanceof TokenErrorResponse) { - logger.error("Bad token response, error={}", ((TokenErrorResponse) response).getErrorObject()); - return null; - } - logger.debug("Token response successful"); - final OIDCTokenResponse tokenSuccessResponse = (OIDCTokenResponse) response; - final OIDCTokens oidcTokens = tokenSuccessResponse.getOIDCTokens(); - final BearerAccessToken accessToken = (BearerAccessToken) oidcTokens.getAccessToken(); - - // User Info request - UserInfo userInfo = null; - if (this.oidcProvider.getUserInfoEndpointURI() != null) { - UserInfoRequest userInfoRequest = new UserInfoRequest(this.oidcProvider.getUserInfoEndpointURI(), - accessToken); - httpResponse = userInfoRequest.toHTTPRequest().send(); - logger.debug("Token response: status={}, content={}", httpResponse.getStatusCode(), - httpResponse.getContent()); - - UserInfoResponse userInfoResponse = UserInfoResponse.parse(httpResponse); - - if (userInfoResponse instanceof UserInfoErrorResponse) { - logger.error("Bad User Info response, error={}", - ((UserInfoErrorResponse) userInfoResponse).getErrorObject()); - } else { - UserInfoSuccessResponse userInfoSuccessResponse = (UserInfoSuccessResponse) userInfoResponse; - userInfo = userInfoSuccessResponse.getUserInfo(); - } - } - - // Check ID Token - final JWTClaimsSet claimsSet = this.jwtDecoder.decodeJWT(oidcTokens.getIDToken()); - if (useNonce()) { - String nonce = claimsSet.getStringClaim("nonce"); - if (nonce == null || !nonce.equals(context.getSessionAttribute(NONCE_ATTRIBUTE))) { - throw new TechnicalException( - "A nonce was sent in the authentication request but it is missing or different in the ID Token. " - + "Session expired or possible threat of cross-site request forgery"); - } - } - - // Return profile with Claims Set, User Info and Access Token - OidcProfile profile = new OidcProfile(accessToken); - profile.setId(claimsSet.getSubject()); - profile.setIdTokenString(oidcTokens.getIDTokenString()); - profile.addAttributes(claimsSet.getClaims()); - profile.addAttributes(userInfo.toJWTClaimsSet().getClaims()); - - return profile; - - } catch (Exception e) { - throw new TechnicalException(e); - } - - } - - /** - * Returns the first available authentication method from the OP. - * - * @return - */ - private ClientAuthenticationMethod getClientAuthenticationMethod() { - return this.oidcProvider.getTokenEndpointAuthMethods() != null - && this.oidcProvider.getTokenEndpointAuthMethods().size() > 0 ? this.oidcProvider - .getTokenEndpointAuthMethods().get(0) : ClientAuthenticationMethod.getDefault(); - } - - /** - * Returns true if we want to use a nonce. - * - * @return - */ - private boolean useNonce() { - return Boolean.parseBoolean(this.authParams.get(USE_NONCE_PARAM)); - } - - /** - * Add the required verifiers and decrypters to the JWT Decoder based on the JWK set from the OP. - * - * @param jwtDecoder - * @param jwkSet - */ - private void initJwtDecoder(final DefaultJWTDecoder jwtDecoder, final JWKSet jwkSet) { - try { - for (JWK key : jwkSet.getKeys()) { - if (key.getKeyUse() == KeyUse.SIGNATURE) { - jwtDecoder.addJWSVerifier(getVerifier(key)); - } else if (key.getKeyUse() == KeyUse.ENCRYPTION) { - jwtDecoder.addJWEDecrypter(getDecrypter(key)); - } - } - } catch (Exception e) { - throw new TechnicalException(e); - } - } - - private JWEDecrypter getDecrypter(final JWK key) throws JOSEException { - if (key instanceof RSAKey) { - return new RSADecrypter(((RSAKey) key).toRSAPrivateKey()); - } - return null; - } - - private JWSVerifier getVerifier(final JWK key) throws JOSEException { - if (key instanceof RSAKey) { - return new RSASSAVerifier(((RSAKey) key).toRSAPublicKey()); - } else if (key instanceof ECKey) { - ECKey ecKey = (ECKey) key; - return new ECDSAVerifier(ecKey); - } - return null; - } - - /** - * Returns a configured Client Authentication with method, client_id and secret for the token End Point. - * - * @param method - * @return - */ - private ClientAuthentication getClientAuthentication(final ClientAuthenticationMethod method) { - if (ClientAuthenticationMethod.CLIENT_SECRET_POST.equals(method)) { - return new ClientSecretPost(this._clientID, this._secret); - } else if (ClientAuthenticationMethod.CLIENT_SECRET_BASIC.equals(method)) { - return new ClientSecretBasic(this._clientID, this._secret); - } - return null; - } - - private Map toSingleParameter(final Map requestParameters) { - Map map = new HashMap(); - for (Entry entry : requestParameters.entrySet()) { - map.put(entry.getKey(), entry.getValue()[0]); - } - return map; - } - - private void setAuthParams(final Map authParams) { - this.authParams = authParams; - } -} diff --git a/All/Genesis-NP/Genesis#29/pair.info b/All/Genesis-NP/Genesis#29/pair.info deleted file mode 100755 index ebf5f88..0000000 --- a/All/Genesis-NP/Genesis#29/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:29 -SATName:Genesis -modifiedFPath:pac4j-oidc/src/main/java/org/pac4j/oidc/client/OidcClient.java -comSha:a87e81539782494f6e01d5b1b909c827e690e202 -parentComSha:a87e81539782494f6e01d5b1b909c827e690e202^1 -githubUrl:https://github.com/pac4j/pac4j -repoName:pac4j#pac4j \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#291/comMsg.txt b/All/Genesis-NP/Genesis#291/comMsg.txt deleted file mode 100755 index b3226b1..0000000 --- a/All/Genesis-NP/Genesis#291/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Handle possible NPE with tabStop.getLeader() diff --git a/All/Genesis-NP/Genesis#291/diff.diff b/All/Genesis-NP/Genesis#291/diff.diff deleted file mode 100755 index ce36c7c..0000000 --- a/All/Genesis-NP/Genesis#291/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/org/docx4j/convert/out/fo/FOExporterVisitorGenerator.java b/src/main/java/org/docx4j/convert/out/fo/FOExporterVisitorGenerator.java -index d38570f..336c44c 100644 ---- a/src/main/java/org/docx4j/convert/out/fo/FOExporterVisitorGenerator.java -+++ b/src/main/java/org/docx4j/convert/out/fo/FOExporterVisitorGenerator.java -@@ -204,0 +205 @@ public class FOExporterVisitorGenerator extends AbstractVisitorExporterGenerator -+ -@@ -206,2 +207,4 @@ public class FOExporterVisitorGenerator extends AbstractVisitorExporterGenerator -- && tabStop.getLeader().equals(STTabTlc.DOT) -- && tabStop.getVal().equals(STTabJc.RIGHT) ) { -+ && tabStop.getVal()!=null // unlikely -+ && tabStop.getVal().equals(STTabJc.RIGHT) -+ && tabStop.getLeader()!=null // more likely -+ && tabStop.getLeader().equals(STTabTlc.DOT) ) { diff --git a/All/Genesis-NP/Genesis#291/new/FOExporterVisitorGenerator.java b/All/Genesis-NP/Genesis#291/new/FOExporterVisitorGenerator.java deleted file mode 100755 index 336c44c..0000000 --- a/All/Genesis-NP/Genesis#291/new/FOExporterVisitorGenerator.java +++ /dev/null @@ -1,670 +0,0 @@ -/* - Licensed to Plutext Pty Ltd under one or more contributor license agreements. - - * This file is part of docx4j. - - docx4j is licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - - You may obtain a copy of the License at - - 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.docx4j.convert.out.fo; - -import java.util.List; - -import org.docx4j.XmlUtils; -import org.docx4j.convert.out.common.AbstractVisitorExporterDelegate; -import org.docx4j.convert.out.common.AbstractVisitorExporterDelegate.AbstractVisitorExporterGeneratorFactory; -import org.docx4j.convert.out.common.AbstractVisitorExporterGenerator; -import org.docx4j.convert.out.common.writer.AbstractBrWriter; -import org.docx4j.model.PropertyResolver; -import org.docx4j.model.images.WordXmlPictureE10; -import org.docx4j.model.images.WordXmlPictureE20; -import org.docx4j.model.listnumbering.Emulator.ResultTriple; -import org.docx4j.model.properties.Property; -import org.docx4j.model.properties.PropertyFactory; -import org.docx4j.model.properties.paragraph.Indent; -import org.docx4j.model.properties.paragraph.Justification; -import org.docx4j.model.properties.paragraph.PBorderBottom; -import org.docx4j.model.properties.paragraph.PBorderTop; -import org.docx4j.model.properties.paragraph.PShading; -import org.docx4j.model.styles.StyleUtil; -import org.docx4j.openpackaging.packages.WordprocessingMLPackage; -import org.docx4j.wml.Br; -import org.docx4j.wml.CTTabStop; -import org.docx4j.wml.JcEnumeration; -import org.docx4j.wml.P; -import org.docx4j.wml.PPr; -import org.docx4j.wml.PPrBase.NumPr.Ilvl; -import org.docx4j.wml.R; -import org.docx4j.wml.RPr; -import org.docx4j.wml.STBrType; -import org.docx4j.wml.STTabJc; -import org.docx4j.wml.STTabTlc; -import org.docx4j.wml.Style; -import org.docx4j.wml.TcPr; -import org.docx4j.wml.TrPr; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.Text; - -public class FOExporterVisitorGenerator extends AbstractVisitorExporterGenerator{ - - private static Logger log = LoggerFactory.getLogger(FOExporterVisitorGenerator.class); - - - private static String XSL_FO = "http://www.w3.org/1999/XSL/Format"; - - public static final AbstractVisitorExporterDelegate.AbstractVisitorExporterGeneratorFactory GENERATOR_FACTORY = - new AbstractVisitorExporterGeneratorFactory() { - @Override - public AbstractVisitorExporterGenerator createInstance( - FOConversionContext conversionContext, - Document document, Node parentNode) { - return new FOExporterVisitorGenerator(conversionContext, document, parentNode); - } - }; - - - private FOExporterVisitorGenerator(FOConversionContext conversionContext, Document document, Node parentNode) { - super(conversionContext, document, parentNode); - } - - @Override - protected AbstractVisitorExporterGeneratorFactory getFactory() { - return GENERATOR_FACTORY; - } - - @Override - protected DocumentFragment createImage(int imgType, FOConversionContext conversionContext, Object anchorOrInline) { - switch (imgType) { - case IMAGE_E10: - return WordXmlPictureE10.createXslFoImgE10(conversionContext, anchorOrInline); - case IMAGE_E20: - return WordXmlPictureE20.createXslFoImgE20(conversionContext, anchorOrInline); - } - return null; - } - - @Override - protected Element createNode(Document doc, int nodeType) { - switch (nodeType) { - case NODE_BLOCK: - return document.createElementNS(XSL_FO, "block"); - case NODE_INLINE: - return document.createElementNS(XSL_FO, "inline"); - } - return null; - } - - @Override - protected void handleBr(Br br) { - - - /* Is there a w:br immediately before this one? - - If this is the first child of this w:r, and the w:r is preceded by another w:r, look at its last child - - If this is not the first child of this w:r, look at the preceding sibling -*/ - - boolean firstBr = true; // until proven otherwise - - R r = (R)br.getParent(); - int pos = getPos(r.getContent(), br); - if (pos<0) { - log.error("Couldn't locate w:br in w:r"); - } - else if (pos==0) { - // Need to look in preceding run - Object rParent = r.getParent(); - // Handle just the case where this is w:p for now - if(rParent instanceof P) { - P parentP = (P)rParent; - pos = getPos(parentP.getContent(), r); - if (pos<0) { - log.error("Couldn't locate w:r in w:p"); - } else if (pos>0) { - Object beforeR = parentP.getContent().get(pos-1); - if (beforeR instanceof R) { - List list = ((R)beforeR).getContent(); - Object previous = list.get(list.size()-1); - if (previous instanceof Br) { - firstBr=false; - } - } else { -// System.out.println(beforeR.getClass().getName()); - - } - } - } else { - log.info("TODO: handle run parent " + rParent.getClass().getName()); - } - } else { - Object previous = r.getContent().get(pos-1); - if (previous instanceof Br) { - firstBr=false; - } else { -// System.out.println("previous: " + previous.getClass().getName()); - } - } - - if ((!firstBr) && - (br.getType()==null - || br.getType().equals(STBrType.TEXT_WRAPPING))) { - - // ie a soft-return following another - // - Element ret = createNode(document, NODE_BLOCK); - // see http://stackoverflow.com/a/3664468/1031689 answer - // at http://stackoverflow.com/questions/3661483/inserting-a-line-break-in-a-pdf-generated-from-xsl-fo-using-xslvalue-of - ret.setAttribute("linefeed-treatment", "preserve"); - ret.setAttribute("white-space-treatment", "preserve"); - ret.setTextContent("\n"); - - getCurrentParent().appendChild(ret); // should be spanEl - - } else { - // Usual case - convertToNode(conversionContext, - br, AbstractBrWriter.WRITER_ID, - document, getCurrentParent() ); - - } - - if ((br.getType()!=null - && br.getType().equals(STBrType.PAGE))) { - currentSpan=null; - } - } - - - @Override - protected void convertTabToNode(FOConversionContext conversionContext, Document document) throws DOMException { - - if (!conversionContext.isInComplexFieldDefinition()) { - - if (pPr!=null && pPr.getTabs()!=null) { - - // xsl:when test="count($p/w:pPr/w:tabs/w:tab[1][@w:leader='dot' and @w:val='right'])=1" - CTTabStop tabStop = pPr.getTabs().getTab().get(0); - - if (tabStop!=null - && tabStop.getVal()!=null // unlikely - && tabStop.getVal().equals(STTabJc.RIGHT) - && tabStop.getLeader()!=null // more likely - && tabStop.getLeader().equals(STTabTlc.DOT) ) { - - // - Element foLeader = document.createElementNS(XSL_FO, "leader"); - foLeader.setAttribute("leader-length.minimum", "12pt"); - foLeader.setAttribute("leader-length.maximum", "100%"); - foLeader.setAttribute("leader-length.optimum", "40pt"); - foLeader.setAttribute("leader-pattern", "dots"); - - getCurrentParent().appendChild(foLeader); - - } else { - getCurrentParent().appendChild(document.createTextNode(TAB_DUMMY)); - } - } - else { - getCurrentParent().appendChild(document.createTextNode(TAB_DUMMY)); - } - - } - } - - - @Override - protected Element handlePPr(FOConversionContext conversionContext, PPr pPrDirect, boolean sdt, - Element currentParent) { - Element ret = currentParent; - - PropertyResolver propertyResolver = conversionContext.getPropertyResolver(); - - - String defaultParagraphStyleId = "Normal"; - if (conversionContext.getWmlPackage().getMainDocumentPart().getStyleDefinitionsPart(false) != null) { - Style defaultParagraphStyle = - conversionContext.getWmlPackage().getMainDocumentPart().getStyleDefinitionsPart(false).getDefaultParagraphStyle(); - if (defaultParagraphStyle != null) { - defaultParagraphStyleId = defaultParagraphStyle.getStyleId(); - } - } - - String pStyleVal = null; - if (pPrDirect!=null && pPrDirect.getPStyle()!=null) { - pStyleVal = pPrDirect.getPStyle().getVal(); - } else { - pStyleVal = defaultParagraphStyleId; - } - getLog().debug("style '" + pStyleVal ); - - try { - -// PPr pPr = null; -// RPr rPr = null; - pPr = propertyResolver.getEffectivePPr(pPrDirect); - - getLog().debug("getting rPr for paragraph style"); - rPr = propertyResolver.getEffectiveRPr(null, pPrDirect); - // rPr in pPr direct formatting only applies to paragraph mark, - // and by virtue of that, to list item label, - // so pass null here - - // Now, work out the value for list item label - RPr rPrParagraphMark = XmlUtils.deepCopy(rPr); - // System.out.println("p rpr-->" + XmlUtils.marshaltoString(pPrDirect.getRPr())); - if (pPrDirect!=null) { - StyleUtil.apply(pPrDirect.getRPr(), rPrParagraphMark); - } - - if (getLog().isDebugEnabled() && pPr!=null) { - getLog().debug(XmlUtils.marshaltoString(pPr, true, true)); - } - - boolean inlist = false; - boolean indentHandledByNumbering = false; - - - Element foBlockElement = null; - Element foListBlock = null; - -// if (pPr!=null && pPr.getNumPr()!=null ) { - if (pPr!=null - && pPr.getNumPr()!=null - && pPr.getNumPr().getNumId()!=null - && pPr.getNumPr().getNumId().getVal().longValue()!=0 //zero means no numbering - ) { - - inlist = true; - - // Its a list item. At present we make a new list-block for - // each list-item. This is not great; DocumentModel will ultimately - // allow us to use fo:list-block properly. - - foListBlock = document.createElementNS(XSL_FO, - "list-block"); - currentParent.appendChild(foListBlock); - // That's different to XSL. - // Here we end up with block/list-block - // cf XSL, where the logic avoids creating 2 elements. - // May be easy to fix, if instead of passing in - // currentParent, we return block or list-block - // from here, and appendChild in the calling code. - -// foListBlock.setAttribute("provisional-distance-between-starts", "0.5in"); - - // Need to apply shading at fo:list-block level - if (pPr.getShd()!=null) { - PShading pShading = new PShading(pPr.getShd()); - pShading.setXslFO(foListBlock); - } - - Element foListItem = document.createElementNS(XSL_FO, - "list-item"); - foListBlock.appendChild(foListItem); - - - Element foListItemLabel = document.createElementNS(XSL_FO, - "list-item-label"); - foListItem.appendChild(foListItemLabel); - - Element foListItemLabelBody = document.createElementNS(XSL_FO, - "block"); - foListItemLabel.appendChild(foListItemLabelBody); - - Element foListItemBody = document.createElementNS("http://www.w3.org/1999/XSL/Format", - "fo:list-item-body"); - foListItem.appendChild(foListItemBody); - foListItemBody.setAttribute(Indent.FO_NAME, "body-start()"); - - ResultTriple triple; - if (pPrDirect!=null && pPrDirect.getNumPr()!=null) { - triple = org.docx4j.model.listnumbering.Emulator.getNumber( - conversionContext.getWmlPackage(), pStyleVal, - pPrDirect.getNumPr().getNumId().getVal().toString(), - pPrDirect.getNumPr().getIlvl().getVal().toString() ); - } else { - // Get the effective values; since we already know this, - // save the effort of doing this again in Emulator - Ilvl ilvl = pPr.getNumPr().getIlvl(); - String ilvlString = ilvl == null ? "0" : ilvl.getVal().toString(); - triple = null; - if (pPr.getNumPr().getNumId()!=null) { - triple = org.docx4j.model.listnumbering.Emulator.getNumber( - conversionContext.getWmlPackage(), pStyleVal, - pPr.getNumPr().getNumId().getVal().toString(), - ilvlString ); - } - } - - if (triple==null) { - getLog().warn("computed number ResultTriple was null"); - if (getLog().isDebugEnabled() ) { - foListItemLabelBody.setTextContent("nrt"); - } - } else { - - /* Format the list item label - * - * Since it turns out (in FOP at least) that the label and the body - * don't have the same vertical alignment - * unless font size is applied at the same level - * (ie to both -label and -body, or to the block inside each), - * we have to format the list-item-body as well. - * This issue only manifests itself if the font size on - * the outer list-block is larger than the font sizes - * set inside it. - */ - - // OK just to override specific values - // Values come from numbering rPr, unless overridden in p-level rpr - if(triple.getRPr()==null) { - - if (pPr.getRPr()==null) { - // do nothing, since we're already inheriting the formatting in the style - // (as opposed to the paragraph mark formatting) - // EXCEPT for font - XsltFOFunctions.setFont( conversionContext, foListItemLabelBody, pPr, rPr, triple.getNumString()); - } else { - - createFoAttributes(conversionContext.getWmlPackage(), rPrParagraphMark, foListItemLabel ); - createFoAttributes(conversionContext.getWmlPackage(), rPrParagraphMark, foListItemBody ); - - XsltFOFunctions.setFont( conversionContext, foListItemLabelBody, pPr, rPrParagraphMark, triple.getNumString()); - } - - } else { - RPr actual = XmlUtils.deepCopy(triple.getRPr()); // clone, so the ilvl rpr is not altered -// System.out.println(XmlUtils.marshaltoString(rPrParagraphMark)); - - // pMark overrides numbering, except for font - // (which makes sense, since that would change the bullet) - // so set the font - XsltFOFunctions.setFont( conversionContext, foListItemLabelBody, pPr, actual, triple.getNumString()); - // .. before taking rPrParagraphMark into account - StyleUtil.apply(rPrParagraphMark, actual); -// System.out.println(XmlUtils.marshaltoString(actual)); - - createFoAttributes(conversionContext.getWmlPackage(), actual, foListItemLabel ); - createFoAttributes(conversionContext.getWmlPackage(), actual, foListItemBody ); - } - -/* - // Indent (in combination with provisional-distance-between-starts - // above - if (triple.getIndent()!=null) { - Indent indent = new Indent(triple.getIndent()); - //foListBlock.setAttribute(Indent.FO_NAME, "2in"); - indent.setXslFO(foListBlock); - } - - */ - } - - int numChars=1; - if (triple.getBullet()!=null ) { - foListItemLabelBody.setTextContent(triple.getBullet() ); - } else if (triple.getNumString()==null) { - getLog().warn("computed NumString was null!"); - if (getLog().isDebugEnabled() ) { - foListItemLabelBody.setTextContent("nns"); - } - numChars=0; - } else { - Text number = document.createTextNode( triple.getNumString() ); - foListItemLabelBody.appendChild(number); - numChars = triple.getNumString().length(); - } - - // Indent (setting provisional-distance-between-starts) - // Indent on direct pPr trumps indent in pPr in numbering, which trumps indent - // specified in a style. Well, not exactly, components which aren't set in - // the direct formatting will be contributed by the numbering's indent settings - Indent indent = new Indent(pPrDirect.getInd(), triple.getIndent()); - if (indent.isHanging() ) { - indent.setXslFOListBlock(foListBlock, -1); - } else { - - int numWidth = 90 * numChars; // crude .. TODO take font size into account - - int pdbs = XsltFOFunctions.getDistanceToNextTabStop(conversionContext, indent.getNumberPosition(), numWidth, - pPrDirect.getTabs(), conversionContext.getWmlPackage().getMainDocumentPart().getDocumentSettingsPart()); - indent.setXslFOListBlock(foListBlock, pdbs); - } - indentHandledByNumbering = true; - - foBlockElement = document.createElementNS(XSL_FO, - "block"); - foListItemBody.appendChild(foBlockElement); - //If we have list items the parent for spans changes (currentP) - ret = foBlockElement; - - } else { - - // Do nothing - } - - - if (pPr!=null) { - // Ignore paragraph borders once inside the container - boolean ignoreBorders = !sdt; - - createFoAttributes(conversionContext, pPr, currentParent, inlist, ignoreBorders ); - } - - if (rPr!=null) { -// createFoAttributes(conversionContext.getWmlPackage(), rPr, currentParent ); - - if (foListBlock==null) { - createFoAttributes(conversionContext.getWmlPackage(), rPr, currentParent ); - } else { - createFoAttributes(conversionContext.getWmlPackage(), rPr, ((Element)foListBlock) ); - } - - } - - - } catch (Exception e) { - getLog().error(e.getMessage(), e); - } - - return ret; - } - - - protected void createFoAttributes(FOConversionContext conversionContext, PPr pPr, Element foBlockElement, boolean inList, boolean ignoreBorders){ - - List properties = PropertyFactory.createProperties(conversionContext.getWmlPackage(), pPr); - - for( Property p : properties ) { - if (p!=null) { - - if (ignoreBorders && - ((p instanceof PBorderTop) - || (p instanceof PBorderBottom))) { - continue; - } - - if (inList && !(p instanceof Indent) ) { - // Don't set start-indent in - // fo:list-item-body/fo:block. - // This has to be handled above using something like - // - p.setXslFO(foBlockElement); - } else if (!inList) { - p.setXslFO(foBlockElement); - } - } - } - - if (pPr==null) return; - - // Special case, since bidi is translated to align right - // Handle interaction between w:pPr/w:bidi and w:pPr/w:jc/@w:val='right' - if (pPr.getBidi()!=null && pPr.getBidi().isVal()) { - - if (pPr.getJc()!=null) { - if (pPr.getJc().getVal().equals(JcEnumeration.RIGHT)) { - // set it to left! - foBlockElement.setAttribute(Justification.FO_NAME, "left"); - } else if (pPr.getJc().getVal().equals(JcEnumeration.LEFT)) { - // set it to right! - foBlockElement.setAttribute(Justification.FO_NAME, "right"); - } - } - } - - // Table of contents dot leader needs text-align-last="justify" - // Are we in a TOC? - if (pPr.getTabs()!=null - - // PStyle is not included in our effective pPr! -// && pPr.getPStyle()!=null -// && pPr.getPStyle().getVal()!=null -// && pPr.getPStyle().getVal().startsWith("TOC") - ) { - - CTTabStop tabStop = pPr.getTabs().getTab().get(0); - if (tabStop!=null - //&& tabStop.getLeader().equals(STTabTlc.DOT) - && tabStop.getVal().equals(STTabJc.RIGHT) ) { - - foBlockElement.setAttribute("text-align-last", "justify"); - } - } - - - } - - /* - * @since 3.0.0 - */ - protected static void applyFoAttributes(List properties, Element foElement) { - if ((properties != null) && (!properties.isEmpty())) { - for (int i=0; i properties = PropertyFactory.createProperties(wmlPackage, rPr); - - for( Property p : properties ) { - p.setXslFO(foInlineElement); - } - - } - - @Override - protected void rtlAwareAppendChildToCurrentP(Element spanEl) { - - // Arabic (and presumably Hebrew) fix - // If we have inline direction="rtl" (created by TextDirection class) - // wrap the inline with: - // - /* See further: - From: Glenn Adams - Date: Fri, Mar 21, 2014 at 8:41 AM - Subject: Re: right align arabic in table-cell - To: FOP Users - */ - - if (rPr!=null - && rPr.getRtl()!=null - && rPr.getRtl().isVal()) { - - spanEl.removeAttribute("direction"); - - Element bidiOverride = document.createElementNS("http://www.w3.org/1999/XSL/Format", - "fo:bidi-override"); - bidiOverride.setAttribute("unicode-bidi", "embed" ); - bidiOverride.setAttribute("direction", "rtl" ); - - bidiOverride.appendChild(spanEl); - - currentP.appendChild( bidiOverride ); - - } else { - // Usual case - currentP.appendChild( spanEl ); - } - - } -} diff --git a/All/Genesis-NP/Genesis#291/old/FOExporterVisitorGenerator.java b/All/Genesis-NP/Genesis#291/old/FOExporterVisitorGenerator.java deleted file mode 100755 index d38570f..0000000 --- a/All/Genesis-NP/Genesis#291/old/FOExporterVisitorGenerator.java +++ /dev/null @@ -1,667 +0,0 @@ -/* - Licensed to Plutext Pty Ltd under one or more contributor license agreements. - - * This file is part of docx4j. - - docx4j is licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - - You may obtain a copy of the License at - - 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.docx4j.convert.out.fo; - -import java.util.List; - -import org.docx4j.XmlUtils; -import org.docx4j.convert.out.common.AbstractVisitorExporterDelegate; -import org.docx4j.convert.out.common.AbstractVisitorExporterDelegate.AbstractVisitorExporterGeneratorFactory; -import org.docx4j.convert.out.common.AbstractVisitorExporterGenerator; -import org.docx4j.convert.out.common.writer.AbstractBrWriter; -import org.docx4j.model.PropertyResolver; -import org.docx4j.model.images.WordXmlPictureE10; -import org.docx4j.model.images.WordXmlPictureE20; -import org.docx4j.model.listnumbering.Emulator.ResultTriple; -import org.docx4j.model.properties.Property; -import org.docx4j.model.properties.PropertyFactory; -import org.docx4j.model.properties.paragraph.Indent; -import org.docx4j.model.properties.paragraph.Justification; -import org.docx4j.model.properties.paragraph.PBorderBottom; -import org.docx4j.model.properties.paragraph.PBorderTop; -import org.docx4j.model.properties.paragraph.PShading; -import org.docx4j.model.styles.StyleUtil; -import org.docx4j.openpackaging.packages.WordprocessingMLPackage; -import org.docx4j.wml.Br; -import org.docx4j.wml.CTTabStop; -import org.docx4j.wml.JcEnumeration; -import org.docx4j.wml.P; -import org.docx4j.wml.PPr; -import org.docx4j.wml.PPrBase.NumPr.Ilvl; -import org.docx4j.wml.R; -import org.docx4j.wml.RPr; -import org.docx4j.wml.STBrType; -import org.docx4j.wml.STTabJc; -import org.docx4j.wml.STTabTlc; -import org.docx4j.wml.Style; -import org.docx4j.wml.TcPr; -import org.docx4j.wml.TrPr; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.DOMException; -import org.w3c.dom.Document; -import org.w3c.dom.DocumentFragment; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.Text; - -public class FOExporterVisitorGenerator extends AbstractVisitorExporterGenerator{ - - private static Logger log = LoggerFactory.getLogger(FOExporterVisitorGenerator.class); - - - private static String XSL_FO = "http://www.w3.org/1999/XSL/Format"; - - public static final AbstractVisitorExporterDelegate.AbstractVisitorExporterGeneratorFactory GENERATOR_FACTORY = - new AbstractVisitorExporterGeneratorFactory() { - @Override - public AbstractVisitorExporterGenerator createInstance( - FOConversionContext conversionContext, - Document document, Node parentNode) { - return new FOExporterVisitorGenerator(conversionContext, document, parentNode); - } - }; - - - private FOExporterVisitorGenerator(FOConversionContext conversionContext, Document document, Node parentNode) { - super(conversionContext, document, parentNode); - } - - @Override - protected AbstractVisitorExporterGeneratorFactory getFactory() { - return GENERATOR_FACTORY; - } - - @Override - protected DocumentFragment createImage(int imgType, FOConversionContext conversionContext, Object anchorOrInline) { - switch (imgType) { - case IMAGE_E10: - return WordXmlPictureE10.createXslFoImgE10(conversionContext, anchorOrInline); - case IMAGE_E20: - return WordXmlPictureE20.createXslFoImgE20(conversionContext, anchorOrInline); - } - return null; - } - - @Override - protected Element createNode(Document doc, int nodeType) { - switch (nodeType) { - case NODE_BLOCK: - return document.createElementNS(XSL_FO, "block"); - case NODE_INLINE: - return document.createElementNS(XSL_FO, "inline"); - } - return null; - } - - @Override - protected void handleBr(Br br) { - - - /* Is there a w:br immediately before this one? - - If this is the first child of this w:r, and the w:r is preceded by another w:r, look at its last child - - If this is not the first child of this w:r, look at the preceding sibling -*/ - - boolean firstBr = true; // until proven otherwise - - R r = (R)br.getParent(); - int pos = getPos(r.getContent(), br); - if (pos<0) { - log.error("Couldn't locate w:br in w:r"); - } - else if (pos==0) { - // Need to look in preceding run - Object rParent = r.getParent(); - // Handle just the case where this is w:p for now - if(rParent instanceof P) { - P parentP = (P)rParent; - pos = getPos(parentP.getContent(), r); - if (pos<0) { - log.error("Couldn't locate w:r in w:p"); - } else if (pos>0) { - Object beforeR = parentP.getContent().get(pos-1); - if (beforeR instanceof R) { - List list = ((R)beforeR).getContent(); - Object previous = list.get(list.size()-1); - if (previous instanceof Br) { - firstBr=false; - } - } else { -// System.out.println(beforeR.getClass().getName()); - - } - } - } else { - log.info("TODO: handle run parent " + rParent.getClass().getName()); - } - } else { - Object previous = r.getContent().get(pos-1); - if (previous instanceof Br) { - firstBr=false; - } else { -// System.out.println("previous: " + previous.getClass().getName()); - } - } - - if ((!firstBr) && - (br.getType()==null - || br.getType().equals(STBrType.TEXT_WRAPPING))) { - - // ie a soft-return following another - // - Element ret = createNode(document, NODE_BLOCK); - // see http://stackoverflow.com/a/3664468/1031689 answer - // at http://stackoverflow.com/questions/3661483/inserting-a-line-break-in-a-pdf-generated-from-xsl-fo-using-xslvalue-of - ret.setAttribute("linefeed-treatment", "preserve"); - ret.setAttribute("white-space-treatment", "preserve"); - ret.setTextContent("\n"); - - getCurrentParent().appendChild(ret); // should be spanEl - - } else { - // Usual case - convertToNode(conversionContext, - br, AbstractBrWriter.WRITER_ID, - document, getCurrentParent() ); - - } - - if ((br.getType()!=null - && br.getType().equals(STBrType.PAGE))) { - currentSpan=null; - } - } - - - @Override - protected void convertTabToNode(FOConversionContext conversionContext, Document document) throws DOMException { - - if (!conversionContext.isInComplexFieldDefinition()) { - - if (pPr!=null && pPr.getTabs()!=null) { - - // xsl:when test="count($p/w:pPr/w:tabs/w:tab[1][@w:leader='dot' and @w:val='right'])=1" - CTTabStop tabStop = pPr.getTabs().getTab().get(0); - if (tabStop!=null - && tabStop.getLeader().equals(STTabTlc.DOT) - && tabStop.getVal().equals(STTabJc.RIGHT) ) { - - // - Element foLeader = document.createElementNS(XSL_FO, "leader"); - foLeader.setAttribute("leader-length.minimum", "12pt"); - foLeader.setAttribute("leader-length.maximum", "100%"); - foLeader.setAttribute("leader-length.optimum", "40pt"); - foLeader.setAttribute("leader-pattern", "dots"); - - getCurrentParent().appendChild(foLeader); - - } else { - getCurrentParent().appendChild(document.createTextNode(TAB_DUMMY)); - } - } - else { - getCurrentParent().appendChild(document.createTextNode(TAB_DUMMY)); - } - - } - } - - - @Override - protected Element handlePPr(FOConversionContext conversionContext, PPr pPrDirect, boolean sdt, - Element currentParent) { - Element ret = currentParent; - - PropertyResolver propertyResolver = conversionContext.getPropertyResolver(); - - - String defaultParagraphStyleId = "Normal"; - if (conversionContext.getWmlPackage().getMainDocumentPart().getStyleDefinitionsPart(false) != null) { - Style defaultParagraphStyle = - conversionContext.getWmlPackage().getMainDocumentPart().getStyleDefinitionsPart(false).getDefaultParagraphStyle(); - if (defaultParagraphStyle != null) { - defaultParagraphStyleId = defaultParagraphStyle.getStyleId(); - } - } - - String pStyleVal = null; - if (pPrDirect!=null && pPrDirect.getPStyle()!=null) { - pStyleVal = pPrDirect.getPStyle().getVal(); - } else { - pStyleVal = defaultParagraphStyleId; - } - getLog().debug("style '" + pStyleVal ); - - try { - -// PPr pPr = null; -// RPr rPr = null; - pPr = propertyResolver.getEffectivePPr(pPrDirect); - - getLog().debug("getting rPr for paragraph style"); - rPr = propertyResolver.getEffectiveRPr(null, pPrDirect); - // rPr in pPr direct formatting only applies to paragraph mark, - // and by virtue of that, to list item label, - // so pass null here - - // Now, work out the value for list item label - RPr rPrParagraphMark = XmlUtils.deepCopy(rPr); - // System.out.println("p rpr-->" + XmlUtils.marshaltoString(pPrDirect.getRPr())); - if (pPrDirect!=null) { - StyleUtil.apply(pPrDirect.getRPr(), rPrParagraphMark); - } - - if (getLog().isDebugEnabled() && pPr!=null) { - getLog().debug(XmlUtils.marshaltoString(pPr, true, true)); - } - - boolean inlist = false; - boolean indentHandledByNumbering = false; - - - Element foBlockElement = null; - Element foListBlock = null; - -// if (pPr!=null && pPr.getNumPr()!=null ) { - if (pPr!=null - && pPr.getNumPr()!=null - && pPr.getNumPr().getNumId()!=null - && pPr.getNumPr().getNumId().getVal().longValue()!=0 //zero means no numbering - ) { - - inlist = true; - - // Its a list item. At present we make a new list-block for - // each list-item. This is not great; DocumentModel will ultimately - // allow us to use fo:list-block properly. - - foListBlock = document.createElementNS(XSL_FO, - "list-block"); - currentParent.appendChild(foListBlock); - // That's different to XSL. - // Here we end up with block/list-block - // cf XSL, where the logic avoids creating 2 elements. - // May be easy to fix, if instead of passing in - // currentParent, we return block or list-block - // from here, and appendChild in the calling code. - -// foListBlock.setAttribute("provisional-distance-between-starts", "0.5in"); - - // Need to apply shading at fo:list-block level - if (pPr.getShd()!=null) { - PShading pShading = new PShading(pPr.getShd()); - pShading.setXslFO(foListBlock); - } - - Element foListItem = document.createElementNS(XSL_FO, - "list-item"); - foListBlock.appendChild(foListItem); - - - Element foListItemLabel = document.createElementNS(XSL_FO, - "list-item-label"); - foListItem.appendChild(foListItemLabel); - - Element foListItemLabelBody = document.createElementNS(XSL_FO, - "block"); - foListItemLabel.appendChild(foListItemLabelBody); - - Element foListItemBody = document.createElementNS("http://www.w3.org/1999/XSL/Format", - "fo:list-item-body"); - foListItem.appendChild(foListItemBody); - foListItemBody.setAttribute(Indent.FO_NAME, "body-start()"); - - ResultTriple triple; - if (pPrDirect!=null && pPrDirect.getNumPr()!=null) { - triple = org.docx4j.model.listnumbering.Emulator.getNumber( - conversionContext.getWmlPackage(), pStyleVal, - pPrDirect.getNumPr().getNumId().getVal().toString(), - pPrDirect.getNumPr().getIlvl().getVal().toString() ); - } else { - // Get the effective values; since we already know this, - // save the effort of doing this again in Emulator - Ilvl ilvl = pPr.getNumPr().getIlvl(); - String ilvlString = ilvl == null ? "0" : ilvl.getVal().toString(); - triple = null; - if (pPr.getNumPr().getNumId()!=null) { - triple = org.docx4j.model.listnumbering.Emulator.getNumber( - conversionContext.getWmlPackage(), pStyleVal, - pPr.getNumPr().getNumId().getVal().toString(), - ilvlString ); - } - } - - if (triple==null) { - getLog().warn("computed number ResultTriple was null"); - if (getLog().isDebugEnabled() ) { - foListItemLabelBody.setTextContent("nrt"); - } - } else { - - /* Format the list item label - * - * Since it turns out (in FOP at least) that the label and the body - * don't have the same vertical alignment - * unless font size is applied at the same level - * (ie to both -label and -body, or to the block inside each), - * we have to format the list-item-body as well. - * This issue only manifests itself if the font size on - * the outer list-block is larger than the font sizes - * set inside it. - */ - - // OK just to override specific values - // Values come from numbering rPr, unless overridden in p-level rpr - if(triple.getRPr()==null) { - - if (pPr.getRPr()==null) { - // do nothing, since we're already inheriting the formatting in the style - // (as opposed to the paragraph mark formatting) - // EXCEPT for font - XsltFOFunctions.setFont( conversionContext, foListItemLabelBody, pPr, rPr, triple.getNumString()); - } else { - - createFoAttributes(conversionContext.getWmlPackage(), rPrParagraphMark, foListItemLabel ); - createFoAttributes(conversionContext.getWmlPackage(), rPrParagraphMark, foListItemBody ); - - XsltFOFunctions.setFont( conversionContext, foListItemLabelBody, pPr, rPrParagraphMark, triple.getNumString()); - } - - } else { - RPr actual = XmlUtils.deepCopy(triple.getRPr()); // clone, so the ilvl rpr is not altered -// System.out.println(XmlUtils.marshaltoString(rPrParagraphMark)); - - // pMark overrides numbering, except for font - // (which makes sense, since that would change the bullet) - // so set the font - XsltFOFunctions.setFont( conversionContext, foListItemLabelBody, pPr, actual, triple.getNumString()); - // .. before taking rPrParagraphMark into account - StyleUtil.apply(rPrParagraphMark, actual); -// System.out.println(XmlUtils.marshaltoString(actual)); - - createFoAttributes(conversionContext.getWmlPackage(), actual, foListItemLabel ); - createFoAttributes(conversionContext.getWmlPackage(), actual, foListItemBody ); - } - -/* - // Indent (in combination with provisional-distance-between-starts - // above - if (triple.getIndent()!=null) { - Indent indent = new Indent(triple.getIndent()); - //foListBlock.setAttribute(Indent.FO_NAME, "2in"); - indent.setXslFO(foListBlock); - } - - */ - } - - int numChars=1; - if (triple.getBullet()!=null ) { - foListItemLabelBody.setTextContent(triple.getBullet() ); - } else if (triple.getNumString()==null) { - getLog().warn("computed NumString was null!"); - if (getLog().isDebugEnabled() ) { - foListItemLabelBody.setTextContent("nns"); - } - numChars=0; - } else { - Text number = document.createTextNode( triple.getNumString() ); - foListItemLabelBody.appendChild(number); - numChars = triple.getNumString().length(); - } - - // Indent (setting provisional-distance-between-starts) - // Indent on direct pPr trumps indent in pPr in numbering, which trumps indent - // specified in a style. Well, not exactly, components which aren't set in - // the direct formatting will be contributed by the numbering's indent settings - Indent indent = new Indent(pPrDirect.getInd(), triple.getIndent()); - if (indent.isHanging() ) { - indent.setXslFOListBlock(foListBlock, -1); - } else { - - int numWidth = 90 * numChars; // crude .. TODO take font size into account - - int pdbs = XsltFOFunctions.getDistanceToNextTabStop(conversionContext, indent.getNumberPosition(), numWidth, - pPrDirect.getTabs(), conversionContext.getWmlPackage().getMainDocumentPart().getDocumentSettingsPart()); - indent.setXslFOListBlock(foListBlock, pdbs); - } - indentHandledByNumbering = true; - - foBlockElement = document.createElementNS(XSL_FO, - "block"); - foListItemBody.appendChild(foBlockElement); - //If we have list items the parent for spans changes (currentP) - ret = foBlockElement; - - } else { - - // Do nothing - } - - - if (pPr!=null) { - // Ignore paragraph borders once inside the container - boolean ignoreBorders = !sdt; - - createFoAttributes(conversionContext, pPr, currentParent, inlist, ignoreBorders ); - } - - if (rPr!=null) { -// createFoAttributes(conversionContext.getWmlPackage(), rPr, currentParent ); - - if (foListBlock==null) { - createFoAttributes(conversionContext.getWmlPackage(), rPr, currentParent ); - } else { - createFoAttributes(conversionContext.getWmlPackage(), rPr, ((Element)foListBlock) ); - } - - } - - - } catch (Exception e) { - getLog().error(e.getMessage(), e); - } - - return ret; - } - - - protected void createFoAttributes(FOConversionContext conversionContext, PPr pPr, Element foBlockElement, boolean inList, boolean ignoreBorders){ - - List properties = PropertyFactory.createProperties(conversionContext.getWmlPackage(), pPr); - - for( Property p : properties ) { - if (p!=null) { - - if (ignoreBorders && - ((p instanceof PBorderTop) - || (p instanceof PBorderBottom))) { - continue; - } - - if (inList && !(p instanceof Indent) ) { - // Don't set start-indent in - // fo:list-item-body/fo:block. - // This has to be handled above using something like - // - p.setXslFO(foBlockElement); - } else if (!inList) { - p.setXslFO(foBlockElement); - } - } - } - - if (pPr==null) return; - - // Special case, since bidi is translated to align right - // Handle interaction between w:pPr/w:bidi and w:pPr/w:jc/@w:val='right' - if (pPr.getBidi()!=null && pPr.getBidi().isVal()) { - - if (pPr.getJc()!=null) { - if (pPr.getJc().getVal().equals(JcEnumeration.RIGHT)) { - // set it to left! - foBlockElement.setAttribute(Justification.FO_NAME, "left"); - } else if (pPr.getJc().getVal().equals(JcEnumeration.LEFT)) { - // set it to right! - foBlockElement.setAttribute(Justification.FO_NAME, "right"); - } - } - } - - // Table of contents dot leader needs text-align-last="justify" - // Are we in a TOC? - if (pPr.getTabs()!=null - - // PStyle is not included in our effective pPr! -// && pPr.getPStyle()!=null -// && pPr.getPStyle().getVal()!=null -// && pPr.getPStyle().getVal().startsWith("TOC") - ) { - - CTTabStop tabStop = pPr.getTabs().getTab().get(0); - if (tabStop!=null - //&& tabStop.getLeader().equals(STTabTlc.DOT) - && tabStop.getVal().equals(STTabJc.RIGHT) ) { - - foBlockElement.setAttribute("text-align-last", "justify"); - } - } - - - } - - /* - * @since 3.0.0 - */ - protected static void applyFoAttributes(List properties, Element foElement) { - if ((properties != null) && (!properties.isEmpty())) { - for (int i=0; i properties = PropertyFactory.createProperties(wmlPackage, rPr); - - for( Property p : properties ) { - p.setXslFO(foInlineElement); - } - - } - - @Override - protected void rtlAwareAppendChildToCurrentP(Element spanEl) { - - // Arabic (and presumably Hebrew) fix - // If we have inline direction="rtl" (created by TextDirection class) - // wrap the inline with: - // - /* See further: - From: Glenn Adams - Date: Fri, Mar 21, 2014 at 8:41 AM - Subject: Re: right align arabic in table-cell - To: FOP Users - */ - - if (rPr!=null - && rPr.getRtl()!=null - && rPr.getRtl().isVal()) { - - spanEl.removeAttribute("direction"); - - Element bidiOverride = document.createElementNS("http://www.w3.org/1999/XSL/Format", - "fo:bidi-override"); - bidiOverride.setAttribute("unicode-bidi", "embed" ); - bidiOverride.setAttribute("direction", "rtl" ); - - bidiOverride.appendChild(spanEl); - - currentP.appendChild( bidiOverride ); - - } else { - // Usual case - currentP.appendChild( spanEl ); - } - - } -} diff --git a/All/Genesis-NP/Genesis#291/pair.info b/All/Genesis-NP/Genesis#291/pair.info deleted file mode 100755 index 11877e5..0000000 --- a/All/Genesis-NP/Genesis#291/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:291 -SATName:Genesis -modifiedFPath:src/main/java/org/docx4j/convert/out/fo/FOExporterVisitorGenerator.java -comSha:3eebcf65e21a01906813d012fbfe95a5277ad25e -parentComSha:3eebcf65e21a01906813d012fbfe95a5277ad25e^1 -githubUrl:https://github.com/plutext/docx4j -repoName:plutext#docx4j \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#297/comMsg.txt b/All/Genesis-NP/Genesis#297/comMsg.txt deleted file mode 100755 index fee5784..0000000 --- a/All/Genesis-NP/Genesis#297/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix NPE on JMX reloadDefaultConfiguration when no configuration file is used diff --git a/All/Genesis-NP/Genesis#297/diff.diff b/All/Genesis-NP/Genesis#297/diff.diff deleted file mode 100755 index 73e2f7a..0000000 --- a/All/Genesis-NP/Genesis#297/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/jmx/JMXConfigurator.java b/logback-classic/src/main/java/ch/qos/logback/classic/jmx/JMXConfigurator.java -index 9f241c3..c6a4be2 100644 ---- a/logback-classic/src/main/java/ch/qos/logback/classic/jmx/JMXConfigurator.java -+++ b/logback-classic/src/main/java/ch/qos/logback/classic/jmx/JMXConfigurator.java -@@ -3 +3 @@ -- * Copyright (C) 1999-2015, QOS.ch. All rights reserved. -+ * Copyright (C) 1999-2016, QOS.ch. All rights reserved. -@@ -142,0 +143,3 @@ public class JMXConfigurator extends ContextAwareBase implements -+ -+ // use configurator only if a url is defined -+ if (url != null) { -@@ -157,0 +161 @@ public class JMXConfigurator extends ContextAwareBase implements -+ } diff --git a/All/Genesis-NP/Genesis#297/new/JMXConfigurator.java b/All/Genesis-NP/Genesis#297/new/JMXConfigurator.java deleted file mode 100755 index c6a4be2..0000000 --- a/All/Genesis-NP/Genesis#297/new/JMXConfigurator.java +++ /dev/null @@ -1,304 +0,0 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2016, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.jmx; - -import java.io.File; -import java.io.FileNotFoundException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.management.InstanceNotFoundException; -import javax.management.MBeanRegistrationException; -import javax.management.MBeanServer; -import javax.management.ObjectName; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.joran.JoranConfigurator; -import ch.qos.logback.classic.spi.LoggerContextListener; -import ch.qos.logback.classic.util.ContextInitializer; -import ch.qos.logback.core.joran.spi.JoranException; -import ch.qos.logback.core.spi.ContextAwareBase; -import ch.qos.logback.core.status.Status; -import ch.qos.logback.core.status.StatusListener; -import ch.qos.logback.core.status.StatusListenerAsList; -import ch.qos.logback.core.status.StatusManager; -import ch.qos.logback.core.util.StatusPrinter; - -/** - * A class that provides access to logback components via JMX. - * - *

Since this class implements {@link JMXConfiguratorMBean} it has to be - * named as JMXConfigurator}. - * - * @author Ceki Gülcü - * @author Sébastien Pennec - * - * Contributor: Sebastian Davids See http://bugzilla.qos.ch/show_bug.cgi?id=35 - */ -public class JMXConfigurator extends ContextAwareBase implements - JMXConfiguratorMBean, LoggerContextListener { - - private static String EMPTY = ""; - - LoggerContext loggerContext; - MBeanServer mbs; - ObjectName objectName; - String objectNameAsString; - - // whether to output status events on the console when reloading the - // configuration - boolean debug = true; - - boolean started; - - public JMXConfigurator(LoggerContext loggerContext, MBeanServer mbs, - ObjectName objectName) { - started = true; - this.context = loggerContext; - this.loggerContext = loggerContext; - this.mbs = mbs; - this.objectName = objectName; - this.objectNameAsString = objectName.toString(); - if (previouslyRegisteredListenerWithSameObjectName()) { - addError("Previously registered JMXConfigurator named [" - + objectNameAsString + "] in the logger context named [" - + loggerContext.getName() + "]"); - } else { - // register as a listener only if there are no homonyms - loggerContext.addListener(this); - } - } - - private boolean previouslyRegisteredListenerWithSameObjectName() { - List lcll = loggerContext.getCopyOfListenerList(); - for (LoggerContextListener lcl : lcll) { - if (lcl instanceof JMXConfigurator) { - JMXConfigurator jmxConfigurator = (JMXConfigurator) lcl; - if (objectName.equals(jmxConfigurator.objectName)) { - return true; - } - } - } - return false; - } - - public void reloadDefaultConfiguration() throws JoranException { - ContextInitializer ci = new ContextInitializer(loggerContext); - URL url = ci.findURLOfDefaultConfigurationFile(true); - reloadByURL(url); - } - - public void reloadByFileName(String fileName) throws JoranException, - FileNotFoundException { - File f = new File(fileName); - if (f.exists() && f.isFile()) { - URL url; - try { - url = f.toURI().toURL(); - reloadByURL(url); - } catch (MalformedURLException e) { - throw new RuntimeException( - "Unexpected MalformedURLException occured. See nexted cause.", e); - } - - } else { - String errMsg = "Could not find [" + fileName + "]"; - addInfo(errMsg); - throw new FileNotFoundException(errMsg); - } - } - - void addStatusListener(StatusListener statusListener) { - StatusManager sm = loggerContext.getStatusManager(); - sm.add(statusListener); - } - - void removeStatusListener(StatusListener statusListener) { - StatusManager sm = loggerContext.getStatusManager(); - sm.remove(statusListener); - } - - public void reloadByURL(URL url) throws JoranException { - StatusListenerAsList statusListenerAsList = new StatusListenerAsList(); - - addStatusListener(statusListenerAsList); - addInfo("Resetting context: " + loggerContext.getName()); - loggerContext.reset(); - - // use configurator only if a url is defined - if (url != null) { - // after a reset the statusListenerAsList gets removed as a listener - addStatusListener(statusListenerAsList); - - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(loggerContext); - configurator.doConfigure(url); - addInfo("Context: " + loggerContext.getName() + " reloaded."); - } finally { - removeStatusListener(statusListenerAsList); - if (debug) { - StatusPrinter.print(statusListenerAsList.getStatusList()); - } - } - } - } - - public void setLoggerLevel(String loggerName, String levelStr) { - if (loggerName == null) { - return; - } - if (levelStr == null) { - return; - } - loggerName = loggerName.trim(); - levelStr = levelStr.trim(); - - addInfo("Trying to set level " + levelStr + " to logger " + loggerName); - LoggerContext lc = (LoggerContext) context; - - Logger logger = lc.getLogger(loggerName); - if ("null".equalsIgnoreCase(levelStr)) { - logger.setLevel(null); - } else { - Level level = Level.toLevel(levelStr, null); - if (level != null) { - logger.setLevel(level); - } - } - } - - public String getLoggerLevel(String loggerName) { - if (loggerName == null) { - return EMPTY; - } - - loggerName = loggerName.trim(); - - LoggerContext lc = (LoggerContext) context; - Logger logger = lc.exists(loggerName); - if (logger != null && logger.getLevel() != null) { - return logger.getLevel().toString(); - } else { - return EMPTY; - } - } - - public String getLoggerEffectiveLevel(String loggerName) { - if (loggerName == null) { - return EMPTY; - } - - loggerName = loggerName.trim(); - - LoggerContext lc = (LoggerContext) context; - Logger logger = lc.exists(loggerName); - if (logger != null) { - return logger.getEffectiveLevel().toString(); - } else { - return EMPTY; - } - } - - public List getLoggerList() { - LoggerContext lc = (LoggerContext) context; - List strList = new ArrayList(); - Iterator it = lc.getLoggerList().iterator(); - while (it.hasNext()) { - Logger log = it.next(); - strList.add(log.getName()); - } - return strList; - } - - public List getStatuses() { - List list = new ArrayList(); - Iterator it = context.getStatusManager().getCopyOfStatusList() - .iterator(); - while (it.hasNext()) { - list.add(it.next().toString()); - } - return list; - } - - /** - * When the associated LoggerContext is stopped, this configurator must be - * unregistered - */ - public void onStop(LoggerContext context) { - if (!started) { - addInfo("onStop() method called on a stopped JMXActivator [" - + objectNameAsString + "]"); - return; - } - if (mbs.isRegistered(objectName)) { - try { - addInfo("Unregistering mbean [" + objectNameAsString + "]"); - mbs.unregisterMBean(objectName); - } catch (InstanceNotFoundException e) { - // this is theoretically impossible - addError("Unable to find a verifiably registered mbean [" - + objectNameAsString + "]", e); - } catch (MBeanRegistrationException e) { - addError("Failed to unregister [" + objectNameAsString + "]", e); - } - } else { - addInfo("mbean [" + objectNameAsString - + "] was not in the mbean registry. This is OK."); - } - stop(); - } - - public void onLevelChange(Logger logger, Level level) { - // nothing to do - } - - public void onReset(LoggerContext context) { - addInfo("onReset() method called JMXActivator [" + objectNameAsString + "]"); - } - - /** - * JMXConfigurator should not be removed subsequent to a LoggerContext reset. - * - * @return - */ - public boolean isResetResistant() { - return true; - } - - private void clearFields() { - mbs = null; - objectName = null; - loggerContext = null; - } - - private void stop() { - started = false; - clearFields(); - } - - public void onStart(LoggerContext context) { - // nop - } - - @Override - public String toString() { - return this.getClass().getName() + "(" + context.getName() + ")"; - } -} diff --git a/All/Genesis-NP/Genesis#297/old/JMXConfigurator.java b/All/Genesis-NP/Genesis#297/old/JMXConfigurator.java deleted file mode 100755 index 9f241c3..0000000 --- a/All/Genesis-NP/Genesis#297/old/JMXConfigurator.java +++ /dev/null @@ -1,300 +0,0 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2015, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.jmx; - -import java.io.File; -import java.io.FileNotFoundException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import javax.management.InstanceNotFoundException; -import javax.management.MBeanRegistrationException; -import javax.management.MBeanServer; -import javax.management.ObjectName; - -import ch.qos.logback.classic.Level; -import ch.qos.logback.classic.Logger; -import ch.qos.logback.classic.LoggerContext; -import ch.qos.logback.classic.joran.JoranConfigurator; -import ch.qos.logback.classic.spi.LoggerContextListener; -import ch.qos.logback.classic.util.ContextInitializer; -import ch.qos.logback.core.joran.spi.JoranException; -import ch.qos.logback.core.spi.ContextAwareBase; -import ch.qos.logback.core.status.Status; -import ch.qos.logback.core.status.StatusListener; -import ch.qos.logback.core.status.StatusListenerAsList; -import ch.qos.logback.core.status.StatusManager; -import ch.qos.logback.core.util.StatusPrinter; - -/** - * A class that provides access to logback components via JMX. - * - *

Since this class implements {@link JMXConfiguratorMBean} it has to be - * named as JMXConfigurator}. - * - * @author Ceki Gülcü - * @author Sébastien Pennec - * - * Contributor: Sebastian Davids See http://bugzilla.qos.ch/show_bug.cgi?id=35 - */ -public class JMXConfigurator extends ContextAwareBase implements - JMXConfiguratorMBean, LoggerContextListener { - - private static String EMPTY = ""; - - LoggerContext loggerContext; - MBeanServer mbs; - ObjectName objectName; - String objectNameAsString; - - // whether to output status events on the console when reloading the - // configuration - boolean debug = true; - - boolean started; - - public JMXConfigurator(LoggerContext loggerContext, MBeanServer mbs, - ObjectName objectName) { - started = true; - this.context = loggerContext; - this.loggerContext = loggerContext; - this.mbs = mbs; - this.objectName = objectName; - this.objectNameAsString = objectName.toString(); - if (previouslyRegisteredListenerWithSameObjectName()) { - addError("Previously registered JMXConfigurator named [" - + objectNameAsString + "] in the logger context named [" - + loggerContext.getName() + "]"); - } else { - // register as a listener only if there are no homonyms - loggerContext.addListener(this); - } - } - - private boolean previouslyRegisteredListenerWithSameObjectName() { - List lcll = loggerContext.getCopyOfListenerList(); - for (LoggerContextListener lcl : lcll) { - if (lcl instanceof JMXConfigurator) { - JMXConfigurator jmxConfigurator = (JMXConfigurator) lcl; - if (objectName.equals(jmxConfigurator.objectName)) { - return true; - } - } - } - return false; - } - - public void reloadDefaultConfiguration() throws JoranException { - ContextInitializer ci = new ContextInitializer(loggerContext); - URL url = ci.findURLOfDefaultConfigurationFile(true); - reloadByURL(url); - } - - public void reloadByFileName(String fileName) throws JoranException, - FileNotFoundException { - File f = new File(fileName); - if (f.exists() && f.isFile()) { - URL url; - try { - url = f.toURI().toURL(); - reloadByURL(url); - } catch (MalformedURLException e) { - throw new RuntimeException( - "Unexpected MalformedURLException occured. See nexted cause.", e); - } - - } else { - String errMsg = "Could not find [" + fileName + "]"; - addInfo(errMsg); - throw new FileNotFoundException(errMsg); - } - } - - void addStatusListener(StatusListener statusListener) { - StatusManager sm = loggerContext.getStatusManager(); - sm.add(statusListener); - } - - void removeStatusListener(StatusListener statusListener) { - StatusManager sm = loggerContext.getStatusManager(); - sm.remove(statusListener); - } - - public void reloadByURL(URL url) throws JoranException { - StatusListenerAsList statusListenerAsList = new StatusListenerAsList(); - - addStatusListener(statusListenerAsList); - addInfo("Resetting context: " + loggerContext.getName()); - loggerContext.reset(); - // after a reset the statusListenerAsList gets removed as a listener - addStatusListener(statusListenerAsList); - - try { - JoranConfigurator configurator = new JoranConfigurator(); - configurator.setContext(loggerContext); - configurator.doConfigure(url); - addInfo("Context: " + loggerContext.getName() + " reloaded."); - } finally { - removeStatusListener(statusListenerAsList); - if (debug) { - StatusPrinter.print(statusListenerAsList.getStatusList()); - } - } - } - - public void setLoggerLevel(String loggerName, String levelStr) { - if (loggerName == null) { - return; - } - if (levelStr == null) { - return; - } - loggerName = loggerName.trim(); - levelStr = levelStr.trim(); - - addInfo("Trying to set level " + levelStr + " to logger " + loggerName); - LoggerContext lc = (LoggerContext) context; - - Logger logger = lc.getLogger(loggerName); - if ("null".equalsIgnoreCase(levelStr)) { - logger.setLevel(null); - } else { - Level level = Level.toLevel(levelStr, null); - if (level != null) { - logger.setLevel(level); - } - } - } - - public String getLoggerLevel(String loggerName) { - if (loggerName == null) { - return EMPTY; - } - - loggerName = loggerName.trim(); - - LoggerContext lc = (LoggerContext) context; - Logger logger = lc.exists(loggerName); - if (logger != null && logger.getLevel() != null) { - return logger.getLevel().toString(); - } else { - return EMPTY; - } - } - - public String getLoggerEffectiveLevel(String loggerName) { - if (loggerName == null) { - return EMPTY; - } - - loggerName = loggerName.trim(); - - LoggerContext lc = (LoggerContext) context; - Logger logger = lc.exists(loggerName); - if (logger != null) { - return logger.getEffectiveLevel().toString(); - } else { - return EMPTY; - } - } - - public List getLoggerList() { - LoggerContext lc = (LoggerContext) context; - List strList = new ArrayList(); - Iterator it = lc.getLoggerList().iterator(); - while (it.hasNext()) { - Logger log = it.next(); - strList.add(log.getName()); - } - return strList; - } - - public List getStatuses() { - List list = new ArrayList(); - Iterator it = context.getStatusManager().getCopyOfStatusList() - .iterator(); - while (it.hasNext()) { - list.add(it.next().toString()); - } - return list; - } - - /** - * When the associated LoggerContext is stopped, this configurator must be - * unregistered - */ - public void onStop(LoggerContext context) { - if (!started) { - addInfo("onStop() method called on a stopped JMXActivator [" - + objectNameAsString + "]"); - return; - } - if (mbs.isRegistered(objectName)) { - try { - addInfo("Unregistering mbean [" + objectNameAsString + "]"); - mbs.unregisterMBean(objectName); - } catch (InstanceNotFoundException e) { - // this is theoretically impossible - addError("Unable to find a verifiably registered mbean [" - + objectNameAsString + "]", e); - } catch (MBeanRegistrationException e) { - addError("Failed to unregister [" + objectNameAsString + "]", e); - } - } else { - addInfo("mbean [" + objectNameAsString - + "] was not in the mbean registry. This is OK."); - } - stop(); - } - - public void onLevelChange(Logger logger, Level level) { - // nothing to do - } - - public void onReset(LoggerContext context) { - addInfo("onReset() method called JMXActivator [" + objectNameAsString + "]"); - } - - /** - * JMXConfigurator should not be removed subsequent to a LoggerContext reset. - * - * @return - */ - public boolean isResetResistant() { - return true; - } - - private void clearFields() { - mbs = null; - objectName = null; - loggerContext = null; - } - - private void stop() { - started = false; - clearFields(); - } - - public void onStart(LoggerContext context) { - // nop - } - - @Override - public String toString() { - return this.getClass().getName() + "(" + context.getName() + ")"; - } -} diff --git a/All/Genesis-NP/Genesis#297/pair.info b/All/Genesis-NP/Genesis#297/pair.info deleted file mode 100755 index 0af5940..0000000 --- a/All/Genesis-NP/Genesis#297/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:297 -SATName:Genesis -modifiedFPath:logback-classic/src/main/java/ch/qos/logback/classic/jmx/JMXConfigurator.java -comSha:a3efa52283f0548f0decea54f49f3beba2318f2a -parentComSha:a3efa52283f0548f0decea54f49f3beba2318f2a^1 -githubUrl:https://github.com/qos-ch/logback -repoName:qos-ch#logback \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#305/comMsg.txt b/All/Genesis-NP/Genesis#305/comMsg.txt deleted file mode 100755 index 92f8faf..0000000 --- a/All/Genesis-NP/Genesis#305/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Avoid NPE when getting CodeSource diff --git a/All/Genesis-NP/Genesis#305/diff.diff b/All/Genesis-NP/Genesis#305/diff.diff deleted file mode 100755 index c395aff..0000000 --- a/All/Genesis-NP/Genesis#305/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/logback-classic/src/main/java/ch/qos/logback/classic/spi/PackagingDataCalculator.java b/logback-classic/src/main/java/ch/qos/logback/classic/spi/PackagingDataCalculator.java -index e2f6dd4..4b89ac8 100644 ---- a/logback-classic/src/main/java/ch/qos/logback/classic/spi/PackagingDataCalculator.java -+++ b/logback-classic/src/main/java/ch/qos/logback/classic/spi/PackagingDataCalculator.java -@@ -16,0 +17 @@ import java.net.URL; -+import java.security.CodeSource; -@@ -165 +166,3 @@ public class PackagingDataCalculator { -- URL resource = type.getProtectionDomain().getCodeSource().getLocation(); -+ CodeSource codeSource = type.getProtectionDomain().getCodeSource(); -+ if (codeSource != null) { -+ URL resource = codeSource.getLocation(); -@@ -175,0 +179 @@ public class PackagingDataCalculator { -+ } diff --git a/All/Genesis-NP/Genesis#305/new/PackagingDataCalculator.java b/All/Genesis-NP/Genesis#305/new/PackagingDataCalculator.java deleted file mode 100755 index 4b89ac8..0000000 --- a/All/Genesis-NP/Genesis#305/new/PackagingDataCalculator.java +++ /dev/null @@ -1,249 +0,0 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.spi; - -import java.net.URL; -import java.security.CodeSource; -import java.util.HashMap; - -import sun.reflect.Reflection; -// import java.security.AccessControlException; import java.security.AccessController;import java.security.PrivilegedAction; -/** - * Given a classname locate associated PackageInfo (jar name, version name). - * - * @author James Strachan - * @Ceki Gülcü - */ -public class PackagingDataCalculator { - - final static StackTraceElementProxy[] STEP_ARRAY_TEMPLATE = new StackTraceElementProxy[0]; - - HashMap cache = new HashMap(); - - private static boolean GET_CALLER_CLASS_METHOD_AVAILABLE = false; //private static boolean HAS_GET_CLASS_LOADER_PERMISSION = false; - - static { - // if either the Reflection class or the getCallerClass method - // are unavailable, then we won't invoke Reflection.getCallerClass() - // This approach ensures that this class will *run* on JDK's lacking - // sun.reflect.Reflection class. However, this class will *not compile* - // on JDKs lacking sun.reflect.Reflection. - try { - Reflection.getCallerClass(2); - GET_CALLER_CLASS_METHOD_AVAILABLE = true; - } catch (NoClassDefFoundError e) { - } catch (NoSuchMethodError e) { - } catch (Throwable e) { - System.err.println("Unexpected exception"); - e.printStackTrace(); - } - } - - - public void calculate(IThrowableProxy tp) { - while (tp != null) { - populateFrames(tp.getStackTraceElementProxyArray()); - IThrowableProxy[] suppressed = tp.getSuppressed(); - if(suppressed != null) { - for(IThrowableProxy current:suppressed) { - populateFrames(current.getStackTraceElementProxyArray()); - } - } - tp = tp.getCause(); - } - } - - void populateFrames(StackTraceElementProxy[] stepArray) { - // in the initial part of this method we populate package information for - // common stack frames - final Throwable t = new Throwable("local stack reference"); - final StackTraceElement[] localteSTEArray = t.getStackTrace(); - final int commonFrames = STEUtil.findNumberOfCommonFrames(localteSTEArray, - stepArray); - final int localFirstCommon = localteSTEArray.length - commonFrames; - final int stepFirstCommon = stepArray.length - commonFrames; - - ClassLoader lastExactClassLoader = null; - ClassLoader firsExactClassLoader = null; - - int missfireCount = 0; - for (int i = 0; i < commonFrames; i++) { - Class callerClass = null; - if (GET_CALLER_CLASS_METHOD_AVAILABLE) { - callerClass = Reflection.getCallerClass(localFirstCommon + i - - missfireCount + 1); - } - StackTraceElementProxy step = stepArray[stepFirstCommon + i]; - String stepClassname = step.ste.getClassName(); - - if (callerClass != null && stepClassname.equals(callerClass.getName())) { - // see also LBCLASSIC-263 - lastExactClassLoader = callerClass.getClassLoader(); - if (firsExactClassLoader == null) { - firsExactClassLoader = lastExactClassLoader; - } - ClassPackagingData pi = calculateByExactType(callerClass); - step.setClassPackagingData(pi); - } else { - missfireCount++; - ClassPackagingData pi = computeBySTEP(step, lastExactClassLoader); - step.setClassPackagingData(pi); - } - } - populateUncommonFrames(commonFrames, stepArray, firsExactClassLoader); - } - - void populateUncommonFrames(int commonFrames, - StackTraceElementProxy[] stepArray, ClassLoader firstExactClassLoader) { - int uncommonFrames = stepArray.length - commonFrames; - for (int i = 0; i < uncommonFrames; i++) { - StackTraceElementProxy step = stepArray[i]; - ClassPackagingData pi = computeBySTEP(step, firstExactClassLoader); - step.setClassPackagingData(pi); - } - } - - private ClassPackagingData calculateByExactType(Class type) { - String className = type.getName(); - ClassPackagingData cpd = cache.get(className); - if (cpd != null) { - return cpd; - } - String version = getImplementationVersion(type); - String codeLocation = getCodeLocation(type); - cpd = new ClassPackagingData(codeLocation, version); - cache.put(className, cpd); - return cpd; - } - - private ClassPackagingData computeBySTEP(StackTraceElementProxy step, - ClassLoader lastExactClassLoader) { - String className = step.ste.getClassName(); - ClassPackagingData cpd = cache.get(className); - if (cpd != null) { - return cpd; - } - Class type = bestEffortLoadClass(lastExactClassLoader, className); - String version = getImplementationVersion(type); - String codeLocation = getCodeLocation(type); - cpd = new ClassPackagingData(codeLocation, version, false); - cache.put(className, cpd); - return cpd; - } - - String getImplementationVersion(Class type) { - if (type == null) { - return "na"; - } - Package aPackage = type.getPackage(); - if (aPackage != null) { - String v = aPackage.getImplementationVersion(); - if (v == null) { - return "na"; - } else { - return v; - } - } - return "na"; - - } - - String getCodeLocation(Class type) { - try { - if (type != null) { - // file:/C:/java/maven-2.0.8/repo/com/icegreen/greenmail/1.3/greenmail-1.3.jar - CodeSource codeSource = type.getProtectionDomain().getCodeSource(); - if (codeSource != null) { - URL resource = codeSource.getLocation(); - if (resource != null) { - String locationStr = resource.toString(); - // now lets remove all but the file name - String result = getCodeLocation(locationStr, '/'); - if (result != null) { - return result; - } - return getCodeLocation(locationStr, '\\'); - } - } - } - } catch (Exception e) { - // ignore - } - return "na"; - } - - private String getCodeLocation(String locationStr, char separator) { - int idx = locationStr.lastIndexOf(separator); - if (isFolder(idx, locationStr)) { - idx = locationStr.lastIndexOf(separator, idx - 1); - return locationStr.substring(idx + 1); - } else if (idx > 0) { - return locationStr.substring(idx + 1); - } - return null; - } - - private boolean isFolder(int idx, String text) { - return (idx != -1 && idx + 1 == text.length()); - } - - private Class loadClass(ClassLoader cl, String className) { - if (cl == null) { - return null; - } - try { - return cl.loadClass(className); - } catch (ClassNotFoundException e1) { - return null; - } catch (NoClassDefFoundError e1) { - return null; - } catch (Exception e) { - e.printStackTrace(); // this is unexpected - return null; - } - - } - - /** - * @param lastGuaranteedClassLoader may be null - * @param className - * @return - */ - private Class bestEffortLoadClass(ClassLoader lastGuaranteedClassLoader, - String className) { - Class result = loadClass(lastGuaranteedClassLoader, className); - if (result != null) { - return result; - } - ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - if (tccl != lastGuaranteedClassLoader) { - result = loadClass(tccl, className); - } - if (result != null) { - return result; - } - - try { - return Class.forName(className); - } catch (ClassNotFoundException e1) { - return null; - } catch (NoClassDefFoundError e1) { - return null; - } catch (Exception e) { - e.printStackTrace(); // this is unexpected - return null; - } - } - -} diff --git a/All/Genesis-NP/Genesis#305/old/PackagingDataCalculator.java b/All/Genesis-NP/Genesis#305/old/PackagingDataCalculator.java deleted file mode 100755 index e2f6dd4..0000000 --- a/All/Genesis-NP/Genesis#305/old/PackagingDataCalculator.java +++ /dev/null @@ -1,245 +0,0 @@ -/** - * Logback: the reliable, generic, fast and flexible logging framework. - * Copyright (C) 1999-2013, QOS.ch. All rights reserved. - * - * This program and the accompanying materials are dual-licensed under - * either the terms of the Eclipse Public License v1.0 as published by - * the Eclipse Foundation - * - * or (per the licensee's choosing) - * - * under the terms of the GNU Lesser General Public License version 2.1 - * as published by the Free Software Foundation. - */ -package ch.qos.logback.classic.spi; - -import java.net.URL; -import java.util.HashMap; - -import sun.reflect.Reflection; -// import java.security.AccessControlException; import java.security.AccessController;import java.security.PrivilegedAction; -/** - * Given a classname locate associated PackageInfo (jar name, version name). - * - * @author James Strachan - * @Ceki Gülcü - */ -public class PackagingDataCalculator { - - final static StackTraceElementProxy[] STEP_ARRAY_TEMPLATE = new StackTraceElementProxy[0]; - - HashMap cache = new HashMap(); - - private static boolean GET_CALLER_CLASS_METHOD_AVAILABLE = false; //private static boolean HAS_GET_CLASS_LOADER_PERMISSION = false; - - static { - // if either the Reflection class or the getCallerClass method - // are unavailable, then we won't invoke Reflection.getCallerClass() - // This approach ensures that this class will *run* on JDK's lacking - // sun.reflect.Reflection class. However, this class will *not compile* - // on JDKs lacking sun.reflect.Reflection. - try { - Reflection.getCallerClass(2); - GET_CALLER_CLASS_METHOD_AVAILABLE = true; - } catch (NoClassDefFoundError e) { - } catch (NoSuchMethodError e) { - } catch (Throwable e) { - System.err.println("Unexpected exception"); - e.printStackTrace(); - } - } - - - public void calculate(IThrowableProxy tp) { - while (tp != null) { - populateFrames(tp.getStackTraceElementProxyArray()); - IThrowableProxy[] suppressed = tp.getSuppressed(); - if(suppressed != null) { - for(IThrowableProxy current:suppressed) { - populateFrames(current.getStackTraceElementProxyArray()); - } - } - tp = tp.getCause(); - } - } - - void populateFrames(StackTraceElementProxy[] stepArray) { - // in the initial part of this method we populate package information for - // common stack frames - final Throwable t = new Throwable("local stack reference"); - final StackTraceElement[] localteSTEArray = t.getStackTrace(); - final int commonFrames = STEUtil.findNumberOfCommonFrames(localteSTEArray, - stepArray); - final int localFirstCommon = localteSTEArray.length - commonFrames; - final int stepFirstCommon = stepArray.length - commonFrames; - - ClassLoader lastExactClassLoader = null; - ClassLoader firsExactClassLoader = null; - - int missfireCount = 0; - for (int i = 0; i < commonFrames; i++) { - Class callerClass = null; - if (GET_CALLER_CLASS_METHOD_AVAILABLE) { - callerClass = Reflection.getCallerClass(localFirstCommon + i - - missfireCount + 1); - } - StackTraceElementProxy step = stepArray[stepFirstCommon + i]; - String stepClassname = step.ste.getClassName(); - - if (callerClass != null && stepClassname.equals(callerClass.getName())) { - // see also LBCLASSIC-263 - lastExactClassLoader = callerClass.getClassLoader(); - if (firsExactClassLoader == null) { - firsExactClassLoader = lastExactClassLoader; - } - ClassPackagingData pi = calculateByExactType(callerClass); - step.setClassPackagingData(pi); - } else { - missfireCount++; - ClassPackagingData pi = computeBySTEP(step, lastExactClassLoader); - step.setClassPackagingData(pi); - } - } - populateUncommonFrames(commonFrames, stepArray, firsExactClassLoader); - } - - void populateUncommonFrames(int commonFrames, - StackTraceElementProxy[] stepArray, ClassLoader firstExactClassLoader) { - int uncommonFrames = stepArray.length - commonFrames; - for (int i = 0; i < uncommonFrames; i++) { - StackTraceElementProxy step = stepArray[i]; - ClassPackagingData pi = computeBySTEP(step, firstExactClassLoader); - step.setClassPackagingData(pi); - } - } - - private ClassPackagingData calculateByExactType(Class type) { - String className = type.getName(); - ClassPackagingData cpd = cache.get(className); - if (cpd != null) { - return cpd; - } - String version = getImplementationVersion(type); - String codeLocation = getCodeLocation(type); - cpd = new ClassPackagingData(codeLocation, version); - cache.put(className, cpd); - return cpd; - } - - private ClassPackagingData computeBySTEP(StackTraceElementProxy step, - ClassLoader lastExactClassLoader) { - String className = step.ste.getClassName(); - ClassPackagingData cpd = cache.get(className); - if (cpd != null) { - return cpd; - } - Class type = bestEffortLoadClass(lastExactClassLoader, className); - String version = getImplementationVersion(type); - String codeLocation = getCodeLocation(type); - cpd = new ClassPackagingData(codeLocation, version, false); - cache.put(className, cpd); - return cpd; - } - - String getImplementationVersion(Class type) { - if (type == null) { - return "na"; - } - Package aPackage = type.getPackage(); - if (aPackage != null) { - String v = aPackage.getImplementationVersion(); - if (v == null) { - return "na"; - } else { - return v; - } - } - return "na"; - - } - - String getCodeLocation(Class type) { - try { - if (type != null) { - // file:/C:/java/maven-2.0.8/repo/com/icegreen/greenmail/1.3/greenmail-1.3.jar - URL resource = type.getProtectionDomain().getCodeSource().getLocation(); - if (resource != null) { - String locationStr = resource.toString(); - // now lets remove all but the file name - String result = getCodeLocation(locationStr, '/'); - if (result != null) { - return result; - } - return getCodeLocation(locationStr, '\\'); - } - } - } catch (Exception e) { - // ignore - } - return "na"; - } - - private String getCodeLocation(String locationStr, char separator) { - int idx = locationStr.lastIndexOf(separator); - if (isFolder(idx, locationStr)) { - idx = locationStr.lastIndexOf(separator, idx - 1); - return locationStr.substring(idx + 1); - } else if (idx > 0) { - return locationStr.substring(idx + 1); - } - return null; - } - - private boolean isFolder(int idx, String text) { - return (idx != -1 && idx + 1 == text.length()); - } - - private Class loadClass(ClassLoader cl, String className) { - if (cl == null) { - return null; - } - try { - return cl.loadClass(className); - } catch (ClassNotFoundException e1) { - return null; - } catch (NoClassDefFoundError e1) { - return null; - } catch (Exception e) { - e.printStackTrace(); // this is unexpected - return null; - } - - } - - /** - * @param lastGuaranteedClassLoader may be null - * @param className - * @return - */ - private Class bestEffortLoadClass(ClassLoader lastGuaranteedClassLoader, - String className) { - Class result = loadClass(lastGuaranteedClassLoader, className); - if (result != null) { - return result; - } - ClassLoader tccl = Thread.currentThread().getContextClassLoader(); - if (tccl != lastGuaranteedClassLoader) { - result = loadClass(tccl, className); - } - if (result != null) { - return result; - } - - try { - return Class.forName(className); - } catch (ClassNotFoundException e1) { - return null; - } catch (NoClassDefFoundError e1) { - return null; - } catch (Exception e) { - e.printStackTrace(); // this is unexpected - return null; - } - } - -} diff --git a/All/Genesis-NP/Genesis#305/pair.info b/All/Genesis-NP/Genesis#305/pair.info deleted file mode 100755 index 627c0c5..0000000 --- a/All/Genesis-NP/Genesis#305/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:305 -SATName:Genesis -modifiedFPath:logback-classic/src/main/java/ch/qos/logback/classic/spi/PackagingDataCalculator.java -comSha:f47aba79547bde8d72d2a9245f17077c0fb9198a -parentComSha:f47aba79547bde8d72d2a9245f17077c0fb9198a^1 -githubUrl:https://github.com/qos-ch/logback -repoName:qos-ch#logback \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#327/comMsg.txt b/All/Genesis-NP/Genesis#327/comMsg.txt deleted file mode 100755 index d73b054..0000000 --- a/All/Genesis-NP/Genesis#327/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix NPE with regex extraction function diff --git a/All/Genesis-NP/Genesis#327/diff.diff b/All/Genesis-NP/Genesis#327/diff.diff deleted file mode 100755 index 2d70272..0000000 --- a/All/Genesis-NP/Genesis#327/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/processing/src/main/java/io/druid/query/extraction/RegexDimExtractionFn.java b/processing/src/main/java/io/druid/query/extraction/RegexDimExtractionFn.java -index cc374ad..b3c33b6 100644 ---- a/processing/src/main/java/io/druid/query/extraction/RegexDimExtractionFn.java -+++ b/processing/src/main/java/io/druid/query/extraction/RegexDimExtractionFn.java -@@ -22,0 +23 @@ import com.google.common.base.Preconditions; -+import com.google.common.base.Strings; -@@ -61,0 +63,3 @@ public class RegexDimExtractionFn extends DimExtractionFn -+ if (dimValue == null) { -+ return null; -+ } -@@ -63 +67 @@ public class RegexDimExtractionFn extends DimExtractionFn -- return matcher.find() ? matcher.group(1) : dimValue; -+ return Strings.emptyToNull(matcher.find() ? matcher.group(1) : dimValue); diff --git a/All/Genesis-NP/Genesis#327/new/RegexDimExtractionFn.java b/All/Genesis-NP/Genesis#327/new/RegexDimExtractionFn.java deleted file mode 100755 index b3c33b6..0000000 --- a/All/Genesis-NP/Genesis#327/new/RegexDimExtractionFn.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright 2012 - 2015 Metamarkets Group 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 io.druid.query.extraction; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.Preconditions; -import com.google.common.base.Strings; -import com.metamx.common.StringUtils; - -import java.nio.ByteBuffer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - */ -public class RegexDimExtractionFn extends DimExtractionFn -{ - private static final byte CACHE_TYPE_ID = 0x1; - - private final String expr; - private final Pattern pattern; - - @JsonCreator - public RegexDimExtractionFn( - @JsonProperty("expr") String expr - ) - { - Preconditions.checkNotNull(expr, "expr must not be null"); - - this.expr = expr; - this.pattern = Pattern.compile(expr); - } - - @Override - public byte[] getCacheKey() - { - byte[] exprBytes = StringUtils.toUtf8(expr); - return ByteBuffer.allocate(1 + exprBytes.length) - .put(CACHE_TYPE_ID) - .put(exprBytes) - .array(); - } - - @Override - public String apply(String dimValue) - { - if (dimValue == null) { - return null; - } - Matcher matcher = pattern.matcher(dimValue); - return Strings.emptyToNull(matcher.find() ? matcher.group(1) : dimValue); - } - - @JsonProperty("expr") - public String getExpr() - { - return expr; - } - - @Override - public boolean preservesOrdering() - { - return false; - } - - @Override - public ExtractionType getExtractionType() - { - return ExtractionType.MANY_TO_ONE; - } - - @Override - public String toString() - { - return String.format("regex(%s)", expr); - } - - @Override - public boolean equals(Object o) - { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - RegexDimExtractionFn that = (RegexDimExtractionFn) o; - - if (!expr.equals(that.expr)) { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - return expr.hashCode(); - } -} diff --git a/All/Genesis-NP/Genesis#327/old/RegexDimExtractionFn.java b/All/Genesis-NP/Genesis#327/old/RegexDimExtractionFn.java deleted file mode 100755 index cc374ad..0000000 --- a/All/Genesis-NP/Genesis#327/old/RegexDimExtractionFn.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright 2012 - 2015 Metamarkets Group 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 io.druid.query.extraction; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.Preconditions; -import com.metamx.common.StringUtils; - -import java.nio.ByteBuffer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - */ -public class RegexDimExtractionFn extends DimExtractionFn -{ - private static final byte CACHE_TYPE_ID = 0x1; - - private final String expr; - private final Pattern pattern; - - @JsonCreator - public RegexDimExtractionFn( - @JsonProperty("expr") String expr - ) - { - Preconditions.checkNotNull(expr, "expr must not be null"); - - this.expr = expr; - this.pattern = Pattern.compile(expr); - } - - @Override - public byte[] getCacheKey() - { - byte[] exprBytes = StringUtils.toUtf8(expr); - return ByteBuffer.allocate(1 + exprBytes.length) - .put(CACHE_TYPE_ID) - .put(exprBytes) - .array(); - } - - @Override - public String apply(String dimValue) - { - Matcher matcher = pattern.matcher(dimValue); - return matcher.find() ? matcher.group(1) : dimValue; - } - - @JsonProperty("expr") - public String getExpr() - { - return expr; - } - - @Override - public boolean preservesOrdering() - { - return false; - } - - @Override - public ExtractionType getExtractionType() - { - return ExtractionType.MANY_TO_ONE; - } - - @Override - public String toString() - { - return String.format("regex(%s)", expr); - } - - @Override - public boolean equals(Object o) - { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - RegexDimExtractionFn that = (RegexDimExtractionFn) o; - - if (!expr.equals(that.expr)) { - return false; - } - - return true; - } - - @Override - public int hashCode() - { - return expr.hashCode(); - } -} diff --git a/All/Genesis-NP/Genesis#327/pair.info b/All/Genesis-NP/Genesis#327/pair.info deleted file mode 100755 index 5391bbb..0000000 --- a/All/Genesis-NP/Genesis#327/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:327 -SATName:Genesis -modifiedFPath:processing/src/main/java/io/druid/query/extraction/RegexDimExtractionFn.java -comSha:08a527d01ab7209c92918ddb2ad5dee478e13d5d -parentComSha:08a527d01ab7209c92918ddb2ad5dee478e13d5d^1 -githubUrl:https://github.com/druid-io/druid -repoName:druid-io#druid \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#328/comMsg.txt b/All/Genesis-NP/Genesis#328/comMsg.txt deleted file mode 100755 index 17b253b..0000000 --- a/All/Genesis-NP/Genesis#328/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix NPE for union queries diff --git a/All/Genesis-NP/Genesis#328/diff.diff b/All/Genesis-NP/Genesis#328/diff.diff deleted file mode 100755 index ddba5e0..0000000 --- a/All/Genesis-NP/Genesis#328/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/common/src/main/java/io/druid/timeline/UnionTimeLineLookup.java b/common/src/main/java/io/druid/timeline/UnionTimeLineLookup.java -index c14fafe..3233b63 100644 ---- a/common/src/main/java/io/druid/timeline/UnionTimeLineLookup.java -+++ b/common/src/main/java/io/druid/timeline/UnionTimeLineLookup.java -@@ -20,0 +21 @@ import com.google.common.base.Function; -+import com.google.common.base.Predicates; -@@ -32 +33,2 @@ public class UnionTimeLineLookup implements TimelineLoo -- this.delegates = delegates; -+ // delegate can be null in case there is no segment loaded for the dataSource on this node -+ this.delegates = Iterables.filter(delegates, Predicates.notNull()); diff --git a/All/Genesis-NP/Genesis#328/new/UnionTimeLineLookup.java b/All/Genesis-NP/Genesis#328/new/UnionTimeLineLookup.java deleted file mode 100755 index 3233b63..0000000 --- a/All/Genesis-NP/Genesis#328/new/UnionTimeLineLookup.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright 2012 - 2015 Metamarkets Group 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 io.druid.timeline; - -import com.google.common.base.Function; -import com.google.common.base.Predicates; -import com.google.common.collect.Iterables; -import io.druid.timeline.partition.PartitionHolder; -import org.joda.time.Interval; - - -public class UnionTimeLineLookup implements TimelineLookup -{ - Iterable> delegates; - - public UnionTimeLineLookup(Iterable> delegates) - { - // delegate can be null in case there is no segment loaded for the dataSource on this node - this.delegates = Iterables.filter(delegates, Predicates.notNull()); - } - - @Override - public Iterable> lookup(final Interval interval) - { - return Iterables.concat( - Iterables.transform( - delegates, - new Function, Iterable>>() - { - @Override - public Iterable> apply(TimelineLookup input) - { - return input.lookup(interval); - } - } - ) - ); - } - - public PartitionHolder findEntry(Interval interval, VersionType version) - { - for (TimelineLookup delegate : delegates) { - final PartitionHolder entry = delegate.findEntry(interval, version); - if (entry != null) { - return entry; - } - } - return null; - } -} diff --git a/All/Genesis-NP/Genesis#328/old/UnionTimeLineLookup.java b/All/Genesis-NP/Genesis#328/old/UnionTimeLineLookup.java deleted file mode 100755 index c14fafe..0000000 --- a/All/Genesis-NP/Genesis#328/old/UnionTimeLineLookup.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright 2012 - 2015 Metamarkets Group 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 io.druid.timeline; - -import com.google.common.base.Function; -import com.google.common.collect.Iterables; -import io.druid.timeline.partition.PartitionHolder; -import org.joda.time.Interval; - - -public class UnionTimeLineLookup implements TimelineLookup -{ - Iterable> delegates; - - public UnionTimeLineLookup(Iterable> delegates) - { - this.delegates = delegates; - } - - @Override - public Iterable> lookup(final Interval interval) - { - return Iterables.concat( - Iterables.transform( - delegates, - new Function, Iterable>>() - { - @Override - public Iterable> apply(TimelineLookup input) - { - return input.lookup(interval); - } - } - ) - ); - } - - public PartitionHolder findEntry(Interval interval, VersionType version) - { - for (TimelineLookup delegate : delegates) { - final PartitionHolder entry = delegate.findEntry(interval, version); - if (entry != null) { - return entry; - } - } - return null; - } -} diff --git a/All/Genesis-NP/Genesis#328/pair.info b/All/Genesis-NP/Genesis#328/pair.info deleted file mode 100755 index 7423dce..0000000 --- a/All/Genesis-NP/Genesis#328/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:328 -SATName:Genesis -modifiedFPath:common/src/main/java/io/druid/timeline/UnionTimeLineLookup.java -comSha:e5fa8e0cb4f4d79e09d615a47b22e44460485e0a -parentComSha:e5fa8e0cb4f4d79e09d615a47b22e44460485e0a^1 -githubUrl:https://github.com/druid-io/druid -repoName:druid-io#druid \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#329/comMsg.txt b/All/Genesis-NP/Genesis#329/comMsg.txt deleted file mode 100755 index c162f3c..0000000 --- a/All/Genesis-NP/Genesis#329/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix NPE for topN over missing hyperUniques column diff --git a/All/Genesis-NP/Genesis#329/diff.diff b/All/Genesis-NP/Genesis#329/diff.diff deleted file mode 100755 index b9a63aa..0000000 --- a/All/Genesis-NP/Genesis#329/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/processing/src/main/java/io/druid/query/aggregation/hyperloglog/HyperUniquesAggregatorFactory.java b/processing/src/main/java/io/druid/query/aggregation/hyperloglog/HyperUniquesAggregatorFactory.java -index 0f68989..7b3d311 100644 ---- a/processing/src/main/java/io/druid/query/aggregation/hyperloglog/HyperUniquesAggregatorFactory.java -+++ b/processing/src/main/java/io/druid/query/aggregation/hyperloglog/HyperUniquesAggregatorFactory.java -@@ -113,0 +114,6 @@ public class HyperUniquesAggregatorFactory implements AggregatorFactory -+ if(lhs == null) { -+ return -1; -+ } -+ if(rhs == null) { -+ return 1; -+ } diff --git a/All/Genesis-NP/Genesis#329/new/HyperUniquesAggregatorFactory.java b/All/Genesis-NP/Genesis#329/new/HyperUniquesAggregatorFactory.java deleted file mode 100755 index 7b3d311..0000000 --- a/All/Genesis-NP/Genesis#329/new/HyperUniquesAggregatorFactory.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright (C) 2012, 2013 Metamarkets Group Inc. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.druid.query.aggregation.hyperloglog; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.Charsets; -import com.metamx.common.IAE; -import com.metamx.common.StringUtils; -import io.druid.query.aggregation.Aggregator; -import io.druid.query.aggregation.AggregatorFactory; -import io.druid.query.aggregation.Aggregators; -import io.druid.query.aggregation.BufferAggregator; -import io.druid.segment.ColumnSelectorFactory; -import io.druid.segment.ObjectColumnSelector; -import org.apache.commons.codec.binary.Base64; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -/** - */ -public class HyperUniquesAggregatorFactory implements AggregatorFactory -{ - public static Object estimateCardinality(Object object) - { - if (object == null) { - return 0; - } - - return ((HyperLogLogCollector) object).estimateCardinality(); - } - - private static final byte CACHE_TYPE_ID = 0x5; - - private final String name; - private final String fieldName; - - @JsonCreator - public HyperUniquesAggregatorFactory( - @JsonProperty("name") String name, - @JsonProperty("fieldName") String fieldName - ) - { - this.name = name; - this.fieldName = fieldName; - } - - @Override - public Aggregator factorize(ColumnSelectorFactory metricFactory) - { - ObjectColumnSelector selector = metricFactory.makeObjectColumnSelector(fieldName); - - if (selector == null) { - return Aggregators.noopAggregator(); - } - - final Class classOfObject = selector.classOfObject(); - if (classOfObject.equals(Object.class) || HyperLogLogCollector.class.isAssignableFrom(classOfObject)) { - return new HyperUniquesAggregator(name, selector); - } - - throw new IAE( - "Incompatible type for metric[%s], expected a HyperUnique, got a %s", fieldName, classOfObject - ); - } - - @Override - public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory) - { - ObjectColumnSelector selector = metricFactory.makeObjectColumnSelector(fieldName); - - if (selector == null) { - return Aggregators.noopBufferAggregator(); - } - - final Class classOfObject = selector.classOfObject(); - if (classOfObject.equals(Object.class) || HyperLogLogCollector.class.isAssignableFrom(classOfObject)) { - return new HyperUniquesBufferAggregator(selector); - } - - throw new IAE( - "Incompatible type for metric[%s], expected a HyperUnique, got a %s", fieldName, classOfObject - ); - } - - @Override - public Comparator getComparator() - { - return new Comparator() - { - @Override - public int compare(HyperLogLogCollector lhs, HyperLogLogCollector rhs) - { - if(lhs == null) { - return -1; - } - if(rhs == null) { - return 1; - } - return lhs.compareTo(rhs); - } - }; - } - - @Override - public Object combine(Object lhs, Object rhs) - { - if (rhs == null) { - return lhs; - } - if (lhs == null) { - return rhs; - } - return ((HyperLogLogCollector) lhs).fold((HyperLogLogCollector) rhs); - } - - @Override - public AggregatorFactory getCombiningFactory() - { - return new HyperUniquesAggregatorFactory(name, name); - } - - @Override - public List getRequiredColumns() - { - return Arrays.asList(new HyperUniquesAggregatorFactory(fieldName, fieldName)); - } - - @Override - public Object deserialize(Object object) - { - if (object instanceof byte[]) { - return HyperLogLogCollector.makeCollector(ByteBuffer.wrap((byte[]) object)); - } else if (object instanceof ByteBuffer) { - return HyperLogLogCollector.makeCollector((ByteBuffer) object); - } else if (object instanceof String) { - return HyperLogLogCollector.makeCollector( - ByteBuffer.wrap(Base64.decodeBase64(StringUtils.toUtf8((String) object))) - ); - } - return object; - } - - @Override - - public Object finalizeComputation(Object object) - { - return estimateCardinality(object); - } - - @Override - @JsonProperty - public String getName() - { - return name; - } - - @Override - public List requiredFields() - { - return Arrays.asList(fieldName); - } - - @JsonProperty - public String getFieldName() - { - return fieldName; - } - - @Override - public byte[] getCacheKey() - { - byte[] fieldNameBytes = StringUtils.toUtf8(fieldName); - - return ByteBuffer.allocate(1 + fieldNameBytes.length).put(CACHE_TYPE_ID).put(fieldNameBytes).array(); - } - - @Override - public String getTypeName() - { - return "hyperUnique"; - } - - @Override - public int getMaxIntermediateSize() - { - return HyperLogLogCollector.getLatestNumBytesForDenseStorage(); - } - - @Override - public Object getAggregatorStartValue() - { - return HyperLogLogCollector.makeLatestCollector(); - } - - @Override - public String toString() - { - return "HyperUniquesAggregatorFactory{" + - "name='" + name + '\'' + - ", fieldName='" + fieldName + '\'' + - '}'; - } - - @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - HyperUniquesAggregatorFactory that = (HyperUniquesAggregatorFactory) o; - - if (!fieldName.equals(that.fieldName)) return false; - if (!name.equals(that.name)) return false; - - return true; - } - - @Override - public int hashCode() - { - int result = name.hashCode(); - result = 31 * result + fieldName.hashCode(); - return result; - } -} diff --git a/All/Genesis-NP/Genesis#329/old/HyperUniquesAggregatorFactory.java b/All/Genesis-NP/Genesis#329/old/HyperUniquesAggregatorFactory.java deleted file mode 100755 index 0f68989..0000000 --- a/All/Genesis-NP/Genesis#329/old/HyperUniquesAggregatorFactory.java +++ /dev/null @@ -1,240 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright (C) 2012, 2013 Metamarkets Group Inc. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.druid.query.aggregation.hyperloglog; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.common.base.Charsets; -import com.metamx.common.IAE; -import com.metamx.common.StringUtils; -import io.druid.query.aggregation.Aggregator; -import io.druid.query.aggregation.AggregatorFactory; -import io.druid.query.aggregation.Aggregators; -import io.druid.query.aggregation.BufferAggregator; -import io.druid.segment.ColumnSelectorFactory; -import io.druid.segment.ObjectColumnSelector; -import org.apache.commons.codec.binary.Base64; - -import java.nio.ByteBuffer; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -/** - */ -public class HyperUniquesAggregatorFactory implements AggregatorFactory -{ - public static Object estimateCardinality(Object object) - { - if (object == null) { - return 0; - } - - return ((HyperLogLogCollector) object).estimateCardinality(); - } - - private static final byte CACHE_TYPE_ID = 0x5; - - private final String name; - private final String fieldName; - - @JsonCreator - public HyperUniquesAggregatorFactory( - @JsonProperty("name") String name, - @JsonProperty("fieldName") String fieldName - ) - { - this.name = name; - this.fieldName = fieldName; - } - - @Override - public Aggregator factorize(ColumnSelectorFactory metricFactory) - { - ObjectColumnSelector selector = metricFactory.makeObjectColumnSelector(fieldName); - - if (selector == null) { - return Aggregators.noopAggregator(); - } - - final Class classOfObject = selector.classOfObject(); - if (classOfObject.equals(Object.class) || HyperLogLogCollector.class.isAssignableFrom(classOfObject)) { - return new HyperUniquesAggregator(name, selector); - } - - throw new IAE( - "Incompatible type for metric[%s], expected a HyperUnique, got a %s", fieldName, classOfObject - ); - } - - @Override - public BufferAggregator factorizeBuffered(ColumnSelectorFactory metricFactory) - { - ObjectColumnSelector selector = metricFactory.makeObjectColumnSelector(fieldName); - - if (selector == null) { - return Aggregators.noopBufferAggregator(); - } - - final Class classOfObject = selector.classOfObject(); - if (classOfObject.equals(Object.class) || HyperLogLogCollector.class.isAssignableFrom(classOfObject)) { - return new HyperUniquesBufferAggregator(selector); - } - - throw new IAE( - "Incompatible type for metric[%s], expected a HyperUnique, got a %s", fieldName, classOfObject - ); - } - - @Override - public Comparator getComparator() - { - return new Comparator() - { - @Override - public int compare(HyperLogLogCollector lhs, HyperLogLogCollector rhs) - { - return lhs.compareTo(rhs); - } - }; - } - - @Override - public Object combine(Object lhs, Object rhs) - { - if (rhs == null) { - return lhs; - } - if (lhs == null) { - return rhs; - } - return ((HyperLogLogCollector) lhs).fold((HyperLogLogCollector) rhs); - } - - @Override - public AggregatorFactory getCombiningFactory() - { - return new HyperUniquesAggregatorFactory(name, name); - } - - @Override - public List getRequiredColumns() - { - return Arrays.asList(new HyperUniquesAggregatorFactory(fieldName, fieldName)); - } - - @Override - public Object deserialize(Object object) - { - if (object instanceof byte[]) { - return HyperLogLogCollector.makeCollector(ByteBuffer.wrap((byte[]) object)); - } else if (object instanceof ByteBuffer) { - return HyperLogLogCollector.makeCollector((ByteBuffer) object); - } else if (object instanceof String) { - return HyperLogLogCollector.makeCollector( - ByteBuffer.wrap(Base64.decodeBase64(StringUtils.toUtf8((String) object))) - ); - } - return object; - } - - @Override - - public Object finalizeComputation(Object object) - { - return estimateCardinality(object); - } - - @Override - @JsonProperty - public String getName() - { - return name; - } - - @Override - public List requiredFields() - { - return Arrays.asList(fieldName); - } - - @JsonProperty - public String getFieldName() - { - return fieldName; - } - - @Override - public byte[] getCacheKey() - { - byte[] fieldNameBytes = StringUtils.toUtf8(fieldName); - - return ByteBuffer.allocate(1 + fieldNameBytes.length).put(CACHE_TYPE_ID).put(fieldNameBytes).array(); - } - - @Override - public String getTypeName() - { - return "hyperUnique"; - } - - @Override - public int getMaxIntermediateSize() - { - return HyperLogLogCollector.getLatestNumBytesForDenseStorage(); - } - - @Override - public Object getAggregatorStartValue() - { - return HyperLogLogCollector.makeLatestCollector(); - } - - @Override - public String toString() - { - return "HyperUniquesAggregatorFactory{" + - "name='" + name + '\'' + - ", fieldName='" + fieldName + '\'' + - '}'; - } - - @Override - public boolean equals(Object o) - { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - HyperUniquesAggregatorFactory that = (HyperUniquesAggregatorFactory) o; - - if (!fieldName.equals(that.fieldName)) return false; - if (!name.equals(that.name)) return false; - - return true; - } - - @Override - public int hashCode() - { - int result = name.hashCode(); - result = 31 * result + fieldName.hashCode(); - return result; - } -} diff --git a/All/Genesis-NP/Genesis#329/pair.info b/All/Genesis-NP/Genesis#329/pair.info deleted file mode 100755 index 0c69449..0000000 --- a/All/Genesis-NP/Genesis#329/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:329 -SATName:Genesis -modifiedFPath:processing/src/main/java/io/druid/query/aggregation/hyperloglog/HyperUniquesAggregatorFactory.java -comSha:f24a89a22a3b92940606fb0ec74c4d70feb77b1d -parentComSha:f24a89a22a3b92940606fb0ec74c4d70feb77b1d^1 -githubUrl:https://github.com/druid-io/druid -repoName:druid-io#druid \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#333/comMsg.txt b/All/Genesis-NP/Genesis#333/comMsg.txt deleted file mode 100755 index 0a8cc23..0000000 --- a/All/Genesis-NP/Genesis#333/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix NPE diff --git a/All/Genesis-NP/Genesis#333/diff.diff b/All/Genesis-NP/Genesis#333/diff.diff deleted file mode 100755 index 01a8f58..0000000 --- a/All/Genesis-NP/Genesis#333/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/indexing-service/src/main/java/io/druid/indexing/firehose/IngestSegmentFirehoseFactory.java b/indexing-service/src/main/java/io/druid/indexing/firehose/IngestSegmentFirehoseFactory.java -index 94adbc0..5744fa7 100644 ---- a/indexing-service/src/main/java/io/druid/indexing/firehose/IngestSegmentFirehoseFactory.java -+++ b/indexing-service/src/main/java/io/druid/indexing/firehose/IngestSegmentFirehoseFactory.java -@@ -257,0 +258,2 @@ public class IngestSegmentFirehoseFactory implements FirehoseFactory -{ - private static final EmittingLogger log = new EmittingLogger(IngestSegmentFirehoseFactory.class); - private final String dataSource; - private final Interval interval; - private final DimFilter dimFilter; - private final List dimensions; - private final List metrics; - private final Injector injector; - - @JsonCreator - public IngestSegmentFirehoseFactory( - @JsonProperty("dataSource") final String dataSource, - @JsonProperty("interval") Interval interval, - @JsonProperty("filter") DimFilter dimFilter, - @JsonProperty("dimensions") List dimensions, - @JsonProperty("metrics") List metrics, - @JacksonInject Injector injector - ) - { - Preconditions.checkNotNull(dataSource, "dataSource"); - Preconditions.checkNotNull(interval, "interval"); - this.dataSource = dataSource; - this.interval = interval; - this.dimFilter = dimFilter; - this.dimensions = dimensions; - this.metrics = metrics; - this.injector = injector; - } - - @JsonProperty - public String getDataSource() - { - return dataSource; - } - - @JsonProperty - public Interval getInterval() - { - return interval; - } - - @JsonProperty("filter") - public DimFilter getDimensionsFilter() - { - return dimFilter; - } - - @JsonProperty - public List getDimensions() - { - return dimensions; - } - - @JsonProperty - public List getMetrics() - { - return metrics; - } - - @Override - public Firehose connect(InputRowParser inputRowParser) throws IOException, ParseException - { - log.info("Connecting firehose: dataSource[%s], interval[%s]", dataSource, interval); - // better way to achieve this is to pass toolbox to Firehose, The instance is initialized Lazily on connect method. - // Noop Task is just used to create the toolbox and list segments. - final TaskToolbox toolbox = injector.getInstance(TaskToolboxFactory.class).build( - new NoopTask("reingest", 0, 0, null, null) - ); - - try { - final List usedSegments = toolbox - .getTaskActionClient() - .submit(new SegmentListUsedAction(dataSource, interval)); - final Map segmentFileMap = toolbox.fetchSegments(usedSegments); - VersionedIntervalTimeline timeline = new VersionedIntervalTimeline( - Ordering.natural().nullsFirst() - ); - - for (DataSegment segment : usedSegments) { - timeline.add(segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(segment)); - } - final List> timeLineSegments = timeline.lookup( - interval - ); - - List dims; - if (dimensions != null) { - dims = dimensions; - } else { - Set dimSet = new HashSet<>(); - for (TimelineObjectHolder timelineObjectHolder : timeLineSegments) { - dimSet.addAll(timelineObjectHolder.getObject().getChunk(0).getObject().getDimensions()); - } - dims = Lists.newArrayList(dimSet); - } - - List metricsList; - if (metrics != null) { - metricsList = metrics; - } else { - Set metricsSet = new HashSet<>(); - for (TimelineObjectHolder timelineObjectHolder : timeLineSegments) { - metricsSet.addAll(timelineObjectHolder.getObject().getChunk(0).getObject().getMetrics()); - } - metricsList = Lists.newArrayList(metricsSet); - } - - - final List adapters = Lists.transform( - timeLineSegments, - new Function, StorageAdapter>() - { - @Override - public StorageAdapter apply(TimelineObjectHolder input) - { - final DataSegment segment = input.getObject().getChunk(0).getObject(); - final File file = Preconditions.checkNotNull( - segmentFileMap.get(segment), - "File for segment %s", segment.getIdentifier() - ); - - try { - return new QueryableIndexStorageAdapter((IndexIO.loadIndex(file))); - } - catch (IOException e) { - throw Throwables.propagate(e); - } - } - } - ); - - return new IngestSegmentFirehose(adapters, dims, metricsList); - - } - catch (IOException e) { - throw Throwables.propagate(e); - } - catch (SegmentLoadingException e) { - throw Throwables.propagate(e); - } - - } - - @Override - public InputRowParser getParser() - { - return null; - } - - public class IngestSegmentFirehose implements Firehose - { - private volatile Yielder rowYielder; - - public IngestSegmentFirehose(List adapters, final List dims, final List metrics) - { - Sequence rows = Sequences.concat( - Iterables.transform( - adapters, new Function>() - { - @Nullable - @Override - public Sequence apply(StorageAdapter adapter) - { - return Sequences.concat( - Sequences.map( - adapter.makeCursors( - Filters.convertDimensionFilters(dimFilter), - interval, - QueryGranularity.ALL - ), new Function>() - { - @Nullable - @Override - public Sequence apply(final Cursor cursor) - { - final TimestampColumnSelector timestampColumnSelector = cursor.makeTimestampColumnSelector(); - - final Map dimSelectors = Maps.newHashMap(); - for (String dim : dims) { - final DimensionSelector dimSelector = cursor.makeDimensionSelector(dim); - // dimSelector is null if the dimension is not present - if (dimSelector != null) { - dimSelectors.put(dim, dimSelector); - } - } - - final Map metSelectors = Maps.newHashMap(); - for (String metric : metrics) { - final ObjectColumnSelector metricSelector = cursor.makeObjectColumnSelector(metric); - if (metricSelector != null) { - metSelectors.put(metric, metricSelector); - } - } - - return Sequences.simple( - new Iterable() - { - @Override - public Iterator iterator() - { - return new Iterator() - { - @Override - public boolean hasNext() - { - return !cursor.isDone(); - } - - @Override - public InputRow next() - { - final Map theEvent = Maps.newLinkedHashMap(); - final long timestamp = timestampColumnSelector.getTimestamp(); - theEvent.put(EventHolder.timestampKey, new DateTime(timestamp)); - - for (Map.Entry dimSelector : dimSelectors.entrySet()) { - final String dim = dimSelector.getKey(); - final DimensionSelector selector = dimSelector.getValue(); - final IndexedInts vals = selector.getRow(); - - if (vals.size() == 1) { - final String dimVal = selector.lookupName(vals.get(0)); - theEvent.put(dim, dimVal); - } else { - List dimVals = Lists.newArrayList(); - for (int i = 0; i < vals.size(); ++i) { - dimVals.add(selector.lookupName(vals.get(i))); - } - theEvent.put(dim, dimVals); - } - } - - for (Map.Entry metSelector : metSelectors.entrySet()) { - final String metric = metSelector.getKey(); - final ObjectColumnSelector selector = metSelector.getValue(); - theEvent.put(metric, selector.get()); - } - cursor.advance(); - return new MapBasedInputRow(timestamp, dims, theEvent); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException("Remove Not Supported"); - } - }; - } - } - ); - } - } - ) - ); - } - } - ) - ); - rowYielder = rows.toYielder( - null, - new YieldingAccumulator() - { - @Override - public Object accumulate(Object accumulated, Object in) - { - yield(); - return in; - } - } - ); - } - - @Override - public boolean hasMore() - { - return !rowYielder.isDone(); - } - - @Override - public InputRow nextRow() - { - final InputRow inputRow = rowYielder.get(); - rowYielder = rowYielder.next(null); - return inputRow; - } - - @Override - public Runnable commit() - { - return Runnables.getNoopRunnable(); - } - - @Override - public void close() throws IOException - { - rowYielder.close(); - } - } -} diff --git a/All/Genesis-NP/Genesis#333/old/IngestSegmentFirehoseFactory.java b/All/Genesis-NP/Genesis#333/old/IngestSegmentFirehoseFactory.java deleted file mode 100755 index 94adbc0..0000000 --- a/All/Genesis-NP/Genesis#333/old/IngestSegmentFirehoseFactory.java +++ /dev/null @@ -1,371 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright (C) 2012, 2013, 2014 Metamarkets Group Inc. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.druid.indexing.firehose; - -import com.fasterxml.jackson.annotation.JacksonInject; -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.google.api.client.repackaged.com.google.common.base.Throwables; -import com.google.common.base.Function; -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Ordering; -import com.google.inject.Injector; -import com.metamx.common.guava.Sequence; -import com.metamx.common.guava.Sequences; -import com.metamx.common.guava.Yielder; -import com.metamx.common.guava.YieldingAccumulator; -import com.metamx.common.parsers.ParseException; -import com.metamx.emitter.EmittingLogger; -import io.druid.data.input.Firehose; -import io.druid.data.input.FirehoseFactory; -import io.druid.data.input.InputRow; -import io.druid.data.input.MapBasedInputRow; -import io.druid.data.input.impl.InputRowParser; -import io.druid.granularity.QueryGranularity; -import io.druid.indexing.common.TaskToolbox; -import io.druid.indexing.common.TaskToolboxFactory; -import io.druid.indexing.common.actions.SegmentListUsedAction; -import io.druid.indexing.common.task.NoopTask; -import io.druid.query.filter.DimFilter; -import io.druid.query.select.EventHolder; -import io.druid.segment.Cursor; -import io.druid.segment.DimensionSelector; -import io.druid.segment.IndexIO; -import io.druid.segment.ObjectColumnSelector; -import io.druid.segment.QueryableIndexStorageAdapter; -import io.druid.segment.StorageAdapter; -import io.druid.segment.TimestampColumnSelector; -import io.druid.segment.data.IndexedInts; -import io.druid.segment.filter.Filters; -import io.druid.segment.loading.SegmentLoadingException; -import io.druid.timeline.DataSegment; -import io.druid.timeline.TimelineObjectHolder; -import io.druid.timeline.VersionedIntervalTimeline; -import io.druid.utils.Runnables; -import org.joda.time.DateTime; -import org.joda.time.Interval; - -import javax.annotation.Nullable; -import java.io.File; -import java.io.IOException; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - -public class IngestSegmentFirehoseFactory implements FirehoseFactory -{ - private static final EmittingLogger log = new EmittingLogger(IngestSegmentFirehoseFactory.class); - private final String dataSource; - private final Interval interval; - private final DimFilter dimFilter; - private final List dimensions; - private final List metrics; - private final Injector injector; - - @JsonCreator - public IngestSegmentFirehoseFactory( - @JsonProperty("dataSource") final String dataSource, - @JsonProperty("interval") Interval interval, - @JsonProperty("filter") DimFilter dimFilter, - @JsonProperty("dimensions") List dimensions, - @JsonProperty("metrics") List metrics, - @JacksonInject Injector injector - ) - { - Preconditions.checkNotNull(dataSource, "dataSource"); - Preconditions.checkNotNull(interval, "interval"); - this.dataSource = dataSource; - this.interval = interval; - this.dimFilter = dimFilter; - this.dimensions = dimensions; - this.metrics = metrics; - this.injector = injector; - } - - @JsonProperty - public String getDataSource() - { - return dataSource; - } - - @JsonProperty - public Interval getInterval() - { - return interval; - } - - @JsonProperty("filter") - public DimFilter getDimensionsFilter() - { - return dimFilter; - } - - @JsonProperty - public List getDimensions() - { - return dimensions; - } - - @JsonProperty - public List getMetrics() - { - return metrics; - } - - @Override - public Firehose connect(InputRowParser inputRowParser) throws IOException, ParseException - { - log.info("Connecting firehose: dataSource[%s], interval[%s]", dataSource, interval); - // better way to achieve this is to pass toolbox to Firehose, The instance is initialized Lazily on connect method. - // Noop Task is just used to create the toolbox and list segments. - final TaskToolbox toolbox = injector.getInstance(TaskToolboxFactory.class).build( - new NoopTask("reingest", 0, 0, null, null) - ); - - try { - final List usedSegments = toolbox - .getTaskActionClient() - .submit(new SegmentListUsedAction(dataSource, interval)); - final Map segmentFileMap = toolbox.fetchSegments(usedSegments); - VersionedIntervalTimeline timeline = new VersionedIntervalTimeline( - Ordering.natural().nullsFirst() - ); - - for (DataSegment segment : usedSegments) { - timeline.add(segment.getInterval(), segment.getVersion(), segment.getShardSpec().createChunk(segment)); - } - final List> timeLineSegments = timeline.lookup( - interval - ); - - List dims; - if (dimensions != null) { - dims = dimensions; - } else { - Set dimSet = new HashSet<>(); - for (TimelineObjectHolder timelineObjectHolder : timeLineSegments) { - dimSet.addAll(timelineObjectHolder.getObject().getChunk(0).getObject().getDimensions()); - } - dims = Lists.newArrayList(dimSet); - } - - List metricsList; - if (metrics != null) { - metricsList = metrics; - } else { - Set metricsSet = new HashSet<>(); - for (TimelineObjectHolder timelineObjectHolder : timeLineSegments) { - metricsSet.addAll(timelineObjectHolder.getObject().getChunk(0).getObject().getMetrics()); - } - metricsList = Lists.newArrayList(metricsSet); - } - - - final List adapters = Lists.transform( - timeLineSegments, - new Function, StorageAdapter>() - { - @Override - public StorageAdapter apply(TimelineObjectHolder input) - { - final DataSegment segment = input.getObject().getChunk(0).getObject(); - final File file = Preconditions.checkNotNull( - segmentFileMap.get(segment), - "File for segment %s", segment.getIdentifier() - ); - - try { - return new QueryableIndexStorageAdapter((IndexIO.loadIndex(file))); - } - catch (IOException e) { - throw Throwables.propagate(e); - } - } - } - ); - - return new IngestSegmentFirehose(adapters, dims, metricsList); - - } - catch (IOException e) { - throw Throwables.propagate(e); - } - catch (SegmentLoadingException e) { - throw Throwables.propagate(e); - } - - } - - @Override - public InputRowParser getParser() - { - return null; - } - - public class IngestSegmentFirehose implements Firehose - { - private volatile Yielder rowYielder; - - public IngestSegmentFirehose(List adapters, final List dims, final List metrics) - { - Sequence rows = Sequences.concat( - Iterables.transform( - adapters, new Function>() - { - @Nullable - @Override - public Sequence apply(StorageAdapter adapter) - { - return Sequences.concat( - Sequences.map( - adapter.makeCursors( - Filters.convertDimensionFilters(dimFilter), - interval, - QueryGranularity.ALL - ), new Function>() - { - @Nullable - @Override - public Sequence apply(final Cursor cursor) - { - final TimestampColumnSelector timestampColumnSelector = cursor.makeTimestampColumnSelector(); - - final Map dimSelectors = Maps.newHashMap(); - for (String dim : dims) { - final DimensionSelector dimSelector = cursor.makeDimensionSelector(dim); - dimSelectors.put(dim, dimSelector); - } - - final Map metSelectors = Maps.newHashMap(); - for (String metric : metrics) { - final ObjectColumnSelector metricSelector = cursor.makeObjectColumnSelector(metric); - metSelectors.put(metric, metricSelector); - } - - return Sequences.simple( - new Iterable() - { - @Override - public Iterator iterator() - { - return new Iterator() - { - @Override - public boolean hasNext() - { - return !cursor.isDone(); - } - - @Override - public InputRow next() - { - final Map theEvent = Maps.newLinkedHashMap(); - final long timestamp = timestampColumnSelector.getTimestamp(); - theEvent.put(EventHolder.timestampKey, new DateTime(timestamp)); - - for (Map.Entry dimSelector : dimSelectors.entrySet()) { - final String dim = dimSelector.getKey(); - final DimensionSelector selector = dimSelector.getValue(); - final IndexedInts vals = selector.getRow(); - - if (vals.size() == 1) { - final String dimVal = selector.lookupName(vals.get(0)); - theEvent.put(dim, dimVal); - } else { - List dimVals = Lists.newArrayList(); - for (int i = 0; i < vals.size(); ++i) { - dimVals.add(selector.lookupName(vals.get(i))); - } - theEvent.put(dim, dimVals); - } - } - - for (Map.Entry metSelector : metSelectors.entrySet()) { - final String metric = metSelector.getKey(); - final ObjectColumnSelector selector = metSelector.getValue(); - theEvent.put(metric, selector.get()); - } - cursor.advance(); - return new MapBasedInputRow(timestamp, dims, theEvent); - } - - @Override - public void remove() - { - throw new UnsupportedOperationException("Remove Not Supported"); - } - }; - } - } - ); - } - } - ) - ); - } - } - ) - ); - rowYielder = rows.toYielder( - null, - new YieldingAccumulator() - { - @Override - public Object accumulate(Object accumulated, Object in) - { - yield(); - return in; - } - } - ); - } - - @Override - public boolean hasMore() - { - return !rowYielder.isDone(); - } - - @Override - public InputRow nextRow() - { - final InputRow inputRow = rowYielder.get(); - rowYielder = rowYielder.next(null); - return inputRow; - } - - @Override - public Runnable commit() - { - return Runnables.getNoopRunnable(); - } - - @Override - public void close() throws IOException - { - rowYielder.close(); - } - } -} diff --git a/All/Genesis-NP/Genesis#333/pair.info b/All/Genesis-NP/Genesis#333/pair.info deleted file mode 100755 index ddc134a..0000000 --- a/All/Genesis-NP/Genesis#333/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:333 -SATName:Genesis -modifiedFPath:indexing-service/src/main/java/io/druid/indexing/firehose/IngestSegmentFirehoseFactory.java -comSha:e6d93a307019406c9e4ec26d9d865fd3717feeb7 -parentComSha:e6d93a307019406c9e4ec26d9d865fd3717feeb7^1 -githubUrl:https://github.com/druid-io/druid -repoName:druid-io#druid \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#335/comMsg.txt b/All/Genesis-NP/Genesis#335/comMsg.txt deleted file mode 100755 index c02d3c0..0000000 --- a/All/Genesis-NP/Genesis#335/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix storage class npe diff --git a/All/Genesis-NP/Genesis#335/diff.diff b/All/Genesis-NP/Genesis#335/diff.diff deleted file mode 100755 index 7f0a229..0000000 --- a/All/Genesis-NP/Genesis#335/diff.diff +++ /dev/null @@ -1,23 +0,0 @@ -diff --git a/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentMover.java b/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentMover.java -index ea585a0..379dd83 100644 ---- a/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentMover.java -+++ b/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentMover.java -@@ -26,0 +27 @@ import com.google.inject.Inject; -+import com.metamx.common.ISE; -@@ -123,4 +124,10 @@ public class S3DataSegmentMover implements DataSegmentMover -- } else if (s3Client.getObjectDetails(s3Bucket, s3Path) -- .getStorageClass() -- .equals(S3Object.STORAGE_CLASS_GLACIER)) { -- log.warn("Cannot move file[s3://%s/%s] of storage class glacier."); -+ } else { -+ final S3Object[] list = s3Client.listObjects(s3Bucket, s3Path, ""); -+ if (list.length == 0) { -+ // should never happen -+ throw new ISE("Unable to list object [s3://%s/%s]", s3Bucket, s3Path); -+ } -+ final S3Object s3Object = list[0]; -+ if (s3Object.getStorageClass() != null && -+ s3Object.getStorageClass().equals(S3Object.STORAGE_CLASS_GLACIER)) { -+ log.warn("Cannot move file[s3://%s/%s] of storage class glacier, skipping."); -@@ -140,0 +148 @@ public class S3DataSegmentMover implements DataSegmentMover -+ } diff --git a/All/Genesis-NP/Genesis#335/new/S3DataSegmentMover.java b/All/Genesis-NP/Genesis#335/new/S3DataSegmentMover.java deleted file mode 100755 index 379dd83..0000000 --- a/All/Genesis-NP/Genesis#335/new/S3DataSegmentMover.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright (C) 2012, 2013 Metamarkets Group Inc. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.druid.storage.s3; - -import com.google.common.base.Predicate; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.inject.Inject; -import com.metamx.common.ISE; -import com.metamx.common.MapUtils; -import com.metamx.common.logger.Logger; -import io.druid.segment.loading.DataSegmentMover; -import io.druid.segment.loading.SegmentLoadingException; -import io.druid.timeline.DataSegment; -import org.jets3t.service.ServiceException; -import org.jets3t.service.acl.gs.GSAccessControlList; -import org.jets3t.service.impl.rest.httpclient.RestS3Service; -import org.jets3t.service.model.S3Object; - -import java.util.Map; -import java.util.concurrent.Callable; - -public class S3DataSegmentMover implements DataSegmentMover -{ - private static final Logger log = new Logger(S3DataSegmentMover.class); - - private final RestS3Service s3Client; - private final S3DataSegmentPusherConfig config; - - @Inject - public S3DataSegmentMover( - RestS3Service s3Client, - S3DataSegmentPusherConfig config - ) - { - this.s3Client = s3Client; - this.config = config; - } - - @Override - public DataSegment move(DataSegment segment, Map targetLoadSpec) throws SegmentLoadingException - { - try { - Map loadSpec = segment.getLoadSpec(); - String s3Bucket = MapUtils.getString(loadSpec, "bucket"); - String s3Path = MapUtils.getString(loadSpec, "key"); - String s3DescriptorPath = S3Utils.descriptorPathForSegmentPath(s3Path); - - final String targetS3Bucket = MapUtils.getString(targetLoadSpec, "bucket"); - final String targetS3BaseKey = MapUtils.getString(targetLoadSpec, "baseKey"); - - final String targetS3Path = S3Utils.constructSegmentPath(targetS3BaseKey, segment); - String targetS3DescriptorPath = S3Utils.descriptorPathForSegmentPath(targetS3Path); - - if (targetS3Bucket.isEmpty()) { - throw new SegmentLoadingException("Target S3 bucket is not specified"); - } - if (targetS3Path.isEmpty()) { - throw new SegmentLoadingException("Target S3 baseKey is not specified"); - } - - safeMove(s3Bucket, s3Path, targetS3Bucket, targetS3Path); - safeMove(s3Bucket, s3DescriptorPath, targetS3Bucket, targetS3DescriptorPath); - - return segment.withLoadSpec( - ImmutableMap.builder() - .putAll( - Maps.filterKeys( - loadSpec, new Predicate() - { - @Override - public boolean apply(String input) - { - return !(input.equals("bucket") || input.equals("key")); - } - } - ) - ) - .put("bucket", targetS3Bucket) - .put("key", targetS3Path) - .build() - ); - } - catch (ServiceException e) { - throw new SegmentLoadingException(e, "Unable to move segment[%s]", segment.getIdentifier()); - } - } - - private void safeMove( - final String s3Bucket, - final String s3Path, - final String targetS3Bucket, - final String targetS3Path - ) throws ServiceException, SegmentLoadingException - { - try { - S3Utils.retryS3Operation( - new Callable() - { - @Override - public Void call() throws Exception - { - if (s3Client.isObjectInBucket(s3Bucket, s3Path)) { - if (s3Bucket.equals(targetS3Bucket) && s3Path.equals(targetS3Path)) { - log.info("No need to move file[s3://%s/%s] onto itself", s3Bucket, s3Path); - } else { - final S3Object[] list = s3Client.listObjects(s3Bucket, s3Path, ""); - if (list.length == 0) { - // should never happen - throw new ISE("Unable to list object [s3://%s/%s]", s3Bucket, s3Path); - } - final S3Object s3Object = list[0]; - if (s3Object.getStorageClass() != null && - s3Object.getStorageClass().equals(S3Object.STORAGE_CLASS_GLACIER)) { - log.warn("Cannot move file[s3://%s/%s] of storage class glacier, skipping."); - } else { - log.info( - "Moving file[s3://%s/%s] to [s3://%s/%s]", - s3Bucket, - s3Path, - targetS3Bucket, - targetS3Path - ); - final S3Object target = new S3Object(targetS3Path); - if (!config.getDisableAcl()) { - target.setAcl(GSAccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL); - } - s3Client.moveObject(s3Bucket, s3Path, targetS3Bucket, target, false); - } - } - } else { - // ensure object exists in target location - if (s3Client.isObjectInBucket(targetS3Bucket, targetS3Path)) { - log.info( - "Not moving file [s3://%s/%s], already present in target location [s3://%s/%s]", - s3Bucket, s3Path, - targetS3Bucket, targetS3Path - ); - } else { - throw new SegmentLoadingException( - "Unable to move file [s3://%s/%s] to [s3://%s/%s], not present in either source or target location", - s3Bucket, s3Path, - targetS3Bucket, targetS3Path - ); - } - } - return null; - } - } - ); - } - catch (Exception e) { - Throwables.propagateIfInstanceOf(e, ServiceException.class); - Throwables.propagateIfInstanceOf(e, SegmentLoadingException.class); - throw Throwables.propagate(e); - } - } -} diff --git a/All/Genesis-NP/Genesis#335/old/S3DataSegmentMover.java b/All/Genesis-NP/Genesis#335/old/S3DataSegmentMover.java deleted file mode 100755 index ea585a0..0000000 --- a/All/Genesis-NP/Genesis#335/old/S3DataSegmentMover.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright (C) 2012, 2013 Metamarkets Group Inc. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.druid.storage.s3; - -import com.google.common.base.Predicate; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.inject.Inject; -import com.metamx.common.MapUtils; -import com.metamx.common.logger.Logger; -import io.druid.segment.loading.DataSegmentMover; -import io.druid.segment.loading.SegmentLoadingException; -import io.druid.timeline.DataSegment; -import org.jets3t.service.ServiceException; -import org.jets3t.service.acl.gs.GSAccessControlList; -import org.jets3t.service.impl.rest.httpclient.RestS3Service; -import org.jets3t.service.model.S3Object; - -import java.util.Map; -import java.util.concurrent.Callable; - -public class S3DataSegmentMover implements DataSegmentMover -{ - private static final Logger log = new Logger(S3DataSegmentMover.class); - - private final RestS3Service s3Client; - private final S3DataSegmentPusherConfig config; - - @Inject - public S3DataSegmentMover( - RestS3Service s3Client, - S3DataSegmentPusherConfig config - ) - { - this.s3Client = s3Client; - this.config = config; - } - - @Override - public DataSegment move(DataSegment segment, Map targetLoadSpec) throws SegmentLoadingException - { - try { - Map loadSpec = segment.getLoadSpec(); - String s3Bucket = MapUtils.getString(loadSpec, "bucket"); - String s3Path = MapUtils.getString(loadSpec, "key"); - String s3DescriptorPath = S3Utils.descriptorPathForSegmentPath(s3Path); - - final String targetS3Bucket = MapUtils.getString(targetLoadSpec, "bucket"); - final String targetS3BaseKey = MapUtils.getString(targetLoadSpec, "baseKey"); - - final String targetS3Path = S3Utils.constructSegmentPath(targetS3BaseKey, segment); - String targetS3DescriptorPath = S3Utils.descriptorPathForSegmentPath(targetS3Path); - - if (targetS3Bucket.isEmpty()) { - throw new SegmentLoadingException("Target S3 bucket is not specified"); - } - if (targetS3Path.isEmpty()) { - throw new SegmentLoadingException("Target S3 baseKey is not specified"); - } - - safeMove(s3Bucket, s3Path, targetS3Bucket, targetS3Path); - safeMove(s3Bucket, s3DescriptorPath, targetS3Bucket, targetS3DescriptorPath); - - return segment.withLoadSpec( - ImmutableMap.builder() - .putAll( - Maps.filterKeys( - loadSpec, new Predicate() - { - @Override - public boolean apply(String input) - { - return !(input.equals("bucket") || input.equals("key")); - } - } - ) - ) - .put("bucket", targetS3Bucket) - .put("key", targetS3Path) - .build() - ); - } - catch (ServiceException e) { - throw new SegmentLoadingException(e, "Unable to move segment[%s]", segment.getIdentifier()); - } - } - - private void safeMove( - final String s3Bucket, - final String s3Path, - final String targetS3Bucket, - final String targetS3Path - ) throws ServiceException, SegmentLoadingException - { - try { - S3Utils.retryS3Operation( - new Callable() - { - @Override - public Void call() throws Exception - { - if (s3Client.isObjectInBucket(s3Bucket, s3Path)) { - if (s3Bucket.equals(targetS3Bucket) && s3Path.equals(targetS3Path)) { - log.info("No need to move file[s3://%s/%s] onto itself", s3Bucket, s3Path); - } else if (s3Client.getObjectDetails(s3Bucket, s3Path) - .getStorageClass() - .equals(S3Object.STORAGE_CLASS_GLACIER)) { - log.warn("Cannot move file[s3://%s/%s] of storage class glacier."); - } else { - log.info( - "Moving file[s3://%s/%s] to [s3://%s/%s]", - s3Bucket, - s3Path, - targetS3Bucket, - targetS3Path - ); - final S3Object target = new S3Object(targetS3Path); - if(!config.getDisableAcl()) { - target.setAcl(GSAccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL); - } - s3Client.moveObject(s3Bucket, s3Path, targetS3Bucket, target, false); - } - } else { - // ensure object exists in target location - if (s3Client.isObjectInBucket(targetS3Bucket, targetS3Path)) { - log.info( - "Not moving file [s3://%s/%s], already present in target location [s3://%s/%s]", - s3Bucket, s3Path, - targetS3Bucket, targetS3Path - ); - } else { - throw new SegmentLoadingException( - "Unable to move file [s3://%s/%s] to [s3://%s/%s], not present in either source or target location", - s3Bucket, s3Path, - targetS3Bucket, targetS3Path - ); - } - } - return null; - } - } - ); - } - catch (Exception e) { - Throwables.propagateIfInstanceOf(e, ServiceException.class); - Throwables.propagateIfInstanceOf(e, SegmentLoadingException.class); - throw Throwables.propagate(e); - } - } -} diff --git a/All/Genesis-NP/Genesis#335/pair.info b/All/Genesis-NP/Genesis#335/pair.info deleted file mode 100755 index 08a991f..0000000 --- a/All/Genesis-NP/Genesis#335/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:335 -SATName:Genesis -modifiedFPath:s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentMover.java -comSha:f56d60b4511d15c3caaeda1dee56b8deb3f14c4b -parentComSha:f56d60b4511d15c3caaeda1dee56b8deb3f14c4b^1 -githubUrl:https://github.com/druid-io/druid -repoName:druid-io#druid \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#336/comMsg.txt b/All/Genesis-NP/Genesis#336/comMsg.txt deleted file mode 100755 index 167c925..0000000 --- a/All/Genesis-NP/Genesis#336/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix npe in topNBinaryFn with post aggs diff --git a/All/Genesis-NP/Genesis#336/diff.diff b/All/Genesis-NP/Genesis#336/diff.diff deleted file mode 100755 index f976e07..0000000 --- a/All/Genesis-NP/Genesis#336/diff.diff +++ /dev/null @@ -1,33 +0,0 @@ -diff --git a/processing/src/main/java/io/druid/query/topn/TopNBinaryFn.java b/processing/src/main/java/io/druid/query/topn/TopNBinaryFn.java -index 18d7fa0..fd2b7a2 100644 ---- a/processing/src/main/java/io/druid/query/topn/TopNBinaryFn.java -+++ b/processing/src/main/java/io/druid/query/topn/TopNBinaryFn.java -@@ -94 +94,13 @@ public class TopNBinaryFn implements BinaryFn, Result retVal = new LinkedHashMap(aggregations.size() + 2); -+ retVal.put(dimension, dimensionValue); -+ -+ for (AggregatorFactory factory : aggregations) { -+ final String metricName = factory.getName(); -+ retVal.put(metricName, arg1Val.getMetric(metricName)); -+ } -+ for (PostAggregator postAgg : postAggregations) { -+ retVal.put(postAgg.getName(), postAgg.compute(retVal)); -+ } -+ -+ retVals.put(dimensionValue, new DimensionAndMetricValueExtractor(retVal)); -@@ -115 +127,12 @@ public class TopNBinaryFn implements BinaryFn, Result retVal = new LinkedHashMap(aggregations.size() + 2); -+ retVal.put(dimension, dimensionValue); -+ -+ for (AggregatorFactory factory : aggregations) { -+ final String metricName = factory.getName(); -+ retVal.put(metricName, arg2Val.getMetric(metricName)); -+ } -+ for (PostAggregator postAgg : postAggregations) { -+ retVal.put(postAgg.getName(), postAgg.compute(retVal)); -+ } -+ -+ retVals.put(dimensionValue, new DimensionAndMetricValueExtractor(retVal)); diff --git a/All/Genesis-NP/Genesis#336/new/TopNBinaryFn.java b/All/Genesis-NP/Genesis#336/new/TopNBinaryFn.java deleted file mode 100755 index fd2b7a2..0000000 --- a/All/Genesis-NP/Genesis#336/new/TopNBinaryFn.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright (C) 2012, 2013 Metamarkets Group Inc. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.druid.query.topn; - -import com.metamx.common.guava.nary.BinaryFn; -import io.druid.granularity.AllGranularity; -import io.druid.granularity.QueryGranularity; -import io.druid.query.Result; -import io.druid.query.aggregation.AggregatorFactory; -import io.druid.query.aggregation.AggregatorUtil; -import io.druid.query.aggregation.PostAggregator; -import io.druid.query.dimension.DimensionSpec; -import org.joda.time.DateTime; - -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - */ -public class TopNBinaryFn implements BinaryFn, Result, Result> -{ - private final TopNResultMerger merger; - private final DimensionSpec dimSpec; - private final QueryGranularity gran; - private final DimensionSpec dimensionSpec; - private final TopNMetricSpec topNMetricSpec; - private final int threshold; - private final List aggregations; - private final List postAggregations; - private final Comparator comparator; - - public TopNBinaryFn( - final TopNResultMerger merger, - final QueryGranularity granularity, - final DimensionSpec dimSpec, - final TopNMetricSpec topNMetricSpec, - final int threshold, - final List aggregatorSpecs, - final List postAggregatorSpecs - ) - { - this.merger = merger; - this.dimSpec = dimSpec; - this.gran = granularity; - this.topNMetricSpec = topNMetricSpec; - this.threshold = threshold; - this.aggregations = aggregatorSpecs; - this.dimensionSpec = dimSpec; - - this.postAggregations = AggregatorUtil.pruneDependentPostAgg( - postAggregatorSpecs, - this.topNMetricSpec.getMetricName(this.dimensionSpec) - ); - - this.comparator = topNMetricSpec.getComparator(aggregatorSpecs, postAggregatorSpecs); - } - - @Override - public Result apply(Result arg1, Result arg2) - { - if (arg1 == null) { - return merger.getResult(arg2, comparator); - } - if (arg2 == null) { - return merger.getResult(arg1, comparator); - } - - - TopNResultValue arg1Vals = arg1.getValue(); - TopNResultValue arg2Vals = arg2.getValue(); - Map retVals = new LinkedHashMap(); - - String dimension = dimensionSpec.getOutputName(); - for (DimensionAndMetricValueExtractor arg1Val : arg1Vals) { - final String dimensionValue = arg1Val.getStringDimensionValue(dimension); - Map retVal = new LinkedHashMap(aggregations.size() + 2); - retVal.put(dimension, dimensionValue); - - for (AggregatorFactory factory : aggregations) { - final String metricName = factory.getName(); - retVal.put(metricName, arg1Val.getMetric(metricName)); - } - for (PostAggregator postAgg : postAggregations) { - retVal.put(postAgg.getName(), postAgg.compute(retVal)); - } - - retVals.put(dimensionValue, new DimensionAndMetricValueExtractor(retVal)); - } - for (DimensionAndMetricValueExtractor arg2Val : arg2Vals) { - final String dimensionValue = arg2Val.getStringDimensionValue(dimension); - DimensionAndMetricValueExtractor arg1Val = retVals.get(dimensionValue); - - if (arg1Val != null) { - // size of map = aggregator + topNDim + postAgg (If sorting is done on post agg field) - Map retVal = new LinkedHashMap(aggregations.size() + 2); - - retVal.put(dimension, dimensionValue); - for (AggregatorFactory factory : aggregations) { - final String metricName = factory.getName(); - retVal.put(metricName, factory.combine(arg1Val.getMetric(metricName), arg2Val.getMetric(metricName))); - } - for (PostAggregator postAgg : postAggregations) { - retVal.put(postAgg.getName(), postAgg.compute(retVal)); - } - - retVals.put(dimensionValue, new DimensionAndMetricValueExtractor(retVal)); - } else { - Map retVal = new LinkedHashMap(aggregations.size() + 2); - retVal.put(dimension, dimensionValue); - - for (AggregatorFactory factory : aggregations) { - final String metricName = factory.getName(); - retVal.put(metricName, arg2Val.getMetric(metricName)); - } - for (PostAggregator postAgg : postAggregations) { - retVal.put(postAgg.getName(), postAgg.compute(retVal)); - } - - retVals.put(dimensionValue, new DimensionAndMetricValueExtractor(retVal)); - } - } - - final DateTime timestamp; - if (gran instanceof AllGranularity) { - timestamp = arg1.getTimestamp(); - } else { - timestamp = gran.toDateTime(gran.truncate(arg1.getTimestamp().getMillis())); - } - - TopNResultBuilder bob = topNMetricSpec.getResultBuilder( - timestamp, - dimSpec, - threshold, - comparator, - aggregations, - postAggregations - ); - for (DimensionAndMetricValueExtractor extractor : retVals.values()) { - bob.addEntry(extractor); - } - return bob.build(); - } -} diff --git a/All/Genesis-NP/Genesis#336/old/TopNBinaryFn.java b/All/Genesis-NP/Genesis#336/old/TopNBinaryFn.java deleted file mode 100755 index 18d7fa0..0000000 --- a/All/Genesis-NP/Genesis#336/old/TopNBinaryFn.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright (C) 2012, 2013 Metamarkets Group Inc. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.druid.query.topn; - -import com.metamx.common.guava.nary.BinaryFn; -import io.druid.granularity.AllGranularity; -import io.druid.granularity.QueryGranularity; -import io.druid.query.Result; -import io.druid.query.aggregation.AggregatorFactory; -import io.druid.query.aggregation.AggregatorUtil; -import io.druid.query.aggregation.PostAggregator; -import io.druid.query.dimension.DimensionSpec; -import org.joda.time.DateTime; - -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -/** - */ -public class TopNBinaryFn implements BinaryFn, Result, Result> -{ - private final TopNResultMerger merger; - private final DimensionSpec dimSpec; - private final QueryGranularity gran; - private final DimensionSpec dimensionSpec; - private final TopNMetricSpec topNMetricSpec; - private final int threshold; - private final List aggregations; - private final List postAggregations; - private final Comparator comparator; - - public TopNBinaryFn( - final TopNResultMerger merger, - final QueryGranularity granularity, - final DimensionSpec dimSpec, - final TopNMetricSpec topNMetricSpec, - final int threshold, - final List aggregatorSpecs, - final List postAggregatorSpecs - ) - { - this.merger = merger; - this.dimSpec = dimSpec; - this.gran = granularity; - this.topNMetricSpec = topNMetricSpec; - this.threshold = threshold; - this.aggregations = aggregatorSpecs; - this.dimensionSpec = dimSpec; - - this.postAggregations = AggregatorUtil.pruneDependentPostAgg( - postAggregatorSpecs, - this.topNMetricSpec.getMetricName(this.dimensionSpec) - ); - - this.comparator = topNMetricSpec.getComparator(aggregatorSpecs, postAggregatorSpecs); - } - - @Override - public Result apply(Result arg1, Result arg2) - { - if (arg1 == null) { - return merger.getResult(arg2, comparator); - } - if (arg2 == null) { - return merger.getResult(arg1, comparator); - } - - - TopNResultValue arg1Vals = arg1.getValue(); - TopNResultValue arg2Vals = arg2.getValue(); - Map retVals = new LinkedHashMap(); - - String dimension = dimensionSpec.getOutputName(); - for (DimensionAndMetricValueExtractor arg1Val : arg1Vals) { - retVals.put(arg1Val.getStringDimensionValue(dimension), arg1Val); - } - for (DimensionAndMetricValueExtractor arg2Val : arg2Vals) { - final String dimensionValue = arg2Val.getStringDimensionValue(dimension); - DimensionAndMetricValueExtractor arg1Val = retVals.get(dimensionValue); - - if (arg1Val != null) { - // size of map = aggregator + topNDim + postAgg (If sorting is done on post agg field) - Map retVal = new LinkedHashMap(aggregations.size() + 2); - - retVal.put(dimension, dimensionValue); - for (AggregatorFactory factory : aggregations) { - final String metricName = factory.getName(); - retVal.put(metricName, factory.combine(arg1Val.getMetric(metricName), arg2Val.getMetric(metricName))); - } - for (PostAggregator postAgg : postAggregations) { - retVal.put(postAgg.getName(), postAgg.compute(retVal)); - } - - retVals.put(dimensionValue, new DimensionAndMetricValueExtractor(retVal)); - } else { - retVals.put(dimensionValue, arg2Val); - } - } - - final DateTime timestamp; - if (gran instanceof AllGranularity) { - timestamp = arg1.getTimestamp(); - } else { - timestamp = gran.toDateTime(gran.truncate(arg1.getTimestamp().getMillis())); - } - - TopNResultBuilder bob = topNMetricSpec.getResultBuilder( - timestamp, - dimSpec, - threshold, - comparator, - aggregations, - postAggregations - ); - for (DimensionAndMetricValueExtractor extractor : retVals.values()) { - bob.addEntry(extractor); - } - return bob.build(); - } -} diff --git a/All/Genesis-NP/Genesis#336/pair.info b/All/Genesis-NP/Genesis#336/pair.info deleted file mode 100755 index ae2b9b3..0000000 --- a/All/Genesis-NP/Genesis#336/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:336 -SATName:Genesis -modifiedFPath:processing/src/main/java/io/druid/query/topn/TopNBinaryFn.java -comSha:bbedde3418ba0a83a1777681d549b3ff1295b000 -parentComSha:bbedde3418ba0a83a1777681d549b3ff1295b000^1 -githubUrl:https://github.com/druid-io/druid -repoName:druid-io#druid \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#342/comMsg.txt b/All/Genesis-NP/Genesis#342/comMsg.txt deleted file mode 100755 index bf6fd5a..0000000 --- a/All/Genesis-NP/Genesis#342/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix NPE in DirectDruidClient diff --git a/All/Genesis-NP/Genesis#342/diff.diff b/All/Genesis-NP/Genesis#342/diff.diff deleted file mode 100755 index 2794bca..0000000 --- a/All/Genesis-NP/Genesis#342/diff.diff +++ /dev/null @@ -1,8 +0,0 @@ -diff --git a/server/src/main/java/io/druid/client/DirectDruidClient.java b/server/src/main/java/io/druid/client/DirectDruidClient.java -index 5292628..8befef5 100644 ---- a/server/src/main/java/io/druid/client/DirectDruidClient.java -+++ b/server/src/main/java/io/druid/client/DirectDruidClient.java -@@ -294,0 +295 @@ public class DirectDruidClient implements QueryRunner -+ if(jp != null) { -@@ -298,0 +300 @@ public class DirectDruidClient implements QueryRunner -+} diff --git a/All/Genesis-NP/Genesis#342/new/DirectDruidClient.java b/All/Genesis-NP/Genesis#342/new/DirectDruidClient.java deleted file mode 100755 index 8befef5..0000000 --- a/All/Genesis-NP/Genesis#342/new/DirectDruidClient.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright (C) 2012, 2013 Metamarkets Group Inc. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.druid.client; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.type.TypeFactory; -import com.fasterxml.jackson.dataformat.smile.SmileFactory; -import com.google.common.base.Throwables; -import com.google.common.collect.Maps; -import com.google.common.io.Closeables; -import com.metamx.common.IAE; -import com.metamx.common.Pair; -import com.metamx.common.guava.BaseSequence; -import com.metamx.common.guava.Sequence; -import com.metamx.common.guava.Sequences; -import com.metamx.common.logger.Logger; -import com.metamx.http.client.HttpClient; -import com.metamx.http.client.io.AppendableByteArrayInputStream; -import com.metamx.http.client.response.ClientResponse; -import com.metamx.http.client.response.InputStreamResponseHandler; -import io.druid.query.BySegmentResultValueClass; -import io.druid.query.Query; -import io.druid.query.QueryRunner; -import io.druid.query.QueryToolChest; -import io.druid.query.QueryToolChestWarehouse; -import io.druid.query.Result; -import io.druid.query.aggregation.AggregatorFactory; -import io.druid.query.aggregation.MetricManipulationFn; -import org.jboss.netty.handler.codec.http.HttpChunk; -import org.jboss.netty.handler.codec.http.HttpHeaders; -import org.jboss.netty.handler.codec.http.HttpResponse; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Iterator; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicInteger; - -/** - */ -public class DirectDruidClient implements QueryRunner -{ - private static final Logger log = new Logger(DirectDruidClient.class); - - private static final Map, Pair> typesMap = Maps.newConcurrentMap(); - - private final QueryToolChestWarehouse warehouse; - private final ObjectMapper objectMapper; - private final HttpClient httpClient; - private final String host; - - private final AtomicInteger openConnections; - private final boolean isSmile; - - public DirectDruidClient( - QueryToolChestWarehouse warehouse, - ObjectMapper objectMapper, - HttpClient httpClient, - String host - ) - { - this.warehouse = warehouse; - this.objectMapper = objectMapper; - this.httpClient = httpClient; - this.host = host; - - this.isSmile = this.objectMapper.getFactory() instanceof SmileFactory; - this.openConnections = new AtomicInteger(); - } - - public int getNumOpenConnections() - { - return openConnections.get(); - } - - @Override - public Sequence run(Query query) - { - QueryToolChest> toolChest = warehouse.getToolChest(query); - boolean isBySegment = Boolean.parseBoolean(query.getContextValue("bySegment", "false")); - - Pair types = typesMap.get(query.getClass()); - if (types == null) { - final TypeFactory typeFactory = objectMapper.getTypeFactory(); - JavaType baseType = typeFactory.constructType(toolChest.getResultTypeReference()); - JavaType bySegmentType = typeFactory.constructParametricType( - Result.class, typeFactory.constructParametricType(BySegmentResultValueClass.class, baseType) - ); - types = Pair.of(baseType, bySegmentType); - typesMap.put(query.getClass(), types); - } - - final JavaType typeRef; - if (isBySegment) { - typeRef = types.rhs; - } - else { - typeRef = types.lhs; - } - - final Future future; - final String url = String.format("http://%s/druid/v2/", host); - - try { - log.debug("Querying url[%s]", url); - openConnections.getAndIncrement(); - future = httpClient - .post(new URL(url)) - .setContent(objectMapper.writeValueAsBytes(query)) - .setHeader(HttpHeaders.Names.CONTENT_TYPE, isSmile ? "application/smile" : "application/json") - .go( - new InputStreamResponseHandler() - { - long startTime; - long byteCount = 0; - - @Override - public ClientResponse handleResponse(HttpResponse response) - { - log.debug("Initial response from url[%s]", url); - startTime = System.currentTimeMillis(); - byteCount += response.getContent().readableBytes(); - return super.handleResponse(response); - } - - @Override - public ClientResponse handleChunk( - ClientResponse clientResponse, HttpChunk chunk - ) - { - final int bytes = chunk.getContent().readableBytes(); - byteCount += bytes; - return super.handleChunk(clientResponse, chunk); - } - - @Override - public ClientResponse done(ClientResponse clientResponse) - { - long stopTime = System.currentTimeMillis(); - log.debug( - "Completed request to url[%s] with %,d bytes returned in %,d millis [%,f b/s].", - url, - byteCount, - stopTime - startTime, - byteCount / (0.0001 * (stopTime - startTime)) - ); - openConnections.getAndDecrement(); - return super.done(clientResponse); - } - } - ); - } - catch (IOException e) { - throw Throwables.propagate(e); - } - - Sequence retVal = new BaseSequence>( - new BaseSequence.IteratorMaker>() - { - @Override - public JsonParserIterator make() - { - return new JsonParserIterator(typeRef, future); - } - - @Override - public void cleanup(JsonParserIterator iterFromMake) - { - Closeables.closeQuietly(iterFromMake); - } - } - ); - - if (!isBySegment) { - retVal = Sequences.map( - retVal, - toolChest.makeMetricManipulatorFn( - query, new MetricManipulationFn() - { - @Override - public Object manipulate(AggregatorFactory factory, Object object) - { - return factory.deserialize(object); - } - } - ) - ); - } - - return retVal; - } - - private class JsonParserIterator implements Iterator, Closeable - { - private JsonParser jp; - private ObjectCodec objectCodec; - private final JavaType typeRef; - private final Future future; - - public JsonParserIterator(JavaType typeRef, Future future) - { - this.typeRef = typeRef; - this.future = future; - jp = null; - } - - @Override - public boolean hasNext() - { - init(); - - if (jp.isClosed()) { - return false; - } - if (jp.getCurrentToken() == JsonToken.END_ARRAY) { - Closeables.closeQuietly(jp); - return false; - } - - return true; - } - - @Override - public T next() - { - init(); - try { - final T retVal = objectCodec.readValue(jp, typeRef); - jp.nextToken(); - return retVal; - } - catch (IOException e) { - throw Throwables.propagate(e); - } - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - private void init() - { - if (jp == null) { - try { - jp = objectMapper.getFactory().createParser(future.get()); - if (jp.nextToken() != JsonToken.START_ARRAY) { - throw new IAE("Next token wasn't a START_ARRAY, was[%s]", jp.getCurrentToken()); - } else { - jp.nextToken(); - objectCodec = jp.getCodec(); - } - } - catch (IOException e) { - throw Throwables.propagate(e); - } - catch (InterruptedException e) { - throw Throwables.propagate(e); - } - catch (ExecutionException e) { - throw Throwables.propagate(e); - } - } - } - - @Override - public void close() throws IOException - { - if(jp != null) { - jp.close(); - } - } - } -} diff --git a/All/Genesis-NP/Genesis#342/old/DirectDruidClient.java b/All/Genesis-NP/Genesis#342/old/DirectDruidClient.java deleted file mode 100755 index 5292628..0000000 --- a/All/Genesis-NP/Genesis#342/old/DirectDruidClient.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Druid - a distributed column store. - * Copyright (C) 2012, 2013 Metamarkets Group Inc. - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ - -package io.druid.client; - -import com.fasterxml.jackson.core.JsonParser; -import com.fasterxml.jackson.core.JsonToken; -import com.fasterxml.jackson.core.ObjectCodec; -import com.fasterxml.jackson.databind.JavaType; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.type.TypeFactory; -import com.fasterxml.jackson.dataformat.smile.SmileFactory; -import com.google.common.base.Throwables; -import com.google.common.collect.Maps; -import com.google.common.io.Closeables; -import com.metamx.common.IAE; -import com.metamx.common.Pair; -import com.metamx.common.guava.BaseSequence; -import com.metamx.common.guava.Sequence; -import com.metamx.common.guava.Sequences; -import com.metamx.common.logger.Logger; -import com.metamx.http.client.HttpClient; -import com.metamx.http.client.io.AppendableByteArrayInputStream; -import com.metamx.http.client.response.ClientResponse; -import com.metamx.http.client.response.InputStreamResponseHandler; -import io.druid.query.BySegmentResultValueClass; -import io.druid.query.Query; -import io.druid.query.QueryRunner; -import io.druid.query.QueryToolChest; -import io.druid.query.QueryToolChestWarehouse; -import io.druid.query.Result; -import io.druid.query.aggregation.AggregatorFactory; -import io.druid.query.aggregation.MetricManipulationFn; -import org.jboss.netty.handler.codec.http.HttpChunk; -import org.jboss.netty.handler.codec.http.HttpHeaders; -import org.jboss.netty.handler.codec.http.HttpResponse; - -import java.io.Closeable; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.Iterator; -import java.util.Map; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; -import java.util.concurrent.atomic.AtomicInteger; - -/** - */ -public class DirectDruidClient implements QueryRunner -{ - private static final Logger log = new Logger(DirectDruidClient.class); - - private static final Map, Pair> typesMap = Maps.newConcurrentMap(); - - private final QueryToolChestWarehouse warehouse; - private final ObjectMapper objectMapper; - private final HttpClient httpClient; - private final String host; - - private final AtomicInteger openConnections; - private final boolean isSmile; - - public DirectDruidClient( - QueryToolChestWarehouse warehouse, - ObjectMapper objectMapper, - HttpClient httpClient, - String host - ) - { - this.warehouse = warehouse; - this.objectMapper = objectMapper; - this.httpClient = httpClient; - this.host = host; - - this.isSmile = this.objectMapper.getFactory() instanceof SmileFactory; - this.openConnections = new AtomicInteger(); - } - - public int getNumOpenConnections() - { - return openConnections.get(); - } - - @Override - public Sequence run(Query query) - { - QueryToolChest> toolChest = warehouse.getToolChest(query); - boolean isBySegment = Boolean.parseBoolean(query.getContextValue("bySegment", "false")); - - Pair types = typesMap.get(query.getClass()); - if (types == null) { - final TypeFactory typeFactory = objectMapper.getTypeFactory(); - JavaType baseType = typeFactory.constructType(toolChest.getResultTypeReference()); - JavaType bySegmentType = typeFactory.constructParametricType( - Result.class, typeFactory.constructParametricType(BySegmentResultValueClass.class, baseType) - ); - types = Pair.of(baseType, bySegmentType); - typesMap.put(query.getClass(), types); - } - - final JavaType typeRef; - if (isBySegment) { - typeRef = types.rhs; - } - else { - typeRef = types.lhs; - } - - final Future future; - final String url = String.format("http://%s/druid/v2/", host); - - try { - log.debug("Querying url[%s]", url); - openConnections.getAndIncrement(); - future = httpClient - .post(new URL(url)) - .setContent(objectMapper.writeValueAsBytes(query)) - .setHeader(HttpHeaders.Names.CONTENT_TYPE, isSmile ? "application/smile" : "application/json") - .go( - new InputStreamResponseHandler() - { - long startTime; - long byteCount = 0; - - @Override - public ClientResponse handleResponse(HttpResponse response) - { - log.debug("Initial response from url[%s]", url); - startTime = System.currentTimeMillis(); - byteCount += response.getContent().readableBytes(); - return super.handleResponse(response); - } - - @Override - public ClientResponse handleChunk( - ClientResponse clientResponse, HttpChunk chunk - ) - { - final int bytes = chunk.getContent().readableBytes(); - byteCount += bytes; - return super.handleChunk(clientResponse, chunk); - } - - @Override - public ClientResponse done(ClientResponse clientResponse) - { - long stopTime = System.currentTimeMillis(); - log.debug( - "Completed request to url[%s] with %,d bytes returned in %,d millis [%,f b/s].", - url, - byteCount, - stopTime - startTime, - byteCount / (0.0001 * (stopTime - startTime)) - ); - openConnections.getAndDecrement(); - return super.done(clientResponse); - } - } - ); - } - catch (IOException e) { - throw Throwables.propagate(e); - } - - Sequence retVal = new BaseSequence>( - new BaseSequence.IteratorMaker>() - { - @Override - public JsonParserIterator make() - { - return new JsonParserIterator(typeRef, future); - } - - @Override - public void cleanup(JsonParserIterator iterFromMake) - { - Closeables.closeQuietly(iterFromMake); - } - } - ); - - if (!isBySegment) { - retVal = Sequences.map( - retVal, - toolChest.makeMetricManipulatorFn( - query, new MetricManipulationFn() - { - @Override - public Object manipulate(AggregatorFactory factory, Object object) - { - return factory.deserialize(object); - } - } - ) - ); - } - - return retVal; - } - - private class JsonParserIterator implements Iterator, Closeable - { - private JsonParser jp; - private ObjectCodec objectCodec; - private final JavaType typeRef; - private final Future future; - - public JsonParserIterator(JavaType typeRef, Future future) - { - this.typeRef = typeRef; - this.future = future; - jp = null; - } - - @Override - public boolean hasNext() - { - init(); - - if (jp.isClosed()) { - return false; - } - if (jp.getCurrentToken() == JsonToken.END_ARRAY) { - Closeables.closeQuietly(jp); - return false; - } - - return true; - } - - @Override - public T next() - { - init(); - try { - final T retVal = objectCodec.readValue(jp, typeRef); - jp.nextToken(); - return retVal; - } - catch (IOException e) { - throw Throwables.propagate(e); - } - } - - @Override - public void remove() - { - throw new UnsupportedOperationException(); - } - - private void init() - { - if (jp == null) { - try { - jp = objectMapper.getFactory().createParser(future.get()); - if (jp.nextToken() != JsonToken.START_ARRAY) { - throw new IAE("Next token wasn't a START_ARRAY, was[%s]", jp.getCurrentToken()); - } else { - jp.nextToken(); - objectCodec = jp.getCodec(); - } - } - catch (IOException e) { - throw Throwables.propagate(e); - } - catch (InterruptedException e) { - throw Throwables.propagate(e); - } - catch (ExecutionException e) { - throw Throwables.propagate(e); - } - } - } - - @Override - public void close() throws IOException - { - jp.close(); - } - } -} diff --git a/All/Genesis-NP/Genesis#342/pair.info b/All/Genesis-NP/Genesis#342/pair.info deleted file mode 100755 index 6218d11..0000000 --- a/All/Genesis-NP/Genesis#342/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:342 -SATName:Genesis -modifiedFPath:server/src/main/java/io/druid/client/DirectDruidClient.java -comSha:3134affac9e1f6fc628289f345c1f0ebfdbf6307 -parentComSha:3134affac9e1f6fc628289f345c1f0ebfdbf6307^1 -githubUrl:https://github.com/druid-io/druid -repoName:druid-io#druid \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#347/comMsg.txt b/All/Genesis-NP/Genesis#347/comMsg.txt deleted file mode 100755 index b61d265..0000000 --- a/All/Genesis-NP/Genesis#347/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -NULL_TO_DEFAULTDEFAULTinsertnullNPE diff --git a/All/Genesis-NP/Genesis#347/diff.diff b/All/Genesis-NP/Genesis#347/diff.diff deleted file mode 100755 index 9f0bbcf..0000000 --- a/All/Genesis-NP/Genesis#347/diff.diff +++ /dev/null @@ -1,24 +0,0 @@ -diff --git a/lealone-db/src/main/java/org/lealone/db/table/Column.java b/lealone-db/src/main/java/org/lealone/db/table/Column.java -index a6fcd71..8b26436 100644 ---- a/lealone-db/src/main/java/org/lealone/db/table/Column.java -+++ b/lealone-db/src/main/java/org/lealone/db/table/Column.java -@@ -270,0 +271,6 @@ public class Column { -+ // take a local copy of defaultExpression to avoid holding the lock -+ // while calling getValue -+ final Expression localDefaultExpression; -+ synchronized (this) { -+ localDefaultExpression = defaultExpression; -+ } -@@ -272 +278 @@ public class Column { -- if (defaultExpression == null) { -+ if (localDefaultExpression == null) { -@@ -276 +282 @@ public class Column { -- value = defaultExpression.getValue(session).convertTo(type); -+ value = localDefaultExpression.getValue(session).convertTo(type); -@@ -285,4 +291,2 @@ public class Column { -- if (convertNullToDefault) { -- synchronized (this) { -- value = defaultExpression.getValue(session).convertTo(type); -- } -+ if (convertNullToDefault && localDefaultExpression != null) { -+ value = localDefaultExpression.getValue(session).convertTo(type); diff --git a/All/Genesis-NP/Genesis#347/new/Column.java b/All/Genesis-NP/Genesis#347/new/Column.java deleted file mode 100755 index 8b26436..0000000 --- a/All/Genesis-NP/Genesis#347/new/Column.java +++ /dev/null @@ -1,757 +0,0 @@ -/* - * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, - * Version 1.0, and under the Eclipse Public License, Version 1.0 - * (http://h2database.com/html/license.html). - * Initial Developer: H2 Group - */ -package org.lealone.db.table; - -import java.sql.Date; -import java.sql.ResultSetMetaData; -import java.sql.Timestamp; - -import org.lealone.api.ErrorCode; -import org.lealone.common.exceptions.DbException; -import org.lealone.common.util.MathUtils; -import org.lealone.common.util.StringUtils; -import org.lealone.db.Constants; -import org.lealone.db.Mode; -import org.lealone.db.SQLEngineHolder; -import org.lealone.db.ServerSession; -import org.lealone.db.expression.Expression; -import org.lealone.db.expression.ExpressionVisitor; -import org.lealone.db.result.Row; -import org.lealone.db.schema.Schema; -import org.lealone.db.schema.Sequence; -import org.lealone.db.value.DataType; -import org.lealone.db.value.Value; -import org.lealone.db.value.ValueDate; -import org.lealone.db.value.ValueInt; -import org.lealone.db.value.ValueLong; -import org.lealone.db.value.ValueNull; -import org.lealone.db.value.ValueString; -import org.lealone.db.value.ValueTime; -import org.lealone.db.value.ValueTimestamp; -import org.lealone.db.value.ValueUuid; - -/** - * This class represents a column in a table. - */ -public class Column { - - /** - * The name of the rowid pseudo column. - */ - public static final String ROWID = "_ROWID_"; - - /** - * This column is not nullable. - */ - public static final int NOT_NULLABLE = ResultSetMetaData.columnNoNulls; - - /** - * This column is nullable. - */ - public static final int NULLABLE = ResultSetMetaData.columnNullable; - - /** - * It is not know whether this column is nullable. - */ - public static final int NULLABLE_UNKNOWN = ResultSetMetaData.columnNullableUnknown; - - private final int type; - private long precision; - private int scale; - private int displaySize; - private Table table; - private String name; - private int columnId; - private boolean nullable = true; - private Expression defaultExpression; - private Expression checkConstraint; - private String checkConstraintSQL; - private String originalSQL; - private boolean autoIncrement; - private long start; - private long increment; - private boolean convertNullToDefault; - private Sequence sequence; - private boolean isComputed; - private TableFilter computeTableFilter; - private int selectivity; - private SingleColumnResolver resolver; - private String comment; - private boolean primaryKey; - - private boolean isRowKeyColumn; - - public void setRowKeyColumn(boolean isRowKeyColumn) { - this.isRowKeyColumn = isRowKeyColumn; - } - - public boolean isRowKeyColumn() { - return isRowKeyColumn; - } - - public Column(String name, int type) { - this(name, type, -1, -1, -1); - } - - public Column(String name, int type, long precision, int scale, int displaySize) { - this.name = name; - this.type = type; - if (precision == -1 && scale == -1 && displaySize == -1) { - DataType dt = DataType.getDataType(type); - precision = dt.defaultPrecision; - scale = dt.defaultScale; - displaySize = dt.defaultDisplaySize; - } - this.precision = precision; - this.scale = scale; - this.displaySize = displaySize; - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (!(o instanceof Column)) { - return false; - } - Column other = (Column) o; - if (table == null || other.table == null || name == null || other.name == null) { - return false; - } - - if (table != other.table) { - return false; - } - return name.equals(other.name); - } - - @Override - public int hashCode() { - if (table == null || name == null) { - return 0; - } - return table.getId() ^ name.hashCode(); - } - - public Column getClone() { - Column newColumn = new Column(name, type, precision, scale, displaySize); - newColumn.copy(this); - return newColumn; - } - - /** - * Convert a value to this column's type. - * - * @param v the value - * @return the value - */ - public Value convert(Value v) { - try { - return v.convertTo(type); - } catch (DbException e) { - if (e.getErrorCode() == ErrorCode.DATA_CONVERSION_ERROR_1) { - String target = (table == null ? "" : table.getName() + ": ") + getCreateSQL(); - throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, v.getSQL() + " (" + target + ")"); - } - throw e; - } - } - - boolean getComputed() { - return isComputed; - } - - /** - * Compute the value of this computed column. - * - * @param session the session - * @param row the row - * @return the value - */ - synchronized Value computeValue(ServerSession session, Row row) { - computeTableFilter.setSession(session); - computeTableFilter.set(row); - return defaultExpression.getValue(session); - } - - /** - * Set the default value in the form of a computed expression of other - * columns. - * - * @param expression the computed expression - */ - public void setComputedExpression(Expression expression) { - this.isComputed = true; - this.defaultExpression = expression; - } - - /** - * Set the table and column id. - * - * @param table the table - * @param columnId the column index - */ - public void setTable(Table table, int columnId) { - this.table = table; - this.columnId = columnId; - } - - public Table getTable() { - return table; - } - - /** - * Set the default expression. - * - * @param session the session - * @param defaultExpression the default expression - */ - public void setDefaultExpression(ServerSession session, Expression defaultExpression) { - // also to test that no column names are used - if (defaultExpression != null) { - defaultExpression = defaultExpression.optimize(session); - if (defaultExpression.isConstant()) { - defaultExpression = (Expression) session.getDatabase().getSQLEngine() - .createValueExpression((defaultExpression.getValue(session))); - } - } - this.defaultExpression = defaultExpression; - } - - public int getColumnId() { - return columnId; - } - - public String getSQL() { - return SQLEngineHolder.quoteIdentifier(name); - } - - public String getName() { - return name; - } - - public int getType() { - return type; - } - - public long getPrecision() { - return precision; - } - - public void setPrecision(long p) { - precision = p; - } - - public int getDisplaySize() { - return displaySize; - } - - public int getScale() { - return scale; - } - - public void setNullable(boolean b) { - nullable = b; - } - - /** - * Validate the value, convert it if required, and update the sequence value - * if required. If the value is null, the default value (NULL if no default - * is set) is returned. Check constraints are validated as well. - * - * @param session the session - * @param value the value or null - * @return the new or converted value - */ - public Value validateConvertUpdateSequence(ServerSession session, Value value) { - // take a local copy of defaultExpression to avoid holding the lock - // while calling getValue - final Expression localDefaultExpression; - synchronized (this) { - localDefaultExpression = defaultExpression; - } - if (value == null) { - if (localDefaultExpression == null) { - value = ValueNull.INSTANCE; - } else { - synchronized (this) { - value = localDefaultExpression.getValue(session).convertTo(type); - } - if (primaryKey) { - session.setLastIdentity(value); - } - } - } - Mode mode = session.getDatabase().getMode(); - if (value == ValueNull.INSTANCE) { - if (convertNullToDefault && localDefaultExpression != null) { - value = localDefaultExpression.getValue(session).convertTo(type); - } - if (value == ValueNull.INSTANCE && !nullable) { - if (mode.convertInsertNullToZero) { - DataType dt = DataType.getDataType(type); - if (dt.decimal) { - value = ValueInt.get(0).convertTo(type); - } else if (dt.type == Value.TIMESTAMP) { - value = ValueTimestamp.get(new Timestamp(session.getTransactionStart())); - } else if (dt.type == Value.TIME) { - value = ValueTime.fromNanos(0); - } else if (dt.type == Value.DATE) { - value = ValueDate.get(new Date(session.getTransactionStart())); - } else { - value = ValueString.get("").convertTo(type); - } - } else { - throw DbException.get(ErrorCode.NULL_NOT_ALLOWED, name); - } - } - } - if (checkConstraint != null) { - resolver.setValue(value); - Value v; - synchronized (this) { - v = checkConstraint.getValue(session); - } - // Both TRUE and NULL are ok - if (Boolean.FALSE.equals(v.getBoolean())) { - throw DbException.get(ErrorCode.CHECK_CONSTRAINT_VIOLATED_1, checkConstraint.getSQL()); - } - } - value = value.convertScale(mode.convertOnlyToSmallerScale, scale); - if (precision > 0) { - if (!value.checkPrecision(precision)) { - String s = value.getTraceSQL(); - if (s.length() > 127) { - s = s.substring(0, 128) + "..."; - } - throw DbException - .get(ErrorCode.VALUE_TOO_LONG_2, getCreateSQL(), s + " (" + value.getPrecision() + ")"); - } - } - updateSequenceIfRequired(session, value); - return value; - } - - private void updateSequenceIfRequired(ServerSession session, Value value) { - if (sequence != null) { - long current = sequence.getCurrentValue(); - long inc = sequence.getIncrement(); - long now = value.getLong(); - boolean update = false; - if (inc > 0 && now > current) { - update = true; - } else if (inc < 0 && now < current) { - update = true; - } - if (update) { - sequence.modify(now + inc, null, null, null); - session.setLastIdentity(ValueLong.get(now)); - sequence.flush(session, 0); - } - } - } - - /** - * Convert the auto-increment flag to a sequence that is linked with this - * table. - * - * @param session the session - * @param schema the schema where the sequence should be generated - * @param id the object id - * @param temporary true if the sequence is temporary and does not need to - * be stored - */ - public void convertAutoIncrementToSequence(ServerSession session, Schema schema, int id, boolean temporary) { - if (!autoIncrement) { - DbException.throwInternalError(); - } - if ("IDENTITY".equals(originalSQL)) { - originalSQL = "BIGINT"; - } else if ("SERIAL".equals(originalSQL)) { - originalSQL = "INT"; - } - String sequenceName; - while (true) { - ValueUuid uuid = ValueUuid.getNewRandom(); - String s = uuid.getString(); - s = s.replace('-', '_').toUpperCase(); - sequenceName = "SYSTEM_SEQUENCE_" + s; - if (schema.findSequence(sequenceName) == null) { - break; - } - } - Sequence seq = new Sequence(schema, id, sequenceName, start, increment); - if (temporary) { - seq.setTemporary(true); - } else { - session.getDatabase().addSchemaObject(session, seq); - } - setAutoIncrement(false, 0, 0); - setDefaultExpression(session, (Expression) session.getDatabase().getSQLEngine().createSequenceValue(seq)); - setSequence(seq); - } - - /** - * Prepare all expressions of this column. - * - * @param session the session - */ - public void prepareExpression(ServerSession session) { - if (defaultExpression != null) { - computeTableFilter = new TableFilter(session, table, null, false, null); - defaultExpression.mapColumns(computeTableFilter, 0); - defaultExpression = defaultExpression.optimize(session); - } - } - - public String getCreateSQL() { - return getCreateSQL(false); - } - - public String getCreateSQL(boolean isAlter) { - StringBuilder buff = new StringBuilder(); - if (name != null) { - buff.append(SQLEngineHolder.quoteIdentifier(name)).append(' '); - } - if (originalSQL != null) { - buff.append(originalSQL); - } else { - buff.append(DataType.getDataType(type).name); - switch (type) { - case Value.DECIMAL: - buff.append('(').append(precision).append(", ").append(scale).append(')'); - break; - case Value.BYTES: - case Value.STRING: - case Value.STRING_IGNORECASE: - case Value.STRING_FIXED: - if (precision < Integer.MAX_VALUE) { - buff.append('(').append(precision).append(')'); - } - break; - default: - } - } - if (defaultExpression != null) { - String sql = defaultExpression.getSQL(); - if (sql != null) { - if (isComputed) { - buff.append(" AS ").append(sql); - } else if (defaultExpression != null) { - buff.append(" DEFAULT ").append(sql); - } - } - } - if (isRowKeyColumn) { - buff.append(" ROW KEY"); - } - if (!nullable) { - buff.append(" NOT NULL"); - } - if (convertNullToDefault) { - buff.append(" NULL_TO_DEFAULT"); - } - if (sequence != null) { - buff.append(" SEQUENCE ").append(sequence.getSQL()); - } - if (selectivity != 0) { - buff.append(" SELECTIVITY ").append(selectivity); - } - if (comment != null) { - buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment)); - } - if (checkConstraint != null) { - buff.append(" CHECK ").append(checkConstraintSQL); - } - return buff.toString(); - } - - public boolean isNullable() { - return nullable; - } - - public void setOriginalSQL(String original) { - originalSQL = original; - } - - public String getOriginalSQL() { - return originalSQL; - } - - public Expression getDefaultExpression() { - return defaultExpression; - } - - public boolean isAutoIncrement() { - return autoIncrement; - } - - /** - * Set the autoincrement flag and related properties of this column. - * - * @param autoInc the new autoincrement flag - * @param start the sequence start value - * @param increment the sequence increment - */ - public void setAutoIncrement(boolean autoInc, long start, long increment) { - this.autoIncrement = autoInc; - this.start = start; - this.increment = increment; - this.nullable = false; - if (autoInc) { - convertNullToDefault = true; - } - } - - public void setConvertNullToDefault(boolean convert) { - this.convertNullToDefault = convert; - } - - /** - * Rename the column. This method will only set the column name to the new - * value. - * - * @param newName the new column name - */ - public void rename(String newName) { - this.name = newName; - } - - public void setSequence(Sequence sequence) { - this.sequence = sequence; - } - - public Sequence getSequence() { - return sequence; - } - - /** - * Get the selectivity of the column. Selectivity 100 means values are - * unique, 10 means every distinct value appears 10 times on average. - * - * @return the selectivity - */ - public int getSelectivity() { - return selectivity == 0 ? Constants.SELECTIVITY_DEFAULT : selectivity; - } - - /** - * Set the new selectivity of a column. - * - * @param selectivity the new value - */ - public void setSelectivity(int selectivity) { - selectivity = selectivity < 0 ? 0 : (selectivity > 100 ? 100 : selectivity); - this.selectivity = selectivity; - } - - /** - * Add a check constraint expression to this column. An existing check - * constraint constraint is added using AND. - * - * @param session the session - * @param expr the (additional) constraint - */ - public void addCheckConstraint(ServerSession session, Expression expr) { - if (expr == null) { - return; - } - resolver = new SingleColumnResolver(this); - synchronized (this) { - String oldName = name; - if (name == null) { - name = "VALUE"; - } - expr.mapColumns(resolver, 0); - name = oldName; - } - expr = expr.optimize(session); - resolver.setValue(ValueNull.INSTANCE); - // check if the column is mapped - synchronized (this) { - expr.getValue(session); - } - if (checkConstraint == null) { - checkConstraint = expr; - } else { - checkConstraint = (Expression) session.getDatabase().getSQLEngine() - .createConditionAndOr(true, checkConstraint, expr); - } - checkConstraintSQL = getCheckConstraintSQL(session, name); - } - - /** - * Remove the check constraint if there is one. - */ - public void removeCheckConstraint() { - checkConstraint = null; - checkConstraintSQL = null; - } - - /** - * Get the check constraint expression for this column if set. - * - * @param session the session - * @param asColumnName the column name to use - * @return the constraint expression - */ - public Expression getCheckConstraint(ServerSession session, String asColumnName) { - if (checkConstraint == null) { - return null; - } - org.lealone.sql.SQLParser parser = session.getDatabase().createParser(session); - String sql; - synchronized (this) { - String oldName = name; - name = asColumnName; - sql = checkConstraint.getSQL(); - name = oldName; - } - Expression expr = (Expression) parser.parseExpression(sql); - return expr; - } - - String getDefaultSQL() { - return defaultExpression == null ? null : defaultExpression.getSQL(); - } - - int getPrecisionAsInt() { - return MathUtils.convertLongToInt(precision); - } - - DataType getDataType() { - return DataType.getDataType(type); - } - - /** - * Get the check constraint SQL snippet. - * - * @param session the session - * @param asColumnName the column name to use - * @return the SQL snippet - */ - String getCheckConstraintSQL(ServerSession session, String asColumnName) { - Expression constraint = getCheckConstraint(session, asColumnName); - return constraint == null ? "" : constraint.getSQL(); - } - - public void setComment(String comment) { - this.comment = comment; - } - - public String getComment() { - return comment; - } - - public void setPrimaryKey(boolean primaryKey) { - this.primaryKey = primaryKey; - } - - /** - * Visit the default expression, the check constraint, and the sequence (if - * any). - * - * @param visitor the visitor - * @return true if every visited expression returned true, or if there are - * no expressions - */ - boolean isEverything(ExpressionVisitor visitor) { - if (visitor.getType() == ExpressionVisitor.GET_DEPENDENCIES) { - if (sequence != null) { - visitor.getDependencies().add(sequence); - } - } - if (defaultExpression != null && !defaultExpression.isEverything(visitor)) { - return false; - } - if (checkConstraint != null && !checkConstraint.isEverything(visitor)) { - return false; - } - return true; - } - - public boolean isPrimaryKey() { - return primaryKey; - } - - @Override - public String toString() { - return name; - } - - /** - * Check whether the new column is of the same type and not more restricted - * than this column. - * - * @param newColumn the new (target) column - * @return true if the new column is compatible - */ - public boolean isWideningConversion(Column newColumn) { - if (type != newColumn.type) { - return false; - } - if (precision > newColumn.precision) { - return false; - } - if (scale != newColumn.scale) { - return false; - } - if (nullable && !newColumn.nullable) { - return false; - } - if (convertNullToDefault != newColumn.convertNullToDefault) { - return false; - } - if (primaryKey != newColumn.primaryKey) { - return false; - } - if (autoIncrement || newColumn.autoIncrement) { - return false; - } - if (checkConstraint != null || newColumn.checkConstraint != null) { - return false; - } - if (convertNullToDefault || newColumn.convertNullToDefault) { - return false; - } - if (defaultExpression != null || newColumn.defaultExpression != null) { - return false; - } - if (isComputed || newColumn.isComputed) { - return false; - } - return true; - } - - /** - * Copy the data of the source column into the current column. - * - * @param source the source column - */ - public void copy(Column source) { - checkConstraint = source.checkConstraint; - checkConstraintSQL = source.checkConstraintSQL; - displaySize = source.displaySize; - name = source.name; - precision = source.precision; - scale = source.scale; - // table is not set - // columnId is not set - nullable = source.nullable; - defaultExpression = source.defaultExpression; - originalSQL = source.originalSQL; - // autoIncrement, start, increment is not set - convertNullToDefault = source.convertNullToDefault; - sequence = source.sequence; - comment = source.comment; - computeTableFilter = source.computeTableFilter; - isComputed = source.isComputed; - selectivity = source.selectivity; - primaryKey = source.primaryKey; - } - -} diff --git a/All/Genesis-NP/Genesis#347/old/Column.java b/All/Genesis-NP/Genesis#347/old/Column.java deleted file mode 100755 index a6fcd71..0000000 --- a/All/Genesis-NP/Genesis#347/old/Column.java +++ /dev/null @@ -1,753 +0,0 @@ -/* - * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, - * Version 1.0, and under the Eclipse Public License, Version 1.0 - * (http://h2database.com/html/license.html). - * Initial Developer: H2 Group - */ -package org.lealone.db.table; - -import java.sql.Date; -import java.sql.ResultSetMetaData; -import java.sql.Timestamp; - -import org.lealone.api.ErrorCode; -import org.lealone.common.exceptions.DbException; -import org.lealone.common.util.MathUtils; -import org.lealone.common.util.StringUtils; -import org.lealone.db.Constants; -import org.lealone.db.Mode; -import org.lealone.db.SQLEngineHolder; -import org.lealone.db.ServerSession; -import org.lealone.db.expression.Expression; -import org.lealone.db.expression.ExpressionVisitor; -import org.lealone.db.result.Row; -import org.lealone.db.schema.Schema; -import org.lealone.db.schema.Sequence; -import org.lealone.db.value.DataType; -import org.lealone.db.value.Value; -import org.lealone.db.value.ValueDate; -import org.lealone.db.value.ValueInt; -import org.lealone.db.value.ValueLong; -import org.lealone.db.value.ValueNull; -import org.lealone.db.value.ValueString; -import org.lealone.db.value.ValueTime; -import org.lealone.db.value.ValueTimestamp; -import org.lealone.db.value.ValueUuid; - -/** - * This class represents a column in a table. - */ -public class Column { - - /** - * The name of the rowid pseudo column. - */ - public static final String ROWID = "_ROWID_"; - - /** - * This column is not nullable. - */ - public static final int NOT_NULLABLE = ResultSetMetaData.columnNoNulls; - - /** - * This column is nullable. - */ - public static final int NULLABLE = ResultSetMetaData.columnNullable; - - /** - * It is not know whether this column is nullable. - */ - public static final int NULLABLE_UNKNOWN = ResultSetMetaData.columnNullableUnknown; - - private final int type; - private long precision; - private int scale; - private int displaySize; - private Table table; - private String name; - private int columnId; - private boolean nullable = true; - private Expression defaultExpression; - private Expression checkConstraint; - private String checkConstraintSQL; - private String originalSQL; - private boolean autoIncrement; - private long start; - private long increment; - private boolean convertNullToDefault; - private Sequence sequence; - private boolean isComputed; - private TableFilter computeTableFilter; - private int selectivity; - private SingleColumnResolver resolver; - private String comment; - private boolean primaryKey; - - private boolean isRowKeyColumn; - - public void setRowKeyColumn(boolean isRowKeyColumn) { - this.isRowKeyColumn = isRowKeyColumn; - } - - public boolean isRowKeyColumn() { - return isRowKeyColumn; - } - - public Column(String name, int type) { - this(name, type, -1, -1, -1); - } - - public Column(String name, int type, long precision, int scale, int displaySize) { - this.name = name; - this.type = type; - if (precision == -1 && scale == -1 && displaySize == -1) { - DataType dt = DataType.getDataType(type); - precision = dt.defaultPrecision; - scale = dt.defaultScale; - displaySize = dt.defaultDisplaySize; - } - this.precision = precision; - this.scale = scale; - this.displaySize = displaySize; - } - - @Override - public boolean equals(Object o) { - if (o == this) { - return true; - } else if (!(o instanceof Column)) { - return false; - } - Column other = (Column) o; - if (table == null || other.table == null || name == null || other.name == null) { - return false; - } - - if (table != other.table) { - return false; - } - return name.equals(other.name); - } - - @Override - public int hashCode() { - if (table == null || name == null) { - return 0; - } - return table.getId() ^ name.hashCode(); - } - - public Column getClone() { - Column newColumn = new Column(name, type, precision, scale, displaySize); - newColumn.copy(this); - return newColumn; - } - - /** - * Convert a value to this column's type. - * - * @param v the value - * @return the value - */ - public Value convert(Value v) { - try { - return v.convertTo(type); - } catch (DbException e) { - if (e.getErrorCode() == ErrorCode.DATA_CONVERSION_ERROR_1) { - String target = (table == null ? "" : table.getName() + ": ") + getCreateSQL(); - throw DbException.get(ErrorCode.DATA_CONVERSION_ERROR_1, v.getSQL() + " (" + target + ")"); - } - throw e; - } - } - - boolean getComputed() { - return isComputed; - } - - /** - * Compute the value of this computed column. - * - * @param session the session - * @param row the row - * @return the value - */ - synchronized Value computeValue(ServerSession session, Row row) { - computeTableFilter.setSession(session); - computeTableFilter.set(row); - return defaultExpression.getValue(session); - } - - /** - * Set the default value in the form of a computed expression of other - * columns. - * - * @param expression the computed expression - */ - public void setComputedExpression(Expression expression) { - this.isComputed = true; - this.defaultExpression = expression; - } - - /** - * Set the table and column id. - * - * @param table the table - * @param columnId the column index - */ - public void setTable(Table table, int columnId) { - this.table = table; - this.columnId = columnId; - } - - public Table getTable() { - return table; - } - - /** - * Set the default expression. - * - * @param session the session - * @param defaultExpression the default expression - */ - public void setDefaultExpression(ServerSession session, Expression defaultExpression) { - // also to test that no column names are used - if (defaultExpression != null) { - defaultExpression = defaultExpression.optimize(session); - if (defaultExpression.isConstant()) { - defaultExpression = (Expression) session.getDatabase().getSQLEngine() - .createValueExpression((defaultExpression.getValue(session))); - } - } - this.defaultExpression = defaultExpression; - } - - public int getColumnId() { - return columnId; - } - - public String getSQL() { - return SQLEngineHolder.quoteIdentifier(name); - } - - public String getName() { - return name; - } - - public int getType() { - return type; - } - - public long getPrecision() { - return precision; - } - - public void setPrecision(long p) { - precision = p; - } - - public int getDisplaySize() { - return displaySize; - } - - public int getScale() { - return scale; - } - - public void setNullable(boolean b) { - nullable = b; - } - - /** - * Validate the value, convert it if required, and update the sequence value - * if required. If the value is null, the default value (NULL if no default - * is set) is returned. Check constraints are validated as well. - * - * @param session the session - * @param value the value or null - * @return the new or converted value - */ - public Value validateConvertUpdateSequence(ServerSession session, Value value) { - if (value == null) { - if (defaultExpression == null) { - value = ValueNull.INSTANCE; - } else { - synchronized (this) { - value = defaultExpression.getValue(session).convertTo(type); - } - if (primaryKey) { - session.setLastIdentity(value); - } - } - } - Mode mode = session.getDatabase().getMode(); - if (value == ValueNull.INSTANCE) { - if (convertNullToDefault) { - synchronized (this) { - value = defaultExpression.getValue(session).convertTo(type); - } - } - if (value == ValueNull.INSTANCE && !nullable) { - if (mode.convertInsertNullToZero) { - DataType dt = DataType.getDataType(type); - if (dt.decimal) { - value = ValueInt.get(0).convertTo(type); - } else if (dt.type == Value.TIMESTAMP) { - value = ValueTimestamp.get(new Timestamp(session.getTransactionStart())); - } else if (dt.type == Value.TIME) { - value = ValueTime.fromNanos(0); - } else if (dt.type == Value.DATE) { - value = ValueDate.get(new Date(session.getTransactionStart())); - } else { - value = ValueString.get("").convertTo(type); - } - } else { - throw DbException.get(ErrorCode.NULL_NOT_ALLOWED, name); - } - } - } - if (checkConstraint != null) { - resolver.setValue(value); - Value v; - synchronized (this) { - v = checkConstraint.getValue(session); - } - // Both TRUE and NULL are ok - if (Boolean.FALSE.equals(v.getBoolean())) { - throw DbException.get(ErrorCode.CHECK_CONSTRAINT_VIOLATED_1, checkConstraint.getSQL()); - } - } - value = value.convertScale(mode.convertOnlyToSmallerScale, scale); - if (precision > 0) { - if (!value.checkPrecision(precision)) { - String s = value.getTraceSQL(); - if (s.length() > 127) { - s = s.substring(0, 128) + "..."; - } - throw DbException - .get(ErrorCode.VALUE_TOO_LONG_2, getCreateSQL(), s + " (" + value.getPrecision() + ")"); - } - } - updateSequenceIfRequired(session, value); - return value; - } - - private void updateSequenceIfRequired(ServerSession session, Value value) { - if (sequence != null) { - long current = sequence.getCurrentValue(); - long inc = sequence.getIncrement(); - long now = value.getLong(); - boolean update = false; - if (inc > 0 && now > current) { - update = true; - } else if (inc < 0 && now < current) { - update = true; - } - if (update) { - sequence.modify(now + inc, null, null, null); - session.setLastIdentity(ValueLong.get(now)); - sequence.flush(session, 0); - } - } - } - - /** - * Convert the auto-increment flag to a sequence that is linked with this - * table. - * - * @param session the session - * @param schema the schema where the sequence should be generated - * @param id the object id - * @param temporary true if the sequence is temporary and does not need to - * be stored - */ - public void convertAutoIncrementToSequence(ServerSession session, Schema schema, int id, boolean temporary) { - if (!autoIncrement) { - DbException.throwInternalError(); - } - if ("IDENTITY".equals(originalSQL)) { - originalSQL = "BIGINT"; - } else if ("SERIAL".equals(originalSQL)) { - originalSQL = "INT"; - } - String sequenceName; - while (true) { - ValueUuid uuid = ValueUuid.getNewRandom(); - String s = uuid.getString(); - s = s.replace('-', '_').toUpperCase(); - sequenceName = "SYSTEM_SEQUENCE_" + s; - if (schema.findSequence(sequenceName) == null) { - break; - } - } - Sequence seq = new Sequence(schema, id, sequenceName, start, increment); - if (temporary) { - seq.setTemporary(true); - } else { - session.getDatabase().addSchemaObject(session, seq); - } - setAutoIncrement(false, 0, 0); - setDefaultExpression(session, (Expression) session.getDatabase().getSQLEngine().createSequenceValue(seq)); - setSequence(seq); - } - - /** - * Prepare all expressions of this column. - * - * @param session the session - */ - public void prepareExpression(ServerSession session) { - if (defaultExpression != null) { - computeTableFilter = new TableFilter(session, table, null, false, null); - defaultExpression.mapColumns(computeTableFilter, 0); - defaultExpression = defaultExpression.optimize(session); - } - } - - public String getCreateSQL() { - return getCreateSQL(false); - } - - public String getCreateSQL(boolean isAlter) { - StringBuilder buff = new StringBuilder(); - if (name != null) { - buff.append(SQLEngineHolder.quoteIdentifier(name)).append(' '); - } - if (originalSQL != null) { - buff.append(originalSQL); - } else { - buff.append(DataType.getDataType(type).name); - switch (type) { - case Value.DECIMAL: - buff.append('(').append(precision).append(", ").append(scale).append(')'); - break; - case Value.BYTES: - case Value.STRING: - case Value.STRING_IGNORECASE: - case Value.STRING_FIXED: - if (precision < Integer.MAX_VALUE) { - buff.append('(').append(precision).append(')'); - } - break; - default: - } - } - if (defaultExpression != null) { - String sql = defaultExpression.getSQL(); - if (sql != null) { - if (isComputed) { - buff.append(" AS ").append(sql); - } else if (defaultExpression != null) { - buff.append(" DEFAULT ").append(sql); - } - } - } - if (isRowKeyColumn) { - buff.append(" ROW KEY"); - } - if (!nullable) { - buff.append(" NOT NULL"); - } - if (convertNullToDefault) { - buff.append(" NULL_TO_DEFAULT"); - } - if (sequence != null) { - buff.append(" SEQUENCE ").append(sequence.getSQL()); - } - if (selectivity != 0) { - buff.append(" SELECTIVITY ").append(selectivity); - } - if (comment != null) { - buff.append(" COMMENT ").append(StringUtils.quoteStringSQL(comment)); - } - if (checkConstraint != null) { - buff.append(" CHECK ").append(checkConstraintSQL); - } - return buff.toString(); - } - - public boolean isNullable() { - return nullable; - } - - public void setOriginalSQL(String original) { - originalSQL = original; - } - - public String getOriginalSQL() { - return originalSQL; - } - - public Expression getDefaultExpression() { - return defaultExpression; - } - - public boolean isAutoIncrement() { - return autoIncrement; - } - - /** - * Set the autoincrement flag and related properties of this column. - * - * @param autoInc the new autoincrement flag - * @param start the sequence start value - * @param increment the sequence increment - */ - public void setAutoIncrement(boolean autoInc, long start, long increment) { - this.autoIncrement = autoInc; - this.start = start; - this.increment = increment; - this.nullable = false; - if (autoInc) { - convertNullToDefault = true; - } - } - - public void setConvertNullToDefault(boolean convert) { - this.convertNullToDefault = convert; - } - - /** - * Rename the column. This method will only set the column name to the new - * value. - * - * @param newName the new column name - */ - public void rename(String newName) { - this.name = newName; - } - - public void setSequence(Sequence sequence) { - this.sequence = sequence; - } - - public Sequence getSequence() { - return sequence; - } - - /** - * Get the selectivity of the column. Selectivity 100 means values are - * unique, 10 means every distinct value appears 10 times on average. - * - * @return the selectivity - */ - public int getSelectivity() { - return selectivity == 0 ? Constants.SELECTIVITY_DEFAULT : selectivity; - } - - /** - * Set the new selectivity of a column. - * - * @param selectivity the new value - */ - public void setSelectivity(int selectivity) { - selectivity = selectivity < 0 ? 0 : (selectivity > 100 ? 100 : selectivity); - this.selectivity = selectivity; - } - - /** - * Add a check constraint expression to this column. An existing check - * constraint constraint is added using AND. - * - * @param session the session - * @param expr the (additional) constraint - */ - public void addCheckConstraint(ServerSession session, Expression expr) { - if (expr == null) { - return; - } - resolver = new SingleColumnResolver(this); - synchronized (this) { - String oldName = name; - if (name == null) { - name = "VALUE"; - } - expr.mapColumns(resolver, 0); - name = oldName; - } - expr = expr.optimize(session); - resolver.setValue(ValueNull.INSTANCE); - // check if the column is mapped - synchronized (this) { - expr.getValue(session); - } - if (checkConstraint == null) { - checkConstraint = expr; - } else { - checkConstraint = (Expression) session.getDatabase().getSQLEngine() - .createConditionAndOr(true, checkConstraint, expr); - } - checkConstraintSQL = getCheckConstraintSQL(session, name); - } - - /** - * Remove the check constraint if there is one. - */ - public void removeCheckConstraint() { - checkConstraint = null; - checkConstraintSQL = null; - } - - /** - * Get the check constraint expression for this column if set. - * - * @param session the session - * @param asColumnName the column name to use - * @return the constraint expression - */ - public Expression getCheckConstraint(ServerSession session, String asColumnName) { - if (checkConstraint == null) { - return null; - } - org.lealone.sql.SQLParser parser = session.getDatabase().createParser(session); - String sql; - synchronized (this) { - String oldName = name; - name = asColumnName; - sql = checkConstraint.getSQL(); - name = oldName; - } - Expression expr = (Expression) parser.parseExpression(sql); - return expr; - } - - String getDefaultSQL() { - return defaultExpression == null ? null : defaultExpression.getSQL(); - } - - int getPrecisionAsInt() { - return MathUtils.convertLongToInt(precision); - } - - DataType getDataType() { - return DataType.getDataType(type); - } - - /** - * Get the check constraint SQL snippet. - * - * @param session the session - * @param asColumnName the column name to use - * @return the SQL snippet - */ - String getCheckConstraintSQL(ServerSession session, String asColumnName) { - Expression constraint = getCheckConstraint(session, asColumnName); - return constraint == null ? "" : constraint.getSQL(); - } - - public void setComment(String comment) { - this.comment = comment; - } - - public String getComment() { - return comment; - } - - public void setPrimaryKey(boolean primaryKey) { - this.primaryKey = primaryKey; - } - - /** - * Visit the default expression, the check constraint, and the sequence (if - * any). - * - * @param visitor the visitor - * @return true if every visited expression returned true, or if there are - * no expressions - */ - boolean isEverything(ExpressionVisitor visitor) { - if (visitor.getType() == ExpressionVisitor.GET_DEPENDENCIES) { - if (sequence != null) { - visitor.getDependencies().add(sequence); - } - } - if (defaultExpression != null && !defaultExpression.isEverything(visitor)) { - return false; - } - if (checkConstraint != null && !checkConstraint.isEverything(visitor)) { - return false; - } - return true; - } - - public boolean isPrimaryKey() { - return primaryKey; - } - - @Override - public String toString() { - return name; - } - - /** - * Check whether the new column is of the same type and not more restricted - * than this column. - * - * @param newColumn the new (target) column - * @return true if the new column is compatible - */ - public boolean isWideningConversion(Column newColumn) { - if (type != newColumn.type) { - return false; - } - if (precision > newColumn.precision) { - return false; - } - if (scale != newColumn.scale) { - return false; - } - if (nullable && !newColumn.nullable) { - return false; - } - if (convertNullToDefault != newColumn.convertNullToDefault) { - return false; - } - if (primaryKey != newColumn.primaryKey) { - return false; - } - if (autoIncrement || newColumn.autoIncrement) { - return false; - } - if (checkConstraint != null || newColumn.checkConstraint != null) { - return false; - } - if (convertNullToDefault || newColumn.convertNullToDefault) { - return false; - } - if (defaultExpression != null || newColumn.defaultExpression != null) { - return false; - } - if (isComputed || newColumn.isComputed) { - return false; - } - return true; - } - - /** - * Copy the data of the source column into the current column. - * - * @param source the source column - */ - public void copy(Column source) { - checkConstraint = source.checkConstraint; - checkConstraintSQL = source.checkConstraintSQL; - displaySize = source.displaySize; - name = source.name; - precision = source.precision; - scale = source.scale; - // table is not set - // columnId is not set - nullable = source.nullable; - defaultExpression = source.defaultExpression; - originalSQL = source.originalSQL; - // autoIncrement, start, increment is not set - convertNullToDefault = source.convertNullToDefault; - sequence = source.sequence; - comment = source.comment; - computeTableFilter = source.computeTableFilter; - isComputed = source.isComputed; - selectivity = source.selectivity; - primaryKey = source.primaryKey; - } - -} diff --git a/All/Genesis-NP/Genesis#347/pair.info b/All/Genesis-NP/Genesis#347/pair.info deleted file mode 100755 index 330adc0..0000000 --- a/All/Genesis-NP/Genesis#347/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:347 -SATName:Genesis -modifiedFPath:lealone-db/src/main/java/org/lealone/db/table/Column.java -comSha:b9e7cf730acd4e2c1a22426314076341312dee5b -parentComSha:b9e7cf730acd4e2c1a22426314076341312dee5b^1 -githubUrl:https://github.com/codefollower/Lealone -repoName:codefollower#Lealone \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#351/comMsg.txt b/All/Genesis-NP/Genesis#351/comMsg.txt deleted file mode 100755 index e37b48d..0000000 --- a/All/Genesis-NP/Genesis#351/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Make PortMapping protocol default to "tcp" diff --git a/All/Genesis-NP/Genesis#351/diff.diff b/All/Genesis-NP/Genesis#351/diff.diff deleted file mode 100755 index 287d87d..0000000 --- a/All/Genesis-NP/Genesis#351/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/helios-client/src/main/java/com/spotify/helios/common/descriptors/PortMapping.java b/helios-client/src/main/java/com/spotify/helios/common/descriptors/PortMapping.java -index 1405dfe..35a53d2 100644 ---- a/helios-client/src/main/java/com/spotify/helios/common/descriptors/PortMapping.java -+++ b/helios-client/src/main/java/com/spotify/helios/common/descriptors/PortMapping.java -@@ -20,0 +21 @@ import com.google.common.base.Objects; -+import com.google.common.base.Optional; -@@ -55 +56 @@ public class PortMapping extends Descriptor { -- this.protocol = protocol; -+ this.protocol = Optional.fromNullable(protocol).or(TCP); diff --git a/All/Genesis-NP/Genesis#351/new/PortMapping.java b/All/Genesis-NP/Genesis#351/new/PortMapping.java deleted file mode 100755 index 35a53d2..0000000 --- a/All/Genesis-NP/Genesis#351/new/PortMapping.java +++ /dev/null @@ -1,150 +0,0 @@ -/* - * Copyright (c) 2014 Spotify AB. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.spotify.helios.common.descriptors; - -import com.google.common.base.Objects; -import com.google.common.base.Optional; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.jetbrains.annotations.Nullable; - - -/** - * Represents a mapping from a port inside the container to be exposed on the agent. - * - * A typical JSON representation might be: - *

- * {
- *   "externalPort" : 8061,
- *   "internalPort" : 8081,
- *   "protocol" : "tcp"
- * }
- * 
- */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class PortMapping extends Descriptor { - - public static final String TCP = "tcp"; - public static final String UDP = "udp"; - - private final int internalPort; - private final Integer externalPort; - private final String protocol; - - public PortMapping(@JsonProperty("internalPort") final int internalPort, - @JsonProperty("externalPort") final Integer externalPort, - @JsonProperty("protocol") final String protocol) { - this.internalPort = internalPort; - this.externalPort = externalPort; - this.protocol = Optional.fromNullable(protocol).or(TCP); - } - - public PortMapping(final int internalPort, final Integer externalPort) { - this.internalPort = internalPort; - this.externalPort = externalPort; - this.protocol = TCP; - } - - public PortMapping(final int internalPort) { - this.internalPort = internalPort; - this.externalPort = null; - this.protocol = TCP; - } - - public int getInternalPort() { - return internalPort; - } - - public boolean hasExternalPort() { - return externalPort != null; - } - - @Nullable - public Integer getExternalPort() { - return externalPort; - } - - public String getProtocol() { - return protocol; - } - - public PortMapping withExternalPort(final Integer externalPort) { - return PortMapping.of(internalPort, externalPort, protocol); - } - - public static PortMapping of(final int internalPort) { - return new PortMapping(internalPort); - } - - public static PortMapping of(final int internalPort, final Integer externalPort) { - return new PortMapping(internalPort, externalPort); - } - - public static PortMapping of(final int internalPort, final Integer externalPort, - final String protocol) { - return new PortMapping(internalPort, externalPort, protocol); - } - - public static PortMapping of(final int internalPort, final String protocol) { - return new PortMapping(internalPort, null, protocol); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - final PortMapping that = (PortMapping) o; - - if (internalPort != that.internalPort) { - return false; - } - if (externalPort != null ? !externalPort.equals(that.externalPort) - : that.externalPort != null) { - return false; - } - if (protocol != null ? !protocol.equals(that.protocol) : that.protocol != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = internalPort; - result = 31 * result + (externalPort != null ? externalPort.hashCode() : 0); - result = 31 * result + (protocol != null ? protocol.hashCode() : 0); - return result; - } - - @Override - public String toString() { - return Objects.toStringHelper(this) - .add("internalPort", internalPort) - .add("externalPort", externalPort) - .add("protocol", protocol) - .toString(); - } -} diff --git a/All/Genesis-NP/Genesis#351/old/PortMapping.java b/All/Genesis-NP/Genesis#351/old/PortMapping.java deleted file mode 100755 index 1405dfe..0000000 --- a/All/Genesis-NP/Genesis#351/old/PortMapping.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (c) 2014 Spotify AB. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package com.spotify.helios.common.descriptors; - -import com.google.common.base.Objects; - -import com.fasterxml.jackson.annotation.JsonIgnoreProperties; -import com.fasterxml.jackson.annotation.JsonProperty; - -import org.jetbrains.annotations.Nullable; - - -/** - * Represents a mapping from a port inside the container to be exposed on the agent. - * - * A typical JSON representation might be: - *
- * {
- *   "externalPort" : 8061,
- *   "internalPort" : 8081,
- *   "protocol" : "tcp"
- * }
- * 
- */ -@JsonIgnoreProperties(ignoreUnknown = true) -public class PortMapping extends Descriptor { - - public static final String TCP = "tcp"; - public static final String UDP = "udp"; - - private final int internalPort; - private final Integer externalPort; - private final String protocol; - - public PortMapping(@JsonProperty("internalPort") final int internalPort, - @JsonProperty("externalPort") final Integer externalPort, - @JsonProperty("protocol") final String protocol) { - this.internalPort = internalPort; - this.externalPort = externalPort; - this.protocol = protocol; - } - - public PortMapping(final int internalPort, final Integer externalPort) { - this.internalPort = internalPort; - this.externalPort = externalPort; - this.protocol = TCP; - } - - public PortMapping(final int internalPort) { - this.internalPort = internalPort; - this.externalPort = null; - this.protocol = TCP; - } - - public int getInternalPort() { - return internalPort; - } - - public boolean hasExternalPort() { - return externalPort != null; - } - - @Nullable - public Integer getExternalPort() { - return externalPort; - } - - public String getProtocol() { - return protocol; - } - - public PortMapping withExternalPort(final Integer externalPort) { - return PortMapping.of(internalPort, externalPort, protocol); - } - - public static PortMapping of(final int internalPort) { - return new PortMapping(internalPort); - } - - public static PortMapping of(final int internalPort, final Integer externalPort) { - return new PortMapping(internalPort, externalPort); - } - - public static PortMapping of(final int internalPort, final Integer externalPort, - final String protocol) { - return new PortMapping(internalPort, externalPort, protocol); - } - - public static PortMapping of(final int internalPort, final String protocol) { - return new PortMapping(internalPort, null, protocol); - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - final PortMapping that = (PortMapping) o; - - if (internalPort != that.internalPort) { - return false; - } - if (externalPort != null ? !externalPort.equals(that.externalPort) - : that.externalPort != null) { - return false; - } - if (protocol != null ? !protocol.equals(that.protocol) : that.protocol != null) { - return false; - } - - return true; - } - - @Override - public int hashCode() { - int result = internalPort; - result = 31 * result + (externalPort != null ? externalPort.hashCode() : 0); - result = 31 * result + (protocol != null ? protocol.hashCode() : 0); - return result; - } - - @Override - public String toString() { - return Objects.toStringHelper(this) - .add("internalPort", internalPort) - .add("externalPort", externalPort) - .add("protocol", protocol) - .toString(); - } -} diff --git a/All/Genesis-NP/Genesis#351/pair.info b/All/Genesis-NP/Genesis#351/pair.info deleted file mode 100755 index 68b332d..0000000 --- a/All/Genesis-NP/Genesis#351/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:351 -SATName:Genesis -modifiedFPath:helios-client/src/main/java/com/spotify/helios/common/descriptors/PortMapping.java -comSha:13b10105713913925969dccd9567debef87686cc -parentComSha:13b10105713913925969dccd9567debef87686cc^1 -githubUrl:https://github.com/spotify/helios -repoName:spotify#helios \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#359/comMsg.txt b/All/Genesis-NP/Genesis#359/comMsg.txt deleted file mode 100755 index 6b6577f..0000000 --- a/All/Genesis-NP/Genesis#359/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -activejdbc #293 NPE in Http in case no error stream diff --git a/All/Genesis-NP/Genesis#359/diff.diff b/All/Genesis-NP/Genesis#359/diff.diff deleted file mode 100755 index 95650ee..0000000 --- a/All/Genesis-NP/Genesis#359/diff.diff +++ /dev/null @@ -1,32 +0,0 @@ -diff --git a/javalite-common/src/main/java/org/javalite/http/Request.java b/javalite-common/src/main/java/org/javalite/http/Request.java -index 50ec853..316a15f 100644 ---- a/javalite-common/src/main/java/org/javalite/http/Request.java -+++ b/javalite-common/src/main/java/org/javalite/http/Request.java -@@ -192 +191,0 @@ public abstract class Request { -- -@@ -195 +193,0 @@ public abstract class Request { -- -@@ -198 +195,0 @@ public abstract class Request { -- int count = 0; -@@ -200,3 +197,2 @@ public abstract class Request { -- while ((count = in.read(bytes)) > 0) { -- }//nothing -- -+ if(in != null){ -+ while ((in.read(bytes)) > 0) {}//do nothing -@@ -203,0 +200 @@ public abstract class Request { -+ } -@@ -207,5 +204,2 @@ public abstract class Request { -- int ret = 0; -- -- while ((ret = errorStream.read(bytes)) > 0) { -- }//nothing -- -+ if(errorStream != null){ -+ while ((errorStream.read(bytes)) > 0) {}//do nothing -@@ -213 +206,0 @@ public abstract class Request { -- } catch (IOException ignoreToo) { -@@ -214,0 +208 @@ public abstract class Request { -+ } catch (IOException ignoreToo) {} -@@ -218 +211,0 @@ public abstract class Request { -- diff --git a/All/Genesis-NP/Genesis#359/new/Request.java b/All/Genesis-NP/Genesis#359/new/Request.java deleted file mode 100755 index 316a15f..0000000 --- a/All/Genesis-NP/Genesis#359/new/Request.java +++ /dev/null @@ -1,253 +0,0 @@ -/* -Copyright 2009-2014 Igor Polevoy - -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.javalite.http; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.PasswordAuthentication; -import java.net.URL; -import java.util.List; -import java.util.Map; - -import static org.javalite.common.Util.read; - -/** - * This class provides static convenience methods for simple HTTP requests. - * - * @author Igor Polevoy - */ -public abstract class Request { - - protected HttpURLConnection connection; - private boolean connected; - protected String url; - - - - public Request(String url, int connectTimeout, int readTimeout) { - try { - this.url = url; - connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setConnectTimeout(connectTimeout); - connection.setReadTimeout(readTimeout); - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - - /** - * Sets an HTTP header - call before making a request. - * - * @param name header name - * @param value header value. - * @return self. - */ - public T header(String name, String value) { - connection.setRequestProperty(name, value); - return (T) this; - } - - - /** - * Returns input stream to read server response from. - * - * @return input stream to read server response from. - */ - public InputStream getInputStream() { - try { - return connection.getInputStream(); - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - /** - * Returns HTTP headers as sent by server. - * - * @return HTTP headers as sent by server. - */ - public Map> headers() { - connect(); - return connection.getHeaderFields(); - } - - /** - * Returns HTTP response code. - * - * @return HTTP response code. - */ - public int responseCode() { - try { - connect(); - return connection.getResponseCode(); - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - /** - * Returns response message from server, such as "OK", or "Created", etc. - * - * @return response message from server, such as "OK", or "Created", etc. - */ - public String responseMessage() { - try { - connect(); - return connection.getResponseMessage(); - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - /** - * Fetches response content from server as bytes. - * - * @return response content from server as bytes. - */ - public byte[] bytes() { - - connect(); - - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - - byte[] bytes = new byte[1024]; - int count; - try { - InputStream in = connection.getInputStream(); - while ((count = in.read(bytes)) != -1) { - bout.write(bytes, 0, count); - } - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - dispose(); - return bout.toByteArray(); - } - - /** - * Fetches response content from server as String. - * - * @return response content from server as String. - */ - public String text() { - try { - connect(); - String result = responseCode() >= 400 ? read(connection.getErrorStream()) : read(connection.getInputStream()); - dispose(); - return result; - } catch (IOException e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - /** - * Fetches response content from server as String. - * - * @param encoding - name of supported charset to apply when reading data. - * - * @return response content from server as String. - */ - public String text(String encoding) { - try { - connect(); - String result = responseCode() >= 400 ? read(connection.getErrorStream()) : read(connection.getInputStream(), encoding); - dispose(); - return result; - } catch (IOException e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - - /** - * This method is already called from {@link #text()} and {@link #bytes()}, you do not have to call it if you use - * those methods. - *

- * However, if you use {@link #getInputStream()}, call this method in those cases when you think you did - * not read entire content from the stream. - * - *

- * This method clears all remaining data in connections after reading a response. - * This will help keep-alive work smoothly. - */ - public void dispose() { - //according to this: http://download.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive.html - //should read all data from connection to make it happy. - byte[] bytes = new byte[1024]; - try { - InputStream in = connection.getInputStream(); - if(in != null){ - while ((in.read(bytes)) > 0) {}//do nothing - in.close(); - } - } catch (Exception ignore) { - try { - InputStream errorStream = connection.getErrorStream(); - if(errorStream != null){ - while ((errorStream.read(bytes)) > 0) {}//do nothing - errorStream.close(); - } - } catch (IOException ignoreToo) {} - } - } - - protected T connect() { - if (!connected) { - T t = doConnect(); - connected = true; - return t; - } else { - return (T) this; - } - } - - - /** - * Makes a connection to the remote resource. - * - * @return self. - */ - protected abstract T doConnect(); - - - /** - * Sets a user and password for basic authentication. - * - * @param user user. - * @param password password. - * @return self. - */ - public T basic(String user, String password){ - Authenticator.setDefault(new BasicAuthenticator(user, password)); - return (T) this; - } - - class BasicAuthenticator extends Authenticator { - private String user, password; - BasicAuthenticator(String user, String password) { - this.user = user; - this.password = password; - } - public PasswordAuthentication getPasswordAuthentication() { - return (new PasswordAuthentication(user, password.toCharArray())); - } - } -} diff --git a/All/Genesis-NP/Genesis#359/old/Request.java b/All/Genesis-NP/Genesis#359/old/Request.java deleted file mode 100755 index 50ec853..0000000 --- a/All/Genesis-NP/Genesis#359/old/Request.java +++ /dev/null @@ -1,260 +0,0 @@ -/* -Copyright 2009-2014 Igor Polevoy - -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.javalite.http; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.Authenticator; -import java.net.HttpURLConnection; -import java.net.PasswordAuthentication; -import java.net.URL; -import java.util.List; -import java.util.Map; - -import static org.javalite.common.Util.read; - -/** - * This class provides static convenience methods for simple HTTP requests. - * - * @author Igor Polevoy - */ -public abstract class Request { - - protected HttpURLConnection connection; - private boolean connected; - protected String url; - - - - public Request(String url, int connectTimeout, int readTimeout) { - try { - this.url = url; - connection = (HttpURLConnection) new URL(url).openConnection(); - connection.setConnectTimeout(connectTimeout); - connection.setReadTimeout(readTimeout); - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - - /** - * Sets an HTTP header - call before making a request. - * - * @param name header name - * @param value header value. - * @return self. - */ - public T header(String name, String value) { - connection.setRequestProperty(name, value); - return (T) this; - } - - - /** - * Returns input stream to read server response from. - * - * @return input stream to read server response from. - */ - public InputStream getInputStream() { - try { - return connection.getInputStream(); - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - /** - * Returns HTTP headers as sent by server. - * - * @return HTTP headers as sent by server. - */ - public Map> headers() { - connect(); - return connection.getHeaderFields(); - } - - /** - * Returns HTTP response code. - * - * @return HTTP response code. - */ - public int responseCode() { - try { - connect(); - return connection.getResponseCode(); - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - /** - * Returns response message from server, such as "OK", or "Created", etc. - * - * @return response message from server, such as "OK", or "Created", etc. - */ - public String responseMessage() { - try { - connect(); - return connection.getResponseMessage(); - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - /** - * Fetches response content from server as bytes. - * - * @return response content from server as bytes. - */ - public byte[] bytes() { - - connect(); - - ByteArrayOutputStream bout = new ByteArrayOutputStream(); - - byte[] bytes = new byte[1024]; - int count; - try { - InputStream in = connection.getInputStream(); - while ((count = in.read(bytes)) != -1) { - bout.write(bytes, 0, count); - } - } catch (Exception e) { - throw new HttpException("Failed URL: " + url, e); - } - dispose(); - return bout.toByteArray(); - } - - /** - * Fetches response content from server as String. - * - * @return response content from server as String. - */ - public String text() { - try { - connect(); - String result = responseCode() >= 400 ? read(connection.getErrorStream()) : read(connection.getInputStream()); - dispose(); - return result; - } catch (IOException e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - /** - * Fetches response content from server as String. - * - * @param encoding - name of supported charset to apply when reading data. - * - * @return response content from server as String. - */ - public String text(String encoding) { - try { - connect(); - String result = responseCode() >= 400 ? read(connection.getErrorStream()) : read(connection.getInputStream(), encoding); - dispose(); - return result; - } catch (IOException e) { - throw new HttpException("Failed URL: " + url, e); - } - } - - - /** - * This method is already called from {@link #text()} and {@link #bytes()}, you do not have to call it if you use - * those methods. - *

- * However, if you use {@link #getInputStream()}, call this method in those cases when you think you did - * not read entire content from the stream. - * - *

- * This method clears all remaining data in connections after reading a response. - * This will help keep-alive work smoothly. - */ - public void dispose() { - - //according to this: http://download.oracle.com/javase/1.5.0/docs/guide/net/http-keepalive.html - //should read all data from connection to make it happy. - - byte[] bytes = new byte[1024]; - try { - int count = 0; - InputStream in = connection.getInputStream(); - while ((count = in.read(bytes)) > 0) { - }//nothing - - in.close(); - } catch (Exception ignore) { - try { - InputStream errorStream = connection.getErrorStream(); - int ret = 0; - - while ((ret = errorStream.read(bytes)) > 0) { - }//nothing - - errorStream.close(); - } catch (IOException ignoreToo) { - } - } - } - - - protected T connect() { - if (!connected) { - T t = doConnect(); - connected = true; - return t; - } else { - return (T) this; - } - } - - - /** - * Makes a connection to the remote resource. - * - * @return self. - */ - protected abstract T doConnect(); - - - /** - * Sets a user and password for basic authentication. - * - * @param user user. - * @param password password. - * @return self. - */ - public T basic(String user, String password){ - Authenticator.setDefault(new BasicAuthenticator(user, password)); - return (T) this; - } - - class BasicAuthenticator extends Authenticator { - private String user, password; - BasicAuthenticator(String user, String password) { - this.user = user; - this.password = password; - } - public PasswordAuthentication getPasswordAuthentication() { - return (new PasswordAuthentication(user, password.toCharArray())); - } - } -} diff --git a/All/Genesis-NP/Genesis#359/pair.info b/All/Genesis-NP/Genesis#359/pair.info deleted file mode 100755 index 24d23ef..0000000 --- a/All/Genesis-NP/Genesis#359/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:359 -SATName:Genesis -modifiedFPath:javalite-common/src/main/java/org/javalite/http/Request.java -comSha:5220cf5ed61656455a4130778600b8487a580831 -parentComSha:5220cf5ed61656455a4130778600b8487a580831^1 -githubUrl:https://github.com/javalite/activejdbc -repoName:javalite#activejdbc \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#360/comMsg.txt b/All/Genesis-NP/Genesis#360/comMsg.txt deleted file mode 100755 index 44081ab..0000000 --- a/All/Genesis-NP/Genesis#360/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -activejdbc-280 Model.setString() may cause NPE diff --git a/All/Genesis-NP/Genesis#360/diff.diff b/All/Genesis-NP/Genesis#360/diff.diff deleted file mode 100755 index d40e3f8..0000000 --- a/All/Genesis-NP/Genesis#360/diff.diff +++ /dev/null @@ -1,8 +0,0 @@ -diff --git a/activejdbc/src/main/java/org/javalite/activejdbc/Model.java b/activejdbc/src/main/java/org/javalite/activejdbc/Model.java -index 8ee1b29..05e935c 100644 ---- a/activejdbc/src/main/java/org/javalite/activejdbc/Model.java -+++ b/activejdbc/src/main/java/org/javalite/activejdbc/Model.java -@@ -1327,2 +1327 @@ public abstract class Model extends CallbackSupport implements Externalizable { -- return set(attribute, value.toString()); -- -+ return set(attribute, Convert.toString(value)); diff --git a/All/Genesis-NP/Genesis#360/new/Model.java b/All/Genesis-NP/Genesis#360/new/Model.java deleted file mode 100755 index 05e935c..0000000 --- a/All/Genesis-NP/Genesis#360/new/Model.java +++ /dev/null @@ -1,2573 +0,0 @@ -/* -Copyright 2009-2014 Igor Polevoy - -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.javalite.activejdbc; - -import org.javalite.activejdbc.associations.*; -import org.javalite.activejdbc.cache.QueryCache; -import org.javalite.activejdbc.validation.*; -import org.javalite.common.Convert; -import org.javalite.common.Inflector; -import org.javalite.common.Util; -import org.javalite.common.XmlEntities; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.*; -import java.math.BigDecimal; -import java.sql.Clob; -import java.sql.Timestamp; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; - -import static org.javalite.common.Collections.list; -import static org.javalite.common.Inflector.*; -import static org.javalite.common.Util.blank; - - -/** - * This class is a super class of all "models" and provides most functionality - * necessary for implementation of Active Record pattern. - */ -public abstract class Model extends CallbackSupport implements Externalizable { - - private final static Logger logger = LoggerFactory.getLogger(Model.class); - private Map attributes = new HashMap(); - private boolean frozen = false; - private MetaModel metaModelLocal; - private Map cachedParents = new HashMap(); - private Map> cachedChildren = new HashMap>(); - private boolean manageTime = true; - - protected Errors errors; - - protected Model() { - errors = new Errors(); - } - - public static MetaModel getMetaModel() { - Registry.instance().init(MetaModel.getDbName(getDaClass())); - return Registry.instance().getMetaModel(getTableName()); - } - - protected Map getAttributes(){ - return attributes; - } - - - - /** - * Overrides attribute values from input map. The input map may have attributes whose name do not match the - * attribute names (columns) of this model. Such attributes will be ignored. Those values whose names are - * not present in the argument map, will stay untouched. The input map may have only partial list of attributes. - * - * @param input map with attributes to overwrite this models'. Keys are names of attributes of this model, values - * are new values for it. - */ - public void fromMap(Map input){ - - List attributeNames = getMetaModelLocal().getAttributeNames(); - - for (String attrName : attributeNames) { - Object value = input.get(attrName.toLowerCase()); - if (value == null) { - value = input.get(attrName.toUpperCase()); - } - if(input.containsKey(attrName.toLowerCase()) || input.containsKey(attrName.toUpperCase())) - attributes.put(attrName.toLowerCase(), value); - } - } - - - - /** - * Hydrates a this instance of model from a map. Only picks values from a map that match - * this instance's attribute names, while ignoring the others. - * - * @param attributesMap map containing values for this instance. - */ - protected void hydrate(Map attributesMap) { - List attributeNames = getMetaModelLocal().getAttributeNamesSkipId(); - - String idName = getMetaModelLocal().getIdName(); - Object id = attributesMap.get(idName); - - if(id != null) - attributes.put(idName, id); - - for (String attrName : attributeNames) { - - if(attrName.equalsIgnoreCase(getMetaModelLocal().getIdName())){ - continue;//skip ID, already set. - } - - Object value = attributesMap.get(attrName.toLowerCase()); - if (value == null) { - value = attributesMap.get(attrName.toUpperCase()); - } - - //it is necessary to cache contents of a clob, because if a clob instance itself is cached, and accessed later, - //it will not be able to connect back to that same connection from which it came. - //This is only important for cached models. This will allocate a ton of memory if Clobs are large. - //Should the Blob behavior be the same? - //TODO: write about this in future tutorial - if( value instanceof Clob && getMetaModelLocal().cached() ){ - this.attributes.put(attrName.toLowerCase(), Convert.toString(value)); - }else { - this.attributes.put(attrName, getMetaModelLocal().getDialect().overrideDriverTypeConversion(getMetaModelLocal(), attrName, value)); - } - } - } - - - /** - * Convenience method, sets ID value on this model, equivalent to set(getIdName(), id). - * - * @param id value of ID - * @return reference to self for chaining. - */ - public T setId(Object id){ - set(getIdName(), id); - return (T) this; - } - - /** - * Converts to java.sql.Date. Expects a java.sql.Date, - * java.sql.Timestamp, java.sql.Time, java.util.Date or - * any object with string with format: yyyy-mm-dd. - * - * @param attribute name of attribute. - * @param value value to convert. - * @return this model. - */ - public Model setDate(String attribute, Object value) { - return set(attribute, Convert.toSqlDate(value)); - } - - /** - * Performs a conversion to java.sql.Date if necessary, - * uses {@link Convert#toSqlDate(Object)} - * @param attribute attribute name - * @return instance of java.sql.Date - */ - public java.sql.Date getDate(String attribute) { - return Convert.toSqlDate(get(attribute)); - } - - /** - * Performs a primitive conversion of java.util.Date to java.sql.Timestamp - * based on the time value. - * - * - * @param name name of field. - * @param date date value. - * @deprecated use {@link #setTimestamp(String, Object)} instead. - */ - public void setTS(String name, java.util.Date date) { - if(date == null) { - set(name, null); - } else { - set(name, new java.sql.Timestamp(date.getTime())); - } - } - - /** - * Sets values for this model instance. The sequence of values must correspond to sequence of names. - * - * @param attributeNames names of attributes. - * @param values values for this instance. - */ - public void set(String[] attributeNames, Object[] values) { - if (attributeNames == null || values == null || attributeNames.length != values.length) { - throw new IllegalArgumentException("must pass non-null arrays of equal length"); - } - - for (int i = 0; i < attributeNames.length; i++) { - set(attributeNames[i], values[i]); - } - } - - /** - * Sets a value of an attribute. - * - * @param attribute name of attribute to set. Names not related to this model will be rejected (those not matching table columns). - * @param value value of attribute. Feel free to set any type, as long as it can be accepted by your driver. - * @return reference to self, so you can string these methods one after another. - */ - public Model set(String attribute, Object value) { - if(attribute.equalsIgnoreCase("created_at") && manageTime) throw new IllegalArgumentException("cannot set 'created_at'"); - - getMetaModelLocal().checkAttributeOrAssociation(attribute); - - attributes.put(attribute.toLowerCase(), value); - return this; - } - - /** - * Will return true if this instance is frozen, false otherwise. - * A frozen instance cannot use used, as it has no relation to a record in table. - * - * @return true if this instance is frozen, false otherwise. - */ - public boolean isFrozen(){ - return frozen; - } - - - /** - * Returns names of all attributes from this model. - * @return names of all attributes from this model. - */ - public static List attributes(){ - return getMetaModel().getAttributeNames(); - } - - /** - * Returns all associations of this model. - * @return all associations of this model. - */ - public static List associations(){ - return getMetaModel().getAssociations(); - } - - /** - * returns true if this is a new instance, not saved yet to DB, false otherwise. - * - * @return true if this is a new instance, not saved yet to DB, false otherwise - */ - public boolean isNew(){ - return getId() == null; - } - - - /** - * Synonym for {@link #isFrozen()}. if(m.frozen()) seems to read better than classical Java convention. - * - * @return true if this instance is frozen, false otherwise. - */ - public boolean frozen(){ - return isFrozen(); - } - - /** - * Deletes a single table record represented by this instance. This method assumes that a corresponding table - * has only one record whose PK is the ID of this instance. - * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. - * - * @return true if a record was deleted, false if not. - */ - public boolean delete() { - fireBeforeDelete(this); - boolean result; - if( 1 == new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + getMetaModelLocal().getTableName() - + " WHERE " + getMetaModelLocal().getIdName() + "= ?", getId())) { - - frozen = true; - if(getMetaModelLocal().cached()){ - QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); - } - purgeEdges(); - result = true; - } - else{ - result = false; - } - fireAfterDelete(this); - return result; - } - - - /** - * Convenience method, will call {@link #delete()} or {@link #deleteCascade()}. - * - * @param cascade true to call {@link #deleteCascade()}, false to call {@link #delete()}. - */ - public void delete(boolean cascade){ - if(cascade){ - deleteCascade(); - }else{ - delete(); - } - } - - /** - * Deletes this record from associated table, as well as children. - * - * Deletes current model and all of its child and many to many associations. This is not a high performance method, as it will - * load every row into a model instance before deleting, effectively calling (N + 1) per table queries to the DB, one to select all - * the associated records (per table), and one delete statement per record. Use it for small data sets. - * - *

- * In cases of simple one to many and polymorphic associations, things are as expected, a parent is deleted an all children are - * deleted as well, but in more complicated cases, this method will walk entire three of associated tables, sometimes - * coming back to the same one where it all started. - * It will follow associations of children and their associations too; consider this a true cascade delete with all implications - * (circular dependencies, referential integrity constraints, potential performance bottlenecks, etc.) - *

- * - * Imagine a situation where you have DOCTORS and PATIENTS in many to many relationship (with DOCTORS_PATIENTS table - * as a join table), and in addition PATIENTS and PRESCRIPTIONS in one to many relationship, where a patient might - * have many prescriptions: - * -

-     DOCTORS
-        +----+------------+-----------+-----------------+
-        | id | first_name | last_name | discipline      |
-        +----+------------+-----------+-----------------+
-        |  1 | John       | Kentor    | otolaryngology  |
-        |  2 | Hellen     | Hunt      | dentistry       |
-        |  3 | John       | Druker    | oncology        |
-        +----+------------+-----------+-----------------+
-
-     PATIENTS
-        +----+------------+-----------+
-        | id | first_name | last_name |
-        +----+------------+-----------+
-        |  1 | Jim        | Cary      |
-        |  2 | John       | Carpenter |
-        |  3 | John       | Doe       |
-        +----+------------+-----------+
-
-     DOCTORS_PATIENTS
-        +----+-----------+------------+
-        | id | doctor_id | patient_id |
-        +----+-----------+------------+
-        |  1 |         1 |          2 |
-        |  2 |         1 |          1 |
-        |  3 |         2 |          1 |
-        |  4 |         3 |          3 |
-        +----+-----------+------------+
-
-     PRESCRIPTIONS
-        +----+------------------------+------------+
-        | id | name                   | patient_id |
-        +----+------------------------+------------+
-        |  1 | Viagra                 |          1 |
-        |  2 | Prozac                 |          1 |
-        |  3 | Valium                 |          2 |
-        |  4 | Marijuana (medicinal)  |          2 |
-        |  5 | CML treatment          |          3 |
-        +----+------------------------+------------+
-     * 
- * - * Lets start with a simple example, Doctor John Druker. This doctor has one patient John Doe, and the patient has one prescription. - * So, when an instance of this doctor model is issued statement: - *
-     *     drDruker.deleteCascade();
-     * 
- * , the result is as expected: the DOCTORS:ID=3 is deleted, DOCTORS_PATIENTS:ID=4 is deleted, PATIENTS:ID=3 is deleted - * and PRESCRIPTIONS:ID=5 is deleted. - * - *

- * However, when doctor Kentor(#1) is deleted, the following records are also deleted: - *

    - *
  • DOCTORS_PATIENTS:ID=1, 2 - these are links to patients
  • - *
  • PATIENTS:ID=1,2 these are patients themselves
  • - *
  • PRESCRIPTIONS:ID=1,2,3,4 - these are prescriptions of patients 1 and 2
  • - *
- * But, in addition, since this is a many to many relationship, deleting patients 1 and 2 results in also deleting - * doctor Hellen Hunt(#2), since she is a doctor of patient Jim Cary(#1), deleting all corresponding join links from - * table DOCTORS_PATIENTS. So, deleting doctor Kentor, deleted most all records from related tables, leaving only these - * records in place: - *
    - *
  • DOCTORS:ID=3
  • - *
  • DOCTORS_PATIENTS:ID=4
  • - *
  • PATIENTS:ID=3
  • - *
  • PRESCRIPTIONS:ID=5
  • - *
- * Had doctor Hellen Hunt(#2) had more patients, it would delete them too, and so on. This goes a long way to say that it - * could be easy to be tangled up in web of associations, so be careful out there. - * - *

- * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. - */ - public void deleteCascade(){ - deleteCascadeExcept(); - } - - /** - * This method does everything {@link #deleteCascade()} does, but in addition allows to exclude some assosiations - * from this action. This is necessary because {@link #deleteCascade()} method can be far too eager to delete - * records in a database, and this is a good way to tell the model to exclude some associations from deletes. - * - *

Example:

- * - * Patient.findById(3).deleteCascadeExcept(Patient.getMetaModel().getAssociationForTarget("prescriptions")); - * - * - * @see {@link #deleteCascade()} - see for more information. - * @param excludedAssociations associations - */ - public void deleteCascadeExcept(Association ... excludedAssociations){ - List excludedAssociationsList = Arrays.asList(excludedAssociations); - deleteMany2ManyDeep(getMetaModelLocal().getManyToManyAssociations(excludedAssociationsList)); - deleteChildrenDeep(getMetaModelLocal().getOneToManyAssociations(excludedAssociationsList)); - deleteChildrenDeep(getMetaModelLocal().getPolymorphicAssociations(excludedAssociationsList)); - delete(); - } - - - - private void deleteMany2ManyDeep(List many2ManyAssociations){ - List allMany2ManyChildren = new ArrayList(); - for (Association association : many2ManyAssociations) { - String targetTableName = association.getTarget(); - Class c = Registry.instance().getModelClass(targetTableName, false); - if(c == null){// this model is probably not defined as a class, but the table exists! - logger.error("ActiveJDBC WARNING: failed to find a model class for: " + targetTableName + ", maybe model is not defined for this table?" + - " There might be a risk of running into integrity constrain violation if this model is not defined."); - } - else{ - allMany2ManyChildren.addAll(getAll(c)); - } - } - - deleteJoinsForManyToMany(); - for (Model model : allMany2ManyChildren) { - model.deleteCascade(); - } - } - - /** - * Deletes this record from associated table, as well as its immediate children. This is a high performance method - * because it does not walk through a chain of child dependencies like {@link #deleteCascade()} does, but rather issues - * one DELETE statement per child dependency table. Also, its semantics are a bit different between than {@link #deleteCascade()}. - * It only deletes current record and immediate children, but not their children (no grand kinds are dead as a result :)). - *

One to many and polymorphic associations

- * The current record is deleted, as well as immediate children. - *

Many to many associations

- * The current record is deleted, as well as links in a join table. Nothing else is deleted. - *

- * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. - */ - public void deleteCascadeShallow(){ - deleteJoinsForManyToMany(); - deleteOne2ManyChildrenShallow(); - deletePolymorphicChildrenShallow(); - delete(); - } - - - private void deleteJoinsForManyToMany() { - List associations = getMetaModelLocal().getManyToManyAssociations(Collections.emptyList()); - for (Association association : associations) { - String join = ((Many2ManyAssociation)association).getJoin(); - String sourceFK = ((Many2ManyAssociation)association).getSourceFkName(); - String query = "DELETE FROM " + join + " WHERE " + sourceFK + " = " + getId(); - new DB(getMetaModelLocal().getDbName()).exec(query); - } - } - - private void deleteOne2ManyChildrenShallow() { - List childAssociations = getMetaModelLocal().getOneToManyAssociations(Collections.emptyList()); - for (OneToManyAssociation association : childAssociations) { - String target = association.getTarget(); - String query = "DELETE FROM " + target + " WHERE " + association.getFkName() + " = ?"; - new DB(getMetaModelLocal().getDbName()).exec(query, getId()); - } - } - - private void deletePolymorphicChildrenShallow() { - List polymorphics = getMetaModelLocal().getPolymorphicAssociations(new ArrayList()); - for (OneToManyPolymorphicAssociation association : polymorphics) { - String target = association.getTarget(); - String parentType = association.getTypeLabel(); - String query = "DELETE FROM " + target + " WHERE parent_id = ? AND parent_type = ?"; - new DB(getMetaModelLocal().getDbName()).exec(query, getId(), parentType); - } - } - - - private void deleteChildrenDeep(List childAssociations){ - for (Association association : childAssociations) { - String targetTableName = association.getTarget(); - Class c = Registry.instance().getModelClass(targetTableName, false); - if(c == null){// this model is probably not defined as a class, but the table exists! - logger.error("ActiveJDBC WARNING: failed to find a model class for: " + targetTableName + ", maybe model is not defined for this table?" + - " There might be a risk of running into integrity constrain violation if this model is not defined."); - } - else{ - List dependencies = getAll(c); - for (Model model : dependencies) { - model.deleteCascade(); - } - } - } - } - - /** - * Deletes some records from associated table. This method does not follow any associations. - * If this model has one to many associations, you might end up with either orphan records in child - * tables, or run into integrity constraint violations. However, this method if very efficient as it deletes all records - * in one shot, without pre-loading them. - * This method also has a side-effect: it will not mark loaded instances corresponding to deleted records as "frozen". - * This means that such an instance would allow calling save() and saveIt() methods resulting DB errors, as you - * would be attempting to update phantom records. - * - * - * @param query narrows which records to delete. Example:

"last_name like '%sen%'"
. - * @param params (optional) - list of parameters if a query is parametrized. - * @return number od deleted records. - */ - public static int delete(String query, Object... params) { - MetaModel metaModel = getMetaModel(); - int count = params == null || params.length == 0? new DB(metaModel.getDbName()).exec("DELETE FROM " + metaModel.getTableName() + " WHERE " + query) : - new DB(metaModel.getDbName()).exec("DELETE FROM " + metaModel.getTableName() + " WHERE " + query, params); - if(metaModel.cached()){ - QueryCache.instance().purgeTableCache(metaModel.getTableName()); - } - purgeEdges(); - return count; - } - - /** - * Returns true if record corresponding to the id passed exists in the DB. - * - * @param id id in question. - * @return true if corresponding record exists in DB, false if it does not. - */ - public static boolean exists(Object id){ - MetaModel metaModel = getMetaModel(); - return null != new DB(metaModel.getDbName()).firstCell("SELECT " + metaModel.getIdName() + " FROM " + metaModel.getTableName() - + " WHERE " + metaModel.getIdName() + " = ?", id); - } - - /** - * Returns true if record corresponding to the id of this instance exists in the DB. - * - * @return true if corresponding record exists in DB, false if it does not. - */ - public boolean exists(){ - MetaModel metaModel = getMetaModelLocal(); - return null != new DB(metaModel.getDbName()).firstCell("SELECT " + metaModel.getIdName() + " FROM " + metaModel.getTableName() - + " WHERE " + metaModel.getIdName() + " = ?", getId()); - } - - /** - * Deletes all records from associated table. This methods does not take associations into account. - * - * @return number of records deleted. - */ - public static int deleteAll() { - MetaModel metaModel = getMetaModel(); - int count = new DB(metaModel.getDbName()).exec("DELETE FROM " + metaModel.getTableName()); - if(metaModel.cached()){ - QueryCache.instance().purgeTableCache(metaModel.getTableName()); - } - - purgeEdges(); - return count; - } - - /** - * Updates records associated with this model. - * - * This example : - *
-     *  Employee.update("bonus = ?", "years_at_company > ?", "5", "10");
-     * 
null, all records in table will be updated. - * In such cases, use a more explicit {@link #updateAll(String, Object...)} method. - * @param params list of parameters for both updates and conditions. Applied in the same order as in the arguments, - * updates first, then conditions. - * @return number of updated records. - */ - public static int update(String updates, String conditions, Object ... params) { - //TODO: validate that the number of question marks is the same as number of parameters - return ModelDelegate.update(Model.getMetaModel(), updates, conditions, params); - } - - - /** - * Updates all records associated with this model. - * - * This example : - *
-     *  Employee.updateAll("bonus = ?", "10");
-     * 
- * If {@link LazyList#include(Class[])} method was used, and this - * model belongs to a parent (as in many to one relationship), then the parent - * will be eagerly loaded and also converted to a map. Parents' maps are keyed in the - * returned map by underscored name of a parent model class name. - *

- * For example, if this model were Address - * and a parent is User (and user has many addresses), then the resulting map would - * have all the attributes of the current table and another map representing a parent user with a - * key "user" in current map. - * - * @return all values of the model with all attribute names converted to lower case. - */ - public Map toMap(){ - Map retVal = new HashMap(); - for (String key : attributes.keySet()) { - if(attributes.get(key) == null) - continue; - - if(attributes.get(key) instanceof Clob){ - retVal.put(key.toLowerCase(), getString(key)); - }else{ - retVal.put(key.toLowerCase(), attributes.get(key)); - } - } - for(Class parentClass: cachedParents.keySet()){ - retVal.put(underscore(shortName(parentClass.getName())), cachedParents.get(parentClass).toMap()); - } - - for(Class childClass: cachedChildren.keySet()){ - List children = cachedChildren.get(childClass); - - List childMaps = new ArrayList(children.size()); - for(Model child:children){ - childMaps.add(child.toMap()); - } - retVal.put(pluralize(underscore(shortName(childClass.getName()))), childMaps); - } - return retVal; - } - - @Override - public String toString() { - - StringBuilder sb = new StringBuilder(); - sb.append("Model: ").append(getClass().getName()) - .append(", table: '").append(getMetaModelLocal().getTableName()) - .append("', attributes: ").append(attributes); - - if (cachedParents.size() > 0) { - sb.append(", parents: ").append(cachedParents); - } - - if (cachedChildren.size() > 0) { - sb.append(", children: ").append(cachedChildren); - } - return sb.toString(); - } - - - /** - * Parses XML into a model. It expects the same structure of XML as the method {@link #toXml(int, boolean, String...)}. - * It ignores children and dependencies (for now) if any. This method will parse the model attributes - * from the XML document, and will then call {@link #fromMap(java.util.Map)} method. It does not save data into a database, just sets the - * attributes. - * - * @param xml xml to read model attributes from. - */ - public void fromXml(String xml) { - - try{ - //such dumb API! - Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes())); - String topTag = Inflector.underscore(getClass().getSimpleName()); - Element root = document.getDocumentElement(); - - if(!root.getTagName().equals(topTag)){ - throw new InitException("top node has to match model name: " + topTag); - } - NodeList childNodes = root.getChildNodes(); - - Map attributes = new HashMap(); - for(int i = 0; i < childNodes.getLength();i++){ - Node node = childNodes.item(i); - if(node instanceof Element){ - Element child = (Element) node; - attributes.put(child.getTagName(), child.getFirstChild().getNodeValue());//this is even dumber! - } - } - fromMap(attributes); - }catch(Exception e){ - throw new InitException(e); - } - } - - /** - * Generates a XML document from content of this model. - * - * @param spaces by how many spaces to indent. - * @param declaration tru to include XML declaration at the top - * @param attrs list of attributes to include. No arguments == include all attributes. - * @return generated XML. - */ - public String toXml(int spaces, boolean declaration, String ... attrs){ - - Map modelMap = toMap(); - - String indent = ""; - for(int i = 0; i < spaces; i++) - indent += " "; - - List attrList = Arrays.asList(attrs); - - StringWriter sw = new StringWriter(); - - if(declaration) sw.write("" + (spaces > 0?"\n":"")); - - String topTag = Inflector.underscore(getClass().getSimpleName()); - - sw.write(indent + "<" + topTag + ">" + (spaces > 0?"\n":"")); - - for(String name: modelMap.keySet()){ - Object value = modelMap.get(name); - if((attrList.contains(name) || attrs.length == 0) && !(value instanceof List)){ - sw.write(indent + indent + "<" + name + ">" + XmlEntities.XML.escape(value.toString()) + "" + (spaces > 0?"\n":"")); - }else if (value instanceof List){ - List children = (List)value; - sw.write(indent + indent + "<" + name + ">" + (spaces > 0?"\n":"")); - for(Map child: children){ - sw.write(indent + indent + indent + "<" + Inflector.singularize(name) + ">" + (spaces > 0?"\n":"")); - for(Object childKey: child.keySet()){ - sw.write(indent + indent + indent + indent + "<" + childKey + ">" + XmlEntities.XML.escape(child.get(childKey).toString())+ "" + (spaces > 0?"\n":"")); - } - sw.write(indent + indent + indent + "" + (spaces > 0?"\n":"")); - } - sw.write(indent + indent + "" + (spaces > 0?"\n":"")); - } - } - beforeClosingTag(spaces, sw, attrs); - sw.write(indent + "" + (spaces > 0?"\n":"")); - return sw.toString(); - } - - /** - * Override in a subclass to inject custom content onto XML just before the closing tag. - * - * @param spaces number of spaces of indent - * @param writer to write content to. - */ - public void beforeClosingTag(int spaces, StringWriter writer, String ... attrs) { - //do nothing. - } - - - /** - * Generates a JSON document from content of this model. - * - * @param pretty pretty format (human readable), or one line text. - * @param attrs list of attributes to include. No arguments == include all attributes. - * @return generated JSON. - */ - public String toJson(boolean pretty, String... attrs) { - return toJsonP(pretty, "", attrs); - } - - private static DateFormat isoDateFormater; - static { - - //2013-05-28T14:03:17.956+0300 - isoDateFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); -// isoDateFormater.setTimeZone(TimeZone.getTimeZone("UTC")); - } - protected String toJsonP(boolean pretty, String indent, String... attrs) { - Collection attrList = Arrays.asList(attrs); - - StringWriter sw = new StringWriter(); - sw.write(indent + "{" + (pretty ? "" + indent : "")); - - List attributeStrings = new ArrayList(); - - if (attrList.size() == 0) { - attrList = attributes.keySet(); - } - - for (String name : attrList) { - Object v = get(name); - String val = null; - if (v == null) { - val = "null"; - } else if (v instanceof Number || v instanceof Boolean) { - val = v.toString(); - } else if (v instanceof Date) { - val = "\"" + isoDateFormater.format((Date) v) + "\""; - } else { - val = "\"" + v.toString() - .replaceAll("\\\\", "\\\\\\\\") // \ - .replaceAll("\"", "\\\\\"") // " - .replaceAll("/", "\\\\/") // / - .replaceAll("\b", "\\\\b") // \b - .replaceAll("\f", "\\\\f") // \f - .replaceAll("\n", "\\\\n") // \n - .replaceAll("\r", "\\\\r") // \r - .replaceAll("\t", "\\\\t") // \t - + "\""; - } - attributeStrings.add((pretty ? "\n " + indent : "") + "\"" + name + "\":" + val); - } - - sw.write(Util.join(attributeStrings, ",")); - - if (cachedChildren != null && cachedChildren.size() > 0) { - - sw.write("," + (pretty ? "\n " + indent : "") + "\"children\" : {"); - - List childClasses = new ArrayList(); - childClasses.addAll(cachedChildren.keySet()); - - for (int i = 0; i < childClasses.size(); i++) { - Class childClass = childClasses.get(i); - String name = Inflector.pluralize(childClass.getSimpleName()).toLowerCase(); - sw.write((pretty ? "\n" + indent + " " : "") + "\"" + name + "\" : ["); - List childrenList = new ArrayList(); - for (Model child : cachedChildren.get(childClass)) { - childrenList.add((pretty ? "\n" + indent : "") + child.toJsonP(pretty, (pretty ? indent + " " : ""))); - } - sw.write(Util.join(childrenList, ",")); - sw.write((pretty ? "\n" + indent + indent : "") + "]"); - - if(i < (childClasses.size() - 1)){ - sw.write(","); - } - } - sw.write((pretty ? "\n" + indent + indent : "") + "}"); - } - - beforeClosingBrace(pretty, pretty ? " " + indent : "", sw); - sw.write((pretty ? "\n" + indent : "") + "}"); - return sw.toString(); - } - - /** - * Override in subclasses in order to inject custom content into Json just before the closing brace. - * - * @param indent indent at current level - * @param writer writer to write custom content to - */ - public void beforeClosingBrace(boolean pretty, String indent, StringWriter writer){ - - } - - - /** - * Returns parent of this model, assuming that this table represents a child. - * This method may return null in cases when you have orphan record and - * referential integrity is not enforced in DBMS with a foreign key constraint. - * - * @param parentClass class of a parent model. - * @return instance of a parent of this instance in the "belongs to" relationship. - */ - public T parent(Class parentClass) { - return parent(parentClass, false); - } - - public T parent(Class parentClass, boolean cache) { - T cachedParent = parentClass.cast(cachedParents.get(parentClass)); - if (cachedParent != null) { - return cachedParent; - } - MetaModel parentMM = Registry.instance().getMetaModel(parentClass); - String parentTable = parentMM.getTableName(); - - BelongsToAssociation ass = (BelongsToAssociation)getMetaModelLocal().getAssociationForTarget(parentTable, BelongsToAssociation.class); - BelongsToPolymorphicAssociation assP = (BelongsToPolymorphicAssociation)getMetaModelLocal() - .getAssociationForTarget(parentTable, BelongsToPolymorphicAssociation.class); - - String fkValue; - String fkName; - if (ass != null) { - fkValue = getString(ass.getFkName()); - fkName = ass.getFkName(); - } else if (assP != null) { - fkValue = getString("parent_id"); - fkName = "parent_id"; - - if (!assP.getTypeLabel().equals(getString("parent_type"))) { - throw new IllegalArgumentException("Wrong parent: '" + parentClass + "'. Actual parent type label of this record is: '" + getString("parent_type") + "'"); - } - } else { - throw new IllegalArgumentException("there is no association with table: " + parentTable); - } - - if (fkValue == null) { - logger.debug("Attribute: " + fkName + " is null, cannot determine parent. Child record: " + this); - return null; - } - String parentIdName = parentMM.getIdName(); - String query = getMetaModelLocal().getDialect().selectStarParametrized(parentTable, parentIdName); - - T parent; - if (parentMM.cached()) { - parent = parentClass.cast(QueryCache.instance().getItem(parentTable, query, new Object[]{fkValue})); - if (parent != null) { - return parent; - } - } - - List results = new DB(getMetaModelLocal().getDbName()).findAll(query, fkValue); - //expect only one result here - if (results.size() == 0) { //this should be covered by referential integrity constraint - return null; - } else { - try { - parent = parentClass.newInstance(); - parent.hydrate(results.get(0)); - if (parentMM.cached()) { - QueryCache.instance().addItem(parentTable, query, new Object[]{fkValue}, parent); - } - if (cache) { - setCachedParent(parent); - } - return parent; - } catch (Exception e) { - throw new InitException(e.getMessage(), e); - } - } - } - - protected void setCachedParent(Model parent) { - if (parent != null) { - cachedParents.put(parent.getClass(), parent); - } - } - - - /** - * Sets multiple parents on this instance. Basically this sets a correct value of a foreign keys in a - * parent/child relationship. This only works for one to many and polymorphic associations. - * - * @param parents - collection of potential parents of this instance. Its ID values must not be null. - */ - public void setParents(Model... parents){ - for (Model parent : parents) { - setParent(parent); - } - } - - - /** - * Sets a parent on this instance. Basically this sets a correct value of a foreign key in a - * parent/child relationship. This only works for one to many and polymorphic associations. - * The act of setting a parent does not result in saving to a database. - * - * @param parent potential parent of this instance. Its ID value must not be null. - */ - public void setParent(Model parent) { - if (parent == null || parent.getId() == null) { - throw new IllegalArgumentException("parent cannot ne null and parent ID cannot be null"); - } - List associations = getMetaModelLocal().getAssociations(); - for (Association association : associations) { - if (association instanceof BelongsToAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())) { - set(((BelongsToAssociation)association).getFkName(), parent.getId()); - return; - } - if(association instanceof BelongsToPolymorphicAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())){ - set("parent_id", parent.getId()); - set("parent_type", ((BelongsToPolymorphicAssociation)association).getTypeLabel()); - return; - } - } - throw new IllegalArgumentException("Class: " + parent.getClass() + " is not associated with " + this.getClass() - + ", list of existing associations: \n" + Util.join(getMetaModelLocal().getAssociations(), "\n")); - } - - /** - * Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other. - * - * @param other target model. - */ - public void copyTo(T other) { - if (!getMetaModelLocal().getTableName().equals(other.getMetaModelLocal().getTableName())) { - throw new IllegalArgumentException("can only copy between the same types"); - } - - List attrs = getMetaModelLocal().getAttributeNamesSkip(getMetaModelLocal().getIdName()); - for (String name : attrs) { - other.getAttributes().put(name, get(name)); - } - } - - /** - * Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other. - * - * @param other target model. - */ - public void copyFrom(Model other) { - other.copyTo(this); - } - - /** - * This method should be called from all instance methods for performance. - * - * @return - */ - protected MetaModel getMetaModelLocal(){ - if(metaModelLocal == null) - metaModelLocal = getMetaModel(); - - return metaModelLocal; - } - - - protected void setMetamodelLocal(MetaModel metamodelLocal){ - this.metaModelLocal = metamodelLocal; - } - - /** - * Re-reads all attribute values from DB. - * - */ - public void refresh() { - Model fresh = findById(getId()); - - if(fresh == null) - throw new StaleModelException("Failed to refresh self because probably record with " + - "this ID does not exist anymore. Stale model: " + this); - - fresh.copyTo(this); - } - - /** - * Returns a value for attribute. - * - *

Infer relationship from name of argument

- * Besides returning direct attributes of this model, this method is also - * aware of relationships and can return collections based on naming conventions. For example, if a model User has a - * one to many relationship with a model Address, then the following code will work: - *
-     * Address address = ...;
-     * User user = (User)address.get("user");
-     * 
- * Conversely, this will also work: - *
-     * List<Address> addresses = (List<Address>)user.get("addresses");
-     * 
- * - * The same would also work for many to many relationships: - *
-     * List<Doctor> doctors = (List<Doctor>)patient.get("doctors");
-     * ...
-     * List<Patient> patients = (List<Patient>)doctor.get("patients");
-     * 
- * - * This methods will try to infer a name if a table by using {@link org.javalite.common.Inflector} to try to - * convert it to singular and them plural form, an attempting to see if this model has an appropriate relationship - * with another model, if one is found. This method of finding of relationships is best used in templating - * technologies, such as JSPs. For standard cases, please use {@link #parent(Class)}, and {@link #getAll(Class)}. - * - *

Suppressing inference for performance

- *

- * In some cases, the inference of relationships might take a toll on performance, and if a project is not using - * the getter method for inference, than it is wise to turn it off with a system property activejdbc.get.inference: - * - *

-     *         -Dactivejdbc.get.inference = false
-     *     
- * If inference is turned off, only a value of the attribute is returned. - * - *

- * - * @param attribute name of attribute of name or related object. - * @return value for attribute. - */ - public Object get(String attribute) { - if(frozen) throw new FrozenException(this); - - if(attribute == null) throw new IllegalArgumentException("attribute cannot be null"); - - // NOTE: this is a workaround for JSP pages. JSTL in cases ${item.id} does not call the getId() method, instead - //calls item.get("id"), considering that this is a map only! - if(!attributes.containsKey("id") && attribute.equalsIgnoreCase("id")){ - String idName = getMetaModelLocal().getIdName(); - return attributes.get(idName.toLowerCase()); - } - - Object returnValue; - String attributeName = attribute.toLowerCase(); - - String getInferenceProperty = System.getProperty("activejdbc.get.inference"); - - boolean getInference = getInferenceProperty == null || getInferenceProperty.equals("true"); - - if (getInference) { - if ((getMetaModelLocal().hasAttribute(attributeName))) { - return attributes.get(attributeName);//this should account for nulls too! - } else if ((returnValue = tryParent(attributeName)) != null) { - return returnValue; - } else if ((returnValue = tryPolymorphicParent(attributeName)) != null) { - return returnValue; - } else if ((returnValue = tryChildren(attributeName)) != null) { - return returnValue; - } else if ((returnValue = tryPolymorphicChildren(attributeName)) != null) { - return returnValue; - } else if ((returnValue = tryOther(attributeName)) != null) { - return returnValue; - } else { - getMetaModelLocal().checkAttributeOrAssociation(attributeName); - return null; - } - } else { - return attributes.get(attributeName); - } - } - - - private Object tryPolymorphicParent(String parentTable){ - MetaModel parentMM = inferTargetMetaModel(parentTable); - if(parentMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToPolymorphicAssociation.class) ? - parent(parentMM.getModelClass()): null; - } - - private Object tryParent(String parentTable){ - MetaModel parentMM = inferTargetMetaModel(parentTable); - if(parentMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToAssociation.class) ? - parent(parentMM.getModelClass()): null; - } - - private Object tryPolymorphicChildren(String childTable){ - MetaModel childMM = inferTargetMetaModel(childTable); - if(childMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyPolymorphicAssociation.class) ? - getAll(childMM.getModelClass()): null; - } - - private Object tryChildren(String childTable){ - MetaModel childMM = inferTargetMetaModel(childTable); - if(childMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyAssociation.class) ? - getAll(childMM.getModelClass()): null; - } - - private Object tryOther(String otherTable){ - MetaModel otherMM = inferTargetMetaModel(otherTable); - if(otherMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(otherMM.getTableName(), Many2ManyAssociation.class) ? - getAll(otherMM.getModelClass()): null; - } - - private MetaModel inferTargetMetaModel(String targetTableName){ - String targetTable = singularize(targetTableName); - MetaModel targetMM = Registry.instance().getMetaModel(targetTable); - if(targetMM == null){ - targetTable = pluralize(targetTableName); - targetMM = Registry.instance().getMetaModel(targetTable); - } - return targetMM != null? targetMM: null; - } - - /*************************** typed getters *****************************************/ - /** - * Get any value as string. - * - * @param attribute name of attribute. - * @return attribute value as string. - */ - public String getString(String attribute) { - Object value = get(attribute); - return Convert.toString(value); - } - - /** - * Gets a value as bytes. If the column is Blob, bytes are - * read directly, if not, then the value is converted to String first, then - * string bytes are returned. Be careful out there, this will read entire - * Blob onto memory. - * - * @param attribute name of attribute - * @return value as bytes. - */ - public byte[] getBytes(String attribute) { - Object value = get(attribute); - return Convert.toBytes(value); - } - - /** - * Converts Model value to BigDecimal - * - * @see {@link Convert#toBigDecimal} - * @param attribute name of attribute to convert - * @return converted value - */ - public BigDecimal getBigDecimal(String attribute) { - return Convert.toBigDecimal(get(attribute)); - } - - /** - * Converts Model value to Integer - * - * @see {@link Convert#toInteger} - * @param attribute name of attribute to convert - * @return converted value - */ - public Integer getInteger(String attribute) { - return Convert.toInteger(get(attribute)); - } - - /** - * Converts Model value to Long - * - * @see {@link Convert#toLong(Object)} - * @param attribute name of attribute to convert - * @return converted value - */ - public Long getLong(String attribute) { - return Convert.toLong(get(attribute)); - } - - /** - * Converts Model value to Short - * - * @see {@link Convert#toShort(Object)} - * @param attribute name of attribute to convert - * @return converted value - */ - public Short getShort(String attribute) { - return Convert.toShort(get(attribute)); - } - - /** - * Converts Model value to Float - * - * @see {@link Convert#toFloat(Object)} - * @param attribute name of attribute to convert - * @return converted value - */ - public Float getFloat(String attribute) { - return Convert.toFloat(get(attribute)); - } - - /** - * If the value is instance of java.sql.Timestamp, returns it, else tries to convert the - * value to Timestamp using {@link Timestamp#valueOf(String)}. - * This method might trow IllegalArgumentException if fails at conversion. - * - * @see {@link Timestamp#valueOf(String)} - * @param attribute attribute name - * @return instance of Timestamp. - */ - public Timestamp getTimestamp(String attribute) { - return Convert.toTimestamp(get(attribute)); - } - - /** - * Converts Model value to Double - * - * @see {@link Convert#toDouble(Object)} - * @param attribute name of attribute to convert - * @return converted value - */ - public Double getDouble(String attribute) { - return Convert.toDouble(get(attribute)); - } - - - /** - * Returns true if the value is any numeric type and has a value of 1, or - * if string type has a value of 'y', 't', 'true' or 'yes'. Otherwise, return false. - * - * @param attribute attribute name - * @return true if the value is any numeric type and has a value of 1, or - * if string type has a value of 'y', 't', 'true' or 'yes'. Otherwise, return false. - */ - public Boolean getBoolean(String attribute) { - return Convert.toBoolean(get(attribute)); - } - - /*************************** typed setters *****************************************/ - - /** - * Converts object to string when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setString(String attribute, Object value) { - return set(attribute, Convert.toString(value)); - } - - /** - * Converts object to BigDecimal when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setBigDecimal(String attribute, Object value) { - return set(attribute, Convert.toBigDecimal(value)); - } - - /** - * Converts object to Integer when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setInteger(String attribute, Object value) { - return set(attribute, Convert.toInteger(value)); - } - - /** - * Converts object to Long when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setLong(String attribute, Object value) { - return set(attribute, Convert.toLong(value)); - } - - /** - * Converts object to Float when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setFloat(String attribute, Object value) { - return set(attribute, Convert.toFloat(value)); - } - - /** - * - * Converts object to java.sql.Timestamp when setting. - * If the value is instance of java.sql.Timestamp, just sets it, else tries to convert the value to Timestamp using - * Timestamp.valueOf(String). This method might trow IllegalArgumentException if fails at conversion. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setTimestamp(String attribute, Object value) { - return set(attribute, Convert.toTimestamp(value)); - } - - /** - * Converts object to Double when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setDouble(String attribute, Object value) { - return set(attribute, Convert.toDouble(value)); - } - - - - /** - * Sets to true if the value is any numeric type and has a value of 1, or if string type has a - * value of 'y', 't', 'true' or 'yes'. Otherwise, sets to false. - * - * @param attribute name of attribute. - * @param value value to convert. - * @return this model. - */ - public Model setBoolean(String attribute, Object value) { - return set(attribute, Convert.toBoolean(value)); - } - - /** - * This methods supports one to many, many to many relationships as well as polymorphic associations. - *

- * In case of one to many, the clazz must be a class of a child model, and it will return a - * collection of all children. - *

- * In case of many to many, the clazz must be a class of a another related model, and it will return a - * collection of all related models. - *

- * In case of polymorphic, the clazz must be a class of a polymorphically related model, and it will return a - * collection of all related models. - * - * - * @param clazz class of a child model for one to many, or class of another model, in case of many to many or class of child in case of - * polymorphic - * - * @return list of children in case of one to many, or list of other models, in case many to many. - */ - - public LazyList getAll(Class clazz) { - List children = cachedChildren.get(clazz); - if(children != null){ - return (LazyList) children; - } - - String tableName = Registry.instance().getTableName(clazz); - if(tableName == null) throw new IllegalArgumentException("table: " + tableName + " does not exist for model: " + clazz); - - return get(tableName, null); - } - - - /** - * Provides a list of child models in one to many, many to many and polymorphic associations, but in addition also allows to filter this list - * by criteria. - * - *

- * 1. For one to many, the criteria is against the child table. - * - *

- * 2. For polymorphic association, the criteria is against the child table. - * - *

- * 3. For many to many, the criteria is against the join table. - * For example, if you have table PROJECTS, ASSIGNMENTS and PROGRAMMERS, where a project has many programmers and a programmer - * has many projects, and ASSIGNMENTS is a join table, you can write code like this, assuming that the ASSIGNMENTS table - * has a column duration_weeks: - * - *

-     * List threeWeekProjects = programmer.get(Project.class, "duration_weeks = ?", 3);
-     * 
- * where this list will contain all projects to which this programmer is assigned for 3 weeks. - * - * @param clazz related type - * @param query sub-query for join table. - * @param params parameters for a sub-query - * @return list of relations in many to many - */ - public LazyList get(Class clazz, String query, Object ... params){ - return get(Registry.instance().getTableName(clazz), query, params); - } - - private LazyList get(String targetTable, String criteria, Object ...params) { - //TODO: interesting thought: is it possible to have two associations of the same name, one to many and many to many? For now, say no. - - OneToManyAssociation oneToManyAssociation = (OneToManyAssociation)getMetaModelLocal().getAssociationForTarget(targetTable, OneToManyAssociation.class); - Many2ManyAssociation manyToManyAssociation = (Many2ManyAssociation)getMetaModelLocal().getAssociationForTarget(targetTable, Many2ManyAssociation.class); - - OneToManyPolymorphicAssociation oneToManyPolymorphicAssociation = (OneToManyPolymorphicAssociation)getMetaModelLocal().getAssociationForTarget(targetTable, OneToManyPolymorphicAssociation.class); - - String additionalCriteria = criteria != null? " AND ( " + criteria + " ) " : ""; - String subQuery; - if (oneToManyAssociation != null) { - subQuery = oneToManyAssociation.getFkName() + " = ? " + additionalCriteria; - } else if (manyToManyAssociation != null) { - String targetId = Registry.instance().getMetaModel(targetTable).getIdName(); - String joinTable = manyToManyAssociation.getJoin(); - - String query = "SELECT " + targetTable + ".* FROM " + targetTable + ", " + joinTable + - " WHERE " + targetTable + "." + targetId + " = " + joinTable + "." + manyToManyAssociation.getTargetFkName() + - " AND " + joinTable + "." + manyToManyAssociation.getSourceFkName() + " = ? " + additionalCriteria; - - Object[] allParams = new Object[params.length + 1]; - allParams[0] = getId(); - for (int i = 0; i < params.length; i++) { - allParams[i + 1] = params[i]; - } - return new LazyList(true, Registry.instance().getMetaModel(targetTable), query, allParams); - } else if (oneToManyPolymorphicAssociation != null) { - subQuery = "parent_id = ? AND " + " parent_type = '" + oneToManyPolymorphicAssociation.getTypeLabel() + "'" + additionalCriteria; - } else { - throw new NotAssociatedException(getMetaModelLocal().getTableName(), targetTable); - } - - Object[] allParams = new Object[params.length + 1]; - allParams[0] = getId(); - for (int i = 0; i < params.length; i++) { - allParams[i + 1] = params[i]; - } - return new LazyList(subQuery, Registry.instance().getMetaModel(targetTable), allParams); - } - - protected static NumericValidationBuilder validateNumericalityOf(String... attributes) { - return ValidationHelper.addNumericalityValidators(getClassName(), ModelDelegate.toLowerCase(attributes)); - } - - /** - * Adds a validator to the model. - * - * @param validator new validator. - * @return - */ - public static ValidationBuilder addValidator(Validator validator){ - return ValidationHelper.addValidator(getClassName(), validator); - } - - /** - * Adds a new error to the collection of errors. This is a convenience method to be used from custom validators. - * - * @param key - key wy which this error can be retrieved from a collection of errors: {@link #errors()}. - * @param value - this is a key of the message in the resource bundle. - * @see {@link Messages}. - */ - public void addError(String key, String value){ - errors.put(key, value); - } - - public static void removeValidator(Validator validator){ - Registry.instance().removeValidator(Model.getDaClass(), validator); - } - - public static List getValidators(Class daClass){ - return Registry.instance().getValidators(daClass.getName()); - } - - - /** - * Validates an attribite format with a ree hand regular expression. - * - * @param attribute attribute to validate. - * @param pattern regexp pattern which must match the value. - * @return - */ - protected static ValidationBuilder validateRegexpOf(String attribute, String pattern) { - return ValidationHelper.addRegexpValidator(getClassName(), attribute.toLowerCase(), pattern); - } - - /** - * Validates email format. - * - * @param attribute name of atribute that holds email value. - * @return - */ - protected static ValidationBuilder validateEmailOf(String attribute) { - return ValidationHelper.addEmailValidator(getClassName(), attribute.toLowerCase()); - } - - /** - * Validates range. Accepted types are all java.lang.Number subclasses: - * Byte, Short, Integer, Long, Float, Double BigDecimal. - * - * @param attribute attribute to validate - should be within range. - * @param min min value of range. - * @param max max value of range. - * @return - */ - protected static ValidationBuilder validateRange(String attribute, Number min, Number max) { - return ValidationHelper.addRangeValidator(getClassName(), attribute.toLowerCase(), min, max); - } - - /** - * The validation will not pass if the value is either an empty string "", or null. - * - * @param attributes list of attributes to validate. - * @return - */ - protected static ValidationBuilder validatePresenceOf(String... attributes) { - return ValidationHelper.addPresenceValidators(getClassName(), ModelDelegate.toLowerCase(attributes)); - } - - /** - * Add a custom validator to the model. - * - * @param validator custom validator. - */ - protected static ValidationBuilder validateWith(Validator validator) { - return addValidator(validator); - } - - /** - * Adds a custom converter to the model. - * - * @param converter custom converter - */ - protected static ValidationBuilder convertWith(Converter converter) { - return addValidator(converter); - } - - /** - * Converts a named attribute to java.sql.Date if possible. - * Acts as a validator if cannot make a conversion. - * - * @param attributeName name of attribute to convert to java.sql.Date. - * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} - * @return message passing for custom validation message. - */ - protected static ValidationBuilder convertDate(String attributeName, String format){ - return ValidationHelper.addDateConverter(getClassName(), attributeName, format); - } - - /** - * Converts a named attribute to java.sql.Timestamp if possible. - * Acts as a validator if cannot make a conversion. - * - * @param attributeName name of attribute to convert to java.sql.Timestamp. - * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} - * @return message passing for custom validation message. - */ - protected static ValidationBuilder convertTimestamp(String attributeName, String format){ - return ValidationHelper.addTimestampConverter(getClassName(), attributeName, format); - } - - public static boolean belongsTo(Class targetClass) { - String targetTable = Registry.instance().getTableName(targetClass); - MetaModel metaModel = getMetaModel(); - return (null != metaModel.getAssociationForTarget(targetTable, BelongsToAssociation.class) || - null != metaModel.getAssociationForTarget(targetTable, Many2ManyAssociation.class)); - } - - - public static void addCallbacks(CallbackListener ... listeners){ - for(CallbackListener listener: listeners ){ - Registry.instance().addListener(getDaClass(), listener); - } - } - - /** - * This method performs validations and then returns true if no errors were generated, otherwise returns false. - * - * @return true if no errors were generated, otherwise returns false. - */ - public boolean isValid(){ - validate(); - return !hasErrors(); - } - - /** - * Executes all validators attached to this model. - */ - public void validate() { - fireBeforeValidation(this); - errors = new Errors(); - List theValidators = Registry.instance().getValidators(getClass().getName()); - if(theValidators != null){ - for (Validator validator : theValidators) { - validator.validate(this); - } - } - fireAfterValidation(this); - } - - public boolean hasErrors() { - return errors != null && errors.size() > 0; - } - - /** - * Binds a validator to an attribute if validation fails. - * - * @param errorKey key of error in errors map. Usually this is a name of attribute, - * but not limited to that, can be anything. - * - * @param validator -validator that failed validation. - */ - public void addValidator(Validator validator, String errorKey) { - if(!errors.containsKey(errorKey)) - errors.addValidator(errorKey, validator); - } - - /** - * Provides an instance of Errors object, filled with error messages after validation. - * - * @return an instance of Errors object, filled with error messages after validation. - */ - public Errors errors() { - return errors; - } - - /** - * Provides an instance of localized Errors object, filled with error messages after validation. - * - * @param locale locale. - * @return an instance of localized Errors object, filled with error messages after validation. - */ - public Errors errors(Locale locale) { - errors.setLocale(locale); - return errors; - } - - /** - * This is a convenience method to create a model instance already initialized with values. - * Example: - *
-     * Person p = Person.create("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07");
-     * 
- * - * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every - * other is a corresponding value. - * - * This allows for better readability of code. If you just read this aloud, it will become clear. - * - * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at - * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. - * @return newly instantiated model. - */ - public static T create(Object ... namesAndValues){ - - if(namesAndValues.length %2 != 0) throw new IllegalArgumentException("number of arguments must be even"); - - try{ - - Model m = getDaClass().newInstance(); - ModelDelegate.setNamesAndValues(m, namesAndValues); - return (T) m; - } - catch(IllegalArgumentException e){throw e;} - catch(ClassCastException e){throw new IllegalArgumentException("All even arguments must be strings");} - catch(DBException e){throw e;} - catch (Exception e){throw new InitException("Model '" + getClassName() + "' must provide a default constructor. Table:", e);} - } - - - /** - * This is a convenience method to set multiple values to a model. - * Example: - *
-     * Person p = ...
-     * Person p = p.set("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07");
-     * 
- * - * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every - * other is a corresponding value. - * - * This allows for better readability of code. If you just read this aloud, it will become clear. - * - * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at - * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. - * @return newly instantiated model. - */ - public Model set(Object ... namesAndValues){ - ModelDelegate.setNamesAndValues(this, namesAndValues); - return this; - } - - /** - * This is a convenience method to {@link #create(Object...)}. It will create a new model and will save it - * to DB. It has the same semantics as {@link #saveIt()}. - * - * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at - * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. - * @return newly instantiated model which also has been saved to DB. - */ - public static T createIt(Object ... namesAndValues){ - T m = (T)create(namesAndValues); - m.saveIt(); - return m; - } - - public static T findById(Object id) { - if(id == null) return null; - - MetaModel mm = getMetaModel(); - LazyList l = new LazyList(mm.getIdName() + " = ?", mm, id).limit(1); - return l.size() > 0 ? l.get(0) : null; - - } - - /** - * Finder method for DB queries based on table represented by this model. Usually the SQL starts with: - * - * "select * from table_name where " + subquery where table_name is a table represented by this model. - * - * Code example: - *
-     *
-     * List teenagers = Person.where("age > ? and age < ?", 12, 20);
-     * // iterate...
-     *
-     * //same can be achieved (since parameters are optional):
-     * List teenagers = Person.where("age > 12 and age < 20");
-     * //iterate
-     * 
- * - * Limit, offset and order by can be chained like this: - * - *
-     * List teenagers = Person.where("age > ? and age < ?", 12, 20).offset(101).limit(20).orderBy(age);
-     * //iterate
-     * 
- * - * This is a great way to build paged applications. - * - * - * @param subquery this is a set of conditions that normally follow the "where" clause. Example: - * "department = ? and dob > ?". If this value is "*" and no parameters provided, then {@link #findAll()} is executed. - * @param params list of parameters corresponding to the place holders in the subquery. - * @return instance of LazyList containing results. - */ - public static LazyList where(String subquery, Object... params) { - return find(subquery, params); - } - - - - /** - * Synonym of {@link #where(String, Object...)} - * - * @param subquery this is a set of conditions that normally follow the "where" clause. Example: - * "department = ? and dob > ?". If this value is "*" and no parameters provided, then {@link #findAll()} is executed. - * @param params list of parameters corresponding to the place holders in the subquery. - * @return instance of LazyList containing results. - */ - public static LazyList find(String subquery, Object... params) { - - if(subquery.trim().equals("*") && params.length == 0){ - return findAll(); - } - - if(subquery.equals("*") && params.length != 0){ - throw new IllegalArgumentException("cannot provide parameters with query: '*', use findAll() method instead"); - } - - return new LazyList(subquery, getMetaModel(), params); - } - - - /** - * Synonym of {@link #first(String, Object...)}. - * - * @param subQuery selection criteria, example: - *
-     * Person johnTheTeenager = Person.findFirst("name = ? and age > 13 and age < 19 order by age", "John")
-     * 
- * Sometimes a query might be just a clause like this: - *
-     * Person oldest = Person.findFirst("order by age desc")
-     * 
- * @param params list of parameters if question marks are used as placeholders - * @return a first result for this condition. May return null if nothing found. - */ - public static T findFirst(String subQuery, Object... params) { - LazyList results = new LazyList(subQuery, getMetaModel(), params).limit(1); - return results.size() > 0 ? results.get(0) : null; - } - - - /** - * Returns a first result for this condition. May return null if nothing found. - * If last result is needed, then order by some field and call this nethod: - * - * Synonym of {@link #findFirst(String, Object...)}. - *
-     * //first:
-     * Person youngestTeenager= Person.first("age > 12 and age < 20 order by age");
-     *
-     * //last:
-     * Person oldestTeenager= Person.first("age > 12 and age < 20 order by age desc");
-     * 
- * - * - * @param subQuery selection criteria, example: - *
-     * Person johnTheTeenager = Person.first("name = ? and age < 13 order by age", "John")
-     * 
- * Sometimes a query might be just a clause like this: - *
-     * Person p = Person.first("order by age desc")
-     * 
- * @param params list of parameters if question marks are used as placeholders - * @return a first result for this condition. May return null if nothing found. - */ - public static T first(String subQuery, Object... params) { - return (T)findFirst(subQuery, params); - } - - - /** - * This method is for processing really large result sets. Results found by this method are never cached. - * - * @param query query text. - * @param listener this is a call back implementation which will receive instances of models found. - * @deprecated use {@link #findWith(ModelListener, String, Object...)}. - */ - public static void find(String query, final ModelListener listener) { - findWith(listener, query); - } - - - /** - * This method is for processing really large result sets. Results found by this method are never cached. - * - * @param listener this is a call back implementation which will receive instances of models found. - * @param query sub-query (content after "WHERE" clause) - * @param params optional parameters for a query. - */ - public static void findWith(final ModelListener listener, String query, Object ... params) { - long start = System.currentTimeMillis(); - final MetaModel metaModel = getMetaModel(); - String sql = metaModel.getDialect().selectStar(metaModel.getTableName(), query); - - new DB(metaModel.getDbName()).find(sql, params).with( new RowListenerAdapter() { - @Override - public void onNext(Map row) { - listener.onModel(instance(row, metaModel)); - } - }); - LogFilter.logQuery(logger, sql, null, start); - } - - - /** - * Free form query finder. Example: - *
-     * List rules = Rule.findBySQL("select rule.*, goal_identifier from rule, goal where goal.goal_id = rule.goal_id order by goal_identifier asc, rule_type desc");
-     * 
- * Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate itself properly. - * Returned columns that are not part of this model will be ignored, but can be used for caluses like above. - * - * @param fullQuery free-form SQL. - * @param params parameters if query is parametrized. - * @param - class that extends Model. - * @return list of models representing result set. - */ - public static LazyList findBySQL(String fullQuery, Object... params) { - return new LazyList(false, getMetaModel(), fullQuery, params); - } - - /** - * This method returns all records from this table. If you need to get a subset, look for variations of "find()". - * - * @return result list - */ - public static LazyList findAll() { - return new LazyList(null, getMetaModel()); - } - - /** - * Adds a new child dependency. This method works for all three association types: - *
    - *
  • One to many - argument model should be a child in the relationship. This method will immediately set it's - * ID as a foreign key on the child and will then save the child.
  • - *
  • Many to many - argument model should be the other model in the relationship. This method will check if the - * added child already has an ID. If the child does have an ID, then the method will create a link in the join - * table. If the child does not have an ID, then this method saves the child first, then creates a record in the - * join table linking this model instance and the child instance.
  • - *
  • Polymorphic - argument model should be a polymorphic child of this model. This method will set the - * parent_id and parent_type as appropriate and then will then save the child.
  • - *
- * - * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. - * - * @param child instance of a model that has a relationship to the current model. - * Either one to many or many to many relationships are accepted. - */ - public void add(Model child) { - - //TODO: refactor this method - String childTable = Registry.instance().getTableName(child.getClass()); - MetaModel metaModel = getMetaModelLocal(); - if (getId() != null) { - - if (metaModel.hasAssociation(childTable, OneToManyAssociation.class)) { - OneToManyAssociation ass = (OneToManyAssociation)metaModel.getAssociationForTarget(childTable, OneToManyAssociation.class); - String fkName = ass.getFkName(); - child.set(fkName, getId()); - child.saveIt();//this will cause an exception in case validations fail. - }else if(metaModel.hasAssociation(childTable, Many2ManyAssociation.class)){ - Many2ManyAssociation ass = (Many2ManyAssociation) metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class); - String join = ass.getJoin(); - String sourceFkName = ass.getSourceFkName(); - String targetFkName = ass.getTargetFkName(); - if(child.getId() == null) - child.saveIt(); - - MetaModel joinMM = Registry.instance().getMetaModel(join); - if(joinMM == null){ - new DB(metaModel.getDbName()).exec("INSERT INTO " + join + " ( " + sourceFkName + ", " + targetFkName + " ) VALUES ( " + getId()+ ", " + child.getId() + ")"); - }else{ - //TODO: write a test to cover this case: - //this is for Oracle, many 2 many, and all annotations used, including @IdGenerator. In this case, - //it is best to delegate generation of insert to a model (sequences, etc.) - try{ - Model joinModel = (Model)joinMM.getModelClass().newInstance(); - joinModel.set(sourceFkName, getId()); - joinModel.set(targetFkName, child.getId()); - joinModel.saveIt(); - } - catch(InstantiationException e){ - throw new InitException("failed to create a new instance of class: " + joinMM.getClass() - + ", are you sure this class has a default constructor?", e); - } - catch(IllegalAccessException e){throw new InitException(e);} - finally { - QueryCache.instance().purgeTableCache(join); - QueryCache.instance().purgeTableCache(metaModel.getTableName()); - QueryCache.instance().purgeTableCache(childTable); - } - } - }else if(metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)){ - - OneToManyPolymorphicAssociation ass = (OneToManyPolymorphicAssociation)metaModel - .getAssociationForTarget(childTable, OneToManyPolymorphicAssociation.class); - child.set("parent_id", getId()); - child.set("parent_type", ass.getTypeLabel()); - child.saveIt(); - - }else - throw new NotAssociatedException(metaModel.getTableName(), childTable); - } else { - throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. Save this instance first, then you will be able to add dependencies to it."); - } - } - - - /** - * Removes associated child from this instance. The child model should be either in belongs to association (including polymorphic) to this model - * or many to many association. - * - *

One to many and polymorphic associations

- * This method will simply call child.delete() method. This will render the child object frozen. - * - *

Many to many associations

- * This method will remove an associated record from the join table, and will do nothing to the child model or record. - * - *

- * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. - * - * @param child model representing a "child" as in one to many or many to many association with this model. - */ - public void remove(Model child){ - - if(child == null) throw new IllegalArgumentException("cannot remove what is null"); - - if(child.frozen() || child.getId() == null) throw new IllegalArgumentException("Cannot remove a child that does " + - "not exist in DB (either frozen, or ID not set)"); - - String childTable = Registry.instance().getTableName(child.getClass()); - MetaModel metaModel = getMetaModelLocal(); - if (getId() != null) { - if (metaModel.hasAssociation(childTable, OneToManyAssociation.class) - || metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)) { - child.delete(); - }else if(metaModel.hasAssociation(childTable, Many2ManyAssociation.class)){ - Many2ManyAssociation ass = (Many2ManyAssociation)metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class); - String join = ass.getJoin(); - String sourceFkName = ass.getSourceFkName(); - String targetFkName = ass.getTargetFkName(); - new DB(metaModel.getDbName()).exec("DELETE FROM " + join + " WHERE " + sourceFkName + " = ? AND " - + targetFkName + " = ?", getId(), child.getId()); - }else - throw new NotAssociatedException(metaModel.getTableName(), childTable); - } else { - throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. " + - "Save this instance first, then you will be able to add dependencies to it."); - } - } - - /** - * This method will not exit silently like {@link #save()}, it instead will throw {@link org.javalite.activejdbc.validation.ValidationException} - * if validations did not pass. - * - * @return true if the model was saved, false if you set an ID value for the model, but such ID does not exist in DB. - */ - public boolean saveIt() { - boolean result = save(); - purgeEdges(); - if(errors.size() > 0){ - throw new ValidationException(this); - } - return result; - } - - - - /** - * Resets all data in this model, including the ID. - * After this method, this instance is equivalent to an empty, just created instance. - */ - public void reset() { - attributes = new HashMap(); - } - - /** - * Unfreezes this model. After this method it is possible again to call save() and saveIt() methods. - * This method will erase the value of ID on this instance, while preserving all other attributes' values. - * - * If a record was deleted, it is frozen and cannot be saved. After it is thawed, it can be saved again, but it will - * generate a new insert statement and create a new record in the table with all the same attribute values. - * - *

- * Synonym for {@link #defrost()}. - */ - public void thaw(){ - attributes.put(getMetaModelLocal().getIdName(), "");//makes it blank - frozen = false; - } - - /** - * Synonym for {@link #thaw()}. - */ - public void defrost(){ - thaw(); - } - - /** - * This method will save data from this instance to a corresponding table in the DB. - * It will generate insert SQL if the model is new, or update if the model exists in the DB. - * This method will execute all associated validations and if those validations generate errors, - * these errors are attached to this instance. Errors are available by {#link #errors() } method. - * The save() method is mostly for web applications, where code like this is written: - *

-     * if(person.save())
-     *      //show page success
-     * else{
-     *      request.setAttribute("errors", person.errors());
-     *      //show errors page, or same page so that user can correct errors.
-     *   }
-     * 
- * - * In other words, this method will not throw validation exceptions. However, if there is a problem in the DB, then - * there can be a runtime exception thrown. - * - * @return true if a model was saved and false if values did not pass validations and the record was not saved. - * False will also be returned if you set an ID value for the model, but such ID does not exist in DB. - */ - public boolean save() { - if(frozen) throw new FrozenException(this); - - fireBeforeSave(this); - - validate(); - if (hasErrors()) { - return false; - } - - boolean result; - if (blank(getId())) { - result = doInsert(); - } else { - result = update(); - } - fireAfterSave(this); - return result; - } - - /** - * Returns total count of records in table. - * - * @return total count of records in table. - */ - public static Long count() { - MetaModel metaModel = getMetaModel(); - String sql = "SELECT COUNT(*) FROM " + metaModel.getTableName(); - Long result; - if(metaModel.cached()){ - result = (Long)QueryCache.instance().getItem(metaModel.getTableName(), sql, null); - if(result == null) - { - result = new DB(metaModel.getDbName()).count(metaModel.getTableName()); - QueryCache.instance().addItem(metaModel.getTableName(), sql, null, result); - } - }else{ - result = new DB(metaModel.getDbName()).count(metaModel.getTableName()); - } - return result; - } - - /** - * Returns count of records in table under a condition. - * - * @param query query to select records to count. - * @param params parameters (if any) for the query. - * @return count of records in table under a condition. - */ - public static Long count(String query, Object... params) { - - MetaModel metaModel = getMetaModel(); - - //attention: this SQL is only used for caching, not for real queries. - String sql = "SELECT COUNT(*) FROM " + metaModel.getTableName() + " where " + query; - - Long result; - if(metaModel.cached()){ - result = (Long)QueryCache.instance().getItem(metaModel.getTableName(), sql, params); - if(result == null){ - result = new DB(metaModel.getDbName()).count(metaModel.getTableName(), query, params); - QueryCache.instance().addItem(metaModel.getTableName(), sql, params, result); - } - }else{ - result = new DB(metaModel.getDbName()).count(metaModel.getTableName(), query, params); - } - return result; - } - - - /** - * @return attributes names that have been set by client code. - */ - private List getValueAttributeNames(boolean includeId) { - List attributeNames = new ArrayList(); - - for(String name: attributes.keySet()){ - if(includeId){ - if (!name.equalsIgnoreCase(getMetaModelLocal().getVersionColumn())) - attributeNames.add(name); - }else{ - if (!name.equalsIgnoreCase(getMetaModelLocal().getVersionColumn()) && !name.equalsIgnoreCase(getMetaModelLocal().getIdName())) - attributeNames.add(name); - } - } - return attributeNames; - } - - - private boolean doInsert() { - - fireBeforeCreate(this); - doCreatedAt(); - doUpdatedAt(); - - //TODO: need to invoke checkAttributes here too, and maybe rely on MetaModel for this. - - List valueAttributes = getValueAttributeNames(false); - - List values = new ArrayList(); - for (String attribute : valueAttributes) { - values.add(this.attributes.get(attribute)); - } - String query = getMetaModelLocal().getDialect().createParametrizedInsert(getMetaModelLocal(), valueAttributes); - try { - Object id = new DB(getMetaModelLocal().getDbName()).execInsert(query, getMetaModelLocal().getIdName(), values.toArray()); - if(getMetaModelLocal().cached()){ - QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); - } - - attributes.put(getMetaModelLocal().getIdName(), id); - - fireAfterCreate(this); - - if(getMetaModelLocal().isVersioned()){ - set(getMetaModelLocal().getVersionColumn(), 1); - } - - return true; - } catch (DBException e) { - throw e; - } catch (Exception e) { - throw new DBException(e.getMessage(), e); - } - } - - - /** - * This method will save a model as new. In other words, it will not try to guess if this is a - * new record or a one that exists in the table. It does not have "belt and suspenders", it will - * simply generate and execute insert statement, assuming that developer knows what he/she is doing. - * - * @return true if model was saved, false if not - */ - public boolean insert() { - - fireBeforeCreate(this); - doCreatedAt(); - doUpdatedAt(); - - List valueAttributes = getValueAttributeNames(true); - - List values = new ArrayList(); - for (String attribute : valueAttributes) { - values.add(this.attributes.get(attribute)); - } - String query = getMetaModelLocal().getDialect().createParametrizedInsertIdUnmanaged(getMetaModelLocal(), valueAttributes); - try { - long recordsUpdated = new DB(getMetaModelLocal().getDbName()).exec(query, values.toArray()); - if(getMetaModelLocal().cached()){ - QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); - } - - fireAfterCreate(this); - - if(getMetaModelLocal().isVersioned()){ - set(getMetaModelLocal().getVersionColumn(), 1); - } - - return recordsUpdated == 1; - } catch (DBException e) { - throw e; - } catch (Exception e) { - throw new DBException(e.getMessage(), e); - } - } - - private void doCreatedAt() { - if(getMetaModelLocal().hasAttribute("created_at") && manageTime){ - //clean just in case. - attributes.remove("created_at"); - attributes.remove("CREATED_AT"); - attributes.put("created_at", new Timestamp(System.currentTimeMillis())); - } - } - - private void doUpdatedAt() { - if(getMetaModelLocal().hasAttribute("updated_at") && manageTime){ - //clean just in case. - attributes.remove("updated_at"); - attributes.remove("UPDATED_AT"); - set("updated_at", new Timestamp(System.currentTimeMillis())); - } - } - - private boolean update() { - - doUpdatedAt(); - - MetaModel metaModel = getMetaModelLocal(); - String query = "UPDATE " + metaModel.getTableName() + " SET "; - List names = metaModel.getAttributeNamesSkipGenerated(manageTime); - for (int i = 0; i < names.size(); i++) { - String name = names.get(i); - query += name + "= ?"; - if (i < names.size() - 1) { - query += ", "; - } - } - - List values = getAttributeValuesSkipGenerated(names); - - if(metaModel.hasAttribute("updated_at")){ - query += ", updated_at = ? "; - values.add(get("updated_at")); - } - - if(metaModel.isVersioned()){ - query += ", " + getMetaModelLocal().getVersionColumn() + " = ? "; - values.add(getLong(getMetaModelLocal().getVersionColumn()) + 1); - } - query += " where " + metaModel.getIdName() + " = ?"; - query += metaModel.isVersioned()? " and " + getMetaModelLocal().getVersionColumn() + " = ?" :""; - values.add(getId()); - if(metaModel.isVersioned()){ - values.add((get(getMetaModelLocal().getVersionColumn()))); - } - int updated = new DB(metaModel.getDbName()).exec(query, values.toArray()); - if(metaModel.isVersioned() && updated == 0){ - throw new StaleModelException("Failed to update record for model '" + getClass() + - "', with " + getIdName() + " = " + getId() + " and " + getMetaModelLocal().getVersionColumn() + " = " + get(getMetaModelLocal().getVersionColumn()) + - ". Either this record does not exist anymore, or has been updated to have another record_version."); - }else if(metaModel.isVersioned()){ - set(getMetaModelLocal().getVersionColumn(), getLong(getMetaModelLocal().getVersionColumn()) + 1); - } - if(metaModel.cached()){ - QueryCache.instance().purgeTableCache(metaModel.getTableName()); - } - return updated > 0; - } - - private List getAttributeValuesSkipGenerated(List names) { - List values = new ArrayList(); - for (String name : names) { - values.add(get(name)); - } - return values; - } - - static T instance(Map m, MetaModel metaModel) { - try { - T instance = (T) metaModel.getModelClass().newInstance(); - instance.setMetamodelLocal(metaModel); - instance.hydrate(m); - return instance; - } - catch(InstantiationException e){ - throw new InitException("Failed to create a new instance of: " + metaModel.getModelClass() + ", are you sure this class has a default constructor?"); - } - catch(DBException e){ - throw e; - } - catch(InitException e){ - throw e; - } - catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - private static Class getDaClass() { - try { - if (Registry.instance().initialized()) { - MetaModel mm = Registry.instance().getMetaModelByClassName(getClassName()); - return mm == null ? (Class) Class.forName(getClassName()) : mm.getModelClass(); - } else { - return (Class) Class.forName(getClassName()); - } - } catch (Exception e) { - throw new DBException(e.getMessage(), e); - } - } - - private static String getClassName() { - return new ClassGetter().getClassName(); - } - - public static String getTableName() { - return Registry.instance().getTableName(getDaClass()); - } - - public Object getId() { - return get(getMetaModelLocal().getIdName()); - } - - public String getIdName() { - return getMetaModelLocal().getIdName(); - } - - protected void setChildren(Class childClass, List children) { - cachedChildren.put(childClass, children); - } - - /** - * Turns off automatic management of time-related attributes created_at and updated_at. - * If management of time attributes is turned off, - * - * @param manage if true, the attributes are managed by the model. If false, they are managed by developer. - */ - public void manageTime(boolean manage) { - this.manageTime = manage; - } - - static class ClassGetter extends SecurityManager { - public String getClassName() { - Class[] classes = getClassContext(); - for (Class clazz : classes) { - if (Model.class.isAssignableFrom(clazz) && clazz != null && !clazz.equals(Model.class)) { - return clazz.getName(); - } - } - throw new InitException("failed to determine Model class name, are you sure models have been instrumented?"); - } - } - - /** - * Generates INSERT SQL based on this model. Uses single quotes for all string values. - * Example: - *
-     *
-     * String insert = u.toInsert();
-     * //yields this output:
-     * //INSERT INTO users (id, first_name, email, last_name) VALUES (1, 'Marilyn', 'mmonroe@yahoo.com', 'Monroe');
-     * 
- * - * @return INSERT SQL based on this model. - */ - public String toInsert(){ - return toInsert("'", "'"); - } - - - /** - * Generates INSERT SQL based on this model. - * For instance, for Oracle, the left quote is: "q'{" and the right quote is: "}'". - * The output will also use single quotes for java.sql.Timestamp and java.sql.Date types. - * - * Example: - *
-     * String insert = u.toInsert("q'{", "}'");
-     * //yields this output
-     * //INSERT INTO users (id, first_name, email, last_name) VALUES (1, q'{Marilyn}', q'{mmonroe@yahoo.com}', q'{Monroe}');
-     * 
- * @param leftStringQuote - left quote for a string value, this can be different for different databases. - * @param rightStringQuote - left quote for a string value, this can be different for different databases. - * @return SQL INSERT string; - */ - public String toInsert(String leftStringQuote, String rightStringQuote){ - return toInsert(new SimpleFormatter(java.sql.Date.class, "'", "'"), - new SimpleFormatter(Timestamp.class, "'", "'"), - new SimpleFormatter(String.class, leftStringQuote, rightStringQuote)); - } - - /** - * TODO: write good JavaDoc, use code inside method above - * - * @param formatters - * @return - */ - public String toInsert(Formatter... formatters){ - HashMap formatterMap = new HashMap(); - - for(Formatter f: formatters){ - formatterMap.put(f.getValueClass(), f); - } - - List names = new ArrayList(attributes.keySet()); - Collections.sort(names); - List values = new ArrayList(); - - for(String name: names){ - Object value = get(name); - if(value == null){ - values.add("NULL"); - } - else if (value instanceof String && !formatterMap.containsKey(String.class)){ - values.add("'" + value + "'"); - }else{ - if(formatterMap.containsKey(value.getClass())){ - values.add(formatterMap.get(value.getClass()).format(value)); - }else{ - values.add(value); - } - } - } - return new StringBuffer("INSERT INTO ").append(getMetaModelLocal().getTableName()).append(" (") - .append(Util.join(names, ", ")).append(") VALUES (").append(Util.join(values, ", ")).append(")").toString(); - } - - /** - * Use to force-purge cache associated with this table. If this table is not cached, this method has no side effect. - */ - public static void purgeCache(){ - MetaModel mm = getMetaModel(); - if(mm.cached()){ - QueryCache.instance().purgeTableCache(mm.getTableName()); - } - } - - - /** - * Convenience method: converts ID value to Long and returns it. - * - * @return value of attribute corresponding to getIdName(), converted to Long. - */ - public Long getLongId() { - Object id = get(getIdName()); - if (id == null) { - throw new NullPointerException(getIdName() + " is null, cannot convert to Long"); - } - return Convert.toLong(id); - } - - private static void purgeEdges(){ - ModelDelegate.purgeEdges(getMetaModel()); - } - - - public void writeExternal(ObjectOutput out) throws IOException { - out.writeObject(attributes); - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - attributes = (Map) in.readObject(); - } -} - diff --git a/All/Genesis-NP/Genesis#360/new/pom.xml b/All/Genesis-NP/Genesis#360/new/pom.xml deleted file mode 100755 index c71b51b..0000000 --- a/All/Genesis-NP/Genesis#360/new/pom.xml +++ /dev/null @@ -1,357 +0,0 @@ - - 4.0.0 - org.javalite - activejdbc - jar - 1.4.10-SNAPSHOT - JavaLite - ActiveJDBC ORM Framework - - - org.sonatype.oss - oss-parent - 7 - - - - - UTF-8 - com.mysql.jdbc.Driver - jdbc:mysql://localhost/activejdbc - root - p@ssw0rd - mysql - - - - - mysql - - false - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost/activejdbc - root - p@ssw0rd - mysql - - - - mysql - mysql-connector-java - 5.1.25 - test - - - - - oracle - - - oracle.jdbc.OracleDriver - - - - - jdbc:oracle:thin:@//192.168.0.112:1521/orcl - scott - oracle - - oracle - - - - oracle - ojdbc14 - 10.2.0.4 - test - - - - - - oracle - http://192.168.0.55:8084/nexus/content/repositories/oracle/ - - - - - postgresql - - org.postgresql.Driver - jdbc:postgresql://192.168.0.55/postgres - postgres - p@ssw0rd - postgresql - - - - postgresql - postgresql - 8.4-701.jdbc3 - test - - - - - h2 - - org.h2.Driver - jdbc:h2:mem:test;DB_CLOSE_DELAY=-1 - sa - - h2 - - - - com.h2database - h2 - 1.3.171 - test - - - - - tds - - net.sourceforge.jtds.jdbc.Driver - jdbc:jtds:sqlserver://192.168.0.33/activejdbc;TDS=8.0 - activejdbc - activejdbc - mssql - - - - net.sourceforge.jtds - jtds - 1.2.4 - test - - - - - - ms-releases - http://192.168.0.55:8084/nexus/content/repositories/microsoft/ - - - - - - mssql - - com.microsoft.sqlserver.jdbc.SQLServerDriver - jdbc:sqlserver://192.168.0.33:1433;databaseName=activejdbc - activejdbc - activejdbc - mssql - - - - - com.microsoft.sqljdbc - sqljdbc4 - 4.0.3 - test - - - - - ms-releases - http://192.168.0.55:8084/nexus/content/repositories/microsoft/ - - - - - instrument - - true - - - - - - org.javalite - activejdbc-instrumentation - ${project.version} - - - process-test-classes - instrument - - ${project.basedir}/target/test-classes - - - - - - org.javassist - javassist - 3.18.1-GA - - - - - - - - - - - src/test/resources - true - - - - - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - true - 128m - 512m - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - org.apache.maven.plugins - maven-surefire-plugin - 2.5 - - brief - true - false - - true - - - - - - - - - junit - junit - 4.8.2 - test - - - javax.servlet - servlet-api - 2.5 - provided - - - org.slf4j - slf4j-api - 1.7.5 - - - org.slf4j - jcl-over-slf4j - 1.7.5 - provided - - - org.slf4j - slf4j-simple - 1.7.5 - provided - - - mysql - mysql-connector-java - 5.1.17 - test - - - org.javalite - javalite-common - ${project.version} - - - dom4j - dom4j - - - jaxen - jaxen - - - - - dom4j - dom4j - 1.6.1 - test - - - jaxen - jaxen - 1.1.4 - test - - - opensymphony - oscache - 2.4 - provided - - - javax.jms - jms - - - javax.servlet - servlet-api - - - org.hibernate - hibernate - - - commons-logging - commons-logging - - - - - com.h2database - h2 - 1.3.171 - jar - test - - - org.codehaus.jackson - jackson-core-lgpl - 1.8.2 - test - - - org.codehaus.jackson - jackson-mapper-lgpl - 1.8.2 - test - - - c3p0 - c3p0 - 0.9.1.2 - test - - - net.sf.ehcache - ehcache-core - 2.4.5 - provided - - - diff --git a/All/Genesis-NP/Genesis#360/old/Model.java b/All/Genesis-NP/Genesis#360/old/Model.java deleted file mode 100755 index 8ee1b29..0000000 --- a/All/Genesis-NP/Genesis#360/old/Model.java +++ /dev/null @@ -1,2574 +0,0 @@ -/* -Copyright 2009-2014 Igor Polevoy - -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.javalite.activejdbc; - -import org.javalite.activejdbc.associations.*; -import org.javalite.activejdbc.cache.QueryCache; -import org.javalite.activejdbc.validation.*; -import org.javalite.common.Convert; -import org.javalite.common.Inflector; -import org.javalite.common.Util; -import org.javalite.common.XmlEntities; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.w3c.dom.Document; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -import javax.xml.parsers.DocumentBuilderFactory; -import java.io.*; -import java.math.BigDecimal; -import java.sql.Clob; -import java.sql.Timestamp; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.*; - -import static org.javalite.common.Collections.list; -import static org.javalite.common.Inflector.*; -import static org.javalite.common.Util.blank; - - -/** - * This class is a super class of all "models" and provides most functionality - * necessary for implementation of Active Record pattern. - */ -public abstract class Model extends CallbackSupport implements Externalizable { - - private final static Logger logger = LoggerFactory.getLogger(Model.class); - private Map attributes = new HashMap(); - private boolean frozen = false; - private MetaModel metaModelLocal; - private Map cachedParents = new HashMap(); - private Map> cachedChildren = new HashMap>(); - private boolean manageTime = true; - - protected Errors errors; - - protected Model() { - errors = new Errors(); - } - - public static MetaModel getMetaModel() { - Registry.instance().init(MetaModel.getDbName(getDaClass())); - return Registry.instance().getMetaModel(getTableName()); - } - - protected Map getAttributes(){ - return attributes; - } - - - - /** - * Overrides attribute values from input map. The input map may have attributes whose name do not match the - * attribute names (columns) of this model. Such attributes will be ignored. Those values whose names are - * not present in the argument map, will stay untouched. The input map may have only partial list of attributes. - * - * @param input map with attributes to overwrite this models'. Keys are names of attributes of this model, values - * are new values for it. - */ - public void fromMap(Map input){ - - List attributeNames = getMetaModelLocal().getAttributeNames(); - - for (String attrName : attributeNames) { - Object value = input.get(attrName.toLowerCase()); - if (value == null) { - value = input.get(attrName.toUpperCase()); - } - if(input.containsKey(attrName.toLowerCase()) || input.containsKey(attrName.toUpperCase())) - attributes.put(attrName.toLowerCase(), value); - } - } - - - - /** - * Hydrates a this instance of model from a map. Only picks values from a map that match - * this instance's attribute names, while ignoring the others. - * - * @param attributesMap map containing values for this instance. - */ - protected void hydrate(Map attributesMap) { - List attributeNames = getMetaModelLocal().getAttributeNamesSkipId(); - - String idName = getMetaModelLocal().getIdName(); - Object id = attributesMap.get(idName); - - if(id != null) - attributes.put(idName, id); - - for (String attrName : attributeNames) { - - if(attrName.equalsIgnoreCase(getMetaModelLocal().getIdName())){ - continue;//skip ID, already set. - } - - Object value = attributesMap.get(attrName.toLowerCase()); - if (value == null) { - value = attributesMap.get(attrName.toUpperCase()); - } - - //it is necessary to cache contents of a clob, because if a clob instance itself is cached, and accessed later, - //it will not be able to connect back to that same connection from which it came. - //This is only important for cached models. This will allocate a ton of memory if Clobs are large. - //Should the Blob behavior be the same? - //TODO: write about this in future tutorial - if( value instanceof Clob && getMetaModelLocal().cached() ){ - this.attributes.put(attrName.toLowerCase(), Convert.toString(value)); - }else { - this.attributes.put(attrName, getMetaModelLocal().getDialect().overrideDriverTypeConversion(getMetaModelLocal(), attrName, value)); - } - } - } - - - /** - * Convenience method, sets ID value on this model, equivalent to set(getIdName(), id). - * - * @param id value of ID - * @return reference to self for chaining. - */ - public T setId(Object id){ - set(getIdName(), id); - return (T) this; - } - - /** - * Converts to java.sql.Date. Expects a java.sql.Date, - * java.sql.Timestamp, java.sql.Time, java.util.Date or - * any object with string with format: yyyy-mm-dd. - * - * @param attribute name of attribute. - * @param value value to convert. - * @return this model. - */ - public Model setDate(String attribute, Object value) { - return set(attribute, Convert.toSqlDate(value)); - } - - /** - * Performs a conversion to java.sql.Date if necessary, - * uses {@link Convert#toSqlDate(Object)} - * @param attribute attribute name - * @return instance of java.sql.Date - */ - public java.sql.Date getDate(String attribute) { - return Convert.toSqlDate(get(attribute)); - } - - /** - * Performs a primitive conversion of java.util.Date to java.sql.Timestamp - * based on the time value. - * - * - * @param name name of field. - * @param date date value. - * @deprecated use {@link #setTimestamp(String, Object)} instead. - */ - public void setTS(String name, java.util.Date date) { - if(date == null) { - set(name, null); - } else { - set(name, new java.sql.Timestamp(date.getTime())); - } - } - - /** - * Sets values for this model instance. The sequence of values must correspond to sequence of names. - * - * @param attributeNames names of attributes. - * @param values values for this instance. - */ - public void set(String[] attributeNames, Object[] values) { - if (attributeNames == null || values == null || attributeNames.length != values.length) { - throw new IllegalArgumentException("must pass non-null arrays of equal length"); - } - - for (int i = 0; i < attributeNames.length; i++) { - set(attributeNames[i], values[i]); - } - } - - /** - * Sets a value of an attribute. - * - * @param attribute name of attribute to set. Names not related to this model will be rejected (those not matching table columns). - * @param value value of attribute. Feel free to set any type, as long as it can be accepted by your driver. - * @return reference to self, so you can string these methods one after another. - */ - public Model set(String attribute, Object value) { - if(attribute.equalsIgnoreCase("created_at") && manageTime) throw new IllegalArgumentException("cannot set 'created_at'"); - - getMetaModelLocal().checkAttributeOrAssociation(attribute); - - attributes.put(attribute.toLowerCase(), value); - return this; - } - - /** - * Will return true if this instance is frozen, false otherwise. - * A frozen instance cannot use used, as it has no relation to a record in table. - * - * @return true if this instance is frozen, false otherwise. - */ - public boolean isFrozen(){ - return frozen; - } - - - /** - * Returns names of all attributes from this model. - * @return names of all attributes from this model. - */ - public static List attributes(){ - return getMetaModel().getAttributeNames(); - } - - /** - * Returns all associations of this model. - * @return all associations of this model. - */ - public static List associations(){ - return getMetaModel().getAssociations(); - } - - /** - * returns true if this is a new instance, not saved yet to DB, false otherwise. - * - * @return true if this is a new instance, not saved yet to DB, false otherwise - */ - public boolean isNew(){ - return getId() == null; - } - - - /** - * Synonym for {@link #isFrozen()}. if(m.frozen()) seems to read better than classical Java convention. - * - * @return true if this instance is frozen, false otherwise. - */ - public boolean frozen(){ - return isFrozen(); - } - - /** - * Deletes a single table record represented by this instance. This method assumes that a corresponding table - * has only one record whose PK is the ID of this instance. - * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. - * - * @return true if a record was deleted, false if not. - */ - public boolean delete() { - fireBeforeDelete(this); - boolean result; - if( 1 == new DB(getMetaModelLocal().getDbName()).exec("DELETE FROM " + getMetaModelLocal().getTableName() - + " WHERE " + getMetaModelLocal().getIdName() + "= ?", getId())) { - - frozen = true; - if(getMetaModelLocal().cached()){ - QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); - } - purgeEdges(); - result = true; - } - else{ - result = false; - } - fireAfterDelete(this); - return result; - } - - - /** - * Convenience method, will call {@link #delete()} or {@link #deleteCascade()}. - * - * @param cascade true to call {@link #deleteCascade()}, false to call {@link #delete()}. - */ - public void delete(boolean cascade){ - if(cascade){ - deleteCascade(); - }else{ - delete(); - } - } - - /** - * Deletes this record from associated table, as well as children. - * - * Deletes current model and all of its child and many to many associations. This is not a high performance method, as it will - * load every row into a model instance before deleting, effectively calling (N + 1) per table queries to the DB, one to select all - * the associated records (per table), and one delete statement per record. Use it for small data sets. - * - *

- * In cases of simple one to many and polymorphic associations, things are as expected, a parent is deleted an all children are - * deleted as well, but in more complicated cases, this method will walk entire three of associated tables, sometimes - * coming back to the same one where it all started. - * It will follow associations of children and their associations too; consider this a true cascade delete with all implications - * (circular dependencies, referential integrity constraints, potential performance bottlenecks, etc.) - *

- * - * Imagine a situation where you have DOCTORS and PATIENTS in many to many relationship (with DOCTORS_PATIENTS table - * as a join table), and in addition PATIENTS and PRESCRIPTIONS in one to many relationship, where a patient might - * have many prescriptions: - * -

-     DOCTORS
-        +----+------------+-----------+-----------------+
-        | id | first_name | last_name | discipline      |
-        +----+------------+-----------+-----------------+
-        |  1 | John       | Kentor    | otolaryngology  |
-        |  2 | Hellen     | Hunt      | dentistry       |
-        |  3 | John       | Druker    | oncology        |
-        +----+------------+-----------+-----------------+
-
-     PATIENTS
-        +----+------------+-----------+
-        | id | first_name | last_name |
-        +----+------------+-----------+
-        |  1 | Jim        | Cary      |
-        |  2 | John       | Carpenter |
-        |  3 | John       | Doe       |
-        +----+------------+-----------+
-
-     DOCTORS_PATIENTS
-        +----+-----------+------------+
-        | id | doctor_id | patient_id |
-        +----+-----------+------------+
-        |  1 |         1 |          2 |
-        |  2 |         1 |          1 |
-        |  3 |         2 |          1 |
-        |  4 |         3 |          3 |
-        +----+-----------+------------+
-
-     PRESCRIPTIONS
-        +----+------------------------+------------+
-        | id | name                   | patient_id |
-        +----+------------------------+------------+
-        |  1 | Viagra                 |          1 |
-        |  2 | Prozac                 |          1 |
-        |  3 | Valium                 |          2 |
-        |  4 | Marijuana (medicinal)  |          2 |
-        |  5 | CML treatment          |          3 |
-        +----+------------------------+------------+
-     * 
- * - * Lets start with a simple example, Doctor John Druker. This doctor has one patient John Doe, and the patient has one prescription. - * So, when an instance of this doctor model is issued statement: - *
-     *     drDruker.deleteCascade();
-     * 
- * , the result is as expected: the DOCTORS:ID=3 is deleted, DOCTORS_PATIENTS:ID=4 is deleted, PATIENTS:ID=3 is deleted - * and PRESCRIPTIONS:ID=5 is deleted. - * - *

- * However, when doctor Kentor(#1) is deleted, the following records are also deleted: - *

    - *
  • DOCTORS_PATIENTS:ID=1, 2 - these are links to patients
  • - *
  • PATIENTS:ID=1,2 these are patients themselves
  • - *
  • PRESCRIPTIONS:ID=1,2,3,4 - these are prescriptions of patients 1 and 2
  • - *
- * But, in addition, since this is a many to many relationship, deleting patients 1 and 2 results in also deleting - * doctor Hellen Hunt(#2), since she is a doctor of patient Jim Cary(#1), deleting all corresponding join links from - * table DOCTORS_PATIENTS. So, deleting doctor Kentor, deleted most all records from related tables, leaving only these - * records in place: - *
    - *
  • DOCTORS:ID=3
  • - *
  • DOCTORS_PATIENTS:ID=4
  • - *
  • PATIENTS:ID=3
  • - *
  • PRESCRIPTIONS:ID=5
  • - *
- * Had doctor Hellen Hunt(#2) had more patients, it would delete them too, and so on. This goes a long way to say that it - * could be easy to be tangled up in web of associations, so be careful out there. - * - *

- * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. - */ - public void deleteCascade(){ - deleteCascadeExcept(); - } - - /** - * This method does everything {@link #deleteCascade()} does, but in addition allows to exclude some assosiations - * from this action. This is necessary because {@link #deleteCascade()} method can be far too eager to delete - * records in a database, and this is a good way to tell the model to exclude some associations from deletes. - * - *

Example:

- * - * Patient.findById(3).deleteCascadeExcept(Patient.getMetaModel().getAssociationForTarget("prescriptions")); - * - * - * @see {@link #deleteCascade()} - see for more information. - * @param excludedAssociations associations - */ - public void deleteCascadeExcept(Association ... excludedAssociations){ - List excludedAssociationsList = Arrays.asList(excludedAssociations); - deleteMany2ManyDeep(getMetaModelLocal().getManyToManyAssociations(excludedAssociationsList)); - deleteChildrenDeep(getMetaModelLocal().getOneToManyAssociations(excludedAssociationsList)); - deleteChildrenDeep(getMetaModelLocal().getPolymorphicAssociations(excludedAssociationsList)); - delete(); - } - - - - private void deleteMany2ManyDeep(List many2ManyAssociations){ - List allMany2ManyChildren = new ArrayList(); - for (Association association : many2ManyAssociations) { - String targetTableName = association.getTarget(); - Class c = Registry.instance().getModelClass(targetTableName, false); - if(c == null){// this model is probably not defined as a class, but the table exists! - logger.error("ActiveJDBC WARNING: failed to find a model class for: " + targetTableName + ", maybe model is not defined for this table?" + - " There might be a risk of running into integrity constrain violation if this model is not defined."); - } - else{ - allMany2ManyChildren.addAll(getAll(c)); - } - } - - deleteJoinsForManyToMany(); - for (Model model : allMany2ManyChildren) { - model.deleteCascade(); - } - } - - /** - * Deletes this record from associated table, as well as its immediate children. This is a high performance method - * because it does not walk through a chain of child dependencies like {@link #deleteCascade()} does, but rather issues - * one DELETE statement per child dependency table. Also, its semantics are a bit different between than {@link #deleteCascade()}. - * It only deletes current record and immediate children, but not their children (no grand kinds are dead as a result :)). - *

One to many and polymorphic associations

- * The current record is deleted, as well as immediate children. - *

Many to many associations

- * The current record is deleted, as well as links in a join table. Nothing else is deleted. - *

- * After deletion, this instance becomes {@link #frozen()} and cannot be used anymore until {@link #thaw()} is called. - */ - public void deleteCascadeShallow(){ - deleteJoinsForManyToMany(); - deleteOne2ManyChildrenShallow(); - deletePolymorphicChildrenShallow(); - delete(); - } - - - private void deleteJoinsForManyToMany() { - List associations = getMetaModelLocal().getManyToManyAssociations(Collections.emptyList()); - for (Association association : associations) { - String join = ((Many2ManyAssociation)association).getJoin(); - String sourceFK = ((Many2ManyAssociation)association).getSourceFkName(); - String query = "DELETE FROM " + join + " WHERE " + sourceFK + " = " + getId(); - new DB(getMetaModelLocal().getDbName()).exec(query); - } - } - - private void deleteOne2ManyChildrenShallow() { - List childAssociations = getMetaModelLocal().getOneToManyAssociations(Collections.emptyList()); - for (OneToManyAssociation association : childAssociations) { - String target = association.getTarget(); - String query = "DELETE FROM " + target + " WHERE " + association.getFkName() + " = ?"; - new DB(getMetaModelLocal().getDbName()).exec(query, getId()); - } - } - - private void deletePolymorphicChildrenShallow() { - List polymorphics = getMetaModelLocal().getPolymorphicAssociations(new ArrayList()); - for (OneToManyPolymorphicAssociation association : polymorphics) { - String target = association.getTarget(); - String parentType = association.getTypeLabel(); - String query = "DELETE FROM " + target + " WHERE parent_id = ? AND parent_type = ?"; - new DB(getMetaModelLocal().getDbName()).exec(query, getId(), parentType); - } - } - - - private void deleteChildrenDeep(List childAssociations){ - for (Association association : childAssociations) { - String targetTableName = association.getTarget(); - Class c = Registry.instance().getModelClass(targetTableName, false); - if(c == null){// this model is probably not defined as a class, but the table exists! - logger.error("ActiveJDBC WARNING: failed to find a model class for: " + targetTableName + ", maybe model is not defined for this table?" + - " There might be a risk of running into integrity constrain violation if this model is not defined."); - } - else{ - List dependencies = getAll(c); - for (Model model : dependencies) { - model.deleteCascade(); - } - } - } - } - - /** - * Deletes some records from associated table. This method does not follow any associations. - * If this model has one to many associations, you might end up with either orphan records in child - * tables, or run into integrity constraint violations. However, this method if very efficient as it deletes all records - * in one shot, without pre-loading them. - * This method also has a side-effect: it will not mark loaded instances corresponding to deleted records as "frozen". - * This means that such an instance would allow calling save() and saveIt() methods resulting DB errors, as you - * would be attempting to update phantom records. - * - * - * @param query narrows which records to delete. Example:

"last_name like '%sen%'"
. - * @param params (optional) - list of parameters if a query is parametrized. - * @return number od deleted records. - */ - public static int delete(String query, Object... params) { - MetaModel metaModel = getMetaModel(); - int count = params == null || params.length == 0? new DB(metaModel.getDbName()).exec("DELETE FROM " + metaModel.getTableName() + " WHERE " + query) : - new DB(metaModel.getDbName()).exec("DELETE FROM " + metaModel.getTableName() + " WHERE " + query, params); - if(metaModel.cached()){ - QueryCache.instance().purgeTableCache(metaModel.getTableName()); - } - purgeEdges(); - return count; - } - - /** - * Returns true if record corresponding to the id passed exists in the DB. - * - * @param id id in question. - * @return true if corresponding record exists in DB, false if it does not. - */ - public static boolean exists(Object id){ - MetaModel metaModel = getMetaModel(); - return null != new DB(metaModel.getDbName()).firstCell("SELECT " + metaModel.getIdName() + " FROM " + metaModel.getTableName() - + " WHERE " + metaModel.getIdName() + " = ?", id); - } - - /** - * Returns true if record corresponding to the id of this instance exists in the DB. - * - * @return true if corresponding record exists in DB, false if it does not. - */ - public boolean exists(){ - MetaModel metaModel = getMetaModelLocal(); - return null != new DB(metaModel.getDbName()).firstCell("SELECT " + metaModel.getIdName() + " FROM " + metaModel.getTableName() - + " WHERE " + metaModel.getIdName() + " = ?", getId()); - } - - /** - * Deletes all records from associated table. This methods does not take associations into account. - * - * @return number of records deleted. - */ - public static int deleteAll() { - MetaModel metaModel = getMetaModel(); - int count = new DB(metaModel.getDbName()).exec("DELETE FROM " + metaModel.getTableName()); - if(metaModel.cached()){ - QueryCache.instance().purgeTableCache(metaModel.getTableName()); - } - - purgeEdges(); - return count; - } - - /** - * Updates records associated with this model. - * - * This example : - *
-     *  Employee.update("bonus = ?", "years_at_company > ?", "5", "10");
-     * 
null, all records in table will be updated. - * In such cases, use a more explicit {@link #updateAll(String, Object...)} method. - * @param params list of parameters for both updates and conditions. Applied in the same order as in the arguments, - * updates first, then conditions. - * @return number of updated records. - */ - public static int update(String updates, String conditions, Object ... params) { - //TODO: validate that the number of question marks is the same as number of parameters - return ModelDelegate.update(Model.getMetaModel(), updates, conditions, params); - } - - - /** - * Updates all records associated with this model. - * - * This example : - *
-     *  Employee.updateAll("bonus = ?", "10");
-     * 
- * If {@link LazyList#include(Class[])} method was used, and this - * model belongs to a parent (as in many to one relationship), then the parent - * will be eagerly loaded and also converted to a map. Parents' maps are keyed in the - * returned map by underscored name of a parent model class name. - *

- * For example, if this model were Address - * and a parent is User (and user has many addresses), then the resulting map would - * have all the attributes of the current table and another map representing a parent user with a - * key "user" in current map. - * - * @return all values of the model with all attribute names converted to lower case. - */ - public Map toMap(){ - Map retVal = new HashMap(); - for (String key : attributes.keySet()) { - if(attributes.get(key) == null) - continue; - - if(attributes.get(key) instanceof Clob){ - retVal.put(key.toLowerCase(), getString(key)); - }else{ - retVal.put(key.toLowerCase(), attributes.get(key)); - } - } - for(Class parentClass: cachedParents.keySet()){ - retVal.put(underscore(shortName(parentClass.getName())), cachedParents.get(parentClass).toMap()); - } - - for(Class childClass: cachedChildren.keySet()){ - List children = cachedChildren.get(childClass); - - List childMaps = new ArrayList(children.size()); - for(Model child:children){ - childMaps.add(child.toMap()); - } - retVal.put(pluralize(underscore(shortName(childClass.getName()))), childMaps); - } - return retVal; - } - - @Override - public String toString() { - - StringBuilder sb = new StringBuilder(); - sb.append("Model: ").append(getClass().getName()) - .append(", table: '").append(getMetaModelLocal().getTableName()) - .append("', attributes: ").append(attributes); - - if (cachedParents.size() > 0) { - sb.append(", parents: ").append(cachedParents); - } - - if (cachedChildren.size() > 0) { - sb.append(", children: ").append(cachedChildren); - } - return sb.toString(); - } - - - /** - * Parses XML into a model. It expects the same structure of XML as the method {@link #toXml(int, boolean, String...)}. - * It ignores children and dependencies (for now) if any. This method will parse the model attributes - * from the XML document, and will then call {@link #fromMap(java.util.Map)} method. It does not save data into a database, just sets the - * attributes. - * - * @param xml xml to read model attributes from. - */ - public void fromXml(String xml) { - - try{ - //such dumb API! - Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes())); - String topTag = Inflector.underscore(getClass().getSimpleName()); - Element root = document.getDocumentElement(); - - if(!root.getTagName().equals(topTag)){ - throw new InitException("top node has to match model name: " + topTag); - } - NodeList childNodes = root.getChildNodes(); - - Map attributes = new HashMap(); - for(int i = 0; i < childNodes.getLength();i++){ - Node node = childNodes.item(i); - if(node instanceof Element){ - Element child = (Element) node; - attributes.put(child.getTagName(), child.getFirstChild().getNodeValue());//this is even dumber! - } - } - fromMap(attributes); - }catch(Exception e){ - throw new InitException(e); - } - } - - /** - * Generates a XML document from content of this model. - * - * @param spaces by how many spaces to indent. - * @param declaration tru to include XML declaration at the top - * @param attrs list of attributes to include. No arguments == include all attributes. - * @return generated XML. - */ - public String toXml(int spaces, boolean declaration, String ... attrs){ - - Map modelMap = toMap(); - - String indent = ""; - for(int i = 0; i < spaces; i++) - indent += " "; - - List attrList = Arrays.asList(attrs); - - StringWriter sw = new StringWriter(); - - if(declaration) sw.write("" + (spaces > 0?"\n":"")); - - String topTag = Inflector.underscore(getClass().getSimpleName()); - - sw.write(indent + "<" + topTag + ">" + (spaces > 0?"\n":"")); - - for(String name: modelMap.keySet()){ - Object value = modelMap.get(name); - if((attrList.contains(name) || attrs.length == 0) && !(value instanceof List)){ - sw.write(indent + indent + "<" + name + ">" + XmlEntities.XML.escape(value.toString()) + "" + (spaces > 0?"\n":"")); - }else if (value instanceof List){ - List children = (List)value; - sw.write(indent + indent + "<" + name + ">" + (spaces > 0?"\n":"")); - for(Map child: children){ - sw.write(indent + indent + indent + "<" + Inflector.singularize(name) + ">" + (spaces > 0?"\n":"")); - for(Object childKey: child.keySet()){ - sw.write(indent + indent + indent + indent + "<" + childKey + ">" + XmlEntities.XML.escape(child.get(childKey).toString())+ "" + (spaces > 0?"\n":"")); - } - sw.write(indent + indent + indent + "" + (spaces > 0?"\n":"")); - } - sw.write(indent + indent + "" + (spaces > 0?"\n":"")); - } - } - beforeClosingTag(spaces, sw, attrs); - sw.write(indent + "" + (spaces > 0?"\n":"")); - return sw.toString(); - } - - /** - * Override in a subclass to inject custom content onto XML just before the closing tag. - * - * @param spaces number of spaces of indent - * @param writer to write content to. - */ - public void beforeClosingTag(int spaces, StringWriter writer, String ... attrs) { - //do nothing. - } - - - /** - * Generates a JSON document from content of this model. - * - * @param pretty pretty format (human readable), or one line text. - * @param attrs list of attributes to include. No arguments == include all attributes. - * @return generated JSON. - */ - public String toJson(boolean pretty, String... attrs) { - return toJsonP(pretty, "", attrs); - } - - private static DateFormat isoDateFormater; - static { - - //2013-05-28T14:03:17.956+0300 - isoDateFormater = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); -// isoDateFormater.setTimeZone(TimeZone.getTimeZone("UTC")); - } - protected String toJsonP(boolean pretty, String indent, String... attrs) { - Collection attrList = Arrays.asList(attrs); - - StringWriter sw = new StringWriter(); - sw.write(indent + "{" + (pretty ? "" + indent : "")); - - List attributeStrings = new ArrayList(); - - if (attrList.size() == 0) { - attrList = attributes.keySet(); - } - - for (String name : attrList) { - Object v = get(name); - String val = null; - if (v == null) { - val = "null"; - } else if (v instanceof Number || v instanceof Boolean) { - val = v.toString(); - } else if (v instanceof Date) { - val = "\"" + isoDateFormater.format((Date) v) + "\""; - } else { - val = "\"" + v.toString() - .replaceAll("\\\\", "\\\\\\\\") // \ - .replaceAll("\"", "\\\\\"") // " - .replaceAll("/", "\\\\/") // / - .replaceAll("\b", "\\\\b") // \b - .replaceAll("\f", "\\\\f") // \f - .replaceAll("\n", "\\\\n") // \n - .replaceAll("\r", "\\\\r") // \r - .replaceAll("\t", "\\\\t") // \t - + "\""; - } - attributeStrings.add((pretty ? "\n " + indent : "") + "\"" + name + "\":" + val); - } - - sw.write(Util.join(attributeStrings, ",")); - - if (cachedChildren != null && cachedChildren.size() > 0) { - - sw.write("," + (pretty ? "\n " + indent : "") + "\"children\" : {"); - - List childClasses = new ArrayList(); - childClasses.addAll(cachedChildren.keySet()); - - for (int i = 0; i < childClasses.size(); i++) { - Class childClass = childClasses.get(i); - String name = Inflector.pluralize(childClass.getSimpleName()).toLowerCase(); - sw.write((pretty ? "\n" + indent + " " : "") + "\"" + name + "\" : ["); - List childrenList = new ArrayList(); - for (Model child : cachedChildren.get(childClass)) { - childrenList.add((pretty ? "\n" + indent : "") + child.toJsonP(pretty, (pretty ? indent + " " : ""))); - } - sw.write(Util.join(childrenList, ",")); - sw.write((pretty ? "\n" + indent + indent : "") + "]"); - - if(i < (childClasses.size() - 1)){ - sw.write(","); - } - } - sw.write((pretty ? "\n" + indent + indent : "") + "}"); - } - - beforeClosingBrace(pretty, pretty ? " " + indent : "", sw); - sw.write((pretty ? "\n" + indent : "") + "}"); - return sw.toString(); - } - - /** - * Override in subclasses in order to inject custom content into Json just before the closing brace. - * - * @param indent indent at current level - * @param writer writer to write custom content to - */ - public void beforeClosingBrace(boolean pretty, String indent, StringWriter writer){ - - } - - - /** - * Returns parent of this model, assuming that this table represents a child. - * This method may return null in cases when you have orphan record and - * referential integrity is not enforced in DBMS with a foreign key constraint. - * - * @param parentClass class of a parent model. - * @return instance of a parent of this instance in the "belongs to" relationship. - */ - public T parent(Class parentClass) { - return parent(parentClass, false); - } - - public T parent(Class parentClass, boolean cache) { - T cachedParent = parentClass.cast(cachedParents.get(parentClass)); - if (cachedParent != null) { - return cachedParent; - } - MetaModel parentMM = Registry.instance().getMetaModel(parentClass); - String parentTable = parentMM.getTableName(); - - BelongsToAssociation ass = (BelongsToAssociation)getMetaModelLocal().getAssociationForTarget(parentTable, BelongsToAssociation.class); - BelongsToPolymorphicAssociation assP = (BelongsToPolymorphicAssociation)getMetaModelLocal() - .getAssociationForTarget(parentTable, BelongsToPolymorphicAssociation.class); - - String fkValue; - String fkName; - if (ass != null) { - fkValue = getString(ass.getFkName()); - fkName = ass.getFkName(); - } else if (assP != null) { - fkValue = getString("parent_id"); - fkName = "parent_id"; - - if (!assP.getTypeLabel().equals(getString("parent_type"))) { - throw new IllegalArgumentException("Wrong parent: '" + parentClass + "'. Actual parent type label of this record is: '" + getString("parent_type") + "'"); - } - } else { - throw new IllegalArgumentException("there is no association with table: " + parentTable); - } - - if (fkValue == null) { - logger.debug("Attribute: " + fkName + " is null, cannot determine parent. Child record: " + this); - return null; - } - String parentIdName = parentMM.getIdName(); - String query = getMetaModelLocal().getDialect().selectStarParametrized(parentTable, parentIdName); - - T parent; - if (parentMM.cached()) { - parent = parentClass.cast(QueryCache.instance().getItem(parentTable, query, new Object[]{fkValue})); - if (parent != null) { - return parent; - } - } - - List results = new DB(getMetaModelLocal().getDbName()).findAll(query, fkValue); - //expect only one result here - if (results.size() == 0) { //this should be covered by referential integrity constraint - return null; - } else { - try { - parent = parentClass.newInstance(); - parent.hydrate(results.get(0)); - if (parentMM.cached()) { - QueryCache.instance().addItem(parentTable, query, new Object[]{fkValue}, parent); - } - if (cache) { - setCachedParent(parent); - } - return parent; - } catch (Exception e) { - throw new InitException(e.getMessage(), e); - } - } - } - - protected void setCachedParent(Model parent) { - if (parent != null) { - cachedParents.put(parent.getClass(), parent); - } - } - - - /** - * Sets multiple parents on this instance. Basically this sets a correct value of a foreign keys in a - * parent/child relationship. This only works for one to many and polymorphic associations. - * - * @param parents - collection of potential parents of this instance. Its ID values must not be null. - */ - public void setParents(Model... parents){ - for (Model parent : parents) { - setParent(parent); - } - } - - - /** - * Sets a parent on this instance. Basically this sets a correct value of a foreign key in a - * parent/child relationship. This only works for one to many and polymorphic associations. - * The act of setting a parent does not result in saving to a database. - * - * @param parent potential parent of this instance. Its ID value must not be null. - */ - public void setParent(Model parent) { - if (parent == null || parent.getId() == null) { - throw new IllegalArgumentException("parent cannot ne null and parent ID cannot be null"); - } - List associations = getMetaModelLocal().getAssociations(); - for (Association association : associations) { - if (association instanceof BelongsToAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())) { - set(((BelongsToAssociation)association).getFkName(), parent.getId()); - return; - } - if(association instanceof BelongsToPolymorphicAssociation && association.getTarget().equals(parent.getMetaModelLocal().getTableName())){ - set("parent_id", parent.getId()); - set("parent_type", ((BelongsToPolymorphicAssociation)association).getTypeLabel()); - return; - } - } - throw new IllegalArgumentException("Class: " + parent.getClass() + " is not associated with " + this.getClass() - + ", list of existing associations: \n" + Util.join(getMetaModelLocal().getAssociations(), "\n")); - } - - /** - * Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other. - * - * @param other target model. - */ - public void copyTo(T other) { - if (!getMetaModelLocal().getTableName().equals(other.getMetaModelLocal().getTableName())) { - throw new IllegalArgumentException("can only copy between the same types"); - } - - List attrs = getMetaModelLocal().getAttributeNamesSkip(getMetaModelLocal().getIdName()); - for (String name : attrs) { - other.getAttributes().put(name, get(name)); - } - } - - /** - * Copies all attribute values (except for ID, created_at and updated_at) from this instance to the other. - * - * @param other target model. - */ - public void copyFrom(Model other) { - other.copyTo(this); - } - - /** - * This method should be called from all instance methods for performance. - * - * @return - */ - protected MetaModel getMetaModelLocal(){ - if(metaModelLocal == null) - metaModelLocal = getMetaModel(); - - return metaModelLocal; - } - - - protected void setMetamodelLocal(MetaModel metamodelLocal){ - this.metaModelLocal = metamodelLocal; - } - - /** - * Re-reads all attribute values from DB. - * - */ - public void refresh() { - Model fresh = findById(getId()); - - if(fresh == null) - throw new StaleModelException("Failed to refresh self because probably record with " + - "this ID does not exist anymore. Stale model: " + this); - - fresh.copyTo(this); - } - - /** - * Returns a value for attribute. - * - *

Infer relationship from name of argument

- * Besides returning direct attributes of this model, this method is also - * aware of relationships and can return collections based on naming conventions. For example, if a model User has a - * one to many relationship with a model Address, then the following code will work: - *
-     * Address address = ...;
-     * User user = (User)address.get("user");
-     * 
- * Conversely, this will also work: - *
-     * List<Address> addresses = (List<Address>)user.get("addresses");
-     * 
- * - * The same would also work for many to many relationships: - *
-     * List<Doctor> doctors = (List<Doctor>)patient.get("doctors");
-     * ...
-     * List<Patient> patients = (List<Patient>)doctor.get("patients");
-     * 
- * - * This methods will try to infer a name if a table by using {@link org.javalite.common.Inflector} to try to - * convert it to singular and them plural form, an attempting to see if this model has an appropriate relationship - * with another model, if one is found. This method of finding of relationships is best used in templating - * technologies, such as JSPs. For standard cases, please use {@link #parent(Class)}, and {@link #getAll(Class)}. - * - *

Suppressing inference for performance

- *

- * In some cases, the inference of relationships might take a toll on performance, and if a project is not using - * the getter method for inference, than it is wise to turn it off with a system property activejdbc.get.inference: - * - *

-     *         -Dactivejdbc.get.inference = false
-     *     
- * If inference is turned off, only a value of the attribute is returned. - * - *

- * - * @param attribute name of attribute of name or related object. - * @return value for attribute. - */ - public Object get(String attribute) { - if(frozen) throw new FrozenException(this); - - if(attribute == null) throw new IllegalArgumentException("attribute cannot be null"); - - // NOTE: this is a workaround for JSP pages. JSTL in cases ${item.id} does not call the getId() method, instead - //calls item.get("id"), considering that this is a map only! - if(!attributes.containsKey("id") && attribute.equalsIgnoreCase("id")){ - String idName = getMetaModelLocal().getIdName(); - return attributes.get(idName.toLowerCase()); - } - - Object returnValue; - String attributeName = attribute.toLowerCase(); - - String getInferenceProperty = System.getProperty("activejdbc.get.inference"); - - boolean getInference = getInferenceProperty == null || getInferenceProperty.equals("true"); - - if (getInference) { - if ((getMetaModelLocal().hasAttribute(attributeName))) { - return attributes.get(attributeName);//this should account for nulls too! - } else if ((returnValue = tryParent(attributeName)) != null) { - return returnValue; - } else if ((returnValue = tryPolymorphicParent(attributeName)) != null) { - return returnValue; - } else if ((returnValue = tryChildren(attributeName)) != null) { - return returnValue; - } else if ((returnValue = tryPolymorphicChildren(attributeName)) != null) { - return returnValue; - } else if ((returnValue = tryOther(attributeName)) != null) { - return returnValue; - } else { - getMetaModelLocal().checkAttributeOrAssociation(attributeName); - return null; - } - } else { - return attributes.get(attributeName); - } - } - - - private Object tryPolymorphicParent(String parentTable){ - MetaModel parentMM = inferTargetMetaModel(parentTable); - if(parentMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToPolymorphicAssociation.class) ? - parent(parentMM.getModelClass()): null; - } - - private Object tryParent(String parentTable){ - MetaModel parentMM = inferTargetMetaModel(parentTable); - if(parentMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(parentMM.getTableName(), BelongsToAssociation.class) ? - parent(parentMM.getModelClass()): null; - } - - private Object tryPolymorphicChildren(String childTable){ - MetaModel childMM = inferTargetMetaModel(childTable); - if(childMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyPolymorphicAssociation.class) ? - getAll(childMM.getModelClass()): null; - } - - private Object tryChildren(String childTable){ - MetaModel childMM = inferTargetMetaModel(childTable); - if(childMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(childMM.getTableName(), OneToManyAssociation.class) ? - getAll(childMM.getModelClass()): null; - } - - private Object tryOther(String otherTable){ - MetaModel otherMM = inferTargetMetaModel(otherTable); - if(otherMM == null){ - return null; - }else - return getMetaModelLocal().hasAssociation(otherMM.getTableName(), Many2ManyAssociation.class) ? - getAll(otherMM.getModelClass()): null; - } - - private MetaModel inferTargetMetaModel(String targetTableName){ - String targetTable = singularize(targetTableName); - MetaModel targetMM = Registry.instance().getMetaModel(targetTable); - if(targetMM == null){ - targetTable = pluralize(targetTableName); - targetMM = Registry.instance().getMetaModel(targetTable); - } - return targetMM != null? targetMM: null; - } - - /*************************** typed getters *****************************************/ - /** - * Get any value as string. - * - * @param attribute name of attribute. - * @return attribute value as string. - */ - public String getString(String attribute) { - Object value = get(attribute); - return Convert.toString(value); - } - - /** - * Gets a value as bytes. If the column is Blob, bytes are - * read directly, if not, then the value is converted to String first, then - * string bytes are returned. Be careful out there, this will read entire - * Blob onto memory. - * - * @param attribute name of attribute - * @return value as bytes. - */ - public byte[] getBytes(String attribute) { - Object value = get(attribute); - return Convert.toBytes(value); - } - - /** - * Converts Model value to BigDecimal - * - * @see {@link Convert#toBigDecimal} - * @param attribute name of attribute to convert - * @return converted value - */ - public BigDecimal getBigDecimal(String attribute) { - return Convert.toBigDecimal(get(attribute)); - } - - /** - * Converts Model value to Integer - * - * @see {@link Convert#toInteger} - * @param attribute name of attribute to convert - * @return converted value - */ - public Integer getInteger(String attribute) { - return Convert.toInteger(get(attribute)); - } - - /** - * Converts Model value to Long - * - * @see {@link Convert#toLong(Object)} - * @param attribute name of attribute to convert - * @return converted value - */ - public Long getLong(String attribute) { - return Convert.toLong(get(attribute)); - } - - /** - * Converts Model value to Short - * - * @see {@link Convert#toShort(Object)} - * @param attribute name of attribute to convert - * @return converted value - */ - public Short getShort(String attribute) { - return Convert.toShort(get(attribute)); - } - - /** - * Converts Model value to Float - * - * @see {@link Convert#toFloat(Object)} - * @param attribute name of attribute to convert - * @return converted value - */ - public Float getFloat(String attribute) { - return Convert.toFloat(get(attribute)); - } - - /** - * If the value is instance of java.sql.Timestamp, returns it, else tries to convert the - * value to Timestamp using {@link Timestamp#valueOf(String)}. - * This method might trow IllegalArgumentException if fails at conversion. - * - * @see {@link Timestamp#valueOf(String)} - * @param attribute attribute name - * @return instance of Timestamp. - */ - public Timestamp getTimestamp(String attribute) { - return Convert.toTimestamp(get(attribute)); - } - - /** - * Converts Model value to Double - * - * @see {@link Convert#toDouble(Object)} - * @param attribute name of attribute to convert - * @return converted value - */ - public Double getDouble(String attribute) { - return Convert.toDouble(get(attribute)); - } - - - /** - * Returns true if the value is any numeric type and has a value of 1, or - * if string type has a value of 'y', 't', 'true' or 'yes'. Otherwise, return false. - * - * @param attribute attribute name - * @return true if the value is any numeric type and has a value of 1, or - * if string type has a value of 'y', 't', 'true' or 'yes'. Otherwise, return false. - */ - public Boolean getBoolean(String attribute) { - return Convert.toBoolean(get(attribute)); - } - - /*************************** typed setters *****************************************/ - - /** - * Converts object to string when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setString(String attribute, Object value) { - return set(attribute, value.toString()); - - } - - /** - * Converts object to BigDecimal when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setBigDecimal(String attribute, Object value) { - return set(attribute, Convert.toBigDecimal(value)); - } - - /** - * Converts object to Integer when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setInteger(String attribute, Object value) { - return set(attribute, Convert.toInteger(value)); - } - - /** - * Converts object to Long when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setLong(String attribute, Object value) { - return set(attribute, Convert.toLong(value)); - } - - /** - * Converts object to Float when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setFloat(String attribute, Object value) { - return set(attribute, Convert.toFloat(value)); - } - - /** - * - * Converts object to java.sql.Timestamp when setting. - * If the value is instance of java.sql.Timestamp, just sets it, else tries to convert the value to Timestamp using - * Timestamp.valueOf(String). This method might trow IllegalArgumentException if fails at conversion. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setTimestamp(String attribute, Object value) { - return set(attribute, Convert.toTimestamp(value)); - } - - /** - * Converts object to Double when setting. - * - * @param attribute name of attribute. - * @param value value - * @return reference to this model. - */ - public Model setDouble(String attribute, Object value) { - return set(attribute, Convert.toDouble(value)); - } - - - - /** - * Sets to true if the value is any numeric type and has a value of 1, or if string type has a - * value of 'y', 't', 'true' or 'yes'. Otherwise, sets to false. - * - * @param attribute name of attribute. - * @param value value to convert. - * @return this model. - */ - public Model setBoolean(String attribute, Object value) { - return set(attribute, Convert.toBoolean(value)); - } - - /** - * This methods supports one to many, many to many relationships as well as polymorphic associations. - *

- * In case of one to many, the clazz must be a class of a child model, and it will return a - * collection of all children. - *

- * In case of many to many, the clazz must be a class of a another related model, and it will return a - * collection of all related models. - *

- * In case of polymorphic, the clazz must be a class of a polymorphically related model, and it will return a - * collection of all related models. - * - * - * @param clazz class of a child model for one to many, or class of another model, in case of many to many or class of child in case of - * polymorphic - * - * @return list of children in case of one to many, or list of other models, in case many to many. - */ - - public LazyList getAll(Class clazz) { - List children = cachedChildren.get(clazz); - if(children != null){ - return (LazyList) children; - } - - String tableName = Registry.instance().getTableName(clazz); - if(tableName == null) throw new IllegalArgumentException("table: " + tableName + " does not exist for model: " + clazz); - - return get(tableName, null); - } - - - /** - * Provides a list of child models in one to many, many to many and polymorphic associations, but in addition also allows to filter this list - * by criteria. - * - *

- * 1. For one to many, the criteria is against the child table. - * - *

- * 2. For polymorphic association, the criteria is against the child table. - * - *

- * 3. For many to many, the criteria is against the join table. - * For example, if you have table PROJECTS, ASSIGNMENTS and PROGRAMMERS, where a project has many programmers and a programmer - * has many projects, and ASSIGNMENTS is a join table, you can write code like this, assuming that the ASSIGNMENTS table - * has a column duration_weeks: - * - *

-     * List threeWeekProjects = programmer.get(Project.class, "duration_weeks = ?", 3);
-     * 
- * where this list will contain all projects to which this programmer is assigned for 3 weeks. - * - * @param clazz related type - * @param query sub-query for join table. - * @param params parameters for a sub-query - * @return list of relations in many to many - */ - public LazyList get(Class clazz, String query, Object ... params){ - return get(Registry.instance().getTableName(clazz), query, params); - } - - private LazyList get(String targetTable, String criteria, Object ...params) { - //TODO: interesting thought: is it possible to have two associations of the same name, one to many and many to many? For now, say no. - - OneToManyAssociation oneToManyAssociation = (OneToManyAssociation)getMetaModelLocal().getAssociationForTarget(targetTable, OneToManyAssociation.class); - Many2ManyAssociation manyToManyAssociation = (Many2ManyAssociation)getMetaModelLocal().getAssociationForTarget(targetTable, Many2ManyAssociation.class); - - OneToManyPolymorphicAssociation oneToManyPolymorphicAssociation = (OneToManyPolymorphicAssociation)getMetaModelLocal().getAssociationForTarget(targetTable, OneToManyPolymorphicAssociation.class); - - String additionalCriteria = criteria != null? " AND ( " + criteria + " ) " : ""; - String subQuery; - if (oneToManyAssociation != null) { - subQuery = oneToManyAssociation.getFkName() + " = ? " + additionalCriteria; - } else if (manyToManyAssociation != null) { - String targetId = Registry.instance().getMetaModel(targetTable).getIdName(); - String joinTable = manyToManyAssociation.getJoin(); - - String query = "SELECT " + targetTable + ".* FROM " + targetTable + ", " + joinTable + - " WHERE " + targetTable + "." + targetId + " = " + joinTable + "." + manyToManyAssociation.getTargetFkName() + - " AND " + joinTable + "." + manyToManyAssociation.getSourceFkName() + " = ? " + additionalCriteria; - - Object[] allParams = new Object[params.length + 1]; - allParams[0] = getId(); - for (int i = 0; i < params.length; i++) { - allParams[i + 1] = params[i]; - } - return new LazyList(true, Registry.instance().getMetaModel(targetTable), query, allParams); - } else if (oneToManyPolymorphicAssociation != null) { - subQuery = "parent_id = ? AND " + " parent_type = '" + oneToManyPolymorphicAssociation.getTypeLabel() + "'" + additionalCriteria; - } else { - throw new NotAssociatedException(getMetaModelLocal().getTableName(), targetTable); - } - - Object[] allParams = new Object[params.length + 1]; - allParams[0] = getId(); - for (int i = 0; i < params.length; i++) { - allParams[i + 1] = params[i]; - } - return new LazyList(subQuery, Registry.instance().getMetaModel(targetTable), allParams); - } - - protected static NumericValidationBuilder validateNumericalityOf(String... attributes) { - return ValidationHelper.addNumericalityValidators(getClassName(), ModelDelegate.toLowerCase(attributes)); - } - - /** - * Adds a validator to the model. - * - * @param validator new validator. - * @return - */ - public static ValidationBuilder addValidator(Validator validator){ - return ValidationHelper.addValidator(getClassName(), validator); - } - - /** - * Adds a new error to the collection of errors. This is a convenience method to be used from custom validators. - * - * @param key - key wy which this error can be retrieved from a collection of errors: {@link #errors()}. - * @param value - this is a key of the message in the resource bundle. - * @see {@link Messages}. - */ - public void addError(String key, String value){ - errors.put(key, value); - } - - public static void removeValidator(Validator validator){ - Registry.instance().removeValidator(Model.getDaClass(), validator); - } - - public static List getValidators(Class daClass){ - return Registry.instance().getValidators(daClass.getName()); - } - - - /** - * Validates an attribite format with a ree hand regular expression. - * - * @param attribute attribute to validate. - * @param pattern regexp pattern which must match the value. - * @return - */ - protected static ValidationBuilder validateRegexpOf(String attribute, String pattern) { - return ValidationHelper.addRegexpValidator(getClassName(), attribute.toLowerCase(), pattern); - } - - /** - * Validates email format. - * - * @param attribute name of atribute that holds email value. - * @return - */ - protected static ValidationBuilder validateEmailOf(String attribute) { - return ValidationHelper.addEmailValidator(getClassName(), attribute.toLowerCase()); - } - - /** - * Validates range. Accepted types are all java.lang.Number subclasses: - * Byte, Short, Integer, Long, Float, Double BigDecimal. - * - * @param attribute attribute to validate - should be within range. - * @param min min value of range. - * @param max max value of range. - * @return - */ - protected static ValidationBuilder validateRange(String attribute, Number min, Number max) { - return ValidationHelper.addRangeValidator(getClassName(), attribute.toLowerCase(), min, max); - } - - /** - * The validation will not pass if the value is either an empty string "", or null. - * - * @param attributes list of attributes to validate. - * @return - */ - protected static ValidationBuilder validatePresenceOf(String... attributes) { - return ValidationHelper.addPresenceValidators(getClassName(), ModelDelegate.toLowerCase(attributes)); - } - - /** - * Add a custom validator to the model. - * - * @param validator custom validator. - */ - protected static ValidationBuilder validateWith(Validator validator) { - return addValidator(validator); - } - - /** - * Adds a custom converter to the model. - * - * @param converter custom converter - */ - protected static ValidationBuilder convertWith(Converter converter) { - return addValidator(converter); - } - - /** - * Converts a named attribute to java.sql.Date if possible. - * Acts as a validator if cannot make a conversion. - * - * @param attributeName name of attribute to convert to java.sql.Date. - * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} - * @return message passing for custom validation message. - */ - protected static ValidationBuilder convertDate(String attributeName, String format){ - return ValidationHelper.addDateConverter(getClassName(), attributeName, format); - } - - /** - * Converts a named attribute to java.sql.Timestamp if possible. - * Acts as a validator if cannot make a conversion. - * - * @param attributeName name of attribute to convert to java.sql.Timestamp. - * @param format format for conversion. Refer to {@link java.text.SimpleDateFormat} - * @return message passing for custom validation message. - */ - protected static ValidationBuilder convertTimestamp(String attributeName, String format){ - return ValidationHelper.addTimestampConverter(getClassName(), attributeName, format); - } - - public static boolean belongsTo(Class targetClass) { - String targetTable = Registry.instance().getTableName(targetClass); - MetaModel metaModel = getMetaModel(); - return (null != metaModel.getAssociationForTarget(targetTable, BelongsToAssociation.class) || - null != metaModel.getAssociationForTarget(targetTable, Many2ManyAssociation.class)); - } - - - public static void addCallbacks(CallbackListener ... listeners){ - for(CallbackListener listener: listeners ){ - Registry.instance().addListener(getDaClass(), listener); - } - } - - /** - * This method performs validations and then returns true if no errors were generated, otherwise returns false. - * - * @return true if no errors were generated, otherwise returns false. - */ - public boolean isValid(){ - validate(); - return !hasErrors(); - } - - /** - * Executes all validators attached to this model. - */ - public void validate() { - fireBeforeValidation(this); - errors = new Errors(); - List theValidators = Registry.instance().getValidators(getClass().getName()); - if(theValidators != null){ - for (Validator validator : theValidators) { - validator.validate(this); - } - } - fireAfterValidation(this); - } - - public boolean hasErrors() { - return errors != null && errors.size() > 0; - } - - /** - * Binds a validator to an attribute if validation fails. - * - * @param errorKey key of error in errors map. Usually this is a name of attribute, - * but not limited to that, can be anything. - * - * @param validator -validator that failed validation. - */ - public void addValidator(Validator validator, String errorKey) { - if(!errors.containsKey(errorKey)) - errors.addValidator(errorKey, validator); - } - - /** - * Provides an instance of Errors object, filled with error messages after validation. - * - * @return an instance of Errors object, filled with error messages after validation. - */ - public Errors errors() { - return errors; - } - - /** - * Provides an instance of localized Errors object, filled with error messages after validation. - * - * @param locale locale. - * @return an instance of localized Errors object, filled with error messages after validation. - */ - public Errors errors(Locale locale) { - errors.setLocale(locale); - return errors; - } - - /** - * This is a convenience method to create a model instance already initialized with values. - * Example: - *
-     * Person p = Person.create("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07");
-     * 
- * - * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every - * other is a corresponding value. - * - * This allows for better readability of code. If you just read this aloud, it will become clear. - * - * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at - * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. - * @return newly instantiated model. - */ - public static T create(Object ... namesAndValues){ - - if(namesAndValues.length %2 != 0) throw new IllegalArgumentException("number of arguments must be even"); - - try{ - - Model m = getDaClass().newInstance(); - ModelDelegate.setNamesAndValues(m, namesAndValues); - return (T) m; - } - catch(IllegalArgumentException e){throw e;} - catch(ClassCastException e){throw new IllegalArgumentException("All even arguments must be strings");} - catch(DBException e){throw e;} - catch (Exception e){throw new InitException("Model '" + getClassName() + "' must provide a default constructor. Table:", e);} - } - - - /** - * This is a convenience method to set multiple values to a model. - * Example: - *
-     * Person p = ...
-     * Person p = p.set("name", "Sam", "last_name", "Margulis", "dob", "2001-01-07");
-     * 
- * - * The first (index 0) and every other element in the array is an attribute name, while the second (index 1) and every - * other is a corresponding value. - * - * This allows for better readability of code. If you just read this aloud, it will become clear. - * - * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at - * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. - * @return newly instantiated model. - */ - public Model set(Object ... namesAndValues){ - ModelDelegate.setNamesAndValues(this, namesAndValues); - return this; - } - - /** - * This is a convenience method to {@link #create(Object...)}. It will create a new model and will save it - * to DB. It has the same semantics as {@link #saveIt()}. - * - * @param namesAndValues names and values. elements at indexes 0, 2, 4, 8... are attribute names, and elements at - * indexes 1, 3, 5... are values. Element at index 1 is a value for attribute at index 0 and so on. - * @return newly instantiated model which also has been saved to DB. - */ - public static T createIt(Object ... namesAndValues){ - T m = (T)create(namesAndValues); - m.saveIt(); - return m; - } - - public static T findById(Object id) { - if(id == null) return null; - - MetaModel mm = getMetaModel(); - LazyList l = new LazyList(mm.getIdName() + " = ?", mm, id).limit(1); - return l.size() > 0 ? l.get(0) : null; - - } - - /** - * Finder method for DB queries based on table represented by this model. Usually the SQL starts with: - * - * "select * from table_name where " + subquery where table_name is a table represented by this model. - * - * Code example: - *
-     *
-     * List teenagers = Person.where("age > ? and age < ?", 12, 20);
-     * // iterate...
-     *
-     * //same can be achieved (since parameters are optional):
-     * List teenagers = Person.where("age > 12 and age < 20");
-     * //iterate
-     * 
- * - * Limit, offset and order by can be chained like this: - * - *
-     * List teenagers = Person.where("age > ? and age < ?", 12, 20).offset(101).limit(20).orderBy(age);
-     * //iterate
-     * 
- * - * This is a great way to build paged applications. - * - * - * @param subquery this is a set of conditions that normally follow the "where" clause. Example: - * "department = ? and dob > ?". If this value is "*" and no parameters provided, then {@link #findAll()} is executed. - * @param params list of parameters corresponding to the place holders in the subquery. - * @return instance of LazyList containing results. - */ - public static LazyList where(String subquery, Object... params) { - return find(subquery, params); - } - - - - /** - * Synonym of {@link #where(String, Object...)} - * - * @param subquery this is a set of conditions that normally follow the "where" clause. Example: - * "department = ? and dob > ?". If this value is "*" and no parameters provided, then {@link #findAll()} is executed. - * @param params list of parameters corresponding to the place holders in the subquery. - * @return instance of LazyList containing results. - */ - public static LazyList find(String subquery, Object... params) { - - if(subquery.trim().equals("*") && params.length == 0){ - return findAll(); - } - - if(subquery.equals("*") && params.length != 0){ - throw new IllegalArgumentException("cannot provide parameters with query: '*', use findAll() method instead"); - } - - return new LazyList(subquery, getMetaModel(), params); - } - - - /** - * Synonym of {@link #first(String, Object...)}. - * - * @param subQuery selection criteria, example: - *
-     * Person johnTheTeenager = Person.findFirst("name = ? and age > 13 and age < 19 order by age", "John")
-     * 
- * Sometimes a query might be just a clause like this: - *
-     * Person oldest = Person.findFirst("order by age desc")
-     * 
- * @param params list of parameters if question marks are used as placeholders - * @return a first result for this condition. May return null if nothing found. - */ - public static T findFirst(String subQuery, Object... params) { - LazyList results = new LazyList(subQuery, getMetaModel(), params).limit(1); - return results.size() > 0 ? results.get(0) : null; - } - - - /** - * Returns a first result for this condition. May return null if nothing found. - * If last result is needed, then order by some field and call this nethod: - * - * Synonym of {@link #findFirst(String, Object...)}. - *
-     * //first:
-     * Person youngestTeenager= Person.first("age > 12 and age < 20 order by age");
-     *
-     * //last:
-     * Person oldestTeenager= Person.first("age > 12 and age < 20 order by age desc");
-     * 
- * - * - * @param subQuery selection criteria, example: - *
-     * Person johnTheTeenager = Person.first("name = ? and age < 13 order by age", "John")
-     * 
- * Sometimes a query might be just a clause like this: - *
-     * Person p = Person.first("order by age desc")
-     * 
- * @param params list of parameters if question marks are used as placeholders - * @return a first result for this condition. May return null if nothing found. - */ - public static T first(String subQuery, Object... params) { - return (T)findFirst(subQuery, params); - } - - - /** - * This method is for processing really large result sets. Results found by this method are never cached. - * - * @param query query text. - * @param listener this is a call back implementation which will receive instances of models found. - * @deprecated use {@link #findWith(ModelListener, String, Object...)}. - */ - public static void find(String query, final ModelListener listener) { - findWith(listener, query); - } - - - /** - * This method is for processing really large result sets. Results found by this method are never cached. - * - * @param listener this is a call back implementation which will receive instances of models found. - * @param query sub-query (content after "WHERE" clause) - * @param params optional parameters for a query. - */ - public static void findWith(final ModelListener listener, String query, Object ... params) { - long start = System.currentTimeMillis(); - final MetaModel metaModel = getMetaModel(); - String sql = metaModel.getDialect().selectStar(metaModel.getTableName(), query); - - new DB(metaModel.getDbName()).find(sql, params).with( new RowListenerAdapter() { - @Override - public void onNext(Map row) { - listener.onModel(instance(row, metaModel)); - } - }); - LogFilter.logQuery(logger, sql, null, start); - } - - - /** - * Free form query finder. Example: - *
-     * List rules = Rule.findBySQL("select rule.*, goal_identifier from rule, goal where goal.goal_id = rule.goal_id order by goal_identifier asc, rule_type desc");
-     * 
- * Ensure that the query returns all columns associated with this model, so that the resulting models could hydrate itself properly. - * Returned columns that are not part of this model will be ignored, but can be used for caluses like above. - * - * @param fullQuery free-form SQL. - * @param params parameters if query is parametrized. - * @param - class that extends Model. - * @return list of models representing result set. - */ - public static LazyList findBySQL(String fullQuery, Object... params) { - return new LazyList(false, getMetaModel(), fullQuery, params); - } - - /** - * This method returns all records from this table. If you need to get a subset, look for variations of "find()". - * - * @return result list - */ - public static LazyList findAll() { - return new LazyList(null, getMetaModel()); - } - - /** - * Adds a new child dependency. This method works for all three association types: - *
    - *
  • One to many - argument model should be a child in the relationship. This method will immediately set it's - * ID as a foreign key on the child and will then save the child.
  • - *
  • Many to many - argument model should be the other model in the relationship. This method will check if the - * added child already has an ID. If the child does have an ID, then the method will create a link in the join - * table. If the child does not have an ID, then this method saves the child first, then creates a record in the - * join table linking this model instance and the child instance.
  • - *
  • Polymorphic - argument model should be a polymorphic child of this model. This method will set the - * parent_id and parent_type as appropriate and then will then save the child.
  • - *
- * - * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. - * - * @param child instance of a model that has a relationship to the current model. - * Either one to many or many to many relationships are accepted. - */ - public void add(Model child) { - - //TODO: refactor this method - String childTable = Registry.instance().getTableName(child.getClass()); - MetaModel metaModel = getMetaModelLocal(); - if (getId() != null) { - - if (metaModel.hasAssociation(childTable, OneToManyAssociation.class)) { - OneToManyAssociation ass = (OneToManyAssociation)metaModel.getAssociationForTarget(childTable, OneToManyAssociation.class); - String fkName = ass.getFkName(); - child.set(fkName, getId()); - child.saveIt();//this will cause an exception in case validations fail. - }else if(metaModel.hasAssociation(childTable, Many2ManyAssociation.class)){ - Many2ManyAssociation ass = (Many2ManyAssociation) metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class); - String join = ass.getJoin(); - String sourceFkName = ass.getSourceFkName(); - String targetFkName = ass.getTargetFkName(); - if(child.getId() == null) - child.saveIt(); - - MetaModel joinMM = Registry.instance().getMetaModel(join); - if(joinMM == null){ - new DB(metaModel.getDbName()).exec("INSERT INTO " + join + " ( " + sourceFkName + ", " + targetFkName + " ) VALUES ( " + getId()+ ", " + child.getId() + ")"); - }else{ - //TODO: write a test to cover this case: - //this is for Oracle, many 2 many, and all annotations used, including @IdGenerator. In this case, - //it is best to delegate generation of insert to a model (sequences, etc.) - try{ - Model joinModel = (Model)joinMM.getModelClass().newInstance(); - joinModel.set(sourceFkName, getId()); - joinModel.set(targetFkName, child.getId()); - joinModel.saveIt(); - } - catch(InstantiationException e){ - throw new InitException("failed to create a new instance of class: " + joinMM.getClass() - + ", are you sure this class has a default constructor?", e); - } - catch(IllegalAccessException e){throw new InitException(e);} - finally { - QueryCache.instance().purgeTableCache(join); - QueryCache.instance().purgeTableCache(metaModel.getTableName()); - QueryCache.instance().purgeTableCache(childTable); - } - } - }else if(metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)){ - - OneToManyPolymorphicAssociation ass = (OneToManyPolymorphicAssociation)metaModel - .getAssociationForTarget(childTable, OneToManyPolymorphicAssociation.class); - child.set("parent_id", getId()); - child.set("parent_type", ass.getTypeLabel()); - child.saveIt(); - - }else - throw new NotAssociatedException(metaModel.getTableName(), childTable); - } else { - throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. Save this instance first, then you will be able to add dependencies to it."); - } - } - - - /** - * Removes associated child from this instance. The child model should be either in belongs to association (including polymorphic) to this model - * or many to many association. - * - *

One to many and polymorphic associations

- * This method will simply call child.delete() method. This will render the child object frozen. - * - *

Many to many associations

- * This method will remove an associated record from the join table, and will do nothing to the child model or record. - * - *

- * This method will throw a {@link NotAssociatedException} in case a model that has no relationship is passed. - * - * @param child model representing a "child" as in one to many or many to many association with this model. - */ - public void remove(Model child){ - - if(child == null) throw new IllegalArgumentException("cannot remove what is null"); - - if(child.frozen() || child.getId() == null) throw new IllegalArgumentException("Cannot remove a child that does " + - "not exist in DB (either frozen, or ID not set)"); - - String childTable = Registry.instance().getTableName(child.getClass()); - MetaModel metaModel = getMetaModelLocal(); - if (getId() != null) { - if (metaModel.hasAssociation(childTable, OneToManyAssociation.class) - || metaModel.hasAssociation(childTable, OneToManyPolymorphicAssociation.class)) { - child.delete(); - }else if(metaModel.hasAssociation(childTable, Many2ManyAssociation.class)){ - Many2ManyAssociation ass = (Many2ManyAssociation)metaModel.getAssociationForTarget(childTable, Many2ManyAssociation.class); - String join = ass.getJoin(); - String sourceFkName = ass.getSourceFkName(); - String targetFkName = ass.getTargetFkName(); - new DB(metaModel.getDbName()).exec("DELETE FROM " + join + " WHERE " + sourceFkName + " = ? AND " - + targetFkName + " = ?", getId(), child.getId()); - }else - throw new NotAssociatedException(metaModel.getTableName(), childTable); - } else { - throw new IllegalArgumentException("You can only add associated model to an instance that exists in DB. " + - "Save this instance first, then you will be able to add dependencies to it."); - } - } - - /** - * This method will not exit silently like {@link #save()}, it instead will throw {@link org.javalite.activejdbc.validation.ValidationException} - * if validations did not pass. - * - * @return true if the model was saved, false if you set an ID value for the model, but such ID does not exist in DB. - */ - public boolean saveIt() { - boolean result = save(); - purgeEdges(); - if(errors.size() > 0){ - throw new ValidationException(this); - } - return result; - } - - - - /** - * Resets all data in this model, including the ID. - * After this method, this instance is equivalent to an empty, just created instance. - */ - public void reset() { - attributes = new HashMap(); - } - - /** - * Unfreezes this model. After this method it is possible again to call save() and saveIt() methods. - * This method will erase the value of ID on this instance, while preserving all other attributes' values. - * - * If a record was deleted, it is frozen and cannot be saved. After it is thawed, it can be saved again, but it will - * generate a new insert statement and create a new record in the table with all the same attribute values. - * - *

- * Synonym for {@link #defrost()}. - */ - public void thaw(){ - attributes.put(getMetaModelLocal().getIdName(), "");//makes it blank - frozen = false; - } - - /** - * Synonym for {@link #thaw()}. - */ - public void defrost(){ - thaw(); - } - - /** - * This method will save data from this instance to a corresponding table in the DB. - * It will generate insert SQL if the model is new, or update if the model exists in the DB. - * This method will execute all associated validations and if those validations generate errors, - * these errors are attached to this instance. Errors are available by {#link #errors() } method. - * The save() method is mostly for web applications, where code like this is written: - *

-     * if(person.save())
-     *      //show page success
-     * else{
-     *      request.setAttribute("errors", person.errors());
-     *      //show errors page, or same page so that user can correct errors.
-     *   }
-     * 
- * - * In other words, this method will not throw validation exceptions. However, if there is a problem in the DB, then - * there can be a runtime exception thrown. - * - * @return true if a model was saved and false if values did not pass validations and the record was not saved. - * False will also be returned if you set an ID value for the model, but such ID does not exist in DB. - */ - public boolean save() { - if(frozen) throw new FrozenException(this); - - fireBeforeSave(this); - - validate(); - if (hasErrors()) { - return false; - } - - boolean result; - if (blank(getId())) { - result = doInsert(); - } else { - result = update(); - } - fireAfterSave(this); - return result; - } - - /** - * Returns total count of records in table. - * - * @return total count of records in table. - */ - public static Long count() { - MetaModel metaModel = getMetaModel(); - String sql = "SELECT COUNT(*) FROM " + metaModel.getTableName(); - Long result; - if(metaModel.cached()){ - result = (Long)QueryCache.instance().getItem(metaModel.getTableName(), sql, null); - if(result == null) - { - result = new DB(metaModel.getDbName()).count(metaModel.getTableName()); - QueryCache.instance().addItem(metaModel.getTableName(), sql, null, result); - } - }else{ - result = new DB(metaModel.getDbName()).count(metaModel.getTableName()); - } - return result; - } - - /** - * Returns count of records in table under a condition. - * - * @param query query to select records to count. - * @param params parameters (if any) for the query. - * @return count of records in table under a condition. - */ - public static Long count(String query, Object... params) { - - MetaModel metaModel = getMetaModel(); - - //attention: this SQL is only used for caching, not for real queries. - String sql = "SELECT COUNT(*) FROM " + metaModel.getTableName() + " where " + query; - - Long result; - if(metaModel.cached()){ - result = (Long)QueryCache.instance().getItem(metaModel.getTableName(), sql, params); - if(result == null){ - result = new DB(metaModel.getDbName()).count(metaModel.getTableName(), query, params); - QueryCache.instance().addItem(metaModel.getTableName(), sql, params, result); - } - }else{ - result = new DB(metaModel.getDbName()).count(metaModel.getTableName(), query, params); - } - return result; - } - - - /** - * @return attributes names that have been set by client code. - */ - private List getValueAttributeNames(boolean includeId) { - List attributeNames = new ArrayList(); - - for(String name: attributes.keySet()){ - if(includeId){ - if (!name.equalsIgnoreCase(getMetaModelLocal().getVersionColumn())) - attributeNames.add(name); - }else{ - if (!name.equalsIgnoreCase(getMetaModelLocal().getVersionColumn()) && !name.equalsIgnoreCase(getMetaModelLocal().getIdName())) - attributeNames.add(name); - } - } - return attributeNames; - } - - - private boolean doInsert() { - - fireBeforeCreate(this); - doCreatedAt(); - doUpdatedAt(); - - //TODO: need to invoke checkAttributes here too, and maybe rely on MetaModel for this. - - List valueAttributes = getValueAttributeNames(false); - - List values = new ArrayList(); - for (String attribute : valueAttributes) { - values.add(this.attributes.get(attribute)); - } - String query = getMetaModelLocal().getDialect().createParametrizedInsert(getMetaModelLocal(), valueAttributes); - try { - Object id = new DB(getMetaModelLocal().getDbName()).execInsert(query, getMetaModelLocal().getIdName(), values.toArray()); - if(getMetaModelLocal().cached()){ - QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); - } - - attributes.put(getMetaModelLocal().getIdName(), id); - - fireAfterCreate(this); - - if(getMetaModelLocal().isVersioned()){ - set(getMetaModelLocal().getVersionColumn(), 1); - } - - return true; - } catch (DBException e) { - throw e; - } catch (Exception e) { - throw new DBException(e.getMessage(), e); - } - } - - - /** - * This method will save a model as new. In other words, it will not try to guess if this is a - * new record or a one that exists in the table. It does not have "belt and suspenders", it will - * simply generate and execute insert statement, assuming that developer knows what he/she is doing. - * - * @return true if model was saved, false if not - */ - public boolean insert() { - - fireBeforeCreate(this); - doCreatedAt(); - doUpdatedAt(); - - List valueAttributes = getValueAttributeNames(true); - - List values = new ArrayList(); - for (String attribute : valueAttributes) { - values.add(this.attributes.get(attribute)); - } - String query = getMetaModelLocal().getDialect().createParametrizedInsertIdUnmanaged(getMetaModelLocal(), valueAttributes); - try { - long recordsUpdated = new DB(getMetaModelLocal().getDbName()).exec(query, values.toArray()); - if(getMetaModelLocal().cached()){ - QueryCache.instance().purgeTableCache(getMetaModelLocal().getTableName()); - } - - fireAfterCreate(this); - - if(getMetaModelLocal().isVersioned()){ - set(getMetaModelLocal().getVersionColumn(), 1); - } - - return recordsUpdated == 1; - } catch (DBException e) { - throw e; - } catch (Exception e) { - throw new DBException(e.getMessage(), e); - } - } - - private void doCreatedAt() { - if(getMetaModelLocal().hasAttribute("created_at") && manageTime){ - //clean just in case. - attributes.remove("created_at"); - attributes.remove("CREATED_AT"); - attributes.put("created_at", new Timestamp(System.currentTimeMillis())); - } - } - - private void doUpdatedAt() { - if(getMetaModelLocal().hasAttribute("updated_at") && manageTime){ - //clean just in case. - attributes.remove("updated_at"); - attributes.remove("UPDATED_AT"); - set("updated_at", new Timestamp(System.currentTimeMillis())); - } - } - - private boolean update() { - - doUpdatedAt(); - - MetaModel metaModel = getMetaModelLocal(); - String query = "UPDATE " + metaModel.getTableName() + " SET "; - List names = metaModel.getAttributeNamesSkipGenerated(manageTime); - for (int i = 0; i < names.size(); i++) { - String name = names.get(i); - query += name + "= ?"; - if (i < names.size() - 1) { - query += ", "; - } - } - - List values = getAttributeValuesSkipGenerated(names); - - if(metaModel.hasAttribute("updated_at")){ - query += ", updated_at = ? "; - values.add(get("updated_at")); - } - - if(metaModel.isVersioned()){ - query += ", " + getMetaModelLocal().getVersionColumn() + " = ? "; - values.add(getLong(getMetaModelLocal().getVersionColumn()) + 1); - } - query += " where " + metaModel.getIdName() + " = ?"; - query += metaModel.isVersioned()? " and " + getMetaModelLocal().getVersionColumn() + " = ?" :""; - values.add(getId()); - if(metaModel.isVersioned()){ - values.add((get(getMetaModelLocal().getVersionColumn()))); - } - int updated = new DB(metaModel.getDbName()).exec(query, values.toArray()); - if(metaModel.isVersioned() && updated == 0){ - throw new StaleModelException("Failed to update record for model '" + getClass() + - "', with " + getIdName() + " = " + getId() + " and " + getMetaModelLocal().getVersionColumn() + " = " + get(getMetaModelLocal().getVersionColumn()) + - ". Either this record does not exist anymore, or has been updated to have another record_version."); - }else if(metaModel.isVersioned()){ - set(getMetaModelLocal().getVersionColumn(), getLong(getMetaModelLocal().getVersionColumn()) + 1); - } - if(metaModel.cached()){ - QueryCache.instance().purgeTableCache(metaModel.getTableName()); - } - return updated > 0; - } - - private List getAttributeValuesSkipGenerated(List names) { - List values = new ArrayList(); - for (String name : names) { - values.add(get(name)); - } - return values; - } - - static T instance(Map m, MetaModel metaModel) { - try { - T instance = (T) metaModel.getModelClass().newInstance(); - instance.setMetamodelLocal(metaModel); - instance.hydrate(m); - return instance; - } - catch(InstantiationException e){ - throw new InitException("Failed to create a new instance of: " + metaModel.getModelClass() + ", are you sure this class has a default constructor?"); - } - catch(DBException e){ - throw e; - } - catch(InitException e){ - throw e; - } - catch (Exception e) { - throw new RuntimeException(e.getMessage(), e); - } - } - - private static Class getDaClass() { - try { - if (Registry.instance().initialized()) { - MetaModel mm = Registry.instance().getMetaModelByClassName(getClassName()); - return mm == null ? (Class) Class.forName(getClassName()) : mm.getModelClass(); - } else { - return (Class) Class.forName(getClassName()); - } - } catch (Exception e) { - throw new DBException(e.getMessage(), e); - } - } - - private static String getClassName() { - return new ClassGetter().getClassName(); - } - - public static String getTableName() { - return Registry.instance().getTableName(getDaClass()); - } - - public Object getId() { - return get(getMetaModelLocal().getIdName()); - } - - public String getIdName() { - return getMetaModelLocal().getIdName(); - } - - protected void setChildren(Class childClass, List children) { - cachedChildren.put(childClass, children); - } - - /** - * Turns off automatic management of time-related attributes created_at and updated_at. - * If management of time attributes is turned off, - * - * @param manage if true, the attributes are managed by the model. If false, they are managed by developer. - */ - public void manageTime(boolean manage) { - this.manageTime = manage; - } - - static class ClassGetter extends SecurityManager { - public String getClassName() { - Class[] classes = getClassContext(); - for (Class clazz : classes) { - if (Model.class.isAssignableFrom(clazz) && clazz != null && !clazz.equals(Model.class)) { - return clazz.getName(); - } - } - throw new InitException("failed to determine Model class name, are you sure models have been instrumented?"); - } - } - - /** - * Generates INSERT SQL based on this model. Uses single quotes for all string values. - * Example: - *
-     *
-     * String insert = u.toInsert();
-     * //yields this output:
-     * //INSERT INTO users (id, first_name, email, last_name) VALUES (1, 'Marilyn', 'mmonroe@yahoo.com', 'Monroe');
-     * 
- * - * @return INSERT SQL based on this model. - */ - public String toInsert(){ - return toInsert("'", "'"); - } - - - /** - * Generates INSERT SQL based on this model. - * For instance, for Oracle, the left quote is: "q'{" and the right quote is: "}'". - * The output will also use single quotes for java.sql.Timestamp and java.sql.Date types. - * - * Example: - *
-     * String insert = u.toInsert("q'{", "}'");
-     * //yields this output
-     * //INSERT INTO users (id, first_name, email, last_name) VALUES (1, q'{Marilyn}', q'{mmonroe@yahoo.com}', q'{Monroe}');
-     * 
- * @param leftStringQuote - left quote for a string value, this can be different for different databases. - * @param rightStringQuote - left quote for a string value, this can be different for different databases. - * @return SQL INSERT string; - */ - public String toInsert(String leftStringQuote, String rightStringQuote){ - return toInsert(new SimpleFormatter(java.sql.Date.class, "'", "'"), - new SimpleFormatter(Timestamp.class, "'", "'"), - new SimpleFormatter(String.class, leftStringQuote, rightStringQuote)); - } - - /** - * TODO: write good JavaDoc, use code inside method above - * - * @param formatters - * @return - */ - public String toInsert(Formatter... formatters){ - HashMap formatterMap = new HashMap(); - - for(Formatter f: formatters){ - formatterMap.put(f.getValueClass(), f); - } - - List names = new ArrayList(attributes.keySet()); - Collections.sort(names); - List values = new ArrayList(); - - for(String name: names){ - Object value = get(name); - if(value == null){ - values.add("NULL"); - } - else if (value instanceof String && !formatterMap.containsKey(String.class)){ - values.add("'" + value + "'"); - }else{ - if(formatterMap.containsKey(value.getClass())){ - values.add(formatterMap.get(value.getClass()).format(value)); - }else{ - values.add(value); - } - } - } - return new StringBuffer("INSERT INTO ").append(getMetaModelLocal().getTableName()).append(" (") - .append(Util.join(names, ", ")).append(") VALUES (").append(Util.join(values, ", ")).append(")").toString(); - } - - /** - * Use to force-purge cache associated with this table. If this table is not cached, this method has no side effect. - */ - public static void purgeCache(){ - MetaModel mm = getMetaModel(); - if(mm.cached()){ - QueryCache.instance().purgeTableCache(mm.getTableName()); - } - } - - - /** - * Convenience method: converts ID value to Long and returns it. - * - * @return value of attribute corresponding to getIdName(), converted to Long. - */ - public Long getLongId() { - Object id = get(getIdName()); - if (id == null) { - throw new NullPointerException(getIdName() + " is null, cannot convert to Long"); - } - return Convert.toLong(id); - } - - private static void purgeEdges(){ - ModelDelegate.purgeEdges(getMetaModel()); - } - - - public void writeExternal(ObjectOutput out) throws IOException { - out.writeObject(attributes); - } - - public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { - attributes = (Map) in.readObject(); - } -} - diff --git a/All/Genesis-NP/Genesis#360/old/pom.xml b/All/Genesis-NP/Genesis#360/old/pom.xml deleted file mode 100755 index 2f10118..0000000 --- a/All/Genesis-NP/Genesis#360/old/pom.xml +++ /dev/null @@ -1,350 +0,0 @@ - - 4.0.0 - org.javalite - activejdbc - jar - 1.4.10-SNAPSHOT - JavaLite - ActiveJDBC ORM Framework - - - org.sonatype.oss - oss-parent - 7 - - - - - UTF-8 - com.mysql.jdbc.Driver - jdbc:mysql://localhost/activejdbc - root - p@ssw0rd - mysql - - - - - mysql - - false - - - com.mysql.jdbc.Driver - jdbc:mysql://localhost/activejdbc - root - p@ssw0rd - mysql - - - - mysql - mysql-connector-java - 5.1.25 - test - - - - - oracle - - - oracle.jdbc.OracleDriver - - - - - jdbc:oracle:thin:@//192.168.0.112:1521/orcl - scott - oracle - - oracle - - - - oracle - ojdbc14 - 10.2.0.4 - test - - - - - - oracle - http://192.168.0.55:8084/nexus/content/repositories/oracle/ - - - - - postgresql - - org.postgresql.Driver - jdbc:postgresql://192.168.0.55/postgres - postgres - p@ssw0rd - postgresql - - - - postgresql - postgresql - 8.4-701.jdbc3 - test - - - - - h2 - - org.h2.Driver - jdbc:h2:mem:test;DB_CLOSE_DELAY=-1 - sa - - h2 - - - - com.h2database - h2 - 1.3.171 - test - - - - - tds - - net.sourceforge.jtds.jdbc.Driver - jdbc:jtds:sqlserver://192.168.0.33/activejdbc;TDS=8.0 - activejdbc - activejdbc - mssql - - - - net.sourceforge.jtds - jtds - 1.2.4 - test - - - - - - ms-releases - http://192.168.0.55:8084/nexus/content/repositories/microsoft/ - - - - - - mssql - - com.microsoft.sqlserver.jdbc.SQLServerDriver - jdbc:sqlserver://192.168.0.33:1433;databaseName=activejdbc - activejdbc - activejdbc - mssql - - - - - com.microsoft.sqljdbc - sqljdbc4 - 4.0.3 - test - - - - - ms-releases - http://192.168.0.55:8084/nexus/content/repositories/microsoft/ - - - - - instrument - - true - - - - - - org.javalite - activejdbc-instrumentation - ${project.version} - - - process-test-classes - instrument - - ${project.basedir}/target/test-classes - - - - - - - - - - - - src/test/resources - true - - - - - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - true - 128m - 512m - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - org.apache.maven.plugins - maven-surefire-plugin - 2.5 - - brief - true - false - - true - - - - - - - - - junit - junit - 4.8.2 - test - - - javax.servlet - servlet-api - 2.5 - provided - - - org.slf4j - slf4j-api - 1.7.5 - - - org.slf4j - jcl-over-slf4j - 1.7.5 - provided - - - org.slf4j - slf4j-simple - 1.7.5 - provided - - - mysql - mysql-connector-java - 5.1.17 - test - - - org.javalite - javalite-common - ${project.version} - - - dom4j - dom4j - - - jaxen - jaxen - - - - - dom4j - dom4j - 1.6.1 - test - - - jaxen - jaxen - 1.1.4 - test - - - opensymphony - oscache - 2.4 - provided - - - javax.jms - jms - - - javax.servlet - servlet-api - - - org.hibernate - hibernate - - - commons-logging - commons-logging - - - - - com.h2database - h2 - 1.3.171 - jar - test - - - org.codehaus.jackson - jackson-core-lgpl - 1.8.2 - test - - - org.codehaus.jackson - jackson-mapper-lgpl - 1.8.2 - test - - - c3p0 - c3p0 - 0.9.1.2 - test - - - net.sf.ehcache - ehcache-core - 2.4.5 - provided - - - diff --git a/All/Genesis-NP/Genesis#360/pair.info b/All/Genesis-NP/Genesis#360/pair.info deleted file mode 100755 index 3289226..0000000 --- a/All/Genesis-NP/Genesis#360/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:360 -SATName:Genesis -modifiedFPath:activejdbc/src/main/java/org/javalite/activejdbc/Model.java -comSha:045ecdce4563b11d6eb1c1cf9695d1df5f1f0166 -parentComSha:045ecdce4563b11d6eb1c1cf9695d1df5f1f0166^1 -githubUrl:https://github.com/javalite/activejdbc -repoName:javalite#activejdbc \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#367/comMsg.txt b/All/Genesis-NP/Genesis#367/comMsg.txt deleted file mode 100755 index 58a3ed3..0000000 --- a/All/Genesis-NP/Genesis#367/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix possible NPE diff --git a/All/Genesis-NP/Genesis#367/diff.diff b/All/Genesis-NP/Genesis#367/diff.diff deleted file mode 100755 index a44be1f..0000000 --- a/All/Genesis-NP/Genesis#367/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/modules/cpr/src/main/java/org/atmosphere/container/version/JSR356WebSocket.java b/modules/cpr/src/main/java/org/atmosphere/container/version/JSR356WebSocket.java -index 871b5c7..8c61752 100644 ---- a/modules/cpr/src/main/java/org/atmosphere/container/version/JSR356WebSocket.java -+++ b/modules/cpr/src/main/java/org/atmosphere/container/version/JSR356WebSocket.java -@@ -162 +162 @@ public class JSR356WebSocket extends WebSocket { -- if (!result.isOK() || result.getException() != null && r != null) { -+ if (!result.isOK() || result.getException() != null) { -@@ -163,0 +164 @@ public class JSR356WebSocket extends WebSocket { -+ if (r != null) { -@@ -169,0 +171 @@ public class JSR356WebSocket extends WebSocket { -+} -\ No newline at end of file diff --git a/All/Genesis-NP/Genesis#367/new/JSR356WebSocket.java b/All/Genesis-NP/Genesis#367/new/JSR356WebSocket.java deleted file mode 100755 index 8c61752..0000000 --- a/All/Genesis-NP/Genesis#367/new/JSR356WebSocket.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Copyright 2015 Async-IO.org - * - * 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.atmosphere.container.version; - -import org.atmosphere.cache.BroadcastMessage; -import org.atmosphere.cpr.ApplicationConfig; -import org.atmosphere.cpr.AtmosphereConfig; -import org.atmosphere.cpr.AtmosphereResource; -import org.atmosphere.cpr.Broadcaster; -import org.atmosphere.cpr.WebSocketProcessorFactory; -import org.atmosphere.websocket.WebSocket; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.websocket.SendHandler; -import javax.websocket.SendResult; -import javax.websocket.Session; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Asynchronous based {@link Session} websocket - * - * @author Jeanfrancois Arcand - */ -public class JSR356WebSocket extends WebSocket { - - private final Logger logger = LoggerFactory.getLogger(JSR356WebSocket.class); - private final Session session; - private final Semaphore semaphore = new Semaphore(1, true);// https://issues.apache.org/bugzilla/show_bug.cgi?id=56026 - private final int writeTimeout; - private final AtomicBoolean closed = new AtomicBoolean(); - - public JSR356WebSocket(Session session, AtmosphereConfig config) { - super(config); - this.session = session; - this.writeTimeout = config.getInitParameter(ApplicationConfig.WEBSOCKET_WRITE_TIMEOUT, 60 * 1000); - session.getAsyncRemote().setSendTimeout(writeTimeout); - } - - @Override - public boolean isOpen() { - return session.isOpen() && !closed.get(); - } - - @Override - public WebSocket write(String s) throws IOException { - - if (!isOpen()) { - throw new IOException("Socket closed {}"); - } - - boolean acquired = false; - try { - acquired = semaphore.tryAcquire(writeTimeout, TimeUnit.MILLISECONDS); - if (acquired) { - session.getAsyncRemote().sendText(s, new WriteResult(resource(), s)); - } else { - throw new IOException("Socket closed"); - } - } catch (Throwable e) { - if (IOException.class.isAssignableFrom(e.getClass())) { - throw IOException.class.cast(e); - } - handleError(e, acquired); - } - return this; - } - - @Override - public WebSocket write(byte[] data, int offset, int length) throws IOException { - - if (!isOpen()) { - throw new IOException("Socket closed {}"); - } - - boolean acquired = false; - try { - acquired = semaphore.tryAcquire(writeTimeout, TimeUnit.MILLISECONDS); - if (acquired) { - ByteBuffer b = ByteBuffer.wrap(data, offset, length); - session.getAsyncRemote().sendBinary(b, - new WriteResult(resource(), b.array())); - } else { - throw new IOException("Socket closed"); - } - } catch (Throwable e) { - if (IOException.class.isAssignableFrom(e.getClass())) { - throw IOException.class.cast(e); - } - handleError(e, acquired); - } - return this; - } - - private void handleError(Throwable e, boolean acquired) throws IOException { - if (acquired) { - semaphore.release(); - } - - if (e instanceof NullPointerException) { - patchGlassFish((NullPointerException) e); - return; - } - - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } - - throw new RuntimeException("Unexpected error while writing to socket", e); - } - - void patchGlassFish(NullPointerException e) { - // https://java.net/jira/browse/TYRUS-175 - logger.trace("", e); - WebSocketProcessorFactory.getDefault().getWebSocketProcessor(config().framework()).close(this, 1002); - } - - @Override - public void close() { - - if (!session.isOpen() || closed.getAndSet(true)) return; - - logger.trace("WebSocket.close() for AtmosphereResource {}", resource() != null ? resource().uuid() : "null"); - try { - session.close(); - // Tomcat may throw https://gist.github.com/jfarcand/6702738 - } catch (Exception e) { - logger.trace("", e); - } - } - - private final class WriteResult implements SendHandler { - - private final AtmosphereResource r; - private final Object message; - - private WriteResult(AtmosphereResource r, Object message) { - this.r = r; - this.message = message; - } - - @Override - public void onResult(SendResult result) { - semaphore.release(); - if (!result.isOK() || result.getException() != null) { - logger.trace("WebSocket {} failed to write {}", r, message); - if (r != null) { - Broadcaster b = r.getBroadcaster(); - b.getBroadcasterConfig().getBroadcasterCache().addToCache(b.getID(), r.uuid(), new BroadcastMessage(message)); - } - } - } - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#367/old/JSR356WebSocket.java b/All/Genesis-NP/Genesis#367/old/JSR356WebSocket.java deleted file mode 100755 index 871b5c7..0000000 --- a/All/Genesis-NP/Genesis#367/old/JSR356WebSocket.java +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright 2015 Async-IO.org - * - * 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.atmosphere.container.version; - -import org.atmosphere.cache.BroadcastMessage; -import org.atmosphere.cpr.ApplicationConfig; -import org.atmosphere.cpr.AtmosphereConfig; -import org.atmosphere.cpr.AtmosphereResource; -import org.atmosphere.cpr.Broadcaster; -import org.atmosphere.cpr.WebSocketProcessorFactory; -import org.atmosphere.websocket.WebSocket; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.websocket.SendHandler; -import javax.websocket.SendResult; -import javax.websocket.Session; -import java.io.IOException; -import java.nio.ByteBuffer; -import java.util.concurrent.Semaphore; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Asynchronous based {@link Session} websocket - * - * @author Jeanfrancois Arcand - */ -public class JSR356WebSocket extends WebSocket { - - private final Logger logger = LoggerFactory.getLogger(JSR356WebSocket.class); - private final Session session; - private final Semaphore semaphore = new Semaphore(1, true);// https://issues.apache.org/bugzilla/show_bug.cgi?id=56026 - private final int writeTimeout; - private final AtomicBoolean closed = new AtomicBoolean(); - - public JSR356WebSocket(Session session, AtmosphereConfig config) { - super(config); - this.session = session; - this.writeTimeout = config.getInitParameter(ApplicationConfig.WEBSOCKET_WRITE_TIMEOUT, 60 * 1000); - session.getAsyncRemote().setSendTimeout(writeTimeout); - } - - @Override - public boolean isOpen() { - return session.isOpen() && !closed.get(); - } - - @Override - public WebSocket write(String s) throws IOException { - - if (!isOpen()) { - throw new IOException("Socket closed {}"); - } - - boolean acquired = false; - try { - acquired = semaphore.tryAcquire(writeTimeout, TimeUnit.MILLISECONDS); - if (acquired) { - session.getAsyncRemote().sendText(s, new WriteResult(resource(), s)); - } else { - throw new IOException("Socket closed"); - } - } catch (Throwable e) { - if (IOException.class.isAssignableFrom(e.getClass())) { - throw IOException.class.cast(e); - } - handleError(e, acquired); - } - return this; - } - - @Override - public WebSocket write(byte[] data, int offset, int length) throws IOException { - - if (!isOpen()) { - throw new IOException("Socket closed {}"); - } - - boolean acquired = false; - try { - acquired = semaphore.tryAcquire(writeTimeout, TimeUnit.MILLISECONDS); - if (acquired) { - ByteBuffer b = ByteBuffer.wrap(data, offset, length); - session.getAsyncRemote().sendBinary(b, - new WriteResult(resource(), b.array())); - } else { - throw new IOException("Socket closed"); - } - } catch (Throwable e) { - if (IOException.class.isAssignableFrom(e.getClass())) { - throw IOException.class.cast(e); - } - handleError(e, acquired); - } - return this; - } - - private void handleError(Throwable e, boolean acquired) throws IOException { - if (acquired) { - semaphore.release(); - } - - if (e instanceof NullPointerException) { - patchGlassFish((NullPointerException) e); - return; - } - - if (e instanceof RuntimeException) { - throw (RuntimeException) e; - } - - throw new RuntimeException("Unexpected error while writing to socket", e); - } - - void patchGlassFish(NullPointerException e) { - // https://java.net/jira/browse/TYRUS-175 - logger.trace("", e); - WebSocketProcessorFactory.getDefault().getWebSocketProcessor(config().framework()).close(this, 1002); - } - - @Override - public void close() { - - if (!session.isOpen() || closed.getAndSet(true)) return; - - logger.trace("WebSocket.close() for AtmosphereResource {}", resource() != null ? resource().uuid() : "null"); - try { - session.close(); - // Tomcat may throw https://gist.github.com/jfarcand/6702738 - } catch (Exception e) { - logger.trace("", e); - } - } - - private final class WriteResult implements SendHandler { - - private final AtmosphereResource r; - private final Object message; - - private WriteResult(AtmosphereResource r, Object message) { - this.r = r; - this.message = message; - } - - @Override - public void onResult(SendResult result) { - semaphore.release(); - if (!result.isOK() || result.getException() != null && r != null) { - logger.trace("WebSocket {} failed to write {}", r, message); - Broadcaster b = r.getBroadcaster(); - b.getBroadcasterConfig().getBroadcasterCache().addToCache(b.getID(), r.uuid(), new BroadcastMessage(message)); - } - } - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#367/pair.info b/All/Genesis-NP/Genesis#367/pair.info deleted file mode 100755 index 62febc6..0000000 --- a/All/Genesis-NP/Genesis#367/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:367 -SATName:Genesis -modifiedFPath:modules/cpr/src/main/java/org/atmosphere/container/version/JSR356WebSocket.java -comSha:0723408e04ba7ccf56e9c858111375dcb317852b -parentComSha:0723408e04ba7ccf56e9c858111375dcb317852b^1 -githubUrl:https://github.com/Atmosphere/atmosphere -repoName:Atmosphere#atmosphere \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#369/comMsg.txt b/All/Genesis-NP/Genesis#369/comMsg.txt deleted file mode 100755 index 6e3c734..0000000 --- a/All/Genesis-NP/Genesis#369/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Oups, fix NPE diff --git a/All/Genesis-NP/Genesis#369/diff.diff b/All/Genesis-NP/Genesis#369/diff.diff deleted file mode 100755 index 12ca203..0000000 --- a/All/Genesis-NP/Genesis#369/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereResourceImpl.java b/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereResourceImpl.java -index 8e558ed..eb868a4 100644 ---- a/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereResourceImpl.java -+++ b/modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereResourceImpl.java -@@ -121 +121 @@ public class AtmosphereResourceImpl implements AtmosphereResource { -- if (s == null) { -+ if (s == null && req != null) { -@@ -123 +123 @@ public class AtmosphereResourceImpl implements AtmosphereResource { -- s = !tmp.equalsIgnoreCase("0") ? tmp : null; -+ s = tmp != null && !tmp.equalsIgnoreCase("0") ? tmp : null; diff --git a/All/Genesis-NP/Genesis#369/new/AtmosphereResourceImpl.java b/All/Genesis-NP/Genesis#369/new/AtmosphereResourceImpl.java deleted file mode 100755 index eb868a4..0000000 --- a/All/Genesis-NP/Genesis#369/new/AtmosphereResourceImpl.java +++ /dev/null @@ -1,945 +0,0 @@ -/* - * Copyright 2014 Jeanfrancois Arcand - * - * 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.atmosphere.cpr; - -import org.atmosphere.interceptor.AllowInterceptor; -import org.atmosphere.util.Utils; -import org.atmosphere.websocket.WebSocket; -import org.atmosphere.websocket.WebSocketEventListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.util.Enumeration; -import java.util.UUID; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID; -import static org.atmosphere.cpr.AtmosphereResource.TRANSPORT.UNDEFINED; -import static org.atmosphere.cpr.Broadcaster.ROOT_MASTER; -import static org.atmosphere.cpr.HeaderConfig.LONG_POLLING_TRANSPORT; -import static org.atmosphere.cpr.HeaderConfig.WEBSOCKET_UPGRADE; -import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_ERROR; -import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRANSPORT; -import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CLOSE; - -/** - * {@link AtmosphereResource} implementation for supporting {@link AtmosphereRequest} - * and {@link AtmosphereResponse}. - * - * @author Jeanfrancois Arcand - */ -public class AtmosphereResourceImpl implements AtmosphereResource { - - private static final Logger logger = LoggerFactory.getLogger(AtmosphereResourceImpl.class); - - public static final String PRE_SUSPEND = AtmosphereResourceImpl.class.getName() + ".preSuspend"; - public static final String SKIP_BROADCASTER_CREATION = AtmosphereResourceImpl.class.getName() + ".skipBroadcasterCreation"; - public static final String METEOR = Meteor.class.getName(); - - private AtmosphereRequest req; - private AtmosphereResponse response; - private final Action action = new Action(); - protected Broadcaster broadcaster; - private AtmosphereConfig config; - protected AsyncSupport asyncSupport; - private Serializer serializer; - private final AtomicBoolean isInScope = new AtomicBoolean(true); - private AtmosphereResourceEventImpl event; - private final AtomicBoolean isResumed = new AtomicBoolean(); - private final AtomicBoolean isCancelled = new AtomicBoolean(); - private final AtomicBoolean resumeOnBroadcast = new AtomicBoolean(); - private Object writeOnTimeout = null; - private boolean disableSuspend = false; - private final AtomicBoolean disconnected = new AtomicBoolean(); - - private final ConcurrentLinkedQueue listeners = - new ConcurrentLinkedQueue(); - - private final AtomicBoolean isSuspendEvent = new AtomicBoolean(); - private AtmosphereHandler atmosphereHandler; - private String uuid; - protected HttpSession session; - private boolean disableSuspendEvent; - private TRANSPORT transport; - private boolean forceBinaryWrite; - private final AtomicBoolean suspended = new AtomicBoolean(); - private WebSocket webSocket; - - public AtmosphereResourceImpl() { - } - - @Deprecated - public AtmosphereResourceImpl(AtmosphereConfig config, Broadcaster broadcaster, - AtmosphereRequest req, AtmosphereResponse response, - AsyncSupport asyncSupport, AtmosphereHandler atmosphereHandler) { - initialize(config, broadcaster, req, response, asyncSupport, atmosphereHandler); - } - - /** - * Initialize an {@link AtmosphereResource}. - * - * @param config The {@link org.atmosphere.cpr.AtmosphereConfig} - * @param broadcaster The {@link org.atmosphere.cpr.Broadcaster}. - * @param req The {@link AtmosphereRequest} - * @param response The {@link AtmosphereResource} - * @param asyncSupport The {@link AsyncSupport} - * @param atmosphereHandler The {@link AtmosphereHandler} - * @return this - */ - @Override - public AtmosphereResource initialize(AtmosphereConfig config, Broadcaster broadcaster, - AtmosphereRequest req, AtmosphereResponse response, - AsyncSupport asyncSupport, AtmosphereHandler atmosphereHandler) { - this.req = req; - this.response = response; - this.broadcaster = broadcaster; - this.config = config; - this.asyncSupport = asyncSupport; - this.atmosphereHandler = atmosphereHandler; - this.event = new AtmosphereResourceEventImpl(this); - - String s = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID); - if (s == null) { - s = response.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); - if (s == null && req != null) { - String tmp = req.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); - s = tmp != null && !tmp.equalsIgnoreCase("0") ? tmp : null; - } - } - uuid = s == null ? UUID.randomUUID().toString() : s; - - if (config.isSupportSession()) { - // Keep a reference to an HttpSession in case the associated request get recycled by the underlying container. - try { - session = req.getSession(true); - } catch (NullPointerException ex) { - // http://java.net/jira/browse/GLASSFISH-18856 - logger.trace("http://java.net/jira/browse/GLASSFISH-18856", ex); - } - } - transport = configureTransport(); - return this; - } - - - protected void register() { - if (!Utils.pollableTransport(transport()) && !Utils.webSocketMessage(this)) { - config.resourcesFactory().registerUuidForFindCandidate(this); - } - } - - private TRANSPORT configureTransport() { - if (req == null) return UNDEFINED; - - String s = req.getHeader(HeaderConfig.X_ATMOSPHERE_TRANSPORT); - if (s == null) return UNDEFINED; - - s = s.replace("-", "_").toUpperCase(); - if (TRANSPORT.POLLING.name().equals(s)) { - return TRANSPORT.POLLING; - } else if (TRANSPORT.LONG_POLLING.name().equals(s)) { - return TRANSPORT.LONG_POLLING; - } else if (TRANSPORT.STREAMING.name().equals(s)) { - return TRANSPORT.STREAMING; - } else if (TRANSPORT.JSONP.name().equals(s)) { - return TRANSPORT.JSONP; - } else if (TRANSPORT.WEBSOCKET.name().equals(s)) { - return TRANSPORT.WEBSOCKET; - } else if (TRANSPORT.SSE.name().equals(s)) { - return TRANSPORT.SSE; - } else if (TRANSPORT.AJAX.name().equals(s)) { - return TRANSPORT.AJAX; - } else if (TRANSPORT.CLOSE.name().equals(s)) { - return TRANSPORT.CLOSE; - } else { - return UNDEFINED; - } - } - - @Override - public AtmosphereResourceEventImpl getAtmosphereResourceEvent() { - return event; - } - - @Override - public AtmosphereHandler getAtmosphereHandler() { - return atmosphereHandler; - } - - @Override - public AtmosphereResource writeOnTimeout(Object o) { - writeOnTimeout = o; - return this; - } - - @Override - public Object writeOnTimeout() { - return writeOnTimeout; - } - - @Override - public String uuid() { - return uuid; - } - - @Override - public TRANSPORT transport() { - return transport; - } - - /** - * Manually set the {@link TRANSPORT} - * - * @param transport set the {@link TRANSPORT} - * @return - */ - public AtmosphereResourceImpl transport(TRANSPORT transport) { - this.transport = transport; - return this; - } - - @Override - public AtmosphereResource resumeOnBroadcast(boolean resumeOnBroadcast) { - this.resumeOnBroadcast.set(resumeOnBroadcast); - // For legacy reason - req.setAttribute(ApplicationConfig.RESUME_ON_BROADCAST, resumeOnBroadcast); - return this; - } - - @Override - public boolean isSuspended() { - return suspended.get(); - } - - @Override - public boolean resumeOnBroadcast() { - boolean rob = resumeOnBroadcast.get(); - if (!rob) { - Boolean b = (Boolean) req.getAttribute(ApplicationConfig.RESUME_ON_BROADCAST); - return b == null ? false : b; - } - return rob; - } - - @Override - public AtmosphereResource resume() { - - if (!isSuspended()) { - logger.trace("AtmosphereResource {} not suspended {}, cannot resume it.", uuid(), action); - return this; - } - - try { - if (!isResumed.getAndSet(true) && isInScope.get()) { - suspended.set(false); - logger.trace("AtmosphereResource {} is resuming", uuid()); - - action.type(Action.TYPE.RESUME); - - // We need it as Jetty doesn't support timeout - Broadcaster b = getBroadcaster(false); - if (!b.isDestroyed() && b instanceof DefaultBroadcaster) { - ((DefaultBroadcaster) b).broadcastOnResume(this); - } - - notifyListeners(); - - try { - if (!b.isDestroyed()) { - broadcaster.removeAtmosphereResource(this); - } - } catch (IllegalStateException ex) { - logger.warn("Unable to resume", this); - logger.debug(ex.getMessage(), ex); - } - - if (b.getScope() == Broadcaster.SCOPE.REQUEST) { - logger.debug("Broadcaster's scope is set to request, destroying it {}", b.getID()); - b.destroy(); - } - - // Resuming here means we need to pull away from all other Broadcaster, if they exists. - if (config.getBroadcasterFactory() != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(this); - } - - try { - req.setAttribute(ApplicationConfig.RESUMED_ON_TIMEOUT, Boolean.FALSE); - } catch (Exception ex) { - logger.debug("Resume exception: Cannot resume an already resumed/cancelled request", ex); - } - - if (req.getAttribute(PRE_SUSPEND) == null) { - asyncSupport.action(this); - } - } else { - logger.trace("Already resumed {}", this); - return this; - } - } catch (Throwable t) { - logger.trace("Wasn't able to resume a connection {}", this, t); - } finally { - unregister(); - try { - Meteor m = (Meteor) req.getAttribute(METEOR); - if (m != null) { - m.destroy(); - } - } catch (Exception ex) { - logger.debug("Meteor resume exception: Cannot resume an already resumed/cancelled request", ex); - } - } - listeners.clear(); - return this; - } - - @Override - public AtmosphereResource suspend() { - return suspend(-1); - } - - @Override - public AtmosphereResource suspend(long timeout, TimeUnit timeunit) { - long timeoutms = -1; - if (timeunit != null) { - timeoutms = TimeUnit.MILLISECONDS.convert(timeout, timeunit); - } - - return suspend(timeoutms); - } - - @Override - public AtmosphereResource suspend(long timeout) { - - if (event.isSuspended() || disableSuspend) return this; - - if (config.isSupportSession() - && req.getSession(false) != null - && req.getSession().getMaxInactiveInterval() >= 0 - && req.getSession().getMaxInactiveInterval() * 1000 < timeout) { - throw new IllegalStateException("Cannot suspend a " + - "response longer than the session timeout. Increase the value of session-timeout in web.xml"); - } - - if (Utils.resumableTransport(transport())) { - resumeOnBroadcast.set(true); - } - - onPreSuspend(event); - - // Recheck based on preSuspend - if (event.isSuspended() || disableSuspend) return this; - - if (!event.isResumedOnTimeout()) { - suspended.set(true); - - Enumeration connection = req.getHeaders("Connection"); - if (connection == null) { - connection = req.getHeaders("connection"); - } - - if (connection != null && connection.hasMoreElements()) { - String[] e = connection.nextElement().toString().split(","); - for (String upgrade : e) { - if (upgrade.trim().equalsIgnoreCase(WEBSOCKET_UPGRADE)) { - if (!asyncSupport.supportWebSocket()) { - response.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported"); - } else { - req.setAttribute(FrameworkConfig.TRANSPORT_IN_USE, HeaderConfig.WEBSOCKET_TRANSPORT); - } - } - } - } - - if (req.getHeader(X_ATMOSPHERE_TRANSPORT) == null || transport().equals(UNDEFINED)) { - req.setAttribute(FrameworkConfig.TRANSPORT_IN_USE, LONG_POLLING_TRANSPORT); - } - - req.setAttribute(PRE_SUSPEND, "true"); - action.type(Action.TYPE.SUSPEND); - action.timeout(timeout); - - // TODO: We can possibly optimize that call by avoiding creating a Broadcaster if we are sure the Broadcaster - // is unique. - boolean isJersey = req.getAttribute(FrameworkConfig.CONTAINER_RESPONSE) != null; - - boolean skipCreation = false; - if (req.getAttribute(SKIP_BROADCASTER_CREATION) != null) { - skipCreation = true; - } - - // Null means SCOPE=REQUEST set by a Meteor - if (!skipCreation && (broadcaster == null || broadcaster.getScope() == Broadcaster.SCOPE.REQUEST) && !isJersey) { - String id = broadcaster != null ? broadcaster.getID() : ROOT_MASTER; - Class clazz = broadcaster != null ? broadcaster.getClass() : DefaultBroadcaster.class; - - broadcaster = config.getBroadcasterFactory().lookup(clazz, id, false); - if (broadcaster == null || broadcaster.getAtmosphereResources().size() > 0) { - broadcaster = config.getBroadcasterFactory().lookup(clazz, id + "/" + UUID.randomUUID(), true); - } - } - - broadcaster.addAtmosphereResource(this); - if (req.getAttribute(DefaultBroadcaster.CACHED) != null && transport() != null && Utils.resumableTransport(transport())) { - action.type(Action.TYPE.CONTINUE); - // Do nothing because we have found cached message which was written already, and the handler resumed. - logger.debug("Cached message found, not suspending {}", uuid()); - return this; - } - req.removeAttribute(PRE_SUSPEND); - register(); - notifyListeners(); - } - return this; - } - - public AtmosphereRequest getRequest(boolean enforceScope) { - if (enforceScope && !isInScope.get()) { - throw new IllegalStateException("Request object no longer" + " valid. This object has been cancelled"); - } - return req; - } - - public AtmosphereResponse getResponse(boolean enforceScope) { - if (enforceScope && !isInScope.get()) { - throw new IllegalStateException("Response object no longer valid. This object has been cancelled"); - } - return response; - } - - @Override - public AtmosphereRequest getRequest() { - return getRequest(true); - } - - @Override - public AtmosphereResponse getResponse() { - return getResponse(true); - } - - @Override - public Broadcaster getBroadcaster() { - return getBroadcaster(true); - } - - protected Broadcaster getBroadcaster(boolean autoCreate) { - if (broadcaster == null) { - throw new IllegalStateException("No Broadcaster associated with this AtmosphereResource."); - } - - String s = config.getInitParameter(ApplicationConfig.RECOVER_DEAD_BROADCASTER); - if (s != null) { - autoCreate = Boolean.parseBoolean(s); - } - - if (autoCreate && broadcaster.isDestroyed() && config.getBroadcasterFactory() != null) { - logger.debug("Broadcaster {} has been destroyed and cannot be re-used. Recreating a new one with the same name. You can turn off this" + - " mechanism by adding, in web.xml, {} set to false", broadcaster.getID(), ApplicationConfig.RECOVER_DEAD_BROADCASTER); - - Broadcaster.SCOPE scope = broadcaster.getScope(); - synchronized (this) { - String id = scope != Broadcaster.SCOPE.REQUEST ? broadcaster.getID() : broadcaster.getID() + ".recovered" + UUID.randomUUID(); - - // Another Thread may have added the Broadcaster. - broadcaster = config.getBroadcasterFactory().lookup(id, true); - broadcaster.setScope(scope); - broadcaster.addAtmosphereResource(this); - } - } - return broadcaster; - } - - @Override - public AtmosphereResourceImpl setBroadcaster(Broadcaster broadcaster) { - this.broadcaster = broadcaster; - return this; - } - - @Override - public AtmosphereConfig getAtmosphereConfig() { - return config; - } - - /** - * Return the {@link Action} which represent the state of the response, e.g. suspended, resumed or timed out. - * - * @return the {@link Action} - */ - public Action action() { - return action; - } - - /** - * Completely reset the instance to its initial state. - */ - public void reset() { - isResumed.set(false); - isCancelled.set(false); - isInScope.set(true); - isSuspendEvent.set(false); - listeners.clear(); - action.type(Action.TYPE.CREATED); - } - - /** - * Protect the object from being used after it got cancelled. - * - * @param isInScope - */ - public void setIsInScope(boolean isInScope) { - this.isInScope.set(isInScope); - } - - /** - * Check if the {@link AtmosphereRequest} still is valid. - * - * @return true if the {@link AtmosphereRequest} still is valid - */ - public boolean isInScope() { - return isInScope.get(); - } - - /** - * Set the {@link Serializer} used to write broadcasted objects. - * - * @param s - */ - @Override - public AtmosphereResource setSerializer(Serializer s) { - serializer = s; - return this; - } - - @Override - public boolean isResumed() { - return isResumed.get(); - } - - @Override - public boolean isCancelled() { - return isCancelled.get(); - } - - @Override - public AtmosphereResource write(String s) { - response.write(s); - if (resumeOnBroadcast()) { - resume(); - } - return this; - } - - @Override - public AtmosphereResource write(byte[] o) { - response.write(o); - if (resumeOnBroadcast()) { - resume(); - } - return this; - } - - @Override - public Serializer getSerializer() { - return serializer; - } - - /** - * Add a {@link AtmosphereResourceEventListener}. - * - * @param e an instance of AtmosphereResourceEventListener - */ - @Override - public AtmosphereResource addEventListener(AtmosphereResourceEventListener e) { - if (listeners.contains(e)) return this; - listeners.add(e); - return this; - } - - @Override - public AtmosphereResource removeEventListener(AtmosphereResourceEventListener e) { - listeners.remove(e); - return this; - } - - @Override - public AtmosphereResource removeEventListeners() { - listeners.clear(); - return this; - } - - @Override - public AtmosphereResource notifyListeners() { - notifyListeners(event); - return this; - } - - @Override - public AtmosphereResource notifyListeners(AtmosphereResourceEvent event) { - if (listeners.isEmpty()) { - logger.trace("No listener with {}", uuid); - return this; - } - logger.trace("Invoking listener {} for {}", listeners, uuid); - - Action oldAction = action; - try { - if (HeartbeatAtmosphereResourceEvent.class.isAssignableFrom(event.getClass())) { - onHeartbeat(event); - } else if (event.isClosedByApplication()) { - onClose(event); - } else if (event.isCancelled() || event.isClosedByClient()) { - if (!disconnected.getAndSet(true)) { - onDisconnect(event); - } else { - logger.trace("Skipping notification, already disconnected {}", event.getResource().uuid()); - } - } else if (event.isResuming() || event.isResumedOnTimeout()) { - onResume(event); - } else if (!isSuspendEvent.getAndSet(true) && event.isSuspended()) { - onSuspend(event); - } else if (event.throwable() != null) { - onThrowable(event); - } else { - onBroadcast(event); - } - - if (oldAction.type() != action.type()) { - action().type(Action.TYPE.CREATED); - } - } catch (Throwable t) { - AtmosphereResourceEventImpl.class.cast(event).setThrowable(t); - if (event.isSuspended()) { - logger.warn("Exception during suspend() operation {}", t); - broadcaster.removeAtmosphereResource(this); - if (config.getBroadcasterFactory() != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(this); - } - } else { - logger.debug("Listener error {}", t); - } - - try { - onThrowable(event); - } catch (Throwable t2) { - logger.warn("Listener error {}", t2); - } - } - return this; - } - - /** - * Notify {@link AtmosphereResourceEventListener} thah an unexpected exception occured. - * - * @pram a {@link Throwable} - */ - public void onThrowable(Throwable t) { - onThrowable(new AtmosphereResourceEventImpl(this, false, false, t)); - } - - void onThrowable(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onThrowable(e); - } - } - - /** - *

- * Notifies to all listeners that a heartbeat has been sent. - *

- * - * @param e the event - */ - void onHeartbeat(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onHeartbeat(e); - } - } - - void onSuspend(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - if (disableSuspendEvent) { - if (!AllowInterceptor.class.isAssignableFrom(r.getClass())) { - continue; - } - } - r.onSuspend(e); - } - } - - void onPreSuspend(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - if (disableSuspendEvent) { - if (!AllowInterceptor.class.isAssignableFrom(r.getClass())) { - continue; - } - } - r.onPreSuspend(e); - } - } - - void onResume(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onResume(e); - } - } - - void onDisconnect(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onDisconnect(e); - if (transport.equals(TRANSPORT.WEBSOCKET) && WebSocketEventListener.class.isAssignableFrom(r.getClass())) { - WebSocketEventListener.class.cast(r).onDisconnect(new WebSocketEventListener.WebSocketEvent(1005, CLOSE, webSocket)); - } - } - } - - void onBroadcast(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onBroadcast(e); - } - } - - void onClose(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onClose(e); - if (transport.equals(TRANSPORT.WEBSOCKET) && WebSocketEventListener.class.isAssignableFrom(r.getClass())) { - WebSocketEventListener.class.cast(r).onClose(new WebSocketEventListener.WebSocketEvent(1005, CLOSE, webSocket)); - } - } - } - - public ConcurrentLinkedQueue atmosphereResourceEventListener() { - return listeners; - } - - public AtmosphereResourceImpl atmosphereHandler(AtmosphereHandler atmosphereHandler) { - this.atmosphereHandler = atmosphereHandler; - return this; - } - - public void cancel() throws IOException { - try { - if (!isCancelled.getAndSet(true)) { - suspended.set(false); - logger.trace("Cancelling {}", uuid); - - if (config.getBroadcasterFactory() != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(this); - if (transport.equals(TRANSPORT.WEBSOCKET)) { - String parentUUID = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID); - AtmosphereResource p = config.resourcesFactory().find(parentUUID); - if (p != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(p); - } - } - } - - asyncSupport.complete(this); - - try { - Meteor m = (Meteor) req.getAttribute(AtmosphereResourceImpl.METEOR); - if (m != null) { - m.destroy(); - } - } catch (Exception ex) { - logger.trace("Meteor exception {}", ex); - } - - SessionTimeoutSupport.restoreTimeout(req); - action.type(Action.TYPE.CANCELLED); - if (asyncSupport != null) asyncSupport.action(this); - // We must close the underlying WebSocket as well. - if (AtmosphereResponse.class.isAssignableFrom(response.getClass())) { - AtmosphereResponse.class.cast(response).close(); - AtmosphereResponse.class.cast(response).destroy(); - } - - if (AtmosphereRequest.class.isAssignableFrom(req.getClass())) { - AtmosphereRequest.class.cast(req).destroy(); - } - event.destroy(); - } - } finally { - unregister(); - } - } - - private void unregister() { - config.resourcesFactory().remove(uuid); - } - - public void _destroy() { - try { - if (!isCancelled.get()) { - if (broadcaster != null) broadcaster.removeAtmosphereResource(this); - - if (config.getBroadcasterFactory() != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(this); - } - } - unregister(); - removeEventListeners(); - } catch (Throwable t) { - logger.trace("destroyResource", t); - } finally { - unregister(); - webSocket = null; - } - } - - @Override - public String toString() { - try { - return "AtmosphereResource{" + - "\n\t uuid=" + uuid + - ",\n\t transport=" + transport() + - ",\n\t isInScope=" + isInScope + - ",\n\t isResumed=" + isResumed() + - ",\n\t isCancelled=" + isCancelled() + - ",\n\t isSuspended=" + isSuspended() + - ",\n\t broadcaster=" + broadcaster.getID() + " size: " + broadcaster.getAtmosphereResources().size() + - ",\n\t isClosedByClient=" + (event != null ? event.isClosedByClient() : false) + - ",\n\t isClosedByApplication=" + (event != null ? event.isClosedByApplication() : false) + - ",\n\t action=" + action + - '}'; - } catch (NullPointerException ex) { - // Prevent logger - return "AtmosphereResourceImpl{" + uuid + "}"; - } - } - - public AtmosphereResourceImpl disableSuspend(boolean disableSuspend) { - this.disableSuspend = disableSuspend; - return this; - } - - @Override - public HttpSession session(boolean create) { - if (config.isSupportSession() && session == null) { - // http://java.net/jira/browse/GLASSFISH-18856 - session = req.getSession(create); - } - return session; - } - - @Override - public void close() throws IOException { - event.setCloseByApplication(true); - notifyListeners(); - cancel(); - if (webSocket != null) { - webSocket.close(); - } - } - - public void dirtyClose() { - try { - event.setCancelled(true); - notifyListeners(); - cancel(); - if (webSocket != null) { - webSocket.close(); - } - } catch (IOException ex) { - logger.trace("", ex); - } - } - - @Override - public AtmosphereResource forceBinaryWrite(boolean forceBinaryWrite) { - this.forceBinaryWrite = forceBinaryWrite; - return this; - } - - @Override - public boolean forceBinaryWrite() { - return forceBinaryWrite; - } - - @Override - public HttpSession session() { - return session(true); - } - - public AtmosphereResourceImpl session(HttpSession session) { - this.session = session; - return this; - } - - public AtmosphereResourceImpl cloneState(AtmosphereResource r) { - for (AtmosphereResourceEventListener l : AtmosphereResourceImpl.class.cast(r).atmosphereResourceEventListener()) { - addEventListener(l); - } - AtmosphereResourceImpl.class.cast(r).session(r.session()); - setBroadcaster(r.getBroadcaster()); - atmosphereHandler(r.getAtmosphereHandler()); - return this; - } - - public ConcurrentLinkedQueue listeners() { - return listeners; - } - - /** - * Disable invocation of {@link AtmosphereResourceEventListener#onSuspend(AtmosphereResourceEvent)} and - * {@link AtmosphereResourceEventListener#onPreSuspend(AtmosphereResourceEvent)}. You normally disable those events - * after the first onSuspend has been called so all transports behave the same way. - *
- * {@link AtmosphereResourceEventListener} marked with {@link org.atmosphere.interceptor.AllowInterceptor} will not - * be affected by this property. - * - * @param disableSuspendEvent - * @return this - */ - public AtmosphereResourceImpl disableSuspendEvent(boolean disableSuspendEvent) { - this.disableSuspendEvent = disableSuspendEvent; - return this; - } - - /** - * Return true if {@link AtmosphereResourceEventListener#onSuspend(AtmosphereResourceEvent)} and - * {@link AtmosphereResourceEventListener#onPreSuspend(AtmosphereResourceEvent)} events are disabled. - * - * @return true if disabled - */ - public boolean disableSuspendEvent() { - return disableSuspendEvent; - } - - public WebSocket webSocket() { - return webSocket; - } - - public AtmosphereResourceImpl webSocket(WebSocket webSocket) { - this.webSocket = webSocket; - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - AtmosphereResourceImpl that = (AtmosphereResourceImpl) o; - - if (!uuid.equals(that.uuid)) return false; - - return true; - } -} diff --git a/All/Genesis-NP/Genesis#369/old/AtmosphereResourceImpl.java b/All/Genesis-NP/Genesis#369/old/AtmosphereResourceImpl.java deleted file mode 100755 index 8e558ed..0000000 --- a/All/Genesis-NP/Genesis#369/old/AtmosphereResourceImpl.java +++ /dev/null @@ -1,945 +0,0 @@ -/* - * Copyright 2014 Jeanfrancois Arcand - * - * 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.atmosphere.cpr; - -import org.atmosphere.interceptor.AllowInterceptor; -import org.atmosphere.util.Utils; -import org.atmosphere.websocket.WebSocket; -import org.atmosphere.websocket.WebSocketEventListener; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.http.HttpSession; -import java.io.IOException; -import java.util.Enumeration; -import java.util.UUID; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -import static org.atmosphere.cpr.ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID; -import static org.atmosphere.cpr.AtmosphereResource.TRANSPORT.UNDEFINED; -import static org.atmosphere.cpr.Broadcaster.ROOT_MASTER; -import static org.atmosphere.cpr.HeaderConfig.LONG_POLLING_TRANSPORT; -import static org.atmosphere.cpr.HeaderConfig.WEBSOCKET_UPGRADE; -import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_ERROR; -import static org.atmosphere.cpr.HeaderConfig.X_ATMOSPHERE_TRANSPORT; -import static org.atmosphere.websocket.WebSocketEventListener.WebSocketEvent.TYPE.CLOSE; - -/** - * {@link AtmosphereResource} implementation for supporting {@link AtmosphereRequest} - * and {@link AtmosphereResponse}. - * - * @author Jeanfrancois Arcand - */ -public class AtmosphereResourceImpl implements AtmosphereResource { - - private static final Logger logger = LoggerFactory.getLogger(AtmosphereResourceImpl.class); - - public static final String PRE_SUSPEND = AtmosphereResourceImpl.class.getName() + ".preSuspend"; - public static final String SKIP_BROADCASTER_CREATION = AtmosphereResourceImpl.class.getName() + ".skipBroadcasterCreation"; - public static final String METEOR = Meteor.class.getName(); - - private AtmosphereRequest req; - private AtmosphereResponse response; - private final Action action = new Action(); - protected Broadcaster broadcaster; - private AtmosphereConfig config; - protected AsyncSupport asyncSupport; - private Serializer serializer; - private final AtomicBoolean isInScope = new AtomicBoolean(true); - private AtmosphereResourceEventImpl event; - private final AtomicBoolean isResumed = new AtomicBoolean(); - private final AtomicBoolean isCancelled = new AtomicBoolean(); - private final AtomicBoolean resumeOnBroadcast = new AtomicBoolean(); - private Object writeOnTimeout = null; - private boolean disableSuspend = false; - private final AtomicBoolean disconnected = new AtomicBoolean(); - - private final ConcurrentLinkedQueue listeners = - new ConcurrentLinkedQueue(); - - private final AtomicBoolean isSuspendEvent = new AtomicBoolean(); - private AtmosphereHandler atmosphereHandler; - private String uuid; - protected HttpSession session; - private boolean disableSuspendEvent; - private TRANSPORT transport; - private boolean forceBinaryWrite; - private final AtomicBoolean suspended = new AtomicBoolean(); - private WebSocket webSocket; - - public AtmosphereResourceImpl() { - } - - @Deprecated - public AtmosphereResourceImpl(AtmosphereConfig config, Broadcaster broadcaster, - AtmosphereRequest req, AtmosphereResponse response, - AsyncSupport asyncSupport, AtmosphereHandler atmosphereHandler) { - initialize(config, broadcaster, req, response, asyncSupport, atmosphereHandler); - } - - /** - * Initialize an {@link AtmosphereResource}. - * - * @param config The {@link org.atmosphere.cpr.AtmosphereConfig} - * @param broadcaster The {@link org.atmosphere.cpr.Broadcaster}. - * @param req The {@link AtmosphereRequest} - * @param response The {@link AtmosphereResource} - * @param asyncSupport The {@link AsyncSupport} - * @param atmosphereHandler The {@link AtmosphereHandler} - * @return this - */ - @Override - public AtmosphereResource initialize(AtmosphereConfig config, Broadcaster broadcaster, - AtmosphereRequest req, AtmosphereResponse response, - AsyncSupport asyncSupport, AtmosphereHandler atmosphereHandler) { - this.req = req; - this.response = response; - this.broadcaster = broadcaster; - this.config = config; - this.asyncSupport = asyncSupport; - this.atmosphereHandler = atmosphereHandler; - this.event = new AtmosphereResourceEventImpl(this); - - String s = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID); - if (s == null) { - s = response.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); - if (s == null) { - String tmp = req.getHeader(HeaderConfig.X_ATMOSPHERE_TRACKING_ID); - s = !tmp.equalsIgnoreCase("0") ? tmp : null; - } - } - uuid = s == null ? UUID.randomUUID().toString() : s; - - if (config.isSupportSession()) { - // Keep a reference to an HttpSession in case the associated request get recycled by the underlying container. - try { - session = req.getSession(true); - } catch (NullPointerException ex) { - // http://java.net/jira/browse/GLASSFISH-18856 - logger.trace("http://java.net/jira/browse/GLASSFISH-18856", ex); - } - } - transport = configureTransport(); - return this; - } - - - protected void register() { - if (!Utils.pollableTransport(transport()) && !Utils.webSocketMessage(this)) { - config.resourcesFactory().registerUuidForFindCandidate(this); - } - } - - private TRANSPORT configureTransport() { - if (req == null) return UNDEFINED; - - String s = req.getHeader(HeaderConfig.X_ATMOSPHERE_TRANSPORT); - if (s == null) return UNDEFINED; - - s = s.replace("-", "_").toUpperCase(); - if (TRANSPORT.POLLING.name().equals(s)) { - return TRANSPORT.POLLING; - } else if (TRANSPORT.LONG_POLLING.name().equals(s)) { - return TRANSPORT.LONG_POLLING; - } else if (TRANSPORT.STREAMING.name().equals(s)) { - return TRANSPORT.STREAMING; - } else if (TRANSPORT.JSONP.name().equals(s)) { - return TRANSPORT.JSONP; - } else if (TRANSPORT.WEBSOCKET.name().equals(s)) { - return TRANSPORT.WEBSOCKET; - } else if (TRANSPORT.SSE.name().equals(s)) { - return TRANSPORT.SSE; - } else if (TRANSPORT.AJAX.name().equals(s)) { - return TRANSPORT.AJAX; - } else if (TRANSPORT.CLOSE.name().equals(s)) { - return TRANSPORT.CLOSE; - } else { - return UNDEFINED; - } - } - - @Override - public AtmosphereResourceEventImpl getAtmosphereResourceEvent() { - return event; - } - - @Override - public AtmosphereHandler getAtmosphereHandler() { - return atmosphereHandler; - } - - @Override - public AtmosphereResource writeOnTimeout(Object o) { - writeOnTimeout = o; - return this; - } - - @Override - public Object writeOnTimeout() { - return writeOnTimeout; - } - - @Override - public String uuid() { - return uuid; - } - - @Override - public TRANSPORT transport() { - return transport; - } - - /** - * Manually set the {@link TRANSPORT} - * - * @param transport set the {@link TRANSPORT} - * @return - */ - public AtmosphereResourceImpl transport(TRANSPORT transport) { - this.transport = transport; - return this; - } - - @Override - public AtmosphereResource resumeOnBroadcast(boolean resumeOnBroadcast) { - this.resumeOnBroadcast.set(resumeOnBroadcast); - // For legacy reason - req.setAttribute(ApplicationConfig.RESUME_ON_BROADCAST, resumeOnBroadcast); - return this; - } - - @Override - public boolean isSuspended() { - return suspended.get(); - } - - @Override - public boolean resumeOnBroadcast() { - boolean rob = resumeOnBroadcast.get(); - if (!rob) { - Boolean b = (Boolean) req.getAttribute(ApplicationConfig.RESUME_ON_BROADCAST); - return b == null ? false : b; - } - return rob; - } - - @Override - public AtmosphereResource resume() { - - if (!isSuspended()) { - logger.trace("AtmosphereResource {} not suspended {}, cannot resume it.", uuid(), action); - return this; - } - - try { - if (!isResumed.getAndSet(true) && isInScope.get()) { - suspended.set(false); - logger.trace("AtmosphereResource {} is resuming", uuid()); - - action.type(Action.TYPE.RESUME); - - // We need it as Jetty doesn't support timeout - Broadcaster b = getBroadcaster(false); - if (!b.isDestroyed() && b instanceof DefaultBroadcaster) { - ((DefaultBroadcaster) b).broadcastOnResume(this); - } - - notifyListeners(); - - try { - if (!b.isDestroyed()) { - broadcaster.removeAtmosphereResource(this); - } - } catch (IllegalStateException ex) { - logger.warn("Unable to resume", this); - logger.debug(ex.getMessage(), ex); - } - - if (b.getScope() == Broadcaster.SCOPE.REQUEST) { - logger.debug("Broadcaster's scope is set to request, destroying it {}", b.getID()); - b.destroy(); - } - - // Resuming here means we need to pull away from all other Broadcaster, if they exists. - if (config.getBroadcasterFactory() != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(this); - } - - try { - req.setAttribute(ApplicationConfig.RESUMED_ON_TIMEOUT, Boolean.FALSE); - } catch (Exception ex) { - logger.debug("Resume exception: Cannot resume an already resumed/cancelled request", ex); - } - - if (req.getAttribute(PRE_SUSPEND) == null) { - asyncSupport.action(this); - } - } else { - logger.trace("Already resumed {}", this); - return this; - } - } catch (Throwable t) { - logger.trace("Wasn't able to resume a connection {}", this, t); - } finally { - unregister(); - try { - Meteor m = (Meteor) req.getAttribute(METEOR); - if (m != null) { - m.destroy(); - } - } catch (Exception ex) { - logger.debug("Meteor resume exception: Cannot resume an already resumed/cancelled request", ex); - } - } - listeners.clear(); - return this; - } - - @Override - public AtmosphereResource suspend() { - return suspend(-1); - } - - @Override - public AtmosphereResource suspend(long timeout, TimeUnit timeunit) { - long timeoutms = -1; - if (timeunit != null) { - timeoutms = TimeUnit.MILLISECONDS.convert(timeout, timeunit); - } - - return suspend(timeoutms); - } - - @Override - public AtmosphereResource suspend(long timeout) { - - if (event.isSuspended() || disableSuspend) return this; - - if (config.isSupportSession() - && req.getSession(false) != null - && req.getSession().getMaxInactiveInterval() >= 0 - && req.getSession().getMaxInactiveInterval() * 1000 < timeout) { - throw new IllegalStateException("Cannot suspend a " + - "response longer than the session timeout. Increase the value of session-timeout in web.xml"); - } - - if (Utils.resumableTransport(transport())) { - resumeOnBroadcast.set(true); - } - - onPreSuspend(event); - - // Recheck based on preSuspend - if (event.isSuspended() || disableSuspend) return this; - - if (!event.isResumedOnTimeout()) { - suspended.set(true); - - Enumeration connection = req.getHeaders("Connection"); - if (connection == null) { - connection = req.getHeaders("connection"); - } - - if (connection != null && connection.hasMoreElements()) { - String[] e = connection.nextElement().toString().split(","); - for (String upgrade : e) { - if (upgrade.trim().equalsIgnoreCase(WEBSOCKET_UPGRADE)) { - if (!asyncSupport.supportWebSocket()) { - response.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported"); - } else { - req.setAttribute(FrameworkConfig.TRANSPORT_IN_USE, HeaderConfig.WEBSOCKET_TRANSPORT); - } - } - } - } - - if (req.getHeader(X_ATMOSPHERE_TRANSPORT) == null || transport().equals(UNDEFINED)) { - req.setAttribute(FrameworkConfig.TRANSPORT_IN_USE, LONG_POLLING_TRANSPORT); - } - - req.setAttribute(PRE_SUSPEND, "true"); - action.type(Action.TYPE.SUSPEND); - action.timeout(timeout); - - // TODO: We can possibly optimize that call by avoiding creating a Broadcaster if we are sure the Broadcaster - // is unique. - boolean isJersey = req.getAttribute(FrameworkConfig.CONTAINER_RESPONSE) != null; - - boolean skipCreation = false; - if (req.getAttribute(SKIP_BROADCASTER_CREATION) != null) { - skipCreation = true; - } - - // Null means SCOPE=REQUEST set by a Meteor - if (!skipCreation && (broadcaster == null || broadcaster.getScope() == Broadcaster.SCOPE.REQUEST) && !isJersey) { - String id = broadcaster != null ? broadcaster.getID() : ROOT_MASTER; - Class clazz = broadcaster != null ? broadcaster.getClass() : DefaultBroadcaster.class; - - broadcaster = config.getBroadcasterFactory().lookup(clazz, id, false); - if (broadcaster == null || broadcaster.getAtmosphereResources().size() > 0) { - broadcaster = config.getBroadcasterFactory().lookup(clazz, id + "/" + UUID.randomUUID(), true); - } - } - - broadcaster.addAtmosphereResource(this); - if (req.getAttribute(DefaultBroadcaster.CACHED) != null && transport() != null && Utils.resumableTransport(transport())) { - action.type(Action.TYPE.CONTINUE); - // Do nothing because we have found cached message which was written already, and the handler resumed. - logger.debug("Cached message found, not suspending {}", uuid()); - return this; - } - req.removeAttribute(PRE_SUSPEND); - register(); - notifyListeners(); - } - return this; - } - - public AtmosphereRequest getRequest(boolean enforceScope) { - if (enforceScope && !isInScope.get()) { - throw new IllegalStateException("Request object no longer" + " valid. This object has been cancelled"); - } - return req; - } - - public AtmosphereResponse getResponse(boolean enforceScope) { - if (enforceScope && !isInScope.get()) { - throw new IllegalStateException("Response object no longer valid. This object has been cancelled"); - } - return response; - } - - @Override - public AtmosphereRequest getRequest() { - return getRequest(true); - } - - @Override - public AtmosphereResponse getResponse() { - return getResponse(true); - } - - @Override - public Broadcaster getBroadcaster() { - return getBroadcaster(true); - } - - protected Broadcaster getBroadcaster(boolean autoCreate) { - if (broadcaster == null) { - throw new IllegalStateException("No Broadcaster associated with this AtmosphereResource."); - } - - String s = config.getInitParameter(ApplicationConfig.RECOVER_DEAD_BROADCASTER); - if (s != null) { - autoCreate = Boolean.parseBoolean(s); - } - - if (autoCreate && broadcaster.isDestroyed() && config.getBroadcasterFactory() != null) { - logger.debug("Broadcaster {} has been destroyed and cannot be re-used. Recreating a new one with the same name. You can turn off this" + - " mechanism by adding, in web.xml, {} set to false", broadcaster.getID(), ApplicationConfig.RECOVER_DEAD_BROADCASTER); - - Broadcaster.SCOPE scope = broadcaster.getScope(); - synchronized (this) { - String id = scope != Broadcaster.SCOPE.REQUEST ? broadcaster.getID() : broadcaster.getID() + ".recovered" + UUID.randomUUID(); - - // Another Thread may have added the Broadcaster. - broadcaster = config.getBroadcasterFactory().lookup(id, true); - broadcaster.setScope(scope); - broadcaster.addAtmosphereResource(this); - } - } - return broadcaster; - } - - @Override - public AtmosphereResourceImpl setBroadcaster(Broadcaster broadcaster) { - this.broadcaster = broadcaster; - return this; - } - - @Override - public AtmosphereConfig getAtmosphereConfig() { - return config; - } - - /** - * Return the {@link Action} which represent the state of the response, e.g. suspended, resumed or timed out. - * - * @return the {@link Action} - */ - public Action action() { - return action; - } - - /** - * Completely reset the instance to its initial state. - */ - public void reset() { - isResumed.set(false); - isCancelled.set(false); - isInScope.set(true); - isSuspendEvent.set(false); - listeners.clear(); - action.type(Action.TYPE.CREATED); - } - - /** - * Protect the object from being used after it got cancelled. - * - * @param isInScope - */ - public void setIsInScope(boolean isInScope) { - this.isInScope.set(isInScope); - } - - /** - * Check if the {@link AtmosphereRequest} still is valid. - * - * @return true if the {@link AtmosphereRequest} still is valid - */ - public boolean isInScope() { - return isInScope.get(); - } - - /** - * Set the {@link Serializer} used to write broadcasted objects. - * - * @param s - */ - @Override - public AtmosphereResource setSerializer(Serializer s) { - serializer = s; - return this; - } - - @Override - public boolean isResumed() { - return isResumed.get(); - } - - @Override - public boolean isCancelled() { - return isCancelled.get(); - } - - @Override - public AtmosphereResource write(String s) { - response.write(s); - if (resumeOnBroadcast()) { - resume(); - } - return this; - } - - @Override - public AtmosphereResource write(byte[] o) { - response.write(o); - if (resumeOnBroadcast()) { - resume(); - } - return this; - } - - @Override - public Serializer getSerializer() { - return serializer; - } - - /** - * Add a {@link AtmosphereResourceEventListener}. - * - * @param e an instance of AtmosphereResourceEventListener - */ - @Override - public AtmosphereResource addEventListener(AtmosphereResourceEventListener e) { - if (listeners.contains(e)) return this; - listeners.add(e); - return this; - } - - @Override - public AtmosphereResource removeEventListener(AtmosphereResourceEventListener e) { - listeners.remove(e); - return this; - } - - @Override - public AtmosphereResource removeEventListeners() { - listeners.clear(); - return this; - } - - @Override - public AtmosphereResource notifyListeners() { - notifyListeners(event); - return this; - } - - @Override - public AtmosphereResource notifyListeners(AtmosphereResourceEvent event) { - if (listeners.isEmpty()) { - logger.trace("No listener with {}", uuid); - return this; - } - logger.trace("Invoking listener {} for {}", listeners, uuid); - - Action oldAction = action; - try { - if (HeartbeatAtmosphereResourceEvent.class.isAssignableFrom(event.getClass())) { - onHeartbeat(event); - } else if (event.isClosedByApplication()) { - onClose(event); - } else if (event.isCancelled() || event.isClosedByClient()) { - if (!disconnected.getAndSet(true)) { - onDisconnect(event); - } else { - logger.trace("Skipping notification, already disconnected {}", event.getResource().uuid()); - } - } else if (event.isResuming() || event.isResumedOnTimeout()) { - onResume(event); - } else if (!isSuspendEvent.getAndSet(true) && event.isSuspended()) { - onSuspend(event); - } else if (event.throwable() != null) { - onThrowable(event); - } else { - onBroadcast(event); - } - - if (oldAction.type() != action.type()) { - action().type(Action.TYPE.CREATED); - } - } catch (Throwable t) { - AtmosphereResourceEventImpl.class.cast(event).setThrowable(t); - if (event.isSuspended()) { - logger.warn("Exception during suspend() operation {}", t); - broadcaster.removeAtmosphereResource(this); - if (config.getBroadcasterFactory() != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(this); - } - } else { - logger.debug("Listener error {}", t); - } - - try { - onThrowable(event); - } catch (Throwable t2) { - logger.warn("Listener error {}", t2); - } - } - return this; - } - - /** - * Notify {@link AtmosphereResourceEventListener} thah an unexpected exception occured. - * - * @pram a {@link Throwable} - */ - public void onThrowable(Throwable t) { - onThrowable(new AtmosphereResourceEventImpl(this, false, false, t)); - } - - void onThrowable(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onThrowable(e); - } - } - - /** - *

- * Notifies to all listeners that a heartbeat has been sent. - *

- * - * @param e the event - */ - void onHeartbeat(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onHeartbeat(e); - } - } - - void onSuspend(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - if (disableSuspendEvent) { - if (!AllowInterceptor.class.isAssignableFrom(r.getClass())) { - continue; - } - } - r.onSuspend(e); - } - } - - void onPreSuspend(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - if (disableSuspendEvent) { - if (!AllowInterceptor.class.isAssignableFrom(r.getClass())) { - continue; - } - } - r.onPreSuspend(e); - } - } - - void onResume(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onResume(e); - } - } - - void onDisconnect(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onDisconnect(e); - if (transport.equals(TRANSPORT.WEBSOCKET) && WebSocketEventListener.class.isAssignableFrom(r.getClass())) { - WebSocketEventListener.class.cast(r).onDisconnect(new WebSocketEventListener.WebSocketEvent(1005, CLOSE, webSocket)); - } - } - } - - void onBroadcast(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onBroadcast(e); - } - } - - void onClose(AtmosphereResourceEvent e) { - for (AtmosphereResourceEventListener r : listeners) { - r.onClose(e); - if (transport.equals(TRANSPORT.WEBSOCKET) && WebSocketEventListener.class.isAssignableFrom(r.getClass())) { - WebSocketEventListener.class.cast(r).onClose(new WebSocketEventListener.WebSocketEvent(1005, CLOSE, webSocket)); - } - } - } - - public ConcurrentLinkedQueue atmosphereResourceEventListener() { - return listeners; - } - - public AtmosphereResourceImpl atmosphereHandler(AtmosphereHandler atmosphereHandler) { - this.atmosphereHandler = atmosphereHandler; - return this; - } - - public void cancel() throws IOException { - try { - if (!isCancelled.getAndSet(true)) { - suspended.set(false); - logger.trace("Cancelling {}", uuid); - - if (config.getBroadcasterFactory() != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(this); - if (transport.equals(TRANSPORT.WEBSOCKET)) { - String parentUUID = (String) req.getAttribute(SUSPENDED_ATMOSPHERE_RESOURCE_UUID); - AtmosphereResource p = config.resourcesFactory().find(parentUUID); - if (p != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(p); - } - } - } - - asyncSupport.complete(this); - - try { - Meteor m = (Meteor) req.getAttribute(AtmosphereResourceImpl.METEOR); - if (m != null) { - m.destroy(); - } - } catch (Exception ex) { - logger.trace("Meteor exception {}", ex); - } - - SessionTimeoutSupport.restoreTimeout(req); - action.type(Action.TYPE.CANCELLED); - if (asyncSupport != null) asyncSupport.action(this); - // We must close the underlying WebSocket as well. - if (AtmosphereResponse.class.isAssignableFrom(response.getClass())) { - AtmosphereResponse.class.cast(response).close(); - AtmosphereResponse.class.cast(response).destroy(); - } - - if (AtmosphereRequest.class.isAssignableFrom(req.getClass())) { - AtmosphereRequest.class.cast(req).destroy(); - } - event.destroy(); - } - } finally { - unregister(); - } - } - - private void unregister() { - config.resourcesFactory().remove(uuid); - } - - public void _destroy() { - try { - if (!isCancelled.get()) { - if (broadcaster != null) broadcaster.removeAtmosphereResource(this); - - if (config.getBroadcasterFactory() != null) { - config.getBroadcasterFactory().removeAllAtmosphereResource(this); - } - } - unregister(); - removeEventListeners(); - } catch (Throwable t) { - logger.trace("destroyResource", t); - } finally { - unregister(); - webSocket = null; - } - } - - @Override - public String toString() { - try { - return "AtmosphereResource{" + - "\n\t uuid=" + uuid + - ",\n\t transport=" + transport() + - ",\n\t isInScope=" + isInScope + - ",\n\t isResumed=" + isResumed() + - ",\n\t isCancelled=" + isCancelled() + - ",\n\t isSuspended=" + isSuspended() + - ",\n\t broadcaster=" + broadcaster.getID() + " size: " + broadcaster.getAtmosphereResources().size() + - ",\n\t isClosedByClient=" + (event != null ? event.isClosedByClient() : false) + - ",\n\t isClosedByApplication=" + (event != null ? event.isClosedByApplication() : false) + - ",\n\t action=" + action + - '}'; - } catch (NullPointerException ex) { - // Prevent logger - return "AtmosphereResourceImpl{" + uuid + "}"; - } - } - - public AtmosphereResourceImpl disableSuspend(boolean disableSuspend) { - this.disableSuspend = disableSuspend; - return this; - } - - @Override - public HttpSession session(boolean create) { - if (config.isSupportSession() && session == null) { - // http://java.net/jira/browse/GLASSFISH-18856 - session = req.getSession(create); - } - return session; - } - - @Override - public void close() throws IOException { - event.setCloseByApplication(true); - notifyListeners(); - cancel(); - if (webSocket != null) { - webSocket.close(); - } - } - - public void dirtyClose() { - try { - event.setCancelled(true); - notifyListeners(); - cancel(); - if (webSocket != null) { - webSocket.close(); - } - } catch (IOException ex) { - logger.trace("", ex); - } - } - - @Override - public AtmosphereResource forceBinaryWrite(boolean forceBinaryWrite) { - this.forceBinaryWrite = forceBinaryWrite; - return this; - } - - @Override - public boolean forceBinaryWrite() { - return forceBinaryWrite; - } - - @Override - public HttpSession session() { - return session(true); - } - - public AtmosphereResourceImpl session(HttpSession session) { - this.session = session; - return this; - } - - public AtmosphereResourceImpl cloneState(AtmosphereResource r) { - for (AtmosphereResourceEventListener l : AtmosphereResourceImpl.class.cast(r).atmosphereResourceEventListener()) { - addEventListener(l); - } - AtmosphereResourceImpl.class.cast(r).session(r.session()); - setBroadcaster(r.getBroadcaster()); - atmosphereHandler(r.getAtmosphereHandler()); - return this; - } - - public ConcurrentLinkedQueue listeners() { - return listeners; - } - - /** - * Disable invocation of {@link AtmosphereResourceEventListener#onSuspend(AtmosphereResourceEvent)} and - * {@link AtmosphereResourceEventListener#onPreSuspend(AtmosphereResourceEvent)}. You normally disable those events - * after the first onSuspend has been called so all transports behave the same way. - *
- * {@link AtmosphereResourceEventListener} marked with {@link org.atmosphere.interceptor.AllowInterceptor} will not - * be affected by this property. - * - * @param disableSuspendEvent - * @return this - */ - public AtmosphereResourceImpl disableSuspendEvent(boolean disableSuspendEvent) { - this.disableSuspendEvent = disableSuspendEvent; - return this; - } - - /** - * Return true if {@link AtmosphereResourceEventListener#onSuspend(AtmosphereResourceEvent)} and - * {@link AtmosphereResourceEventListener#onPreSuspend(AtmosphereResourceEvent)} events are disabled. - * - * @return true if disabled - */ - public boolean disableSuspendEvent() { - return disableSuspendEvent; - } - - public WebSocket webSocket() { - return webSocket; - } - - public AtmosphereResourceImpl webSocket(WebSocket webSocket) { - this.webSocket = webSocket; - return this; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - AtmosphereResourceImpl that = (AtmosphereResourceImpl) o; - - if (!uuid.equals(that.uuid)) return false; - - return true; - } -} diff --git a/All/Genesis-NP/Genesis#369/pair.info b/All/Genesis-NP/Genesis#369/pair.info deleted file mode 100755 index bd4f87f..0000000 --- a/All/Genesis-NP/Genesis#369/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:369 -SATName:Genesis -modifiedFPath:modules/cpr/src/main/java/org/atmosphere/cpr/AtmosphereResourceImpl.java -comSha:28ba4cee88e6eb983244cb85dcd91e5f150f7e32 -parentComSha:28ba4cee88e6eb983244cb85dcd91e5f150f7e32^1 -githubUrl:https://github.com/Atmosphere/atmosphere -repoName:Atmosphere#atmosphere \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#374/comMsg.txt b/All/Genesis-NP/Genesis#374/comMsg.txt deleted file mode 100755 index 4d2fc02..0000000 --- a/All/Genesis-NP/Genesis#374/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Avoid NPE in SSEAtmosphereInterceptor diff --git a/All/Genesis-NP/Genesis#374/diff.diff b/All/Genesis-NP/Genesis#374/diff.diff deleted file mode 100755 index 5696ee8..0000000 --- a/All/Genesis-NP/Genesis#374/diff.diff +++ /dev/null @@ -1,27 +0,0 @@ -diff --git a/modules/cpr/src/main/java/org/atmosphere/interceptor/SSEAtmosphereInterceptor.java b/modules/cpr/src/main/java/org/atmosphere/interceptor/SSEAtmosphereInterceptor.java -index d065d17..55c5ef5 100644 ---- a/modules/cpr/src/main/java/org/atmosphere/interceptor/SSEAtmosphereInterceptor.java -+++ b/modules/cpr/src/main/java/org/atmosphere/interceptor/SSEAtmosphereInterceptor.java -@@ -80 +79,0 @@ public class SSEAtmosphereInterceptor extends AtmosphereInterceptorAdapter { -- OutputStream stream = null; -@@ -82,5 +81 @@ public class SSEAtmosphereInterceptor extends AtmosphereInterceptorAdapter { -- stream = response.getResponse().getOutputStream(); -- } catch (IOException e) { -- logger.trace("", e); -- } -- -+ OutputStream stream = response.getResponse().getOutputStream(); -@@ -93,4 +87,0 @@ public class SSEAtmosphereInterceptor extends AtmosphereInterceptorAdapter { -- } else { -- PrintWriter w = null; -- try { -- w = response.getResponse().getWriter(); -@@ -100 +91,3 @@ public class SSEAtmosphereInterceptor extends AtmosphereInterceptorAdapter { -- -+ } else { -+ try { -+ PrintWriter w = response.getResponse().getWriter(); -@@ -102,0 +96,3 @@ public class SSEAtmosphereInterceptor extends AtmosphereInterceptorAdapter { -+ } catch (IOException e) { -+ logger.trace("", e); -+ } diff --git a/All/Genesis-NP/Genesis#374/new/SSEAtmosphereInterceptor.java b/All/Genesis-NP/Genesis#374/new/SSEAtmosphereInterceptor.java deleted file mode 100755 index 55c5ef5..0000000 --- a/All/Genesis-NP/Genesis#374/new/SSEAtmosphereInterceptor.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * Copyright 2014 Jeanfrancois Arcand - * - * 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.atmosphere.interceptor; - -import org.atmosphere.cpr.Action; -import org.atmosphere.cpr.ApplicationConfig; -import org.atmosphere.cpr.AsyncIOInterceptorAdapter; -import org.atmosphere.cpr.AsyncIOWriter; -import org.atmosphere.cpr.AtmosphereConfig; -import org.atmosphere.cpr.AtmosphereInterceptorAdapter; -import org.atmosphere.cpr.AtmosphereInterceptorWriter; -import org.atmosphere.cpr.AtmosphereRequest; -import org.atmosphere.cpr.AtmosphereResource; -import org.atmosphere.cpr.AtmosphereResourceEvent; -import org.atmosphere.cpr.AtmosphereResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; - -import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_USE_STREAM; -import static org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter.OnPreSuspend; -import static org.atmosphere.cpr.FrameworkConfig.CALLBACK_JAVASCRIPT_PROTOCOL; -import static org.atmosphere.cpr.FrameworkConfig.CONTAINER_RESPONSE; - -/** - * HTML 5 Server-Side Events implementation. - * - * @author Jeanfrancois Arcand - */ -public class SSEAtmosphereInterceptor extends AtmosphereInterceptorAdapter { - - private static final Logger logger = LoggerFactory.getLogger(SSEAtmosphereInterceptor.class); - - private static final byte[] padding; - private static final String paddingText; - private static final byte[] END = "\r\n\r\n".getBytes(); - private String contentType = "text/event-stream"; - - static { - StringBuffer whitespace = new StringBuffer(); - for (int i = 0; i < 2000; i++) { - whitespace.append(" "); - } - whitespace.append("\n"); - paddingText = whitespace.toString(); - padding = paddingText.getBytes(); - } - - @Override - public void configure(AtmosphereConfig config) { - String s = config.getInitParameter(ApplicationConfig.SSE_DEFAULT_CONTENTTYPE); - if (s != null) { - contentType = s; - } - } - - private boolean writePadding(AtmosphereResponse response) { - if (response.request() != null && response.request().getAttribute("paddingWritten") != null) return false; - - response.setContentType(contentType); - response.setCharacterEncoding("utf-8"); - boolean isUsingStream = (Boolean) response.request().getAttribute(PROPERTY_USE_STREAM); - if (isUsingStream) { - try { - OutputStream stream = response.getResponse().getOutputStream(); - try { - stream.write(padding); - stream.flush(); - } catch (IOException ex) { - logger.warn("SSE may not work", ex); - } - } catch (IOException e) { - logger.trace("", e); - } - } else { - try { - PrintWriter w = response.getResponse().getWriter(); - w.println(paddingText); - w.flush(); - } catch (IOException e) { - logger.trace("", e); - } - } - response.resource().getRequest().setAttribute("paddingWritten", "true"); - return true; - } - - private final class P extends OnPreSuspend implements AllowInterceptor { - - private final AtmosphereResponse response; - - private P(AtmosphereResponse response) { - this.response = response; - } - - @Override - public void onPreSuspend(AtmosphereResourceEvent event) { - writePadding(response); - } - } - - @Override - public Action inspect(final AtmosphereResource r) { - final AtmosphereResponse response = r.getResponse(); - final AtmosphereRequest request = r.getRequest(); - String accept = request.getHeader("Accept") == null ? "text/plain" : request.getHeader("Accept").trim(); - - if (r.transport().equals(AtmosphereResource.TRANSPORT.SSE) || contentType.equalsIgnoreCase(accept)) { - super.inspect(r); - - r.addEventListener(new P(response)); - - AsyncIOWriter writer = response.getAsyncIOWriter(); - if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) { - AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() { - private boolean padding() { - if (!r.isSuspended()) { - return writePadding(response); - } - return false; - } - - @Override - public void prePayload(AtmosphereResponse response, byte[] data, int offset, int length) { - boolean noPadding = padding(); - // The CALLBACK_JAVASCRIPT_PROTOCOL may be called by a framework running on top of Atmosphere - // In that case, we must pad/protocol indenendently of the state of the AtmosphereResource - if (!noPadding || r.getRequest().getAttribute(CALLBACK_JAVASCRIPT_PROTOCOL) != null) { - response.write("data:", true); - } - } - - @Override - public void postPayload(AtmosphereResponse response, byte[] data, int offset, int length) { - // The CALLBACK_JAVASCRIPT_PROTOCOL may be called by a framework running on top of Atmosphere - // In that case, we must pad/protocol indenendently of the state of the AtmosphereResource - if (r.isSuspended() || r.getRequest().getAttribute(CALLBACK_JAVASCRIPT_PROTOCOL) != null - || r.getRequest().getAttribute(CONTAINER_RESPONSE) != null) { - response.write(END, true); - } - - /** - * When used with https://github.com/remy/polyfills/blob/master/EventSource.js , we - * resume after every message. - */ - String ua = r.getRequest().getHeader("User-Agent"); - if (ua != null && ua.contains("MSIE")) { - try { - response.flushBuffer(); - } catch (IOException e) { - logger.trace("", e); - } - r.resume(); - } - } - }); - } else { - logger.warn("Unable to apply {}. Your AsyncIOWriter must implement {}", getClass().getName(), AtmosphereInterceptorWriter.class.getName()); - } - } - return Action.CONTINUE; - } - - @Override - public String toString() { - return "SSE Interceptor Support"; - } -} diff --git a/All/Genesis-NP/Genesis#374/old/SSEAtmosphereInterceptor.java b/All/Genesis-NP/Genesis#374/old/SSEAtmosphereInterceptor.java deleted file mode 100755 index d065d17..0000000 --- a/All/Genesis-NP/Genesis#374/old/SSEAtmosphereInterceptor.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * Copyright 2014 Jeanfrancois Arcand - * - * 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.atmosphere.interceptor; - -import org.atmosphere.cpr.Action; -import org.atmosphere.cpr.ApplicationConfig; -import org.atmosphere.cpr.AsyncIOInterceptorAdapter; -import org.atmosphere.cpr.AsyncIOWriter; -import org.atmosphere.cpr.AtmosphereConfig; -import org.atmosphere.cpr.AtmosphereInterceptorAdapter; -import org.atmosphere.cpr.AtmosphereInterceptorWriter; -import org.atmosphere.cpr.AtmosphereRequest; -import org.atmosphere.cpr.AtmosphereResource; -import org.atmosphere.cpr.AtmosphereResourceEvent; -import org.atmosphere.cpr.AtmosphereResponse; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; -import java.io.OutputStream; -import java.io.PrintWriter; - -import static org.atmosphere.cpr.ApplicationConfig.PROPERTY_USE_STREAM; -import static org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter.OnPreSuspend; -import static org.atmosphere.cpr.FrameworkConfig.CALLBACK_JAVASCRIPT_PROTOCOL; -import static org.atmosphere.cpr.FrameworkConfig.CONTAINER_RESPONSE; - -/** - * HTML 5 Server-Side Events implementation. - * - * @author Jeanfrancois Arcand - */ -public class SSEAtmosphereInterceptor extends AtmosphereInterceptorAdapter { - - private static final Logger logger = LoggerFactory.getLogger(SSEAtmosphereInterceptor.class); - - private static final byte[] padding; - private static final String paddingText; - private static final byte[] END = "\r\n\r\n".getBytes(); - private String contentType = "text/event-stream"; - - static { - StringBuffer whitespace = new StringBuffer(); - for (int i = 0; i < 2000; i++) { - whitespace.append(" "); - } - whitespace.append("\n"); - paddingText = whitespace.toString(); - padding = paddingText.getBytes(); - } - - @Override - public void configure(AtmosphereConfig config) { - String s = config.getInitParameter(ApplicationConfig.SSE_DEFAULT_CONTENTTYPE); - if (s != null) { - contentType = s; - } - } - - private boolean writePadding(AtmosphereResponse response) { - if (response.request() != null && response.request().getAttribute("paddingWritten") != null) return false; - - response.setContentType(contentType); - response.setCharacterEncoding("utf-8"); - boolean isUsingStream = (Boolean) response.request().getAttribute(PROPERTY_USE_STREAM); - if (isUsingStream) { - OutputStream stream = null; - try { - stream = response.getResponse().getOutputStream(); - } catch (IOException e) { - logger.trace("", e); - } - - try { - stream.write(padding); - stream.flush(); - } catch (IOException ex) { - logger.warn("SSE may not work", ex); - } - } else { - PrintWriter w = null; - try { - w = response.getResponse().getWriter(); - } catch (IOException e) { - logger.trace("", e); - } - - w.println(paddingText); - w.flush(); - } - response.resource().getRequest().setAttribute("paddingWritten", "true"); - return true; - } - - private final class P extends OnPreSuspend implements AllowInterceptor { - - private final AtmosphereResponse response; - - private P(AtmosphereResponse response) { - this.response = response; - } - - @Override - public void onPreSuspend(AtmosphereResourceEvent event) { - writePadding(response); - } - } - - @Override - public Action inspect(final AtmosphereResource r) { - final AtmosphereResponse response = r.getResponse(); - final AtmosphereRequest request = r.getRequest(); - String accept = request.getHeader("Accept") == null ? "text/plain" : request.getHeader("Accept").trim(); - - if (r.transport().equals(AtmosphereResource.TRANSPORT.SSE) || contentType.equalsIgnoreCase(accept)) { - super.inspect(r); - - r.addEventListener(new P(response)); - - AsyncIOWriter writer = response.getAsyncIOWriter(); - if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) { - AtmosphereInterceptorWriter.class.cast(writer).interceptor(new AsyncIOInterceptorAdapter() { - private boolean padding() { - if (!r.isSuspended()) { - return writePadding(response); - } - return false; - } - - @Override - public void prePayload(AtmosphereResponse response, byte[] data, int offset, int length) { - boolean noPadding = padding(); - // The CALLBACK_JAVASCRIPT_PROTOCOL may be called by a framework running on top of Atmosphere - // In that case, we must pad/protocol indenendently of the state of the AtmosphereResource - if (!noPadding || r.getRequest().getAttribute(CALLBACK_JAVASCRIPT_PROTOCOL) != null) { - response.write("data:", true); - } - } - - @Override - public void postPayload(AtmosphereResponse response, byte[] data, int offset, int length) { - // The CALLBACK_JAVASCRIPT_PROTOCOL may be called by a framework running on top of Atmosphere - // In that case, we must pad/protocol indenendently of the state of the AtmosphereResource - if (r.isSuspended() || r.getRequest().getAttribute(CALLBACK_JAVASCRIPT_PROTOCOL) != null - || r.getRequest().getAttribute(CONTAINER_RESPONSE) != null) { - response.write(END, true); - } - - /** - * When used with https://github.com/remy/polyfills/blob/master/EventSource.js , we - * resume after every message. - */ - String ua = r.getRequest().getHeader("User-Agent"); - if (ua != null && ua.contains("MSIE")) { - try { - response.flushBuffer(); - } catch (IOException e) { - logger.trace("", e); - } - r.resume(); - } - } - }); - } else { - logger.warn("Unable to apply {}. Your AsyncIOWriter must implement {}", getClass().getName(), AtmosphereInterceptorWriter.class.getName()); - } - } - return Action.CONTINUE; - } - - @Override - public String toString() { - return "SSE Interceptor Support"; - } -} diff --git a/All/Genesis-NP/Genesis#374/pair.info b/All/Genesis-NP/Genesis#374/pair.info deleted file mode 100755 index 072d28e..0000000 --- a/All/Genesis-NP/Genesis#374/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:374 -SATName:Genesis -modifiedFPath:modules/cpr/src/main/java/org/atmosphere/interceptor/SSEAtmosphereInterceptor.java -comSha:5c7f8cb77c8fea15584b06bca1c5d93b3e2c104e -parentComSha:5c7f8cb77c8fea15584b06bca1c5d93b3e2c104e^1 -githubUrl:https://github.com/Atmosphere/atmosphere -repoName:Atmosphere#atmosphere \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#38/comMsg.txt b/All/Genesis-NP/Genesis#38/comMsg.txt deleted file mode 100755 index 9bf3f69..0000000 --- a/All/Genesis-NP/Genesis#38/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix: AbstractPathView,testcaseNPE diff --git a/All/Genesis-NP/Genesis#38/diff.diff b/All/Genesis-NP/Genesis#38/diff.diff deleted file mode 100755 index 8432fad..0000000 --- a/All/Genesis-NP/Genesis#38/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/org/nutz/mvc/view/AbstractPathView.java b/src/org/nutz/mvc/view/AbstractPathView.java -index 38ab07d..c022f71 100644 ---- a/src/org/nutz/mvc/view/AbstractPathView.java -+++ b/src/org/nutz/mvc/view/AbstractPathView.java -@@ -5 +4,0 @@ import java.util.HashMap; --import java.util.List; -@@ -17,0 +17 @@ import org.nutz.lang.util.Context; -+import org.nutz.mvc.ActionContext; -@@ -87,0 +88,2 @@ public abstract class AbstractPathView implements View { -+ ActionContext ac = Mvcs.getActionContext(); -+ if (ac != null) diff --git a/All/Genesis-NP/Genesis#38/new/AbstractPathView.java b/All/Genesis-NP/Genesis#38/new/AbstractPathView.java deleted file mode 100755 index c022f71..0000000 --- a/All/Genesis-NP/Genesis#38/new/AbstractPathView.java +++ /dev/null @@ -1,126 +0,0 @@ -package org.nutz.mvc.view; - -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.nutz.el.El; -import org.nutz.lang.Lang; -import org.nutz.lang.Strings; -import org.nutz.lang.segment.CharSegment; -import org.nutz.lang.segment.Segment; -import org.nutz.lang.util.Context; -import org.nutz.mvc.ActionContext; -import org.nutz.mvc.Loading; -import org.nutz.mvc.Mvcs; -import org.nutz.mvc.View; -import org.nutz.mvc.config.AtMap; -import org.nutz.mvc.impl.processor.ViewProcessor; - -/** - * @author mawm(ming300@gmail.com) - * @author wendal(wendal1985@gmail.com) - */ -public abstract class AbstractPathView implements View { - - private Segment dest; - - private Map exps; - - public AbstractPathView(String dest) { - if (null != dest) { - this.dest = new CharSegment(Strings.trim(dest)); - this.exps = new HashMap(); - // 预先将每个占位符解析成表达式 - for (String key : this.dest.keys()) { - this.exps.put(key, new El(key)); - } - } - } - - protected String evalPath(HttpServletRequest req, Object obj) { - if (null == dest) - return null; - - Context context = Lang.context(); - - // 解析每个表达式 - Context expContext = createContext(req, obj); - for (Entry en : exps.entrySet()) - context.set(en.getKey(), en.getValue().eval(expContext)); - - // 生成解析后的路径 - return Strings.trim(this.dest.render(context).toString()); - } - - /** - * 为一次 HTTP 请求,创建一个可以被表达式引擎接受的上下文对象 - * - * @param req - * HTTP 请求对象 - * @param obj - * 入口函数的返回值 - * @return 上下文对象 - */ - @SuppressWarnings("unchecked") - public static Context createContext(HttpServletRequest req, Object obj) { - Context context = Lang.context(); - // 复制全局的上下文对象 - Object globalContext = Mvcs.getServletContext() - .getAttribute(Loading.CONTEXT_NAME); - if (globalContext != null) { - context.putAll((Context) globalContext); - } - - // 请求对象的属性列表 - Map req_attr = new HashMap(); - for (Enumeration en = req.getAttributeNames(); en.hasMoreElements();) { - String tem = en.nextElement(); - req_attr.put(tem, req.getAttribute(tem)); - } - context.set("a", req_attr);//兼容最初的写法 - context.set("req_attr", req_attr); - - ActionContext ac = Mvcs.getActionContext(); - if (ac != null) - context.set("pathargs", Mvcs.getActionContext().getPathArgs()); - - HttpSession session = Mvcs.getHttpSession(false); - if (session != null) { - Map session_attr = new HashMap(); - for (Enumeration en = session.getAttributeNames(); en.hasMoreElements();) { - String tem = en.nextElement(); - session_attr.put(tem, session.getAttribute(tem)); - } - context.set("session_attr", session_attr); - } - // 请求的参数表,需要兼容之前的p.参数, Fix issue 418 - Map p = new HashMap(); - for (Object o : req.getParameterMap().keySet()) { - String key = (String) o; - String value = req.getParameter(key); - p.put(key, value); - context.set(key, value);//以支持直接获取请求参数 - } - context.set("p", p); - - Map u = new HashMap(); - AtMap at = Mvcs.getAtMap(); - if (at != null) { - for(Object o : at.keys()){ - String key = (String) o; - u.put(key, at.get(key)); - } - context.set("u", u); - } - - // 加入返回对象 - if (null != obj) - context.set(ViewProcessor.DEFAULT_ATTRIBUTE, obj); - return context; - } -} diff --git a/All/Genesis-NP/Genesis#38/old/AbstractPathView.java b/All/Genesis-NP/Genesis#38/old/AbstractPathView.java deleted file mode 100755 index 38ab07d..0000000 --- a/All/Genesis-NP/Genesis#38/old/AbstractPathView.java +++ /dev/null @@ -1,124 +0,0 @@ -package org.nutz.mvc.view; - -import java.util.Enumeration; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpSession; - -import org.nutz.el.El; -import org.nutz.lang.Lang; -import org.nutz.lang.Strings; -import org.nutz.lang.segment.CharSegment; -import org.nutz.lang.segment.Segment; -import org.nutz.lang.util.Context; -import org.nutz.mvc.Loading; -import org.nutz.mvc.Mvcs; -import org.nutz.mvc.View; -import org.nutz.mvc.config.AtMap; -import org.nutz.mvc.impl.processor.ViewProcessor; - -/** - * @author mawm(ming300@gmail.com) - * @author wendal(wendal1985@gmail.com) - */ -public abstract class AbstractPathView implements View { - - private Segment dest; - - private Map exps; - - public AbstractPathView(String dest) { - if (null != dest) { - this.dest = new CharSegment(Strings.trim(dest)); - this.exps = new HashMap(); - // 预先将每个占位符解析成表达式 - for (String key : this.dest.keys()) { - this.exps.put(key, new El(key)); - } - } - } - - protected String evalPath(HttpServletRequest req, Object obj) { - if (null == dest) - return null; - - Context context = Lang.context(); - - // 解析每个表达式 - Context expContext = createContext(req, obj); - for (Entry en : exps.entrySet()) - context.set(en.getKey(), en.getValue().eval(expContext)); - - // 生成解析后的路径 - return Strings.trim(this.dest.render(context).toString()); - } - - /** - * 为一次 HTTP 请求,创建一个可以被表达式引擎接受的上下文对象 - * - * @param req - * HTTP 请求对象 - * @param obj - * 入口函数的返回值 - * @return 上下文对象 - */ - @SuppressWarnings("unchecked") - public static Context createContext(HttpServletRequest req, Object obj) { - Context context = Lang.context(); - // 复制全局的上下文对象 - Object globalContext = Mvcs.getServletContext() - .getAttribute(Loading.CONTEXT_NAME); - if (globalContext != null) { - context.putAll((Context) globalContext); - } - - // 请求对象的属性列表 - Map req_attr = new HashMap(); - for (Enumeration en = req.getAttributeNames(); en.hasMoreElements();) { - String tem = en.nextElement(); - req_attr.put(tem, req.getAttribute(tem)); - } - context.set("a", req_attr);//兼容最初的写法 - context.set("req_attr", req_attr); - - context.set("pathargs", Mvcs.getActionContext().getPathArgs()); - - HttpSession session = Mvcs.getHttpSession(false); - if (session != null) { - Map session_attr = new HashMap(); - for (Enumeration en = session.getAttributeNames(); en.hasMoreElements();) { - String tem = en.nextElement(); - session_attr.put(tem, session.getAttribute(tem)); - } - context.set("session_attr", session_attr); - } - // 请求的参数表,需要兼容之前的p.参数, Fix issue 418 - Map p = new HashMap(); - for (Object o : req.getParameterMap().keySet()) { - String key = (String) o; - String value = req.getParameter(key); - p.put(key, value); - context.set(key, value);//以支持直接获取请求参数 - } - context.set("p", p); - - Map u = new HashMap(); - AtMap at = Mvcs.getAtMap(); - if (at != null) { - for(Object o : at.keys()){ - String key = (String) o; - u.put(key, at.get(key)); - } - context.set("u", u); - } - - // 加入返回对象 - if (null != obj) - context.set(ViewProcessor.DEFAULT_ATTRIBUTE, obj); - return context; - } -} diff --git a/All/Genesis-NP/Genesis#38/pair.info b/All/Genesis-NP/Genesis#38/pair.info deleted file mode 100755 index b2bf819..0000000 --- a/All/Genesis-NP/Genesis#38/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:38 -SATName:Genesis -modifiedFPath:src/org/nutz/mvc/view/AbstractPathView.java -comSha:dc8ff5a008a1c3a507477effcc7eebb38a714413 -parentComSha:dc8ff5a008a1c3a507477effcc7eebb38a714413^1 -githubUrl:https://github.com/nutzam/nutz -repoName:nutzam#nutz \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#383/comMsg.txt b/All/Genesis-NP/Genesis#383/comMsg.txt deleted file mode 100755 index 0ef5cef..0000000 --- a/All/Genesis-NP/Genesis#383/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ - * Fix `NullPointerException` when leaving the `includePath`, `linkPath`, or `preloadPath` Mojo parameter empty diff --git a/All/Genesis-NP/Genesis#383/diff.diff b/All/Genesis-NP/Genesis#383/diff.diff deleted file mode 100755 index 3e257bc..0000000 --- a/All/Genesis-NP/Genesis#383/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/src/main/java/org/bytedeco/javacpp/tools/BuildMojo.java b/src/main/java/org/bytedeco/javacpp/tools/BuildMojo.java -index 4706015..e261d55 100644 ---- a/src/main/java/org/bytedeco/javacpp/tools/BuildMojo.java -+++ b/src/main/java/org/bytedeco/javacpp/tools/BuildMojo.java -@@ -189 +189 @@ public class BuildMojo extends AbstractMojo { -- return ss; -+ return ss != null ? ss : new String[0]; diff --git a/All/Genesis-NP/Genesis#383/new/BuildMojo.java b/All/Genesis-NP/Genesis#383/new/BuildMojo.java deleted file mode 100755 index e261d55..0000000 --- a/All/Genesis-NP/Genesis#383/new/BuildMojo.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (C) 2012,2013,2014 Arnaud Nauwynck, Samuel Audet - * - * This file is part of JavaCPP. - * - * JavaCPP is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 2 of the License, or - * (at your option) any later version (subject to the "Classpath" exception - * as provided in the LICENSE.txt file that accompanied this code). - * - * JavaCPP is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with JavaCPP. If not, see . - */ - -package org.bytedeco.javacpp.tools; - -import java.io.File; -import java.util.Arrays; -import java.util.Map; -import java.util.Properties; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.project.MavenProject; - -/** - * A Maven Mojo to call the {@link Builder} (C++ header file -> Java class -> C++ JNI -> native library). - * Can also be considered as an example of how to use the Builder programmatically. - * - * @goal build - * @phase process-classes - * @author Arnaud Nauwynck - * @author Samuel Audet - */ -public class BuildMojo extends AbstractMojo { - - /** - * Load user classes from classPath - * @parameter property="classPath" default-value="${project.build.outputDirectory}" - */ - private String classPath = null; - - /** - * Load user classes from classPaths - * @parameter property="classPaths" - */ - private String[] classPaths = null; - - /** - * Add the path to the "platform.includepath" property. - * @parameter property="includePath" - */ - private String includePath = null; - - /** - * Add the paths to the "platform.includepath" property. - * @parameter property="includePaths" - */ - private String[] includePaths = null; - - /** - * Add the path to the "platform.linkpath" property. - * @parameter property="linkPath" - */ - private String linkPath = null; - - /** - * Add the paths to the "platform.linkpath" property. - * @parameter property="linkPaths" - */ - private String[] linkPaths = null; - - /** - * Add the path to the "platform.preloadpath" property. - * @parameter property="preloadPath" - */ - private String preloadPath = null; - - /** - * Add the paths to the "platform.preloadpath" property. - * @parameter property="preloadPaths" - */ - private String[] preloadPaths = null; - - /** - * Output all generated files to outputDirectory - * @parameter property="outputDirectory" - */ - private File outputDirectory = null; - - /** - * Output everything in a file named after given outputName - * @parameter property="outputName" - */ - private String outputName = null; - - /** - * Compile and delete the generated .cpp files - * @parameter property="compile" default-value="true" - */ - private boolean compile = true; - - /** - * Generate header file with declarations of callbacks functions - * @parameter property="header" default-value="false" - */ - private boolean header = false; - - /** - * Copy to output directory dependent libraries (link and preload) - * @parameter property="copyLibs" default-value="false" - */ - private boolean copyLibs = false; - - /** - * Also create a JAR file named {@code -.jar} - * @parameter property="jarPrefix" - */ - private String jarPrefix = null; - - /** - * Load all properties from resource - * @parameter property="properties" - */ - private String properties = null; - - /** - * Load all properties from file - * @parameter property="propertyFile" - */ - private File propertyFile = null; - - /** - * Set property keys to values - * @parameter property="propertyKeysAndValues" - */ - private Properties propertyKeysAndValues = null; - - /** - * Process only this class or package (suffixed with .* or .**) - * @parameter property="classOrPackageName" - */ - private String classOrPackageName = null; - - /** - * Process only these classes or packages (suffixed with .* or .**) - * @parameter property="classOrPackageNames" - */ - private String[] classOrPackageNames = null; - - /** - * Environment variables added to the compiler subprocess - * @parameter property="environmentVariables" - */ - private Map environmentVariables = null; - - /** - * Pass compilerOptions directly to compiler - * @parameter property="compilerOptions" - */ - private String[] compilerOptions = null; - - /** - * Skip the execution. - * @parameter property="skip" default-value="false" - */ - private boolean skip = false; - - /** - * @parameter default-value="${project}" - * @required - * @readonly - */ - private MavenProject project; - - String[] merge(String[] ss, String s) { - if (ss != null && s != null) { - ss = Arrays.copyOf(ss, ss.length + 1); - ss[ss.length - 1] = s; - } else if (s != null) { - ss = new String[] { s }; - } - return ss != null ? ss : new String[0]; - } - - @Override public void execute() throws MojoExecutionException { - final Log log = getLog(); - try { - log.info("Executing JavaCPP Builder"); - if (log.isDebugEnabled()) { - log.debug("classPath: " + classPath); - log.debug("classPaths: " + Arrays.deepToString(classPaths)); - log.debug("includePath: " + includePath); - log.debug("includePaths: " + Arrays.deepToString(includePaths)); - log.debug("linkPath: " + linkPath); - log.debug("linkPaths: " + Arrays.deepToString(linkPaths)); - log.debug("preloadPath: " + preloadPath); - log.debug("preloadPaths: " + Arrays.deepToString(preloadPaths)); - log.debug("outputDirectory: " + outputDirectory); - log.debug("outputName: " + outputName); - log.debug("compile: " + compile); - log.debug("header: " + header); - log.debug("copyLibs: " + copyLibs); - log.debug("jarPrefix: " + jarPrefix); - log.debug("properties: " + properties); - log.debug("propertyFile: " + propertyFile); - log.debug("propertyKeysAndValues: " + propertyKeysAndValues); - log.debug("classOrPackageName: " + classOrPackageName); - log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames)); - log.debug("environmentVariables: " + environmentVariables); - log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions)); - log.debug("skip: " + skip); - } - - if (skip) { - log.info("Skipped execution of JavaCPP Builder"); - return; - } - - classPaths = merge(classPaths, classPath); - classOrPackageNames = merge(classOrPackageNames, classOrPackageName); - - Logger logger = new Logger() { - @Override public void debug(CharSequence cs) { log.debug(cs); } - @Override public void info (CharSequence cs) { log.info(cs); } - @Override public void warn (CharSequence cs) { log.warn(cs); } - @Override public void error(CharSequence cs) { log.error(cs); } - }; - Builder builder = new Builder(logger) - .classPaths(classPaths) - .outputDirectory(outputDirectory) - .outputName(outputName) - .compile(compile) - .header(header) - .copyLibs(copyLibs) - .jarPrefix(jarPrefix) - .properties(properties) - .propertyFile(propertyFile) - .properties(propertyKeysAndValues) - .classesOrPackages(classOrPackageNames) - .environmentVariables(environmentVariables) - .compilerOptions(compilerOptions); - Properties properties = builder.properties; - String separator = properties.getProperty("platform.path.separator"); - for (String s : merge(includePaths, includePath)) { - String v = properties.getProperty("platform.includepath", ""); - properties.setProperty("platform.includepath", - v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); - } - for (String s : merge(linkPaths, linkPath)) { - String v = properties.getProperty("platform.linkpath", ""); - properties.setProperty("platform.linkpath", - v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); - } - for (String s : merge(preloadPaths, preloadPath)) { - String v = properties.getProperty("platform.preloadpath", ""); - properties.setProperty("platform.preloadpath", - v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); - } - project.getProperties().putAll(properties); - File[] outputFiles = builder.build(); - log.info("Successfully executed JavaCPP Builder"); - if (log.isDebugEnabled()) { - log.debug("outputFiles: " + Arrays.deepToString(outputFiles)); - } - } catch (Exception e) { - log.error("Failed to execute JavaCPP Builder: " + e.getMessage()); - throw new MojoExecutionException("Failed to execute JavaCPP Builder", e); - } - } -} diff --git a/All/Genesis-NP/Genesis#383/new/CHANGELOG.md b/All/Genesis-NP/Genesis#383/new/CHANGELOG.md deleted file mode 100755 index 2ce5290..0000000 --- a/All/Genesis-NP/Genesis#383/new/CHANGELOG.md +++ /dev/null @@ -1,242 +0,0 @@ - - * Fix `NullPointerException` when leaving the `includePath`, `linkPath`, or `preloadPath` Mojo parameter empty - * Add `Info.virtualize` to have the `Parser` generate `@Virtual abstract` for pure virtual functions in the given classes - * Add `@Virtual` annotation and update `Generator` to support callback by overriding such annotated `native` or `abstract` methods - * Add hack for `typedef void*` definitions and parameters with a double indirection to them - -### July 27, 2014 version 0.9 - * Fix `Generator.checkPlatform()` not checking super classes - * Add `includePath`, `linkPath`, and `preloadPath` parameters to `BuildMojo` to let Maven users append paths to the properties easily - * In consequence, remove too arbitrary "local" paths from the default platform properties (issue #43) - * Fix a few other more or less minor issues in the `Parser` with the `long double`, `ptrdiff_t`, `intptr_t`, `uintptr_t`, `off_t` types, floating-point numbers, macro redefinitions, access specifiers, casting of const values by reference, optional parentheses, const data types in templates, declarator names equal to a type name, friend functions, inline constructors, `typedef void` declarations within namespaces, pointers to function pointers - * Allow users to instruct the `Parser` to skip the expansion of specific macro invocations - * Let `Parser` concatenate tokens when expanding macros containing the `##` operator - * Add some documentation for `Info`, `InfoMap`, `InfoMapper`, and `Parser` - * Fix the `Parser` not filtering and expanding properly some preprocessor directives, as well as producing wrong code for `typedef struct *` - * Skip Java path search when building for Android to prevent including some random `jni.h` file ([issue #3](https://github.com/bytedeco/javacpp/issues/3)) - * Fix the `Parser` losing some keywords like `static` on methods annotated with an `@Adapter` ([issue #2](https://github.com/bytedeco/javacpp/issues/2)) - * Fix `Loader.load()` not properly force loading all inherited target classes ([issue #1](https://github.com/bytedeco/javacpp/issues/1)) - -### April 28, 2014 version 0.8 - * Move from Google Code to GitHub as main source code repository - * Place build-time classes in the `org.bytedeco.javacpp.tools` package and bring out static nested classes, in an effort to avoid conflicts and ease development - * Rename the `com.googlecode.javacpp` package to `org.bytedeco.javacpp` - * Added `public long Pointer.address()` getter method, useful when one needs to subtract two pointers - * Removed old NetBeans project files that cause a conflict when trying to open as a Maven project (issue javacv:210) - * Fixed compilation error on `FunctionPointer` classes containing no native callback methods - * Added a `platform.library.path` property, such as "lib/armeabi/" in the case of the "android-arm" platform, to be used instead of "package/platform" (issue javacv:427) - * Generalized references to the path of the Android NDK - * Improved a few small things in the set of `Pointer` classes - * Introduced a simple `Logger` class and unified the logging output calls around it - * Unified the property names with the `@Properties` and `@Platform` annotations into a consistent naming scheme - * Continued to clean up the `Parser` and improve the support of, for the most part, comments, enumerations, functions pointers, anonymous `struct` or `union`, templates, overloaded operators, namespaces, standard containers, default parameter arguments, multiple inheritance, custom names of wrapped declarators, and helper classes written in Java - * Annotations such as `@Adapter` or `@ByVal` are no longer ignored on parameters of getters or setters annotated with `@Index` - * Fixed some other corner cases in `Generator` and a few potential issues with the hacks in `Loader` - * Added for convenience to `PointerPointer` a generic parameter `

` and the associated `get(Class

...)` getters, as well as `String` getters and setters - * Passing a `Class` object as first argument to a native method that returns a `Pointer` now determines the runtime type of that returned object - * Generalized somewhat more the compiler options used inside `linux-arm.properties` (issue javacv:418) - * Unified the function pointer type of native deallocators to `void (*)(void*)` - * Removed dependency on (efficient) `AllocObject()` and `CallNonvirtualVoidMethodA()` JNI functions, which are not supported by Avian - * Cleaned up and optimized `Generator` a bit, also fixing a crash that could occur when `FindClass()` returns `NULL` - -### January 6, 2014 version 0.7 - * Tweaked a few things to support RoboVM and target iOS, but `JNI_OnLoad()` does not appear to get called... - * Upgraded references of the Android NDK to version r9c - * Made `Loader.load()` work, within reason, even when all annotations and resources have been removed, for example, by ProGuard - * Fixed compile error when using a `FunctionPointer` as parameter from outside its top-level enclosing class - * Added new `Pointer.deallocate(false)` call to disable garbage collection on a per object basis, allowing users to deal with memory leaks in other ways - * Changed the default compiler option `-mfpu=vfpv` for ARM to `-mfpu=vfpv3-d16`, because the former is not supported by Tegra 2 (issue javacv:366) - * Removed call to `Arrays.copyOf()` in `Loader.findLibrary()`, which would prevent it from working on Android 2.2 (issue #39) - * Fixed invalid code generated for `FunctionPointer` parameters annotated with `@Const @ByRef` - * Fixed `NullPointerException` in `Loader.load()` when no `@Platform` annotation is provided (issue #38) - * Parsing for anonymous `struct` or `union` and for `typedef void` (mapped to `@Opaque Pointer`) now outputs something - * The `Parser` now expands preprocessor macros, filters tokens appropriately, and outputs all unprocessed directives as comments - * Improved the C++ support of the `Parser` for namespaces, derived classes, access specifiers, custom constructors, vector types, macros, templates, overloaded operators, etc - * Fixed `typedef` of function pointers and a few code formatting issues with `Parser` - * Supplied checks to prevent `Loader.load()` from throwing `java.lang.IllegalStateException: Can't overwrite cause` - -### September 15, 2013 version 0.6 - * Added new very preliminary `Parser` to produce Java interface files almost automatically from C/C++ header files; please refer to the new JavaCPP Presets subproject for details - * When catching a C++ exception, the first class declared after `throws` now gets thrown (issue #36) instead of `RuntimeException`, which is still used by default - * Fixed Java resource leak after catching a C++ exception - * Upgraded references of the Android NDK to version r9 - * Added new `Builder` option "-copylibs" that copies into the build directory any dependent shared libraries listed in the `@Platform(link={...}, preload={...})` annotation - * `Loader.getPlatformName()` can now be overridden by setting the `com.googlecode.javacpp.platform.name` system property - * Refactored the loading code for `@Properties()` into a neat `Loader.ClassProperties` class, among a few other small changes in `Loader`, `Builder`, `Generator`, and the properties - * Included often used directories such as `/usr/local/include/` and `/usr/local/lib/` to `compiler.includepath` and `compiler.linkpath` default properties - * New `@Properties(inherit={Class})` value lets users specify properties in common on a similarly annotated shared config class of sorts - * Fixed callbacks when used with custom class loaders such as with Web containers or frameworks like Tomcat and Play - * Fixed using `@StdString` (or other `@Adapter` with `@Cast` annotations) on callbacks (issue #34), incidentally allowing them to return a `String` - * By default, `Builder` now links to the `jvm` library only when required, when using the `-header` command line option (issue #33) - * Incorporated missing explicit cast on return values when using the `@Cast` annotation - * Fixed duplicate code getting generated when both specifying the output filename with `-o ` and using wildcards on packages containing nested classes - * Let `Buffer` or arrays of primitive values be valid return and callback arguments, mostly useful when used along with the `@StdVector` annotation, or some other custom adapter - -### April 7, 2013 version 0.5 - * Upgraded references of the Android NDK to version r8e - * Arguments of `Pointer` type now get handled as `char*` in cases when the `position` can be used for arithmetic - * Worked around bug of `InputStream.available()` always returning 0 with the `http` protocol in `Loader.extractResource(URL)` - -### March 3, 2013 version 0.4 - * Fixed potential problem with methods of `FunctionPointer` annotated with `@Cast("const...")` - * Upgraded references of the Android NDK to version r8d - * Fixed callbacks not working on Android anymore (issue #30) - * Added some Javadoc to most of the code - * To help diagnose `UnsatisfiedLinkError` thrown by `Loader.load()`, they have been augmented with a potential cause originating from the "preloading" of libraries, whose premature deletion has also been fixed - * Provided new `@Platform(library="...")` annotation value to let users specify the name of the native library used by both `Builder` and `Loader`, where different classes with the same name get built together, which also works on nested classes (issue #29) - * Added the ability to change the name of the class of function objects created when defining a `FunctionPointer` with the `@Name` annotation - * `Builder` would go on a compile spree when all classes specified on the command line could not be loaded - * Exported `Loader.isLoadLibraries()`, which always returns true, except when the `Builder` loads the classes - * Made it possible to specify a nested class (with a '$' character in the name) on the command line - * When `Pointer.limit == 0`, the methods `put()`, `zero()`, and `asBuffer()` now assume a size of 1 - * Fixed compiler error on 32-bit Mac OS X - -### November 4, 2012 version 0.3 - * Added `Pointer.withDeallocator(Pointer)` method to attach easily a custom `Deallocator` created out of a `static void deallocate(Pointer)` method in the subclass, including native ones such as `@Namespace @Name("delete") static native void deallocate(Pointer)` - * A name starting with "::", for example `@Name("::std::string")` or `@Namespace("::std")`, now drops the remaining enclosing scope - * Removed confusing `cast` value of `@Adapter` instead relying on new `String[]` value of `@Cast` to order multiple casts - * Renamed various variables in `Generator` to make the generated code more readable - * Fixed memory corruption when using an adapter or `@ByRef` on a function that returns by value an `std::vector<>` or `std::string` (issue #26) - * Added `Pointer.zero()` method that calls `memset(0)` on the range - * For easier memory management, more than one `Pointer` now allowed to share the `deallocator` when "casting" them - * Upgraded references of the Android NDK to version r8b - * Fixed `JavaCPP_log()` not printing correctly (issue #27) - * Added functionality to access easily `FunctionPointer` callbacks by their names from C/C++: We can annotate them with `@Name` and build with the new `-header` option to get their declarations in a header file, while the `Builder` links with the `jvm` library by default - * `Loader` now displays an informative error message when trying to use an undefined `compiler.options` with `@Platform(options="")` (issue #24) - * `Pointer.deallocator()` would needlessly enqueue `Deallocator` objects pointing to the native `NULL` address - * Added support for C++ "functors" based on the `operator()`, which gets used when annotating a `FunctionPointer` method parameter with `@ByRef` or `@ByVal` - * For convenience in Scala, added `apply()` as an acceptable caller method name within a `FunctionPointer`, in addition to `call()` - * Fixed `@Cast` not working along parameters with an `@Adapter` or when attempting to `return` the argument - * `Generator` would ignore `Pointer.position()` in the case of `@ByPtrPtr` and `@ByPtrRef` parameters - * Replaced hack to create a `Pointer` from a `Buffer` object with something more standard - * Fixed `Loader.sizeof(Pointer.class)` to return the `sizeof(void*)` - * In addition to methods and parameters, we may now apply `@Adapter` to annotation types as well, allowing us to shorten expressions like `@Adapter("VectorAdapter") int[]` to just `@StdVector int[]`, for `std::vector` support, and similarly for `@StdString` and `std::string` - * Fixed callback parameter casting of primitive and `String` types - * An empty `@Namespace` can now be used to let `Generator` know of entities that are not part of any scope, such as macros and operators - * Turned `FunctionPointer` into an `abstract class` with `protected` constructors, but if users still try to use it as function parameters, `Generator` now logs a warning indicating that a subclass should be used (issue #23) - * Removed the `out` value of the `@Adapter` annotation: All adapters are now "out" by default, unless `@Const` also appears on the same element - * Fixed `Pointer.equals(null)` throwing `NullPointerException` (issue #22) - * `@NoOffset` would erroneously prevent `sizeof()` operations from getting generated - -### July 21, 2012 version 0.2 - * Fixed problems when trying to map `java.lang.String` to other native types than `char*`, such as `unsigned char*` - * JavaCPP now uses the `new (std::nothrow)` operator for allocation, which guarantees that allocation of primitive native arrays won't throw exceptions, making it possible to build C++ exception free JNI libraries - * Added new `Pointer.limit` property, mainly useful to get the `size` of an output parameter, as returned by an adapter specified with the `@Adapter` annotation - * Renamed the `capacity` field of an adapter to `size` as it now maps to both `Pointer.limit` and `Pointer.capacity` (the latter only for new allocations) - * Added `Pointer.put(Pointer)` method, the counterpart of `Buffer.put(Buffer)`, to call the native `memcpy()` function on two `Pointer` objects - * New `@NoException` annotation to reduce the size of generated code and optimize runtime performance of functions that are guaranteed not to throw exceptions, or for cases when we do not mind that the JVM may crash and burn - * Trying to generate code for non-static native methods inside a class not extending `Pointer` now generates proper warning (issue #19) - * Fixed regression where the `@Adapter` notation generates incorrect code for types other than `Pointer` (issue #20) - -### May 27, 2012 version 0.1 - * Started using version numbers, friendly to tools like Maven, and placing packages in a sort of [Maven repository](http://maven2.javacpp.googlecode.com/git/) (issue #10) - * Before loading a JNI library, the `Loader` now also tries to extract and load libraries listed in the `@Platform(link={...}, preload={...})` annotation values, and to support library names with version numbers, each value has to follow the format "libname@version" (or "libname@@version" to have `Builder` use it for the compiler as well), where "version" is the version number found in the filename as required by the native dynamic linker, usually a short sequence of digits and dots, but it can be anything (e.g.: "mylib@.4.2" would map to "libmylib.so.4.2", "libmylib.4.2.dylib", and "mylib.4.2.dll" under Linux, Mac OS X, and Windows respectively) - * All files now get extracted into a temporary subdirectory, and with the appropriate platform-dependent linker options, or with libraries patched up after the fact with tools such as `install_name_tool` of Mac OS X, most native dynamic linkers can load dependent libraries from there - * Stopped using `java.net.URL` as hash key in `Loader` (very bad idea) - * Changed the default value of the `@Index` annotation from 0 to 1, and fixed the `Generator` when it is used with member getters and setters - * Renamed `mingw-*.properties` to `windows-*-mingw.properties` for consistency - * Made the `Generator` allocate native heap memory for callback arguments passed `@ByVal` (in addition to `FunctionPointer`), rendering their behavior consistent with return `@ByVal` in the case of function calls (issue #16) - * `Generator` now uses `std::runtime_error(std::string&)` instead of assuming that some nonstandard `std::exception(std::string&)` constructor exists (issue #17) - * Fixed `Generator` producing incorrect code when applying invalid annotations such as `@ByVal` on a method that returns something else than a `Pointer` object (issue #18) - -### May 12, 2012 - * Added `pom.xml` file and `BuildMojo` plugin class for Maven support and changed the directory structure of the source code to match Maven's standard directory layout (issue #10) Many thanks to Adam Waldenberg and Arnaud Nauwynck for their ongoing support with that! - * Moved the source code repository to Git - * Created a new `@Raw` annotation to use Java object as raw `jobject` in C++, also passing `JNIEnv` and the enclosing `jclass` or the `jobject` corresponding to `this`, as the first two arguments of the function, when the `Generator` encounters any `@Raw(withEnv=true)` (issue #13) - * The `Builder` now handles more cases when some prefix or suffix property starts or ends with a space (issue #14) - * Fixed syntax error in `VectorAdapter`, which GCC and Visual C++ would still happily compile - * Added new `source.suffix` property to have the names of generated source files end with something else than `.cpp` and support frameworks like CUDA that require filenames with a `.cu` extension to compile properly, such as used by the new `*-cuda.properties`, and also changed the "-cpp" command line option to "-nocompile" - * New `Loader.loadLibrary()` method similar to `System.loadLibrary()`, but before searching the library path, it tries to extract and load the library from Java resources - * `Generator` now accepts `@Const` on `FunctionPointer` class declarations - * Added new `@Adapter.cast()` value to cast explicitly the output of a C++ adapter object - * Upgraded references of the Android NDK to version r8 - * Included new command line option "-Xcompiler" to pass options such as "-Wl,-static" directly to the compiler - * Made other various minor changes and enhancements - -### March 29, 2012 - * Added new `compiler.framework` property and corresponding `@Platform.framework()` value to allow easier binding with Mac OS X frameworks - * Changed most `Builder` errors into warnings, letting the building process complete successfully more often - * We may now use the `@NoDeallocator` annotation on a class to disable deallocation for all allocation methods - -### March 03, 2012 - * Added new `@NoDeallocator` annotation to prevent `allocate()` and `allocateArray()` methods from registering a native deallocator to `Pointer` objects (issue #1) - * `Generator` now properly skips as unsupported array parameters that do not have a primitive component type, and logs a warning (issue #7) - * `Generator` and `Builder` would append the same include files, libraries, or options multiple times when not required: Fixed in `Loader.appendProperty()` (issue #8) - * Moved the placement of the class-level @Index annotation to the getter and setter methods themselves - * To process all classes in a package, we may now specify as argument to the `Builder` its name followed by ".*", in a similar fashion to the `import` statement of the Java language, or by ".**" to process recursively all packages, while omitting to specify any class or package results in JavaCPP processing all classes found under the directories or JAR files specified with the "-classpath" option (issue #12) - * Equipped the `*Pointer` classes with new bulk `get()` and `put()` methods taking an array as argument, to compensate for direct NIO buffers lacking in performance on Android (issue #11) - -### February 18, 2012 - * Cleaned up a few minor `Exception` blocks - * New `Pointer.deallocateReferences()` static method to force immediate deallocation of all native memory allocated by `Pointer` objects that since have been garbage collected - * Updated `android-arm.properties` to reflect the fact that, starting from Android NDK r7, `libstdc++.a` has been surreptitiously renamed to `libgnustl_static.a`, such that JavaCPP was instead linking to a new bogus `libstdc++.so` library, causing runtime linking errors - * Included new `android-x86.properties` to compile binaries for that platform as well - * Added new `compiler.sysroot.prefix` and `compiler.sysroot` platform properties to pass options such as `--sysroot` to satisfy new rituals of the Android NDK starting from r7b - * Upgraded references of the Android NDK to version r7b - -### January 8, 2012 - * Added new `compiler.linkpath.prefix2` platform property to pass options such as `-Wl,-rpath,` to linkers that support them - * Fixed `Loader.load()` on Android 4.0, where `SecurityManager.getClassContext()` returns `null` - * Upgraded references of the Android NDK to version r7 - -### October 29, 2011 - * Changed the following to make MinGW work: `Generator` now maps `jlong` to the more standard `long long` instead of `__int64` type and also includes `stdint.h`, and added `-D_JNI_IMPLEMENTATION_ -Wl,--kill-at` to the compiler options, as recommended by MinGW's documentation for building DLLs compatible with JNI - * Added hack for `AttachCurrentThread()`, whose signature differs under Android, and `DetachCurrentThread()` now gets called as appropriate after returning from a callback function, to prevent memory leaks (and also crashes on platforms such as Android) (issue #3) - * `Generator` now generates correct code for the annotation pairs `@Const @ByRef` and `@Const @ByVal` (issue #4) - * Worked around callback functions crashing on Android, which is unable to load user classes from native threads (issue #5) - * Fixed a few potential pitfalls inside `Generator` and `Loader` - * Removed compiler warnings due to the type of the `capacity` member variable of `VectorAdapter` - * Callback `FunctionPointer` objects may now return `@ByVal` or `@ByRef` - * On Android, changed the output of runtime error messages from `stderr` (equivalent to `/dev/null` on Android) to the log - -### October 1, 2011 - * Changed default option flag "/MT" to "/MD" (and a few others that Visual Studio uses by default) inside `windows-x86.properties` and `windows-x86_64.properties` because `std::vector`, `VectorAdapter` and C++ memory allocation in general does not work well with static runtime libraries across DLLs under Windows Vista and Windows 7 for some reason, and because Microsoft fixed the manifest file insanity starting with Visual C++ 2010 - * `Builder` now searches for `jni.h` and `jni_md.h` inside `/System/Library/Frameworks/JavaVM.framework/Headers/` if not found inside `java.home`, as with Mac OS X Lion (issue #2) - * Upgraded references of the Android NDK to version r6b - * Fixed a few potential pitfalls inside `Generator` - * Added hack to let `*Pointer` classes with a corresponding `*Buffer` class have constructors for them - -### July 5, 2011 - * `Generator` now lets `get()/put()` (or the `ValueGetter/ValueSetter` annotated) methods use non-integer indices for the `Index` annotation - * Removed calls to `Arrays.copyOf()` inside `getString*()` methods so they may work on Android as well - * Fixed race condition that could occur in the deallocation code of `Pointer` due to incorrect synchronization - * `platform.root` now defaults to the current directory - -### June 10, 2011 - * New `Adapter` annotation that uses C++ classes such as `VectorAdapter`, which can let us use Java arrays or `Pointer` objects in place of C++ vector objects by mapping types such as `vector` to `@Adapter("VectorAdapter") int[]` or `@Adapter("VectorAdapter") IntPointer` - * Added new `Pointer.capacity` field to keep track of allocated size for arrays, needed by the `Adapter` annotation - * Removed the `capacity` parameter from the `Pointer.asByteBuffer()` and `Pointer.asBuffer()` methods, which now rely instead on the value of the new `capacity` field - * `ValueGetter` and `ValueSetter`, defaulting to the `get()` and `put()` methods, now accept indices as arguments, and `*Pointer` classes have been updated accordingly - * New `Index` annotation to indicate that a C++ class, such as `vector` implements the `operator[]` that can be mapped to the `ValueGetter` and `ValueSetter` as well as to arbitrary function calls, taking the first n arguments as indices, where n is the value placed in the annotation - * The `Name` annotation now accepts as value a `String` array to indicate names before and after these indices - * New `Const` annotation for convenience - * Fixed scoping of static members inside namespaces and classes - * Added new `BoolPointer` class - * Improved support of function pointers to generate more standard C++ and to make it work with things like member function pointers - * Inserted hack to call `std::string.c_str()` when returned as `@ByRef java.lang.String` - * Multiplied checks for invalid `NULL` pointers - * Upgraded references of the Android NDK to version r5c, which now also works on Android 2.1 or older ([android issue #16008](http://code.google.com/p/android/issues/detail?id=16008)) - * `Loader.load()` no longer requires a JVM that supports annotations to function properly - -### April 22, 2011 - * `Generator` now outputs `#include `, the lack of which prevents Android NDK under Windows from compiling - -### April 7, 2011 - * Replaced arrays from constructors with variable-length argument lists for convenience - * Fixed a few small potential pitfalls previously overlooked - -### March 1, 2011 - * Fixed directory search for `jni_md.h`, which did not search deep enough in some cases - * Added new `path.separator` property to set the path separator of the target platform, regardless of the build platform - * Added hack to make sure the temporarily extracted library files get properly deleted under Windows - * Now loads classes more lazily - * Changed the paths for libstdc++ inside `android-arm.properties` to the non "v7a" versions - * Added new `platform.root` property to let users specify the path to their toolchains more easily - -### February 18, 2011 -Initial release - - -Acknowledgments ---------------- -This project was conceived at the [Okutomi & Tanaka Laboratory](http://www.ok.ctrl.titech.ac.jp/), Tokyo Institute of Technology, where I was supported for my doctoral research program by a generous scholarship from the Ministry of Education, Culture, Sports, Science and Technology (MEXT) of the Japanese Government. I extend my gratitude further to all who have reported bugs, donated code, or made suggestions for improvements (details above)! diff --git a/All/Genesis-NP/Genesis#383/old/BuildMojo.java b/All/Genesis-NP/Genesis#383/old/BuildMojo.java deleted file mode 100755 index 4706015..0000000 --- a/All/Genesis-NP/Genesis#383/old/BuildMojo.java +++ /dev/null @@ -1,277 +0,0 @@ -/* - * Copyright (C) 2012,2013,2014 Arnaud Nauwynck, Samuel Audet - * - * This file is part of JavaCPP. - * - * JavaCPP is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 2 of the License, or - * (at your option) any later version (subject to the "Classpath" exception - * as provided in the LICENSE.txt file that accompanied this code). - * - * JavaCPP is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with JavaCPP. If not, see . - */ - -package org.bytedeco.javacpp.tools; - -import java.io.File; -import java.util.Arrays; -import java.util.Map; -import java.util.Properties; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.project.MavenProject; - -/** - * A Maven Mojo to call the {@link Builder} (C++ header file -> Java class -> C++ JNI -> native library). - * Can also be considered as an example of how to use the Builder programmatically. - * - * @goal build - * @phase process-classes - * @author Arnaud Nauwynck - * @author Samuel Audet - */ -public class BuildMojo extends AbstractMojo { - - /** - * Load user classes from classPath - * @parameter property="classPath" default-value="${project.build.outputDirectory}" - */ - private String classPath = null; - - /** - * Load user classes from classPaths - * @parameter property="classPaths" - */ - private String[] classPaths = null; - - /** - * Add the path to the "platform.includepath" property. - * @parameter property="includePath" - */ - private String includePath = null; - - /** - * Add the paths to the "platform.includepath" property. - * @parameter property="includePaths" - */ - private String[] includePaths = null; - - /** - * Add the path to the "platform.linkpath" property. - * @parameter property="linkPath" - */ - private String linkPath = null; - - /** - * Add the paths to the "platform.linkpath" property. - * @parameter property="linkPaths" - */ - private String[] linkPaths = null; - - /** - * Add the path to the "platform.preloadpath" property. - * @parameter property="preloadPath" - */ - private String preloadPath = null; - - /** - * Add the paths to the "platform.preloadpath" property. - * @parameter property="preloadPaths" - */ - private String[] preloadPaths = null; - - /** - * Output all generated files to outputDirectory - * @parameter property="outputDirectory" - */ - private File outputDirectory = null; - - /** - * Output everything in a file named after given outputName - * @parameter property="outputName" - */ - private String outputName = null; - - /** - * Compile and delete the generated .cpp files - * @parameter property="compile" default-value="true" - */ - private boolean compile = true; - - /** - * Generate header file with declarations of callbacks functions - * @parameter property="header" default-value="false" - */ - private boolean header = false; - - /** - * Copy to output directory dependent libraries (link and preload) - * @parameter property="copyLibs" default-value="false" - */ - private boolean copyLibs = false; - - /** - * Also create a JAR file named {@code -.jar} - * @parameter property="jarPrefix" - */ - private String jarPrefix = null; - - /** - * Load all properties from resource - * @parameter property="properties" - */ - private String properties = null; - - /** - * Load all properties from file - * @parameter property="propertyFile" - */ - private File propertyFile = null; - - /** - * Set property keys to values - * @parameter property="propertyKeysAndValues" - */ - private Properties propertyKeysAndValues = null; - - /** - * Process only this class or package (suffixed with .* or .**) - * @parameter property="classOrPackageName" - */ - private String classOrPackageName = null; - - /** - * Process only these classes or packages (suffixed with .* or .**) - * @parameter property="classOrPackageNames" - */ - private String[] classOrPackageNames = null; - - /** - * Environment variables added to the compiler subprocess - * @parameter property="environmentVariables" - */ - private Map environmentVariables = null; - - /** - * Pass compilerOptions directly to compiler - * @parameter property="compilerOptions" - */ - private String[] compilerOptions = null; - - /** - * Skip the execution. - * @parameter property="skip" default-value="false" - */ - private boolean skip = false; - - /** - * @parameter default-value="${project}" - * @required - * @readonly - */ - private MavenProject project; - - String[] merge(String[] ss, String s) { - if (ss != null && s != null) { - ss = Arrays.copyOf(ss, ss.length + 1); - ss[ss.length - 1] = s; - } else if (s != null) { - ss = new String[] { s }; - } - return ss; - } - - @Override public void execute() throws MojoExecutionException { - final Log log = getLog(); - try { - log.info("Executing JavaCPP Builder"); - if (log.isDebugEnabled()) { - log.debug("classPath: " + classPath); - log.debug("classPaths: " + Arrays.deepToString(classPaths)); - log.debug("includePath: " + includePath); - log.debug("includePaths: " + Arrays.deepToString(includePaths)); - log.debug("linkPath: " + linkPath); - log.debug("linkPaths: " + Arrays.deepToString(linkPaths)); - log.debug("preloadPath: " + preloadPath); - log.debug("preloadPaths: " + Arrays.deepToString(preloadPaths)); - log.debug("outputDirectory: " + outputDirectory); - log.debug("outputName: " + outputName); - log.debug("compile: " + compile); - log.debug("header: " + header); - log.debug("copyLibs: " + copyLibs); - log.debug("jarPrefix: " + jarPrefix); - log.debug("properties: " + properties); - log.debug("propertyFile: " + propertyFile); - log.debug("propertyKeysAndValues: " + propertyKeysAndValues); - log.debug("classOrPackageName: " + classOrPackageName); - log.debug("classOrPackageNames: " + Arrays.deepToString(classOrPackageNames)); - log.debug("environmentVariables: " + environmentVariables); - log.debug("compilerOptions: " + Arrays.deepToString(compilerOptions)); - log.debug("skip: " + skip); - } - - if (skip) { - log.info("Skipped execution of JavaCPP Builder"); - return; - } - - classPaths = merge(classPaths, classPath); - classOrPackageNames = merge(classOrPackageNames, classOrPackageName); - - Logger logger = new Logger() { - @Override public void debug(CharSequence cs) { log.debug(cs); } - @Override public void info (CharSequence cs) { log.info(cs); } - @Override public void warn (CharSequence cs) { log.warn(cs); } - @Override public void error(CharSequence cs) { log.error(cs); } - }; - Builder builder = new Builder(logger) - .classPaths(classPaths) - .outputDirectory(outputDirectory) - .outputName(outputName) - .compile(compile) - .header(header) - .copyLibs(copyLibs) - .jarPrefix(jarPrefix) - .properties(properties) - .propertyFile(propertyFile) - .properties(propertyKeysAndValues) - .classesOrPackages(classOrPackageNames) - .environmentVariables(environmentVariables) - .compilerOptions(compilerOptions); - Properties properties = builder.properties; - String separator = properties.getProperty("platform.path.separator"); - for (String s : merge(includePaths, includePath)) { - String v = properties.getProperty("platform.includepath", ""); - properties.setProperty("platform.includepath", - v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); - } - for (String s : merge(linkPaths, linkPath)) { - String v = properties.getProperty("platform.linkpath", ""); - properties.setProperty("platform.linkpath", - v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); - } - for (String s : merge(preloadPaths, preloadPath)) { - String v = properties.getProperty("platform.preloadpath", ""); - properties.setProperty("platform.preloadpath", - v.length() == 0 || v.endsWith(separator) ? v + s : v + separator + s); - } - project.getProperties().putAll(properties); - File[] outputFiles = builder.build(); - log.info("Successfully executed JavaCPP Builder"); - if (log.isDebugEnabled()) { - log.debug("outputFiles: " + Arrays.deepToString(outputFiles)); - } - } catch (Exception e) { - log.error("Failed to execute JavaCPP Builder: " + e.getMessage()); - throw new MojoExecutionException("Failed to execute JavaCPP Builder", e); - } - } -} diff --git a/All/Genesis-NP/Genesis#383/old/CHANGELOG.md b/All/Genesis-NP/Genesis#383/old/CHANGELOG.md deleted file mode 100755 index a237cf8..0000000 --- a/All/Genesis-NP/Genesis#383/old/CHANGELOG.md +++ /dev/null @@ -1,241 +0,0 @@ - - * Add `Info.virtualize` to have the `Parser` generate `@Virtual abstract` for pure virtual functions in the given classes - * Add `@Virtual` annotation and update `Generator` to support callback by overriding such annotated `native` or `abstract` methods - * Add hack for `typedef void*` definitions and parameters with a double indirection to them - -### July 27, 2014 version 0.9 - * Fix `Generator.checkPlatform()` not checking super classes - * Add `includePath`, `linkPath`, and `preloadPath` parameters to `BuildMojo` to let Maven users append paths to the properties easily - * In consequence, remove too arbitrary "local" paths from the default platform properties - * Fix a few other more or less minor issues in the `Parser` with the `long double`, `ptrdiff_t`, `intptr_t`, `uintptr_t`, `off_t` types, floating-point numbers, macro redefinitions, access specifiers, casting of const values by reference, optional parentheses, const data types in templates, declarator names equal to a type name, friend functions, inline constructors, `typedef void` declarations within namespaces, pointers to function pointers - * Allow users to instruct the `Parser` to skip the expansion of specific macro invocations - * Let `Parser` concatenate tokens when expanding macros containing the `##` operator - * Add some documentation for `Info`, `InfoMap`, `InfoMapper`, and `Parser` - * Fix the `Parser` not filtering and expanding properly some preprocessor directives, as well as producing wrong code for `typedef struct *` - * Skip Java path search when building for Android to prevent including some random `jni.h` file ([issue #3](https://github.com/bytedeco/javacpp/issues/3)) - * Fix the `Parser` losing some keywords like `static` on methods annotated with an `@Adapter` ([issue #2](https://github.com/bytedeco/javacpp/issues/2)) - * Fix `Loader.load()` not properly force loading all inherited target classes ([issue #1](https://github.com/bytedeco/javacpp/issues/1)) - -### April 28, 2014 version 0.8 - * Move from Google Code to GitHub as main source code repository - * Place build-time classes in the `org.bytedeco.javacpp.tools` package and bring out static nested classes, in an effort to avoid conflicts and ease development - * Rename the `com.googlecode.javacpp` package to `org.bytedeco.javacpp` - * Added `public long Pointer.address()` getter method, useful when one needs to subtract two pointers - * Removed old NetBeans project files that cause a conflict when trying to open as a Maven project (issue javacv:210) - * Fixed compilation error on `FunctionPointer` classes containing no native callback methods - * Added a `platform.library.path` property, such as "lib/armeabi/" in the case of the "android-arm" platform, to be used instead of "package/platform" (issue javacv:427) - * Generalized references to the path of the Android NDK - * Improved a few small things in the set of `Pointer` classes - * Introduced a simple `Logger` class and unified the logging output calls around it - * Unified the property names with the `@Properties` and `@Platform` annotations into a consistent naming scheme - * Continued to clean up the `Parser` and improve the support of, for the most part, comments, enumerations, functions pointers, anonymous `struct` or `union`, templates, overloaded operators, namespaces, standard containers, default parameter arguments, multiple inheritance, custom names of wrapped declarators, and helper classes written in Java - * Annotations such as `@Adapter` or `@ByVal` are no longer ignored on parameters of getters or setters annotated with `@Index` - * Fixed some other corner cases in `Generator` and a few potential issues with the hacks in `Loader` - * Added for convenience to `PointerPointer` a generic parameter `

` and the associated `get(Class

...)` getters, as well as `String` getters and setters - * Passing a `Class` object as first argument to a native method that returns a `Pointer` now determines the runtime type of that returned object - * Generalized somewhat more the compiler options used inside `linux-arm.properties` (issue javacv:418) - * Unified the function pointer type of native deallocators to `void (*)(void*)` - * Removed dependency on (efficient) `AllocObject()` and `CallNonvirtualVoidMethodA()` JNI functions, which are not supported by Avian - * Cleaned up and optimized `Generator` a bit, also fixing a crash that could occur when `FindClass()` returns `NULL` - -### January 6, 2014 version 0.7 - * Tweaked a few things to support RoboVM and target iOS, but `JNI_OnLoad()` does not appear to get called... - * Upgraded references of the Android NDK to version r9c - * Made `Loader.load()` work, within reason, even when all annotations and resources have been removed, for example, by ProGuard - * Fixed compile error when using a `FunctionPointer` as parameter from outside its top-level enclosing class - * Added new `Pointer.deallocate(false)` call to disable garbage collection on a per object basis, allowing users to deal with memory leaks in other ways - * Changed the default compiler option `-mfpu=vfpv` for ARM to `-mfpu=vfpv3-d16`, because the former is not supported by Tegra 2 (issue javacv:366) - * Removed call to `Arrays.copyOf()` in `Loader.findLibrary()`, which would prevent it from working on Android 2.2 (issue #39) - * Fixed invalid code generated for `FunctionPointer` parameters annotated with `@Const @ByRef` - * Fixed `NullPointerException` in `Loader.load()` when no `@Platform` annotation is provided (issue #38) - * Parsing for anonymous `struct` or `union` and for `typedef void` (mapped to `@Opaque Pointer`) now outputs something - * The `Parser` now expands preprocessor macros, filters tokens appropriately, and outputs all unprocessed directives as comments - * Improved the C++ support of the `Parser` for namespaces, derived classes, access specifiers, custom constructors, vector types, macros, templates, overloaded operators, etc - * Fixed `typedef` of function pointers and a few code formatting issues with `Parser` - * Supplied checks to prevent `Loader.load()` from throwing `java.lang.IllegalStateException: Can't overwrite cause` - -### September 15, 2013 version 0.6 - * Added new very preliminary `Parser` to produce Java interface files almost automatically from C/C++ header files; please refer to the new JavaCPP Presets subproject for details - * When catching a C++ exception, the first class declared after `throws` now gets thrown (issue #36) instead of `RuntimeException`, which is still used by default - * Fixed Java resource leak after catching a C++ exception - * Upgraded references of the Android NDK to version r9 - * Added new `Builder` option "-copylibs" that copies into the build directory any dependent shared libraries listed in the `@Platform(link={...}, preload={...})` annotation - * `Loader.getPlatformName()` can now be overridden by setting the `com.googlecode.javacpp.platform.name` system property - * Refactored the loading code for `@Properties()` into a neat `Loader.ClassProperties` class, among a few other small changes in `Loader`, `Builder`, `Generator`, and the properties - * Included often used directories such as `/usr/local/include/` and `/usr/local/lib/` to `compiler.includepath` and `compiler.linkpath` default properties - * New `@Properties(inherit={Class})` value lets users specify properties in common on a similarly annotated shared config class of sorts - * Fixed callbacks when used with custom class loaders such as with Web containers or frameworks like Tomcat and Play - * Fixed using `@StdString` (or other `@Adapter` with `@Cast` annotations) on callbacks (issue #34), incidentally allowing them to return a `String` - * By default, `Builder` now links to the `jvm` library only when required, when using the `-header` command line option (issue #33) - * Incorporated missing explicit cast on return values when using the `@Cast` annotation - * Fixed duplicate code getting generated when both specifying the output filename with `-o ` and using wildcards on packages containing nested classes - * Let `Buffer` or arrays of primitive values be valid return and callback arguments, mostly useful when used along with the `@StdVector` annotation, or some other custom adapter - -### April 7, 2013 version 0.5 - * Upgraded references of the Android NDK to version r8e - * Arguments of `Pointer` type now get handled as `char*` in cases when the `position` can be used for arithmetic - * Worked around bug of `InputStream.available()` always returning 0 with the `http` protocol in `Loader.extractResource(URL)` - -### March 3, 2013 version 0.4 - * Fixed potential problem with methods of `FunctionPointer` annotated with `@Cast("const...")` - * Upgraded references of the Android NDK to version r8d - * Fixed callbacks not working on Android anymore (issue #30) - * Added some Javadoc to most of the code - * To help diagnose `UnsatisfiedLinkError` thrown by `Loader.load()`, they have been augmented with a potential cause originating from the "preloading" of libraries, whose premature deletion has also been fixed - * Provided new `@Platform(library="...")` annotation value to let users specify the name of the native library used by both `Builder` and `Loader`, where different classes with the same name get built together, which also works on nested classes (issue #29) - * Added the ability to change the name of the class of function objects created when defining a `FunctionPointer` with the `@Name` annotation - * `Builder` would go on a compile spree when all classes specified on the command line could not be loaded - * Exported `Loader.isLoadLibraries()`, which always returns true, except when the `Builder` loads the classes - * Made it possible to specify a nested class (with a '$' character in the name) on the command line - * When `Pointer.limit == 0`, the methods `put()`, `zero()`, and `asBuffer()` now assume a size of 1 - * Fixed compiler error on 32-bit Mac OS X - -### November 4, 2012 version 0.3 - * Added `Pointer.withDeallocator(Pointer)` method to attach easily a custom `Deallocator` created out of a `static void deallocate(Pointer)` method in the subclass, including native ones such as `@Namespace @Name("delete") static native void deallocate(Pointer)` - * A name starting with "::", for example `@Name("::std::string")` or `@Namespace("::std")`, now drops the remaining enclosing scope - * Removed confusing `cast` value of `@Adapter` instead relying on new `String[]` value of `@Cast` to order multiple casts - * Renamed various variables in `Generator` to make the generated code more readable - * Fixed memory corruption when using an adapter or `@ByRef` on a function that returns by value an `std::vector<>` or `std::string` (issue #26) - * Added `Pointer.zero()` method that calls `memset(0)` on the range - * For easier memory management, more than one `Pointer` now allowed to share the `deallocator` when "casting" them - * Upgraded references of the Android NDK to version r8b - * Fixed `JavaCPP_log()` not printing correctly (issue #27) - * Added functionality to access easily `FunctionPointer` callbacks by their names from C/C++: We can annotate them with `@Name` and build with the new `-header` option to get their declarations in a header file, while the `Builder` links with the `jvm` library by default - * `Loader` now displays an informative error message when trying to use an undefined `compiler.options` with `@Platform(options="")` (issue #24) - * `Pointer.deallocator()` would needlessly enqueue `Deallocator` objects pointing to the native `NULL` address - * Added support for C++ "functors" based on the `operator()`, which gets used when annotating a `FunctionPointer` method parameter with `@ByRef` or `@ByVal` - * For convenience in Scala, added `apply()` as an acceptable caller method name within a `FunctionPointer`, in addition to `call()` - * Fixed `@Cast` not working along parameters with an `@Adapter` or when attempting to `return` the argument - * `Generator` would ignore `Pointer.position()` in the case of `@ByPtrPtr` and `@ByPtrRef` parameters - * Replaced hack to create a `Pointer` from a `Buffer` object with something more standard - * Fixed `Loader.sizeof(Pointer.class)` to return the `sizeof(void*)` - * In addition to methods and parameters, we may now apply `@Adapter` to annotation types as well, allowing us to shorten expressions like `@Adapter("VectorAdapter") int[]` to just `@StdVector int[]`, for `std::vector` support, and similarly for `@StdString` and `std::string` - * Fixed callback parameter casting of primitive and `String` types - * An empty `@Namespace` can now be used to let `Generator` know of entities that are not part of any scope, such as macros and operators - * Turned `FunctionPointer` into an `abstract class` with `protected` constructors, but if users still try to use it as function parameters, `Generator` now logs a warning indicating that a subclass should be used (issue #23) - * Removed the `out` value of the `@Adapter` annotation: All adapters are now "out" by default, unless `@Const` also appears on the same element - * Fixed `Pointer.equals(null)` throwing `NullPointerException` (issue #22) - * `@NoOffset` would erroneously prevent `sizeof()` operations from getting generated - -### July 21, 2012 version 0.2 - * Fixed problems when trying to map `java.lang.String` to other native types than `char*`, such as `unsigned char*` - * JavaCPP now uses the `new (std::nothrow)` operator for allocation, which guarantees that allocation of primitive native arrays won't throw exceptions, making it possible to build C++ exception free JNI libraries - * Added new `Pointer.limit` property, mainly useful to get the `size` of an output parameter, as returned by an adapter specified with the `@Adapter` annotation - * Renamed the `capacity` field of an adapter to `size` as it now maps to both `Pointer.limit` and `Pointer.capacity` (the latter only for new allocations) - * Added `Pointer.put(Pointer)` method, the counterpart of `Buffer.put(Buffer)`, to call the native `memcpy()` function on two `Pointer` objects - * New `@NoException` annotation to reduce the size of generated code and optimize runtime performance of functions that are guaranteed not to throw exceptions, or for cases when we do not mind that the JVM may crash and burn - * Trying to generate code for non-static native methods inside a class not extending `Pointer` now generates proper warning (issue #19) - * Fixed regression where the `@Adapter` notation generates incorrect code for types other than `Pointer` (issue #20) - -### May 27, 2012 version 0.1 - * Started using version numbers, friendly to tools like Maven, and placing packages in a sort of [Maven repository](http://maven2.javacpp.googlecode.com/git/) (issue #10) - * Before loading a JNI library, the `Loader` now also tries to extract and load libraries listed in the `@Platform(link={...}, preload={...})` annotation values, and to support library names with version numbers, each value has to follow the format "libname@version" (or "libname@@version" to have `Builder` use it for the compiler as well), where "version" is the version number found in the filename as required by the native dynamic linker, usually a short sequence of digits and dots, but it can be anything (e.g.: "mylib@.4.2" would map to "libmylib.so.4.2", "libmylib.4.2.dylib", and "mylib.4.2.dll" under Linux, Mac OS X, and Windows respectively) - * All files now get extracted into a temporary subdirectory, and with the appropriate platform-dependent linker options, or with libraries patched up after the fact with tools such as `install_name_tool` of Mac OS X, most native dynamic linkers can load dependent libraries from there - * Stopped using `java.net.URL` as hash key in `Loader` (very bad idea) - * Changed the default value of the `@Index` annotation from 0 to 1, and fixed the `Generator` when it is used with member getters and setters - * Renamed `mingw-*.properties` to `windows-*-mingw.properties` for consistency - * Made the `Generator` allocate native heap memory for callback arguments passed `@ByVal` (in addition to `FunctionPointer`), rendering their behavior consistent with return `@ByVal` in the case of function calls (issue #16) - * `Generator` now uses `std::runtime_error(std::string&)` instead of assuming that some nonstandard `std::exception(std::string&)` constructor exists (issue #17) - * Fixed `Generator` producing incorrect code when applying invalid annotations such as `@ByVal` on a method that returns something else than a `Pointer` object (issue #18) - -### May 12, 2012 - * Added `pom.xml` file and `BuildMojo` plugin class for Maven support and changed the directory structure of the source code to match Maven's standard directory layout (issue #10) Many thanks to Adam Waldenberg and Arnaud Nauwynck for their ongoing support with that! - * Moved the source code repository to Git - * Created a new `@Raw` annotation to use Java object as raw `jobject` in C++, also passing `JNIEnv` and the enclosing `jclass` or the `jobject` corresponding to `this`, as the first two arguments of the function, when the `Generator` encounters any `@Raw(withEnv=true)` (issue #13) - * The `Builder` now handles more cases when some prefix or suffix property starts or ends with a space (issue #14) - * Fixed syntax error in `VectorAdapter`, which GCC and Visual C++ would still happily compile - * Added new `source.suffix` property to have the names of generated source files end with something else than `.cpp` and support frameworks like CUDA that require filenames with a `.cu` extension to compile properly, such as used by the new `*-cuda.properties`, and also changed the "-cpp" command line option to "-nocompile" - * New `Loader.loadLibrary()` method similar to `System.loadLibrary()`, but before searching the library path, it tries to extract and load the library from Java resources - * `Generator` now accepts `@Const` on `FunctionPointer` class declarations - * Added new `@Adapter.cast()` value to cast explicitly the output of a C++ adapter object - * Upgraded references of the Android NDK to version r8 - * Included new command line option "-Xcompiler" to pass options such as "-Wl,-static" directly to the compiler - * Made other various minor changes and enhancements - -### March 29, 2012 - * Added new `compiler.framework` property and corresponding `@Platform.framework()` value to allow easier binding with Mac OS X frameworks - * Changed most `Builder` errors into warnings, letting the building process complete successfully more often - * We may now use the `@NoDeallocator` annotation on a class to disable deallocation for all allocation methods - -### March 03, 2012 - * Added new `@NoDeallocator` annotation to prevent `allocate()` and `allocateArray()` methods from registering a native deallocator to `Pointer` objects (issue #1) - * `Generator` now properly skips as unsupported array parameters that do not have a primitive component type, and logs a warning (issue #7) - * `Generator` and `Builder` would append the same include files, libraries, or options multiple times when not required: Fixed in `Loader.appendProperty()` (issue #8) - * Moved the placement of the class-level @Index annotation to the getter and setter methods themselves - * To process all classes in a package, we may now specify as argument to the `Builder` its name followed by ".*", in a similar fashion to the `import` statement of the Java language, or by ".**" to process recursively all packages, while omitting to specify any class or package results in JavaCPP processing all classes found under the directories or JAR files specified with the "-classpath" option (issue #12) - * Equipped the `*Pointer` classes with new bulk `get()` and `put()` methods taking an array as argument, to compensate for direct NIO buffers lacking in performance on Android (issue #11) - -### February 18, 2012 - * Cleaned up a few minor `Exception` blocks - * New `Pointer.deallocateReferences()` static method to force immediate deallocation of all native memory allocated by `Pointer` objects that since have been garbage collected - * Updated `android-arm.properties` to reflect the fact that, starting from Android NDK r7, `libstdc++.a` has been surreptitiously renamed to `libgnustl_static.a`, such that JavaCPP was instead linking to a new bogus `libstdc++.so` library, causing runtime linking errors - * Included new `android-x86.properties` to compile binaries for that platform as well - * Added new `compiler.sysroot.prefix` and `compiler.sysroot` platform properties to pass options such as `--sysroot` to satisfy new rituals of the Android NDK starting from r7b - * Upgraded references of the Android NDK to version r7b - -### January 8, 2012 - * Added new `compiler.linkpath.prefix2` platform property to pass options such as `-Wl,-rpath,` to linkers that support them - * Fixed `Loader.load()` on Android 4.0, where `SecurityManager.getClassContext()` returns `null` - * Upgraded references of the Android NDK to version r7 - -### October 29, 2011 - * Changed the following to make MinGW work: `Generator` now maps `jlong` to the more standard `long long` instead of `__int64` type and also includes `stdint.h`, and added `-D_JNI_IMPLEMENTATION_ -Wl,--kill-at` to the compiler options, as recommended by MinGW's documentation for building DLLs compatible with JNI - * Added hack for `AttachCurrentThread()`, whose signature differs under Android, and `DetachCurrentThread()` now gets called as appropriate after returning from a callback function, to prevent memory leaks (and also crashes on platforms such as Android) (issue #3) - * `Generator` now generates correct code for the annotation pairs `@Const @ByRef` and `@Const @ByVal` (issue #4) - * Worked around callback functions crashing on Android, which is unable to load user classes from native threads (issue #5) - * Fixed a few potential pitfalls inside `Generator` and `Loader` - * Removed compiler warnings due to the type of the `capacity` member variable of `VectorAdapter` - * Callback `FunctionPointer` objects may now return `@ByVal` or `@ByRef` - * On Android, changed the output of runtime error messages from `stderr` (equivalent to `/dev/null` on Android) to the log - -### October 1, 2011 - * Changed default option flag "/MT" to "/MD" (and a few others that Visual Studio uses by default) inside `windows-x86.properties` and `windows-x86_64.properties` because `std::vector`, `VectorAdapter` and C++ memory allocation in general does not work well with static runtime libraries across DLLs under Windows Vista and Windows 7 for some reason, and because Microsoft fixed the manifest file insanity starting with Visual C++ 2010 - * `Builder` now searches for `jni.h` and `jni_md.h` inside `/System/Library/Frameworks/JavaVM.framework/Headers/` if not found inside `java.home`, as with Mac OS X Lion (issue #2) - * Upgraded references of the Android NDK to version r6b - * Fixed a few potential pitfalls inside `Generator` - * Added hack to let `*Pointer` classes with a corresponding `*Buffer` class have constructors for them - -### July 5, 2011 - * `Generator` now lets `get()/put()` (or the `ValueGetter/ValueSetter` annotated) methods use non-integer indices for the `Index` annotation - * Removed calls to `Arrays.copyOf()` inside `getString*()` methods so they may work on Android as well - * Fixed race condition that could occur in the deallocation code of `Pointer` due to incorrect synchronization - * `platform.root` now defaults to the current directory - -### June 10, 2011 - * New `Adapter` annotation that uses C++ classes such as `VectorAdapter`, which can let us use Java arrays or `Pointer` objects in place of C++ vector objects by mapping types such as `vector` to `@Adapter("VectorAdapter") int[]` or `@Adapter("VectorAdapter") IntPointer` - * Added new `Pointer.capacity` field to keep track of allocated size for arrays, needed by the `Adapter` annotation - * Removed the `capacity` parameter from the `Pointer.asByteBuffer()` and `Pointer.asBuffer()` methods, which now rely instead on the value of the new `capacity` field - * `ValueGetter` and `ValueSetter`, defaulting to the `get()` and `put()` methods, now accept indices as arguments, and `*Pointer` classes have been updated accordingly - * New `Index` annotation to indicate that a C++ class, such as `vector` implements the `operator[]` that can be mapped to the `ValueGetter` and `ValueSetter` as well as to arbitrary function calls, taking the first n arguments as indices, where n is the value placed in the annotation - * The `Name` annotation now accepts as value a `String` array to indicate names before and after these indices - * New `Const` annotation for convenience - * Fixed scoping of static members inside namespaces and classes - * Added new `BoolPointer` class - * Improved support of function pointers to generate more standard C++ and to make it work with things like member function pointers - * Inserted hack to call `std::string.c_str()` when returned as `@ByRef java.lang.String` - * Multiplied checks for invalid `NULL` pointers - * Upgraded references of the Android NDK to version r5c, which now also works on Android 2.1 or older ([android issue #16008](http://code.google.com/p/android/issues/detail?id=16008)) - * `Loader.load()` no longer requires a JVM that supports annotations to function properly - -### April 22, 2011 - * `Generator` now outputs `#include `, the lack of which prevents Android NDK under Windows from compiling - -### April 7, 2011 - * Replaced arrays from constructors with variable-length argument lists for convenience - * Fixed a few small potential pitfalls previously overlooked - -### March 1, 2011 - * Fixed directory search for `jni_md.h`, which did not search deep enough in some cases - * Added new `path.separator` property to set the path separator of the target platform, regardless of the build platform - * Added hack to make sure the temporarily extracted library files get properly deleted under Windows - * Now loads classes more lazily - * Changed the paths for libstdc++ inside `android-arm.properties` to the non "v7a" versions - * Added new `platform.root` property to let users specify the path to their toolchains more easily - -### February 18, 2011 -Initial release - - -Acknowledgments ---------------- -This project was conceived at the [Okutomi & Tanaka Laboratory](http://www.ok.ctrl.titech.ac.jp/), Tokyo Institute of Technology, where I was supported for my doctoral research program by a generous scholarship from the Ministry of Education, Culture, Sports, Science and Technology (MEXT) of the Japanese Government. I extend my gratitude further to all who have reported bugs, donated code, or made suggestions for improvements (details above)! diff --git a/All/Genesis-NP/Genesis#383/pair.info b/All/Genesis-NP/Genesis#383/pair.info deleted file mode 100755 index a0aad6e..0000000 --- a/All/Genesis-NP/Genesis#383/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:383 -SATName:Genesis -modifiedFPath:src/main/java/org/bytedeco/javacpp/tools/BuildMojo.java -comSha:0c7bd3a37c6d190fa113fc01d58008b886727be7 -parentComSha:0c7bd3a37c6d190fa113fc01d58008b886727be7^1 -githubUrl:https://github.com/bytedeco/javacpp -repoName:bytedeco#javacpp \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#387/comMsg.txt b/All/Genesis-NP/Genesis#387/comMsg.txt deleted file mode 100755 index 2fc5541..0000000 --- a/All/Genesis-NP/Genesis#387/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -[issue 46] Fixed NullPointerException when propertyWordDelimiters is not specified diff --git a/All/Genesis-NP/Genesis#387/diff.diff b/All/Genesis-NP/Genesis#387/diff.diff deleted file mode 100755 index 11674a4..0000000 --- a/All/Genesis-NP/Genesis#387/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/jsonschema2pojo-maven-plugin/src/main/java/com/googlecode/jsonschema2pojo/maven/Jsonschema2PojoMojo.java b/jsonschema2pojo-maven-plugin/src/main/java/com/googlecode/jsonschema2pojo/maven/Jsonschema2PojoMojo.java -index 28a9706..7f4af3a 100644 ---- a/jsonschema2pojo-maven-plugin/src/main/java/com/googlecode/jsonschema2pojo/maven/Jsonschema2PojoMojo.java -+++ b/jsonschema2pojo-maven-plugin/src/main/java/com/googlecode/jsonschema2pojo/maven/Jsonschema2PojoMojo.java -@@ -129 +129 @@ public class Jsonschema2PojoMojo extends AbstractMojo implements -- private String propertyWordDelimiters; -+ private String propertyWordDelimiters = ""; diff --git a/All/Genesis-NP/Genesis#387/new/Jsonschema2PojoMojo.java b/All/Genesis-NP/Genesis#387/new/Jsonschema2PojoMojo.java deleted file mode 100755 index 7f4af3a..0000000 --- a/All/Genesis-NP/Genesis#387/new/Jsonschema2PojoMojo.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * Copyright © 2010-2011 Nokia - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.googlecode.jsonschema2pojo.maven; - -import java.io.File; -import java.io.IOException; - -import org.apache.maven.artifact.DependencyResolutionRequiredException; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; - -import com.googlecode.jsonschema2pojo.GenerationConfig; -import com.googlecode.jsonschema2pojo.cli.Jsonschema2Pojo; - -/** - * When invoked, this goal reads one or more JSON Schema documents and generates DTO - * style Java classes for data binding. - *

- * See jsonschema2pojo.googlecode.com. - * - * @goal generate - * @phase generate-sources - * @requiresDependencyResolution compile - * @see Mojo - * API Specification - */ -public class Jsonschema2PojoMojo extends AbstractMojo implements - GenerationConfig { - - /** - * Target directory for generated Java source files. - * - * @parameter expression="${jsonschema2pojo.outputDirectory}" - * default-value="${project.build.directory}/java-gen" - * @since 0.1.0 - */ - private File outputDirectory; - - /** - * Location of the JSON Schema file(s). Note: this may refer to a single - * file or a directory of files. - * - * @parameter expression="${jsonschema2pojo.sourceDirectory}" - * @required - * @since 0.1.0 - */ - private File sourceDirectory; - - /** - * Package name used for generated Java classes (for types where a fully - * qualified name has not been supplied in the schema using the 'javaType' - * property). - * - * @parameter expression="${jsonschema2pojo.targetPackage}" - * @since 0.1.0 - */ - private String targetPackage = ""; - - /** - * Whether to generate builder-style methods of the form - * withXxx(value) (that return this), alongside - * the standard, void-return setters. - * - * @parameter expression="${jsonschema2pojo.generateBuilders}" - * default-value="false" - * @since 0.1.2 - */ - private boolean generateBuilders; - - /** - * Whether to use primitives (long, double, - * boolean) instead of wrapper types where possible when - * generating bean properties (has the side-effect of making those - * properties non-null). - * - * @parameter expression="${jsonschema2pojo.usePrimitives}" - * default-value="false" - * @since 0.2.0 - */ - private boolean usePrimitives; - - /** - * Add the output directory to the project as a source root, so that the - * generated java types are compiled and included in the project artifact. - * - * @parameter expression="${jsonschema2pojo.addCompileSourceRoot}" - * default-value="true" - * @since 0.1.9 - */ - private boolean addCompileSourceRoot = true; - - /** - * Skip plugin execution (don't read/validate any schema files, don't - * generate any java types). - * - * @parameter expression="${jsonschema2pojo.skip}" default-value="false" - * @since 0.2.1 - */ - private boolean skip = false; - - /** - * The characters that should be considered as word delimiters when creating - * Java Bean property names from JSON property names. If blank or not set, - * JSON properties will be considered to contain a single word when creating - * Java Bean property names. - * - * @parameter expression=${jsonschema2pojo.propertyWordDelimiters} - * default-value="" - * @since 0.2.2 - */ - private String propertyWordDelimiters = ""; - - /** - * Whether to use the java type long (or - * Long) instead of int (or - * Integer) when representing the JSON Schema type 'integer'. - * - * @parameter expression=${jsonschema2pojo.useLongIntegers} - * default-value="false" - * @since 0.2.2 - */ - private boolean useLongIntegers = false; - - /** - * The project being built. - * - * @parameter expression="${project}" - * @required - * @readonly - */ - private MavenProject project; - - /** - * Executes the plugin, to read the given source and behavioural properties - * and generate POJOs. The current implementation acts as a wrapper around - * the command line interface. - */ - @Override - @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { - "NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD" }, justification = "Private fields set by Maven.") - public void execute() throws MojoExecutionException { - - if (skip) { - return; - } - - if (addCompileSourceRoot) { - project.addCompileSourceRoot(outputDirectory.getPath()); - } - - addProjectDependenciesToClasspath(); - - try { - Jsonschema2Pojo.generate(this); - } catch (IOException e) { - throw new MojoExecutionException( - "Error generating classes from JSON Schema file(s) " - + sourceDirectory.getPath(), e); - } - - } - - private void addProjectDependenciesToClasspath() { - - try { - - ClassLoader oldClassLoader = Thread.currentThread() - .getContextClassLoader(); - ClassLoader newClassLoader = new ProjectClasspath().getClassLoader( - project, oldClassLoader, getLog()); - Thread.currentThread().setContextClassLoader(newClassLoader); - - } catch (DependencyResolutionRequiredException e) { - getLog().info( - "Skipping addition of project artifacts, there appears to be a dependecy resolution problem", - e); - } - - } - - @Override - public boolean isGenerateBuilders() { - return generateBuilders; - } - - @Override - public File getTargetDirectory() { - return outputDirectory; - } - - @Override - public File getSource() { - return sourceDirectory; - } - - @Override - public boolean isUsePrimitives() { - return usePrimitives; - } - - @Override - public String getTargetPackage() { - return targetPackage; - } - - @Override - public char[] getPropertyWordDelimiters() { - return propertyWordDelimiters.toCharArray(); - } - - @Override - public boolean isUseLongIntegers() { - return useLongIntegers; - } - -} diff --git a/All/Genesis-NP/Genesis#387/old/Jsonschema2PojoMojo.java b/All/Genesis-NP/Genesis#387/old/Jsonschema2PojoMojo.java deleted file mode 100755 index 28a9706..0000000 --- a/All/Genesis-NP/Genesis#387/old/Jsonschema2PojoMojo.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * Copyright © 2010-2011 Nokia - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.googlecode.jsonschema2pojo.maven; - -import java.io.File; -import java.io.IOException; - -import org.apache.maven.artifact.DependencyResolutionRequiredException; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.project.MavenProject; - -import com.googlecode.jsonschema2pojo.GenerationConfig; -import com.googlecode.jsonschema2pojo.cli.Jsonschema2Pojo; - -/** - * When invoked, this goal reads one or more JSON Schema documents and generates DTO - * style Java classes for data binding. - *

- * See jsonschema2pojo.googlecode.com. - * - * @goal generate - * @phase generate-sources - * @requiresDependencyResolution compile - * @see Mojo - * API Specification - */ -public class Jsonschema2PojoMojo extends AbstractMojo implements - GenerationConfig { - - /** - * Target directory for generated Java source files. - * - * @parameter expression="${jsonschema2pojo.outputDirectory}" - * default-value="${project.build.directory}/java-gen" - * @since 0.1.0 - */ - private File outputDirectory; - - /** - * Location of the JSON Schema file(s). Note: this may refer to a single - * file or a directory of files. - * - * @parameter expression="${jsonschema2pojo.sourceDirectory}" - * @required - * @since 0.1.0 - */ - private File sourceDirectory; - - /** - * Package name used for generated Java classes (for types where a fully - * qualified name has not been supplied in the schema using the 'javaType' - * property). - * - * @parameter expression="${jsonschema2pojo.targetPackage}" - * @since 0.1.0 - */ - private String targetPackage = ""; - - /** - * Whether to generate builder-style methods of the form - * withXxx(value) (that return this), alongside - * the standard, void-return setters. - * - * @parameter expression="${jsonschema2pojo.generateBuilders}" - * default-value="false" - * @since 0.1.2 - */ - private boolean generateBuilders; - - /** - * Whether to use primitives (long, double, - * boolean) instead of wrapper types where possible when - * generating bean properties (has the side-effect of making those - * properties non-null). - * - * @parameter expression="${jsonschema2pojo.usePrimitives}" - * default-value="false" - * @since 0.2.0 - */ - private boolean usePrimitives; - - /** - * Add the output directory to the project as a source root, so that the - * generated java types are compiled and included in the project artifact. - * - * @parameter expression="${jsonschema2pojo.addCompileSourceRoot}" - * default-value="true" - * @since 0.1.9 - */ - private boolean addCompileSourceRoot = true; - - /** - * Skip plugin execution (don't read/validate any schema files, don't - * generate any java types). - * - * @parameter expression="${jsonschema2pojo.skip}" default-value="false" - * @since 0.2.1 - */ - private boolean skip = false; - - /** - * The characters that should be considered as word delimiters when creating - * Java Bean property names from JSON property names. If blank or not set, - * JSON properties will be considered to contain a single word when creating - * Java Bean property names. - * - * @parameter expression=${jsonschema2pojo.propertyWordDelimiters} - * default-value="" - * @since 0.2.2 - */ - private String propertyWordDelimiters; - - /** - * Whether to use the java type long (or - * Long) instead of int (or - * Integer) when representing the JSON Schema type 'integer'. - * - * @parameter expression=${jsonschema2pojo.useLongIntegers} - * default-value="false" - * @since 0.2.2 - */ - private boolean useLongIntegers = false; - - /** - * The project being built. - * - * @parameter expression="${project}" - * @required - * @readonly - */ - private MavenProject project; - - /** - * Executes the plugin, to read the given source and behavioural properties - * and generate POJOs. The current implementation acts as a wrapper around - * the command line interface. - */ - @Override - @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { - "NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD" }, justification = "Private fields set by Maven.") - public void execute() throws MojoExecutionException { - - if (skip) { - return; - } - - if (addCompileSourceRoot) { - project.addCompileSourceRoot(outputDirectory.getPath()); - } - - addProjectDependenciesToClasspath(); - - try { - Jsonschema2Pojo.generate(this); - } catch (IOException e) { - throw new MojoExecutionException( - "Error generating classes from JSON Schema file(s) " - + sourceDirectory.getPath(), e); - } - - } - - private void addProjectDependenciesToClasspath() { - - try { - - ClassLoader oldClassLoader = Thread.currentThread() - .getContextClassLoader(); - ClassLoader newClassLoader = new ProjectClasspath().getClassLoader( - project, oldClassLoader, getLog()); - Thread.currentThread().setContextClassLoader(newClassLoader); - - } catch (DependencyResolutionRequiredException e) { - getLog().info( - "Skipping addition of project artifacts, there appears to be a dependecy resolution problem", - e); - } - - } - - @Override - public boolean isGenerateBuilders() { - return generateBuilders; - } - - @Override - public File getTargetDirectory() { - return outputDirectory; - } - - @Override - public File getSource() { - return sourceDirectory; - } - - @Override - public boolean isUsePrimitives() { - return usePrimitives; - } - - @Override - public String getTargetPackage() { - return targetPackage; - } - - @Override - public char[] getPropertyWordDelimiters() { - return propertyWordDelimiters.toCharArray(); - } - - @Override - public boolean isUseLongIntegers() { - return useLongIntegers; - } - -} diff --git a/All/Genesis-NP/Genesis#387/pair.info b/All/Genesis-NP/Genesis#387/pair.info deleted file mode 100755 index 07c4f7a..0000000 --- a/All/Genesis-NP/Genesis#387/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:387 -SATName:Genesis -modifiedFPath:jsonschema2pojo-maven-plugin/src/main/java/com/googlecode/jsonschema2pojo/maven/Jsonschema2PojoMojo.java -comSha:6961e11ba289988dc21f80db7314f1ee5e2ce7b8 -parentComSha:6961e11ba289988dc21f80db7314f1ee5e2ce7b8^1 -githubUrl:https://github.com/joelittlejohn/jsonschema2pojo -repoName:joelittlejohn#jsonschema2pojo \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#388/comMsg.txt b/All/Genesis-NP/Genesis#388/comMsg.txt deleted file mode 100755 index 17adc52..0000000 --- a/All/Genesis-NP/Genesis#388/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix NPE on kubernetes diff --git a/All/Genesis-NP/Genesis#388/diff.diff b/All/Genesis-NP/Genesis#388/diff.diff deleted file mode 100755 index a506282..0000000 --- a/All/Genesis-NP/Genesis#388/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/components/kubernetes-api/src/main/java/io/fabric8/kubernetes/api/builds/Builds.java b/components/kubernetes-api/src/main/java/io/fabric8/kubernetes/api/builds/Builds.java -index ab92eb2..0891f1f 100644 ---- a/components/kubernetes-api/src/main/java/io/fabric8/kubernetes/api/builds/Builds.java -+++ b/components/kubernetes-api/src/main/java/io/fabric8/kubernetes/api/builds/Builds.java -@@ -33,0 +34 @@ import io.fabric8.utils.URLUtils; -+import java.util.ArrayList; -@@ -111,0 +113,3 @@ public class Builds { -+ if (triggers == null) { -+ triggers = new ArrayList<>(); -+ } diff --git a/All/Genesis-NP/Genesis#388/new/Builds.java b/All/Genesis-NP/Genesis#388/new/Builds.java deleted file mode 100755 index 0891f1f..0000000 --- a/All/Genesis-NP/Genesis#388/new/Builds.java +++ /dev/null @@ -1,281 +0,0 @@ -/** - * Copyright 2005-2016 Red Hat, Inc. - * - * Red Hat 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 io.fabric8.kubernetes.api.builds; - -import io.fabric8.kubernetes.api.KubernetesHelper; -import io.fabric8.kubernetes.api.builders.ListEnvVarBuilder; -import io.fabric8.kubernetes.api.model.ObjectReferenceBuilder; -import io.fabric8.openshift.api.model.Build; -import io.fabric8.openshift.api.model.BuildConfig; -import io.fabric8.openshift.api.model.BuildConfigSpec; -import io.fabric8.openshift.api.model.BuildSource; -import io.fabric8.openshift.api.model.BuildStrategy; -import io.fabric8.openshift.api.model.BuildTriggerPolicy; -import io.fabric8.openshift.api.model.BuildTriggerPolicyBuilder; -import io.fabric8.openshift.api.model.CustomBuildStrategy; -import io.fabric8.openshift.api.model.GitBuildSource; -import io.fabric8.utils.Objects; -import io.fabric8.utils.Strings; -import io.fabric8.utils.URLUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import static io.fabric8.kubernetes.api.KubernetesHelper.getOrCreateMetadata; - -public class Builds { - - public static final String DEFAULT_SECRET = "secret101"; - public static final String DEFAULT_BUILD_IMAGE_STREAM = "triggerJenkins"; - public static final String DEFAULT_IMAGE_TAG = "latest"; - public static final String DEFAULT_CUSTOM_BUILDER_IMAGE = "fabric8/openshift-s2i-jenkins-trigger"; - - public static class Status { - public static final String COMPLETE = "Complete"; - public static final String FAIL = "Fail"; - public static final String ERROR = "Error"; - public static final String CANCELLED = "Cancelled"; - } - - public static BuildConfig createDefaultBuildConfig(String name, String gitUrl, String jenkinsUrl) { - BuildConfig buildConfig = new BuildConfig(); - getOrCreateMetadata(buildConfig).setName(name); - boolean foundExistingGitUrl = false; - return configureDefaultBuildConfig(buildConfig, name, gitUrl, foundExistingGitUrl, jenkinsUrl); - } - - public static BuildConfig configureDefaultBuildConfig(BuildConfig buildConfig, String name, String gitUrl, boolean foundExistingGitUrl, String jenkinsUrl) { - return configureDefaultBuildConfig(buildConfig, name, gitUrl, foundExistingGitUrl, DEFAULT_BUILD_IMAGE_STREAM, DEFAULT_IMAGE_TAG, DEFAULT_CUSTOM_BUILDER_IMAGE, DEFAULT_SECRET, jenkinsUrl); - } - - public static BuildConfig configureDefaultBuildConfig(BuildConfig buildConfig, String name, String gitUrl, boolean foundExistingGitUrl, String buildImageStream, String buildImageTag, String s2iCustomBuilderImage, String secret, String jenkinsUrl) { - BuildConfigSpec spec = buildConfig.getSpec(); - if (spec == null) { - spec = new BuildConfigSpec(); - buildConfig.setSpec(spec); - } - - if (!foundExistingGitUrl && Strings.isNotBlank(gitUrl)) { - BuildSource source = spec.getSource(); - if (source == null) { - source = new BuildSource(); - spec.setSource(source); - } - source.setType("Git"); - GitBuildSource git = source.getGit(); - if (git == null) { - git = new GitBuildSource(); - source.setGit(git); - } - git.setUri(gitUrl); - } - - if (Strings.isNotBlank(buildImageStream) && Strings.isNotBlank(buildImageTag)) { - BuildStrategy strategy = spec.getStrategy(); - if (strategy == null) { - strategy = new BuildStrategy(); - spec.setStrategy(strategy); - } - - // TODO only do this if we are using Jenkins? - strategy.setType("Custom"); - CustomBuildStrategy customStrategy = strategy.getCustomStrategy(); - if (customStrategy == null) { - customStrategy = new CustomBuildStrategy(); - strategy.setCustomStrategy(customStrategy); - } - - ListEnvVarBuilder envBuilder = new ListEnvVarBuilder(); - if (Strings.isNotBlank(jenkinsUrl)) { - envBuilder.withEnvVar("BASE_URI", jenkinsUrl); - } - envBuilder.withEnvVar("JOB_NAME", name); - customStrategy.setEnv(envBuilder.build()); - customStrategy.setFrom(new ObjectReferenceBuilder().withKind("DockerImage").withName(s2iCustomBuilderImage).build()); - } - List triggers = spec.getTriggers(); - if (triggers == null) { - triggers = new ArrayList<>(); - } - if (triggers.isEmpty()) { - triggers.add(new BuildTriggerPolicyBuilder().withType("GitHub").withNewGithub().withSecret(secret).endGithub().build()); - triggers.add(new BuildTriggerPolicyBuilder().withType("Generic").withNewGeneric().withSecret(secret).endGeneric().build()); - spec.setTriggers(triggers); - } - return buildConfig; - } - - public static boolean isCompleted(String status) { - return Objects.equal(Status.COMPLETE, status); - } - - public static boolean isCancelled(String status) { - return Objects.equal(Status.CANCELLED, status); - } - - public static boolean isFailed(String status) { - if (status != null) { - return status.startsWith(Status.FAIL) || status.startsWith(Status.ERROR); - } - return false; - } - - public static boolean isFinished(String status) { - return isCompleted(status) || isFailed(status) || isCancelled(status); - } - - /** - * Returns a unique UUID for a build - */ - public static String getUid(Build build) { - String answer = null; - if (build != null) { - answer = build.getMetadata().getUid(); - if (Strings.isNullOrBlank(answer)) { - Map metadata = getMetadata(build); - answer = getString(metadata, "uid"); - if (Strings.isNullOrBlank(answer)) { - answer = getString(metadata, "id"); - } - if (Strings.isNullOrBlank(answer)) { - answer = getString(metadata, "name"); - } - } - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getName(); - } - } - return answer; - } - - protected static String getString(Map metadata, String name) { - Object answer = metadata.get(name); - if (answer != null) { - return answer.toString(); - } - return null; - } - - public static Map getMetadata(Build build) { - if (build != null) { - Map additionalProperties = build.getAdditionalProperties(); - if (additionalProperties != null) { - Object metadata = additionalProperties.get("metadata"); - if (metadata instanceof Map) { - return (Map) metadata; - } - } - } - return Collections.EMPTY_MAP; - - } - - public static Map getMetadata(BuildConfig build) { - if (build != null) { - Map additionalProperties = build.getAdditionalProperties(); - if (additionalProperties != null) { - Object metadata = additionalProperties.get("metadata"); - if (metadata instanceof Map) { - return (Map) metadata; - } - } - } - return Collections.EMPTY_MAP; - - } - - public static String getName(BuildConfig build) { - String answer = null; - if (build != null) { - Map metadata = getMetadata(build); - answer = getString(metadata, "name"); - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getName(); - } - } - return answer; - } - - public static String getName(Build build) { - String answer = null; - if (build != null) { - Map metadata = getMetadata(build); - answer = getString(metadata, "name"); - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getName(); - } - } - return answer; - } - - public static String getNamespace(Build build) { - String answer = null; - if (build != null) { - Map metadata = getMetadata(build); - answer = getString(metadata, "namespace"); - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getNamespace(); - } - } - return answer; - } - - - public static String getCreationTimestamp(Build build) { - String answer = null; - if (build != null) { - Map metadata = getMetadata(build); - answer = getString(metadata, "creationTimestamp"); - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getCreationTimestamp(); - } - } - return answer; - } - - public static Date getCreationTimestampDate(Build build) { - String text = getCreationTimestamp(build); - if (Strings.isNullOrBlank(text)) { - return null; - } else { - return KubernetesHelper.parseDate(text); - } - } - - - public static String getBuildConfigName(Build build) { - if (build != null) { - Map metadata = getMetadata(build); - Object labels = metadata.get("labels"); - if (labels instanceof Map) { - Map labelMap = (Map) labels; - return getString(labelMap, "buildconfig"); - } - } - return null; - } - - /** - * Returns the link to the build page in the console for the given build UUID - */ - public static String createConsoleBuildLink(String fabricConsoleExternalUrl, String buildName) { - return URLUtils.pathJoin(fabricConsoleExternalUrl, "kubernetes/builds", buildName); - } - -} diff --git a/All/Genesis-NP/Genesis#388/old/Builds.java b/All/Genesis-NP/Genesis#388/old/Builds.java deleted file mode 100755 index ab92eb2..0000000 --- a/All/Genesis-NP/Genesis#388/old/Builds.java +++ /dev/null @@ -1,277 +0,0 @@ -/** - * Copyright 2005-2016 Red Hat, Inc. - * - * Red Hat 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 io.fabric8.kubernetes.api.builds; - -import io.fabric8.kubernetes.api.KubernetesHelper; -import io.fabric8.kubernetes.api.builders.ListEnvVarBuilder; -import io.fabric8.kubernetes.api.model.ObjectReferenceBuilder; -import io.fabric8.openshift.api.model.Build; -import io.fabric8.openshift.api.model.BuildConfig; -import io.fabric8.openshift.api.model.BuildConfigSpec; -import io.fabric8.openshift.api.model.BuildSource; -import io.fabric8.openshift.api.model.BuildStrategy; -import io.fabric8.openshift.api.model.BuildTriggerPolicy; -import io.fabric8.openshift.api.model.BuildTriggerPolicyBuilder; -import io.fabric8.openshift.api.model.CustomBuildStrategy; -import io.fabric8.openshift.api.model.GitBuildSource; -import io.fabric8.utils.Objects; -import io.fabric8.utils.Strings; -import io.fabric8.utils.URLUtils; - -import java.util.Collections; -import java.util.Date; -import java.util.List; -import java.util.Map; - -import static io.fabric8.kubernetes.api.KubernetesHelper.getOrCreateMetadata; - -public class Builds { - - public static final String DEFAULT_SECRET = "secret101"; - public static final String DEFAULT_BUILD_IMAGE_STREAM = "triggerJenkins"; - public static final String DEFAULT_IMAGE_TAG = "latest"; - public static final String DEFAULT_CUSTOM_BUILDER_IMAGE = "fabric8/openshift-s2i-jenkins-trigger"; - - public static class Status { - public static final String COMPLETE = "Complete"; - public static final String FAIL = "Fail"; - public static final String ERROR = "Error"; - public static final String CANCELLED = "Cancelled"; - } - - public static BuildConfig createDefaultBuildConfig(String name, String gitUrl, String jenkinsUrl) { - BuildConfig buildConfig = new BuildConfig(); - getOrCreateMetadata(buildConfig).setName(name); - boolean foundExistingGitUrl = false; - return configureDefaultBuildConfig(buildConfig, name, gitUrl, foundExistingGitUrl, jenkinsUrl); - } - - public static BuildConfig configureDefaultBuildConfig(BuildConfig buildConfig, String name, String gitUrl, boolean foundExistingGitUrl, String jenkinsUrl) { - return configureDefaultBuildConfig(buildConfig, name, gitUrl, foundExistingGitUrl, DEFAULT_BUILD_IMAGE_STREAM, DEFAULT_IMAGE_TAG, DEFAULT_CUSTOM_BUILDER_IMAGE, DEFAULT_SECRET, jenkinsUrl); - } - - public static BuildConfig configureDefaultBuildConfig(BuildConfig buildConfig, String name, String gitUrl, boolean foundExistingGitUrl, String buildImageStream, String buildImageTag, String s2iCustomBuilderImage, String secret, String jenkinsUrl) { - BuildConfigSpec spec = buildConfig.getSpec(); - if (spec == null) { - spec = new BuildConfigSpec(); - buildConfig.setSpec(spec); - } - - if (!foundExistingGitUrl && Strings.isNotBlank(gitUrl)) { - BuildSource source = spec.getSource(); - if (source == null) { - source = new BuildSource(); - spec.setSource(source); - } - source.setType("Git"); - GitBuildSource git = source.getGit(); - if (git == null) { - git = new GitBuildSource(); - source.setGit(git); - } - git.setUri(gitUrl); - } - - if (Strings.isNotBlank(buildImageStream) && Strings.isNotBlank(buildImageTag)) { - BuildStrategy strategy = spec.getStrategy(); - if (strategy == null) { - strategy = new BuildStrategy(); - spec.setStrategy(strategy); - } - - // TODO only do this if we are using Jenkins? - strategy.setType("Custom"); - CustomBuildStrategy customStrategy = strategy.getCustomStrategy(); - if (customStrategy == null) { - customStrategy = new CustomBuildStrategy(); - strategy.setCustomStrategy(customStrategy); - } - - ListEnvVarBuilder envBuilder = new ListEnvVarBuilder(); - if (Strings.isNotBlank(jenkinsUrl)) { - envBuilder.withEnvVar("BASE_URI", jenkinsUrl); - } - envBuilder.withEnvVar("JOB_NAME", name); - customStrategy.setEnv(envBuilder.build()); - customStrategy.setFrom(new ObjectReferenceBuilder().withKind("DockerImage").withName(s2iCustomBuilderImage).build()); - } - List triggers = spec.getTriggers(); - if (triggers.isEmpty()) { - triggers.add(new BuildTriggerPolicyBuilder().withType("GitHub").withNewGithub().withSecret(secret).endGithub().build()); - triggers.add(new BuildTriggerPolicyBuilder().withType("Generic").withNewGeneric().withSecret(secret).endGeneric().build()); - spec.setTriggers(triggers); - } - return buildConfig; - } - - public static boolean isCompleted(String status) { - return Objects.equal(Status.COMPLETE, status); - } - - public static boolean isCancelled(String status) { - return Objects.equal(Status.CANCELLED, status); - } - - public static boolean isFailed(String status) { - if (status != null) { - return status.startsWith(Status.FAIL) || status.startsWith(Status.ERROR); - } - return false; - } - - public static boolean isFinished(String status) { - return isCompleted(status) || isFailed(status) || isCancelled(status); - } - - /** - * Returns a unique UUID for a build - */ - public static String getUid(Build build) { - String answer = null; - if (build != null) { - answer = build.getMetadata().getUid(); - if (Strings.isNullOrBlank(answer)) { - Map metadata = getMetadata(build); - answer = getString(metadata, "uid"); - if (Strings.isNullOrBlank(answer)) { - answer = getString(metadata, "id"); - } - if (Strings.isNullOrBlank(answer)) { - answer = getString(metadata, "name"); - } - } - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getName(); - } - } - return answer; - } - - protected static String getString(Map metadata, String name) { - Object answer = metadata.get(name); - if (answer != null) { - return answer.toString(); - } - return null; - } - - public static Map getMetadata(Build build) { - if (build != null) { - Map additionalProperties = build.getAdditionalProperties(); - if (additionalProperties != null) { - Object metadata = additionalProperties.get("metadata"); - if (metadata instanceof Map) { - return (Map) metadata; - } - } - } - return Collections.EMPTY_MAP; - - } - - public static Map getMetadata(BuildConfig build) { - if (build != null) { - Map additionalProperties = build.getAdditionalProperties(); - if (additionalProperties != null) { - Object metadata = additionalProperties.get("metadata"); - if (metadata instanceof Map) { - return (Map) metadata; - } - } - } - return Collections.EMPTY_MAP; - - } - - public static String getName(BuildConfig build) { - String answer = null; - if (build != null) { - Map metadata = getMetadata(build); - answer = getString(metadata, "name"); - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getName(); - } - } - return answer; - } - - public static String getName(Build build) { - String answer = null; - if (build != null) { - Map metadata = getMetadata(build); - answer = getString(metadata, "name"); - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getName(); - } - } - return answer; - } - - public static String getNamespace(Build build) { - String answer = null; - if (build != null) { - Map metadata = getMetadata(build); - answer = getString(metadata, "namespace"); - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getNamespace(); - } - } - return answer; - } - - - public static String getCreationTimestamp(Build build) { - String answer = null; - if (build != null) { - Map metadata = getMetadata(build); - answer = getString(metadata, "creationTimestamp"); - if (Strings.isNullOrBlank(answer)) { - answer = build.getMetadata().getCreationTimestamp(); - } - } - return answer; - } - - public static Date getCreationTimestampDate(Build build) { - String text = getCreationTimestamp(build); - if (Strings.isNullOrBlank(text)) { - return null; - } else { - return KubernetesHelper.parseDate(text); - } - } - - - public static String getBuildConfigName(Build build) { - if (build != null) { - Map metadata = getMetadata(build); - Object labels = metadata.get("labels"); - if (labels instanceof Map) { - Map labelMap = (Map) labels; - return getString(labelMap, "buildconfig"); - } - } - return null; - } - - /** - * Returns the link to the build page in the console for the given build UUID - */ - public static String createConsoleBuildLink(String fabricConsoleExternalUrl, String buildName) { - return URLUtils.pathJoin(fabricConsoleExternalUrl, "kubernetes/builds", buildName); - } - -} diff --git a/All/Genesis-NP/Genesis#388/pair.info b/All/Genesis-NP/Genesis#388/pair.info deleted file mode 100755 index de4ac28..0000000 --- a/All/Genesis-NP/Genesis#388/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:388 -SATName:Genesis -modifiedFPath:components/kubernetes-api/src/main/java/io/fabric8/kubernetes/api/builds/Builds.java -comSha:4c0ddd76a087356ad7cfd49bbe4e594f1e88588a -parentComSha:4c0ddd76a087356ad7cfd49bbe4e594f1e88588a^1 -githubUrl:https://github.com/fabric8io/fabric8 -repoName:fabric8io#fabric8 \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#397/comMsg.txt b/All/Genesis-NP/Genesis#397/comMsg.txt deleted file mode 100755 index ea68208..0000000 --- a/All/Genesis-NP/Genesis#397/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE diff --git a/All/Genesis-NP/Genesis#397/diff.diff b/All/Genesis-NP/Genesis#397/diff.diff deleted file mode 100755 index 268062d..0000000 --- a/All/Genesis-NP/Genesis#397/diff.diff +++ /dev/null @@ -1,34 +0,0 @@ -diff --git a/object/src/main/java/com/orientechnologies/orient/object/jpa/OJPAPersistenceProvider.java b/object/src/main/java/com/orientechnologies/orient/object/jpa/OJPAPersistenceProvider.java -index 35b5887..88fd304 100644 ---- a/object/src/main/java/com/orientechnologies/orient/object/jpa/OJPAPersistenceProvider.java -+++ b/object/src/main/java/com/orientechnologies/orient/object/jpa/OJPAPersistenceProvider.java -@@ -22,11 +21,0 @@ package com.orientechnologies.orient.object.jpa; --import static com.orientechnologies.orient.core.entity.OEntityManager.getEntityManagerByDatabaseURL; --import static com.orientechnologies.orient.object.jpa.parsing.PersistenceXmlUtil.PERSISTENCE_XML; -- --import java.net.URL; --import java.util.Collection; --import java.util.Map; --import java.util.logging.Logger; -- -- -- -- -@@ -33,0 +23 @@ import com.orientechnologies.orient.core.entity.OEntityManager; -+import com.orientechnologies.orient.object.jpa.parsing.PersistenceXmlUtil; -@@ -35 +24,0 @@ import com.orientechnologies.orient.core.entity.OEntityManager; --import com.orientechnologies.orient.object.jpa.OJPAProviderUtil; -@@ -39,0 +29,4 @@ import javax.persistence.spi.ProviderUtil; -+import java.net.URL; -+import java.util.Collection; -+import java.util.Map; -+import java.util.logging.Logger; -@@ -41,2 +34,2 @@ import javax.persistence.spi.ProviderUtil; --import com.orientechnologies.orient.core.entity.OEntityManager; --import com.orientechnologies.orient.object.jpa.parsing.PersistenceXmlUtil; -+import static com.orientechnologies.orient.core.entity.OEntityManager.getEntityManagerByDatabaseURL; -+import static com.orientechnologies.orient.object.jpa.parsing.PersistenceXmlUtil.PERSISTENCE_XML; -@@ -50 +42,0 @@ public class OJPAPersistenceProvider implements PersistenceProvider { -- -@@ -54,0 +47 @@ public class OJPAPersistenceProvider implements PersistenceProvider { -+ if (persistenceXml != null) diff --git a/All/Genesis-NP/Genesis#397/new/OJPAPersistenceProvider.java b/All/Genesis-NP/Genesis#397/new/OJPAPersistenceProvider.java deleted file mode 100755 index 88fd304..0000000 --- a/All/Genesis-NP/Genesis#397/new/OJPAPersistenceProvider.java +++ /dev/null @@ -1,87 +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.object.jpa; - -import com.orientechnologies.orient.core.entity.OEntityManager; -import com.orientechnologies.orient.object.jpa.parsing.PersistenceXmlUtil; - -import javax.persistence.EntityManagerFactory; -import javax.persistence.spi.PersistenceProvider; -import javax.persistence.spi.PersistenceUnitInfo; -import javax.persistence.spi.ProviderUtil; -import java.net.URL; -import java.util.Collection; -import java.util.Map; -import java.util.logging.Logger; - -import static com.orientechnologies.orient.core.entity.OEntityManager.getEntityManagerByDatabaseURL; -import static com.orientechnologies.orient.object.jpa.parsing.PersistenceXmlUtil.PERSISTENCE_XML; - -@SuppressWarnings("rawtypes") -public class OJPAPersistenceProvider implements PersistenceProvider { - /** the log used by this class. */ - private static Logger logger = Logger.getLogger(OJPAPersistenceProvider.class.getName()); - private static OJPAProviderUtil providerUtil = new OJPAProviderUtil(); - - private Collection persistenceUnits = null; - - public OJPAPersistenceProvider() { - URL persistenceXml = Thread.currentThread().getContextClassLoader().getResource(PERSISTENCE_XML); - if (persistenceXml != null) - try { - persistenceUnits = PersistenceXmlUtil.parse(persistenceXml); - } catch (Exception e) { - logger.info("Can't parse '" + PERSISTENCE_XML + "' :" + e.getMessage()); - } - } - - @Override - public synchronized EntityManagerFactory createEntityManagerFactory(String emName, Map map) { - if (emName == null) { - throw new IllegalStateException("Name of the persistence unit should not be null"); - } - - PersistenceUnitInfo unitInfo = PersistenceXmlUtil.findPersistenceUnit(emName, persistenceUnits); - return createContainerEntityManagerFactory(unitInfo, map); - } - - @SuppressWarnings("unchecked") - @Override - public synchronized EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) { - - OJPAProperties properties = ((info == null) ? new OJPAProperties() : (OJPAProperties) info.getProperties()); - - // Override parsed properties with user specified - if (map != null && !map.isEmpty()) { - properties.putAll(map); - } - - // register entities from tag - OEntityManager entityManager = getEntityManagerByDatabaseURL(properties.getURL()); - entityManager.registerEntityClasses(info.getManagedClassNames()); - - return new OJPAEntityManagerFactory(properties); - } - - @Override - public ProviderUtil getProviderUtil() { - return providerUtil; - } -} diff --git a/All/Genesis-NP/Genesis#397/old/OJPAPersistenceProvider.java b/All/Genesis-NP/Genesis#397/old/OJPAPersistenceProvider.java deleted file mode 100755 index 35b5887..0000000 --- a/All/Genesis-NP/Genesis#397/old/OJPAPersistenceProvider.java +++ /dev/null @@ -1,94 +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.object.jpa; - -import static com.orientechnologies.orient.core.entity.OEntityManager.getEntityManagerByDatabaseURL; -import static com.orientechnologies.orient.object.jpa.parsing.PersistenceXmlUtil.PERSISTENCE_XML; - -import java.net.URL; -import java.util.Collection; -import java.util.Map; -import java.util.logging.Logger; - - - - -import com.orientechnologies.orient.core.entity.OEntityManager; - -import com.orientechnologies.orient.object.jpa.OJPAProviderUtil; -import javax.persistence.EntityManagerFactory; -import javax.persistence.spi.PersistenceProvider; -import javax.persistence.spi.PersistenceUnitInfo; -import javax.persistence.spi.ProviderUtil; - -import com.orientechnologies.orient.core.entity.OEntityManager; -import com.orientechnologies.orient.object.jpa.parsing.PersistenceXmlUtil; - -@SuppressWarnings("rawtypes") -public class OJPAPersistenceProvider implements PersistenceProvider { - /** the log used by this class. */ - private static Logger logger = Logger.getLogger(OJPAPersistenceProvider.class.getName()); - private static OJPAProviderUtil providerUtil=new OJPAProviderUtil(); - - - private Collection persistenceUnits = null; - - public OJPAPersistenceProvider() { - URL persistenceXml = Thread.currentThread().getContextClassLoader().getResource(PERSISTENCE_XML); - try { - persistenceUnits = PersistenceXmlUtil.parse(persistenceXml); - } catch (Exception e) { - logger.info("Can't parse '" + PERSISTENCE_XML + "' :" + e.getMessage()); - } - } - - @Override - public synchronized EntityManagerFactory createEntityManagerFactory(String emName, Map map) { - if (emName == null) { - throw new IllegalStateException("Name of the persistence unit should not be null"); - } - - PersistenceUnitInfo unitInfo = PersistenceXmlUtil.findPersistenceUnit(emName, persistenceUnits); - return createContainerEntityManagerFactory(unitInfo, map); - } - - @SuppressWarnings("unchecked") - @Override - public synchronized EntityManagerFactory createContainerEntityManagerFactory(PersistenceUnitInfo info, Map map) { - - OJPAProperties properties = ((info == null) ? new OJPAProperties() : (OJPAProperties) info.getProperties()); - - // Override parsed properties with user specified - if (map != null && !map.isEmpty()) { - properties.putAll(map); - } - - // register entities from tag - OEntityManager entityManager = getEntityManagerByDatabaseURL(properties.getURL()); - entityManager.registerEntityClasses(info.getManagedClassNames()); - - return new OJPAEntityManagerFactory(properties); - } - - @Override - public ProviderUtil getProviderUtil() { - return providerUtil; - } -} diff --git a/All/Genesis-NP/Genesis#397/pair.info b/All/Genesis-NP/Genesis#397/pair.info deleted file mode 100755 index 720d647..0000000 --- a/All/Genesis-NP/Genesis#397/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:397 -SATName:Genesis -modifiedFPath:object/src/main/java/com/orientechnologies/orient/object/jpa/OJPAPersistenceProvider.java -comSha:37b8f3900b55dbdb6b52402aaff1616f2602d920 -parentComSha:37b8f3900b55dbdb6b52402aaff1616f2602d920^1 -githubUrl:https://github.com/orientechnologies/orientdb -repoName:orientechnologies#orientdb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#399/comMsg.txt b/All/Genesis-NP/Genesis#399/comMsg.txt deleted file mode 100755 index 3aa3087..0000000 --- a/All/Genesis-NP/Genesis#399/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Minor: check if graph instance is active avoiding NPE diff --git a/All/Genesis-NP/Genesis#399/diff.diff b/All/Genesis-NP/Genesis#399/diff.diff deleted file mode 100755 index 37532f6..0000000 --- a/All/Genesis-NP/Genesis#399/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientBaseGraph.java b/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientBaseGraph.java -index d901702..6551914 100755 ---- a/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientBaseGraph.java -+++ b/graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientBaseGraph.java -@@ -255,2 +255 @@ public abstract class OrientBaseGraph extends OrientConfigurableGraph implements -- this(configuration.getString("blueprints.orientdb.url", null), configuration.getString("blueprints.orientdb.username", null), -- configuration.getString("blueprints.orientdb.password", null)); -+ this(configuration.getString("blueprints.orientdb.url", null), configuration.getString("blueprints.orientdb.username", null), configuration.getString("blueprints.orientdb.password", null)); -@@ -292 +291 @@ public abstract class OrientBaseGraph extends OrientConfigurableGraph implements -- if (iLabels != null && graph.isUseClassForEdgeLabel()) { -+ if (iLabels != null && graph != null && graph.isUseClassForEdgeLabel()) { diff --git a/All/Genesis-NP/Genesis#399/new/OrientBaseGraph.java b/All/Genesis-NP/Genesis#399/new/OrientBaseGraph.java deleted file mode 100755 index 6551914..0000000 --- a/All/Genesis-NP/Genesis#399/new/OrientBaseGraph.java +++ /dev/null @@ -1,1890 +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.tinkerpop.blueprints.impls.orient; - -import com.orientechnologies.common.exception.OException; -import com.orientechnologies.common.io.OFileUtils; -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.util.OCallable; -import com.orientechnologies.orient.core.OOrientListenerAbstract; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandRequest; -import com.orientechnologies.orient.core.command.traverse.OTraverse; -import com.orientechnologies.orient.core.config.OStorageEntryConfiguration; -import com.orientechnologies.orient.core.conflict.ORecordConflictStrategy; -import com.orientechnologies.orient.core.db.ODatabase.ATTRIBUTES; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.OPartitionedDatabasePool; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.index.OCompositeKey; -import com.orientechnologies.orient.core.index.OIndex; -import com.orientechnologies.orient.core.index.OIndexManager; -import com.orientechnologies.orient.core.index.OPropertyIndexDefinition; -import com.orientechnologies.orient.core.intent.OIntent; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.metadata.schema.OImmutableClass; -import com.orientechnologies.orient.core.metadata.schema.OProperty; -import com.orientechnologies.orient.core.metadata.schema.OSchema; -import com.orientechnologies.orient.core.metadata.schema.OType; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.record.impl.ODocumentInternal; -import com.orientechnologies.orient.core.storage.OStorage; -import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage; -import com.tinkerpop.blueprints.Edge; -import com.tinkerpop.blueprints.Element; -import com.tinkerpop.blueprints.GraphQuery; -import com.tinkerpop.blueprints.Index; -import com.tinkerpop.blueprints.Parameter; -import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.blueprints.util.ExceptionFactory; -import com.tinkerpop.blueprints.util.StringFactory; -import com.tinkerpop.blueprints.util.wrappers.partition.PartitionVertex; -import org.apache.commons.configuration.Configuration; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Deque; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * A Blueprints implementation of the graph database OrientDB (http://www.orientechnologies.com) - * - * @author Luca Garulli (http://www.orientechnologies.com) - */ -public abstract class OrientBaseGraph extends OrientConfigurableGraph implements OrientExtendedGraph { - public static final String CONNECTION_OUT = "out"; - public static final String CONNECTION_IN = "in"; - public static final String CLASS_PREFIX = "class:"; - public static final String CLUSTER_PREFIX = "cluster:"; - public static final String ADMIN = "admin"; - private static volatile ThreadLocal activeGraph = new ThreadLocal(); - private static volatile ThreadLocal> initializationStack = new InitializationStackThreadLocal(); - - static { - Orient.instance().registerListener(new OOrientListenerAbstract() { - @Override - public void onStartup() { - if (activeGraph == null) - activeGraph = new ThreadLocal(); - if (initializationStack == null) - initializationStack = new InitializationStackThreadLocal(); - } - - @Override - public void onShutdown() { - activeGraph = null; - initializationStack = null; - } - }); - } - - private final OPartitionedDatabasePool pool; - protected ODatabaseDocumentTx database; - private String url; - private String username; - private String password; - - /** - * Constructs a new object using an existent database instance. - * - * @param iDatabase - * Underlying database object to attach - */ - public OrientBaseGraph(final ODatabaseDocumentTx iDatabase, final String iUserName, final String iUserPassword, - final Settings iConfiguration) { - this.pool = null; - this.username = iUserName; - this.password = iUserPassword; - - database = iDatabase; - checkForGraphSchema(database); - - makeActive(); - putInInitializationStack(); - - readDatabaseConfiguration(); - configure(iConfiguration); - } - - public OrientBaseGraph(final OPartitionedDatabasePool pool) { - this.pool = pool; - - database = pool.acquire(); - makeActive(); - putInInitializationStack(); - - this.username = database.getUser() != null ? database.getUser().getName() : null; - - readDatabaseConfiguration(); - } - - public OrientBaseGraph(final OPartitionedDatabasePool pool, final Settings iConfiguration) { - this.pool = pool; - - database = pool.acquire(); - makeActive(); - putInInitializationStack(); - this.username = database.getUser() != null ? database.getUser().getName() : null; - - readDatabaseConfiguration(); - configure(iConfiguration); - } - - public OrientBaseGraph(final String url) { - this(url, ADMIN, ADMIN); - } - - public OrientBaseGraph(final String url, final String username, final String password) { - this.pool = null; - this.url = OFileUtils.getPath(url); - this.username = username; - this.password = password; - this.openOrCreate(); - readDatabaseConfiguration(); - } - - /** - * Builds a OrientGraph instance passing a configuration. Supported configuration settings are: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
NameDescriptionDefault value
blueprints.orientdb.urlDatabase URL-
blueprints.orientdb.usernameUser nameadmin
blueprints.orientdb.passwordUser passwordadmin
blueprints.orientdb.saveOriginalIdsSaves the original element IDs by using the property origId. This could be useful on import of graph to preserve original - * idsfalse
blueprints.orientdb.keepInMemoryReferencesAvoid to keep records in memory but only RIDsfalse
blueprints.orientdb.useCustomClassesForEdgesUse Edge's label as OrientDB class. If doesn't exist create it under the hoodtrue
blueprints.orientdb.useCustomClassesForVertexUse Vertex's label as OrientDB class. If doesn't exist create it under the hoodtrue
blueprints.orientdb.useVertexFieldsForEdgeLabelsStore the edge relationships in vertex by using the Edge's class. This allow to use multiple fields and make faster - * traversal by edge's label (class)true
blueprints.orientdb.lightweightEdgesUses lightweight edges. This avoid to create a physical document per edge. Documents are created only when they have - * propertiestrue
blueprints.orientdb.autoScaleEdgeTypeSet auto scale of edge type. True means one edge is managed as LINK, 2 or more are managed with a LINKBAGfalse
blueprints.orientdb.edgeContainerEmbedded2TreeThresholdChanges the minimum number of edges for edge containers to transform the underlying structure from embedded to tree. Use -1 - * to disable transformation-1
blueprints.orientdb.edgeContainerTree2EmbeddedThresholdChanges the minimum number of edges for edge containers to transform the underlying structure from tree to embedded. Use -1 - * to disable transformation-1
- * - * @param configuration - * of graph - */ - public OrientBaseGraph(final Configuration configuration) { - this(configuration.getString("blueprints.orientdb.url", null), configuration.getString("blueprints.orientdb.username", null), configuration.getString("blueprints.orientdb.password", null)); - super.init(configuration); - } - - public static OrientBaseGraph getActiveGraph() { - return activeGraph.get(); - } - - /** - * Internal use only. - */ - public static void clearInitStack() { - final ThreadLocal> is = initializationStack; - if (is != null) - is.get().clear(); - - final ThreadLocal ag = activeGraph; - if (ag != null) - ag.remove(); - - } - - /** - * (Internal) - */ - public static void encodeClassNames(final String... iLabels) { - if (iLabels != null) - // ENCODE LABELS - for (int i = 0; i < iLabels.length; ++i) - iLabels[i] = encodeClassName(iLabels[i]); - } - - /** - * (Internal) Returns the case sensitive edge class names. - */ - public static void getEdgeClassNames(final OrientBaseGraph graph, final String... iLabels) { - if (iLabels != null && graph != null && graph.isUseClassForEdgeLabel()) { - for (int i = 0; i < iLabels.length; ++i) { - final OrientEdgeType edgeType = graph.getEdgeType(iLabels[i]); - if (edgeType != null) - // OVERWRITE CLASS NAME BECAUSE ATTRIBUTES ARE CASE SENSITIVE - iLabels[i] = edgeType.getName(); - } - } - } - - /** - * (Internal) - */ - public static String encodeClassName(String iClassName) { - if (iClassName == null) - return null; - - if (Character.isDigit(iClassName.charAt(0))) - iClassName = "-" + iClassName; - - try { - return URLEncoder.encode(iClassName, "UTF-8"); - } catch (UnsupportedEncodingException e) { - OLogManager.instance().error(null, "Error on encoding class name using encoding '%s'", e, "UTF-8"); - return iClassName; - } - } - - /** - * (Internal) - */ - public static String decodeClassName(String iClassName) { - if (iClassName == null) - return null; - - if (iClassName.charAt(0) == '-') - iClassName = iClassName.substring(1); - - try { - return URLDecoder.decode(iClassName, "UTF-8"); - } catch (UnsupportedEncodingException e) { - OLogManager.instance().error(null, "Error on decoding class name using encoding '%s'", e, "UTF-8"); - return iClassName; - } - } - - protected static void checkForGraphSchema(final ODatabaseDocumentTx iDatabase) { - final OSchema schema = iDatabase.getMetadata().getSchema(); - - final OClass vertexBaseClass = schema.getClass(OrientVertexType.CLASS_NAME); - final OClass edgeBaseClass = schema.getClass(OrientEdgeType.CLASS_NAME); - - if (vertexBaseClass == null) - // CREATE THE META MODEL USING THE ORIENT SCHEMA - schema.createClass(OrientVertexType.CLASS_NAME).setOverSize(2); - - if (edgeBaseClass == null) - schema.createClass(OrientEdgeType.CLASS_NAME); - - // @COMPATIBILITY < 1.4.0: - boolean warn = false; - final String MSG_SUFFIX = ". Probably you are using a database created with a previous version of OrientDB. Export in graphml format and reimport it"; - - if (vertexBaseClass != null) { - if (!vertexBaseClass.getName().equals(OrientVertexType.CLASS_NAME)) { - OLogManager.instance().warn(null, "Found Vertex class %s" + MSG_SUFFIX, vertexBaseClass.getName()); - warn = true; - } - - if (vertexBaseClass.existsProperty(CONNECTION_OUT) || vertexBaseClass.existsProperty(CONNECTION_IN)) { - OLogManager.instance().warn(null, "Found property in/out against V"); - warn = true; - } - } - - if (edgeBaseClass != null) { - if (!warn && !edgeBaseClass.getName().equals(OrientEdgeType.CLASS_NAME)) { - OLogManager.instance().warn(null, "Found Edge class %s" + MSG_SUFFIX, edgeBaseClass.getName()); - warn = true; - } - - if (edgeBaseClass.existsProperty(CONNECTION_OUT) || edgeBaseClass.existsProperty(CONNECTION_IN)) { - OLogManager.instance().warn(null, "Found property in/out against E"); - warn = true; - } - } - } - - public void makeActive() { - activeGraph.set(this); - - final ODatabaseDocument tlDb = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(); - if (database != null && tlDb != database) - ODatabaseRecordThreadLocal.INSTANCE.set(database); - } - - /** - * (Blueprints Extension) Configure the Graph instance. - * - * @param iSetting - * Settings object containing all the settings - */ - public OrientBaseGraph configure(final Settings iSetting) { - makeActive(); - - if (iSetting != null) { - if (settings == null) { - settings = iSetting; - } else { - settings.copyFrom(iSetting); - } - } - return this; - } - - /** - * (Blueprints Extension) Drops the database - */ - public void drop() { - makeActive(); - - getRawGraph().drop(); - - pollGraphFromStack(true); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Index createIndex(final String indexName, final Class indexClass, - final Parameter... indexParameters) { - makeActive(); - - return executeOutsideTx(new OCallable, OrientBaseGraph>() { - public Index call(final OrientBaseGraph g) { - - final OIndexManager indexManager = database.getMetadata().getIndexManager(); - - if (indexManager.getIndex(indexName) != null) - throw ExceptionFactory.indexAlreadyExists(indexName); - - final OrientIndex index = new OrientIndex(g, indexName, indexClass, null); - - // SAVE THE CONFIGURATION INTO THE GLOBAL CONFIG - saveIndexConfiguration(); - - return (Index) index; - } - }, "create index '", indexName, "'"); - } - - /** - * Returns an index by name and class - * - * @param indexName - * Index name - * @param indexClass - * Class as one or subclass of Vertex.class and Edge.class - * @return Index instance - */ - @SuppressWarnings("unchecked") - @Override - public Index getIndex(final String indexName, final Class indexClass) { - makeActive(); - - final OIndexManager indexManager = database.getMetadata().getIndexManager(); - final OIndex idx = indexManager.getIndex(indexName); - if (idx == null || !hasIndexClass(idx)) - return null; - - final Index index = new OrientIndex(this, idx); - - if (indexClass.isAssignableFrom(index.getIndexClass())) - return (Index) index; - else - throw ExceptionFactory.indexDoesNotSupportClass(indexName, indexClass); - } - - /** - * Returns all the indices. - * - * @return Iterable of Index instances - */ - public Iterable> getIndices() { - makeActive(); - - return loadManualIndexes(); - } - - /** - * Drops an index by name. - * - * @param indexName - * Index name - */ - public void dropIndex(final String indexName) { - makeActive(); - - executeOutsideTx(new OCallable() { - @Override - public Object call(OrientBaseGraph g) { - try { - final OIndexManager indexManager = getRawGraph().getMetadata().getIndexManager(); - final OIndex index = indexManager.getIndex(indexName); - final String recordMapIndexName = index.getConfiguration().field(OrientIndex.CONFIG_RECORD_MAP_NAME); - - indexManager.dropIndex(indexName); - if (recordMapIndexName != null) - getRawGraph().getMetadata().getIndexManager().dropIndex(recordMapIndexName); - - saveIndexConfiguration(); - return null; - } catch (Exception e) { - g.rollback(); - throw new RuntimeException(e.getMessage(), e); - } - } - }, "drop index '", indexName, "'"); - } - - /** - * Creates a new unconnected vertex with no fields in the Graph. - * - * @param id - * Optional, can contains the Vertex's class name by prefixing with "class:" - * @return The new OrientVertex created - */ - @Override - public OrientVertex addVertex(final Object id) { - makeActive(); - - return addVertex(id, (Object[]) null); - } - - public ORecordConflictStrategy getConflictStrategy() { - makeActive(); - - return database.getStorage().getConflictStrategy(); - } - - public OrientBaseGraph setConflictStrategy(final String iStrategyName) { - makeActive(); - - database.setConflictStrategy(Orient.instance().getRecordConflictStrategy().getStrategy(iStrategyName)); - return this; - } - - public OrientBaseGraph setConflictStrategy(final ORecordConflictStrategy iResolver) { - makeActive(); - - database.setConflictStrategy(iResolver); - return this; - } - - /** - * (Blueprints Extension) Creates a new unconnected vertex in the Graph setting the initial field values. - * - * @param id - * Optional, can contains the Vertex's class name by prefixing with "class:" - * @param prop - * Fields must be a odd pairs of key/value or a single object as Map containing entries as key/value pairs - * @return The new OrientVertex created - */ - public OrientVertex addVertex(Object id, final Object... prop) { - makeActive(); - - String className = null; - String clusterName = null; - Object[] fields = null; - - if (id != null) { - if (id instanceof String) { - // PARSE ARGUMENTS - final String[] args = ((String) id).split(","); - for (String s : args) { - if (s.startsWith(CLASS_PREFIX)) - // GET THE CLASS NAME - className = s.substring(CLASS_PREFIX.length()); - else if (s.startsWith(CLUSTER_PREFIX)) - // GET THE CLASS NAME - clusterName = s.substring(CLUSTER_PREFIX.length()); - else - id = s; - } - } - - if (isSaveOriginalIds()) - // SAVE THE ID TOO - fields = new Object[] { OrientElement.DEF_ORIGINAL_ID_FIELDNAME, id }; - } - - setCurrentGraphInThreadLocal(); - autoStartTransaction(); - - final OrientVertex vertex = new OrientVertex(this, className, fields); - vertex.setPropertiesInternal(prop); - - // SAVE IT - if (clusterName != null) - vertex.save(clusterName); - else - vertex.save(); - return vertex; - } - - /** - * (Blueprints Extension) Creates a new unconnected vertex with no fields of specific class in a cluster in the Graph. - * - * @param iClassName - * Vertex class name - * @param iClusterName - * Vertex cluster name - * @return New vertex created - */ - public OrientVertex addVertex(final String iClassName, final String iClusterName) { - makeActive(); - - setCurrentGraphInThreadLocal(); - autoStartTransaction(); - - final OrientVertex vertex = new OrientVertex(this, iClassName); - - // SAVE IT - if (iClusterName != null) - vertex.save(iClusterName); - else - vertex.save(); - return vertex; - } - - /** - * (Blueprints Extension) Creates a temporary vertex setting the initial field values. The vertex is not saved and the transaction - * is not started. - * - * @param iClassName - * Vertex's class name - * @param prop - * Fields must be a odd pairs of key/value or a single object as Map containing entries as key/value pairs - * @return added vertex - */ - public OrientVertex addTemporaryVertex(final String iClassName, final Object... prop) { - makeActive(); - - setCurrentGraphInThreadLocal(); - autoStartTransaction(); - - final OrientVertex vertex = new OrientVertex(this, iClassName); - vertex.setPropertiesInternal(prop); - return vertex; - } - - /** - * Creates an edge between a source Vertex and a destination Vertex setting label as Edge's label. - * - * @param id - * Optional, can contains the Edge's class name by prefixing with "class:" - * @param outVertex - * Source vertex - * @param inVertex - * Destination vertex - * @param label - * Edge's label - * @return - */ - @Override - public OrientEdge addEdge(final Object id, Vertex outVertex, Vertex inVertex, final String label) { - makeActive(); - - String className = null; - String clusterName = null; - - if (id != null) { - if (id instanceof String) { - // PARSE ARGUMENTS - final String[] args = ((String) id).split(","); - for (String s : args) { - if (s.startsWith(CLASS_PREFIX)) - // GET THE CLASS NAME - className = s.substring(CLASS_PREFIX.length()); - else if (s.startsWith(CLUSTER_PREFIX)) - // GET THE CLASS NAME - clusterName = s.substring(CLUSTER_PREFIX.length()); - } - } - } - - // SAVE THE ID TOO? - final Object[] fields = isSaveOriginalIds() && id != null ? new Object[] { OrientElement.DEF_ORIGINAL_ID_FIELDNAME, id } : null; - - if (outVertex instanceof PartitionVertex) - // WRAPPED: GET THE BASE VERTEX - outVertex = ((PartitionVertex) outVertex).getBaseVertex(); - - if (inVertex instanceof PartitionVertex) - // WRAPPED: GET THE BASE VERTEX - inVertex = ((PartitionVertex) inVertex).getBaseVertex(); - - return ((OrientVertex) outVertex).addEdge(label, (OrientVertex) inVertex, className, clusterName, fields); - - } - - /** - * Returns a vertex by an ID. - * - * @param id - * Can by a String, ODocument or an OIdentifiable object. - */ - public OrientVertex getVertex(final Object id) { - makeActive(); - - if (null == id) - throw ExceptionFactory.vertexIdCanNotBeNull(); - - if (id instanceof OrientVertex) - return (OrientVertex) id; - else if (id instanceof ODocument) - return new OrientVertex(this, (OIdentifiable) id); - - setCurrentGraphInThreadLocal(); - - ORID rid; - if (id instanceof OIdentifiable) - rid = ((OIdentifiable) id).getIdentity(); - else { - try { - rid = new ORecordId(id.toString()); - } catch (IllegalArgumentException iae) { - // orientdb throws IllegalArgumentException: Argument 'xxxx' is - // not a RecordId in form of string. Format must be: - // : - return null; - } - } - - if (!rid.isValid()) - return null; - - ORecord rec = rid.getRecord(); - if (rec == null || !(rec instanceof ODocument)) - return null; - - return new OrientVertex(this, rec); - } - - @Override - public void declareIntent(final OIntent iIntent) { - makeActive(); - - getRawGraph().declareIntent(iIntent); - } - - /** - * Removes a vertex from the Graph. All the edges connected to the Vertex are automatically removed. - * - * @param vertex - * Vertex to remove - */ - public void removeVertex(final Vertex vertex) { - makeActive(); - - vertex.remove(); - } - - /** - * Get all the Vertices in Graph. - * - * @return Vertices as Iterable - */ - public Iterable getVertices() { - makeActive(); - - return getVerticesOfClass(OrientVertexType.CLASS_NAME, true); - } - - /** - * Get all the Vertices in Graph specifying if consider or not sub-classes of V. - * - * @param iPolymorphic - * If true then get all the vertices of any sub-class - * @return Vertices as Iterable - */ - public Iterable getVertices(final boolean iPolymorphic) { - makeActive(); - - return getVerticesOfClass(OrientVertexType.CLASS_NAME, iPolymorphic); - } - - /** - * Get all the Vertices in Graph of a specific vertex class and all sub-classes. - * - * @param iClassName - * Vertex class name to filter - * @return Vertices as Iterable - */ - public Iterable getVerticesOfClass(final String iClassName) { - makeActive(); - - return getVerticesOfClass(iClassName, true); - } - - /** - * Get all the Vertices in Graph of a specific vertex class and all sub-classes only if iPolymorphic is true. - * - * @param iClassName - * Vertex class name to filter - * @param iPolymorphic - * If true consider also Vertex iClassName sub-classes - * @return Vertices as Iterable - */ - public Iterable getVerticesOfClass(final String iClassName, final boolean iPolymorphic) { - makeActive(); - - final OClass cls = getRawGraph().getMetadata().getSchema().getClass(iClassName); - if (cls == null) - throw new IllegalArgumentException("Cannot find class '" + iClassName + "' in database schema"); - - if (!cls.isSubClassOf(OrientVertexType.CLASS_NAME)) - throw new IllegalArgumentException("Class '" + iClassName + "' is not a vertex class"); - - return new OrientElementScanIterable(this, iClassName, iPolymorphic); - } - - /** - * Get all the Vertices in Graph filtering by field name and value. Example: - * Iterable resultset = getVertices("name", "Jay"); - * - * - * @param iKey - * Field name - * @param iValue - * Field value - * @return Vertices as Iterable - */ - public Iterable getVertices(final String iKey, Object iValue) { - makeActive(); - - if (iKey.equals("@class")) - return getVerticesOfClass(iValue.toString()); - - String indexName; - final String key; - int pos = iKey.indexOf('.'); - if (pos > -1) { - indexName = iKey; - - final String className = iKey.substring(0, pos); - key = iKey.substring(iKey.indexOf('.') + 1); - - final OClass clazz = database.getMetadata().getImmutableSchemaSnapshot().getClass(className); - - final Collection> indexes = clazz.getIndexes(); - for (OIndex index : indexes) { - final String oInName = index.getName(); - final int point = oInName.indexOf("."); - final String okey = oInName.substring(point + 1); - if (okey.equals(key)) { - indexName = oInName; - break; - } - } - - } else { - indexName = OrientVertexType.CLASS_NAME + "." + iKey; - key = iKey; - } - - final OIndex idx = database.getMetadata().getIndexManager().getIndex(indexName); - if (idx != null) { - iValue = convertKey(idx, iValue); - - Object indexValue = idx.get(iValue); - if (indexValue != null && !(indexValue instanceof Iterable)) - indexValue = Arrays.asList(indexValue); - - return new OrientElementIterable(this, (Iterable) indexValue); - } - - // NO INDEX: EXECUTE A QUERY - return query().has(key, iValue).vertices(); - } - - /** - * Lookup for a vertex by id using an index.
- * This API relies on Unique index (SBTREE/HASH) but is deprecated.
- * Example: - * Vertex v = getVertexByKey("V.name", "name", "Jay"); - * - * - * @param iKey - * Name of the indexed property - * @param iValue - * Field value - * @return Vertex instance if found, otherwise null - * @see #getVertices(String,Object) - */ - @Deprecated - public Vertex getVertexByKey(final String iKey, Object iValue) { - makeActive(); - - String indexName; - if (iKey.indexOf('.') > -1) - indexName = iKey; - else - indexName = OrientVertexType.CLASS_NAME + "." + iKey; - - final OIndex idx = database.getMetadata().getIndexManager().getIndex(indexName); - if (idx != null) { - iValue = convertKey(idx, iValue); - - Object v = idx.get(iValue); - if (v != null) - return getVertex(v); - return null; - } else - throw new IllegalArgumentException("Index '" + indexName + "' not found"); - } - - /** - * Get all the Vertices in Graph filtering by field name and value. Example: - * Iterable resultset = getVertices("Person",new String[] {"name","surname"},new Object[] { "Sherlock" ,"Holmes"}); - * - * - * @param iKey - * Fields name - * @param iValue - * Fields value - * @return Vertices as Iterable - */ - public Iterable getVertices(final String label, final String[] iKey, Object[] iValue) { - makeActive(); - final OClass clazz = database.getMetadata().getImmutableSchemaSnapshot().getClass(label); - Set> indexes = clazz.getInvolvedIndexes(Arrays.asList(iKey)); - if (indexes.iterator().hasNext()) { - final OIndex idx = indexes.iterator().next(); - if (idx != null) { - List keys = Arrays.asList(convertKeys(idx, iValue)); - Object key; - if (keys.size() == 1) { - key = keys.get(0); - } else { - key = new OCompositeKey(keys); - } - Object indexValue = idx.get(key); - if (indexValue != null && !(indexValue instanceof Iterable)) - indexValue = Arrays.asList(indexValue); - return new OrientElementIterable(this, (Iterable) indexValue); - } - } - // NO INDEX: EXECUTE A QUERY - OrientGraphQuery query = (OrientGraphQuery) query(); - query.labels(label); - for (int i = 0; i < iKey.length; i++) { - query.has(iKey[i], iValue[i]); - } - return query.vertices(); - } - - /** - * Returns all the edges in Graph. - * - * @return Edges as Iterable - */ - public Iterable getEdges() { - makeActive(); - - return getEdgesOfClass(OrientEdgeType.CLASS_NAME, true); - } - - /** - * Get all the Edges in Graph specifying if consider or not sub-classes of E. - * - * @param iPolymorphic - * If true then get all the edge of any sub-class - * @return Edges as Iterable - */ - public Iterable getEdges(final boolean iPolymorphic) { - makeActive(); - - return getEdgesOfClass(OrientEdgeType.CLASS_NAME, iPolymorphic); - } - - /** - * Get all the Edges in Graph of a specific edge class and all sub-classes. - * - * @param iClassName - * Edge class name to filter - * @return Edges as Iterable - */ - public Iterable getEdgesOfClass(final String iClassName) { - makeActive(); - - return getEdgesOfClass(iClassName, true); - } - - /** - * Get all the Edges in Graph of a specific edges class and all sub-classes only if iPolymorphic is true. - * - * @param iClassName - * Edge class name to filter - * @param iPolymorphic - * If true consider also iClassName Edge sub-classes - * @return Edges as Iterable - */ - public Iterable getEdgesOfClass(final String iClassName, final boolean iPolymorphic) { - makeActive(); - - final OClass cls = getRawGraph().getMetadata().getSchema().getClass(iClassName); - if (cls == null) - throw new IllegalArgumentException("Cannot find class '" + iClassName + "' in database schema"); - - if (!cls.isSubClassOf(OrientEdgeType.CLASS_NAME)) - throw new IllegalArgumentException("Class '" + iClassName + "' is not an edge class"); - - return new OrientElementScanIterable(this, iClassName, iPolymorphic); - } - - /** - * Get all the Edges in Graph filtering by field name and value. Example: - * Iterable resultset = getEdges("name", "Jay"); - * - * - * @param iKey - * Field name - * @param iValue - * Field value - * @return Edges as Iterable - */ - public Iterable getEdges(final String iKey, Object iValue) { - makeActive(); - - if (iKey.equals("@class")) - return getEdgesOfClass(iValue.toString()); - - final String indexName; - final String key; - int pos = iKey.indexOf('.'); - if (pos > -1) { - indexName = iKey; - key = iKey.substring(iKey.indexOf('.') + 1); - } else { - indexName = OrientEdgeType.CLASS_NAME + "." + iKey; - key = iKey; - } - - final OIndex idx = database.getMetadata().getIndexManager().getIndex(indexName); - if (idx != null) { - iValue = convertKey(idx, iValue); - - Object indexValue = idx.get(iValue); - if (indexValue != null && !(indexValue instanceof Iterable)) - indexValue = Arrays.asList(indexValue); - - return new OrientElementIterable(this, (Iterable) indexValue); - } - - // NO INDEX: EXECUTE A QUERY - return query().has(key, iValue).edges(); - } - - /** - * Returns a edge by an ID. - * - * @param id - * Can by a String, ODocument or an OIdentifiable object. - */ - public OrientEdge getEdge(final Object id) { - makeActive(); - - if (null == id) - throw ExceptionFactory.edgeIdCanNotBeNull(); - - if (id instanceof OrientEdge) - return (OrientEdge) id; - else if (id instanceof ODocument) - return new OrientEdge(this, (OIdentifiable) id); - - final OIdentifiable rec; - if (id instanceof OIdentifiable) - rec = (OIdentifiable) id; - else { - final String str = id.toString(); - - int pos = str.indexOf("->"); - - if (pos > -1) { - // DUMMY EDGE: CREATE IT IN MEMORY - final String from = str.substring(0, pos); - final String to = str.substring(pos + 2); - return new OrientEdge(this, new ORecordId(from), new ORecordId(to)); - } - - try { - rec = new ORecordId(str); - } catch (IllegalArgumentException iae) { - // orientdb throws IllegalArgumentException: Argument 'xxxx' is - // not a RecordId in form of string. Format must be: - // [#]: - return null; - } - } - - final ODocument doc = rec.getRecord(); - if (doc == null) - return null; - - if (!doc.getSchemaClass().isSubClassOf(OrientEdgeType.CLASS_NAME)) - throw new IllegalArgumentException("Class '" + doc.getClassName() + "' is not an edge class"); - - return new OrientEdge(this, rec); - } - - /** - * Removes an edge from the Graph. - * - * @param edge - * Edge to remove - */ - public void removeEdge(final Edge edge) { - makeActive(); - - edge.remove(); - } - - /** - * Reuses the underlying database avoiding to create and open it every time. - * - * @param iDatabase - * Underlying database object - */ - public OrientBaseGraph reuse(final ODatabaseDocumentTx iDatabase) { - ODatabaseRecordThreadLocal.INSTANCE.set(iDatabase); - this.url = iDatabase.getURL(); - database = iDatabase; - - makeActive(); - - return this; - } - - /** - * Checks if the Graph has been closed. - * - * @return True if it is closed, otherwise false - */ - public boolean isClosed() { - makeActive(); - - return database == null || database.isClosed(); - } - - /** - * Closes the Graph. After closing the Graph cannot be used. - */ - public void shutdown() { - shutdown(true); - } - - /** - * Closes the Graph. After closing the Graph cannot be used. - */ - public void shutdown(boolean closeDb) { - shutdown(closeDb, true); - } - - /** - * Closes the Graph. After closing the Graph cannot be used. - */ - public void shutdown(boolean closeDb, boolean commitTx) { - makeActive(); - - try { - if (!database.isClosed() && commitTx) { - final OStorage storage = database.getStorage().getUnderlying(); - if (storage instanceof OAbstractPaginatedStorage) { - if (((OAbstractPaginatedStorage) storage).getWALInstance() != null) - database.commit(); - } - - } - - } catch (RuntimeException e) { - OLogManager.instance().error(this, "Error during context close for db " + url, e); - throw e; - } catch (Exception e) { - OLogManager.instance().error(this, "Error during context close for db " + url, e); - throw new OException("Error during context close for db " + url, e); - } finally { - try { - if (closeDb) - database.close(); - } catch (Exception e) { - OLogManager.instance().error(this, "Error during context close for db " + url, e); - } - } - - url = null; - username = null; - password = null; - - pollGraphFromStack(closeDb); - - if (!closeDb) - database.activateOnCurrentThread(); - } - - /** - * Returns the Graph URL. - */ - public String toString() { - return StringFactory.graphString(this, getRawGraph().getURL()); - } - - /** - * Returns the underlying Database instance as ODatabaseDocumentTx instance. - */ - public ODatabaseDocumentTx getRawGraph() { - return database; - } - - /** - * Commits the current active transaction. - */ - public void commit() { - makeActive(); - } - - /** - * Rollbacks the current active transaction. All the pending changes are rollbacked. - */ - public void rollback() { - makeActive(); - } - - /** - * Returns the V persistent class as OrientVertexType instance. - */ - public OrientVertexType getVertexBaseType() { - makeActive(); - - return new OrientVertexType(this, getRawGraph().getMetadata().getSchema().getClass(OrientVertexType.CLASS_NAME)); - } - - /** - * Returns the persistent class for type iTypeName as OrientVertexType instance. - * - * @param iTypeName - * Vertex class name - */ - public final OrientVertexType getVertexType(final String iTypeName) { - makeActive(); - - final OClass cls = getRawGraph().getMetadata().getSchema().getClass(iTypeName); - if (cls == null) - return null; - - OrientVertexType.checkType(cls); - return new OrientVertexType(this, cls); - - } - - /** - * Creates a new Vertex persistent class. - * - * @param iClassName - * Vertex class name - * @return OrientVertexType instance representing the persistent class - */ - public OrientVertexType createVertexType(final String iClassName) { - makeActive(); - - return createVertexType(iClassName, (String) null); - } - - /** - * Creates a new Vertex persistent class specifying the super class. - * - * @param iClassName - * Vertex class name - * @param iSuperClassName - * Vertex class name to extend - * @return OrientVertexType instance representing the persistent class - */ - public OrientVertexType createVertexType(final String iClassName, final String iSuperClassName) { - makeActive(); - - return createVertexType(iClassName, iSuperClassName == null ? getVertexBaseType() : getVertexType(iSuperClassName)); - } - - /** - * Creates a new Vertex persistent class specifying the super class. - * - * @param iClassName - * Vertex class name - * @param iSuperClass - * OClass Vertex to extend - * @return OrientVertexType instance representing the persistent class - */ - public OrientVertexType createVertexType(final String iClassName, final OClass iSuperClass) { - makeActive(); - - OrientVertexType.checkType(iSuperClass); - - return executeOutsideTx(new OCallable() { - @Override - public OrientVertexType call(final OrientBaseGraph g) { - return new OrientVertexType(g, getRawGraph().getMetadata().getSchema().createClass(iClassName, iSuperClass)); - } - }, "create vertex type '", iClassName, "' as subclass of '", iSuperClass.getName(), "'"); - } - - /** - * Drop a vertex class. - * - * @param iTypeName - * Vertex class name - */ - public final void dropVertexType(final String iTypeName) { - makeActive(); - - executeOutsideTx(new OCallable() { - @Override - public OClass call(final OrientBaseGraph g) { - getRawGraph().getMetadata().getSchema().dropClass(iTypeName); - return null; - } - }, "drop vertex type '", iTypeName, "'"); - } - - /** - * Returns the E persistent class as OrientEdgeType instance. - */ - public OrientEdgeType getEdgeBaseType() { - makeActive(); - - return new OrientEdgeType(this); - } - - /** - * Returns the persistent class for type iTypeName as OrientEdgeType instance. - * - * @param iTypeName - * Edge class name - */ - public final OrientEdgeType getEdgeType(final String iTypeName) { - makeActive(); - - final OClass cls = getRawGraph().getMetadata().getSchema().getClass(iTypeName); - if (cls == null) - return null; - - OrientEdgeType.checkType(cls); - return new OrientEdgeType(this, cls); - } - - /** - * Creates a new Edge persistent class. - * - * @param iClassName - * Edge class name - * @return OrientEdgeType instance representing the persistent class - */ - public OrientEdgeType createEdgeType(final String iClassName) { - makeActive(); - - return createEdgeType(iClassName, (String) null); - } - - /** - * Creates a new Edge persistent class specifying the super class. - * - * @param iClassName - * Edge class name - * @param iSuperClassName - * Edge class name to extend - * @return OrientEdgeType instance representing the persistent class - */ - public OrientEdgeType createEdgeType(final String iClassName, final String iSuperClassName) { - makeActive(); - - return createEdgeType(iClassName, iSuperClassName == null ? getEdgeBaseType() : getEdgeType(iSuperClassName)); - } - - /** - * Creates a new Edge persistent class specifying the super class. - * - * @param iClassName - * Edge class name - * @param iSuperClass - * OClass Edge to extend - * @return OrientEdgeType instance representing the persistent class - */ - public OrientEdgeType createEdgeType(final String iClassName, final OClass iSuperClass) { - makeActive(); - - OrientEdgeType.checkType(iSuperClass); - return executeOutsideTx(new OCallable() { - @Override - public OrientEdgeType call(final OrientBaseGraph g) { - return new OrientEdgeType(g, getRawGraph().getMetadata().getSchema().createClass(iClassName, iSuperClass)); - } - }, "create edge type '", iClassName, "' as subclass of '", iSuperClass.getName(), "'"); - } - - /** - * Drops an edge class. - * - * @param iTypeName - * Edge class name - */ - public final void dropEdgeType(final String iTypeName) { - makeActive(); - - executeOutsideTx(new OCallable() { - @Override - public OClass call(final OrientBaseGraph g) { - getRawGraph().getMetadata().getSchema().dropClass(iTypeName); - return null; - } - }, "drop edge type '", iTypeName, "'"); - } - - /** - * Detaches a Graph Element to be used offline. All the changes will be committed on further @attach call. - * - * @param iElement - * Graph element to detach - * @return The detached element - * @see #attach(OrientElement) - */ - public OrientElement detach(final OrientElement iElement) { - makeActive(); - - iElement.detach(); - return iElement; - } - - /** - * Attaches a previously detached Graph Element to the current Graph. All the pending changes will be committed. - * - * @param iElement - * Graph element to attach - * @return The attached element - * @see #detach(OrientElement) - */ - public OrientElement attach(final OrientElement iElement) { - makeActive(); - - return iElement.attach(this); - } - - /** - * Returns a graph element, vertex or edge, starting from an ID. - * - * @param id - * Can by a String, ODocument or an OIdentifiable object. - * @return OrientElement subclass such as OrientVertex or OrientEdge - */ - public OrientElement getElement(final Object id) { - makeActive(); - - if (null == id) - throw new IllegalArgumentException("id cannot be null"); - - if (id instanceof OrientElement) - return (OrientElement) id; - - OIdentifiable rec; - if (id instanceof OIdentifiable) - rec = (OIdentifiable) id; - else - try { - rec = new ORecordId(id.toString()); - } catch (IllegalArgumentException iae) { - // orientdb throws IllegalArgumentException: Argument 'xxxx' is - // not a RecordId in form of string. Format must be: - // : - return null; - } - - final ODocument doc = rec.getRecord(); - if (doc != null) { - final OImmutableClass schemaClass = ODocumentInternal.getImmutableSchemaClass(doc); - if (schemaClass != null && schemaClass.isEdgeType()) - return new OrientEdge(this, doc); - else - return new OrientVertex(this, doc); - // else - // throw new IllegalArgumentException("Type error. The class " + schemaClass + " does not extend class neither '" - // + OrientVertexType.CLASS_NAME + "' nor '" + OrientEdgeType.CLASS_NAME + "'"); - } - - return null; - } - - /** - * Drops the index against a field name. - * - * @param key - * Field name - * @param elementClass - * Element class as instances of Vertex and Edge - */ - public void dropKeyIndex(final String key, final Class elementClass) { - makeActive(); - - if (elementClass == null) - throw ExceptionFactory.classForElementCannotBeNull(); - - executeOutsideTx(new OCallable() { - @Override - public OClass call(final OrientBaseGraph g) { - final String className = getClassName(elementClass); - getRawGraph().getMetadata().getIndexManager().dropIndex(className + "." + key); - return null; - } - }, "drop key index '", elementClass.getSimpleName(), ".", key, "'"); - - } - - /** - * Creates an automatic indexing structure for indexing provided key for element class. - * - * @param key - * the key to create the index for - * @param elementClass - * the element class that the index is for - * @param indexParameters - * a collection of parameters for the underlying index implementation: - *
    - *
  • "type" is the index type between the supported types (UNIQUE, NOTUNIQUE, FULLTEXT). The default type is NOT_UNIQUE - *
  • "class" is the class to index when it's a custom type derived by Vertex (V) or Edge (E) - *
  • "keytype" to use a key type different by OType.STRING,
  • - * - *
- * @param - * the element class specification - */ - @SuppressWarnings({ "rawtypes" }) - @Override - public void createKeyIndex(final String key, final Class elementClass, final Parameter... indexParameters) { - makeActive(); - - if (elementClass == null) - throw ExceptionFactory.classForElementCannotBeNull(); - - executeOutsideTx(new OCallable() { - @Override - public OClass call(final OrientBaseGraph g) { - - String indexType = OClass.INDEX_TYPE.NOTUNIQUE.name(); - OType keyType = OType.STRING; - String className = null; - String collate = null; - ODocument metadata = null; - - final String ancestorClassName = getClassName(elementClass); - - // READ PARAMETERS - for (Parameter p : indexParameters) { - if (p.getKey().equals("type")) - indexType = p.getValue().toString().toUpperCase(); - else if (p.getKey().equals("keytype")) - keyType = OType.valueOf(p.getValue().toString().toUpperCase()); - else if (p.getKey().equals("class")) - className = p.getValue().toString(); - else if (p.getKey().equals("collate")) - collate = p.getValue().toString(); - else if (p.getKey().toString().startsWith("metadata.")) { - if (metadata == null) - metadata = new ODocument(); - metadata.field(p.getKey().toString().substring("metadata.".length()), p.getValue()); - } - } - - if (className == null) - className = ancestorClassName; - - final ODatabaseDocumentTx db = getRawGraph(); - final OSchema schema = db.getMetadata().getSchema(); - - final OClass cls = schema.getOrCreateClass(className, schema.getClass(ancestorClassName)); - final OProperty property = cls.getProperty(key); - if (property != null) - keyType = property.getType(); - - OPropertyIndexDefinition indexDefinition = new OPropertyIndexDefinition(className, key, keyType); - if (collate != null) - indexDefinition.setCollate(collate); - db.getMetadata().getIndexManager() - .createIndex(className + "." + key, indexType, indexDefinition, cls.getPolymorphicClusterIds(), null, metadata); - return null; - - } - }, "create key index on '", elementClass.getSimpleName(), ".", key, "'"); - } - - /** - * Returns the indexed properties. - * - * @param elementClass - * the element class that the index is for - * @return Set of String containing the indexed properties - */ - @Override - public Set getIndexedKeys(final Class elementClass) { - makeActive(); - - return getIndexedKeys(elementClass, false); - } - - /** - * Returns the indexed properties. - * - * @param elementClass - * the element class that the index is for - * @param includeClassNames - * If true includes also the class name as prefix of fields - * @return Set of String containing the indexed properties - */ - public Set getIndexedKeys(final Class elementClass, final boolean includeClassNames) { - makeActive(); - - if (elementClass == null) - throw ExceptionFactory.classForElementCannotBeNull(); - - final OSchema schema = getRawGraph().getMetadata().getImmutableSchemaSnapshot(); - final String elementOClassName = getClassName(elementClass); - - Set result = new HashSet(); - final Collection> indexes = getRawGraph().getMetadata().getIndexManager().getIndexes(); - for (OIndex index : indexes) { - String indexName = index.getName(); - int point = indexName.indexOf("."); - if (point > 0) { - String oClassName = indexName.substring(0, point); - OClass oClass = schema.getClass(oClassName); - if (oClass.isSubClassOf(elementOClassName)) { - if (includeClassNames) - result.add(index.getName()); - else - result.add(index.getDefinition().getFields().get(0)); - } - } - } - return result; - } - - /** - * Returns a GraphQuery object to execute queries against the Graph. - * - * @return new GraphQuery instance - */ - @Override - public GraphQuery query() { - makeActive(); - - return new OrientGraphQuery(this); - } - - /** - * Returns a OTraverse object to start traversing the graph. - */ - public OTraverse traverse() { - makeActive(); - - return new OTraverse(); - } - - /** - * Executes commands against the graph. Commands are executed outside transaction. - * - * @param iCommand - * Command request between SQL, GREMLIN and SCRIPT commands - */ - public OCommandRequest command(final OCommandRequest iCommand) { - makeActive(); - - return new OrientGraphCommand(this, getRawGraph().command(iCommand)); - } - - /** - * Counts the vertices in graph. - * - * @return Long as number of total vertices - */ - public long countVertices() { - return countVertices(OrientVertexType.CLASS_NAME); - } - - /** - * Counts the vertices in graph of a particular class. - * - * @return Long as number of total vertices - */ - public long countVertices(final String iClassName) { - makeActive(); - - return getRawGraph().countClass(iClassName); - } - - /** - * Counts the edges in graph. Edge counting works only if useLightweightEdges is false. - * - * @return Long as number of total edges - */ - public long countEdges() { - return countEdges(OrientEdgeType.CLASS_NAME); - } - - /** - * Counts the edges in graph of a particular class. Edge counting works only if useLightweightEdges is false. - * - * @return Long as number of total edges - */ - public long countEdges(final String iClassName) { - makeActive(); - - if (isUseLightweightEdges()) - throw new UnsupportedOperationException("Graph set to use Lightweight Edges, count against edges is not supported"); - - return getRawGraph().countClass(iClassName); - } - - public RET executeOutsideTx(final OCallable iCallable, final String... iOperationStrings) - throws RuntimeException { - makeActive(); - - final boolean committed; - final ODatabaseDocumentTx raw = getRawGraph(); - if (raw.getTransaction().isActive()) { - if (isWarnOnForceClosingTx() && OLogManager.instance().isWarnEnabled() && iOperationStrings.length > 0) { - // COMPOSE THE MESSAGE - final StringBuilder msg = new StringBuilder(256); - for (String s : iOperationStrings) - msg.append(s); - - // ASSURE PENDING TX IF ANY IS COMMITTED - OLogManager - .instance() - .warn( - this, - "Requested command '%s' must be executed outside active transaction: the transaction will be committed and reopen right after it. To avoid this behavior execute it outside a transaction", - msg.toString()); - } - raw.commit(); - committed = true; - } else - committed = false; - - try { - return iCallable.call(this); - } finally { - if (committed) - // RESTART TRANSACTION - ((OrientTransactionalGraph) this).begin(); - } - } - - protected void autoStartTransaction() { - } - - protected void saveIndexConfiguration() { - getRawGraph().getMetadata().getIndexManager().getConfiguration().save(); - } - - protected String getClassName(final Class elementClass) { - if (elementClass.isAssignableFrom(Vertex.class)) - return OrientVertexType.CLASS_NAME; - else if (elementClass.isAssignableFrom(Edge.class)) - return OrientEdgeType.CLASS_NAME; - throw new IllegalArgumentException("Class '" + elementClass + "' is neither a Vertex, nor an Edge"); - } - - protected Object convertKey(final OIndex idx, Object iValue) { - if (iValue != null) { - final OType[] types = idx.getKeyTypes(); - if (types.length == 0) - iValue = iValue.toString(); - else - iValue = OType.convert(iValue, types[0].getDefaultJavaType()); - } - return iValue; - } - - protected Object[] convertKeys(final OIndex idx, Object[] iValue) { - if (iValue != null) { - - final OType[] types = idx.getKeyTypes(); - if (types.length == iValue.length) { - Object[] newValue = new Object[types.length]; - for (int i = 0; i < types.length; i++) { - newValue[i] = OType.convert(iValue[i], types[i].getDefaultJavaType()); - } - iValue = newValue; - } - } - return iValue; - } - - protected void setCurrentGraphInThreadLocal() { - if (getThreadMode() == THREAD_MODE.MANUAL) - return; - - final ODatabaseDocument tlDb = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(); - if (getThreadMode() == THREAD_MODE.ALWAYS_AUTOSET || tlDb == null) { - if (database != null && tlDb != database) - // SET IT - ODatabaseRecordThreadLocal.INSTANCE.set(database); - } - } - - private void putInInitializationStack() { - Deque stack = initializationStack.get(); - stack.push(this); - } - - private void pollGraphFromStack(boolean updateDb) { - final Deque stack = initializationStack.get(); - stack.poll(); - - final OrientBaseGraph prevGraph = stack.peek(); - - if (prevGraph != null) { - activeGraph.set(prevGraph); - prevGraph.makeActive(); - } else { - activeGraph.set(null); - if (updateDb) - ODatabaseRecordThreadLocal.INSTANCE.set(null); - } - - } - - @SuppressWarnings("unchecked") - private void readDatabaseConfiguration() { - final ODatabaseDocumentTx databaseDocumentTx = getRawGraph(); - - final List custom = (List) databaseDocumentTx.get(ATTRIBUTES.CUSTOM); - for (OStorageEntryConfiguration c : custom) { - if (c.name.equals("useLightweightEdges")) - setUseLightweightEdges(Boolean.parseBoolean(c.value)); - else if (c.name.equals("useClassForEdgeLabel")) - setUseClassForEdgeLabel(Boolean.parseBoolean(c.value)); - else if (c.name.equals("useClassForVertexLabel")) - setUseClassForVertexLabel(Boolean.parseBoolean(c.value)); - else if (c.name.equals("useVertexFieldsForEdgeLabels")) - setUseVertexFieldsForEdgeLabels(Boolean.parseBoolean(c.value)); - else if (c.name.equals("standardElementConstraints")) - setStandardElementConstraints(Boolean.parseBoolean(c.value)); - } - - } - - private void openOrCreate() { - if (url == null) - throw new IllegalStateException("Database is closed"); - - if (pool == null) { - database = new ODatabaseDocumentTx(url); - if (url.startsWith("remote:") || database.exists()) { - if (database.isClosed()) - database.open(username, password); - - // LOAD THE INDEX CONFIGURATION FROM INTO THE DICTIONARY - // final ODocument indexConfiguration = - // database.getMetadata().getIndexManager().getConfiguration(); - } else - database.create(); - } else - database = pool.acquire(); - - makeActive(); - putInInitializationStack(); - checkForGraphSchema(database); - } - - private List> loadManualIndexes() { - final List> result = new ArrayList>(); - for (OIndex idx : database.getMetadata().getIndexManager().getIndexes()) { - if (hasIndexClass(idx)) - // LOAD THE INDEXES - result.add(new OrientIndex(this, idx)); - } - - return result; - } - - private boolean hasIndexClass(OIndex idx) { - final ODocument metadata = idx.getMetadata(); - - return (metadata != null && metadata.field(OrientIndex.CONFIG_CLASSNAME) != null) - // compatibility with versions earlier 1.6.3 - || idx.getConfiguration().field(OrientIndex.CONFIG_CLASSNAME) != null; - } - - private static class InitializationStackThreadLocal extends ThreadLocal> { - @Override - protected Deque initialValue() { - return new LinkedList(); - } - } -} diff --git a/All/Genesis-NP/Genesis#399/old/OrientBaseGraph.java b/All/Genesis-NP/Genesis#399/old/OrientBaseGraph.java deleted file mode 100755 index d901702..0000000 --- a/All/Genesis-NP/Genesis#399/old/OrientBaseGraph.java +++ /dev/null @@ -1,1891 +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.tinkerpop.blueprints.impls.orient; - -import com.orientechnologies.common.exception.OException; -import com.orientechnologies.common.io.OFileUtils; -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.util.OCallable; -import com.orientechnologies.orient.core.OOrientListenerAbstract; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandRequest; -import com.orientechnologies.orient.core.command.traverse.OTraverse; -import com.orientechnologies.orient.core.config.OStorageEntryConfiguration; -import com.orientechnologies.orient.core.conflict.ORecordConflictStrategy; -import com.orientechnologies.orient.core.db.ODatabase.ATTRIBUTES; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.OPartitionedDatabasePool; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.index.OCompositeKey; -import com.orientechnologies.orient.core.index.OIndex; -import com.orientechnologies.orient.core.index.OIndexManager; -import com.orientechnologies.orient.core.index.OPropertyIndexDefinition; -import com.orientechnologies.orient.core.intent.OIntent; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.metadata.schema.OImmutableClass; -import com.orientechnologies.orient.core.metadata.schema.OProperty; -import com.orientechnologies.orient.core.metadata.schema.OSchema; -import com.orientechnologies.orient.core.metadata.schema.OType; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.record.impl.ODocumentInternal; -import com.orientechnologies.orient.core.storage.OStorage; -import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage; -import com.tinkerpop.blueprints.Edge; -import com.tinkerpop.blueprints.Element; -import com.tinkerpop.blueprints.GraphQuery; -import com.tinkerpop.blueprints.Index; -import com.tinkerpop.blueprints.Parameter; -import com.tinkerpop.blueprints.Vertex; -import com.tinkerpop.blueprints.util.ExceptionFactory; -import com.tinkerpop.blueprints.util.StringFactory; -import com.tinkerpop.blueprints.util.wrappers.partition.PartitionVertex; -import org.apache.commons.configuration.Configuration; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Deque; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -/** - * A Blueprints implementation of the graph database OrientDB (http://www.orientechnologies.com) - * - * @author Luca Garulli (http://www.orientechnologies.com) - */ -public abstract class OrientBaseGraph extends OrientConfigurableGraph implements OrientExtendedGraph { - public static final String CONNECTION_OUT = "out"; - public static final String CONNECTION_IN = "in"; - public static final String CLASS_PREFIX = "class:"; - public static final String CLUSTER_PREFIX = "cluster:"; - public static final String ADMIN = "admin"; - private static volatile ThreadLocal activeGraph = new ThreadLocal(); - private static volatile ThreadLocal> initializationStack = new InitializationStackThreadLocal(); - - static { - Orient.instance().registerListener(new OOrientListenerAbstract() { - @Override - public void onStartup() { - if (activeGraph == null) - activeGraph = new ThreadLocal(); - if (initializationStack == null) - initializationStack = new InitializationStackThreadLocal(); - } - - @Override - public void onShutdown() { - activeGraph = null; - initializationStack = null; - } - }); - } - - private final OPartitionedDatabasePool pool; - protected ODatabaseDocumentTx database; - private String url; - private String username; - private String password; - - /** - * Constructs a new object using an existent database instance. - * - * @param iDatabase - * Underlying database object to attach - */ - public OrientBaseGraph(final ODatabaseDocumentTx iDatabase, final String iUserName, final String iUserPassword, - final Settings iConfiguration) { - this.pool = null; - this.username = iUserName; - this.password = iUserPassword; - - database = iDatabase; - checkForGraphSchema(database); - - makeActive(); - putInInitializationStack(); - - readDatabaseConfiguration(); - configure(iConfiguration); - } - - public OrientBaseGraph(final OPartitionedDatabasePool pool) { - this.pool = pool; - - database = pool.acquire(); - makeActive(); - putInInitializationStack(); - - this.username = database.getUser() != null ? database.getUser().getName() : null; - - readDatabaseConfiguration(); - } - - public OrientBaseGraph(final OPartitionedDatabasePool pool, final Settings iConfiguration) { - this.pool = pool; - - database = pool.acquire(); - makeActive(); - putInInitializationStack(); - this.username = database.getUser() != null ? database.getUser().getName() : null; - - readDatabaseConfiguration(); - configure(iConfiguration); - } - - public OrientBaseGraph(final String url) { - this(url, ADMIN, ADMIN); - } - - public OrientBaseGraph(final String url, final String username, final String password) { - this.pool = null; - this.url = OFileUtils.getPath(url); - this.username = username; - this.password = password; - this.openOrCreate(); - readDatabaseConfiguration(); - } - - /** - * Builds a OrientGraph instance passing a configuration. Supported configuration settings are: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
NameDescriptionDefault value
blueprints.orientdb.urlDatabase URL-
blueprints.orientdb.usernameUser nameadmin
blueprints.orientdb.passwordUser passwordadmin
blueprints.orientdb.saveOriginalIdsSaves the original element IDs by using the property origId. This could be useful on import of graph to preserve original - * idsfalse
blueprints.orientdb.keepInMemoryReferencesAvoid to keep records in memory but only RIDsfalse
blueprints.orientdb.useCustomClassesForEdgesUse Edge's label as OrientDB class. If doesn't exist create it under the hoodtrue
blueprints.orientdb.useCustomClassesForVertexUse Vertex's label as OrientDB class. If doesn't exist create it under the hoodtrue
blueprints.orientdb.useVertexFieldsForEdgeLabelsStore the edge relationships in vertex by using the Edge's class. This allow to use multiple fields and make faster - * traversal by edge's label (class)true
blueprints.orientdb.lightweightEdgesUses lightweight edges. This avoid to create a physical document per edge. Documents are created only when they have - * propertiestrue
blueprints.orientdb.autoScaleEdgeTypeSet auto scale of edge type. True means one edge is managed as LINK, 2 or more are managed with a LINKBAGfalse
blueprints.orientdb.edgeContainerEmbedded2TreeThresholdChanges the minimum number of edges for edge containers to transform the underlying structure from embedded to tree. Use -1 - * to disable transformation-1
blueprints.orientdb.edgeContainerTree2EmbeddedThresholdChanges the minimum number of edges for edge containers to transform the underlying structure from tree to embedded. Use -1 - * to disable transformation-1
- * - * @param configuration - * of graph - */ - public OrientBaseGraph(final Configuration configuration) { - this(configuration.getString("blueprints.orientdb.url", null), configuration.getString("blueprints.orientdb.username", null), - configuration.getString("blueprints.orientdb.password", null)); - super.init(configuration); - } - - public static OrientBaseGraph getActiveGraph() { - return activeGraph.get(); - } - - /** - * Internal use only. - */ - public static void clearInitStack() { - final ThreadLocal> is = initializationStack; - if (is != null) - is.get().clear(); - - final ThreadLocal ag = activeGraph; - if (ag != null) - ag.remove(); - - } - - /** - * (Internal) - */ - public static void encodeClassNames(final String... iLabels) { - if (iLabels != null) - // ENCODE LABELS - for (int i = 0; i < iLabels.length; ++i) - iLabels[i] = encodeClassName(iLabels[i]); - } - - /** - * (Internal) Returns the case sensitive edge class names. - */ - public static void getEdgeClassNames(final OrientBaseGraph graph, final String... iLabels) { - if (iLabels != null && graph.isUseClassForEdgeLabel()) { - for (int i = 0; i < iLabels.length; ++i) { - final OrientEdgeType edgeType = graph.getEdgeType(iLabels[i]); - if (edgeType != null) - // OVERWRITE CLASS NAME BECAUSE ATTRIBUTES ARE CASE SENSITIVE - iLabels[i] = edgeType.getName(); - } - } - } - - /** - * (Internal) - */ - public static String encodeClassName(String iClassName) { - if (iClassName == null) - return null; - - if (Character.isDigit(iClassName.charAt(0))) - iClassName = "-" + iClassName; - - try { - return URLEncoder.encode(iClassName, "UTF-8"); - } catch (UnsupportedEncodingException e) { - OLogManager.instance().error(null, "Error on encoding class name using encoding '%s'", e, "UTF-8"); - return iClassName; - } - } - - /** - * (Internal) - */ - public static String decodeClassName(String iClassName) { - if (iClassName == null) - return null; - - if (iClassName.charAt(0) == '-') - iClassName = iClassName.substring(1); - - try { - return URLDecoder.decode(iClassName, "UTF-8"); - } catch (UnsupportedEncodingException e) { - OLogManager.instance().error(null, "Error on decoding class name using encoding '%s'", e, "UTF-8"); - return iClassName; - } - } - - protected static void checkForGraphSchema(final ODatabaseDocumentTx iDatabase) { - final OSchema schema = iDatabase.getMetadata().getSchema(); - - final OClass vertexBaseClass = schema.getClass(OrientVertexType.CLASS_NAME); - final OClass edgeBaseClass = schema.getClass(OrientEdgeType.CLASS_NAME); - - if (vertexBaseClass == null) - // CREATE THE META MODEL USING THE ORIENT SCHEMA - schema.createClass(OrientVertexType.CLASS_NAME).setOverSize(2); - - if (edgeBaseClass == null) - schema.createClass(OrientEdgeType.CLASS_NAME); - - // @COMPATIBILITY < 1.4.0: - boolean warn = false; - final String MSG_SUFFIX = ". Probably you are using a database created with a previous version of OrientDB. Export in graphml format and reimport it"; - - if (vertexBaseClass != null) { - if (!vertexBaseClass.getName().equals(OrientVertexType.CLASS_NAME)) { - OLogManager.instance().warn(null, "Found Vertex class %s" + MSG_SUFFIX, vertexBaseClass.getName()); - warn = true; - } - - if (vertexBaseClass.existsProperty(CONNECTION_OUT) || vertexBaseClass.existsProperty(CONNECTION_IN)) { - OLogManager.instance().warn(null, "Found property in/out against V"); - warn = true; - } - } - - if (edgeBaseClass != null) { - if (!warn && !edgeBaseClass.getName().equals(OrientEdgeType.CLASS_NAME)) { - OLogManager.instance().warn(null, "Found Edge class %s" + MSG_SUFFIX, edgeBaseClass.getName()); - warn = true; - } - - if (edgeBaseClass.existsProperty(CONNECTION_OUT) || edgeBaseClass.existsProperty(CONNECTION_IN)) { - OLogManager.instance().warn(null, "Found property in/out against E"); - warn = true; - } - } - } - - public void makeActive() { - activeGraph.set(this); - - final ODatabaseDocument tlDb = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(); - if (database != null && tlDb != database) - ODatabaseRecordThreadLocal.INSTANCE.set(database); - } - - /** - * (Blueprints Extension) Configure the Graph instance. - * - * @param iSetting - * Settings object containing all the settings - */ - public OrientBaseGraph configure(final Settings iSetting) { - makeActive(); - - if (iSetting != null) { - if (settings == null) { - settings = iSetting; - } else { - settings.copyFrom(iSetting); - } - } - return this; - } - - /** - * (Blueprints Extension) Drops the database - */ - public void drop() { - makeActive(); - - getRawGraph().drop(); - - pollGraphFromStack(true); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public Index createIndex(final String indexName, final Class indexClass, - final Parameter... indexParameters) { - makeActive(); - - return executeOutsideTx(new OCallable, OrientBaseGraph>() { - public Index call(final OrientBaseGraph g) { - - final OIndexManager indexManager = database.getMetadata().getIndexManager(); - - if (indexManager.getIndex(indexName) != null) - throw ExceptionFactory.indexAlreadyExists(indexName); - - final OrientIndex index = new OrientIndex(g, indexName, indexClass, null); - - // SAVE THE CONFIGURATION INTO THE GLOBAL CONFIG - saveIndexConfiguration(); - - return (Index) index; - } - }, "create index '", indexName, "'"); - } - - /** - * Returns an index by name and class - * - * @param indexName - * Index name - * @param indexClass - * Class as one or subclass of Vertex.class and Edge.class - * @return Index instance - */ - @SuppressWarnings("unchecked") - @Override - public Index getIndex(final String indexName, final Class indexClass) { - makeActive(); - - final OIndexManager indexManager = database.getMetadata().getIndexManager(); - final OIndex idx = indexManager.getIndex(indexName); - if (idx == null || !hasIndexClass(idx)) - return null; - - final Index index = new OrientIndex(this, idx); - - if (indexClass.isAssignableFrom(index.getIndexClass())) - return (Index) index; - else - throw ExceptionFactory.indexDoesNotSupportClass(indexName, indexClass); - } - - /** - * Returns all the indices. - * - * @return Iterable of Index instances - */ - public Iterable> getIndices() { - makeActive(); - - return loadManualIndexes(); - } - - /** - * Drops an index by name. - * - * @param indexName - * Index name - */ - public void dropIndex(final String indexName) { - makeActive(); - - executeOutsideTx(new OCallable() { - @Override - public Object call(OrientBaseGraph g) { - try { - final OIndexManager indexManager = getRawGraph().getMetadata().getIndexManager(); - final OIndex index = indexManager.getIndex(indexName); - final String recordMapIndexName = index.getConfiguration().field(OrientIndex.CONFIG_RECORD_MAP_NAME); - - indexManager.dropIndex(indexName); - if (recordMapIndexName != null) - getRawGraph().getMetadata().getIndexManager().dropIndex(recordMapIndexName); - - saveIndexConfiguration(); - return null; - } catch (Exception e) { - g.rollback(); - throw new RuntimeException(e.getMessage(), e); - } - } - }, "drop index '", indexName, "'"); - } - - /** - * Creates a new unconnected vertex with no fields in the Graph. - * - * @param id - * Optional, can contains the Vertex's class name by prefixing with "class:" - * @return The new OrientVertex created - */ - @Override - public OrientVertex addVertex(final Object id) { - makeActive(); - - return addVertex(id, (Object[]) null); - } - - public ORecordConflictStrategy getConflictStrategy() { - makeActive(); - - return database.getStorage().getConflictStrategy(); - } - - public OrientBaseGraph setConflictStrategy(final String iStrategyName) { - makeActive(); - - database.setConflictStrategy(Orient.instance().getRecordConflictStrategy().getStrategy(iStrategyName)); - return this; - } - - public OrientBaseGraph setConflictStrategy(final ORecordConflictStrategy iResolver) { - makeActive(); - - database.setConflictStrategy(iResolver); - return this; - } - - /** - * (Blueprints Extension) Creates a new unconnected vertex in the Graph setting the initial field values. - * - * @param id - * Optional, can contains the Vertex's class name by prefixing with "class:" - * @param prop - * Fields must be a odd pairs of key/value or a single object as Map containing entries as key/value pairs - * @return The new OrientVertex created - */ - public OrientVertex addVertex(Object id, final Object... prop) { - makeActive(); - - String className = null; - String clusterName = null; - Object[] fields = null; - - if (id != null) { - if (id instanceof String) { - // PARSE ARGUMENTS - final String[] args = ((String) id).split(","); - for (String s : args) { - if (s.startsWith(CLASS_PREFIX)) - // GET THE CLASS NAME - className = s.substring(CLASS_PREFIX.length()); - else if (s.startsWith(CLUSTER_PREFIX)) - // GET THE CLASS NAME - clusterName = s.substring(CLUSTER_PREFIX.length()); - else - id = s; - } - } - - if (isSaveOriginalIds()) - // SAVE THE ID TOO - fields = new Object[] { OrientElement.DEF_ORIGINAL_ID_FIELDNAME, id }; - } - - setCurrentGraphInThreadLocal(); - autoStartTransaction(); - - final OrientVertex vertex = new OrientVertex(this, className, fields); - vertex.setPropertiesInternal(prop); - - // SAVE IT - if (clusterName != null) - vertex.save(clusterName); - else - vertex.save(); - return vertex; - } - - /** - * (Blueprints Extension) Creates a new unconnected vertex with no fields of specific class in a cluster in the Graph. - * - * @param iClassName - * Vertex class name - * @param iClusterName - * Vertex cluster name - * @return New vertex created - */ - public OrientVertex addVertex(final String iClassName, final String iClusterName) { - makeActive(); - - setCurrentGraphInThreadLocal(); - autoStartTransaction(); - - final OrientVertex vertex = new OrientVertex(this, iClassName); - - // SAVE IT - if (iClusterName != null) - vertex.save(iClusterName); - else - vertex.save(); - return vertex; - } - - /** - * (Blueprints Extension) Creates a temporary vertex setting the initial field values. The vertex is not saved and the transaction - * is not started. - * - * @param iClassName - * Vertex's class name - * @param prop - * Fields must be a odd pairs of key/value or a single object as Map containing entries as key/value pairs - * @return added vertex - */ - public OrientVertex addTemporaryVertex(final String iClassName, final Object... prop) { - makeActive(); - - setCurrentGraphInThreadLocal(); - autoStartTransaction(); - - final OrientVertex vertex = new OrientVertex(this, iClassName); - vertex.setPropertiesInternal(prop); - return vertex; - } - - /** - * Creates an edge between a source Vertex and a destination Vertex setting label as Edge's label. - * - * @param id - * Optional, can contains the Edge's class name by prefixing with "class:" - * @param outVertex - * Source vertex - * @param inVertex - * Destination vertex - * @param label - * Edge's label - * @return - */ - @Override - public OrientEdge addEdge(final Object id, Vertex outVertex, Vertex inVertex, final String label) { - makeActive(); - - String className = null; - String clusterName = null; - - if (id != null) { - if (id instanceof String) { - // PARSE ARGUMENTS - final String[] args = ((String) id).split(","); - for (String s : args) { - if (s.startsWith(CLASS_PREFIX)) - // GET THE CLASS NAME - className = s.substring(CLASS_PREFIX.length()); - else if (s.startsWith(CLUSTER_PREFIX)) - // GET THE CLASS NAME - clusterName = s.substring(CLUSTER_PREFIX.length()); - } - } - } - - // SAVE THE ID TOO? - final Object[] fields = isSaveOriginalIds() && id != null ? new Object[] { OrientElement.DEF_ORIGINAL_ID_FIELDNAME, id } : null; - - if (outVertex instanceof PartitionVertex) - // WRAPPED: GET THE BASE VERTEX - outVertex = ((PartitionVertex) outVertex).getBaseVertex(); - - if (inVertex instanceof PartitionVertex) - // WRAPPED: GET THE BASE VERTEX - inVertex = ((PartitionVertex) inVertex).getBaseVertex(); - - return ((OrientVertex) outVertex).addEdge(label, (OrientVertex) inVertex, className, clusterName, fields); - - } - - /** - * Returns a vertex by an ID. - * - * @param id - * Can by a String, ODocument or an OIdentifiable object. - */ - public OrientVertex getVertex(final Object id) { - makeActive(); - - if (null == id) - throw ExceptionFactory.vertexIdCanNotBeNull(); - - if (id instanceof OrientVertex) - return (OrientVertex) id; - else if (id instanceof ODocument) - return new OrientVertex(this, (OIdentifiable) id); - - setCurrentGraphInThreadLocal(); - - ORID rid; - if (id instanceof OIdentifiable) - rid = ((OIdentifiable) id).getIdentity(); - else { - try { - rid = new ORecordId(id.toString()); - } catch (IllegalArgumentException iae) { - // orientdb throws IllegalArgumentException: Argument 'xxxx' is - // not a RecordId in form of string. Format must be: - // : - return null; - } - } - - if (!rid.isValid()) - return null; - - ORecord rec = rid.getRecord(); - if (rec == null || !(rec instanceof ODocument)) - return null; - - return new OrientVertex(this, rec); - } - - @Override - public void declareIntent(final OIntent iIntent) { - makeActive(); - - getRawGraph().declareIntent(iIntent); - } - - /** - * Removes a vertex from the Graph. All the edges connected to the Vertex are automatically removed. - * - * @param vertex - * Vertex to remove - */ - public void removeVertex(final Vertex vertex) { - makeActive(); - - vertex.remove(); - } - - /** - * Get all the Vertices in Graph. - * - * @return Vertices as Iterable - */ - public Iterable getVertices() { - makeActive(); - - return getVerticesOfClass(OrientVertexType.CLASS_NAME, true); - } - - /** - * Get all the Vertices in Graph specifying if consider or not sub-classes of V. - * - * @param iPolymorphic - * If true then get all the vertices of any sub-class - * @return Vertices as Iterable - */ - public Iterable getVertices(final boolean iPolymorphic) { - makeActive(); - - return getVerticesOfClass(OrientVertexType.CLASS_NAME, iPolymorphic); - } - - /** - * Get all the Vertices in Graph of a specific vertex class and all sub-classes. - * - * @param iClassName - * Vertex class name to filter - * @return Vertices as Iterable - */ - public Iterable getVerticesOfClass(final String iClassName) { - makeActive(); - - return getVerticesOfClass(iClassName, true); - } - - /** - * Get all the Vertices in Graph of a specific vertex class and all sub-classes only if iPolymorphic is true. - * - * @param iClassName - * Vertex class name to filter - * @param iPolymorphic - * If true consider also Vertex iClassName sub-classes - * @return Vertices as Iterable - */ - public Iterable getVerticesOfClass(final String iClassName, final boolean iPolymorphic) { - makeActive(); - - final OClass cls = getRawGraph().getMetadata().getSchema().getClass(iClassName); - if (cls == null) - throw new IllegalArgumentException("Cannot find class '" + iClassName + "' in database schema"); - - if (!cls.isSubClassOf(OrientVertexType.CLASS_NAME)) - throw new IllegalArgumentException("Class '" + iClassName + "' is not a vertex class"); - - return new OrientElementScanIterable(this, iClassName, iPolymorphic); - } - - /** - * Get all the Vertices in Graph filtering by field name and value. Example: - * Iterable resultset = getVertices("name", "Jay"); - * - * - * @param iKey - * Field name - * @param iValue - * Field value - * @return Vertices as Iterable - */ - public Iterable getVertices(final String iKey, Object iValue) { - makeActive(); - - if (iKey.equals("@class")) - return getVerticesOfClass(iValue.toString()); - - String indexName; - final String key; - int pos = iKey.indexOf('.'); - if (pos > -1) { - indexName = iKey; - - final String className = iKey.substring(0, pos); - key = iKey.substring(iKey.indexOf('.') + 1); - - final OClass clazz = database.getMetadata().getImmutableSchemaSnapshot().getClass(className); - - final Collection> indexes = clazz.getIndexes(); - for (OIndex index : indexes) { - final String oInName = index.getName(); - final int point = oInName.indexOf("."); - final String okey = oInName.substring(point + 1); - if (okey.equals(key)) { - indexName = oInName; - break; - } - } - - } else { - indexName = OrientVertexType.CLASS_NAME + "." + iKey; - key = iKey; - } - - final OIndex idx = database.getMetadata().getIndexManager().getIndex(indexName); - if (idx != null) { - iValue = convertKey(idx, iValue); - - Object indexValue = idx.get(iValue); - if (indexValue != null && !(indexValue instanceof Iterable)) - indexValue = Arrays.asList(indexValue); - - return new OrientElementIterable(this, (Iterable) indexValue); - } - - // NO INDEX: EXECUTE A QUERY - return query().has(key, iValue).vertices(); - } - - /** - * Lookup for a vertex by id using an index.
- * This API relies on Unique index (SBTREE/HASH) but is deprecated.
- * Example: - * Vertex v = getVertexByKey("V.name", "name", "Jay"); - * - * - * @param iKey - * Name of the indexed property - * @param iValue - * Field value - * @return Vertex instance if found, otherwise null - * @see #getVertices(String,Object) - */ - @Deprecated - public Vertex getVertexByKey(final String iKey, Object iValue) { - makeActive(); - - String indexName; - if (iKey.indexOf('.') > -1) - indexName = iKey; - else - indexName = OrientVertexType.CLASS_NAME + "." + iKey; - - final OIndex idx = database.getMetadata().getIndexManager().getIndex(indexName); - if (idx != null) { - iValue = convertKey(idx, iValue); - - Object v = idx.get(iValue); - if (v != null) - return getVertex(v); - return null; - } else - throw new IllegalArgumentException("Index '" + indexName + "' not found"); - } - - /** - * Get all the Vertices in Graph filtering by field name and value. Example: - * Iterable resultset = getVertices("Person",new String[] {"name","surname"},new Object[] { "Sherlock" ,"Holmes"}); - * - * - * @param iKey - * Fields name - * @param iValue - * Fields value - * @return Vertices as Iterable - */ - public Iterable getVertices(final String label, final String[] iKey, Object[] iValue) { - makeActive(); - final OClass clazz = database.getMetadata().getImmutableSchemaSnapshot().getClass(label); - Set> indexes = clazz.getInvolvedIndexes(Arrays.asList(iKey)); - if (indexes.iterator().hasNext()) { - final OIndex idx = indexes.iterator().next(); - if (idx != null) { - List keys = Arrays.asList(convertKeys(idx, iValue)); - Object key; - if (keys.size() == 1) { - key = keys.get(0); - } else { - key = new OCompositeKey(keys); - } - Object indexValue = idx.get(key); - if (indexValue != null && !(indexValue instanceof Iterable)) - indexValue = Arrays.asList(indexValue); - return new OrientElementIterable(this, (Iterable) indexValue); - } - } - // NO INDEX: EXECUTE A QUERY - OrientGraphQuery query = (OrientGraphQuery) query(); - query.labels(label); - for (int i = 0; i < iKey.length; i++) { - query.has(iKey[i], iValue[i]); - } - return query.vertices(); - } - - /** - * Returns all the edges in Graph. - * - * @return Edges as Iterable - */ - public Iterable getEdges() { - makeActive(); - - return getEdgesOfClass(OrientEdgeType.CLASS_NAME, true); - } - - /** - * Get all the Edges in Graph specifying if consider or not sub-classes of E. - * - * @param iPolymorphic - * If true then get all the edge of any sub-class - * @return Edges as Iterable - */ - public Iterable getEdges(final boolean iPolymorphic) { - makeActive(); - - return getEdgesOfClass(OrientEdgeType.CLASS_NAME, iPolymorphic); - } - - /** - * Get all the Edges in Graph of a specific edge class and all sub-classes. - * - * @param iClassName - * Edge class name to filter - * @return Edges as Iterable - */ - public Iterable getEdgesOfClass(final String iClassName) { - makeActive(); - - return getEdgesOfClass(iClassName, true); - } - - /** - * Get all the Edges in Graph of a specific edges class and all sub-classes only if iPolymorphic is true. - * - * @param iClassName - * Edge class name to filter - * @param iPolymorphic - * If true consider also iClassName Edge sub-classes - * @return Edges as Iterable - */ - public Iterable getEdgesOfClass(final String iClassName, final boolean iPolymorphic) { - makeActive(); - - final OClass cls = getRawGraph().getMetadata().getSchema().getClass(iClassName); - if (cls == null) - throw new IllegalArgumentException("Cannot find class '" + iClassName + "' in database schema"); - - if (!cls.isSubClassOf(OrientEdgeType.CLASS_NAME)) - throw new IllegalArgumentException("Class '" + iClassName + "' is not an edge class"); - - return new OrientElementScanIterable(this, iClassName, iPolymorphic); - } - - /** - * Get all the Edges in Graph filtering by field name and value. Example: - * Iterable resultset = getEdges("name", "Jay"); - * - * - * @param iKey - * Field name - * @param iValue - * Field value - * @return Edges as Iterable - */ - public Iterable getEdges(final String iKey, Object iValue) { - makeActive(); - - if (iKey.equals("@class")) - return getEdgesOfClass(iValue.toString()); - - final String indexName; - final String key; - int pos = iKey.indexOf('.'); - if (pos > -1) { - indexName = iKey; - key = iKey.substring(iKey.indexOf('.') + 1); - } else { - indexName = OrientEdgeType.CLASS_NAME + "." + iKey; - key = iKey; - } - - final OIndex idx = database.getMetadata().getIndexManager().getIndex(indexName); - if (idx != null) { - iValue = convertKey(idx, iValue); - - Object indexValue = idx.get(iValue); - if (indexValue != null && !(indexValue instanceof Iterable)) - indexValue = Arrays.asList(indexValue); - - return new OrientElementIterable(this, (Iterable) indexValue); - } - - // NO INDEX: EXECUTE A QUERY - return query().has(key, iValue).edges(); - } - - /** - * Returns a edge by an ID. - * - * @param id - * Can by a String, ODocument or an OIdentifiable object. - */ - public OrientEdge getEdge(final Object id) { - makeActive(); - - if (null == id) - throw ExceptionFactory.edgeIdCanNotBeNull(); - - if (id instanceof OrientEdge) - return (OrientEdge) id; - else if (id instanceof ODocument) - return new OrientEdge(this, (OIdentifiable) id); - - final OIdentifiable rec; - if (id instanceof OIdentifiable) - rec = (OIdentifiable) id; - else { - final String str = id.toString(); - - int pos = str.indexOf("->"); - - if (pos > -1) { - // DUMMY EDGE: CREATE IT IN MEMORY - final String from = str.substring(0, pos); - final String to = str.substring(pos + 2); - return new OrientEdge(this, new ORecordId(from), new ORecordId(to)); - } - - try { - rec = new ORecordId(str); - } catch (IllegalArgumentException iae) { - // orientdb throws IllegalArgumentException: Argument 'xxxx' is - // not a RecordId in form of string. Format must be: - // [#]: - return null; - } - } - - final ODocument doc = rec.getRecord(); - if (doc == null) - return null; - - if (!doc.getSchemaClass().isSubClassOf(OrientEdgeType.CLASS_NAME)) - throw new IllegalArgumentException("Class '" + doc.getClassName() + "' is not an edge class"); - - return new OrientEdge(this, rec); - } - - /** - * Removes an edge from the Graph. - * - * @param edge - * Edge to remove - */ - public void removeEdge(final Edge edge) { - makeActive(); - - edge.remove(); - } - - /** - * Reuses the underlying database avoiding to create and open it every time. - * - * @param iDatabase - * Underlying database object - */ - public OrientBaseGraph reuse(final ODatabaseDocumentTx iDatabase) { - ODatabaseRecordThreadLocal.INSTANCE.set(iDatabase); - this.url = iDatabase.getURL(); - database = iDatabase; - - makeActive(); - - return this; - } - - /** - * Checks if the Graph has been closed. - * - * @return True if it is closed, otherwise false - */ - public boolean isClosed() { - makeActive(); - - return database == null || database.isClosed(); - } - - /** - * Closes the Graph. After closing the Graph cannot be used. - */ - public void shutdown() { - shutdown(true); - } - - /** - * Closes the Graph. After closing the Graph cannot be used. - */ - public void shutdown(boolean closeDb) { - shutdown(closeDb, true); - } - - /** - * Closes the Graph. After closing the Graph cannot be used. - */ - public void shutdown(boolean closeDb, boolean commitTx) { - makeActive(); - - try { - if (!database.isClosed() && commitTx) { - final OStorage storage = database.getStorage().getUnderlying(); - if (storage instanceof OAbstractPaginatedStorage) { - if (((OAbstractPaginatedStorage) storage).getWALInstance() != null) - database.commit(); - } - - } - - } catch (RuntimeException e) { - OLogManager.instance().error(this, "Error during context close for db " + url, e); - throw e; - } catch (Exception e) { - OLogManager.instance().error(this, "Error during context close for db " + url, e); - throw new OException("Error during context close for db " + url, e); - } finally { - try { - if (closeDb) - database.close(); - } catch (Exception e) { - OLogManager.instance().error(this, "Error during context close for db " + url, e); - } - } - - url = null; - username = null; - password = null; - - pollGraphFromStack(closeDb); - - if (!closeDb) - database.activateOnCurrentThread(); - } - - /** - * Returns the Graph URL. - */ - public String toString() { - return StringFactory.graphString(this, getRawGraph().getURL()); - } - - /** - * Returns the underlying Database instance as ODatabaseDocumentTx instance. - */ - public ODatabaseDocumentTx getRawGraph() { - return database; - } - - /** - * Commits the current active transaction. - */ - public void commit() { - makeActive(); - } - - /** - * Rollbacks the current active transaction. All the pending changes are rollbacked. - */ - public void rollback() { - makeActive(); - } - - /** - * Returns the V persistent class as OrientVertexType instance. - */ - public OrientVertexType getVertexBaseType() { - makeActive(); - - return new OrientVertexType(this, getRawGraph().getMetadata().getSchema().getClass(OrientVertexType.CLASS_NAME)); - } - - /** - * Returns the persistent class for type iTypeName as OrientVertexType instance. - * - * @param iTypeName - * Vertex class name - */ - public final OrientVertexType getVertexType(final String iTypeName) { - makeActive(); - - final OClass cls = getRawGraph().getMetadata().getSchema().getClass(iTypeName); - if (cls == null) - return null; - - OrientVertexType.checkType(cls); - return new OrientVertexType(this, cls); - - } - - /** - * Creates a new Vertex persistent class. - * - * @param iClassName - * Vertex class name - * @return OrientVertexType instance representing the persistent class - */ - public OrientVertexType createVertexType(final String iClassName) { - makeActive(); - - return createVertexType(iClassName, (String) null); - } - - /** - * Creates a new Vertex persistent class specifying the super class. - * - * @param iClassName - * Vertex class name - * @param iSuperClassName - * Vertex class name to extend - * @return OrientVertexType instance representing the persistent class - */ - public OrientVertexType createVertexType(final String iClassName, final String iSuperClassName) { - makeActive(); - - return createVertexType(iClassName, iSuperClassName == null ? getVertexBaseType() : getVertexType(iSuperClassName)); - } - - /** - * Creates a new Vertex persistent class specifying the super class. - * - * @param iClassName - * Vertex class name - * @param iSuperClass - * OClass Vertex to extend - * @return OrientVertexType instance representing the persistent class - */ - public OrientVertexType createVertexType(final String iClassName, final OClass iSuperClass) { - makeActive(); - - OrientVertexType.checkType(iSuperClass); - - return executeOutsideTx(new OCallable() { - @Override - public OrientVertexType call(final OrientBaseGraph g) { - return new OrientVertexType(g, getRawGraph().getMetadata().getSchema().createClass(iClassName, iSuperClass)); - } - }, "create vertex type '", iClassName, "' as subclass of '", iSuperClass.getName(), "'"); - } - - /** - * Drop a vertex class. - * - * @param iTypeName - * Vertex class name - */ - public final void dropVertexType(final String iTypeName) { - makeActive(); - - executeOutsideTx(new OCallable() { - @Override - public OClass call(final OrientBaseGraph g) { - getRawGraph().getMetadata().getSchema().dropClass(iTypeName); - return null; - } - }, "drop vertex type '", iTypeName, "'"); - } - - /** - * Returns the E persistent class as OrientEdgeType instance. - */ - public OrientEdgeType getEdgeBaseType() { - makeActive(); - - return new OrientEdgeType(this); - } - - /** - * Returns the persistent class for type iTypeName as OrientEdgeType instance. - * - * @param iTypeName - * Edge class name - */ - public final OrientEdgeType getEdgeType(final String iTypeName) { - makeActive(); - - final OClass cls = getRawGraph().getMetadata().getSchema().getClass(iTypeName); - if (cls == null) - return null; - - OrientEdgeType.checkType(cls); - return new OrientEdgeType(this, cls); - } - - /** - * Creates a new Edge persistent class. - * - * @param iClassName - * Edge class name - * @return OrientEdgeType instance representing the persistent class - */ - public OrientEdgeType createEdgeType(final String iClassName) { - makeActive(); - - return createEdgeType(iClassName, (String) null); - } - - /** - * Creates a new Edge persistent class specifying the super class. - * - * @param iClassName - * Edge class name - * @param iSuperClassName - * Edge class name to extend - * @return OrientEdgeType instance representing the persistent class - */ - public OrientEdgeType createEdgeType(final String iClassName, final String iSuperClassName) { - makeActive(); - - return createEdgeType(iClassName, iSuperClassName == null ? getEdgeBaseType() : getEdgeType(iSuperClassName)); - } - - /** - * Creates a new Edge persistent class specifying the super class. - * - * @param iClassName - * Edge class name - * @param iSuperClass - * OClass Edge to extend - * @return OrientEdgeType instance representing the persistent class - */ - public OrientEdgeType createEdgeType(final String iClassName, final OClass iSuperClass) { - makeActive(); - - OrientEdgeType.checkType(iSuperClass); - return executeOutsideTx(new OCallable() { - @Override - public OrientEdgeType call(final OrientBaseGraph g) { - return new OrientEdgeType(g, getRawGraph().getMetadata().getSchema().createClass(iClassName, iSuperClass)); - } - }, "create edge type '", iClassName, "' as subclass of '", iSuperClass.getName(), "'"); - } - - /** - * Drops an edge class. - * - * @param iTypeName - * Edge class name - */ - public final void dropEdgeType(final String iTypeName) { - makeActive(); - - executeOutsideTx(new OCallable() { - @Override - public OClass call(final OrientBaseGraph g) { - getRawGraph().getMetadata().getSchema().dropClass(iTypeName); - return null; - } - }, "drop edge type '", iTypeName, "'"); - } - - /** - * Detaches a Graph Element to be used offline. All the changes will be committed on further @attach call. - * - * @param iElement - * Graph element to detach - * @return The detached element - * @see #attach(OrientElement) - */ - public OrientElement detach(final OrientElement iElement) { - makeActive(); - - iElement.detach(); - return iElement; - } - - /** - * Attaches a previously detached Graph Element to the current Graph. All the pending changes will be committed. - * - * @param iElement - * Graph element to attach - * @return The attached element - * @see #detach(OrientElement) - */ - public OrientElement attach(final OrientElement iElement) { - makeActive(); - - return iElement.attach(this); - } - - /** - * Returns a graph element, vertex or edge, starting from an ID. - * - * @param id - * Can by a String, ODocument or an OIdentifiable object. - * @return OrientElement subclass such as OrientVertex or OrientEdge - */ - public OrientElement getElement(final Object id) { - makeActive(); - - if (null == id) - throw new IllegalArgumentException("id cannot be null"); - - if (id instanceof OrientElement) - return (OrientElement) id; - - OIdentifiable rec; - if (id instanceof OIdentifiable) - rec = (OIdentifiable) id; - else - try { - rec = new ORecordId(id.toString()); - } catch (IllegalArgumentException iae) { - // orientdb throws IllegalArgumentException: Argument 'xxxx' is - // not a RecordId in form of string. Format must be: - // : - return null; - } - - final ODocument doc = rec.getRecord(); - if (doc != null) { - final OImmutableClass schemaClass = ODocumentInternal.getImmutableSchemaClass(doc); - if (schemaClass != null && schemaClass.isEdgeType()) - return new OrientEdge(this, doc); - else - return new OrientVertex(this, doc); - // else - // throw new IllegalArgumentException("Type error. The class " + schemaClass + " does not extend class neither '" - // + OrientVertexType.CLASS_NAME + "' nor '" + OrientEdgeType.CLASS_NAME + "'"); - } - - return null; - } - - /** - * Drops the index against a field name. - * - * @param key - * Field name - * @param elementClass - * Element class as instances of Vertex and Edge - */ - public void dropKeyIndex(final String key, final Class elementClass) { - makeActive(); - - if (elementClass == null) - throw ExceptionFactory.classForElementCannotBeNull(); - - executeOutsideTx(new OCallable() { - @Override - public OClass call(final OrientBaseGraph g) { - final String className = getClassName(elementClass); - getRawGraph().getMetadata().getIndexManager().dropIndex(className + "." + key); - return null; - } - }, "drop key index '", elementClass.getSimpleName(), ".", key, "'"); - - } - - /** - * Creates an automatic indexing structure for indexing provided key for element class. - * - * @param key - * the key to create the index for - * @param elementClass - * the element class that the index is for - * @param indexParameters - * a collection of parameters for the underlying index implementation: - *
    - *
  • "type" is the index type between the supported types (UNIQUE, NOTUNIQUE, FULLTEXT). The default type is NOT_UNIQUE - *
  • "class" is the class to index when it's a custom type derived by Vertex (V) or Edge (E) - *
  • "keytype" to use a key type different by OType.STRING,
  • - * - *
- * @param - * the element class specification - */ - @SuppressWarnings({ "rawtypes" }) - @Override - public void createKeyIndex(final String key, final Class elementClass, final Parameter... indexParameters) { - makeActive(); - - if (elementClass == null) - throw ExceptionFactory.classForElementCannotBeNull(); - - executeOutsideTx(new OCallable() { - @Override - public OClass call(final OrientBaseGraph g) { - - String indexType = OClass.INDEX_TYPE.NOTUNIQUE.name(); - OType keyType = OType.STRING; - String className = null; - String collate = null; - ODocument metadata = null; - - final String ancestorClassName = getClassName(elementClass); - - // READ PARAMETERS - for (Parameter p : indexParameters) { - if (p.getKey().equals("type")) - indexType = p.getValue().toString().toUpperCase(); - else if (p.getKey().equals("keytype")) - keyType = OType.valueOf(p.getValue().toString().toUpperCase()); - else if (p.getKey().equals("class")) - className = p.getValue().toString(); - else if (p.getKey().equals("collate")) - collate = p.getValue().toString(); - else if (p.getKey().toString().startsWith("metadata.")) { - if (metadata == null) - metadata = new ODocument(); - metadata.field(p.getKey().toString().substring("metadata.".length()), p.getValue()); - } - } - - if (className == null) - className = ancestorClassName; - - final ODatabaseDocumentTx db = getRawGraph(); - final OSchema schema = db.getMetadata().getSchema(); - - final OClass cls = schema.getOrCreateClass(className, schema.getClass(ancestorClassName)); - final OProperty property = cls.getProperty(key); - if (property != null) - keyType = property.getType(); - - OPropertyIndexDefinition indexDefinition = new OPropertyIndexDefinition(className, key, keyType); - if (collate != null) - indexDefinition.setCollate(collate); - db.getMetadata().getIndexManager() - .createIndex(className + "." + key, indexType, indexDefinition, cls.getPolymorphicClusterIds(), null, metadata); - return null; - - } - }, "create key index on '", elementClass.getSimpleName(), ".", key, "'"); - } - - /** - * Returns the indexed properties. - * - * @param elementClass - * the element class that the index is for - * @return Set of String containing the indexed properties - */ - @Override - public Set getIndexedKeys(final Class elementClass) { - makeActive(); - - return getIndexedKeys(elementClass, false); - } - - /** - * Returns the indexed properties. - * - * @param elementClass - * the element class that the index is for - * @param includeClassNames - * If true includes also the class name as prefix of fields - * @return Set of String containing the indexed properties - */ - public Set getIndexedKeys(final Class elementClass, final boolean includeClassNames) { - makeActive(); - - if (elementClass == null) - throw ExceptionFactory.classForElementCannotBeNull(); - - final OSchema schema = getRawGraph().getMetadata().getImmutableSchemaSnapshot(); - final String elementOClassName = getClassName(elementClass); - - Set result = new HashSet(); - final Collection> indexes = getRawGraph().getMetadata().getIndexManager().getIndexes(); - for (OIndex index : indexes) { - String indexName = index.getName(); - int point = indexName.indexOf("."); - if (point > 0) { - String oClassName = indexName.substring(0, point); - OClass oClass = schema.getClass(oClassName); - if (oClass.isSubClassOf(elementOClassName)) { - if (includeClassNames) - result.add(index.getName()); - else - result.add(index.getDefinition().getFields().get(0)); - } - } - } - return result; - } - - /** - * Returns a GraphQuery object to execute queries against the Graph. - * - * @return new GraphQuery instance - */ - @Override - public GraphQuery query() { - makeActive(); - - return new OrientGraphQuery(this); - } - - /** - * Returns a OTraverse object to start traversing the graph. - */ - public OTraverse traverse() { - makeActive(); - - return new OTraverse(); - } - - /** - * Executes commands against the graph. Commands are executed outside transaction. - * - * @param iCommand - * Command request between SQL, GREMLIN and SCRIPT commands - */ - public OCommandRequest command(final OCommandRequest iCommand) { - makeActive(); - - return new OrientGraphCommand(this, getRawGraph().command(iCommand)); - } - - /** - * Counts the vertices in graph. - * - * @return Long as number of total vertices - */ - public long countVertices() { - return countVertices(OrientVertexType.CLASS_NAME); - } - - /** - * Counts the vertices in graph of a particular class. - * - * @return Long as number of total vertices - */ - public long countVertices(final String iClassName) { - makeActive(); - - return getRawGraph().countClass(iClassName); - } - - /** - * Counts the edges in graph. Edge counting works only if useLightweightEdges is false. - * - * @return Long as number of total edges - */ - public long countEdges() { - return countEdges(OrientEdgeType.CLASS_NAME); - } - - /** - * Counts the edges in graph of a particular class. Edge counting works only if useLightweightEdges is false. - * - * @return Long as number of total edges - */ - public long countEdges(final String iClassName) { - makeActive(); - - if (isUseLightweightEdges()) - throw new UnsupportedOperationException("Graph set to use Lightweight Edges, count against edges is not supported"); - - return getRawGraph().countClass(iClassName); - } - - public RET executeOutsideTx(final OCallable iCallable, final String... iOperationStrings) - throws RuntimeException { - makeActive(); - - final boolean committed; - final ODatabaseDocumentTx raw = getRawGraph(); - if (raw.getTransaction().isActive()) { - if (isWarnOnForceClosingTx() && OLogManager.instance().isWarnEnabled() && iOperationStrings.length > 0) { - // COMPOSE THE MESSAGE - final StringBuilder msg = new StringBuilder(256); - for (String s : iOperationStrings) - msg.append(s); - - // ASSURE PENDING TX IF ANY IS COMMITTED - OLogManager - .instance() - .warn( - this, - "Requested command '%s' must be executed outside active transaction: the transaction will be committed and reopen right after it. To avoid this behavior execute it outside a transaction", - msg.toString()); - } - raw.commit(); - committed = true; - } else - committed = false; - - try { - return iCallable.call(this); - } finally { - if (committed) - // RESTART TRANSACTION - ((OrientTransactionalGraph) this).begin(); - } - } - - protected void autoStartTransaction() { - } - - protected void saveIndexConfiguration() { - getRawGraph().getMetadata().getIndexManager().getConfiguration().save(); - } - - protected String getClassName(final Class elementClass) { - if (elementClass.isAssignableFrom(Vertex.class)) - return OrientVertexType.CLASS_NAME; - else if (elementClass.isAssignableFrom(Edge.class)) - return OrientEdgeType.CLASS_NAME; - throw new IllegalArgumentException("Class '" + elementClass + "' is neither a Vertex, nor an Edge"); - } - - protected Object convertKey(final OIndex idx, Object iValue) { - if (iValue != null) { - final OType[] types = idx.getKeyTypes(); - if (types.length == 0) - iValue = iValue.toString(); - else - iValue = OType.convert(iValue, types[0].getDefaultJavaType()); - } - return iValue; - } - - protected Object[] convertKeys(final OIndex idx, Object[] iValue) { - if (iValue != null) { - - final OType[] types = idx.getKeyTypes(); - if (types.length == iValue.length) { - Object[] newValue = new Object[types.length]; - for (int i = 0; i < types.length; i++) { - newValue[i] = OType.convert(iValue[i], types[i].getDefaultJavaType()); - } - iValue = newValue; - } - } - return iValue; - } - - protected void setCurrentGraphInThreadLocal() { - if (getThreadMode() == THREAD_MODE.MANUAL) - return; - - final ODatabaseDocument tlDb = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined(); - if (getThreadMode() == THREAD_MODE.ALWAYS_AUTOSET || tlDb == null) { - if (database != null && tlDb != database) - // SET IT - ODatabaseRecordThreadLocal.INSTANCE.set(database); - } - } - - private void putInInitializationStack() { - Deque stack = initializationStack.get(); - stack.push(this); - } - - private void pollGraphFromStack(boolean updateDb) { - final Deque stack = initializationStack.get(); - stack.poll(); - - final OrientBaseGraph prevGraph = stack.peek(); - - if (prevGraph != null) { - activeGraph.set(prevGraph); - prevGraph.makeActive(); - } else { - activeGraph.set(null); - if (updateDb) - ODatabaseRecordThreadLocal.INSTANCE.set(null); - } - - } - - @SuppressWarnings("unchecked") - private void readDatabaseConfiguration() { - final ODatabaseDocumentTx databaseDocumentTx = getRawGraph(); - - final List custom = (List) databaseDocumentTx.get(ATTRIBUTES.CUSTOM); - for (OStorageEntryConfiguration c : custom) { - if (c.name.equals("useLightweightEdges")) - setUseLightweightEdges(Boolean.parseBoolean(c.value)); - else if (c.name.equals("useClassForEdgeLabel")) - setUseClassForEdgeLabel(Boolean.parseBoolean(c.value)); - else if (c.name.equals("useClassForVertexLabel")) - setUseClassForVertexLabel(Boolean.parseBoolean(c.value)); - else if (c.name.equals("useVertexFieldsForEdgeLabels")) - setUseVertexFieldsForEdgeLabels(Boolean.parseBoolean(c.value)); - else if (c.name.equals("standardElementConstraints")) - setStandardElementConstraints(Boolean.parseBoolean(c.value)); - } - - } - - private void openOrCreate() { - if (url == null) - throw new IllegalStateException("Database is closed"); - - if (pool == null) { - database = new ODatabaseDocumentTx(url); - if (url.startsWith("remote:") || database.exists()) { - if (database.isClosed()) - database.open(username, password); - - // LOAD THE INDEX CONFIGURATION FROM INTO THE DICTIONARY - // final ODocument indexConfiguration = - // database.getMetadata().getIndexManager().getConfiguration(); - } else - database.create(); - } else - database = pool.acquire(); - - makeActive(); - putInInitializationStack(); - checkForGraphSchema(database); - } - - private List> loadManualIndexes() { - final List> result = new ArrayList>(); - for (OIndex idx : database.getMetadata().getIndexManager().getIndexes()) { - if (hasIndexClass(idx)) - // LOAD THE INDEXES - result.add(new OrientIndex(this, idx)); - } - - return result; - } - - private boolean hasIndexClass(OIndex idx) { - final ODocument metadata = idx.getMetadata(); - - return (metadata != null && metadata.field(OrientIndex.CONFIG_CLASSNAME) != null) - // compatibility with versions earlier 1.6.3 - || idx.getConfiguration().field(OrientIndex.CONFIG_CLASSNAME) != null; - } - - private static class InitializationStackThreadLocal extends ThreadLocal> { - @Override - protected Deque initialValue() { - return new LinkedList(); - } - } -} diff --git a/All/Genesis-NP/Genesis#399/pair.info b/All/Genesis-NP/Genesis#399/pair.info deleted file mode 100755 index bcf4aea..0000000 --- a/All/Genesis-NP/Genesis#399/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:399 -SATName:Genesis -modifiedFPath:graphdb/src/main/java/com/tinkerpop/blueprints/impls/orient/OrientBaseGraph.java -comSha:347023f272c3645a4fc01333d5e2112e125b7f0c -parentComSha:347023f272c3645a4fc01333d5e2112e125b7f0c^1 -githubUrl:https://github.com/orientechnologies/orientdb -repoName:orientechnologies#orientdb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#402/comMsg.txt b/All/Genesis-NP/Genesis#402/comMsg.txt deleted file mode 100755 index ec68872..0000000 --- a/All/Genesis-NP/Genesis#402/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixes npe on OStorageRemote client on shutdown diff --git a/All/Genesis-NP/Genesis#402/diff.diff b/All/Genesis-NP/Genesis#402/diff.diff deleted file mode 100755 index 3f33922..0000000 --- a/All/Genesis-NP/Genesis#402/diff.diff +++ /dev/null @@ -1,34 +0,0 @@ -diff --git a/core/src/main/java/com/orientechnologies/orient/core/Orient.java b/core/src/main/java/com/orientechnologies/orient/core/Orient.java -index b00aa9b..e216ac6 100755 ---- a/core/src/main/java/com/orientechnologies/orient/core/Orient.java -+++ b/core/src/main/java/com/orientechnologies/orient/core/Orient.java -@@ -295,11 +294,0 @@ public class Orient extends OListenerManger { -- // CALL THE SHUTDOWN ON ALL THE LISTENERS -- for (OOrientListener l : browseListeners()) { -- if (l != null) -- try { -- l.onShutdown(); -- } catch (Exception e) { -- OLogManager.instance().error(this, "Error during orient shutdown.", e); -- } -- -- } -- -@@ -311 +300 @@ public class Orient extends OListenerManger { -- if (l != null) -+ if (l != null) { -@@ -313,0 +303,5 @@ public class Orient extends OListenerManger { -+ } -+ -+ } catch (Exception e) { -+ OLogManager.instance().error(this, "Error during orient shutdown.", e); -+ } -@@ -314,0 +309,5 @@ public class Orient extends OListenerManger { -+ // CALL THE SHUTDOWN ON ALL THE LISTENERS -+ for (OOrientListener l : browseListeners()) { -+ if (l != null) -+ try { -+ l.onShutdown(); -@@ -318,0 +318,2 @@ public class Orient extends OListenerManger { -+ } -+ diff --git a/All/Genesis-NP/Genesis#402/new/Orient.java b/All/Genesis-NP/Genesis#402/new/Orient.java deleted file mode 100755 index e216ac6..0000000 --- a/All/Genesis-NP/Genesis#402/new/Orient.java +++ /dev/null @@ -1,763 +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; - -import java.io.IOException; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import com.orientechnologies.common.io.OFileUtils; -import com.orientechnologies.common.io.OIOUtils; -import com.orientechnologies.common.listener.OListenerManger; -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.parser.OSystemVariableResolver; -import com.orientechnologies.common.profiler.OProfiler; -import com.orientechnologies.common.profiler.OProfilerMBean; -import com.orientechnologies.orient.core.command.script.OScriptManager; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.conflict.ORecordConflictStrategyFactory; -import com.orientechnologies.orient.core.db.ODatabaseFactory; -import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener; -import com.orientechnologies.orient.core.db.ODatabaseThreadLocalFactory; -import com.orientechnologies.orient.core.engine.OEngine; -import com.orientechnologies.orient.core.engine.local.OEngineLocalPaginated; -import com.orientechnologies.orient.core.engine.memory.OEngineMemory; -import com.orientechnologies.orient.core.exception.OConfigurationException; -import com.orientechnologies.orient.core.record.ORecordFactoryManager; -import com.orientechnologies.orient.core.storage.OStorage; - -public class Orient extends OListenerManger { - public static final String ORIENTDB_HOME = "ORIENTDB_HOME"; - public static final String URL_SYNTAX = "::[?=[&]]*"; - - private static final Orient instance = new Orient(); - private static volatile boolean registerDatabaseByPath = false; - - private final ConcurrentMap engines = new ConcurrentHashMap(); - private final ConcurrentMap storages = new ConcurrentHashMap(); - - private final Map dbLifecycleListeners = new LinkedHashMap(); - private final ODatabaseFactory databaseFactory = new ODatabaseFactory(); - private final OScriptManager scriptManager = new OScriptManager(); - private final ThreadGroup threadGroup; - private final AtomicInteger serialId = new AtomicInteger(); - private final ReadWriteLock engineLock = new ReentrantReadWriteLock(); - private final ORecordConflictStrategyFactory recordConflictStrategy = new ORecordConflictStrategyFactory(); - private final ReferenceQueue removedStartupListenersQueue = new ReferenceQueue(); - private final ReferenceQueue removedShutdownListenersQueue = new ReferenceQueue(); - private final Set startupListeners = Collections - .newSetFromMap(new ConcurrentHashMap()); - private final Set> weakStartupListeners = Collections - .newSetFromMap(new ConcurrentHashMap, Boolean>()); - private final Set> weakShutdownListeners = Collections - .newSetFromMap(new ConcurrentHashMap, Boolean>()); - static { - instance.startup(); - } - private volatile Timer timer; - private volatile ORecordFactoryManager recordFactoryManager = new ORecordFactoryManager(); - private OrientShutdownHook shutdownHook; - private volatile OProfilerMBean profiler; - private ODatabaseThreadLocalFactory databaseThreadFactory; - private volatile boolean active = false; - private ThreadPoolExecutor workers; - private OSignalHandler signalHandler; - - private static class WeakHashSetValueHolder extends WeakReference { - private final int hashCode; - - private WeakHashSetValueHolder(T referent, ReferenceQueue q) { - super(referent, q); - this.hashCode = referent.hashCode(); - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - - if (o == null || getClass() != o.getClass()) - return false; - - WeakHashSetValueHolder that = (WeakHashSetValueHolder) o; - - if (hashCode != that.hashCode) - return false; - - final T thisObject = get(); - final Object thatObject = that.get(); - - if (thisObject == null && thatObject == null) - return super.equals(that); - else if (thisObject != null && thatObject != null) - return thisObject.equals(thatObject); - - return false; - } - } - - protected Orient() { - super(true); - - threadGroup = new ThreadGroup("OrientDB"); - threadGroup.setDaemon(false); - } - - public static Orient instance() { - return instance; - } - - public static String getHomePath() { - String v = System.getProperty("orient.home"); - - if (v == null) - v = OSystemVariableResolver.resolveVariable(ORIENTDB_HOME); - - return OFileUtils.getPath(v); - } - - public static String getTempPath() { - return OFileUtils.getPath(System.getProperty("java.io.tmpdir") + "/orientdb/"); - } - - /** - * Tells if to register database by path. Default is false. Setting to true allows to have multiple databases in different path - * with the same name. - * - * @see #setRegisterDatabaseByPath(boolean) - * @return - */ - public static boolean isRegisterDatabaseByPath() { - return registerDatabaseByPath; - } - - /** - * Register database by path. Default is false. Setting to true allows to have multiple databases in different path with the same - * name. - * - * @param iValue - */ - public static void setRegisterDatabaseByPath(final boolean iValue) { - registerDatabaseByPath = iValue; - } - - public ORecordConflictStrategyFactory getRecordConflictStrategy() { - return recordConflictStrategy; - } - - public Orient startup() { - engineLock.writeLock().lock(); - try { - if (active) - // ALREADY ACTIVE - return this; - - if (timer == null) - timer = new Timer(true); - - profiler = new OProfiler(); - - shutdownHook = new OrientShutdownHook(); - if (signalHandler == null) { - signalHandler = new OSignalHandler(); - signalHandler.installDefaultSignals(); - } - - final int cores = Runtime.getRuntime().availableProcessors(); - - workers = new ThreadPoolExecutor(cores, cores * 3, 10, TimeUnit.SECONDS, new LinkedBlockingQueue(cores * 500) { - @Override - public boolean offer(Runnable e) { - // turn offer() and add() into a blocking calls (unless interrupted) - try { - put(e); - return true; - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - } - return false; - } - }); - - // REGISTER THE EMBEDDED ENGINE - registerEngine(new OEngineLocalPaginated()); - registerEngine(new OEngineMemory()); - registerEngine("com.orientechnologies.orient.client.remote.OEngineRemote"); - - if (OGlobalConfiguration.ENVIRONMENT_DUMP_CFG_AT_STARTUP.getValueAsBoolean()) - OGlobalConfiguration.dumpConfiguration(System.out); - - active = true; - - for (OOrientStartupListener l : startupListeners) - try { - if (l != null) - l.onStartup(); - } catch (Exception e) { - OLogManager.instance().error(this, "Error on startup", e); - } - - purgeWeakStartupListeners(); - for (final WeakHashSetValueHolder wl : weakStartupListeners) - try { - if (wl != null) { - final OOrientStartupListener l = wl.get(); - if (l != null) - l.onStartup(); - } - - } catch (Exception e) { - OLogManager.instance().error(this, "Error on startup", e); - } - } finally { - engineLock.writeLock().unlock(); - } - - return this; - } - - public Orient shutdown() { - engineLock.writeLock().lock(); - try { - if (!active) - return this; - - active = false; - - workers.shutdown(); - try { - workers.awaitTermination(2, TimeUnit.MINUTES); - } catch (InterruptedException e) { - } - - OLogManager.instance().debug(this, "Orient Engine is shutting down..."); - - closeAllStorages(); - - // SHUTDOWN ENGINES - for (OEngine engine : engines.values()) - engine.shutdown(); - engines.clear(); - - if (databaseFactory != null) - // CLOSE ALL DATABASES - databaseFactory.shutdown(); - - if (shutdownHook != null) { - shutdownHook.cancel(); - shutdownHook = null; - } - - if (threadGroup != null) - // STOP ALL THE PENDING THREADS - threadGroup.interrupt(); - - timer.cancel(); - timer = null; - - // NOTE: DON'T REMOVE PROFILER TO AVOID NPE AROUND THE CODE IF ANY THREADS IS STILL WORKING - profiler.shutdown(); - - purgeWeakShutdownListeners(); - for (final WeakHashSetValueHolder wl : weakShutdownListeners) - try { - if (wl != null) { - final OOrientShutdownListener l = wl.get(); - if (l != null) { - l.onShutdown(); - } - } - - } catch (Exception e) { - OLogManager.instance().error(this, "Error during orient shutdown.", e); - } - - // CALL THE SHUTDOWN ON ALL THE LISTENERS - for (OOrientListener l : browseListeners()) { - if (l != null) - try { - l.onShutdown(); - } catch (Exception e) { - OLogManager.instance().error(this, "Error during orient shutdown.", e); - } - - } - - OLogManager.instance().info(this, "OrientDB Engine shutdown complete"); - OLogManager.instance().flush(); - } finally { - engineLock.writeLock().unlock(); - } - - return this; - } - - public void scheduleTask(TimerTask task, long delay, long period) { - engineLock.readLock().lock(); - try { - if (active) - timer.schedule(task, delay, period); - else - OLogManager.instance().warn(this, "OrientDB engine is down. Task will not be scheduled."); - } finally { - engineLock.readLock().unlock(); - } - } - - public void scheduleTask(TimerTask task, Date firstTime, long period) { - engineLock.readLock().lock(); - try { - if (active) - timer.schedule(task, firstTime, period); - else - OLogManager.instance().warn(this, "OrientDB engine is down. Task will not be scheduled."); - } finally { - engineLock.readLock().unlock(); - } - } - - public void closeAllStorages() { - engineLock.writeLock().lock(); - try { - // CLOSE ALL THE STORAGES - final List storagesCopy = new ArrayList(storages.values()); - for (OStorage stg : storagesCopy) { - try { - OLogManager.instance().info(this, "- closing storage: " + stg.getName() + "..."); - stg.close(true, false); - } catch (Throwable e) { - OLogManager.instance().warn(this, "-- error on closing storage", e); - } - } - storages.clear(); - } finally { - engineLock.writeLock().unlock(); - } - } - - public boolean isActive() { - return active; - } - - /** - * @deprecated This method is not thread safe. Use {@link #submit(java.util.concurrent.Callable)} instead. - */ - @Deprecated - public ThreadPoolExecutor getWorkers() { - return workers; - } - - public Future submit(final Runnable runnable) { - engineLock.readLock().lock(); - try { - if (active) - return workers.submit(runnable); - else { - OLogManager.instance().warn(this, "OrientDB engine is down. Task will not be submitted."); - throw new IllegalStateException("OrientDB engine is down. Task will not be submitted."); - } - } finally { - engineLock.readLock().unlock(); - } - } - - public Future submit(final Callable callable) { - engineLock.readLock().lock(); - try { - if (active) - return workers.submit(callable); - else { - OLogManager.instance().warn(this, "OrientDB engine is down. Task will not be submitted."); - throw new IllegalStateException("OrientDB engine is down. Task will not be submitted."); - } - } finally { - engineLock.readLock().unlock(); - } - } - - public OStorage loadStorage(String iURL) { - if (iURL == null || iURL.length() == 0) - throw new IllegalArgumentException("URL missed"); - - if (iURL.endsWith("/")) - iURL = iURL.substring(0, iURL.length() - 1); - - iURL = iURL.replace("//", "/"); - - // SEARCH FOR ENGINE - int pos = iURL.indexOf(':'); - if (pos <= 0) - throw new OConfigurationException("Error in database URL: the engine was not specified. Syntax is: " + URL_SYNTAX - + ". URL was: " + iURL); - - final String engineName = iURL.substring(0, pos); - - engineLock.readLock().lock(); - try { - final OEngine engine = engines.get(engineName.toLowerCase()); - - if (engine == null) - throw new OConfigurationException("Error on opening database: the engine '" + engineName + "' was not found. URL was: " - + iURL + ". Registered engines are: " + engines.keySet()); - - // SEARCH FOR DB-NAME - iURL = iURL.substring(pos + 1); - pos = iURL.indexOf('?'); - - Map parameters = null; - String dbPath = null; - if (pos > 0) { - dbPath = iURL.substring(0, pos); - iURL = iURL.substring(pos + 1); - - // PARSE PARAMETERS - parameters = new HashMap(); - String[] pairs = iURL.split("&"); - String[] kv; - for (String pair : pairs) { - kv = pair.split("="); - if (kv.length < 2) - throw new OConfigurationException("Error on opening database: parameter has no value. Syntax is: " + URL_SYNTAX - + ". URL was: " + iURL); - parameters.put(kv[0], kv[1]); - } - } else - dbPath = iURL; - - final String dbName = registerDatabaseByPath ? dbPath : OIOUtils.getRelativePathIfAny(dbPath, null); - - OStorage storage; - if (engine.isShared()) { - // SEARCH IF ALREADY USED - storage = storages.get(dbName); - if (storage == null) { - // NOT FOUND: CREATE IT - storage = engine.createStorage(dbPath, parameters); - - final OStorage oldStorage = storages.putIfAbsent(dbName, storage); - if (oldStorage != null) - storage = oldStorage; - } - } else { - // REGISTER IT WITH A SERIAL NAME TO AVOID BEING REUSED - storage = engine.createStorage(dbPath, parameters); - storages.put(dbName + "__" + serialId.incrementAndGet(), storage); - } - - for (OOrientListener l : browseListeners()) - l.onStorageRegistered(storage); - - return storage; - } finally { - engineLock.readLock().unlock(); - } - } - - public OStorage registerStorage(OStorage storage) throws IOException { - engineLock.readLock().lock(); - try { - for (OOrientListener l : browseListeners()) - l.onStorageRegistered(storage); - - OStorage oldStorage = storages.putIfAbsent(storage.getName(), storage); - if (oldStorage != null) - storage = oldStorage; - - return storage; - } finally { - engineLock.readLock().unlock(); - } - } - - public OStorage getStorage(final String dbName) { - engineLock.readLock().lock(); - try { - return storages.get(dbName); - } finally { - engineLock.readLock().unlock(); - } - } - - public void registerEngine(final OEngine iEngine) { - engineLock.readLock().lock(); - try { - engines.put(iEngine.getName(), iEngine); - } finally { - engineLock.readLock().unlock(); - } - } - - /** - * Returns the engine by its name. - * - * @param engineName - * Engine name to retrieve - * @return OEngine instance of found, otherwise null - */ - public OEngine getEngine(final String engineName) { - engineLock.readLock().lock(); - try { - return engines.get(engineName); - } finally { - engineLock.readLock().unlock(); - } - } - - public Set getEngines() { - engineLock.readLock().lock(); - try { - return Collections.unmodifiableSet(engines.keySet()); - } finally { - engineLock.readLock().unlock(); - } - } - - public void unregisterStorageByName(final String name) { - final String dbName = registerDatabaseByPath ? name : OIOUtils.getRelativePathIfAny(name, null); - final OStorage stg = storages.get(dbName); - unregisterStorage(stg); - } - - public void unregisterStorage(final OStorage storage) { - if (!active) - // SHUTDOWNING OR NOT ACTIVE: RETURN - return; - - if (storage == null) - return; - - engineLock.writeLock().lock(); - try { - // UNREGISTER ALL THE LISTENER ONE BY ONE AVOIDING SELF-RECURSION BY REMOVING FROM THE LIST - final Iterable listenerCopy = getListenersCopy(); - for (Iterator it = listenerCopy.iterator(); it.hasNext();) { - final OOrientListener l = it.next(); - unregisterListener(l); - l.onStorageUnregistered(storage); - } - - final List storagesToRemove = new ArrayList(); - - for (Entry s : storages.entrySet()) { - if (s.getValue().equals(storage)) - storagesToRemove.add(s.getKey()); - } - - for (String dbName : storagesToRemove) - storages.remove(dbName); - - // UNREGISTER STORAGE FROM ENGINES IN CASE IS CACHED - for (OEngine engine : engines.values()) { - engine.removeStorage(storage); - } - - } finally { - engineLock.writeLock().unlock(); - } - } - - public Collection getStorages() { - engineLock.readLock().lock(); - try { - return new ArrayList(storages.values()); - } finally { - engineLock.readLock().unlock(); - } - } - - /** - * @deprecated This method is not thread safe please use {@link #scheduleTask(java.util.TimerTask, long, long)} instead. - */ - @Deprecated - public Timer getTimer() { - return timer; - } - - public void removeShutdownHook() { - if (shutdownHook != null) { - shutdownHook.cancel(); - shutdownHook = null; - } - } - - public boolean isSelfManagedShutdown() { - return shutdownHook != null; - } - - public Iterator getDbLifecycleListeners() { - return dbLifecycleListeners.keySet().iterator(); - } - - public void addDbLifecycleListener(final ODatabaseLifecycleListener iListener) { - final Map tmp = new LinkedHashMap( - dbLifecycleListeners); - tmp.put(iListener, iListener.getPriority()); - dbLifecycleListeners.clear(); - for (ODatabaseLifecycleListener.PRIORITY p : ODatabaseLifecycleListener.PRIORITY.values()) { - for (Map.Entry e : tmp.entrySet()) { - if (e.getValue() == p) - dbLifecycleListeners.put(e.getKey(), e.getValue()); - } - } - } - - public void removeDbLifecycleListener(final ODatabaseLifecycleListener iListener) { - dbLifecycleListeners.remove(iListener); - } - - public ThreadGroup getThreadGroup() { - return threadGroup; - } - - public ODatabaseThreadLocalFactory getDatabaseThreadFactory() { - return databaseThreadFactory; - } - - public ORecordFactoryManager getRecordFactoryManager() { - return recordFactoryManager; - } - - public void setRecordFactoryManager(final ORecordFactoryManager iRecordFactoryManager) { - recordFactoryManager = iRecordFactoryManager; - } - - public ODatabaseFactory getDatabaseFactory() { - return databaseFactory; - } - - public OProfilerMBean getProfiler() { - return profiler; - } - - public void setProfiler(final OProfilerMBean iProfiler) { - profiler = iProfiler; - } - - public void registerThreadDatabaseFactory(final ODatabaseThreadLocalFactory iDatabaseFactory) { - databaseThreadFactory = iDatabaseFactory; - } - - public OScriptManager getScriptManager() { - return scriptManager; - } - - @Override - public void registerListener(OOrientListener listener) { - if (listener instanceof OOrientStartupListener) - registerOrientStartupListener((OOrientStartupListener) listener); - - super.registerListener(listener); - } - - @Override - public void unregisterListener(OOrientListener listener) { - if (listener instanceof OOrientStartupListener) - unregisterOrientStartupListener((OOrientStartupListener) listener); - - super.unregisterListener(listener); - } - - public void registerOrientStartupListener(OOrientStartupListener listener) { - startupListeners.add(listener); - } - - public void registerWeakOrientStartupListener(OOrientStartupListener listener) { - purgeWeakStartupListeners(); - weakStartupListeners.add(new WeakHashSetValueHolder(listener, removedStartupListenersQueue)); - } - - public void unregisterOrientStartupListener(OOrientStartupListener listener) { - startupListeners.remove(listener); - } - - public void unregisterWeakOrientStartupListener(OOrientStartupListener listener) { - purgeWeakStartupListeners(); - weakStartupListeners.remove(new WeakHashSetValueHolder(listener, null)); - } - - public void registerWeakOrientShutdownListener(OOrientShutdownListener listener) { - purgeWeakShutdownListeners(); - weakShutdownListeners.add(new WeakHashSetValueHolder(listener, removedShutdownListenersQueue)); - } - - public void unregisterWeakOrientShutdownListener(OOrientShutdownListener listener) { - purgeWeakShutdownListeners(); - weakShutdownListeners.remove(new WeakHashSetValueHolder(listener, null)); - } - - @Override - public void resetListeners() { - super.resetListeners(); - - weakShutdownListeners.clear(); - - startupListeners.clear(); - weakStartupListeners.clear(); - } - - private void registerEngine(final String className) { - try { - final Class cls = Class.forName(className); - registerEngine((OEngine) cls.newInstance()); - } catch (Exception e) { - } - } - - private void purgeWeakStartupListeners() { - synchronized (removedStartupListenersQueue) { - WeakHashSetValueHolder ref = (WeakHashSetValueHolder) removedStartupListenersQueue - .poll(); - while (ref != null) { - weakStartupListeners.remove(ref); - ref = (WeakHashSetValueHolder) removedStartupListenersQueue.poll(); - } - - } - } - - private void purgeWeakShutdownListeners() { - synchronized (removedShutdownListenersQueue) { - WeakHashSetValueHolder ref = (WeakHashSetValueHolder) removedShutdownListenersQueue - .poll(); - while (ref != null) { - weakShutdownListeners.remove(ref); - ref = (WeakHashSetValueHolder) removedShutdownListenersQueue.poll(); - } - - } - } -} diff --git a/All/Genesis-NP/Genesis#402/old/Orient.java b/All/Genesis-NP/Genesis#402/old/Orient.java deleted file mode 100755 index b00aa9b..0000000 --- a/All/Genesis-NP/Genesis#402/old/Orient.java +++ /dev/null @@ -1,762 +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; - -import java.io.IOException; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; -import java.util.*; -import java.util.Map.Entry; -import java.util.concurrent.Callable; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; - -import com.orientechnologies.common.io.OFileUtils; -import com.orientechnologies.common.io.OIOUtils; -import com.orientechnologies.common.listener.OListenerManger; -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.parser.OSystemVariableResolver; -import com.orientechnologies.common.profiler.OProfiler; -import com.orientechnologies.common.profiler.OProfilerMBean; -import com.orientechnologies.orient.core.command.script.OScriptManager; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.conflict.ORecordConflictStrategyFactory; -import com.orientechnologies.orient.core.db.ODatabaseFactory; -import com.orientechnologies.orient.core.db.ODatabaseLifecycleListener; -import com.orientechnologies.orient.core.db.ODatabaseThreadLocalFactory; -import com.orientechnologies.orient.core.engine.OEngine; -import com.orientechnologies.orient.core.engine.local.OEngineLocalPaginated; -import com.orientechnologies.orient.core.engine.memory.OEngineMemory; -import com.orientechnologies.orient.core.exception.OConfigurationException; -import com.orientechnologies.orient.core.record.ORecordFactoryManager; -import com.orientechnologies.orient.core.storage.OStorage; - -public class Orient extends OListenerManger { - public static final String ORIENTDB_HOME = "ORIENTDB_HOME"; - public static final String URL_SYNTAX = "::[?=[&]]*"; - - private static final Orient instance = new Orient(); - private static volatile boolean registerDatabaseByPath = false; - - private final ConcurrentMap engines = new ConcurrentHashMap(); - private final ConcurrentMap storages = new ConcurrentHashMap(); - - private final Map dbLifecycleListeners = new LinkedHashMap(); - private final ODatabaseFactory databaseFactory = new ODatabaseFactory(); - private final OScriptManager scriptManager = new OScriptManager(); - private final ThreadGroup threadGroup; - private final AtomicInteger serialId = new AtomicInteger(); - private final ReadWriteLock engineLock = new ReentrantReadWriteLock(); - private final ORecordConflictStrategyFactory recordConflictStrategy = new ORecordConflictStrategyFactory(); - private final ReferenceQueue removedStartupListenersQueue = new ReferenceQueue(); - private final ReferenceQueue removedShutdownListenersQueue = new ReferenceQueue(); - private final Set startupListeners = Collections - .newSetFromMap(new ConcurrentHashMap()); - private final Set> weakStartupListeners = Collections - .newSetFromMap(new ConcurrentHashMap, Boolean>()); - private final Set> weakShutdownListeners = Collections - .newSetFromMap(new ConcurrentHashMap, Boolean>()); - static { - instance.startup(); - } - private volatile Timer timer; - private volatile ORecordFactoryManager recordFactoryManager = new ORecordFactoryManager(); - private OrientShutdownHook shutdownHook; - private volatile OProfilerMBean profiler; - private ODatabaseThreadLocalFactory databaseThreadFactory; - private volatile boolean active = false; - private ThreadPoolExecutor workers; - private OSignalHandler signalHandler; - - private static class WeakHashSetValueHolder extends WeakReference { - private final int hashCode; - - private WeakHashSetValueHolder(T referent, ReferenceQueue q) { - super(referent, q); - this.hashCode = referent.hashCode(); - } - - @Override - public int hashCode() { - return hashCode; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - - if (o == null || getClass() != o.getClass()) - return false; - - WeakHashSetValueHolder that = (WeakHashSetValueHolder) o; - - if (hashCode != that.hashCode) - return false; - - final T thisObject = get(); - final Object thatObject = that.get(); - - if (thisObject == null && thatObject == null) - return super.equals(that); - else if (thisObject != null && thatObject != null) - return thisObject.equals(thatObject); - - return false; - } - } - - protected Orient() { - super(true); - - threadGroup = new ThreadGroup("OrientDB"); - threadGroup.setDaemon(false); - } - - public static Orient instance() { - return instance; - } - - public static String getHomePath() { - String v = System.getProperty("orient.home"); - - if (v == null) - v = OSystemVariableResolver.resolveVariable(ORIENTDB_HOME); - - return OFileUtils.getPath(v); - } - - public static String getTempPath() { - return OFileUtils.getPath(System.getProperty("java.io.tmpdir") + "/orientdb/"); - } - - /** - * Tells if to register database by path. Default is false. Setting to true allows to have multiple databases in different path - * with the same name. - * - * @see #setRegisterDatabaseByPath(boolean) - * @return - */ - public static boolean isRegisterDatabaseByPath() { - return registerDatabaseByPath; - } - - /** - * Register database by path. Default is false. Setting to true allows to have multiple databases in different path with the same - * name. - * - * @param iValue - */ - public static void setRegisterDatabaseByPath(final boolean iValue) { - registerDatabaseByPath = iValue; - } - - public ORecordConflictStrategyFactory getRecordConflictStrategy() { - return recordConflictStrategy; - } - - public Orient startup() { - engineLock.writeLock().lock(); - try { - if (active) - // ALREADY ACTIVE - return this; - - if (timer == null) - timer = new Timer(true); - - profiler = new OProfiler(); - - shutdownHook = new OrientShutdownHook(); - if (signalHandler == null) { - signalHandler = new OSignalHandler(); - signalHandler.installDefaultSignals(); - } - - final int cores = Runtime.getRuntime().availableProcessors(); - - workers = new ThreadPoolExecutor(cores, cores * 3, 10, TimeUnit.SECONDS, new LinkedBlockingQueue(cores * 500) { - @Override - public boolean offer(Runnable e) { - // turn offer() and add() into a blocking calls (unless interrupted) - try { - put(e); - return true; - } catch (InterruptedException ie) { - Thread.currentThread().interrupt(); - } - return false; - } - }); - - // REGISTER THE EMBEDDED ENGINE - registerEngine(new OEngineLocalPaginated()); - registerEngine(new OEngineMemory()); - registerEngine("com.orientechnologies.orient.client.remote.OEngineRemote"); - - if (OGlobalConfiguration.ENVIRONMENT_DUMP_CFG_AT_STARTUP.getValueAsBoolean()) - OGlobalConfiguration.dumpConfiguration(System.out); - - active = true; - - for (OOrientStartupListener l : startupListeners) - try { - if (l != null) - l.onStartup(); - } catch (Exception e) { - OLogManager.instance().error(this, "Error on startup", e); - } - - purgeWeakStartupListeners(); - for (final WeakHashSetValueHolder wl : weakStartupListeners) - try { - if (wl != null) { - final OOrientStartupListener l = wl.get(); - if (l != null) - l.onStartup(); - } - - } catch (Exception e) { - OLogManager.instance().error(this, "Error on startup", e); - } - } finally { - engineLock.writeLock().unlock(); - } - - return this; - } - - public Orient shutdown() { - engineLock.writeLock().lock(); - try { - if (!active) - return this; - - active = false; - - workers.shutdown(); - try { - workers.awaitTermination(2, TimeUnit.MINUTES); - } catch (InterruptedException e) { - } - - OLogManager.instance().debug(this, "Orient Engine is shutting down..."); - - closeAllStorages(); - - // SHUTDOWN ENGINES - for (OEngine engine : engines.values()) - engine.shutdown(); - engines.clear(); - - if (databaseFactory != null) - // CLOSE ALL DATABASES - databaseFactory.shutdown(); - - if (shutdownHook != null) { - shutdownHook.cancel(); - shutdownHook = null; - } - - if (threadGroup != null) - // STOP ALL THE PENDING THREADS - threadGroup.interrupt(); - - timer.cancel(); - timer = null; - - // NOTE: DON'T REMOVE PROFILER TO AVOID NPE AROUND THE CODE IF ANY THREADS IS STILL WORKING - profiler.shutdown(); - - // CALL THE SHUTDOWN ON ALL THE LISTENERS - for (OOrientListener l : browseListeners()) { - if (l != null) - try { - l.onShutdown(); - } catch (Exception e) { - OLogManager.instance().error(this, "Error during orient shutdown.", e); - } - - } - - purgeWeakShutdownListeners(); - for (final WeakHashSetValueHolder wl : weakShutdownListeners) - try { - if (wl != null) { - final OOrientShutdownListener l = wl.get(); - if (l != null) - l.onShutdown(); - } - - } catch (Exception e) { - OLogManager.instance().error(this, "Error during orient shutdown.", e); - } - - OLogManager.instance().info(this, "OrientDB Engine shutdown complete"); - OLogManager.instance().flush(); - } finally { - engineLock.writeLock().unlock(); - } - - return this; - } - - public void scheduleTask(TimerTask task, long delay, long period) { - engineLock.readLock().lock(); - try { - if (active) - timer.schedule(task, delay, period); - else - OLogManager.instance().warn(this, "OrientDB engine is down. Task will not be scheduled."); - } finally { - engineLock.readLock().unlock(); - } - } - - public void scheduleTask(TimerTask task, Date firstTime, long period) { - engineLock.readLock().lock(); - try { - if (active) - timer.schedule(task, firstTime, period); - else - OLogManager.instance().warn(this, "OrientDB engine is down. Task will not be scheduled."); - } finally { - engineLock.readLock().unlock(); - } - } - - public void closeAllStorages() { - engineLock.writeLock().lock(); - try { - // CLOSE ALL THE STORAGES - final List storagesCopy = new ArrayList(storages.values()); - for (OStorage stg : storagesCopy) { - try { - OLogManager.instance().info(this, "- closing storage: " + stg.getName() + "..."); - stg.close(true, false); - } catch (Throwable e) { - OLogManager.instance().warn(this, "-- error on closing storage", e); - } - } - storages.clear(); - } finally { - engineLock.writeLock().unlock(); - } - } - - public boolean isActive() { - return active; - } - - /** - * @deprecated This method is not thread safe. Use {@link #submit(java.util.concurrent.Callable)} instead. - */ - @Deprecated - public ThreadPoolExecutor getWorkers() { - return workers; - } - - public Future submit(final Runnable runnable) { - engineLock.readLock().lock(); - try { - if (active) - return workers.submit(runnable); - else { - OLogManager.instance().warn(this, "OrientDB engine is down. Task will not be submitted."); - throw new IllegalStateException("OrientDB engine is down. Task will not be submitted."); - } - } finally { - engineLock.readLock().unlock(); - } - } - - public Future submit(final Callable callable) { - engineLock.readLock().lock(); - try { - if (active) - return workers.submit(callable); - else { - OLogManager.instance().warn(this, "OrientDB engine is down. Task will not be submitted."); - throw new IllegalStateException("OrientDB engine is down. Task will not be submitted."); - } - } finally { - engineLock.readLock().unlock(); - } - } - - public OStorage loadStorage(String iURL) { - if (iURL == null || iURL.length() == 0) - throw new IllegalArgumentException("URL missed"); - - if (iURL.endsWith("/")) - iURL = iURL.substring(0, iURL.length() - 1); - - iURL = iURL.replace("//", "/"); - - // SEARCH FOR ENGINE - int pos = iURL.indexOf(':'); - if (pos <= 0) - throw new OConfigurationException("Error in database URL: the engine was not specified. Syntax is: " + URL_SYNTAX - + ". URL was: " + iURL); - - final String engineName = iURL.substring(0, pos); - - engineLock.readLock().lock(); - try { - final OEngine engine = engines.get(engineName.toLowerCase()); - - if (engine == null) - throw new OConfigurationException("Error on opening database: the engine '" + engineName + "' was not found. URL was: " - + iURL + ". Registered engines are: " + engines.keySet()); - - // SEARCH FOR DB-NAME - iURL = iURL.substring(pos + 1); - pos = iURL.indexOf('?'); - - Map parameters = null; - String dbPath = null; - if (pos > 0) { - dbPath = iURL.substring(0, pos); - iURL = iURL.substring(pos + 1); - - // PARSE PARAMETERS - parameters = new HashMap(); - String[] pairs = iURL.split("&"); - String[] kv; - for (String pair : pairs) { - kv = pair.split("="); - if (kv.length < 2) - throw new OConfigurationException("Error on opening database: parameter has no value. Syntax is: " + URL_SYNTAX - + ". URL was: " + iURL); - parameters.put(kv[0], kv[1]); - } - } else - dbPath = iURL; - - final String dbName = registerDatabaseByPath ? dbPath : OIOUtils.getRelativePathIfAny(dbPath, null); - - OStorage storage; - if (engine.isShared()) { - // SEARCH IF ALREADY USED - storage = storages.get(dbName); - if (storage == null) { - // NOT FOUND: CREATE IT - storage = engine.createStorage(dbPath, parameters); - - final OStorage oldStorage = storages.putIfAbsent(dbName, storage); - if (oldStorage != null) - storage = oldStorage; - } - } else { - // REGISTER IT WITH A SERIAL NAME TO AVOID BEING REUSED - storage = engine.createStorage(dbPath, parameters); - storages.put(dbName + "__" + serialId.incrementAndGet(), storage); - } - - for (OOrientListener l : browseListeners()) - l.onStorageRegistered(storage); - - return storage; - } finally { - engineLock.readLock().unlock(); - } - } - - public OStorage registerStorage(OStorage storage) throws IOException { - engineLock.readLock().lock(); - try { - for (OOrientListener l : browseListeners()) - l.onStorageRegistered(storage); - - OStorage oldStorage = storages.putIfAbsent(storage.getName(), storage); - if (oldStorage != null) - storage = oldStorage; - - return storage; - } finally { - engineLock.readLock().unlock(); - } - } - - public OStorage getStorage(final String dbName) { - engineLock.readLock().lock(); - try { - return storages.get(dbName); - } finally { - engineLock.readLock().unlock(); - } - } - - public void registerEngine(final OEngine iEngine) { - engineLock.readLock().lock(); - try { - engines.put(iEngine.getName(), iEngine); - } finally { - engineLock.readLock().unlock(); - } - } - - /** - * Returns the engine by its name. - * - * @param engineName - * Engine name to retrieve - * @return OEngine instance of found, otherwise null - */ - public OEngine getEngine(final String engineName) { - engineLock.readLock().lock(); - try { - return engines.get(engineName); - } finally { - engineLock.readLock().unlock(); - } - } - - public Set getEngines() { - engineLock.readLock().lock(); - try { - return Collections.unmodifiableSet(engines.keySet()); - } finally { - engineLock.readLock().unlock(); - } - } - - public void unregisterStorageByName(final String name) { - final String dbName = registerDatabaseByPath ? name : OIOUtils.getRelativePathIfAny(name, null); - final OStorage stg = storages.get(dbName); - unregisterStorage(stg); - } - - public void unregisterStorage(final OStorage storage) { - if (!active) - // SHUTDOWNING OR NOT ACTIVE: RETURN - return; - - if (storage == null) - return; - - engineLock.writeLock().lock(); - try { - // UNREGISTER ALL THE LISTENER ONE BY ONE AVOIDING SELF-RECURSION BY REMOVING FROM THE LIST - final Iterable listenerCopy = getListenersCopy(); - for (Iterator it = listenerCopy.iterator(); it.hasNext();) { - final OOrientListener l = it.next(); - unregisterListener(l); - l.onStorageUnregistered(storage); - } - - final List storagesToRemove = new ArrayList(); - - for (Entry s : storages.entrySet()) { - if (s.getValue().equals(storage)) - storagesToRemove.add(s.getKey()); - } - - for (String dbName : storagesToRemove) - storages.remove(dbName); - - // UNREGISTER STORAGE FROM ENGINES IN CASE IS CACHED - for (OEngine engine : engines.values()) { - engine.removeStorage(storage); - } - - } finally { - engineLock.writeLock().unlock(); - } - } - - public Collection getStorages() { - engineLock.readLock().lock(); - try { - return new ArrayList(storages.values()); - } finally { - engineLock.readLock().unlock(); - } - } - - /** - * @deprecated This method is not thread safe please use {@link #scheduleTask(java.util.TimerTask, long, long)} instead. - */ - @Deprecated - public Timer getTimer() { - return timer; - } - - public void removeShutdownHook() { - if (shutdownHook != null) { - shutdownHook.cancel(); - shutdownHook = null; - } - } - - public boolean isSelfManagedShutdown() { - return shutdownHook != null; - } - - public Iterator getDbLifecycleListeners() { - return dbLifecycleListeners.keySet().iterator(); - } - - public void addDbLifecycleListener(final ODatabaseLifecycleListener iListener) { - final Map tmp = new LinkedHashMap( - dbLifecycleListeners); - tmp.put(iListener, iListener.getPriority()); - dbLifecycleListeners.clear(); - for (ODatabaseLifecycleListener.PRIORITY p : ODatabaseLifecycleListener.PRIORITY.values()) { - for (Map.Entry e : tmp.entrySet()) { - if (e.getValue() == p) - dbLifecycleListeners.put(e.getKey(), e.getValue()); - } - } - } - - public void removeDbLifecycleListener(final ODatabaseLifecycleListener iListener) { - dbLifecycleListeners.remove(iListener); - } - - public ThreadGroup getThreadGroup() { - return threadGroup; - } - - public ODatabaseThreadLocalFactory getDatabaseThreadFactory() { - return databaseThreadFactory; - } - - public ORecordFactoryManager getRecordFactoryManager() { - return recordFactoryManager; - } - - public void setRecordFactoryManager(final ORecordFactoryManager iRecordFactoryManager) { - recordFactoryManager = iRecordFactoryManager; - } - - public ODatabaseFactory getDatabaseFactory() { - return databaseFactory; - } - - public OProfilerMBean getProfiler() { - return profiler; - } - - public void setProfiler(final OProfilerMBean iProfiler) { - profiler = iProfiler; - } - - public void registerThreadDatabaseFactory(final ODatabaseThreadLocalFactory iDatabaseFactory) { - databaseThreadFactory = iDatabaseFactory; - } - - public OScriptManager getScriptManager() { - return scriptManager; - } - - @Override - public void registerListener(OOrientListener listener) { - if (listener instanceof OOrientStartupListener) - registerOrientStartupListener((OOrientStartupListener) listener); - - super.registerListener(listener); - } - - @Override - public void unregisterListener(OOrientListener listener) { - if (listener instanceof OOrientStartupListener) - unregisterOrientStartupListener((OOrientStartupListener) listener); - - super.unregisterListener(listener); - } - - public void registerOrientStartupListener(OOrientStartupListener listener) { - startupListeners.add(listener); - } - - public void registerWeakOrientStartupListener(OOrientStartupListener listener) { - purgeWeakStartupListeners(); - weakStartupListeners.add(new WeakHashSetValueHolder(listener, removedStartupListenersQueue)); - } - - public void unregisterOrientStartupListener(OOrientStartupListener listener) { - startupListeners.remove(listener); - } - - public void unregisterWeakOrientStartupListener(OOrientStartupListener listener) { - purgeWeakStartupListeners(); - weakStartupListeners.remove(new WeakHashSetValueHolder(listener, null)); - } - - public void registerWeakOrientShutdownListener(OOrientShutdownListener listener) { - purgeWeakShutdownListeners(); - weakShutdownListeners.add(new WeakHashSetValueHolder(listener, removedShutdownListenersQueue)); - } - - public void unregisterWeakOrientShutdownListener(OOrientShutdownListener listener) { - purgeWeakShutdownListeners(); - weakShutdownListeners.remove(new WeakHashSetValueHolder(listener, null)); - } - - @Override - public void resetListeners() { - super.resetListeners(); - - weakShutdownListeners.clear(); - - startupListeners.clear(); - weakStartupListeners.clear(); - } - - private void registerEngine(final String className) { - try { - final Class cls = Class.forName(className); - registerEngine((OEngine) cls.newInstance()); - } catch (Exception e) { - } - } - - private void purgeWeakStartupListeners() { - synchronized (removedStartupListenersQueue) { - WeakHashSetValueHolder ref = (WeakHashSetValueHolder) removedStartupListenersQueue - .poll(); - while (ref != null) { - weakStartupListeners.remove(ref); - ref = (WeakHashSetValueHolder) removedStartupListenersQueue.poll(); - } - - } - } - - private void purgeWeakShutdownListeners() { - synchronized (removedShutdownListenersQueue) { - WeakHashSetValueHolder ref = (WeakHashSetValueHolder) removedShutdownListenersQueue - .poll(); - while (ref != null) { - weakShutdownListeners.remove(ref); - ref = (WeakHashSetValueHolder) removedShutdownListenersQueue.poll(); - } - - } - } -} diff --git a/All/Genesis-NP/Genesis#402/pair.info b/All/Genesis-NP/Genesis#402/pair.info deleted file mode 100755 index c8f141e..0000000 --- a/All/Genesis-NP/Genesis#402/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:402 -SATName:Genesis -modifiedFPath:core/src/main/java/com/orientechnologies/orient/core/Orient.java -comSha:2fe7f0458df591a76fc00a3e92102588938abb13 -parentComSha:2fe7f0458df591a76fc00a3e92102588938abb13^1 -githubUrl:https://github.com/orientechnologies/orientdb -repoName:orientechnologies#orientdb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#405/comMsg.txt b/All/Genesis-NP/Genesis#405/comMsg.txt deleted file mode 100755 index 14cae9e..0000000 --- a/All/Genesis-NP/Genesis#405/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Distributed: fixed NPE diff --git a/All/Genesis-NP/Genesis#405/diff.diff b/All/Genesis-NP/Genesis#405/diff.diff deleted file mode 100755 index 465205e..0000000 --- a/All/Genesis-NP/Genesis#405/diff.diff +++ /dev/null @@ -1,40 +0,0 @@ -diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java -index 4fd9685..8aec09f 100755 ---- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java -+++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java -@@ -22,14 +21,0 @@ package com.orientechnologies.orient.server; --import java.io.IOException; --import java.net.Socket; --import java.util.ArrayList; --import java.util.HashMap; --import java.util.HashSet; --import java.util.Iterator; --import java.util.List; --import java.util.Map.Entry; --import java.util.Set; --import java.util.TimerTask; --import java.util.concurrent.ConcurrentHashMap; --import java.util.concurrent.ConcurrentMap; --import java.util.concurrent.atomic.AtomicInteger; -- -@@ -49,0 +36,14 @@ import com.orientechnologies.orient.server.network.protocol.binary.ONetworkProto -+import java.io.IOException; -+import java.net.Socket; -+import java.util.ArrayList; -+import java.util.HashMap; -+import java.util.HashSet; -+import java.util.Iterator; -+import java.util.List; -+import java.util.Map.Entry; -+import java.util.Set; -+import java.util.TimerTask; -+import java.util.concurrent.ConcurrentHashMap; -+import java.util.concurrent.ConcurrentMap; -+import java.util.concurrent.atomic.AtomicInteger; -+ -@@ -302 +302,4 @@ public class OClientConnectionManager { -- ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.data.serializationImpl); -+ final ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.data.serializationImpl); -+ if( ser == null ) -+ return; -+ diff --git a/All/Genesis-NP/Genesis#405/new/OClientConnectionManager.java b/All/Genesis-NP/Genesis#405/new/OClientConnectionManager.java deleted file mode 100755 index 8aec09f..0000000 --- a/All/Genesis-NP/Genesis#405/new/OClientConnectionManager.java +++ /dev/null @@ -1,371 +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.server; - -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.profiler.OAbstractProfiler.OProfilerHookValue; -import com.orientechnologies.common.profiler.OProfilerMBean.METRIC_TYPE; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandRequestText; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; -import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol; -import com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary; - -import java.io.IOException; -import java.net.Socket; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - -public class OClientConnectionManager { - private static final OClientConnectionManager instance = new OClientConnectionManager(); - protected ConcurrentMap connections = new ConcurrentHashMap(); - protected AtomicInteger connectionSerial = new AtomicInteger(0); - - public OClientConnectionManager() { - final int delay = OGlobalConfiguration.SERVER_CHANNEL_CLEAN_DELAY.getValueAsInteger(); - - Orient.instance().scheduleTask(new TimerTask() { - - @Override - public void run() { - cleanExpiredConnections(); - } - } - - , delay, delay); - - Orient - .instance() - .getProfiler() - .registerHookValue("server.connections.actives", "Number of active network connections", METRIC_TYPE.COUNTER, - new OProfilerHookValue() { - public Object getValue() { - return connections.size(); - } - }); - } - - public void cleanExpiredConnections() { - final Iterator> iterator = connections.entrySet().iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - - final Socket socket; - if (entry.getValue().protocol == null || entry.getValue().protocol.getChannel() == null) - socket = null; - else - socket = entry.getValue().protocol.getChannel().socket; - - if (socket == null || socket.isClosed() || socket.isInputShutdown()) { - OLogManager.instance().debug(this, "[OClientConnectionManager] found and removed pending closed channel %d (%s)", - entry.getKey(), socket); - try { - OCommandRequestText command = entry.getValue().data.command; - if (command != null && command.isIdempotent()) { - entry.getValue().protocol.sendShutdown(); - entry.getValue().protocol.interrupt(); - } - entry.getValue().close(); - - } catch (Exception e) { - OLogManager.instance().error(this, "Error during close of connection for close channel", e); - } - iterator.remove(); - } - } - } - - public static OClientConnectionManager instance() { - return instance; - } - - /** - * Create a connection. - * - * @param iProtocol - * protocol which will be used by connection - * @return new connection - * @throws IOException - */ - public OClientConnection connect(final ONetworkProtocol iProtocol) throws IOException { - - final OClientConnection connection; - - connection = new OClientConnection(connectionSerial.incrementAndGet(), iProtocol); - - connections.put(connection.id, connection); - - OLogManager.instance().config(this, "Remote client connected from: " + connection); - - return connection; - } - - /** - * Retrieves the connection by id. - * - * @param iChannelId - * id of connection - * @return The connection if any, otherwise null - */ - public OClientConnection getConnection(final int iChannelId, ONetworkProtocol protocol) { - // SEARCH THE CONNECTION BY ID - OClientConnection connection = connections.get(iChannelId); - if (connection != null) - connection.protocol = protocol; - - return connection; - } - - /** - * Retrieves the connection by address/port. - * - * @param iAddress - * The address as string in the format address as format : - * @return The connection if any, otherwise null - */ - public OClientConnection getConnection(final String iAddress) { - for (OClientConnection conn : connections.values()) { - if (iAddress.equals(conn.getRemoteAddress())) - return conn; - } - return null; - } - - /** - * Disconnects and kill the associated network manager. - * - * @param iChannelId - * id of connection - */ - public void kill(final int iChannelId) { - kill(connections.get(iChannelId)); - } - - /** - * Disconnects and kill the associated network manager. - * - * @param connection - * connection to kill - */ - public void kill(final OClientConnection connection) { - if (connection != null) { - final ONetworkProtocol protocol = connection.protocol; - - try { - // INTERRUPT THE NEWTORK MANAGER TOO - protocol.interrupt(); - } catch (Exception e) { - } - - disconnect(connection); - - // KILL THE NETWORK MANAGER TOO - protocol.sendShutdown(); - } - } - - public boolean has(final int id) { - return connections.containsKey(id); - } - - /** - * Interrupt the associated network manager. - * - * @param iChannelId - * id of connection - */ - public void interrupt(final int iChannelId) { - final OClientConnection connection = connections.get(iChannelId); - if (connection != null) { - final ONetworkProtocol protocol = connection.protocol; - if (protocol != null) - // INTERRUPT THE NEWTORK MANAGER - protocol.interrupt(); - } - } - - /** - * Disconnects a client connections - * - * @param iChannelId - * id of connection - * @return true if was last one, otherwise false - */ - public boolean disconnect(final int iChannelId) { - OLogManager.instance().debug(this, "Disconnecting connection with id=%d", iChannelId); - - final OClientConnection connection = connections.remove(iChannelId); - - if (connection != null) { - connection.close(); - - // CHECK IF THERE ARE OTHER CONNECTIONS - for (Entry entry : connections.entrySet()) { - if (entry.getValue().getProtocol().equals(connection.getProtocol())) { - OLogManager.instance() - .debug(this, "Disconnected connection with id=%d but are present other active channels", iChannelId); - return false; - } - } - - OLogManager.instance().debug(this, "Disconnected connection with id=%d, no other active channels found", iChannelId); - return true; - } - - OLogManager.instance().debug(this, "Cannot find connection with id=%d", iChannelId); - return false; - } - - public void disconnect(final OClientConnection iConnection) { - OLogManager.instance().debug(this, "Disconnecting connection %s...", iConnection); - - iConnection.close(); - - int totalRemoved = 0; - for (Entry entry : new HashMap(connections).entrySet()) { - final OClientConnection conn = entry.getValue(); - if (conn != null && conn.equals(iConnection)) { - connections.remove(entry.getKey()); - totalRemoved++; - } - } - - OLogManager.instance().debug(this, "Disconnected connection %s found %d channels", iConnection, totalRemoved); - - } - - public List getConnections() { - return new ArrayList(connections.values()); - } - - public int getTotal() { - return connections.size(); - } - - /** - * Pushes the distributed configuration to all the connected clients. - */ - public void pushDistribCfg2Clients(final ODocument iConfig) { - if (iConfig == null) - return; - - final Set pushed = new HashSet(); - for (OClientConnection c : connections.values()) { - try { - final String remoteAddress = c.getRemoteAddress(); - if (pushed.contains(remoteAddress)) - // ALREADY SENT: JUMP IT - continue; - - } catch (Exception e) { - // SOCKET EXCEPTION SKIP IT - continue; - } - - if (!(c.protocol instanceof ONetworkProtocolBinary) && c.data.serializationImpl != null) - // INVOLVE ONLY BINAR PROTOCOLS - continue; - - final ONetworkProtocolBinary p = (ONetworkProtocolBinary) c.protocol; - final OChannelBinary channel = (OChannelBinary) p.getChannel(); - final ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.data.serializationImpl); - if( ser == null ) - return; - - final byte[] content = ser.toStream(iConfig, false); - - try { - channel.acquireWriteLock(); - try { - channel.writeByte(OChannelBinaryProtocol.PUSH_DATA); - channel.writeInt(Integer.MIN_VALUE); - channel.writeByte(OChannelBinaryProtocol.REQUEST_PUSH_DISTRIB_CONFIG); - channel.writeBytes(content); - channel.flush(); - - pushed.add(c.getRemoteAddress()); - OLogManager.instance().info(this, "Sent updated cluster configuration to the remote client %s", c.getRemoteAddress()); - - } finally { - channel.releaseWriteLock(); - } - } catch (IOException e) { - disconnect(c); - } catch (Exception e) { - OLogManager.instance().warn(this, "Cannot push cluster configuration to the client %s", e, c.getRemoteAddress()); - disconnect(c); - } - } - } - - public void shutdown() { - - final Iterator> iterator = connections.entrySet().iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - entry.getValue().protocol.sendShutdown(); - OCommandRequestText command = entry.getValue().data.command; - if (command != null && command.isIdempotent()) { - entry.getValue().protocol.interrupt(); - } else { - ONetworkProtocol protocol = entry.getValue().protocol; - if (protocol instanceof ONetworkProtocolBinary - && ((ONetworkProtocolBinary) protocol).getRequestType() == OChannelBinaryProtocol.REQUEST_SHUTDOWN) { - continue; - } - - try { - final Socket socket; - if (entry.getValue().protocol == null || entry.getValue().protocol.getChannel() == null) - socket = null; - else - socket = entry.getValue().protocol.getChannel().socket; - - if (socket != null && !socket.isClosed() && !socket.isInputShutdown()) { - try { - socket.shutdownInput(); - } catch (IOException e) { - OLogManager.instance().warn(this, "Error on closing connection of %s client during shutdown", e, - entry.getValue().getRemoteAddress()); - } - } - if (entry.getValue().protocol.isAlive()) - entry.getValue().protocol.join(); - } catch (InterruptedException e) { - // NOT Needed to handle - } - } - } - } -} diff --git a/All/Genesis-NP/Genesis#405/old/OClientConnectionManager.java b/All/Genesis-NP/Genesis#405/old/OClientConnectionManager.java deleted file mode 100755 index 4fd9685..0000000 --- a/All/Genesis-NP/Genesis#405/old/OClientConnectionManager.java +++ /dev/null @@ -1,368 +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.server; - -import java.io.IOException; -import java.net.Socket; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.profiler.OAbstractProfiler.OProfilerHookValue; -import com.orientechnologies.common.profiler.OProfilerMBean.METRIC_TYPE; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandRequestText; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; -import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol; -import com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary; - -public class OClientConnectionManager { - private static final OClientConnectionManager instance = new OClientConnectionManager(); - protected ConcurrentMap connections = new ConcurrentHashMap(); - protected AtomicInteger connectionSerial = new AtomicInteger(0); - - public OClientConnectionManager() { - final int delay = OGlobalConfiguration.SERVER_CHANNEL_CLEAN_DELAY.getValueAsInteger(); - - Orient.instance().scheduleTask(new TimerTask() { - - @Override - public void run() { - cleanExpiredConnections(); - } - } - - , delay, delay); - - Orient - .instance() - .getProfiler() - .registerHookValue("server.connections.actives", "Number of active network connections", METRIC_TYPE.COUNTER, - new OProfilerHookValue() { - public Object getValue() { - return connections.size(); - } - }); - } - - public void cleanExpiredConnections() { - final Iterator> iterator = connections.entrySet().iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - - final Socket socket; - if (entry.getValue().protocol == null || entry.getValue().protocol.getChannel() == null) - socket = null; - else - socket = entry.getValue().protocol.getChannel().socket; - - if (socket == null || socket.isClosed() || socket.isInputShutdown()) { - OLogManager.instance().debug(this, "[OClientConnectionManager] found and removed pending closed channel %d (%s)", - entry.getKey(), socket); - try { - OCommandRequestText command = entry.getValue().data.command; - if (command != null && command.isIdempotent()) { - entry.getValue().protocol.sendShutdown(); - entry.getValue().protocol.interrupt(); - } - entry.getValue().close(); - - } catch (Exception e) { - OLogManager.instance().error(this, "Error during close of connection for close channel", e); - } - iterator.remove(); - } - } - } - - public static OClientConnectionManager instance() { - return instance; - } - - /** - * Create a connection. - * - * @param iProtocol - * protocol which will be used by connection - * @return new connection - * @throws IOException - */ - public OClientConnection connect(final ONetworkProtocol iProtocol) throws IOException { - - final OClientConnection connection; - - connection = new OClientConnection(connectionSerial.incrementAndGet(), iProtocol); - - connections.put(connection.id, connection); - - OLogManager.instance().config(this, "Remote client connected from: " + connection); - - return connection; - } - - /** - * Retrieves the connection by id. - * - * @param iChannelId - * id of connection - * @return The connection if any, otherwise null - */ - public OClientConnection getConnection(final int iChannelId, ONetworkProtocol protocol) { - // SEARCH THE CONNECTION BY ID - OClientConnection connection = connections.get(iChannelId); - if (connection != null) - connection.protocol = protocol; - - return connection; - } - - /** - * Retrieves the connection by address/port. - * - * @param iAddress - * The address as string in the format address as format : - * @return The connection if any, otherwise null - */ - public OClientConnection getConnection(final String iAddress) { - for (OClientConnection conn : connections.values()) { - if (iAddress.equals(conn.getRemoteAddress())) - return conn; - } - return null; - } - - /** - * Disconnects and kill the associated network manager. - * - * @param iChannelId - * id of connection - */ - public void kill(final int iChannelId) { - kill(connections.get(iChannelId)); - } - - /** - * Disconnects and kill the associated network manager. - * - * @param connection - * connection to kill - */ - public void kill(final OClientConnection connection) { - if (connection != null) { - final ONetworkProtocol protocol = connection.protocol; - - try { - // INTERRUPT THE NEWTORK MANAGER TOO - protocol.interrupt(); - } catch (Exception e) { - } - - disconnect(connection); - - // KILL THE NETWORK MANAGER TOO - protocol.sendShutdown(); - } - } - - public boolean has(final int id) { - return connections.containsKey(id); - } - - /** - * Interrupt the associated network manager. - * - * @param iChannelId - * id of connection - */ - public void interrupt(final int iChannelId) { - final OClientConnection connection = connections.get(iChannelId); - if (connection != null) { - final ONetworkProtocol protocol = connection.protocol; - if (protocol != null) - // INTERRUPT THE NEWTORK MANAGER - protocol.interrupt(); - } - } - - /** - * Disconnects a client connections - * - * @param iChannelId - * id of connection - * @return true if was last one, otherwise false - */ - public boolean disconnect(final int iChannelId) { - OLogManager.instance().debug(this, "Disconnecting connection with id=%d", iChannelId); - - final OClientConnection connection = connections.remove(iChannelId); - - if (connection != null) { - connection.close(); - - // CHECK IF THERE ARE OTHER CONNECTIONS - for (Entry entry : connections.entrySet()) { - if (entry.getValue().getProtocol().equals(connection.getProtocol())) { - OLogManager.instance() - .debug(this, "Disconnected connection with id=%d but are present other active channels", iChannelId); - return false; - } - } - - OLogManager.instance().debug(this, "Disconnected connection with id=%d, no other active channels found", iChannelId); - return true; - } - - OLogManager.instance().debug(this, "Cannot find connection with id=%d", iChannelId); - return false; - } - - public void disconnect(final OClientConnection iConnection) { - OLogManager.instance().debug(this, "Disconnecting connection %s...", iConnection); - - iConnection.close(); - - int totalRemoved = 0; - for (Entry entry : new HashMap(connections).entrySet()) { - final OClientConnection conn = entry.getValue(); - if (conn != null && conn.equals(iConnection)) { - connections.remove(entry.getKey()); - totalRemoved++; - } - } - - OLogManager.instance().debug(this, "Disconnected connection %s found %d channels", iConnection, totalRemoved); - - } - - public List getConnections() { - return new ArrayList(connections.values()); - } - - public int getTotal() { - return connections.size(); - } - - /** - * Pushes the distributed configuration to all the connected clients. - */ - public void pushDistribCfg2Clients(final ODocument iConfig) { - if (iConfig == null) - return; - - final Set pushed = new HashSet(); - for (OClientConnection c : connections.values()) { - try { - final String remoteAddress = c.getRemoteAddress(); - if (pushed.contains(remoteAddress)) - // ALREADY SENT: JUMP IT - continue; - - } catch (Exception e) { - // SOCKET EXCEPTION SKIP IT - continue; - } - - if (!(c.protocol instanceof ONetworkProtocolBinary) && c.data.serializationImpl != null) - // INVOLVE ONLY BINAR PROTOCOLS - continue; - - final ONetworkProtocolBinary p = (ONetworkProtocolBinary) c.protocol; - final OChannelBinary channel = (OChannelBinary) p.getChannel(); - ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.data.serializationImpl); - final byte[] content = ser.toStream(iConfig, false); - - try { - channel.acquireWriteLock(); - try { - channel.writeByte(OChannelBinaryProtocol.PUSH_DATA); - channel.writeInt(Integer.MIN_VALUE); - channel.writeByte(OChannelBinaryProtocol.REQUEST_PUSH_DISTRIB_CONFIG); - channel.writeBytes(content); - channel.flush(); - - pushed.add(c.getRemoteAddress()); - OLogManager.instance().info(this, "Sent updated cluster configuration to the remote client %s", c.getRemoteAddress()); - - } finally { - channel.releaseWriteLock(); - } - } catch (IOException e) { - disconnect(c); - } catch (Exception e) { - OLogManager.instance().warn(this, "Cannot push cluster configuration to the client %s", e, c.getRemoteAddress()); - disconnect(c); - } - } - } - - public void shutdown() { - - final Iterator> iterator = connections.entrySet().iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - entry.getValue().protocol.sendShutdown(); - OCommandRequestText command = entry.getValue().data.command; - if (command != null && command.isIdempotent()) { - entry.getValue().protocol.interrupt(); - } else { - ONetworkProtocol protocol = entry.getValue().protocol; - if (protocol instanceof ONetworkProtocolBinary - && ((ONetworkProtocolBinary) protocol).getRequestType() == OChannelBinaryProtocol.REQUEST_SHUTDOWN) { - continue; - } - - try { - final Socket socket; - if (entry.getValue().protocol == null || entry.getValue().protocol.getChannel() == null) - socket = null; - else - socket = entry.getValue().protocol.getChannel().socket; - - if (socket != null && !socket.isClosed() && !socket.isInputShutdown()) { - try { - socket.shutdownInput(); - } catch (IOException e) { - OLogManager.instance().warn(this, "Error on closing connection of %s client during shutdown", e, - entry.getValue().getRemoteAddress()); - } - } - if (entry.getValue().protocol.isAlive()) - entry.getValue().protocol.join(); - } catch (InterruptedException e) { - // NOT Needed to handle - } - } - } - } -} diff --git a/All/Genesis-NP/Genesis#405/pair.info b/All/Genesis-NP/Genesis#405/pair.info deleted file mode 100755 index ced6c18..0000000 --- a/All/Genesis-NP/Genesis#405/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:405 -SATName:Genesis -modifiedFPath:server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java -comSha:51706fe132412faf15218a7f82ab080ac966363b -parentComSha:51706fe132412faf15218a7f82ab080ac966363b^1 -githubUrl:https://github.com/orientechnologies/orientdb -repoName:orientechnologies#orientdb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#406/comMsg.txt b/All/Genesis-NP/Genesis#406/comMsg.txt deleted file mode 100755 index 14cae9e..0000000 --- a/All/Genesis-NP/Genesis#406/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Distributed: fixed NPE diff --git a/All/Genesis-NP/Genesis#406/diff.diff b/All/Genesis-NP/Genesis#406/diff.diff deleted file mode 100755 index 603ea74..0000000 --- a/All/Genesis-NP/Genesis#406/diff.diff +++ /dev/null @@ -1,40 +0,0 @@ -diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java -index faab0ec..936c7b8 100755 ---- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java -+++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java -@@ -22,14 +21,0 @@ package com.orientechnologies.orient.server; --import java.io.IOException; --import java.net.Socket; --import java.util.ArrayList; --import java.util.HashMap; --import java.util.HashSet; --import java.util.Iterator; --import java.util.List; --import java.util.Map.Entry; --import java.util.Set; --import java.util.TimerTask; --import java.util.concurrent.ConcurrentHashMap; --import java.util.concurrent.ConcurrentMap; --import java.util.concurrent.atomic.AtomicInteger; -- -@@ -49,0 +36,14 @@ import com.orientechnologies.orient.server.network.protocol.binary.ONetworkProto -+import java.io.IOException; -+import java.net.Socket; -+import java.util.ArrayList; -+import java.util.HashMap; -+import java.util.HashSet; -+import java.util.Iterator; -+import java.util.List; -+import java.util.Map.Entry; -+import java.util.Set; -+import java.util.TimerTask; -+import java.util.concurrent.ConcurrentHashMap; -+import java.util.concurrent.ConcurrentMap; -+import java.util.concurrent.atomic.AtomicInteger; -+ -@@ -302 +302,4 @@ public class OClientConnectionManager { -- ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.data.serializationImpl); -+ final ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.data.serializationImpl); -+ if( ser == null ) -+ return; -+ diff --git a/All/Genesis-NP/Genesis#406/new/OClientConnectionManager.java b/All/Genesis-NP/Genesis#406/new/OClientConnectionManager.java deleted file mode 100755 index 936c7b8..0000000 --- a/All/Genesis-NP/Genesis#406/new/OClientConnectionManager.java +++ /dev/null @@ -1,371 +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.server; - -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.profiler.OAbstractProfiler.OProfilerHookValue; -import com.orientechnologies.common.profiler.OProfilerMBean.METRIC_TYPE; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandRequestText; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; -import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol; -import com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary; - -import java.io.IOException; -import java.net.Socket; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - -public class OClientConnectionManager { - private static final OClientConnectionManager instance = new OClientConnectionManager(); - protected ConcurrentMap connections = new ConcurrentHashMap(); - protected AtomicInteger connectionSerial = new AtomicInteger(0); - - public OClientConnectionManager() { - final int delay = OGlobalConfiguration.SERVER_CHANNEL_CLEAN_DELAY.getValueAsInteger(); - - Orient.instance().scheduleTask(new TimerTask() { - - @Override - public void run() { - cleanExpiredConnections(); - } - } - - , delay, delay); - - Orient - .instance() - .getProfiler() - .registerHookValue("server.connections.actives", "Number of active network connections", METRIC_TYPE.COUNTER, - new OProfilerHookValue() { - public Object getValue() { - return connections.size(); - } - }); - } - - public void cleanExpiredConnections() { - final Iterator> iterator = connections.entrySet().iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - - final Socket socket; - if (entry.getValue().protocol == null || entry.getValue().protocol.getChannel() == null) - socket = null; - else - socket = entry.getValue().protocol.getChannel().socket; - - if (socket == null || socket.isClosed() || socket.isInputShutdown()) { - OLogManager.instance().debug(this, "[OClientConnectionManager] found and removed pending closed channel %d (%s)", - entry.getKey(), socket); - try { - OCommandRequestText command = entry.getValue().data.command; - if (command != null && command.isIdempotent()) { - entry.getValue().protocol.sendShutdown(); - entry.getValue().protocol.interrupt(); - } - entry.getValue().close(); - - } catch (Exception e) { - OLogManager.instance().error(this, "Error during close of connection for close channel", e); - } - iterator.remove(); - } - } - } - - public static OClientConnectionManager instance() { - return instance; - } - - /** - * Create a connection. - * - * @param iProtocol - * protocol which will be used by connection - * @return new connection - * @throws IOException - */ - public OClientConnection connect(final ONetworkProtocol iProtocol) throws IOException { - - final OClientConnection connection; - - connection = new OClientConnection(connectionSerial.incrementAndGet(), iProtocol); - - connections.put(connection.id, connection); - - OLogManager.instance().config(this, "Remote client connected from: " + connection); - - return connection; - } - - /** - * Retrieves the connection by id. - * - * @param iChannelId - * id of connection - * @return The connection if any, otherwise null - */ - public OClientConnection getConnection(final int iChannelId, ONetworkProtocol protocol) { - // SEARCH THE CONNECTION BY ID - OClientConnection connection = connections.get(iChannelId); - if (connection != null) - connection.protocol = protocol; - - return connection; - } - - /** - * Retrieves the connection by address/port. - * - * @param iAddress - * The address as string in the format address as format : - * @return The connection if any, otherwise null - */ - public OClientConnection getConnection(final String iAddress) { - for (OClientConnection conn : connections.values()) { - if (iAddress.equals(conn.getRemoteAddress())) - return conn; - } - return null; - } - - /** - * Disconnects and kill the associated network manager. - * - * @param iChannelId - * id of connection - */ - public void kill(final int iChannelId) { - kill(connections.get(iChannelId)); - } - - /** - * Disconnects and kill the associated network manager. - * - * @param connection - * connection to kill - */ - public void kill(final OClientConnection connection) { - if (connection != null) { - final ONetworkProtocol protocol = connection.protocol; - - try { - // INTERRUPT THE NEWTORK MANAGER TOO - protocol.interrupt(); - } catch (Exception e) { - } - - disconnect(connection); - - // KILL THE NETWORK MANAGER TOO - protocol.sendShutdown(); - } - } - - public boolean has(final int id) { - return connections.containsKey(id); - } - - /** - * Interrupt the associated network manager. - * - * @param iChannelId - * id of connection - */ - public void interrupt(final int iChannelId) { - final OClientConnection connection = connections.get(iChannelId); - if (connection != null) { - final ONetworkProtocol protocol = connection.protocol; - if (protocol != null) - // INTERRUPT THE NEWTORK MANAGER - protocol.interrupt(); - } - } - - /** - * Disconnects a client connections - * - * @param iChannelId - * id of connection - * @return true if was last one, otherwise false - */ - public boolean disconnect(final int iChannelId) { - OLogManager.instance().debug(this, "Disconnecting connection with id=%d", iChannelId); - - final OClientConnection connection = connections.remove(iChannelId); - - if (connection != null) { - connection.close(); - - // CHECK IF THERE ARE OTHER CONNECTIONS - for (Entry entry : connections.entrySet()) { - if (entry.getValue().getProtocol().equals(connection.getProtocol())) { - OLogManager.instance() - .debug(this, "Disconnected connection with id=%d but are present other active channels", iChannelId); - return false; - } - } - - OLogManager.instance().debug(this, "Disconnected connection with id=%d, no other active channels found", iChannelId); - return true; - } - - OLogManager.instance().debug(this, "Cannot find connection with id=%d", iChannelId); - return false; - } - - public void disconnect(final OClientConnection iConnection) { - OLogManager.instance().debug(this, "Disconnecting connection %s...", iConnection); - - iConnection.close(); - - int totalRemoved = 0; - for (Entry entry : new HashMap(connections).entrySet()) { - final OClientConnection conn = entry.getValue(); - if (conn != null && conn.equals(iConnection)) { - connections.remove(entry.getKey()); - totalRemoved++; - } - } - - OLogManager.instance().debug(this, "Disconnected connection %s found %d channels", iConnection, totalRemoved); - - } - - public List getConnections() { - return new ArrayList(connections.values()); - } - - public int getTotal() { - return connections.size(); - } - - /** - * Pushes the distributed configuration to all the connected clients. - */ - public void pushDistribCfg2Clients(final ODocument iConfig) { - if (iConfig == null) - return; - - final Set pushed = new HashSet(); - for (OClientConnection c : connections.values()) { - try { - final String remoteAddress = c.getRemoteAddress(); - if (pushed.contains(remoteAddress)) - // ALREADY SENT: JUMP IT - continue; - - } catch (Exception e) { - // SOCKET EXCEPTION SKIP IT - continue; - } - - if (!(c.protocol instanceof ONetworkProtocolBinary) || c.data.serializationImpl == null) - // INVOLVE ONLY BINAR PROTOCOLS - continue; - - final ONetworkProtocolBinary p = (ONetworkProtocolBinary) c.protocol; - final OChannelBinary channel = (OChannelBinary) p.getChannel(); - final ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.data.serializationImpl); - if( ser == null ) - return; - - final byte[] content = ser.toStream(iConfig, false); - - try { - channel.acquireWriteLock(); - try { - channel.writeByte(OChannelBinaryProtocol.PUSH_DATA); - channel.writeInt(Integer.MIN_VALUE); - channel.writeByte(OChannelBinaryProtocol.REQUEST_PUSH_DISTRIB_CONFIG); - channel.writeBytes(content); - channel.flush(); - - pushed.add(c.getRemoteAddress()); - OLogManager.instance().info(this, "Sent updated cluster configuration to the remote client %s", c.getRemoteAddress()); - - } finally { - channel.releaseWriteLock(); - } - } catch (IOException e) { - disconnect(c); - } catch (Exception e) { - OLogManager.instance().warn(this, "Cannot push cluster configuration to the client %s", e, c.getRemoteAddress()); - disconnect(c); - } - } - } - - public void shutdown() { - - final Iterator> iterator = connections.entrySet().iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - entry.getValue().protocol.sendShutdown(); - OCommandRequestText command = entry.getValue().data.command; - if (command != null && command.isIdempotent()) { - entry.getValue().protocol.interrupt(); - } else { - ONetworkProtocol protocol = entry.getValue().protocol; - if (protocol instanceof ONetworkProtocolBinary - && ((ONetworkProtocolBinary) protocol).getRequestType() == OChannelBinaryProtocol.REQUEST_SHUTDOWN) { - continue; - } - - try { - final Socket socket; - if (entry.getValue().protocol == null || entry.getValue().protocol.getChannel() == null) - socket = null; - else - socket = entry.getValue().protocol.getChannel().socket; - - if (socket != null && !socket.isClosed() && !socket.isInputShutdown()) { - try { - socket.shutdownInput(); - } catch (IOException e) { - OLogManager.instance().warn(this, "Error on closing connection of %s client during shutdown", e, - entry.getValue().getRemoteAddress()); - } - } - if (entry.getValue().protocol.isAlive()) - entry.getValue().protocol.join(); - } catch (InterruptedException e) { - // NOT Needed to handle - } - } - } - } -} diff --git a/All/Genesis-NP/Genesis#406/old/OClientConnectionManager.java b/All/Genesis-NP/Genesis#406/old/OClientConnectionManager.java deleted file mode 100755 index faab0ec..0000000 --- a/All/Genesis-NP/Genesis#406/old/OClientConnectionManager.java +++ /dev/null @@ -1,368 +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.server; - -import java.io.IOException; -import java.net.Socket; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; -import java.util.TimerTask; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.profiler.OAbstractProfiler.OProfilerHookValue; -import com.orientechnologies.common.profiler.OProfilerMBean.METRIC_TYPE; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandRequestText; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer; -import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; -import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol; -import com.orientechnologies.orient.server.network.protocol.binary.ONetworkProtocolBinary; - -public class OClientConnectionManager { - private static final OClientConnectionManager instance = new OClientConnectionManager(); - protected ConcurrentMap connections = new ConcurrentHashMap(); - protected AtomicInteger connectionSerial = new AtomicInteger(0); - - public OClientConnectionManager() { - final int delay = OGlobalConfiguration.SERVER_CHANNEL_CLEAN_DELAY.getValueAsInteger(); - - Orient.instance().scheduleTask(new TimerTask() { - - @Override - public void run() { - cleanExpiredConnections(); - } - } - - , delay, delay); - - Orient - .instance() - .getProfiler() - .registerHookValue("server.connections.actives", "Number of active network connections", METRIC_TYPE.COUNTER, - new OProfilerHookValue() { - public Object getValue() { - return connections.size(); - } - }); - } - - public void cleanExpiredConnections() { - final Iterator> iterator = connections.entrySet().iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - - final Socket socket; - if (entry.getValue().protocol == null || entry.getValue().protocol.getChannel() == null) - socket = null; - else - socket = entry.getValue().protocol.getChannel().socket; - - if (socket == null || socket.isClosed() || socket.isInputShutdown()) { - OLogManager.instance().debug(this, "[OClientConnectionManager] found and removed pending closed channel %d (%s)", - entry.getKey(), socket); - try { - OCommandRequestText command = entry.getValue().data.command; - if (command != null && command.isIdempotent()) { - entry.getValue().protocol.sendShutdown(); - entry.getValue().protocol.interrupt(); - } - entry.getValue().close(); - - } catch (Exception e) { - OLogManager.instance().error(this, "Error during close of connection for close channel", e); - } - iterator.remove(); - } - } - } - - public static OClientConnectionManager instance() { - return instance; - } - - /** - * Create a connection. - * - * @param iProtocol - * protocol which will be used by connection - * @return new connection - * @throws IOException - */ - public OClientConnection connect(final ONetworkProtocol iProtocol) throws IOException { - - final OClientConnection connection; - - connection = new OClientConnection(connectionSerial.incrementAndGet(), iProtocol); - - connections.put(connection.id, connection); - - OLogManager.instance().config(this, "Remote client connected from: " + connection); - - return connection; - } - - /** - * Retrieves the connection by id. - * - * @param iChannelId - * id of connection - * @return The connection if any, otherwise null - */ - public OClientConnection getConnection(final int iChannelId, ONetworkProtocol protocol) { - // SEARCH THE CONNECTION BY ID - OClientConnection connection = connections.get(iChannelId); - if (connection != null) - connection.protocol = protocol; - - return connection; - } - - /** - * Retrieves the connection by address/port. - * - * @param iAddress - * The address as string in the format address as format : - * @return The connection if any, otherwise null - */ - public OClientConnection getConnection(final String iAddress) { - for (OClientConnection conn : connections.values()) { - if (iAddress.equals(conn.getRemoteAddress())) - return conn; - } - return null; - } - - /** - * Disconnects and kill the associated network manager. - * - * @param iChannelId - * id of connection - */ - public void kill(final int iChannelId) { - kill(connections.get(iChannelId)); - } - - /** - * Disconnects and kill the associated network manager. - * - * @param connection - * connection to kill - */ - public void kill(final OClientConnection connection) { - if (connection != null) { - final ONetworkProtocol protocol = connection.protocol; - - try { - // INTERRUPT THE NEWTORK MANAGER TOO - protocol.interrupt(); - } catch (Exception e) { - } - - disconnect(connection); - - // KILL THE NETWORK MANAGER TOO - protocol.sendShutdown(); - } - } - - public boolean has(final int id) { - return connections.containsKey(id); - } - - /** - * Interrupt the associated network manager. - * - * @param iChannelId - * id of connection - */ - public void interrupt(final int iChannelId) { - final OClientConnection connection = connections.get(iChannelId); - if (connection != null) { - final ONetworkProtocol protocol = connection.protocol; - if (protocol != null) - // INTERRUPT THE NEWTORK MANAGER - protocol.interrupt(); - } - } - - /** - * Disconnects a client connections - * - * @param iChannelId - * id of connection - * @return true if was last one, otherwise false - */ - public boolean disconnect(final int iChannelId) { - OLogManager.instance().debug(this, "Disconnecting connection with id=%d", iChannelId); - - final OClientConnection connection = connections.remove(iChannelId); - - if (connection != null) { - connection.close(); - - // CHECK IF THERE ARE OTHER CONNECTIONS - for (Entry entry : connections.entrySet()) { - if (entry.getValue().getProtocol().equals(connection.getProtocol())) { - OLogManager.instance() - .debug(this, "Disconnected connection with id=%d but are present other active channels", iChannelId); - return false; - } - } - - OLogManager.instance().debug(this, "Disconnected connection with id=%d, no other active channels found", iChannelId); - return true; - } - - OLogManager.instance().debug(this, "Cannot find connection with id=%d", iChannelId); - return false; - } - - public void disconnect(final OClientConnection iConnection) { - OLogManager.instance().debug(this, "Disconnecting connection %s...", iConnection); - - iConnection.close(); - - int totalRemoved = 0; - for (Entry entry : new HashMap(connections).entrySet()) { - final OClientConnection conn = entry.getValue(); - if (conn != null && conn.equals(iConnection)) { - connections.remove(entry.getKey()); - totalRemoved++; - } - } - - OLogManager.instance().debug(this, "Disconnected connection %s found %d channels", iConnection, totalRemoved); - - } - - public List getConnections() { - return new ArrayList(connections.values()); - } - - public int getTotal() { - return connections.size(); - } - - /** - * Pushes the distributed configuration to all the connected clients. - */ - public void pushDistribCfg2Clients(final ODocument iConfig) { - if (iConfig == null) - return; - - final Set pushed = new HashSet(); - for (OClientConnection c : connections.values()) { - try { - final String remoteAddress = c.getRemoteAddress(); - if (pushed.contains(remoteAddress)) - // ALREADY SENT: JUMP IT - continue; - - } catch (Exception e) { - // SOCKET EXCEPTION SKIP IT - continue; - } - - if (!(c.protocol instanceof ONetworkProtocolBinary) || c.data.serializationImpl == null) - // INVOLVE ONLY BINAR PROTOCOLS - continue; - - final ONetworkProtocolBinary p = (ONetworkProtocolBinary) c.protocol; - final OChannelBinary channel = (OChannelBinary) p.getChannel(); - ORecordSerializer ser = ORecordSerializerFactory.instance().getFormat(c.data.serializationImpl); - final byte[] content = ser.toStream(iConfig, false); - - try { - channel.acquireWriteLock(); - try { - channel.writeByte(OChannelBinaryProtocol.PUSH_DATA); - channel.writeInt(Integer.MIN_VALUE); - channel.writeByte(OChannelBinaryProtocol.REQUEST_PUSH_DISTRIB_CONFIG); - channel.writeBytes(content); - channel.flush(); - - pushed.add(c.getRemoteAddress()); - OLogManager.instance().info(this, "Sent updated cluster configuration to the remote client %s", c.getRemoteAddress()); - - } finally { - channel.releaseWriteLock(); - } - } catch (IOException e) { - disconnect(c); - } catch (Exception e) { - OLogManager.instance().warn(this, "Cannot push cluster configuration to the client %s", e, c.getRemoteAddress()); - disconnect(c); - } - } - } - - public void shutdown() { - - final Iterator> iterator = connections.entrySet().iterator(); - while (iterator.hasNext()) { - final Entry entry = iterator.next(); - entry.getValue().protocol.sendShutdown(); - OCommandRequestText command = entry.getValue().data.command; - if (command != null && command.isIdempotent()) { - entry.getValue().protocol.interrupt(); - } else { - ONetworkProtocol protocol = entry.getValue().protocol; - if (protocol instanceof ONetworkProtocolBinary - && ((ONetworkProtocolBinary) protocol).getRequestType() == OChannelBinaryProtocol.REQUEST_SHUTDOWN) { - continue; - } - - try { - final Socket socket; - if (entry.getValue().protocol == null || entry.getValue().protocol.getChannel() == null) - socket = null; - else - socket = entry.getValue().protocol.getChannel().socket; - - if (socket != null && !socket.isClosed() && !socket.isInputShutdown()) { - try { - socket.shutdownInput(); - } catch (IOException e) { - OLogManager.instance().warn(this, "Error on closing connection of %s client during shutdown", e, - entry.getValue().getRemoteAddress()); - } - } - if (entry.getValue().protocol.isAlive()) - entry.getValue().protocol.join(); - } catch (InterruptedException e) { - // NOT Needed to handle - } - } - } - } -} diff --git a/All/Genesis-NP/Genesis#406/pair.info b/All/Genesis-NP/Genesis#406/pair.info deleted file mode 100755 index 802de61..0000000 --- a/All/Genesis-NP/Genesis#406/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:406 -SATName:Genesis -modifiedFPath:server/src/main/java/com/orientechnologies/orient/server/OClientConnectionManager.java -comSha:ccfddfae6cae445197789e78383e74d91c118f92 -parentComSha:ccfddfae6cae445197789e78383e74d91c118f92^1 -githubUrl:https://github.com/orientechnologies/orientdb -repoName:orientechnologies#orientdb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#407/comMsg.txt b/All/Genesis-NP/Genesis#407/comMsg.txt deleted file mode 100755 index fb84413..0000000 --- a/All/Genesis-NP/Genesis#407/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Distributed: avoided NPE in case of records with no class diff --git a/All/Genesis-NP/Genesis#407/diff.diff b/All/Genesis-NP/Genesis#407/diff.diff deleted file mode 100755 index b5558da..0000000 --- a/All/Genesis-NP/Genesis#407/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java -index 3976e2d..fe1f7fa 100644 ---- a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java -+++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java -@@ -21,0 +22,4 @@ package com.orientechnologies.orient.server.distributed.task; -+import java.io.IOException; -+import java.io.ObjectInput; -+import java.io.ObjectOutput; -+ -@@ -38,4 +41,0 @@ import com.orientechnologies.orient.server.distributed.ODistributedServerManager --import java.io.IOException; --import java.io.ObjectInput; --import java.io.ObjectOutput; -- -@@ -69,0 +70 @@ public class OCreateRecordTask extends OAbstractRecordReplicatedTask { -+ if (clazz != null) diff --git a/All/Genesis-NP/Genesis#407/new/OCreateRecordTask.java b/All/Genesis-NP/Genesis#407/new/OCreateRecordTask.java deleted file mode 100755 index fe1f7fa..0000000 --- a/All/Genesis-NP/Genesis#407/new/OCreateRecordTask.java +++ /dev/null @@ -1,166 +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.server.distributed.task; - -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; - -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.OPlaceholder; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.ORecordInternal; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.version.ORecordVersion; -import com.orientechnologies.orient.server.OServer; -import com.orientechnologies.orient.server.distributed.ODistributedRequest; -import com.orientechnologies.orient.server.distributed.ODistributedServerLog; -import com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION; -import com.orientechnologies.orient.server.distributed.ODistributedServerManager; - -/** - * Distributed create record task used for synchronization. - * - * @author Luca Garulli (l.garulli--at--orientechnologies.com) - * - */ -public class OCreateRecordTask extends OAbstractRecordReplicatedTask { - public static final String SUFFIX_QUEUE_NAME = ".insert"; - private static final long serialVersionUID = 1L; - protected byte[] content; - protected byte recordType; - protected transient ORecord record; - - public OCreateRecordTask() { - } - - public OCreateRecordTask(final ORecordId iRid, final byte[] iContent, final ORecordVersion iVersion, final byte iRecordType) { - super(iRid, iVersion); - content = iContent; - recordType = iRecordType; - } - - public OCreateRecordTask(final ORecord record) { - this((ORecordId) record.getIdentity(), record.toStream(), record.getRecordVersion(), ORecordInternal.getRecordType(record)); - - if (record instanceof ODocument) { - // PRE-ASSIGN THE CLUSTER ID ON CALLER NODE - final OClass clazz = ((ODocument) record).getSchemaClass(); - if (clazz != null) - rid.clusterId = clazz.getClusterSelection().getCluster(clazz, (ODocument) record); - } - } - - @Override - public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database) - throws Exception { - ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "creating record %s/%s v.%s...", - database.getName(), rid.toString(), version.toString()); - - getRecord(); - - if (ORecordId.isPersistent(rid.getClusterPosition())) - // OVERWRITE RID TO BE TEMPORARY - ORecordInternal.setIdentity(record, rid.getClusterId(), ORID.CLUSTER_POS_INVALID); - - if (rid.getClusterId() != -1) - record.save(database.getClusterNameById(rid.getClusterId()), true); - else - record.save(); - - rid = (ORecordId) record.getIdentity(); - - ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, - "+-> assigned new rid %s/%s v.%d", database.getName(), rid.toString(), record.getVersion()); - - // TODO: IMPROVE TRANSPORT BY AVOIDING THE RECORD CONTENT, BUT JUST RID + VERSION - return new OPlaceholder(record); - } - - @Override - public QUORUM_TYPE getQuorumType() { - return QUORUM_TYPE.WRITE; - } - - @Override - public ODeleteRecordTask getFixTask(final ODistributedRequest iRequest, OAbstractRemoteTask iOriginalTask, final Object iBadResponse, final Object iGoodResponse) { - if (iBadResponse instanceof Throwable) - return null; - - final OPlaceholder badResult = (OPlaceholder) iBadResponse; - return new ODeleteRecordTask(new ORecordId(badResult.getIdentity()), badResult.getRecordVersion()).setDelayed(false); - } - - @Override - public ODeleteRecordTask getUndoTask(final ODistributedRequest iRequest, final Object iBadResponse) { - if (iBadResponse instanceof Throwable) - return null; - - final OPlaceholder badResult = (OPlaceholder) iBadResponse; - return new ODeleteRecordTask(new ORecordId(badResult.getIdentity()), badResult.getRecordVersion()).setDelayed(false); - } - - @Override - public void writeExternal(final ObjectOutput out) throws IOException { - super.writeExternal(out); - if (content == null) - out.writeInt(0); - else { - out.writeInt(content.length); - out.write(content); - } - out.write(recordType); - } - - @Override - public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { - super.readExternal(in); - final int contentSize = in.readInt(); - if (contentSize == 0) - content = null; - else { - content = new byte[contentSize]; - in.readFully(content); - } - recordType = in.readByte(); - } - - // @Override - // public String getQueueName(final String iOriginalQueueName) { - // return iOriginalQueueName + SUFFIX_QUEUE_NAME; - // } - - @Override - public String getName() { - return "record_create"; - } - - public ORecord getRecord() { - if (record == null) { - record = Orient.instance().getRecordFactoryManager().newInstance(recordType); - ORecordInternal.fill(record, rid, version, content, true); - } - return record; - } -} diff --git a/All/Genesis-NP/Genesis#407/old/OCreateRecordTask.java b/All/Genesis-NP/Genesis#407/old/OCreateRecordTask.java deleted file mode 100755 index 3976e2d..0000000 --- a/All/Genesis-NP/Genesis#407/old/OCreateRecordTask.java +++ /dev/null @@ -1,165 +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.server.distributed.task; - -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.OPlaceholder; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.ORecordInternal; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.version.ORecordVersion; -import com.orientechnologies.orient.server.OServer; -import com.orientechnologies.orient.server.distributed.ODistributedRequest; -import com.orientechnologies.orient.server.distributed.ODistributedServerLog; -import com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION; -import com.orientechnologies.orient.server.distributed.ODistributedServerManager; - -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; - -/** - * Distributed create record task used for synchronization. - * - * @author Luca Garulli (l.garulli--at--orientechnologies.com) - * - */ -public class OCreateRecordTask extends OAbstractRecordReplicatedTask { - public static final String SUFFIX_QUEUE_NAME = ".insert"; - private static final long serialVersionUID = 1L; - protected byte[] content; - protected byte recordType; - protected transient ORecord record; - - public OCreateRecordTask() { - } - - public OCreateRecordTask(final ORecordId iRid, final byte[] iContent, final ORecordVersion iVersion, final byte iRecordType) { - super(iRid, iVersion); - content = iContent; - recordType = iRecordType; - } - - public OCreateRecordTask(final ORecord record) { - this((ORecordId) record.getIdentity(), record.toStream(), record.getRecordVersion(), ORecordInternal.getRecordType(record)); - - if (record instanceof ODocument) { - // PRE-ASSIGN THE CLUSTER ID ON CALLER NODE - final OClass clazz = ((ODocument) record).getSchemaClass(); - rid.clusterId = clazz.getClusterSelection().getCluster(clazz, (ODocument) record); - } - } - - @Override - public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database) - throws Exception { - ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "creating record %s/%s v.%s...", - database.getName(), rid.toString(), version.toString()); - - getRecord(); - - if (ORecordId.isPersistent(rid.getClusterPosition())) - // OVERWRITE RID TO BE TEMPORARY - ORecordInternal.setIdentity(record, rid.getClusterId(), ORID.CLUSTER_POS_INVALID); - - if (rid.getClusterId() != -1) - record.save(database.getClusterNameById(rid.getClusterId()), true); - else - record.save(); - - rid = (ORecordId) record.getIdentity(); - - ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, - "+-> assigned new rid %s/%s v.%d", database.getName(), rid.toString(), record.getVersion()); - - // TODO: IMPROVE TRANSPORT BY AVOIDING THE RECORD CONTENT, BUT JUST RID + VERSION - return new OPlaceholder(record); - } - - @Override - public QUORUM_TYPE getQuorumType() { - return QUORUM_TYPE.WRITE; - } - - @Override - public ODeleteRecordTask getFixTask(final ODistributedRequest iRequest, OAbstractRemoteTask iOriginalTask, final Object iBadResponse, final Object iGoodResponse) { - if (iBadResponse instanceof Throwable) - return null; - - final OPlaceholder badResult = (OPlaceholder) iBadResponse; - return new ODeleteRecordTask(new ORecordId(badResult.getIdentity()), badResult.getRecordVersion()).setDelayed(false); - } - - @Override - public ODeleteRecordTask getUndoTask(final ODistributedRequest iRequest, final Object iBadResponse) { - if (iBadResponse instanceof Throwable) - return null; - - final OPlaceholder badResult = (OPlaceholder) iBadResponse; - return new ODeleteRecordTask(new ORecordId(badResult.getIdentity()), badResult.getRecordVersion()).setDelayed(false); - } - - @Override - public void writeExternal(final ObjectOutput out) throws IOException { - super.writeExternal(out); - if (content == null) - out.writeInt(0); - else { - out.writeInt(content.length); - out.write(content); - } - out.write(recordType); - } - - @Override - public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { - super.readExternal(in); - final int contentSize = in.readInt(); - if (contentSize == 0) - content = null; - else { - content = new byte[contentSize]; - in.readFully(content); - } - recordType = in.readByte(); - } - - // @Override - // public String getQueueName(final String iOriginalQueueName) { - // return iOriginalQueueName + SUFFIX_QUEUE_NAME; - // } - - @Override - public String getName() { - return "record_create"; - } - - public ORecord getRecord() { - if (record == null) { - record = Orient.instance().getRecordFactoryManager().newInstance(recordType); - ORecordInternal.fill(record, rid, version, content, true); - } - return record; - } -} diff --git a/All/Genesis-NP/Genesis#407/pair.info b/All/Genesis-NP/Genesis#407/pair.info deleted file mode 100755 index 0438654..0000000 --- a/All/Genesis-NP/Genesis#407/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:407 -SATName:Genesis -modifiedFPath:server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java -comSha:9fd093e09540df41a31997297417a0653db75a15 -parentComSha:9fd093e09540df41a31997297417a0653db75a15^1 -githubUrl:https://github.com/orientechnologies/orientdb -repoName:orientechnologies#orientdb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#408/comMsg.txt b/All/Genesis-NP/Genesis#408/comMsg.txt deleted file mode 100755 index fb84413..0000000 --- a/All/Genesis-NP/Genesis#408/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Distributed: avoided NPE in case of records with no class diff --git a/All/Genesis-NP/Genesis#408/diff.diff b/All/Genesis-NP/Genesis#408/diff.diff deleted file mode 100755 index 7aa389f..0000000 --- a/All/Genesis-NP/Genesis#408/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java -index 2b08923..908ba90 100644 ---- a/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java -+++ b/server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java -@@ -21,0 +22,4 @@ package com.orientechnologies.orient.server.distributed.task; -+import java.io.IOException; -+import java.io.ObjectInput; -+import java.io.ObjectOutput; -+ -@@ -38,4 +41,0 @@ import com.orientechnologies.orient.server.distributed.ODistributedServerManager --import java.io.IOException; --import java.io.ObjectInput; --import java.io.ObjectOutput; -- -@@ -69,0 +70 @@ public class OCreateRecordTask extends OAbstractRecordReplicatedTask { -+ if (clazz != null) diff --git a/All/Genesis-NP/Genesis#408/new/OCreateRecordTask.java b/All/Genesis-NP/Genesis#408/new/OCreateRecordTask.java deleted file mode 100755 index 908ba90..0000000 --- a/All/Genesis-NP/Genesis#408/new/OCreateRecordTask.java +++ /dev/null @@ -1,166 +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.server.distributed.task; - -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; - -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.OPlaceholder; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.ORecordInternal; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.version.ORecordVersion; -import com.orientechnologies.orient.server.OServer; -import com.orientechnologies.orient.server.distributed.ODistributedRequest; -import com.orientechnologies.orient.server.distributed.ODistributedServerLog; -import com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION; -import com.orientechnologies.orient.server.distributed.ODistributedServerManager; - -/** - * Distributed create record task used for synchronization. - * - * @author Luca Garulli (l.garulli--at--orientechnologies.com) - * - */ -public class OCreateRecordTask extends OAbstractRecordReplicatedTask { - public static final String SUFFIX_QUEUE_NAME = ".insert"; - private static final long serialVersionUID = 1L; - protected byte[] content; - protected byte recordType; - protected transient ORecord record; - - public OCreateRecordTask() { - } - - public OCreateRecordTask(final ORecordId iRid, final byte[] iContent, final ORecordVersion iVersion, final byte iRecordType) { - super(iRid, iVersion); - content = iContent; - recordType = iRecordType; - } - - public OCreateRecordTask(final ORecord record) { - this((ORecordId) record.getIdentity(), record.toStream(), record.getRecordVersion(), ORecordInternal.getRecordType(record)); - - if (record instanceof ODocument) { - // PRE-ASSIGN THE CLUSTER ID ON CALLER NODE - final OClass clazz = ((ODocument) record).getSchemaClass(); - if (clazz != null) - rid.clusterId = clazz.getClusterSelection().getCluster(clazz, (ODocument) record); - } - } - - @Override - public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database) - throws Exception { - ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "creating record %s/%s v.%s...", - database.getName(), rid.toString(), version.toString()); - - getRecord(); - - if (ORecordId.isPersistent(rid.getClusterPosition())) - // OVERWRITE RID TO BE TEMPORARY - ORecordInternal.setIdentity(record, rid.getClusterId(), ORID.CLUSTER_POS_INVALID); - - if (rid.getClusterId() != -1) - record.save(database.getClusterNameById(rid.getClusterId()), true); - else - record.save(); - - rid = (ORecordId) record.getIdentity(); - - ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, - "+-> assigned new rid %s/%s v.%d", database.getName(), rid.toString(), record.getVersion()); - - // TODO: IMPROVE TRANSPORT BY AVOIDING THE RECORD CONTENT, BUT JUST RID + VERSION - return new OPlaceholder(record); - } - - @Override - public QUORUM_TYPE getQuorumType() { - return QUORUM_TYPE.WRITE; - } - - @Override - public ODeleteRecordTask getFixTask(final ODistributedRequest iRequest, final Object iBadResponse, final Object iGoodResponse) { - if (iBadResponse instanceof Throwable) - return null; - - final OPlaceholder badResult = (OPlaceholder) iBadResponse; - return new ODeleteRecordTask(new ORecordId(badResult.getIdentity()), badResult.getRecordVersion()).setDelayed(false); - } - - @Override - public ODeleteRecordTask getUndoTask(final ODistributedRequest iRequest, final Object iBadResponse) { - if (iBadResponse instanceof Throwable) - return null; - - final OPlaceholder badResult = (OPlaceholder) iBadResponse; - return new ODeleteRecordTask(new ORecordId(badResult.getIdentity()), badResult.getRecordVersion()).setDelayed(false); - } - - @Override - public void writeExternal(final ObjectOutput out) throws IOException { - super.writeExternal(out); - if (content == null) - out.writeInt(0); - else { - out.writeInt(content.length); - out.write(content); - } - out.write(recordType); - } - - @Override - public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { - super.readExternal(in); - final int contentSize = in.readInt(); - if (contentSize == 0) - content = null; - else { - content = new byte[contentSize]; - in.readFully(content); - } - recordType = in.readByte(); - } - - // @Override - // public String getQueueName(final String iOriginalQueueName) { - // return iOriginalQueueName + SUFFIX_QUEUE_NAME; - // } - - @Override - public String getName() { - return "record_create"; - } - - public ORecord getRecord() { - if (record == null) { - record = Orient.instance().getRecordFactoryManager().newInstance(recordType); - ORecordInternal.fill(record, rid, version, content, true); - } - return record; - } -} diff --git a/All/Genesis-NP/Genesis#408/old/OCreateRecordTask.java b/All/Genesis-NP/Genesis#408/old/OCreateRecordTask.java deleted file mode 100755 index 2b08923..0000000 --- a/All/Genesis-NP/Genesis#408/old/OCreateRecordTask.java +++ /dev/null @@ -1,165 +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.server.distributed.task; - -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.OPlaceholder; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.metadata.schema.OClass; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.ORecordInternal; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.version.ORecordVersion; -import com.orientechnologies.orient.server.OServer; -import com.orientechnologies.orient.server.distributed.ODistributedRequest; -import com.orientechnologies.orient.server.distributed.ODistributedServerLog; -import com.orientechnologies.orient.server.distributed.ODistributedServerLog.DIRECTION; -import com.orientechnologies.orient.server.distributed.ODistributedServerManager; - -import java.io.IOException; -import java.io.ObjectInput; -import java.io.ObjectOutput; - -/** - * Distributed create record task used for synchronization. - * - * @author Luca Garulli (l.garulli--at--orientechnologies.com) - * - */ -public class OCreateRecordTask extends OAbstractRecordReplicatedTask { - public static final String SUFFIX_QUEUE_NAME = ".insert"; - private static final long serialVersionUID = 1L; - protected byte[] content; - protected byte recordType; - protected transient ORecord record; - - public OCreateRecordTask() { - } - - public OCreateRecordTask(final ORecordId iRid, final byte[] iContent, final ORecordVersion iVersion, final byte iRecordType) { - super(iRid, iVersion); - content = iContent; - recordType = iRecordType; - } - - public OCreateRecordTask(final ORecord record) { - this((ORecordId) record.getIdentity(), record.toStream(), record.getRecordVersion(), ORecordInternal.getRecordType(record)); - - if (record instanceof ODocument) { - // PRE-ASSIGN THE CLUSTER ID ON CALLER NODE - final OClass clazz = ((ODocument) record).getSchemaClass(); - rid.clusterId = clazz.getClusterSelection().getCluster(clazz, (ODocument) record); - } - } - - @Override - public Object execute(final OServer iServer, ODistributedServerManager iManager, final ODatabaseDocumentTx database) - throws Exception { - ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, "creating record %s/%s v.%s...", - database.getName(), rid.toString(), version.toString()); - - getRecord(); - - if (ORecordId.isPersistent(rid.getClusterPosition())) - // OVERWRITE RID TO BE TEMPORARY - ORecordInternal.setIdentity(record, rid.getClusterId(), ORID.CLUSTER_POS_INVALID); - - if (rid.getClusterId() != -1) - record.save(database.getClusterNameById(rid.getClusterId()), true); - else - record.save(); - - rid = (ORecordId) record.getIdentity(); - - ODistributedServerLog.debug(this, iManager.getLocalNodeName(), getNodeSource(), DIRECTION.IN, - "+-> assigned new rid %s/%s v.%d", database.getName(), rid.toString(), record.getVersion()); - - // TODO: IMPROVE TRANSPORT BY AVOIDING THE RECORD CONTENT, BUT JUST RID + VERSION - return new OPlaceholder(record); - } - - @Override - public QUORUM_TYPE getQuorumType() { - return QUORUM_TYPE.WRITE; - } - - @Override - public ODeleteRecordTask getFixTask(final ODistributedRequest iRequest, final Object iBadResponse, final Object iGoodResponse) { - if (iBadResponse instanceof Throwable) - return null; - - final OPlaceholder badResult = (OPlaceholder) iBadResponse; - return new ODeleteRecordTask(new ORecordId(badResult.getIdentity()), badResult.getRecordVersion()).setDelayed(false); - } - - @Override - public ODeleteRecordTask getUndoTask(final ODistributedRequest iRequest, final Object iBadResponse) { - if (iBadResponse instanceof Throwable) - return null; - - final OPlaceholder badResult = (OPlaceholder) iBadResponse; - return new ODeleteRecordTask(new ORecordId(badResult.getIdentity()), badResult.getRecordVersion()).setDelayed(false); - } - - @Override - public void writeExternal(final ObjectOutput out) throws IOException { - super.writeExternal(out); - if (content == null) - out.writeInt(0); - else { - out.writeInt(content.length); - out.write(content); - } - out.write(recordType); - } - - @Override - public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException { - super.readExternal(in); - final int contentSize = in.readInt(); - if (contentSize == 0) - content = null; - else { - content = new byte[contentSize]; - in.readFully(content); - } - recordType = in.readByte(); - } - - // @Override - // public String getQueueName(final String iOriginalQueueName) { - // return iOriginalQueueName + SUFFIX_QUEUE_NAME; - // } - - @Override - public String getName() { - return "record_create"; - } - - public ORecord getRecord() { - if (record == null) { - record = Orient.instance().getRecordFactoryManager().newInstance(recordType); - ORecordInternal.fill(record, rid, version, content, true); - } - return record; - } -} diff --git a/All/Genesis-NP/Genesis#408/pair.info b/All/Genesis-NP/Genesis#408/pair.info deleted file mode 100755 index e7be673..0000000 --- a/All/Genesis-NP/Genesis#408/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:408 -SATName:Genesis -modifiedFPath:server/src/main/java/com/orientechnologies/orient/server/distributed/task/OCreateRecordTask.java -comSha:9ce6c2e0e55283f086e5dfebc8ddfbf5724d15d9 -parentComSha:9ce6c2e0e55283f086e5dfebc8ddfbf5724d15d9^1 -githubUrl:https://github.com/orientechnologies/orientdb -repoName:orientechnologies#orientdb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#417/comMsg.txt b/All/Genesis-NP/Genesis#417/comMsg.txt deleted file mode 100755 index 9087c47..0000000 --- a/All/Genesis-NP/Genesis#417/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE reported by Steven Tomer on ML diff --git a/All/Genesis-NP/Genesis#417/diff.diff b/All/Genesis-NP/Genesis#417/diff.diff deleted file mode 100755 index 7ff39bb..0000000 --- a/All/Genesis-NP/Genesis#417/diff.diff +++ /dev/null @@ -1,21 +0,0 @@ -diff --git a/server/src/main/java/com/orientechnologies/orient/server/OClientConnection.java b/server/src/main/java/com/orientechnologies/orient/server/OClientConnection.java -index bef2dc0..6074e81 100644 ---- a/server/src/main/java/com/orientechnologies/orient/server/OClientConnection.java -+++ b/server/src/main/java/com/orientechnologies/orient/server/OClientConnection.java -@@ -18,3 +17,0 @@ package com.orientechnologies.orient.server; --import java.io.IOException; --import java.net.InetSocketAddress; -- -@@ -27,0 +25,3 @@ import com.orientechnologies.orient.server.network.protocol.ONetworkProtocolData -+import java.io.IOException; -+import java.net.InetSocketAddress; -+ -@@ -53,3 +53,5 @@ public class OClientConnection { -- return "OClientConnection [id=" + id + ", source=" -- + (protocol != null && protocol.getChannel() != null ? protocol.getChannel().socket.getRemoteSocketAddress() : "?") -- + ", since=" + since + "]"; -+ return "OClientConnection [id=" -+ + id -+ + ", source=" -+ + (protocol != null && protocol.getChannel() != null && protocol.getChannel().socket != null ? protocol.getChannel().socket -+ .getRemoteSocketAddress() : "?") + ", since=" + since + "]"; diff --git a/All/Genesis-NP/Genesis#417/new/OClientConnection.java b/All/Genesis-NP/Genesis#417/new/OClientConnection.java deleted file mode 100755 index 6074e81..0000000 --- a/All/Genesis-NP/Genesis#417/new/OClientConnection.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2010-2012 Luca Garulli (l.garulli--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. - */ -package com.orientechnologies.orient.server; - -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.raw.ODatabaseRaw; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary; -import com.orientechnologies.orient.server.config.OServerUserConfiguration; -import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol; -import com.orientechnologies.orient.server.network.protocol.ONetworkProtocolData; - -import java.io.IOException; -import java.net.InetSocketAddress; - -public class OClientConnection { - public final int id; - public final ONetworkProtocol protocol; - public final long since; - public volatile ODatabaseDocumentTx database; - public volatile ODatabaseRaw rawDatabase; - public volatile OServerUserConfiguration serverUser; - - public ONetworkProtocolData data = new ONetworkProtocolData(); - - public OClientConnection(final int iId, final ONetworkProtocol iProtocol) throws IOException { - this.id = iId; - this.protocol = iProtocol; - this.since = System.currentTimeMillis(); - } - - public void close() { - if (database != null) { - database.close(); - database = null; - } - } - - @Override - public String toString() { - return "OClientConnection [id=" - + id - + ", source=" - + (protocol != null && protocol.getChannel() != null && protocol.getChannel().socket != null ? protocol.getChannel().socket - .getRemoteSocketAddress() : "?") + ", since=" + since + "]"; - } - - /** - * Returns the remote network address in the format :. - */ - public String getRemoteAddress() { - final InetSocketAddress remoteAddress = (InetSocketAddress) protocol.getChannel().socket.getRemoteSocketAddress(); - return remoteAddress.getAddress().getHostAddress() + ":" + remoteAddress.getPort(); - } - - @Override - public int hashCode() { - return id; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final OClientConnection other = (OClientConnection) obj; - if (id != other.id) - return false; - return true; - } - - public OChannelBinary getChannel() { - return (OChannelBinary) protocol.getChannel(); - } - - public ONetworkProtocol getProtocol() { - return protocol; - } -} diff --git a/All/Genesis-NP/Genesis#417/old/OClientConnection.java b/All/Genesis-NP/Genesis#417/old/OClientConnection.java deleted file mode 100755 index bef2dc0..0000000 --- a/All/Genesis-NP/Genesis#417/old/OClientConnection.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright 2010-2012 Luca Garulli (l.garulli--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. - */ -package com.orientechnologies.orient.server; - -import java.io.IOException; -import java.net.InetSocketAddress; - -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.raw.ODatabaseRaw; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinary; -import com.orientechnologies.orient.server.config.OServerUserConfiguration; -import com.orientechnologies.orient.server.network.protocol.ONetworkProtocol; -import com.orientechnologies.orient.server.network.protocol.ONetworkProtocolData; - -public class OClientConnection { - public final int id; - public final ONetworkProtocol protocol; - public final long since; - public volatile ODatabaseDocumentTx database; - public volatile ODatabaseRaw rawDatabase; - public volatile OServerUserConfiguration serverUser; - - public ONetworkProtocolData data = new ONetworkProtocolData(); - - public OClientConnection(final int iId, final ONetworkProtocol iProtocol) throws IOException { - this.id = iId; - this.protocol = iProtocol; - this.since = System.currentTimeMillis(); - } - - public void close() { - if (database != null) { - database.close(); - database = null; - } - } - - @Override - public String toString() { - return "OClientConnection [id=" + id + ", source=" - + (protocol != null && protocol.getChannel() != null ? protocol.getChannel().socket.getRemoteSocketAddress() : "?") - + ", since=" + since + "]"; - } - - /** - * Returns the remote network address in the format :. - */ - public String getRemoteAddress() { - final InetSocketAddress remoteAddress = (InetSocketAddress) protocol.getChannel().socket.getRemoteSocketAddress(); - return remoteAddress.getAddress().getHostAddress() + ":" + remoteAddress.getPort(); - } - - @Override - public int hashCode() { - return id; - } - - @Override - public boolean equals(final Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - final OClientConnection other = (OClientConnection) obj; - if (id != other.id) - return false; - return true; - } - - public OChannelBinary getChannel() { - return (OChannelBinary) protocol.getChannel(); - } - - public ONetworkProtocol getProtocol() { - return protocol; - } -} diff --git a/All/Genesis-NP/Genesis#417/pair.info b/All/Genesis-NP/Genesis#417/pair.info deleted file mode 100755 index a33ec17..0000000 --- a/All/Genesis-NP/Genesis#417/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:417 -SATName:Genesis -modifiedFPath:server/src/main/java/com/orientechnologies/orient/server/OClientConnection.java -comSha:f799df224d4ecb749cd058713b74aab5e7bf8c23 -parentComSha:f799df224d4ecb749cd058713b74aab5e7bf8c23^1 -githubUrl:https://github.com/orientechnologies/orientdb -repoName:orientechnologies#orientdb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#418/comMsg.txt b/All/Genesis-NP/Genesis#418/comMsg.txt deleted file mode 100755 index 58a3ed3..0000000 --- a/All/Genesis-NP/Genesis#418/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix possible NPE diff --git a/All/Genesis-NP/Genesis#418/diff.diff b/All/Genesis-NP/Genesis#418/diff.diff deleted file mode 100755 index ab20a60..0000000 --- a/All/Genesis-NP/Genesis#418/diff.diff +++ /dev/null @@ -1,34 +0,0 @@ -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 2b25487..229a233 100755 ---- 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 -@@ -17,0 +18,12 @@ package com.orientechnologies.orient.server.network.protocol.binary; -+import java.io.IOException; -+import java.io.ObjectOutputStream; -+import java.net.Socket; -+import java.net.SocketException; -+import java.util.Collection; -+import java.util.HashSet; -+import java.util.List; -+import java.util.Map; -+import java.util.Map.Entry; -+import java.util.Set; -+import java.util.UUID; -+ -@@ -86,12 +97,0 @@ import com.orientechnologies.orient.server.tx.OTransactionOptimisticProxy; --import java.io.IOException; --import java.io.ObjectOutputStream; --import java.net.Socket; --import java.net.SocketException; --import java.util.Collection; --import java.util.HashSet; --import java.util.List; --import java.util.Map; --import java.util.Map.Entry; --import java.util.Set; --import java.util.UUID; -- -@@ -1937 +1936,0 @@ public class ONetworkProtocolBinary extends OBinaryNetworkProtocolAbstract { -- } -@@ -1939,0 +1939 @@ public class ONetworkProtocolBinary extends OBinaryNetworkProtocolAbstract { -+ } diff --git a/All/Genesis-NP/Genesis#418/new/ONetworkProtocolBinary.java b/All/Genesis-NP/Genesis#418/new/ONetworkProtocolBinary.java deleted file mode 100755 index 229a233..0000000 --- a/All/Genesis-NP/Genesis#418/new/ONetworkProtocolBinary.java +++ /dev/null @@ -1,1985 +0,0 @@ -/* - * Copyright 2010-2012 Luca Garulli (l.garulli--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. - */ -package com.orientechnologies.orient.server.network.protocol.binary; - -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.net.Socket; -import java.net.SocketException; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.UUID; - -import com.orientechnologies.common.collection.OMultiValue; -import com.orientechnologies.common.concur.lock.OLockException; -import com.orientechnologies.common.io.OIOException; -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.serialization.types.OBinarySerializer; -import com.orientechnologies.common.serialization.types.OByteSerializer; -import com.orientechnologies.common.serialization.types.OIntegerSerializer; -import com.orientechnologies.common.serialization.types.ONullSerializer; -import com.orientechnologies.orient.client.remote.OCollectionNetworkSerializer; -import com.orientechnologies.orient.client.remote.OEngineRemote; -import com.orientechnologies.orient.core.OConstants; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandRequestText; -import com.orientechnologies.orient.core.config.OContextConfiguration; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.db.ODatabase; -import com.orientechnologies.orient.core.db.ODatabaseComplex; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OBonsaiCollectionPointer; -import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeCollectionManager; -import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeRidBag; -import com.orientechnologies.orient.core.exception.OConfigurationException; -import com.orientechnologies.orient.core.exception.ODatabaseException; -import com.orientechnologies.orient.core.exception.OSecurityAccessException; -import com.orientechnologies.orient.core.exception.OSecurityException; -import com.orientechnologies.orient.core.exception.OStorageException; -import com.orientechnologies.orient.core.exception.OTransactionAbortedException; -import com.orientechnologies.orient.core.fetch.OFetchContext; -import com.orientechnologies.orient.core.fetch.OFetchHelper; -import com.orientechnologies.orient.core.fetch.OFetchListener; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchContext; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchListener; -import com.orientechnologies.orient.core.id.OClusterPosition; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.index.sbtree.OTreeInternal; -import com.orientechnologies.orient.core.index.sbtreebonsai.local.OSBTreeBonsai; -import com.orientechnologies.orient.core.metadata.schema.OType; -import com.orientechnologies.orient.core.metadata.security.OUser; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.ORecordInternal; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.record.impl.ORecordBytes; -import com.orientechnologies.orient.core.serialization.OMemoryStream; -import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerStringAbstract; -import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerAnyStreamable; -import com.orientechnologies.orient.core.storage.OCluster; -import com.orientechnologies.orient.core.storage.OPhysicalPosition; -import com.orientechnologies.orient.core.storage.ORecordMetadata; -import com.orientechnologies.orient.core.storage.OStorage; -import com.orientechnologies.orient.core.storage.OStorageProxy; -import com.orientechnologies.orient.core.storage.impl.memory.OStorageMemory; -import com.orientechnologies.orient.core.version.ORecordVersion; -import com.orientechnologies.orient.core.version.OVersionFactory; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryServer; -import com.orientechnologies.orient.server.OClientConnection; -import com.orientechnologies.orient.server.OClientConnectionManager; -import com.orientechnologies.orient.server.OServer; -import com.orientechnologies.orient.server.distributed.ODistributedServerManager; -import com.orientechnologies.orient.server.plugin.OServerPlugin; -import com.orientechnologies.orient.server.plugin.OServerPluginHelper; -import com.orientechnologies.orient.server.tx.OTransactionOptimisticProxy; - -public class ONetworkProtocolBinary extends OBinaryNetworkProtocolAbstract { - protected OClientConnection connection; - protected OUser account; - - private String dbType; - - public ONetworkProtocolBinary() { - super("OrientDB <- BinaryClient/?"); - } - - public ONetworkProtocolBinary(final String iThreadName) { - super(iThreadName); - } - - @Override - public void config(final OServer iServer, final Socket iSocket, final OContextConfiguration iConfig, - final List iStatelessCommands, List iStatefulCommands) throws IOException { - // CREATE THE CLIENT CONNECTION - connection = OClientConnectionManager.instance().connect(this); - - super.config(iServer, iSocket, iConfig, iStatelessCommands, iStatefulCommands); - - // SEND PROTOCOL VERSION - channel.writeShort((short) OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION); - - channel.flush(); - start(); - - setName("OrientDB <- BinaryClient (" + iSocket.getRemoteSocketAddress() + ")"); - } - - @Override - public int getVersion() { - return OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION; - } - - @Override - public void startup() { - super.startup(); - OServerPluginHelper.invokeHandlerCallbackOnClientConnection(server, connection); - } - - @Override - public void shutdown() { - sendShutdown(); - super.shutdown(); - - if (connection == null) - return; - - OServerPluginHelper.invokeHandlerCallbackOnClientDisconnection(server, connection); - - OClientConnectionManager.instance().disconnect(connection); - } - - public String getType() { - return "binary"; - } - - @Override - protected void onBeforeRequest() throws IOException { - waitNodeIsOnline(); - - connection = OClientConnectionManager.instance().getConnection(clientTxId); - - if (clientTxId < 0) { - short protocolId = 0; - - if (connection != null) - protocolId = connection.data.protocolVersion; - - connection = OClientConnectionManager.instance().connect(this); - - if (connection != null) - connection.data.protocolVersion = protocolId; - } - - if (connection != null) { - ODatabaseRecordThreadLocal.INSTANCE.set(connection.database); - if (connection.database != null) { - connection.data.lastDatabase = connection.database.getName(); - connection.data.lastUser = connection.database.getUser() != null ? connection.database.getUser().getName() : null; - } else { - connection.data.lastDatabase = null; - connection.data.lastUser = null; - } - - ++connection.data.totalRequests; - setDataCommandInfo("Listening"); - connection.data.commandDetail = "-"; - connection.data.lastCommandReceived = System.currentTimeMillis(); - } else { - ODatabaseRecordThreadLocal.INSTANCE.remove(); - if (requestType != OChannelBinaryProtocol.REQUEST_DB_CLOSE && requestType != OChannelBinaryProtocol.REQUEST_SHUTDOWN) { - OLogManager.instance().debug(this, "Found unknown session %d, shutdown current connection", clientTxId); - shutdown(); - throw new OIOException("Found unknown session " + clientTxId); - } - } - - OServerPluginHelper.invokeHandlerCallbackOnBeforeClientRequest(server, connection, (byte) requestType); - } - - @Override - protected void onAfterRequest() throws IOException { - OServerPluginHelper.invokeHandlerCallbackOnAfterClientRequest(server, connection, (byte) requestType); - - if (connection != null) { - if (connection.database != null) - if (!connection.database.isClosed()) - connection.database.getLevel1Cache().clear(); - - connection.data.lastCommandExecutionTime = System.currentTimeMillis() - connection.data.lastCommandReceived; - connection.data.totalCommandExecutionTime += connection.data.lastCommandExecutionTime; - - connection.data.lastCommandInfo = connection.data.commandInfo; - connection.data.lastCommandDetail = connection.data.commandDetail; - - setDataCommandInfo("Listening"); - connection.data.commandDetail = "-"; - } - } - - protected boolean executeRequest() throws IOException { - try { - switch (requestType) { - - case OChannelBinaryProtocol.REQUEST_SHUTDOWN: - shutdownConnection(); - break; - - case OChannelBinaryProtocol.REQUEST_CONNECT: - connect(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_LIST: - listDatabases(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_OPEN: - openDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_RELOAD: - reloadDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_CREATE: - createDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_CLOSE: - closeDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_EXIST: - existsDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_DROP: - dropDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_SIZE: - sizeDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_COUNTRECORDS: - countDatabaseRecords(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_COPY: - copyDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_REPLICATION: - replicationDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_CLUSTER: - distributedCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_DATASEGMENT_ADD: - addDataSegment(); - break; - - case OChannelBinaryProtocol.REQUEST_DATASEGMENT_DROP: - dropDataSegment(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_COUNT: - countClusters(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_DATARANGE: - rangeCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_ADD: - addCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_DROP: - removeCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_METADATA: - readRecordMetadata(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_LOAD: - readRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_CREATE: - createRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_UPDATE: - updateRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_DELETE: - deleteRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_HIDE: - hideRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_POSITIONS_HIGHER: - higherPositions(); - break; - - case OChannelBinaryProtocol.REQUEST_POSITIONS_CEILING: - ceilingPositions(); - break; - - case OChannelBinaryProtocol.REQUEST_POSITIONS_LOWER: - lowerPositions(); - break; - - case OChannelBinaryProtocol.REQUEST_POSITIONS_FLOOR: - floorPositions(); - break; - - case OChannelBinaryProtocol.REQUEST_COUNT: - throw new UnsupportedOperationException("Operation OChannelBinaryProtocol.REQUEST_COUNT has been deprecated"); - - case OChannelBinaryProtocol.REQUEST_COMMAND: - command(); - break; - - case OChannelBinaryProtocol.REQUEST_TX_COMMIT: - commit(); - break; - - case OChannelBinaryProtocol.REQUEST_CONFIG_GET: - configGet(); - break; - - case OChannelBinaryProtocol.REQUEST_CONFIG_SET: - configSet(); - break; - - case OChannelBinaryProtocol.REQUEST_CONFIG_LIST: - configList(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_FREEZE: - freezeDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_RELEASE: - releaseDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE: - freezeCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE: - releaseCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT: - cleanOutRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_CREATE_SBTREE_BONSAI: - createSBTreeBonsai(); - break; - - case OChannelBinaryProtocol.REQUEST_SBTREE_BONSAI_GET: - sbTreeBonsaiGet(); - break; - - case OChannelBinaryProtocol.REQUEST_SBTREE_BONSAI_FIRST_KEY: - sbTreeBonsaiFirstKey(); - break; - - case OChannelBinaryProtocol.REQUEST_SBTREE_BONSAI_GET_ENTRIES_MAJOR: - sbTreeBonsaiGetEntriesMajor(); - break; - - case OChannelBinaryProtocol.REQUEST_RIDBAG_GET_SIZE: - ridBagSize(); - break; - - default: - setDataCommandInfo("Command not supported"); - return false; - } - - return true; - } catch (RuntimeException e) { - if (connection != null && connection.database != null) { - final OSBTreeCollectionManager collectionManager = connection.database.getSbTreeCollectionManager(); - if (collectionManager != null) - collectionManager.clearChangedIds(); - } - - throw e; - } - } - - protected void checkServerAccess(final String iResource) { - if (connection.serverUser == null) - throw new OSecurityAccessException("Server user not authenticated."); - - if (!server.authenticate(connection.serverUser.name, null, iResource)) - throw new OSecurityAccessException("User '" + connection.serverUser.name + "' cannot access to the resource [" + iResource - + "]. Use another server user or change permission in the file config/orientdb-server-config.xml"); - } - - protected ODatabaseComplex openDatabase(final ODatabaseComplex database, final String iUser, final String iPassword) { - - if (database.isClosed()) - if (database.getStorage() instanceof OStorageMemory && !database.exists()) - database.create(); - else { - try { - database.open(iUser, iPassword); - } catch (OSecurityException e) { - // TRY WITH SERVER'S USER - try { - connection.serverUser = server.serverLogin(iUser, iPassword, "database.passthrough"); - } catch (OSecurityException ex) { - throw e; - } - - // SERVER AUTHENTICATED, BYPASS SECURITY - database.setProperty(ODatabase.OPTIONS.SECURITY.toString(), Boolean.FALSE); - database.open(iUser, iPassword); - } - } - - return database; - } - - protected void addDataSegment() throws IOException { - setDataCommandInfo("Add data segment"); - - if (!isConnectionAlive()) - return; - - final String name = channel.readString(); - final String location = channel.readString(); - - final int num = connection.database.addDataSegment(name, location); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeInt(num); - } finally { - endResponse(); - } - } - - protected void dropDataSegment() throws IOException { - setDataCommandInfo("Drop data segment"); - - if (!isConnectionAlive()) - return; - - final String name = channel.readString(); - - boolean result = connection.database.dropDataSegment(name); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) (result ? 1 : 0)); - } finally { - endResponse(); - } - } - - protected void removeCluster() throws IOException { - setDataCommandInfo("Remove cluster"); - - if (!isConnectionAlive()) - return; - - final int id = channel.readShort(); - - final String clusterName = connection.database.getClusterNameById(id); - if (clusterName == null) - throw new IllegalArgumentException("Cluster " + id - + " doesn't exist anymore. Refresh the db structure or just reconnect to the database"); - - boolean result = connection.database.dropCluster(clusterName, true); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) (result ? 1 : 0)); - } finally { - endResponse(); - } - } - - protected void addCluster() throws IOException { - setDataCommandInfo("Add cluster"); - - if (!isConnectionAlive()) - return; - - final String type = channel.readString(); - final String name = channel.readString(); - int clusterId = -1; - - final String location; - if (connection.data.protocolVersion >= 10 || type.equalsIgnoreCase("PHYSICAL")) - location = channel.readString(); - else - location = null; - - final String dataSegmentName; - if (connection.data.protocolVersion >= 10) - dataSegmentName = channel.readString(); - else { - channel.readInt(); // OLD INIT SIZE, NOT MORE USED - dataSegmentName = null; - } - - if (connection.data.protocolVersion >= 18) - clusterId = channel.readShort(); - - Object[] params = null; - - final int num; - - if (clusterId < 0) - num = connection.database.addCluster(type, name, location, dataSegmentName, params); - else - num = connection.database.addCluster(type, name, clusterId, location, dataSegmentName, params); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeShort((short) num); - } finally { - endResponse(); - } - } - - protected void rangeCluster() throws IOException { - setDataCommandInfo("Get the begin/end range of data in cluster"); - - if (!isConnectionAlive()) - return; - - OClusterPosition[] pos = connection.database.getStorage().getClusterDataRange(channel.readShort()); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeClusterPosition(pos[0]); - channel.writeClusterPosition(pos[1]); - } finally { - endResponse(); - } - } - - protected void countClusters() throws IOException { - setDataCommandInfo("Count cluster elements"); - - if (!isConnectionAlive()) - return; - - int[] clusterIds = new int[channel.readShort()]; - for (int i = 0; i < clusterIds.length; ++i) - clusterIds[i] = channel.readShort(); - - boolean countTombstones = false; - if (connection.data.protocolVersion >= 13) - countTombstones = channel.readByte() > 0; - - final long count = connection.database.countClusterElements(clusterIds, countTombstones); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeLong(count); - } finally { - endResponse(); - } - } - - protected void reloadDatabase() throws IOException { - setDataCommandInfo("Reload database information"); - - if (!isConnectionAlive()) - return; - - beginResponse(); - try { - sendOk(clientTxId); - - sendDatabaseInformation(); - - } finally { - endResponse(); - } - } - - protected void openDatabase() throws IOException { - setDataCommandInfo("Open database"); - - readConnectionData(); - - final String dbURL = channel.readString(); - - dbType = ODatabaseDocument.TYPE; - if (connection.data.protocolVersion >= 8) - // READ DB-TYPE FROM THE CLIENT - dbType = channel.readString(); - - final String user = channel.readString(); - final String passwd = channel.readString(); - - connection.database = (ODatabaseDocumentTx) server.openDatabase(dbType, dbURL, user, passwd); - connection.rawDatabase = ((ODatabaseComplex) connection.database.getUnderlying()).getUnderlying(); - - if (connection.database.getStorage() instanceof OStorageProxy && !loadUserFromSchema(user, passwd)) { - sendError(clientTxId, new OSecurityAccessException(connection.database.getName(), - "User or password not valid for database: '" + connection.database.getName() + "'")); - } else { - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeInt(connection.id); - - sendDatabaseInformation(); - - final OServerPlugin plugin = server.getPlugin("cluster"); - ODocument distributedCfg = null; - if (plugin != null && plugin instanceof ODistributedServerManager) - distributedCfg = ((ODistributedServerManager) plugin).getClusterConfiguration(); - - channel.writeBytes(distributedCfg != null ? distributedCfg.toStream() : null); - - if (connection.data.protocolVersion >= 14) - channel.writeString(OConstants.getVersion()); - } finally { - endResponse(); - } - } - } - - protected void connect() throws IOException { - setDataCommandInfo("Connect"); - - readConnectionData(); - - connection.serverUser = server.serverLogin(channel.readString(), channel.readString(), "connect"); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeInt(connection.id); - } finally { - endResponse(); - } - } - - protected void shutdownConnection() throws IOException { - setDataCommandInfo("Shutdowning"); - - OLogManager.instance().info(this, "Received shutdown command from the remote client %s:%d", channel.socket.getInetAddress(), - channel.socket.getPort()); - - final String user = channel.readString(); - final String passwd = channel.readString(); - - if (server.authenticate(user, passwd, "shutdown")) { - OLogManager.instance().info(this, "Remote client %s:%d authenticated. Starting shutdown of server...", - channel.socket.getInetAddress(), channel.socket.getPort()); - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - channel.close(); - server.shutdown(); - System.exit(0); - } - - OLogManager.instance().error(this, "Authentication error of remote client %s:%d: shutdown is aborted.", - channel.socket.getInetAddress(), channel.socket.getPort()); - - sendError(clientTxId, new OSecurityAccessException("Invalid user/password to shutdown the server")); - } - - protected void copyDatabase() throws IOException { - setDataCommandInfo("Copy the database to a remote server"); - - final String dbUrl = channel.readString(); - final String dbUser = channel.readString(); - final String dbPassword = channel.readString(); - final String remoteServerName = channel.readString(); - final String remoteServerEngine = channel.readString(); - - checkServerAccess("database.copy"); - - final ODatabaseDocumentTx db = (ODatabaseDocumentTx) server.openDatabase(ODatabaseDocument.TYPE, dbUrl, dbUser, dbPassword); - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void replicationDatabase() throws IOException { - setDataCommandInfo("Replication command"); - - final ODocument request = new ODocument(channel.readBytes()); - - final ODistributedServerManager dManager = server.getDistributedManager(); - if (dManager == null) - throw new OConfigurationException("No distributed manager configured"); - - final String operation = request.field("operation"); - - ODocument response = null; - - if (operation.equals("start")) { - checkServerAccess("server.replication.start"); - - } else if (operation.equals("stop")) { - checkServerAccess("server.replication.stop"); - - } else if (operation.equals("config")) { - checkServerAccess("server.replication.config"); - - response = new ODocument().fromJSON(dManager.getDatabaseConfiguration((String) request.field("db")).serialize() - .toJSON("prettyPrint")); - - } - - sendResponse(response); - - } - - protected void distributedCluster() throws IOException { - setDataCommandInfo("Cluster status"); - - final ODocument req = new ODocument(channel.readBytes()); - - ODocument response = null; - - final String operation = req.field("operation"); - if (operation == null) - throw new IllegalArgumentException("Cluster operation is null"); - - if (operation.equals("status")) { - final OServerPlugin plugin = server.getPlugin("cluster"); - if (plugin != null && plugin instanceof ODistributedServerManager) - response = ((ODistributedServerManager) plugin).getClusterConfiguration(); - } else - throw new IllegalArgumentException("Cluster operation '" + operation + "' is not supported"); - - sendResponse(response); - } - - protected void countDatabaseRecords() throws IOException { - setDataCommandInfo("Database count records"); - - if (!isConnectionAlive()) - return; - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeLong(connection.database.getStorage().countRecords()); - } finally { - endResponse(); - } - } - - protected void sizeDatabase() throws IOException { - setDataCommandInfo("Database size"); - - if (!isConnectionAlive()) - return; - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeLong(connection.database.getStorage().getSize()); - } finally { - endResponse(); - } - } - - protected void dropDatabase() throws IOException { - setDataCommandInfo("Drop database"); - String dbName = channel.readString(); - - String storageType; - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - checkServerAccess("database.delete"); - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Dropped database '%s'", connection.database.getName()); - - if (connection.database.isClosed()) - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - - connection.database.drop(); - connection.close(); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void existsDatabase() throws IOException { - setDataCommandInfo("Exists database"); - final String dbName = channel.readString(); - final String storageType; - - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - checkServerAccess("database.exists"); - - if (storageType != null) - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - else { - // CHECK AGAINST ALL THE ENGINE TYPES, BUT REMOTE - for (String engine : Orient.instance().getEngines()) { - if (!engine.equalsIgnoreCase(OEngineRemote.NAME)) { - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, engine); - if (connection.database.exists()) - // FOUND - break; - - // NOT FOUND: ASSURE TO UNREGISTER IT TO AVOID CACHING - Orient.instance().unregisterStorage(connection.database.getStorage()); - } - } - } - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) (connection.database.exists() ? 1 : 0)); - } finally { - endResponse(); - } - } - - protected void createDatabase() throws IOException { - setDataCommandInfo("Create database"); - - String dbName = channel.readString(); - String dbType = ODatabaseDocument.TYPE; - if (connection.data.protocolVersion >= 8) - // READ DB-TYPE FROM THE CLIENT - dbType = channel.readString(); - String storageType = channel.readString(); - - checkServerAccess("database.create"); - checkStorageExistence(dbName); - connection.database = getDatabaseInstance(dbName, dbType, storageType); - createDatabase(connection.database, null, null); - connection.rawDatabase = (((ODatabaseComplex) connection.database.getUnderlying()).getUnderlying()); - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void closeDatabase() throws IOException { - setDataCommandInfo("Close Database"); - - if (connection != null) { - if (connection.data.protocolVersion > 0 && connection.data.protocolVersion < 9) - // OLD CLIENTS WAIT FOR A OK - sendOk(clientTxId); - - if (OClientConnectionManager.instance().disconnect(connection.id)) - sendShutdown(); - } - } - - protected void configList() throws IOException { - setDataCommandInfo("List config"); - - checkServerAccess("server.config.get"); - - beginResponse(); - try { - sendOk(clientTxId); - - channel.writeShort((short) OGlobalConfiguration.values().length); - for (OGlobalConfiguration cfg : OGlobalConfiguration.values()) { - - String key; - try { - key = cfg.getKey(); - } catch (Exception e) { - key = "?"; - } - - String value; - try { - value = cfg.getValueAsString() != null ? cfg.getValueAsString() : ""; - } catch (Exception e) { - value = ""; - } - - channel.writeString(key); - channel.writeString(value); - } - } finally { - endResponse(); - } - } - - protected void configSet() throws IOException { - setDataCommandInfo("Get config"); - - checkServerAccess("server.config.set"); - - final String key = channel.readString(); - final String value = channel.readString(); - final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(key); - if (cfg != null) - cfg.setValue(value); - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void configGet() throws IOException { - setDataCommandInfo("Get config"); - - checkServerAccess("server.config.get"); - - final String key = channel.readString(); - final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(key); - String cfgValue = cfg != null ? cfg.getValueAsString() : ""; - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeString(cfgValue); - } finally { - endResponse(); - } - } - - protected void commit() throws IOException { - setDataCommandInfo("Transaction commit"); - - if (!isConnectionAlive()) - return; - - final OTransactionOptimisticProxy tx = new OTransactionOptimisticProxy((ODatabaseRecordTx) connection.database.getUnderlying(), - channel); - - try { - connection.database.begin(tx); - - try { - connection.database.commit(); - beginResponse(); - try { - sendOk(clientTxId); - - // SEND BACK ALL THE RECORD IDS FOR THE CREATED RECORDS - channel.writeInt(tx.getCreatedRecords().size()); - for (Entry> entry : tx.getCreatedRecords().entrySet()) { - channel.writeRID(entry.getKey()); - channel.writeRID(entry.getValue().getIdentity()); - - // IF THE NEW OBJECT HAS VERSION > 0 MEANS THAT HAS BEEN UPDATED IN THE SAME TX. THIS HAPPENS FOR GRAPHS - if (entry.getValue().getRecordVersion().getCounter() > 0) - tx.getUpdatedRecords().put((ORecordId) entry.getValue().getIdentity(), entry.getValue()); - } - - // SEND BACK ALL THE NEW VERSIONS FOR THE UPDATED RECORDS - channel.writeInt(tx.getUpdatedRecords().size()); - for (Entry> entry : tx.getUpdatedRecords().entrySet()) { - channel.writeRID(entry.getKey()); - channel.writeVersion(entry.getValue().getRecordVersion()); - } - - if (connection.data.protocolVersion >= 20) - sendCollectionChanges(); - } finally { - endResponse(); - } - } catch (Exception e) { - if (connection.database != null) { - if (connection.database.getTransaction().isActive()) - connection.database.rollback(true); - } - sendError(clientTxId, e); - } - } catch (OTransactionAbortedException e) { - // TX ABORTED BY THE CLIENT - } catch (Exception e) { - // Error during TX initialization, possibly index constraints violation. - if (tx.isActive()) - tx.rollback(true, -1); - - sendError(clientTxId, e); - } - } - - protected void command() throws IOException { - setDataCommandInfo("Execute remote command"); - - final boolean asynch = channel.readByte() == 'a'; - - final OCommandRequestText command = (OCommandRequestText) OStreamSerializerAnyStreamable.INSTANCE.fromStream(channel - .readBytes()); - - connection.data.commandDetail = command.getText(); - - // ENABLES THE CACHE TO IMPROVE PERFORMANCE OF COMPLEX COMMANDS LIKE TRAVERSE - // connection.database.getLevel1Cache().setEnable(true); - beginResponse(); - try { - final OAbstractCommandResultListener listener; - - if (asynch) { - listener = new OAsyncCommandResultListener(this, clientTxId); - command.setResultListener(listener); - } else - listener = new OSyncCommandResultListener(); - - final long serverTimeout = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong(); - - if (serverTimeout > 0 && command.getTimeoutTime() > serverTimeout) - // FORCE THE SERVER'S TIMEOUT - command.setTimeout(serverTimeout, command.getTimeoutStrategy()); - - if (!isConnectionAlive()) - return; - - // ASSIGNED THE PARSED FETCHPLAN - listener.setFetchPlan(connection.database.command(command).getFetchPlan()); - - final Object result = connection.database.command(command).execute(); - - // FETCHPLAN HAS TO BE ASSIGNED AGAIN, because it can be changed by SQL statement - listener.setFetchPlan(command.getFetchPlan()); - - if (asynch) { - // ASYNCHRONOUS - if (listener.isEmpty()) - try { - sendOk(clientTxId); - } catch (IOException ignored) { - } - channel.writeByte((byte) 0); // NO MORE RECORDS - - } else { - // SYNCHRONOUS - sendOk(clientTxId); - - if (result == null) { - // NULL VALUE - channel.writeByte((byte) 'n'); - } else if (result instanceof OIdentifiable) { - // RECORD - channel.writeByte((byte) 'r'); - listener.result(result); - writeIdentifiable((OIdentifiable) result); - } else if (OMultiValue.isMultiValue(result)) { - channel.writeByte((byte) 'l'); - channel.writeInt(OMultiValue.getSize(result)); - for (Object o : OMultiValue.getMultiValueIterable(result)) { - try { - listener.result(o); - writeIdentifiable((OIdentifiable) o); - } catch (Exception e) { - OLogManager.instance().warn(this, "Cannot serialize record: " + o); - // WRITE NULL RECORD TO AVOID BREAKING PROTOCOL - writeIdentifiable(null); - } - } - } else { - // ANY OTHER (INCLUDING LITERALS) - channel.writeByte((byte) 'a'); - final StringBuilder value = new StringBuilder(); - listener.result(result); - ORecordSerializerStringAbstract.fieldTypeToString(value, OType.getTypeByClass(result.getClass()), result); - channel.writeString(value.toString()); - } - - if (connection.data.protocolVersion >= 17) { - // SEND FETCHED RECORDS TO LOAD IN CLIENT CACHE - for (ORecord rec : ((OSyncCommandResultListener) listener).getFetchedRecordsToSend()) { - channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT - // ISN'T PART OF THE - // RESULT SET - writeIdentifiable(rec); - } - - channel.writeByte((byte) 0); // NO MORE RECORDS - } - } - - } finally { - endResponse(); - } - } - - protected void deleteRecord() throws IOException { - setDataCommandInfo("Delete record"); - - if (!isConnectionAlive()) - return; - - final ORID rid = channel.readRID(); - final ORecordVersion version = channel.readVersion(); - final byte mode = channel.readByte(); - - final int result = deleteRecord(connection.database, rid, version); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) result); - } finally { - endResponse(); - } - } - } - - protected void hideRecord() throws IOException { - setDataCommandInfo("Hide record"); - - if (!isConnectionAlive()) - return; - - final ORID rid = channel.readRID(); - final byte mode = channel.readByte(); - - final int result = hideRecord(connection.database, rid); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) result); - } finally { - endResponse(); - } - } - } - - protected void cleanOutRecord() throws IOException { - setDataCommandInfo("Clean out record"); - - if (!isConnectionAlive()) - return; - - final ORID rid = channel.readRID(); - final ORecordVersion version = channel.readVersion(); - final byte mode = channel.readByte(); - - final int result = cleanOutRecord(connection.database, rid, version); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) result); - } finally { - endResponse(); - } - } - } - - /** - * VERSION MANAGEMENT:
- * -1 : DOCUMENT UPDATE, NO VERSION CONTROL
- * -2 : DOCUMENT UPDATE, NO VERSION CONTROL, NO VERSION INCREMENT
- * -3 : DOCUMENT ROLLBACK, DECREMENT VERSION
- * >-1 : MVCC CONTROL, RECORD UPDATE AND VERSION INCREMENT
- * <-3 : WRONG VERSION VALUE - * - * @throws IOException - */ - protected void updateRecord() throws IOException { - setDataCommandInfo("Update record"); - - if (!isConnectionAlive()) - return; - - final ORecordId rid = channel.readRID(); - final byte[] buffer = channel.readBytes(); - final ORecordVersion version = channel.readVersion(); - final byte recordType = channel.readByte(); - final byte mode = channel.readByte(); - - final ORecordVersion newVersion = updateRecord(connection.database, rid, buffer, version, recordType); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeVersion(newVersion); - - if (connection.data.protocolVersion >= 20) - sendCollectionChanges(); - } finally { - endResponse(); - } - } - } - - protected void createRecord() throws IOException { - setDataCommandInfo("Create record"); - - if (!isConnectionAlive()) - return; - - final int dataSegmentId = connection.data.protocolVersion >= 10 ? channel.readInt() : 0; - final ORecordId rid = new ORecordId(channel.readShort(), ORID.CLUSTER_POS_INVALID); - final byte[] buffer = channel.readBytes(); - final byte recordType = channel.readByte(); - final byte mode = channel.readByte(); - - final ORecord record = createRecord(connection.database, rid, buffer, recordType, dataSegmentId); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeClusterPosition(record.getIdentity().getClusterPosition()); - if (connection.data.protocolVersion >= 11) - channel.writeVersion(record.getRecordVersion()); - - if (connection.data.protocolVersion >= 20) - sendCollectionChanges(); - } finally { - endResponse(); - } - } - } - - protected void readRecordMetadata() throws IOException { - setDataCommandInfo("Record metadata"); - - final ORID rid = channel.readRID(); - - beginResponse(); - try { - final ORecordMetadata metadata = connection.database.getRecordMetadata(rid); - sendOk(clientTxId); - channel.writeRID(metadata.getRecordId()); - channel.writeVersion(metadata.getRecordVersion()); - } finally { - endResponse(); - } - } - - protected void readRecord() throws IOException { - setDataCommandInfo("Load record"); - - if (!isConnectionAlive()) - return; - - final ORecordId rid = channel.readRID(); - final String fetchPlanString = channel.readString(); - boolean ignoreCache = false; - if (connection.data.protocolVersion >= 9) - ignoreCache = channel.readByte() == 1; - - boolean loadTombstones = false; - if (connection.data.protocolVersion >= 13) - loadTombstones = channel.readByte() > 0; - - if (rid.clusterId == 0 && rid.clusterPosition.longValue() == 0) { - // @COMPATIBILITY 0.9.25 - // SEND THE DB CONFIGURATION INSTEAD SINCE IT WAS ON RECORD 0:0 - OFetchHelper.checkFetchPlanValid(fetchPlanString); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) 1); - channel.writeBytes(connection.database.getStorage().getConfiguration().toStream()); - channel.writeVersion(OVersionFactory.instance().createVersion()); - channel.writeByte(ORecordBytes.RECORD_TYPE); - channel.writeByte((byte) 0); // NO MORE RECORDS - } finally { - endResponse(); - } - - } else { - final ORecordInternal record = connection.database.load(rid, fetchPlanString, ignoreCache, loadTombstones, - OStorage.LOCKING_STRATEGY.DEFAULT); - - beginResponse(); - try { - sendOk(clientTxId); - - if (record != null) { - channel.writeByte((byte) 1); // HAS RECORD - channel.writeBytes(record.toStream()); - channel.writeVersion(record.getRecordVersion()); - channel.writeByte(record.getRecordType()); - - if (fetchPlanString.length() > 0) { - // BUILD THE SERVER SIDE RECORD TO ACCES TO THE FETCH - // PLAN - if (record instanceof ODocument) { - final Map fetchPlan = OFetchHelper.buildFetchPlan(fetchPlanString); - - final Set> recordsToSend = new HashSet>(); - final ODocument doc = (ODocument) record; - final OFetchListener listener = new ORemoteFetchListener() { - @Override - protected void sendRecord(ORecord iLinked) { - recordsToSend.add(iLinked); - } - }; - final OFetchContext context = new ORemoteFetchContext(); - OFetchHelper.fetch(doc, doc, fetchPlan, listener, context, ""); - - // SEND RECORDS TO LOAD IN CLIENT CACHE - for (ORecord d : recordsToSend) { - if (d.getIdentity().isValid()) { - channel.writeByte((byte) 2); // CLIENT CACHE - // RECORD. IT ISN'T PART OF THE RESULT SET - writeIdentifiable(d); - } - } - } - - } - } - channel.writeByte((byte) 0); // NO MORE RECORDS - - } finally { - endResponse(); - } - } - } - - protected void beginResponse() { - channel.acquireWriteLock(); - } - - protected void endResponse() throws IOException { - // resetting transaction state. Commands are stateless and connection should be cleared - // otherwise reused connection (connections pool) may lead to unpredicted errors - if (connection != null && connection.database != null && connection.database.getTransaction() != null) - connection.database.getTransaction().rollback(); - channel.flush(); - channel.releaseWriteLock(); - } - - protected void setDataCommandInfo(final String iCommandInfo) { - if (connection != null) - connection.data.commandInfo = iCommandInfo; - } - - protected void readConnectionData() throws IOException { - connection.data.driverName = channel.readString(); - connection.data.driverVersion = channel.readString(); - connection.data.protocolVersion = channel.readShort(); - connection.data.clientId = channel.readString(); - } - - protected void sendOk(final int iClientTxId) throws IOException { - channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_OK); - channel.writeInt(iClientTxId); - } - - protected void sendError(final int iClientTxId, final Throwable t) throws IOException { - channel.acquireWriteLock(); - try { - - channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_ERROR); - channel.writeInt(iClientTxId); - - Throwable current; - if (t instanceof OLockException && t.getCause() instanceof ODatabaseException) - // BYPASS THE DB POOL EXCEPTION TO PROPAGATE THE RIGHT SECURITY ONE - current = t.getCause(); - else - current = t; - - final Throwable original = current; - while (current != null) { - // MORE DETAILS ARE COMING AS EXCEPTION - channel.writeByte((byte) 1); - - channel.writeString(current.getClass().getName()); - channel.writeString(current.getMessage()); - - current = current.getCause(); - } - channel.writeByte((byte) 0); - - if (connection != null && connection.data.protocolVersion >= 19) { - final OMemoryStream memoryStream = new OMemoryStream(); - final ObjectOutputStream objectOutputStream = new ObjectOutputStream(memoryStream); - - objectOutputStream.writeObject(original); - objectOutputStream.flush(); - - final byte[] result = memoryStream.toByteArray(); - objectOutputStream.close(); - - channel.writeBytes(result); - } - - channel.flush(); - - if (OLogManager.instance().isLevelEnabled(logClientExceptions)) { - if (logClientFullStackTrace) - OLogManager.instance().log(this, logClientExceptions, "Sent run-time exception to the client %s: %s", t, - channel.socket.getRemoteSocketAddress(), t.toString()); - else - OLogManager.instance().log(this, logClientExceptions, "Sent run-time exception to the client %s: %s", null, - channel.socket.getRemoteSocketAddress(), t.toString()); - } - } catch (Exception e) { - if (e instanceof SocketException) - shutdown(); - } finally { - channel.releaseWriteLock(); - } - } - - @Override - protected void handleConnectionError(final OChannelBinaryServer iChannel, final Throwable e) { - super.handleConnectionError(channel, e); - OServerPluginHelper.invokeHandlerCallbackOnClientError(server, connection, e); - } - - protected void sendResponse(final ODocument iResponse) throws IOException { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(iResponse != null ? iResponse.toStream() : null); - } finally { - endResponse(); - } - } - - protected void freezeDatabase() throws IOException { - setDataCommandInfo("Freeze database"); - String dbName = channel.readString(); - - checkServerAccess("database.freeze"); - - final String storageType; - - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Freezing database '%s'", connection.database.getURL()); - - if (connection.database.isClosed()) - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - - connection.database.freeze(true); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void releaseDatabase() throws IOException { - setDataCommandInfo("Release database"); - String dbName = channel.readString(); - - checkServerAccess("database.release"); - - final String storageType; - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Realising database '%s'", connection.database.getURL()); - - if (connection.database.isClosed()) - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - - connection.database.release(); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void freezeCluster() throws IOException { - setDataCommandInfo("Freeze cluster"); - final String dbName = channel.readString(); - final int clusterId = channel.readShort(); - - checkServerAccess("database.freeze"); - - final String storageType; - - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Freezing database '%s' cluster %d", connection.database.getURL(), clusterId); - - if (connection.database.isClosed()) { - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - } - - connection.database.freezeCluster(clusterId); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void releaseCluster() throws IOException { - setDataCommandInfo("Release database"); - final String dbName = channel.readString(); - final int clusterId = channel.readShort(); - - checkServerAccess("database.release"); - - final String storageType; - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Realising database '%s' cluster %d", connection.database.getURL(), clusterId); - - if (connection.database.isClosed()) { - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - } - - connection.database.releaseCluster(clusterId); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - private void ridBagSize() throws IOException { - setDataCommandInfo("RidBag get size"); - - OBonsaiCollectionPointer collectionPointer = OCollectionNetworkSerializer.INSTANCE.readCollectionPointer(channel); - final byte[] changeStream = channel.readBytes(); - - OSBTreeBonsai tree = connection.database.getSbTreeCollectionManager().loadSBTree(collectionPointer); - final Map changes = OSBTreeRidBag.ChangeSerializationHelper.INSTANCE.deserializeChanges( - changeStream, 0); - - int realSize = tree.getRealBagSize(changes); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeInt(realSize); - } finally { - endResponse(); - } - } - - private void sbTreeBonsaiGetEntriesMajor() throws IOException { - setDataCommandInfo("SB-Tree bonsai get values major"); - - OBonsaiCollectionPointer collectionPointer = OCollectionNetworkSerializer.INSTANCE.readCollectionPointer(channel); - byte[] keyStream = channel.readBytes(); - boolean inclusive = channel.readBoolean(); - int pageSize = 128; - - if (connection.data.protocolVersion>=21) - pageSize = channel.readInt(); - - OSBTreeBonsai tree = connection.database.getSbTreeCollectionManager().loadSBTree(collectionPointer); - - final OBinarySerializer keySerializer = tree.getKeySerializer(); - OIdentifiable key = keySerializer.deserialize(keyStream, 0); - - final OBinarySerializer valueSerializer = tree.getValueSerializer(); - - OTreeInternal.AccumulativeListener listener = new OTreeInternal.AccumulativeListener( - pageSize); - tree.loadEntriesMajor(key, inclusive, true, listener); - List> result = listener.getResult(); - byte[] stream = serializeSBTreeEntryCollection(result, keySerializer, valueSerializer); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(stream); - } finally { - endResponse(); - } - } - - private byte[] serializeSBTreeEntryCollection(List> collection, - OBinarySerializer keySerializer, OBinarySerializer valueSerializer) { - byte[] stream = new byte[OIntegerSerializer.INT_SIZE + collection.size() - * (keySerializer.getFixedLength() + valueSerializer.getFixedLength())]; - int offset = 0; - - OIntegerSerializer.INSTANCE.serialize(collection.size(), stream, offset); - offset += OIntegerSerializer.INT_SIZE; - - for (Entry entry : collection) { - keySerializer.serialize(entry.getKey(), stream, offset); - offset += keySerializer.getObjectSize(entry.getKey()); - - valueSerializer.serialize(entry.getValue(), stream, offset); - offset += valueSerializer.getObjectSize(entry.getValue()); - } - return stream; - } - - private void sbTreeBonsaiFirstKey() throws IOException { - setDataCommandInfo("SB-Tree bonsai get first key"); - - OBonsaiCollectionPointer collectionPointer = OCollectionNetworkSerializer.INSTANCE.readCollectionPointer(channel); - OSBTreeBonsai tree = connection.database.getSbTreeCollectionManager().loadSBTree(collectionPointer); - - OIdentifiable result = tree.firstKey(); - final OBinarySerializer keySerializer; - if (result == null) { - keySerializer = ONullSerializer.INSTANCE; - } else { - keySerializer = tree.getKeySerializer(); - } - - byte[] stream = new byte[OByteSerializer.BYTE_SIZE + keySerializer.getObjectSize(result)]; - OByteSerializer.INSTANCE.serialize(keySerializer.getId(), stream, 0); - keySerializer.serialize(result, stream, OByteSerializer.BYTE_SIZE); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(stream); - } finally { - endResponse(); - } - } - - private void sbTreeBonsaiGet() throws IOException { - setDataCommandInfo("SB-Tree bonsai get"); - - OBonsaiCollectionPointer collectionPointer = OCollectionNetworkSerializer.INSTANCE.readCollectionPointer(channel); - final byte[] keyStream = channel.readBytes(); - - OSBTreeBonsai tree = connection.database.getSbTreeCollectionManager().loadSBTree(collectionPointer); - - final OIdentifiable key = tree.getKeySerializer().deserialize(keyStream, 0); - - Integer result = tree.get(key); - final OBinarySerializer valueSerializer; - if (result == null) { - valueSerializer = ONullSerializer.INSTANCE; - } else { - valueSerializer = tree.getValueSerializer(); - } - - byte[] stream = new byte[OByteSerializer.BYTE_SIZE + valueSerializer.getObjectSize(result)]; - OByteSerializer.INSTANCE.serialize(valueSerializer.getId(), stream, 0); - valueSerializer.serialize(result, stream, OByteSerializer.BYTE_SIZE); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(stream); - } finally { - endResponse(); - } - } - - private void createSBTreeBonsai() throws IOException { - setDataCommandInfo("Create SB-Tree bonsai instance"); - - int clusterId = channel.readInt(); - - OBonsaiCollectionPointer collectionPointer = connection.database.getSbTreeCollectionManager().createSBTree(clusterId, null); - - beginResponse(); - try { - sendOk(clientTxId); - OCollectionNetworkSerializer.INSTANCE.writeCollectionPointer(channel, collectionPointer); - } finally { - endResponse(); - } - } - - private void lowerPositions() throws IOException { - setDataCommandInfo("Retrieve lower positions"); - - final int clusterId = channel.readInt(); - final OClusterPosition clusterPosition = channel.readClusterPosition(); - - beginResponse(); - try { - sendOk(clientTxId); - - final OPhysicalPosition[] previousPositions = connection.database.getStorage().lowerPhysicalPositions(clusterId, - new OPhysicalPosition(clusterPosition)); - - if (previousPositions != null) { - channel.writeInt(previousPositions.length); - - for (final OPhysicalPosition physicalPosition : previousPositions) { - channel.writeClusterPosition(physicalPosition.clusterPosition); - channel.writeInt(physicalPosition.dataSegmentId); - channel.writeLong(physicalPosition.dataSegmentPos); - channel.writeInt(physicalPosition.recordSize); - channel.writeVersion(physicalPosition.recordVersion); - } - - } else { - channel.writeInt(0); // NO MORE RECORDS - } - - } finally { - endResponse(); - } - } - - private void floorPositions() throws IOException { - setDataCommandInfo("Retrieve floor positions"); - - final int clusterId = channel.readInt(); - final OClusterPosition clusterPosition = channel.readClusterPosition(); - - beginResponse(); - try { - sendOk(clientTxId); - - final OPhysicalPosition[] previousPositions = connection.database.getStorage().floorPhysicalPositions(clusterId, - new OPhysicalPosition(clusterPosition)); - - if (previousPositions != null) { - channel.writeInt(previousPositions.length); - - for (final OPhysicalPosition physicalPosition : previousPositions) { - channel.writeClusterPosition(physicalPosition.clusterPosition); - channel.writeInt(physicalPosition.dataSegmentId); - channel.writeLong(physicalPosition.dataSegmentPos); - channel.writeInt(physicalPosition.recordSize); - channel.writeVersion(physicalPosition.recordVersion); - } - - } else { - channel.writeInt(0); // NO MORE RECORDS - } - - } finally { - endResponse(); - } - } - - private void higherPositions() throws IOException { - setDataCommandInfo("Retrieve higher positions"); - - final int clusterId = channel.readInt(); - final OClusterPosition clusterPosition = channel.readClusterPosition(); - - beginResponse(); - try { - sendOk(clientTxId); - - OPhysicalPosition[] nextPositions = connection.database.getStorage().higherPhysicalPositions(clusterId, - new OPhysicalPosition(clusterPosition)); - - if (nextPositions != null) { - - channel.writeInt(nextPositions.length); - for (final OPhysicalPosition physicalPosition : nextPositions) { - channel.writeClusterPosition(physicalPosition.clusterPosition); - channel.writeInt(physicalPosition.dataSegmentId); - channel.writeLong(physicalPosition.dataSegmentPos); - channel.writeInt(physicalPosition.recordSize); - channel.writeVersion(physicalPosition.recordVersion); - } - } else { - channel.writeInt(0); // NO MORE RECORDS - } - } finally { - endResponse(); - } - } - - private void ceilingPositions() throws IOException { - setDataCommandInfo("Retrieve ceiling positions"); - - final int clusterId = channel.readInt(); - final OClusterPosition clusterPosition = channel.readClusterPosition(); - - beginResponse(); - try { - sendOk(clientTxId); - - final OPhysicalPosition[] previousPositions = connection.database.getStorage().ceilingPhysicalPositions(clusterId, - new OPhysicalPosition(clusterPosition)); - - if (previousPositions != null) { - channel.writeInt(previousPositions.length); - - for (final OPhysicalPosition physicalPosition : previousPositions) { - channel.writeClusterPosition(physicalPosition.clusterPosition); - channel.writeInt(physicalPosition.dataSegmentId); - channel.writeLong(physicalPosition.dataSegmentPos); - channel.writeInt(physicalPosition.recordSize); - channel.writeVersion(physicalPosition.recordVersion); - } - - } else { - channel.writeInt(0); // NO MORE RECORDS - } - - } finally { - endResponse(); - } - } - - private boolean isConnectionAlive() { - if (connection == null || connection.database == null) { - // CONNECTION/DATABASE CLOSED, KILL IT - OClientConnectionManager.instance().kill(connection); - return false; - } - return true; - } - - private void sendCollectionChanges() throws IOException { - OSBTreeCollectionManager collectionManager = connection.database.getSbTreeCollectionManager(); - if (collectionManager != null) { - Map changedIds = collectionManager.changedIds(); - - channel.writeInt(changedIds.size()); - - for (Entry entry : changedIds.entrySet()) { - UUID id = entry.getKey(); - channel.writeLong(id.getMostSignificantBits()); - channel.writeLong(id.getLeastSignificantBits()); - - OCollectionNetworkSerializer.INSTANCE.writeCollectionPointer(channel, entry.getValue()); - } - collectionManager.clearChangedIds(); - } - } - - private void sendDatabaseInformation() throws IOException { - final Collection clusters = connection.database.getStorage().getClusterInstances(); - int clusterCount = 0; - for (OCluster c : clusters) { - if (c != null) { - ++clusterCount; - } - } - if (connection.data.protocolVersion >= 7) - channel.writeShort((short) clusterCount); - else - channel.writeInt(clusterCount); - - for (OCluster c : clusters) { - if (c != null) { - channel.writeString(c.getName()); - channel.writeShort((short) c.getId()); - channel.writeString(c.getType()); - if (connection.data.protocolVersion >= 12) - channel.writeShort((short) c.getDataSegmentId()); - } - } - } - - private void listDatabases() throws IOException { - checkServerAccess("server.dblist"); - final ODocument result = new ODocument(); - result.field("databases", server.getAvailableStorageNames()); - - setDataCommandInfo("List databases"); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(result.toStream()); - } finally { - endResponse(); - } - } - - private boolean loadUserFromSchema(final String iUserName, final String iUserPassword) { - account = connection.database.getMetadata().getSecurity().authenticate(iUserName, iUserPassword); - return true; - } -} diff --git a/All/Genesis-NP/Genesis#418/old/ONetworkProtocolBinary.java b/All/Genesis-NP/Genesis#418/old/ONetworkProtocolBinary.java deleted file mode 100755 index 2b25487..0000000 --- a/All/Genesis-NP/Genesis#418/old/ONetworkProtocolBinary.java +++ /dev/null @@ -1,1985 +0,0 @@ -/* - * Copyright 2010-2012 Luca Garulli (l.garulli--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. - */ -package com.orientechnologies.orient.server.network.protocol.binary; - -import com.orientechnologies.common.collection.OMultiValue; -import com.orientechnologies.common.concur.lock.OLockException; -import com.orientechnologies.common.io.OIOException; -import com.orientechnologies.common.log.OLogManager; -import com.orientechnologies.common.serialization.types.OBinarySerializer; -import com.orientechnologies.common.serialization.types.OByteSerializer; -import com.orientechnologies.common.serialization.types.OIntegerSerializer; -import com.orientechnologies.common.serialization.types.ONullSerializer; -import com.orientechnologies.orient.client.remote.OCollectionNetworkSerializer; -import com.orientechnologies.orient.client.remote.OEngineRemote; -import com.orientechnologies.orient.core.OConstants; -import com.orientechnologies.orient.core.Orient; -import com.orientechnologies.orient.core.command.OCommandRequestText; -import com.orientechnologies.orient.core.config.OContextConfiguration; -import com.orientechnologies.orient.core.config.OGlobalConfiguration; -import com.orientechnologies.orient.core.db.ODatabase; -import com.orientechnologies.orient.core.db.ODatabaseComplex; -import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal; -import com.orientechnologies.orient.core.db.document.ODatabaseDocument; -import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; -import com.orientechnologies.orient.core.db.record.ODatabaseRecordTx; -import com.orientechnologies.orient.core.db.record.OIdentifiable; -import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OBonsaiCollectionPointer; -import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeCollectionManager; -import com.orientechnologies.orient.core.db.record.ridbag.sbtree.OSBTreeRidBag; -import com.orientechnologies.orient.core.exception.OConfigurationException; -import com.orientechnologies.orient.core.exception.ODatabaseException; -import com.orientechnologies.orient.core.exception.OSecurityAccessException; -import com.orientechnologies.orient.core.exception.OSecurityException; -import com.orientechnologies.orient.core.exception.OStorageException; -import com.orientechnologies.orient.core.exception.OTransactionAbortedException; -import com.orientechnologies.orient.core.fetch.OFetchContext; -import com.orientechnologies.orient.core.fetch.OFetchHelper; -import com.orientechnologies.orient.core.fetch.OFetchListener; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchContext; -import com.orientechnologies.orient.core.fetch.remote.ORemoteFetchListener; -import com.orientechnologies.orient.core.id.OClusterPosition; -import com.orientechnologies.orient.core.id.ORID; -import com.orientechnologies.orient.core.id.ORecordId; -import com.orientechnologies.orient.core.index.sbtree.OTreeInternal; -import com.orientechnologies.orient.core.index.sbtreebonsai.local.OSBTreeBonsai; -import com.orientechnologies.orient.core.metadata.schema.OType; -import com.orientechnologies.orient.core.metadata.security.OUser; -import com.orientechnologies.orient.core.record.ORecord; -import com.orientechnologies.orient.core.record.ORecordInternal; -import com.orientechnologies.orient.core.record.impl.ODocument; -import com.orientechnologies.orient.core.record.impl.ORecordBytes; -import com.orientechnologies.orient.core.serialization.OMemoryStream; -import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerStringAbstract; -import com.orientechnologies.orient.core.serialization.serializer.stream.OStreamSerializerAnyStreamable; -import com.orientechnologies.orient.core.storage.OCluster; -import com.orientechnologies.orient.core.storage.OPhysicalPosition; -import com.orientechnologies.orient.core.storage.ORecordMetadata; -import com.orientechnologies.orient.core.storage.OStorage; -import com.orientechnologies.orient.core.storage.OStorageProxy; -import com.orientechnologies.orient.core.storage.impl.memory.OStorageMemory; -import com.orientechnologies.orient.core.version.ORecordVersion; -import com.orientechnologies.orient.core.version.OVersionFactory; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryProtocol; -import com.orientechnologies.orient.enterprise.channel.binary.OChannelBinaryServer; -import com.orientechnologies.orient.server.OClientConnection; -import com.orientechnologies.orient.server.OClientConnectionManager; -import com.orientechnologies.orient.server.OServer; -import com.orientechnologies.orient.server.distributed.ODistributedServerManager; -import com.orientechnologies.orient.server.plugin.OServerPlugin; -import com.orientechnologies.orient.server.plugin.OServerPluginHelper; -import com.orientechnologies.orient.server.tx.OTransactionOptimisticProxy; - -import java.io.IOException; -import java.io.ObjectOutputStream; -import java.net.Socket; -import java.net.SocketException; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.UUID; - -public class ONetworkProtocolBinary extends OBinaryNetworkProtocolAbstract { - protected OClientConnection connection; - protected OUser account; - - private String dbType; - - public ONetworkProtocolBinary() { - super("OrientDB <- BinaryClient/?"); - } - - public ONetworkProtocolBinary(final String iThreadName) { - super(iThreadName); - } - - @Override - public void config(final OServer iServer, final Socket iSocket, final OContextConfiguration iConfig, - final List iStatelessCommands, List iStatefulCommands) throws IOException { - // CREATE THE CLIENT CONNECTION - connection = OClientConnectionManager.instance().connect(this); - - super.config(iServer, iSocket, iConfig, iStatelessCommands, iStatefulCommands); - - // SEND PROTOCOL VERSION - channel.writeShort((short) OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION); - - channel.flush(); - start(); - - setName("OrientDB <- BinaryClient (" + iSocket.getRemoteSocketAddress() + ")"); - } - - @Override - public int getVersion() { - return OChannelBinaryProtocol.CURRENT_PROTOCOL_VERSION; - } - - @Override - public void startup() { - super.startup(); - OServerPluginHelper.invokeHandlerCallbackOnClientConnection(server, connection); - } - - @Override - public void shutdown() { - sendShutdown(); - super.shutdown(); - - if (connection == null) - return; - - OServerPluginHelper.invokeHandlerCallbackOnClientDisconnection(server, connection); - - OClientConnectionManager.instance().disconnect(connection); - } - - public String getType() { - return "binary"; - } - - @Override - protected void onBeforeRequest() throws IOException { - waitNodeIsOnline(); - - connection = OClientConnectionManager.instance().getConnection(clientTxId); - - if (clientTxId < 0) { - short protocolId = 0; - - if (connection != null) - protocolId = connection.data.protocolVersion; - - connection = OClientConnectionManager.instance().connect(this); - - if (connection != null) - connection.data.protocolVersion = protocolId; - } - - if (connection != null) { - ODatabaseRecordThreadLocal.INSTANCE.set(connection.database); - if (connection.database != null) { - connection.data.lastDatabase = connection.database.getName(); - connection.data.lastUser = connection.database.getUser() != null ? connection.database.getUser().getName() : null; - } else { - connection.data.lastDatabase = null; - connection.data.lastUser = null; - } - - ++connection.data.totalRequests; - setDataCommandInfo("Listening"); - connection.data.commandDetail = "-"; - connection.data.lastCommandReceived = System.currentTimeMillis(); - } else { - ODatabaseRecordThreadLocal.INSTANCE.remove(); - if (requestType != OChannelBinaryProtocol.REQUEST_DB_CLOSE && requestType != OChannelBinaryProtocol.REQUEST_SHUTDOWN) { - OLogManager.instance().debug(this, "Found unknown session %d, shutdown current connection", clientTxId); - shutdown(); - throw new OIOException("Found unknown session " + clientTxId); - } - } - - OServerPluginHelper.invokeHandlerCallbackOnBeforeClientRequest(server, connection, (byte) requestType); - } - - @Override - protected void onAfterRequest() throws IOException { - OServerPluginHelper.invokeHandlerCallbackOnAfterClientRequest(server, connection, (byte) requestType); - - if (connection != null) { - if (connection.database != null) - if (!connection.database.isClosed()) - connection.database.getLevel1Cache().clear(); - - connection.data.lastCommandExecutionTime = System.currentTimeMillis() - connection.data.lastCommandReceived; - connection.data.totalCommandExecutionTime += connection.data.lastCommandExecutionTime; - - connection.data.lastCommandInfo = connection.data.commandInfo; - connection.data.lastCommandDetail = connection.data.commandDetail; - - setDataCommandInfo("Listening"); - connection.data.commandDetail = "-"; - } - } - - protected boolean executeRequest() throws IOException { - try { - switch (requestType) { - - case OChannelBinaryProtocol.REQUEST_SHUTDOWN: - shutdownConnection(); - break; - - case OChannelBinaryProtocol.REQUEST_CONNECT: - connect(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_LIST: - listDatabases(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_OPEN: - openDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_RELOAD: - reloadDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_CREATE: - createDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_CLOSE: - closeDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_EXIST: - existsDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_DROP: - dropDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_SIZE: - sizeDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_COUNTRECORDS: - countDatabaseRecords(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_COPY: - copyDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_REPLICATION: - replicationDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_CLUSTER: - distributedCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_DATASEGMENT_ADD: - addDataSegment(); - break; - - case OChannelBinaryProtocol.REQUEST_DATASEGMENT_DROP: - dropDataSegment(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_COUNT: - countClusters(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_DATARANGE: - rangeCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_ADD: - addCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_DROP: - removeCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_METADATA: - readRecordMetadata(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_LOAD: - readRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_CREATE: - createRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_UPDATE: - updateRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_DELETE: - deleteRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_HIDE: - hideRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_POSITIONS_HIGHER: - higherPositions(); - break; - - case OChannelBinaryProtocol.REQUEST_POSITIONS_CEILING: - ceilingPositions(); - break; - - case OChannelBinaryProtocol.REQUEST_POSITIONS_LOWER: - lowerPositions(); - break; - - case OChannelBinaryProtocol.REQUEST_POSITIONS_FLOOR: - floorPositions(); - break; - - case OChannelBinaryProtocol.REQUEST_COUNT: - throw new UnsupportedOperationException("Operation OChannelBinaryProtocol.REQUEST_COUNT has been deprecated"); - - case OChannelBinaryProtocol.REQUEST_COMMAND: - command(); - break; - - case OChannelBinaryProtocol.REQUEST_TX_COMMIT: - commit(); - break; - - case OChannelBinaryProtocol.REQUEST_CONFIG_GET: - configGet(); - break; - - case OChannelBinaryProtocol.REQUEST_CONFIG_SET: - configSet(); - break; - - case OChannelBinaryProtocol.REQUEST_CONFIG_LIST: - configList(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_FREEZE: - freezeDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DB_RELEASE: - releaseDatabase(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_FREEZE: - freezeCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_DATACLUSTER_RELEASE: - releaseCluster(); - break; - - case OChannelBinaryProtocol.REQUEST_RECORD_CLEAN_OUT: - cleanOutRecord(); - break; - - case OChannelBinaryProtocol.REQUEST_CREATE_SBTREE_BONSAI: - createSBTreeBonsai(); - break; - - case OChannelBinaryProtocol.REQUEST_SBTREE_BONSAI_GET: - sbTreeBonsaiGet(); - break; - - case OChannelBinaryProtocol.REQUEST_SBTREE_BONSAI_FIRST_KEY: - sbTreeBonsaiFirstKey(); - break; - - case OChannelBinaryProtocol.REQUEST_SBTREE_BONSAI_GET_ENTRIES_MAJOR: - sbTreeBonsaiGetEntriesMajor(); - break; - - case OChannelBinaryProtocol.REQUEST_RIDBAG_GET_SIZE: - ridBagSize(); - break; - - default: - setDataCommandInfo("Command not supported"); - return false; - } - - return true; - } catch (RuntimeException e) { - if (connection != null && connection.database != null) { - final OSBTreeCollectionManager collectionManager = connection.database.getSbTreeCollectionManager(); - if (collectionManager != null) - collectionManager.clearChangedIds(); - } - - throw e; - } - } - - protected void checkServerAccess(final String iResource) { - if (connection.serverUser == null) - throw new OSecurityAccessException("Server user not authenticated."); - - if (!server.authenticate(connection.serverUser.name, null, iResource)) - throw new OSecurityAccessException("User '" + connection.serverUser.name + "' cannot access to the resource [" + iResource - + "]. Use another server user or change permission in the file config/orientdb-server-config.xml"); - } - - protected ODatabaseComplex openDatabase(final ODatabaseComplex database, final String iUser, final String iPassword) { - - if (database.isClosed()) - if (database.getStorage() instanceof OStorageMemory && !database.exists()) - database.create(); - else { - try { - database.open(iUser, iPassword); - } catch (OSecurityException e) { - // TRY WITH SERVER'S USER - try { - connection.serverUser = server.serverLogin(iUser, iPassword, "database.passthrough"); - } catch (OSecurityException ex) { - throw e; - } - - // SERVER AUTHENTICATED, BYPASS SECURITY - database.setProperty(ODatabase.OPTIONS.SECURITY.toString(), Boolean.FALSE); - database.open(iUser, iPassword); - } - } - - return database; - } - - protected void addDataSegment() throws IOException { - setDataCommandInfo("Add data segment"); - - if (!isConnectionAlive()) - return; - - final String name = channel.readString(); - final String location = channel.readString(); - - final int num = connection.database.addDataSegment(name, location); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeInt(num); - } finally { - endResponse(); - } - } - - protected void dropDataSegment() throws IOException { - setDataCommandInfo("Drop data segment"); - - if (!isConnectionAlive()) - return; - - final String name = channel.readString(); - - boolean result = connection.database.dropDataSegment(name); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) (result ? 1 : 0)); - } finally { - endResponse(); - } - } - - protected void removeCluster() throws IOException { - setDataCommandInfo("Remove cluster"); - - if (!isConnectionAlive()) - return; - - final int id = channel.readShort(); - - final String clusterName = connection.database.getClusterNameById(id); - if (clusterName == null) - throw new IllegalArgumentException("Cluster " + id - + " doesn't exist anymore. Refresh the db structure or just reconnect to the database"); - - boolean result = connection.database.dropCluster(clusterName, true); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) (result ? 1 : 0)); - } finally { - endResponse(); - } - } - - protected void addCluster() throws IOException { - setDataCommandInfo("Add cluster"); - - if (!isConnectionAlive()) - return; - - final String type = channel.readString(); - final String name = channel.readString(); - int clusterId = -1; - - final String location; - if (connection.data.protocolVersion >= 10 || type.equalsIgnoreCase("PHYSICAL")) - location = channel.readString(); - else - location = null; - - final String dataSegmentName; - if (connection.data.protocolVersion >= 10) - dataSegmentName = channel.readString(); - else { - channel.readInt(); // OLD INIT SIZE, NOT MORE USED - dataSegmentName = null; - } - - if (connection.data.protocolVersion >= 18) - clusterId = channel.readShort(); - - Object[] params = null; - - final int num; - - if (clusterId < 0) - num = connection.database.addCluster(type, name, location, dataSegmentName, params); - else - num = connection.database.addCluster(type, name, clusterId, location, dataSegmentName, params); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeShort((short) num); - } finally { - endResponse(); - } - } - - protected void rangeCluster() throws IOException { - setDataCommandInfo("Get the begin/end range of data in cluster"); - - if (!isConnectionAlive()) - return; - - OClusterPosition[] pos = connection.database.getStorage().getClusterDataRange(channel.readShort()); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeClusterPosition(pos[0]); - channel.writeClusterPosition(pos[1]); - } finally { - endResponse(); - } - } - - protected void countClusters() throws IOException { - setDataCommandInfo("Count cluster elements"); - - if (!isConnectionAlive()) - return; - - int[] clusterIds = new int[channel.readShort()]; - for (int i = 0; i < clusterIds.length; ++i) - clusterIds[i] = channel.readShort(); - - boolean countTombstones = false; - if (connection.data.protocolVersion >= 13) - countTombstones = channel.readByte() > 0; - - final long count = connection.database.countClusterElements(clusterIds, countTombstones); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeLong(count); - } finally { - endResponse(); - } - } - - protected void reloadDatabase() throws IOException { - setDataCommandInfo("Reload database information"); - - if (!isConnectionAlive()) - return; - - beginResponse(); - try { - sendOk(clientTxId); - - sendDatabaseInformation(); - - } finally { - endResponse(); - } - } - - protected void openDatabase() throws IOException { - setDataCommandInfo("Open database"); - - readConnectionData(); - - final String dbURL = channel.readString(); - - dbType = ODatabaseDocument.TYPE; - if (connection.data.protocolVersion >= 8) - // READ DB-TYPE FROM THE CLIENT - dbType = channel.readString(); - - final String user = channel.readString(); - final String passwd = channel.readString(); - - connection.database = (ODatabaseDocumentTx) server.openDatabase(dbType, dbURL, user, passwd); - connection.rawDatabase = ((ODatabaseComplex) connection.database.getUnderlying()).getUnderlying(); - - if (connection.database.getStorage() instanceof OStorageProxy && !loadUserFromSchema(user, passwd)) { - sendError(clientTxId, new OSecurityAccessException(connection.database.getName(), - "User or password not valid for database: '" + connection.database.getName() + "'")); - } else { - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeInt(connection.id); - - sendDatabaseInformation(); - - final OServerPlugin plugin = server.getPlugin("cluster"); - ODocument distributedCfg = null; - if (plugin != null && plugin instanceof ODistributedServerManager) - distributedCfg = ((ODistributedServerManager) plugin).getClusterConfiguration(); - - channel.writeBytes(distributedCfg != null ? distributedCfg.toStream() : null); - - if (connection.data.protocolVersion >= 14) - channel.writeString(OConstants.getVersion()); - } finally { - endResponse(); - } - } - } - - protected void connect() throws IOException { - setDataCommandInfo("Connect"); - - readConnectionData(); - - connection.serverUser = server.serverLogin(channel.readString(), channel.readString(), "connect"); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeInt(connection.id); - } finally { - endResponse(); - } - } - - protected void shutdownConnection() throws IOException { - setDataCommandInfo("Shutdowning"); - - OLogManager.instance().info(this, "Received shutdown command from the remote client %s:%d", channel.socket.getInetAddress(), - channel.socket.getPort()); - - final String user = channel.readString(); - final String passwd = channel.readString(); - - if (server.authenticate(user, passwd, "shutdown")) { - OLogManager.instance().info(this, "Remote client %s:%d authenticated. Starting shutdown of server...", - channel.socket.getInetAddress(), channel.socket.getPort()); - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - channel.close(); - server.shutdown(); - System.exit(0); - } - - OLogManager.instance().error(this, "Authentication error of remote client %s:%d: shutdown is aborted.", - channel.socket.getInetAddress(), channel.socket.getPort()); - - sendError(clientTxId, new OSecurityAccessException("Invalid user/password to shutdown the server")); - } - - protected void copyDatabase() throws IOException { - setDataCommandInfo("Copy the database to a remote server"); - - final String dbUrl = channel.readString(); - final String dbUser = channel.readString(); - final String dbPassword = channel.readString(); - final String remoteServerName = channel.readString(); - final String remoteServerEngine = channel.readString(); - - checkServerAccess("database.copy"); - - final ODatabaseDocumentTx db = (ODatabaseDocumentTx) server.openDatabase(ODatabaseDocument.TYPE, dbUrl, dbUser, dbPassword); - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void replicationDatabase() throws IOException { - setDataCommandInfo("Replication command"); - - final ODocument request = new ODocument(channel.readBytes()); - - final ODistributedServerManager dManager = server.getDistributedManager(); - if (dManager == null) - throw new OConfigurationException("No distributed manager configured"); - - final String operation = request.field("operation"); - - ODocument response = null; - - if (operation.equals("start")) { - checkServerAccess("server.replication.start"); - - } else if (operation.equals("stop")) { - checkServerAccess("server.replication.stop"); - - } else if (operation.equals("config")) { - checkServerAccess("server.replication.config"); - - response = new ODocument().fromJSON(dManager.getDatabaseConfiguration((String) request.field("db")).serialize() - .toJSON("prettyPrint")); - - } - - sendResponse(response); - - } - - protected void distributedCluster() throws IOException { - setDataCommandInfo("Cluster status"); - - final ODocument req = new ODocument(channel.readBytes()); - - ODocument response = null; - - final String operation = req.field("operation"); - if (operation == null) - throw new IllegalArgumentException("Cluster operation is null"); - - if (operation.equals("status")) { - final OServerPlugin plugin = server.getPlugin("cluster"); - if (plugin != null && plugin instanceof ODistributedServerManager) - response = ((ODistributedServerManager) plugin).getClusterConfiguration(); - } else - throw new IllegalArgumentException("Cluster operation '" + operation + "' is not supported"); - - sendResponse(response); - } - - protected void countDatabaseRecords() throws IOException { - setDataCommandInfo("Database count records"); - - if (!isConnectionAlive()) - return; - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeLong(connection.database.getStorage().countRecords()); - } finally { - endResponse(); - } - } - - protected void sizeDatabase() throws IOException { - setDataCommandInfo("Database size"); - - if (!isConnectionAlive()) - return; - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeLong(connection.database.getStorage().getSize()); - } finally { - endResponse(); - } - } - - protected void dropDatabase() throws IOException { - setDataCommandInfo("Drop database"); - String dbName = channel.readString(); - - String storageType; - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - checkServerAccess("database.delete"); - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Dropped database '%s'", connection.database.getName()); - - if (connection.database.isClosed()) - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - - connection.database.drop(); - connection.close(); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void existsDatabase() throws IOException { - setDataCommandInfo("Exists database"); - final String dbName = channel.readString(); - final String storageType; - - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - checkServerAccess("database.exists"); - - if (storageType != null) - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - else { - // CHECK AGAINST ALL THE ENGINE TYPES, BUT REMOTE - for (String engine : Orient.instance().getEngines()) { - if (!engine.equalsIgnoreCase(OEngineRemote.NAME)) { - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, engine); - if (connection.database.exists()) - // FOUND - break; - - // NOT FOUND: ASSURE TO UNREGISTER IT TO AVOID CACHING - Orient.instance().unregisterStorage(connection.database.getStorage()); - } - } - } - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) (connection.database.exists() ? 1 : 0)); - } finally { - endResponse(); - } - } - - protected void createDatabase() throws IOException { - setDataCommandInfo("Create database"); - - String dbName = channel.readString(); - String dbType = ODatabaseDocument.TYPE; - if (connection.data.protocolVersion >= 8) - // READ DB-TYPE FROM THE CLIENT - dbType = channel.readString(); - String storageType = channel.readString(); - - checkServerAccess("database.create"); - checkStorageExistence(dbName); - connection.database = getDatabaseInstance(dbName, dbType, storageType); - createDatabase(connection.database, null, null); - connection.rawDatabase = (((ODatabaseComplex) connection.database.getUnderlying()).getUnderlying()); - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void closeDatabase() throws IOException { - setDataCommandInfo("Close Database"); - - if (connection != null) { - if (connection.data.protocolVersion > 0 && connection.data.protocolVersion < 9) - // OLD CLIENTS WAIT FOR A OK - sendOk(clientTxId); - - if (OClientConnectionManager.instance().disconnect(connection.id)) - sendShutdown(); - } - } - - protected void configList() throws IOException { - setDataCommandInfo("List config"); - - checkServerAccess("server.config.get"); - - beginResponse(); - try { - sendOk(clientTxId); - - channel.writeShort((short) OGlobalConfiguration.values().length); - for (OGlobalConfiguration cfg : OGlobalConfiguration.values()) { - - String key; - try { - key = cfg.getKey(); - } catch (Exception e) { - key = "?"; - } - - String value; - try { - value = cfg.getValueAsString() != null ? cfg.getValueAsString() : ""; - } catch (Exception e) { - value = ""; - } - - channel.writeString(key); - channel.writeString(value); - } - } finally { - endResponse(); - } - } - - protected void configSet() throws IOException { - setDataCommandInfo("Get config"); - - checkServerAccess("server.config.set"); - - final String key = channel.readString(); - final String value = channel.readString(); - final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(key); - if (cfg != null) - cfg.setValue(value); - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void configGet() throws IOException { - setDataCommandInfo("Get config"); - - checkServerAccess("server.config.get"); - - final String key = channel.readString(); - final OGlobalConfiguration cfg = OGlobalConfiguration.findByKey(key); - String cfgValue = cfg != null ? cfg.getValueAsString() : ""; - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeString(cfgValue); - } finally { - endResponse(); - } - } - - protected void commit() throws IOException { - setDataCommandInfo("Transaction commit"); - - if (!isConnectionAlive()) - return; - - final OTransactionOptimisticProxy tx = new OTransactionOptimisticProxy((ODatabaseRecordTx) connection.database.getUnderlying(), - channel); - - try { - connection.database.begin(tx); - - try { - connection.database.commit(); - beginResponse(); - try { - sendOk(clientTxId); - - // SEND BACK ALL THE RECORD IDS FOR THE CREATED RECORDS - channel.writeInt(tx.getCreatedRecords().size()); - for (Entry> entry : tx.getCreatedRecords().entrySet()) { - channel.writeRID(entry.getKey()); - channel.writeRID(entry.getValue().getIdentity()); - - // IF THE NEW OBJECT HAS VERSION > 0 MEANS THAT HAS BEEN UPDATED IN THE SAME TX. THIS HAPPENS FOR GRAPHS - if (entry.getValue().getRecordVersion().getCounter() > 0) - tx.getUpdatedRecords().put((ORecordId) entry.getValue().getIdentity(), entry.getValue()); - } - - // SEND BACK ALL THE NEW VERSIONS FOR THE UPDATED RECORDS - channel.writeInt(tx.getUpdatedRecords().size()); - for (Entry> entry : tx.getUpdatedRecords().entrySet()) { - channel.writeRID(entry.getKey()); - channel.writeVersion(entry.getValue().getRecordVersion()); - } - - if (connection.data.protocolVersion >= 20) - sendCollectionChanges(); - } finally { - endResponse(); - } - } catch (Exception e) { - if (connection.database != null) { - if (connection.database.getTransaction().isActive()) - connection.database.rollback(true); - } - sendError(clientTxId, e); - } - } catch (OTransactionAbortedException e) { - // TX ABORTED BY THE CLIENT - } catch (Exception e) { - // Error during TX initialization, possibly index constraints violation. - if (tx.isActive()) - tx.rollback(true, -1); - - sendError(clientTxId, e); - } - } - - protected void command() throws IOException { - setDataCommandInfo("Execute remote command"); - - final boolean asynch = channel.readByte() == 'a'; - - final OCommandRequestText command = (OCommandRequestText) OStreamSerializerAnyStreamable.INSTANCE.fromStream(channel - .readBytes()); - - connection.data.commandDetail = command.getText(); - - // ENABLES THE CACHE TO IMPROVE PERFORMANCE OF COMPLEX COMMANDS LIKE TRAVERSE - // connection.database.getLevel1Cache().setEnable(true); - beginResponse(); - try { - final OAbstractCommandResultListener listener; - - if (asynch) { - listener = new OAsyncCommandResultListener(this, clientTxId); - command.setResultListener(listener); - } else - listener = new OSyncCommandResultListener(); - - final long serverTimeout = OGlobalConfiguration.COMMAND_TIMEOUT.getValueAsLong(); - - if (serverTimeout > 0 && command.getTimeoutTime() > serverTimeout) - // FORCE THE SERVER'S TIMEOUT - command.setTimeout(serverTimeout, command.getTimeoutStrategy()); - - if (!isConnectionAlive()) - return; - - // ASSIGNED THE PARSED FETCHPLAN - listener.setFetchPlan(connection.database.command(command).getFetchPlan()); - - final Object result = connection.database.command(command).execute(); - - // FETCHPLAN HAS TO BE ASSIGNED AGAIN, because it can be changed by SQL statement - listener.setFetchPlan(command.getFetchPlan()); - - if (asynch) { - // ASYNCHRONOUS - if (listener.isEmpty()) - try { - sendOk(clientTxId); - } catch (IOException ignored) { - } - channel.writeByte((byte) 0); // NO MORE RECORDS - - } else { - // SYNCHRONOUS - sendOk(clientTxId); - - if (result == null) { - // NULL VALUE - channel.writeByte((byte) 'n'); - } else if (result instanceof OIdentifiable) { - // RECORD - channel.writeByte((byte) 'r'); - listener.result(result); - writeIdentifiable((OIdentifiable) result); - } else if (OMultiValue.isMultiValue(result)) { - channel.writeByte((byte) 'l'); - channel.writeInt(OMultiValue.getSize(result)); - for (Object o : OMultiValue.getMultiValueIterable(result)) { - try { - listener.result(o); - writeIdentifiable((OIdentifiable) o); - } catch (Exception e) { - OLogManager.instance().warn(this, "Cannot serialize record: " + o); - // WRITE NULL RECORD TO AVOID BREAKING PROTOCOL - writeIdentifiable(null); - } - } - } else { - // ANY OTHER (INCLUDING LITERALS) - channel.writeByte((byte) 'a'); - final StringBuilder value = new StringBuilder(); - listener.result(result); - ORecordSerializerStringAbstract.fieldTypeToString(value, OType.getTypeByClass(result.getClass()), result); - channel.writeString(value.toString()); - } - - if (connection.data.protocolVersion >= 17) { - // SEND FETCHED RECORDS TO LOAD IN CLIENT CACHE - for (ORecord rec : ((OSyncCommandResultListener) listener).getFetchedRecordsToSend()) { - channel.writeByte((byte) 2); // CLIENT CACHE RECORD. IT - // ISN'T PART OF THE - // RESULT SET - writeIdentifiable(rec); - } - - channel.writeByte((byte) 0); // NO MORE RECORDS - } - } - - } finally { - endResponse(); - } - } - - protected void deleteRecord() throws IOException { - setDataCommandInfo("Delete record"); - - if (!isConnectionAlive()) - return; - - final ORID rid = channel.readRID(); - final ORecordVersion version = channel.readVersion(); - final byte mode = channel.readByte(); - - final int result = deleteRecord(connection.database, rid, version); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) result); - } finally { - endResponse(); - } - } - } - - protected void hideRecord() throws IOException { - setDataCommandInfo("Hide record"); - - if (!isConnectionAlive()) - return; - - final ORID rid = channel.readRID(); - final byte mode = channel.readByte(); - - final int result = hideRecord(connection.database, rid); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) result); - } finally { - endResponse(); - } - } - } - - protected void cleanOutRecord() throws IOException { - setDataCommandInfo("Clean out record"); - - if (!isConnectionAlive()) - return; - - final ORID rid = channel.readRID(); - final ORecordVersion version = channel.readVersion(); - final byte mode = channel.readByte(); - - final int result = cleanOutRecord(connection.database, rid, version); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) result); - } finally { - endResponse(); - } - } - } - - /** - * VERSION MANAGEMENT:
- * -1 : DOCUMENT UPDATE, NO VERSION CONTROL
- * -2 : DOCUMENT UPDATE, NO VERSION CONTROL, NO VERSION INCREMENT
- * -3 : DOCUMENT ROLLBACK, DECREMENT VERSION
- * >-1 : MVCC CONTROL, RECORD UPDATE AND VERSION INCREMENT
- * <-3 : WRONG VERSION VALUE - * - * @throws IOException - */ - protected void updateRecord() throws IOException { - setDataCommandInfo("Update record"); - - if (!isConnectionAlive()) - return; - - final ORecordId rid = channel.readRID(); - final byte[] buffer = channel.readBytes(); - final ORecordVersion version = channel.readVersion(); - final byte recordType = channel.readByte(); - final byte mode = channel.readByte(); - - final ORecordVersion newVersion = updateRecord(connection.database, rid, buffer, version, recordType); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeVersion(newVersion); - - if (connection.data.protocolVersion >= 20) - sendCollectionChanges(); - } finally { - endResponse(); - } - } - } - - protected void createRecord() throws IOException { - setDataCommandInfo("Create record"); - - if (!isConnectionAlive()) - return; - - final int dataSegmentId = connection.data.protocolVersion >= 10 ? channel.readInt() : 0; - final ORecordId rid = new ORecordId(channel.readShort(), ORID.CLUSTER_POS_INVALID); - final byte[] buffer = channel.readBytes(); - final byte recordType = channel.readByte(); - final byte mode = channel.readByte(); - - final ORecord record = createRecord(connection.database, rid, buffer, recordType, dataSegmentId); - - if (mode < 2) { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeClusterPosition(record.getIdentity().getClusterPosition()); - if (connection.data.protocolVersion >= 11) - channel.writeVersion(record.getRecordVersion()); - - if (connection.data.protocolVersion >= 20) - sendCollectionChanges(); - } finally { - endResponse(); - } - } - } - - protected void readRecordMetadata() throws IOException { - setDataCommandInfo("Record metadata"); - - final ORID rid = channel.readRID(); - - beginResponse(); - try { - final ORecordMetadata metadata = connection.database.getRecordMetadata(rid); - sendOk(clientTxId); - channel.writeRID(metadata.getRecordId()); - channel.writeVersion(metadata.getRecordVersion()); - } finally { - endResponse(); - } - } - - protected void readRecord() throws IOException { - setDataCommandInfo("Load record"); - - if (!isConnectionAlive()) - return; - - final ORecordId rid = channel.readRID(); - final String fetchPlanString = channel.readString(); - boolean ignoreCache = false; - if (connection.data.protocolVersion >= 9) - ignoreCache = channel.readByte() == 1; - - boolean loadTombstones = false; - if (connection.data.protocolVersion >= 13) - loadTombstones = channel.readByte() > 0; - - if (rid.clusterId == 0 && rid.clusterPosition.longValue() == 0) { - // @COMPATIBILITY 0.9.25 - // SEND THE DB CONFIGURATION INSTEAD SINCE IT WAS ON RECORD 0:0 - OFetchHelper.checkFetchPlanValid(fetchPlanString); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeByte((byte) 1); - channel.writeBytes(connection.database.getStorage().getConfiguration().toStream()); - channel.writeVersion(OVersionFactory.instance().createVersion()); - channel.writeByte(ORecordBytes.RECORD_TYPE); - channel.writeByte((byte) 0); // NO MORE RECORDS - } finally { - endResponse(); - } - - } else { - final ORecordInternal record = connection.database.load(rid, fetchPlanString, ignoreCache, loadTombstones, - OStorage.LOCKING_STRATEGY.DEFAULT); - - beginResponse(); - try { - sendOk(clientTxId); - - if (record != null) { - channel.writeByte((byte) 1); // HAS RECORD - channel.writeBytes(record.toStream()); - channel.writeVersion(record.getRecordVersion()); - channel.writeByte(record.getRecordType()); - - if (fetchPlanString.length() > 0) { - // BUILD THE SERVER SIDE RECORD TO ACCES TO THE FETCH - // PLAN - if (record instanceof ODocument) { - final Map fetchPlan = OFetchHelper.buildFetchPlan(fetchPlanString); - - final Set> recordsToSend = new HashSet>(); - final ODocument doc = (ODocument) record; - final OFetchListener listener = new ORemoteFetchListener() { - @Override - protected void sendRecord(ORecord iLinked) { - recordsToSend.add(iLinked); - } - }; - final OFetchContext context = new ORemoteFetchContext(); - OFetchHelper.fetch(doc, doc, fetchPlan, listener, context, ""); - - // SEND RECORDS TO LOAD IN CLIENT CACHE - for (ORecord d : recordsToSend) { - if (d.getIdentity().isValid()) { - channel.writeByte((byte) 2); // CLIENT CACHE - // RECORD. IT ISN'T PART OF THE RESULT SET - writeIdentifiable(d); - } - } - } - - } - } - channel.writeByte((byte) 0); // NO MORE RECORDS - - } finally { - endResponse(); - } - } - } - - protected void beginResponse() { - channel.acquireWriteLock(); - } - - protected void endResponse() throws IOException { - // resetting transaction state. Commands are stateless and connection should be cleared - // otherwise reused connection (connections pool) may lead to unpredicted errors - if (connection != null && connection.database != null && connection.database.getTransaction() != null) - connection.database.getTransaction().rollback(); - channel.flush(); - channel.releaseWriteLock(); - } - - protected void setDataCommandInfo(final String iCommandInfo) { - if (connection != null) - connection.data.commandInfo = iCommandInfo; - } - - protected void readConnectionData() throws IOException { - connection.data.driverName = channel.readString(); - connection.data.driverVersion = channel.readString(); - connection.data.protocolVersion = channel.readShort(); - connection.data.clientId = channel.readString(); - } - - protected void sendOk(final int iClientTxId) throws IOException { - channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_OK); - channel.writeInt(iClientTxId); - } - - protected void sendError(final int iClientTxId, final Throwable t) throws IOException { - channel.acquireWriteLock(); - try { - - channel.writeByte(OChannelBinaryProtocol.RESPONSE_STATUS_ERROR); - channel.writeInt(iClientTxId); - - Throwable current; - if (t instanceof OLockException && t.getCause() instanceof ODatabaseException) - // BYPASS THE DB POOL EXCEPTION TO PROPAGATE THE RIGHT SECURITY ONE - current = t.getCause(); - else - current = t; - - final Throwable original = current; - while (current != null) { - // MORE DETAILS ARE COMING AS EXCEPTION - channel.writeByte((byte) 1); - - channel.writeString(current.getClass().getName()); - channel.writeString(current.getMessage()); - - current = current.getCause(); - } - channel.writeByte((byte) 0); - - if (connection != null && connection.data.protocolVersion >= 19) { - final OMemoryStream memoryStream = new OMemoryStream(); - final ObjectOutputStream objectOutputStream = new ObjectOutputStream(memoryStream); - - objectOutputStream.writeObject(original); - objectOutputStream.flush(); - - final byte[] result = memoryStream.toByteArray(); - objectOutputStream.close(); - - channel.writeBytes(result); - } - - channel.flush(); - - if (OLogManager.instance().isLevelEnabled(logClientExceptions)) { - if (logClientFullStackTrace) - OLogManager.instance().log(this, logClientExceptions, "Sent run-time exception to the client %s: %s", t, - channel.socket.getRemoteSocketAddress(), t.toString()); - else - OLogManager.instance().log(this, logClientExceptions, "Sent run-time exception to the client %s: %s", null, - channel.socket.getRemoteSocketAddress(), t.toString()); - } - } catch (Exception e) { - if (e instanceof SocketException) - shutdown(); - } finally { - channel.releaseWriteLock(); - } - } - - @Override - protected void handleConnectionError(final OChannelBinaryServer iChannel, final Throwable e) { - super.handleConnectionError(channel, e); - OServerPluginHelper.invokeHandlerCallbackOnClientError(server, connection, e); - } - - protected void sendResponse(final ODocument iResponse) throws IOException { - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(iResponse != null ? iResponse.toStream() : null); - } finally { - endResponse(); - } - } - - protected void freezeDatabase() throws IOException { - setDataCommandInfo("Freeze database"); - String dbName = channel.readString(); - - checkServerAccess("database.freeze"); - - final String storageType; - - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Freezing database '%s'", connection.database.getURL()); - - if (connection.database.isClosed()) - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - - connection.database.freeze(true); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void releaseDatabase() throws IOException { - setDataCommandInfo("Release database"); - String dbName = channel.readString(); - - checkServerAccess("database.release"); - - final String storageType; - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Realising database '%s'", connection.database.getURL()); - - if (connection.database.isClosed()) - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - - connection.database.release(); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void freezeCluster() throws IOException { - setDataCommandInfo("Freeze cluster"); - final String dbName = channel.readString(); - final int clusterId = channel.readShort(); - - checkServerAccess("database.freeze"); - - final String storageType; - - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Freezing database '%s' cluster %d", connection.database.getURL(), clusterId); - - if (connection.database.isClosed()) { - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - } - - connection.database.freezeCluster(clusterId); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - protected void releaseCluster() throws IOException { - setDataCommandInfo("Release database"); - final String dbName = channel.readString(); - final int clusterId = channel.readShort(); - - checkServerAccess("database.release"); - - final String storageType; - if (connection.data.protocolVersion >= 16) - storageType = channel.readString(); - else - storageType = "local"; - - connection.database = getDatabaseInstance(dbName, ODatabaseDocument.TYPE, storageType); - - if (connection.database.exists()) { - OLogManager.instance().info(this, "Realising database '%s' cluster %d", connection.database.getURL(), clusterId); - - if (connection.database.isClosed()) { - openDatabase(connection.database, connection.serverUser.name, connection.serverUser.password); - } - - connection.database.releaseCluster(clusterId); - } else { - throw new OStorageException("Database with name '" + dbName + "' doesn't exits."); - } - - beginResponse(); - try { - sendOk(clientTxId); - } finally { - endResponse(); - } - } - - private void ridBagSize() throws IOException { - setDataCommandInfo("RidBag get size"); - - OBonsaiCollectionPointer collectionPointer = OCollectionNetworkSerializer.INSTANCE.readCollectionPointer(channel); - final byte[] changeStream = channel.readBytes(); - - OSBTreeBonsai tree = connection.database.getSbTreeCollectionManager().loadSBTree(collectionPointer); - final Map changes = OSBTreeRidBag.ChangeSerializationHelper.INSTANCE.deserializeChanges( - changeStream, 0); - - int realSize = tree.getRealBagSize(changes); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeInt(realSize); - } finally { - endResponse(); - } - } - - private void sbTreeBonsaiGetEntriesMajor() throws IOException { - setDataCommandInfo("SB-Tree bonsai get values major"); - - OBonsaiCollectionPointer collectionPointer = OCollectionNetworkSerializer.INSTANCE.readCollectionPointer(channel); - byte[] keyStream = channel.readBytes(); - boolean inclusive = channel.readBoolean(); - int pageSize = 128; - - if (connection.data.protocolVersion>=21) - pageSize = channel.readInt(); - - OSBTreeBonsai tree = connection.database.getSbTreeCollectionManager().loadSBTree(collectionPointer); - - final OBinarySerializer keySerializer = tree.getKeySerializer(); - OIdentifiable key = keySerializer.deserialize(keyStream, 0); - - final OBinarySerializer valueSerializer = tree.getValueSerializer(); - - OTreeInternal.AccumulativeListener listener = new OTreeInternal.AccumulativeListener( - pageSize); - tree.loadEntriesMajor(key, inclusive, true, listener); - List> result = listener.getResult(); - byte[] stream = serializeSBTreeEntryCollection(result, keySerializer, valueSerializer); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(stream); - } finally { - endResponse(); - } - } - - private byte[] serializeSBTreeEntryCollection(List> collection, - OBinarySerializer keySerializer, OBinarySerializer valueSerializer) { - byte[] stream = new byte[OIntegerSerializer.INT_SIZE + collection.size() - * (keySerializer.getFixedLength() + valueSerializer.getFixedLength())]; - int offset = 0; - - OIntegerSerializer.INSTANCE.serialize(collection.size(), stream, offset); - offset += OIntegerSerializer.INT_SIZE; - - for (Entry entry : collection) { - keySerializer.serialize(entry.getKey(), stream, offset); - offset += keySerializer.getObjectSize(entry.getKey()); - - valueSerializer.serialize(entry.getValue(), stream, offset); - offset += valueSerializer.getObjectSize(entry.getValue()); - } - return stream; - } - - private void sbTreeBonsaiFirstKey() throws IOException { - setDataCommandInfo("SB-Tree bonsai get first key"); - - OBonsaiCollectionPointer collectionPointer = OCollectionNetworkSerializer.INSTANCE.readCollectionPointer(channel); - OSBTreeBonsai tree = connection.database.getSbTreeCollectionManager().loadSBTree(collectionPointer); - - OIdentifiable result = tree.firstKey(); - final OBinarySerializer keySerializer; - if (result == null) { - keySerializer = ONullSerializer.INSTANCE; - } else { - keySerializer = tree.getKeySerializer(); - } - - byte[] stream = new byte[OByteSerializer.BYTE_SIZE + keySerializer.getObjectSize(result)]; - OByteSerializer.INSTANCE.serialize(keySerializer.getId(), stream, 0); - keySerializer.serialize(result, stream, OByteSerializer.BYTE_SIZE); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(stream); - } finally { - endResponse(); - } - } - - private void sbTreeBonsaiGet() throws IOException { - setDataCommandInfo("SB-Tree bonsai get"); - - OBonsaiCollectionPointer collectionPointer = OCollectionNetworkSerializer.INSTANCE.readCollectionPointer(channel); - final byte[] keyStream = channel.readBytes(); - - OSBTreeBonsai tree = connection.database.getSbTreeCollectionManager().loadSBTree(collectionPointer); - - final OIdentifiable key = tree.getKeySerializer().deserialize(keyStream, 0); - - Integer result = tree.get(key); - final OBinarySerializer valueSerializer; - if (result == null) { - valueSerializer = ONullSerializer.INSTANCE; - } else { - valueSerializer = tree.getValueSerializer(); - } - - byte[] stream = new byte[OByteSerializer.BYTE_SIZE + valueSerializer.getObjectSize(result)]; - OByteSerializer.INSTANCE.serialize(valueSerializer.getId(), stream, 0); - valueSerializer.serialize(result, stream, OByteSerializer.BYTE_SIZE); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(stream); - } finally { - endResponse(); - } - } - - private void createSBTreeBonsai() throws IOException { - setDataCommandInfo("Create SB-Tree bonsai instance"); - - int clusterId = channel.readInt(); - - OBonsaiCollectionPointer collectionPointer = connection.database.getSbTreeCollectionManager().createSBTree(clusterId, null); - - beginResponse(); - try { - sendOk(clientTxId); - OCollectionNetworkSerializer.INSTANCE.writeCollectionPointer(channel, collectionPointer); - } finally { - endResponse(); - } - } - - private void lowerPositions() throws IOException { - setDataCommandInfo("Retrieve lower positions"); - - final int clusterId = channel.readInt(); - final OClusterPosition clusterPosition = channel.readClusterPosition(); - - beginResponse(); - try { - sendOk(clientTxId); - - final OPhysicalPosition[] previousPositions = connection.database.getStorage().lowerPhysicalPositions(clusterId, - new OPhysicalPosition(clusterPosition)); - - if (previousPositions != null) { - channel.writeInt(previousPositions.length); - - for (final OPhysicalPosition physicalPosition : previousPositions) { - channel.writeClusterPosition(physicalPosition.clusterPosition); - channel.writeInt(physicalPosition.dataSegmentId); - channel.writeLong(physicalPosition.dataSegmentPos); - channel.writeInt(physicalPosition.recordSize); - channel.writeVersion(physicalPosition.recordVersion); - } - - } else { - channel.writeInt(0); // NO MORE RECORDS - } - - } finally { - endResponse(); - } - } - - private void floorPositions() throws IOException { - setDataCommandInfo("Retrieve floor positions"); - - final int clusterId = channel.readInt(); - final OClusterPosition clusterPosition = channel.readClusterPosition(); - - beginResponse(); - try { - sendOk(clientTxId); - - final OPhysicalPosition[] previousPositions = connection.database.getStorage().floorPhysicalPositions(clusterId, - new OPhysicalPosition(clusterPosition)); - - if (previousPositions != null) { - channel.writeInt(previousPositions.length); - - for (final OPhysicalPosition physicalPosition : previousPositions) { - channel.writeClusterPosition(physicalPosition.clusterPosition); - channel.writeInt(physicalPosition.dataSegmentId); - channel.writeLong(physicalPosition.dataSegmentPos); - channel.writeInt(physicalPosition.recordSize); - channel.writeVersion(physicalPosition.recordVersion); - } - - } else { - channel.writeInt(0); // NO MORE RECORDS - } - - } finally { - endResponse(); - } - } - - private void higherPositions() throws IOException { - setDataCommandInfo("Retrieve higher positions"); - - final int clusterId = channel.readInt(); - final OClusterPosition clusterPosition = channel.readClusterPosition(); - - beginResponse(); - try { - sendOk(clientTxId); - - OPhysicalPosition[] nextPositions = connection.database.getStorage().higherPhysicalPositions(clusterId, - new OPhysicalPosition(clusterPosition)); - - if (nextPositions != null) { - - channel.writeInt(nextPositions.length); - for (final OPhysicalPosition physicalPosition : nextPositions) { - channel.writeClusterPosition(physicalPosition.clusterPosition); - channel.writeInt(physicalPosition.dataSegmentId); - channel.writeLong(physicalPosition.dataSegmentPos); - channel.writeInt(physicalPosition.recordSize); - channel.writeVersion(physicalPosition.recordVersion); - } - } else { - channel.writeInt(0); // NO MORE RECORDS - } - } finally { - endResponse(); - } - } - - private void ceilingPositions() throws IOException { - setDataCommandInfo("Retrieve ceiling positions"); - - final int clusterId = channel.readInt(); - final OClusterPosition clusterPosition = channel.readClusterPosition(); - - beginResponse(); - try { - sendOk(clientTxId); - - final OPhysicalPosition[] previousPositions = connection.database.getStorage().ceilingPhysicalPositions(clusterId, - new OPhysicalPosition(clusterPosition)); - - if (previousPositions != null) { - channel.writeInt(previousPositions.length); - - for (final OPhysicalPosition physicalPosition : previousPositions) { - channel.writeClusterPosition(physicalPosition.clusterPosition); - channel.writeInt(physicalPosition.dataSegmentId); - channel.writeLong(physicalPosition.dataSegmentPos); - channel.writeInt(physicalPosition.recordSize); - channel.writeVersion(physicalPosition.recordVersion); - } - - } else { - channel.writeInt(0); // NO MORE RECORDS - } - - } finally { - endResponse(); - } - } - - private boolean isConnectionAlive() { - if (connection == null || connection.database == null) { - // CONNECTION/DATABASE CLOSED, KILL IT - OClientConnectionManager.instance().kill(connection); - return false; - } - return true; - } - - private void sendCollectionChanges() throws IOException { - OSBTreeCollectionManager collectionManager = connection.database.getSbTreeCollectionManager(); - if (collectionManager != null) { - Map changedIds = collectionManager.changedIds(); - - channel.writeInt(changedIds.size()); - - for (Entry entry : changedIds.entrySet()) { - UUID id = entry.getKey(); - channel.writeLong(id.getMostSignificantBits()); - channel.writeLong(id.getLeastSignificantBits()); - - OCollectionNetworkSerializer.INSTANCE.writeCollectionPointer(channel, entry.getValue()); - } - } - collectionManager.clearChangedIds(); - } - - private void sendDatabaseInformation() throws IOException { - final Collection clusters = connection.database.getStorage().getClusterInstances(); - int clusterCount = 0; - for (OCluster c : clusters) { - if (c != null) { - ++clusterCount; - } - } - if (connection.data.protocolVersion >= 7) - channel.writeShort((short) clusterCount); - else - channel.writeInt(clusterCount); - - for (OCluster c : clusters) { - if (c != null) { - channel.writeString(c.getName()); - channel.writeShort((short) c.getId()); - channel.writeString(c.getType()); - if (connection.data.protocolVersion >= 12) - channel.writeShort((short) c.getDataSegmentId()); - } - } - } - - private void listDatabases() throws IOException { - checkServerAccess("server.dblist"); - final ODocument result = new ODocument(); - result.field("databases", server.getAvailableStorageNames()); - - setDataCommandInfo("List databases"); - - beginResponse(); - try { - sendOk(clientTxId); - channel.writeBytes(result.toStream()); - } finally { - endResponse(); - } - } - - private boolean loadUserFromSchema(final String iUserName, final String iUserPassword) { - account = connection.database.getMetadata().getSecurity().authenticate(iUserName, iUserPassword); - return true; - } -} diff --git a/All/Genesis-NP/Genesis#418/pair.info b/All/Genesis-NP/Genesis#418/pair.info deleted file mode 100755 index 3b9fe2d..0000000 --- a/All/Genesis-NP/Genesis#418/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:418 -SATName:Genesis -modifiedFPath:server/src/main/java/com/orientechnologies/orient/server/network/protocol/binary/ONetworkProtocolBinary.java -comSha:177d0228fccc159dbfe30d44ffe9ae16961ba67c -parentComSha:177d0228fccc159dbfe30d44ffe9ae16961ba67c^1 -githubUrl:https://github.com/orientechnologies/orientdb -repoName:orientechnologies#orientdb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#419/comMsg.txt b/All/Genesis-NP/Genesis#419/comMsg.txt deleted file mode 100755 index 0a8cc23..0000000 --- a/All/Genesis-NP/Genesis#419/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix NPE diff --git a/All/Genesis-NP/Genesis#419/diff.diff b/All/Genesis-NP/Genesis#419/diff.diff deleted file mode 100755 index 0dd3f5e..0000000 --- a/All/Genesis-NP/Genesis#419/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/disconf-client/src/main/java/com/baidu/disconf/client/common/constants/SupportFileTypeEnum.java b/disconf-client/src/main/java/com/baidu/disconf/client/common/constants/SupportFileTypeEnum.java -index 39f0018..87ac28d 100644 ---- a/disconf-client/src/main/java/com/baidu/disconf/client/common/constants/SupportFileTypeEnum.java -+++ b/disconf-client/src/main/java/com/baidu/disconf/client/common/constants/SupportFileTypeEnum.java -@@ -33 +33 @@ public enum SupportFileTypeEnum { -- return null; -+ return SupportFileTypeEnum.ANY; diff --git a/All/Genesis-NP/Genesis#419/new/SupportFileTypeEnum.java b/All/Genesis-NP/Genesis#419/new/SupportFileTypeEnum.java deleted file mode 100755 index 87ac28d..0000000 --- a/All/Genesis-NP/Genesis#419/new/SupportFileTypeEnum.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.baidu.disconf.client.common.constants; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; - -/** - * 支持的文件后缀类型 - * - * @author knightliao - */ -public enum SupportFileTypeEnum { - - /** - * 支持properties 特殊处理,支持非properties任意处理 - */ - PROPERTIES(0, "properties"), XML(1, "xml"), ANY(3, "*"); - - private int type = 0; - private String modelName = null; - - private SupportFileTypeEnum(int type, String modelName) { - this.type = type; - this.modelName = modelName; - } - - /** - * 根据文件名返回其文件后缀ENUM - */ - public static SupportFileTypeEnum getByFileName(String fileName) { - - String extension = FilenameUtils.getExtension(fileName); - if (StringUtils.isEmpty(extension)) { - return SupportFileTypeEnum.ANY; - } - - for (SupportFileTypeEnum supportFileTypeEnum : SupportFileTypeEnum.values()) { - - if (extension.equals(supportFileTypeEnum.modelName)) { - return supportFileTypeEnum; - } - } - - return SupportFileTypeEnum.ANY; - } - - public static SupportFileTypeEnum getByType(int type) { - - int index = 0; - for (SupportFileTypeEnum supportFileTypeEnum : SupportFileTypeEnum.values()) { - - if (type == index) { - return supportFileTypeEnum; - } - - index++; - } - - return null; - } - - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - - public String getModelName() { - return modelName; - } - - public void setModelName(String modelName) { - this.modelName = modelName; - } - -} diff --git a/All/Genesis-NP/Genesis#419/old/SupportFileTypeEnum.java b/All/Genesis-NP/Genesis#419/old/SupportFileTypeEnum.java deleted file mode 100755 index 39f0018..0000000 --- a/All/Genesis-NP/Genesis#419/old/SupportFileTypeEnum.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.baidu.disconf.client.common.constants; - -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; - -/** - * 支持的文件后缀类型 - * - * @author knightliao - */ -public enum SupportFileTypeEnum { - - /** - * 支持properties 特殊处理,支持非properties任意处理 - */ - PROPERTIES(0, "properties"), XML(1, "xml"), ANY(3, "*"); - - private int type = 0; - private String modelName = null; - - private SupportFileTypeEnum(int type, String modelName) { - this.type = type; - this.modelName = modelName; - } - - /** - * 根据文件名返回其文件后缀ENUM - */ - public static SupportFileTypeEnum getByFileName(String fileName) { - - String extension = FilenameUtils.getExtension(fileName); - if (StringUtils.isEmpty(extension)) { - return null; - } - - for (SupportFileTypeEnum supportFileTypeEnum : SupportFileTypeEnum.values()) { - - if (extension.equals(supportFileTypeEnum.modelName)) { - return supportFileTypeEnum; - } - } - - return SupportFileTypeEnum.ANY; - } - - public static SupportFileTypeEnum getByType(int type) { - - int index = 0; - for (SupportFileTypeEnum supportFileTypeEnum : SupportFileTypeEnum.values()) { - - if (type == index) { - return supportFileTypeEnum; - } - - index++; - } - - return null; - } - - public int getType() { - return type; - } - - public void setType(int type) { - this.type = type; - } - - public String getModelName() { - return modelName; - } - - public void setModelName(String modelName) { - this.modelName = modelName; - } - -} diff --git a/All/Genesis-NP/Genesis#419/pair.info b/All/Genesis-NP/Genesis#419/pair.info deleted file mode 100755 index 2179e21..0000000 --- a/All/Genesis-NP/Genesis#419/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:419 -SATName:Genesis -modifiedFPath:disconf-client/src/main/java/com/baidu/disconf/client/common/constants/SupportFileTypeEnum.java -comSha:58c725e8aed827a23adf293e9b344eb250b56626 -parentComSha:58c725e8aed827a23adf293e9b344eb250b56626^1 -githubUrl:https://github.com/knightliao/disconf -repoName:knightliao#disconf \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#427/comMsg.txt b/All/Genesis-NP/Genesis#427/comMsg.txt deleted file mode 100755 index 4aad097..0000000 --- a/All/Genesis-NP/Genesis#427/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix for #951, NPE diff --git a/All/Genesis-NP/Genesis#427/diff.diff b/All/Genesis-NP/Genesis#427/diff.diff deleted file mode 100755 index 8d1dc3e..0000000 --- a/All/Genesis-NP/Genesis#427/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/listing/ApiListingResource.java b/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/listing/ApiListingResource.java -index 54a391e..35a9e3f 100644 ---- a/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/listing/ApiListingResource.java -+++ b/modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/listing/ApiListingResource.java -@@ -18 +18,2 @@ import javax.ws.rs.core.*; --import java.util.Set; -+import java.util.HashMap; -+import java.util.HashSet; -@@ -21 +22 @@ import java.util.Map; --import java.util.HashMap; -+import java.util.Set; -@@ -40 +41 @@ public class ApiListingResource { -- Set> classes = null; -+ Set> classes = new HashSet>(); diff --git a/All/Genesis-NP/Genesis#427/new/ApiListingResource.java b/All/Genesis-NP/Genesis#427/new/ApiListingResource.java deleted file mode 100755 index 35a9e3f..0000000 --- a/All/Genesis-NP/Genesis#427/new/ApiListingResource.java +++ /dev/null @@ -1,172 +0,0 @@ -package com.wordnik.swagger.jaxrs.listing; - -import com.wordnik.swagger.config.*; -import com.wordnik.swagger.core.filter.*; -import com.wordnik.swagger.jaxrs.Reader; -import com.wordnik.swagger.jaxrs.config.*; -import com.wordnik.swagger.util.*; -import com.wordnik.swagger.models.Swagger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.ws.rs.*; -import javax.ws.rs.core.*; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -@Path("/") -public class ApiListingResource { - Logger LOGGER = LoggerFactory.getLogger(ApiListingResource.class); - - static boolean initialized = false; - @Context - ServletContext context; - - protected synchronized Swagger scan (Application app, ServletConfig sc) { - Swagger swagger = null; - Scanner scanner = ScannerFactory.getScanner(); - LOGGER.debug("using scanner " + scanner); - - if(scanner != null) { - SwaggerSerializers.setPrettyPrint(scanner.getPrettyPrint()); - swagger = (Swagger)context.getAttribute("swagger"); - - Set> classes = new HashSet>(); - if (scanner instanceof JaxrsScanner) { - JaxrsScanner jaxrsScanner = (JaxrsScanner)scanner; - classes = jaxrsScanner.classesFromContext(app, sc); - } - else { - classes = scanner.classes(); - } - if(classes != null) { - Reader reader = new Reader(swagger); - swagger = reader.read(classes); - if(scanner instanceof SwaggerConfig) - swagger = ((SwaggerConfig)scanner).configure(swagger); - else { - SwaggerConfig configurator = (SwaggerConfig)context.getAttribute("reader"); - if(configurator != null) { - LOGGER.debug("configuring swagger with " + configurator); - configurator.configure(swagger); - } - else - LOGGER.debug("no configurator"); - } - context.setAttribute("swagger", swagger); - } - } - initialized = true; - return swagger; - } - - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("/swagger.json") - public Response getListingJson( - @Context Application app, - @Context ServletConfig sc, - @Context HttpHeaders headers, - @Context UriInfo uriInfo) { - Swagger swagger = (Swagger) context.getAttribute("swagger"); - if(!initialized) - swagger = scan(app, sc); - if(swagger != null) { - SwaggerSpecFilter filterImpl = FilterFactory.getFilter(); - if(filterImpl != null) { - SpecFilter f = new SpecFilter(); - swagger = f.filter(swagger, - filterImpl, - getQueryParams(uriInfo.getQueryParameters()), - getCookies(headers), - getHeaders(headers)); - } - return Response.ok().entity(swagger).build(); - } - else - return Response.status(404).build(); - } - - @GET - @Produces("application/yaml") - @Path("/swagger.yaml") - public Response getListingYaml( - @Context Application app, - @Context ServletConfig sc, - @Context HttpHeaders headers, - @Context UriInfo uriInfo) { - Swagger swagger = (Swagger) context.getAttribute("swagger"); - if(!initialized) - swagger = scan(app, sc); - try{ - if(swagger != null) { - SwaggerSpecFilter filterImpl = FilterFactory.getFilter(); - LOGGER.debug("using filter " + filterImpl); - if(filterImpl != null) { - SpecFilter f = new SpecFilter(); - swagger = f.filter(swagger, - filterImpl, - getQueryParams(uriInfo.getQueryParameters()), - getCookies(headers), - getHeaders(headers)); - } - - String yaml = Yaml.mapper().writeValueAsString(swagger); - String[] parts = yaml.split("\n"); - StringBuilder b = new StringBuilder(); - for(String part : parts) { - int pos = part.indexOf("!<"); - int endPos = part.indexOf(">"); - b.append(part); - b.append("\n"); - } - return Response.ok().entity(b.toString()).type("text/plain").build(); - } - } - catch (Exception e) { - e.printStackTrace(); - } - return Response.status(404).build(); - } - - protected Map> getQueryParams(MultivaluedMap params) { - Map> output = new HashMap>(); - if(params != null) { - for(String key: params.keySet()) { - List values = params.get(key); - output.put(key, values); - } - } - return output; - } - - protected Map getCookies(HttpHeaders headers) { - Map output = new HashMap(); - if(headers != null) { - for(String key: headers.getCookies().keySet()) { - Cookie cookie = headers.getCookies().get(key); - output.put(key, cookie.getValue()); - } - } - return output; - } - - - protected Map> getHeaders(HttpHeaders headers) { - Map> output = new HashMap>(); - if(headers != null) { - for(String key: headers.getRequestHeaders().keySet()) { - List values = headers.getRequestHeaders().get(key); - output.put(key, values); - } - } - return output; - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#427/old/ApiListingResource.java b/All/Genesis-NP/Genesis#427/old/ApiListingResource.java deleted file mode 100755 index 54a391e..0000000 --- a/All/Genesis-NP/Genesis#427/old/ApiListingResource.java +++ /dev/null @@ -1,171 +0,0 @@ -package com.wordnik.swagger.jaxrs.listing; - -import com.wordnik.swagger.config.*; -import com.wordnik.swagger.core.filter.*; -import com.wordnik.swagger.jaxrs.Reader; -import com.wordnik.swagger.jaxrs.config.*; -import com.wordnik.swagger.util.*; -import com.wordnik.swagger.models.Swagger; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.servlet.ServletConfig; -import javax.servlet.ServletContext; -import javax.ws.rs.*; -import javax.ws.rs.core.*; - -import java.util.Set; -import java.util.List; -import java.util.Map; -import java.util.HashMap; - -@Path("/") -public class ApiListingResource { - Logger LOGGER = LoggerFactory.getLogger(ApiListingResource.class); - - static boolean initialized = false; - @Context - ServletContext context; - - protected synchronized Swagger scan (Application app, ServletConfig sc) { - Swagger swagger = null; - Scanner scanner = ScannerFactory.getScanner(); - LOGGER.debug("using scanner " + scanner); - - if(scanner != null) { - SwaggerSerializers.setPrettyPrint(scanner.getPrettyPrint()); - swagger = (Swagger)context.getAttribute("swagger"); - - Set> classes = null; - if (scanner instanceof JaxrsScanner) { - JaxrsScanner jaxrsScanner = (JaxrsScanner)scanner; - classes = jaxrsScanner.classesFromContext(app, sc); - } - else { - classes = scanner.classes(); - } - if(classes != null) { - Reader reader = new Reader(swagger); - swagger = reader.read(classes); - if(scanner instanceof SwaggerConfig) - swagger = ((SwaggerConfig)scanner).configure(swagger); - else { - SwaggerConfig configurator = (SwaggerConfig)context.getAttribute("reader"); - if(configurator != null) { - LOGGER.debug("configuring swagger with " + configurator); - configurator.configure(swagger); - } - else - LOGGER.debug("no configurator"); - } - context.setAttribute("swagger", swagger); - } - } - initialized = true; - return swagger; - } - - @GET - @Produces(MediaType.APPLICATION_JSON) - @Path("/swagger.json") - public Response getListingJson( - @Context Application app, - @Context ServletConfig sc, - @Context HttpHeaders headers, - @Context UriInfo uriInfo) { - Swagger swagger = (Swagger) context.getAttribute("swagger"); - if(!initialized) - swagger = scan(app, sc); - if(swagger != null) { - SwaggerSpecFilter filterImpl = FilterFactory.getFilter(); - if(filterImpl != null) { - SpecFilter f = new SpecFilter(); - swagger = f.filter(swagger, - filterImpl, - getQueryParams(uriInfo.getQueryParameters()), - getCookies(headers), - getHeaders(headers)); - } - return Response.ok().entity(swagger).build(); - } - else - return Response.status(404).build(); - } - - @GET - @Produces("application/yaml") - @Path("/swagger.yaml") - public Response getListingYaml( - @Context Application app, - @Context ServletConfig sc, - @Context HttpHeaders headers, - @Context UriInfo uriInfo) { - Swagger swagger = (Swagger) context.getAttribute("swagger"); - if(!initialized) - swagger = scan(app, sc); - try{ - if(swagger != null) { - SwaggerSpecFilter filterImpl = FilterFactory.getFilter(); - LOGGER.debug("using filter " + filterImpl); - if(filterImpl != null) { - SpecFilter f = new SpecFilter(); - swagger = f.filter(swagger, - filterImpl, - getQueryParams(uriInfo.getQueryParameters()), - getCookies(headers), - getHeaders(headers)); - } - - String yaml = Yaml.mapper().writeValueAsString(swagger); - String[] parts = yaml.split("\n"); - StringBuilder b = new StringBuilder(); - for(String part : parts) { - int pos = part.indexOf("!<"); - int endPos = part.indexOf(">"); - b.append(part); - b.append("\n"); - } - return Response.ok().entity(b.toString()).type("text/plain").build(); - } - } - catch (Exception e) { - e.printStackTrace(); - } - return Response.status(404).build(); - } - - protected Map> getQueryParams(MultivaluedMap params) { - Map> output = new HashMap>(); - if(params != null) { - for(String key: params.keySet()) { - List values = params.get(key); - output.put(key, values); - } - } - return output; - } - - protected Map getCookies(HttpHeaders headers) { - Map output = new HashMap(); - if(headers != null) { - for(String key: headers.getCookies().keySet()) { - Cookie cookie = headers.getCookies().get(key); - output.put(key, cookie.getValue()); - } - } - return output; - } - - - protected Map> getHeaders(HttpHeaders headers) { - Map> output = new HashMap>(); - if(headers != null) { - for(String key: headers.getRequestHeaders().keySet()) { - List values = headers.getRequestHeaders().get(key); - output.put(key, values); - } - } - return output; - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#427/pair.info b/All/Genesis-NP/Genesis#427/pair.info deleted file mode 100755 index 00c0794..0000000 --- a/All/Genesis-NP/Genesis#427/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:427 -SATName:Genesis -modifiedFPath:modules/swagger-jaxrs/src/main/java/com/wordnik/swagger/jaxrs/listing/ApiListingResource.java -comSha:3adf9afb93d68f8316926bdfef750362328ff3e0 -parentComSha:3adf9afb93d68f8316926bdfef750362328ff3e0^1 -githubUrl:https://github.com/swagger-api/swagger-core -repoName:swagger-api#swagger-core \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#428/comMsg.txt b/All/Genesis-NP/Genesis#428/comMsg.txt deleted file mode 100755 index 53d72c1..0000000 --- a/All/Genesis-NP/Genesis#428/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed possible NullPointerException diff --git a/All/Genesis-NP/Genesis#428/diff.diff b/All/Genesis-NP/Genesis#428/diff.diff deleted file mode 100755 index 3f316bb..0000000 --- a/All/Genesis-NP/Genesis#428/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/core/src/main/java/hivemall/utils/compress/DeflateCodec.java b/core/src/main/java/hivemall/utils/compress/DeflateCodec.java -index 5defd17..bf79a43 100644 ---- a/core/src/main/java/hivemall/utils/compress/DeflateCodec.java -+++ b/core/src/main/java/hivemall/utils/compress/DeflateCodec.java -@@ -116,0 +117 @@ public final class DeflateCodec extends CompressionCodec { -+ if (compressor != null) { -@@ -117,0 +119,2 @@ public final class DeflateCodec extends CompressionCodec { -+ } -+ if (decompressor != null) { -@@ -119,0 +123 @@ public final class DeflateCodec extends CompressionCodec { -+ } diff --git a/All/Genesis-NP/Genesis#428/new/DeflateCodec.java b/All/Genesis-NP/Genesis#428/new/DeflateCodec.java deleted file mode 100755 index bf79a43..0000000 --- a/All/Genesis-NP/Genesis#428/new/DeflateCodec.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * Hivemall: Hive scalable Machine Learning Library - * - * Copyright (C) 2015 Makoto YUI - * Copyright (C) 2013-2015 National Institute of Advanced Industrial Science and Technology (AIST) - * - * 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 hivemall.utils.compress; - -import static java.util.zip.Deflater.DEFAULT_COMPRESSION; - -import java.io.IOException; -import java.util.zip.DataFormatException; -import java.util.zip.Deflater; -import java.util.zip.Inflater; - -import javax.annotation.Nonnull; - -public final class DeflateCodec extends CompressionCodec { - - private final Deflater compressor; - private final Inflater decompressor; - - public DeflateCodec() { - this(true, true); - } - - public DeflateCodec(boolean compress, boolean decompress) { - super(); - this.compressor = compress ? new Deflater(DEFAULT_COMPRESSION, true) : null; - this.decompressor = decompress ? new Inflater(true) : null; - } - - @Override - public byte[] compress(@Nonnull byte[] in, int off, int len) throws IOException { - return compress(in, off, len, DEFAULT_COMPRESSION); - } - - @Nonnull - public byte[] compress(@Nonnull final byte[] in, final int off, final int len, final int level) - throws IOException { - // Create an expandable byte array to hold the compressed data. - byte[] compressedData = new byte[len]; - - int compressedSize; - try { - compressor.reset(); - if (level != DEFAULT_COMPRESSION) { - compressor.setLevel(level); - } - // Give the compressor the data to compress - compressor.setInput(in, off, len); - compressor.finish(); - compressedSize = compressor.deflate(compressedData); - } catch (Exception ex) { - throw new IOException(ex); - } - final int header; - if (compressedSize == 0) { - compressedData = in; - compressedSize = len; - header = 0; - } else if (compressedSize >= (len - 4)) { - compressedData = in; - compressedSize = len; - header = 0; - } else { - header = len; - } - final byte[] output = new byte[compressedSize + 4]; - output[0] = (byte) (header >> 24); - output[1] = (byte) (header >> 16); - output[2] = (byte) (header >> 8); - output[3] = (byte) header; - System.arraycopy(compressedData, 0, output, 4, compressedSize); - return output; - } - - @Override - public byte[] decompress(@Nonnull final byte[] in, final int off, final int len) - throws IOException { - final int originalSize = (((in[off] & 0xff) << 24) + ((in[off + 1] & 0xff) << 16) - + ((in[off + 2] & 0xff) << 8) + (in[off + 3] & 0xff)); - if (originalSize == 0) { - byte[] dest = new byte[len - 4]; - System.arraycopy(in, 4, dest, 0, len - 4); - return dest; - } - // Create an expandable byte array to hold the decompressed data - final byte[] result = new byte[originalSize]; - try { - // Decompress the data - decompressor.reset(); - decompressor.setInput(in, 4, len - 4); - decompressor.inflate(result); - } catch (DataFormatException dfe) { - throw new IOException(dfe); - } catch (Exception ex) { - throw new IOException(ex); - } - return result; - } - - @Override - public void close() throws IOException { - if (compressor != null) { - compressor.end(); - } - if (decompressor != null) { - decompressor.end(); - } - } - -} diff --git a/All/Genesis-NP/Genesis#428/old/DeflateCodec.java b/All/Genesis-NP/Genesis#428/old/DeflateCodec.java deleted file mode 100755 index 5defd17..0000000 --- a/All/Genesis-NP/Genesis#428/old/DeflateCodec.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * Hivemall: Hive scalable Machine Learning Library - * - * Copyright (C) 2015 Makoto YUI - * Copyright (C) 2013-2015 National Institute of Advanced Industrial Science and Technology (AIST) - * - * 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 hivemall.utils.compress; - -import static java.util.zip.Deflater.DEFAULT_COMPRESSION; - -import java.io.IOException; -import java.util.zip.DataFormatException; -import java.util.zip.Deflater; -import java.util.zip.Inflater; - -import javax.annotation.Nonnull; - -public final class DeflateCodec extends CompressionCodec { - - private final Deflater compressor; - private final Inflater decompressor; - - public DeflateCodec() { - this(true, true); - } - - public DeflateCodec(boolean compress, boolean decompress) { - super(); - this.compressor = compress ? new Deflater(DEFAULT_COMPRESSION, true) : null; - this.decompressor = decompress ? new Inflater(true) : null; - } - - @Override - public byte[] compress(@Nonnull byte[] in, int off, int len) throws IOException { - return compress(in, off, len, DEFAULT_COMPRESSION); - } - - @Nonnull - public byte[] compress(@Nonnull final byte[] in, final int off, final int len, final int level) - throws IOException { - // Create an expandable byte array to hold the compressed data. - byte[] compressedData = new byte[len]; - - int compressedSize; - try { - compressor.reset(); - if (level != DEFAULT_COMPRESSION) { - compressor.setLevel(level); - } - // Give the compressor the data to compress - compressor.setInput(in, off, len); - compressor.finish(); - compressedSize = compressor.deflate(compressedData); - } catch (Exception ex) { - throw new IOException(ex); - } - final int header; - if (compressedSize == 0) { - compressedData = in; - compressedSize = len; - header = 0; - } else if (compressedSize >= (len - 4)) { - compressedData = in; - compressedSize = len; - header = 0; - } else { - header = len; - } - final byte[] output = new byte[compressedSize + 4]; - output[0] = (byte) (header >> 24); - output[1] = (byte) (header >> 16); - output[2] = (byte) (header >> 8); - output[3] = (byte) header; - System.arraycopy(compressedData, 0, output, 4, compressedSize); - return output; - } - - @Override - public byte[] decompress(@Nonnull final byte[] in, final int off, final int len) - throws IOException { - final int originalSize = (((in[off] & 0xff) << 24) + ((in[off + 1] & 0xff) << 16) - + ((in[off + 2] & 0xff) << 8) + (in[off + 3] & 0xff)); - if (originalSize == 0) { - byte[] dest = new byte[len - 4]; - System.arraycopy(in, 4, dest, 0, len - 4); - return dest; - } - // Create an expandable byte array to hold the decompressed data - final byte[] result = new byte[originalSize]; - try { - // Decompress the data - decompressor.reset(); - decompressor.setInput(in, 4, len - 4); - decompressor.inflate(result); - } catch (DataFormatException dfe) { - throw new IOException(dfe); - } catch (Exception ex) { - throw new IOException(ex); - } - return result; - } - - @Override - public void close() throws IOException { - compressor.end(); - decompressor.end(); - } - -} diff --git a/All/Genesis-NP/Genesis#428/pair.info b/All/Genesis-NP/Genesis#428/pair.info deleted file mode 100755 index 1a0cb0c..0000000 --- a/All/Genesis-NP/Genesis#428/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:428 -SATName:Genesis -modifiedFPath:core/src/main/java/hivemall/utils/compress/DeflateCodec.java -comSha:7dce316701c481cfea7edf8bb4a3f1886f35385b -parentComSha:7dce316701c481cfea7edf8bb4a3f1886f35385b^1 -githubUrl:https://github.com/myui/hivemall -repoName:myui#hivemall \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#43/comMsg.txt b/All/Genesis-NP/Genesis#43/comMsg.txt deleted file mode 100755 index 0189c61..0000000 --- a/All/Genesis-NP/Genesis#43/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Small fix for NPE diff --git a/All/Genesis-NP/Genesis#43/diff.diff b/All/Genesis-NP/Genesis#43/diff.diff deleted file mode 100755 index d7ad59d..0000000 --- a/All/Genesis-NP/Genesis#43/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/src/main/java/org/encog/app/analyst/wizard/AnalystWizard.java b/src/main/java/org/encog/app/analyst/wizard/AnalystWizard.java -index e5cfed5..38742c6 100644 ---- a/src/main/java/org/encog/app/analyst/wizard/AnalystWizard.java -+++ b/src/main/java/org/encog/app/analyst/wizard/AnalystWizard.java -@@ -308 +308 @@ -- private TargetLanguage codeTargetLanguage; -+ private TargetLanguage codeTargetLanguage = TargetLanguage.NoGeneration; diff --git a/All/Genesis-NP/Genesis#43/new/AnalystWizard.java b/All/Genesis-NP/Genesis#43/new/AnalystWizard.java deleted file mode 100755 index 38742c6..0000000 --- a/All/Genesis-NP/Genesis#43/new/AnalystWizard.java +++ /dev/null @@ -1,1493 +0,0 @@ -/* - * Encog(tm) Core v3.1 - Java Version - * http://www.heatonresearch.com/encog/ - * http://code.google.com/p/encog-java/ - - * Copyright 2008-2012 Heaton Research, 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. - * - * For more information on Heaton Research copyrights, licenses - * and trademarks visit: - * http://www.heatonresearch.com/copyright - */ -package org.encog.app.analyst.wizard; - -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import org.encog.Encog; -import org.encog.app.analyst.AnalystError; -import org.encog.app.analyst.AnalystFileFormat; -import org.encog.app.analyst.AnalystGoal; -import org.encog.app.analyst.EncogAnalyst; -import org.encog.app.analyst.missing.DiscardMissing; -import org.encog.app.analyst.missing.HandleMissingValues; -import org.encog.app.analyst.script.AnalystClassItem; -import org.encog.app.analyst.script.AnalystScript; -import org.encog.app.analyst.script.DataField; -import org.encog.app.analyst.script.normalize.AnalystField; -import org.encog.app.analyst.script.prop.ScriptProperties; -import org.encog.app.analyst.script.segregate.AnalystSegregateTarget; -import org.encog.app.analyst.script.task.AnalystTask; -import org.encog.app.generate.TargetLanguage; -import org.encog.ml.factory.MLMethodFactory; -import org.encog.ml.factory.MLTrainFactory; -import org.encog.util.arrayutil.NormalizationAction; -import org.encog.util.csv.CSVFormat; -import org.encog.util.file.FileUtil; - -/** - * The Encog Analyst Wizard can be used to create Encog Analyst script files - * from a CSV file. This class is typically used by the Encog Workbench, but it - * can easily be used from any program to create a starting point for an Encog - * Analyst Script. - * - * Several items must be provided to the wizard. - * - * Desired Machine Learning Method: This is the machine learning method that you - * would like the wizard to use. This might be a neural network, SVM or other - * supported method. - * - * Normalization Range: This is the range that the data should be normalized - * into. Some machine learning methods perform better with different ranges. The - * two ranges supported by the wizard are -1 to 1 and 0 to 1. - * - * Goal: What are we trying to accomplish. Is this a classification, regression - * or autoassociation problem. - * - */ -public class AnalystWizard { - - /** - * The default training percent. - */ - public static final int DEFAULT_TRAIN_PERCENT = 75; - - /** - * The default evaluation percent. - */ - public static final int DEFAULT_EVAL_PERCENT = 25; - - /** - * The default training error. - */ - public static final double DEFAULT_TRAIN_ERROR = 0.05; - - /** - * The raw file. - */ - public static final String FILE_RAW = "FILE_RAW"; - - /** - * The normalized file. - */ - public static final String FILE_NORMALIZE = "FILE_NORMALIZE"; - - /** - * The randomized file. - */ - public static final String FILE_RANDOM = "FILE_RANDOMIZE"; - - /** - * The training file. - */ - public static final String FILE_TRAIN = "FILE_TRAIN"; - - /** - * The evaluation file. - */ - public static final String FILE_EVAL = "FILE_EVAL"; - - /** - * The eval file normalization file. - */ - public static final String FILE_EVAL_NORM = "FILE_EVAL_NORM"; - - /** - * The training set. - */ - public static final String FILE_TRAINSET = "FILE_TRAINSET"; - - /** - * The machine learning file. - */ - public static final String FILE_ML = "FILE_ML"; - - /** - * The output file. - */ - public static final String FILE_OUTPUT = "FILE_OUTPUT"; - - /** - * The balanced file. - */ - public static final String FILE_BALANCE = "FILE_BALANCE"; - - /** - * The clustered file. - */ - public static final String FILE_CLUSTER = "FILE_CLUSTER"; - - /** - * The generated code file. - */ - public static final String FILE_CODE = "FILE_CODE"; - - /** - * The raw filename. - */ - private String filenameRaw; - - /** - * The normalized filename. - */ - private String filenameNorm; - - /** - * The random file name. - */ - private String filenameRandom; - - /** - * The training filename. - */ - private String filenameTrain; - - /** - * The evaluation filename. - */ - private String filenameEval; - - /** - * The normalization eval file name. - */ - private String filenameEvalNorm; - - /** - * The training set filename. - */ - private String filenameTrainSet; - - /** - * The machine learning file name. - */ - private String filenameML; - - /** - * The output filename. - */ - private String filenameOutput; - - /** - * The balance filename. - */ - private String filenameBalance; - - /** - * The cluster filename. - */ - private String filenameCluster; - - /** - * The filename that code will be generated to. - */ - private String filenameCode; - - /** - * The analyst script. - */ - private final AnalystScript script; - - /** - * The analyst. - */ - private final EncogAnalyst analyst; - - /** - * The machine learning method that we will be using. - */ - private WizardMethodType methodType; - - /** - * Are we using single-field(direct) classification. - */ - private boolean directClassification = false; - - /** - * The target field, or "" to detect. - */ - private AnalystField targetField; - - /** - * The analyst goal. - */ - private AnalystGoal goal; - - /** - * The size of the lag window, if we are doing time-series. - */ - private int lagWindowSize; - - /** - * The size of the lead window, if we are doing time-series. - */ - private int leadWindowSize; - - /** - * Should the target field be included in the input, if we are doing - * time-series. - */ - private boolean includeTargetField; - - /** - * True if we are doing time-series. - */ - private boolean timeSeries; - - /** - * True if the segregate command should be generated. - */ - private boolean taskSegregate = true; - - /** - * True if the randomize command should be generated. - */ - private boolean taskRandomize = true; - - /** - * True if the normalize command should be generated. - */ - private boolean taskNormalize = true; - - /** - * True if the balance command should be generated. - */ - private boolean taskBalance = false; - - /** - * True if the cluster command should be generated. - */ - private boolean taskCluster = true; - - /** - * The normalization range. - */ - private NormalizeRange range = NormalizeRange.NegOne2One; - - /** - * What to do with missing values. - */ - private HandleMissingValues missing = new DiscardMissing(); - - /** - * The format being used. - */ - private AnalystFileFormat format; - - private boolean naiveBayes = false; - - private int evidenceSegements = 3; - - private double maxError = DEFAULT_TRAIN_ERROR; - - private String targetFieldName; - - private TargetLanguage codeTargetLanguage = TargetLanguage.NoGeneration; - - private boolean codeEmbedData; - - /** - * Construct the analyst wizard. - * @param theAnalyst The analyst to use. - */ - public AnalystWizard(final EncogAnalyst theAnalyst) { - this.analyst = theAnalyst; - this.script = analyst.getScript(); - this.methodType = WizardMethodType.FeedForward; - this.targetField = null; - this.goal = AnalystGoal.Classification; - this.leadWindowSize = 0; - this.lagWindowSize = 0; - this.includeTargetField = false; - } - - /** - * Create a "set" command to add to a task. - * @param setTarget The target. - * @param setSource The source. - * @return The "set" command. - */ - private String createSet(final String setTarget, final String setSource) { - final StringBuilder result = new StringBuilder(); - result.append("set "); - result.append(ScriptProperties.toDots(setTarget)); - result.append("=\""); - result.append(setSource); - result.append("\""); - return result.toString(); - } - - /** - * Determine the type of classification used. - */ - private void determineClassification() { - this.directClassification = false; - - if ((this.methodType == WizardMethodType.SVM) - || (this.methodType == WizardMethodType.SOM) - || (this.methodType == WizardMethodType.PNN)) { - this.directClassification = true; - } - } - - /** - * Determine the target field. - */ - private void determineTargetField() { - final List fields = this.script.getNormalize() - .getNormalizedFields(); - - if (this.targetFieldName == null || this.targetFieldName.length()==0 ) { - boolean success = false; - - if (this.goal == AnalystGoal.Classification) { - // first try to the last classify field - for (final AnalystField field : fields) { - final DataField df = this.script.findDataField(field - .getName()); - if (field.getAction().isClassify() && df.isClass()) { - this.targetField = field; - success = true; - } - } - } else { - - // otherwise, just return the last regression field - for (final AnalystField field : fields) { - final DataField df = this.script - .findDataField(field.getName()); - if (!df.isClass() && (df.isReal() || df.isInteger())) { - this.targetField = field; - success = true; - } - } - } - - if (!success) { - throw new AnalystError( - "Can't determine target field automatically, " - + "please specify one.\nThis can also happen if you " - + "specified the wrong file format."); - } - } else { - this.targetField = this.script.findAnalystField(this.targetFieldName); - if ( this.targetField == null) { - throw new AnalystError("Invalid target field: " - + this.targetField); - } - } - - this.script.getProperties().setProperty( - ScriptProperties.DATA_CONFIG_GOAL, this.goal); - - if (!this.timeSeries && this.taskBalance) { - this.script.getProperties().setProperty( - ScriptProperties.BALANCE_CONFIG_BALANCE_FIELD, - this.targetField.getName()); - final DataField field = this.analyst.getScript().findDataField( - this.targetField.getName()); - if ((field != null) && field.isClass()) { - final int countPer = field.getMinClassCount(); - this.script.getProperties().setProperty( - ScriptProperties.BALANCE_CONFIG_COUNT_PER, countPer); - } - } - - // determine output field - if (this.methodType != WizardMethodType.BayesianNetwork) { - // now that the target field has been determined, set the analyst fields - AnalystField af = null; - for (final AnalystField field : this.analyst.getScript() - .getNormalize().getNormalizedFields()) { - if ((field.getAction() != NormalizationAction.Ignore) - && field == this.targetField) { - if ((af == null) - || (af.getTimeSlice() < field.getTimeSlice())) { - af = field; - } - } - } - - if (af != null) { - af.setOutput(true); - } - } - - // set the clusters count - if (this.taskCluster) { - if ((this.targetField == null) - || (this.goal != AnalystGoal.Classification)) { - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_CLUSTERS, 2); - } else { - final DataField tf = this.script.findDataField(this.targetField - .getName()); - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_CLUSTERS, - tf.getClassMembers().size()); - } - } - } - - /** - * Expand the time-series fields. - */ - private void expandTimeSlices() { - final List oldList = this.script.getNormalize() - .getNormalizedFields(); - final List newList = new ArrayList(); - - // generate the inputs for the new list - for (final AnalystField field : oldList) { - if (!field.isIgnored()) { - - if (this.includeTargetField || field.isInput()) { - for (int i = 0; i < this.lagWindowSize; i++) { - final AnalystField newField = new AnalystField(field); - newField.setTimeSlice(-i); - newField.setOutput(false); - newList.add(newField); - } - } - } else { - newList.add(field); - } - } - - // generate the outputs for the new list - for (final AnalystField field : oldList) { - if (!field.isIgnored()) { - if (field.isOutput()) { - for (int i = 1; i <= this.leadWindowSize; i++) { - final AnalystField newField = new AnalystField(field); - newField.setTimeSlice(i); - newList.add(newField); - } - } - } - } - - // generate the ignores for the new list - for (final AnalystField field : oldList) { - if (field.isIgnored()) { - newList.add(field); - } - } - - // swap back in - oldList.clear(); - oldList.addAll(newList); - - } - - /** - * Generate a feed forward machine learning method. - * @param inputColumns The input column count. - * @param outputColumns The output column count. - */ - private void generateFeedForward(final int inputColumns, - final int outputColumns) { - final int hidden = (int) ((inputColumns) * 1.5); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, - MLMethodFactory.TYPE_FEEDFORWARD); - - if (this.range == NormalizeRange.NegOne2One) { - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, - "?:B->TANH->" + hidden + ":B->TANH->?"); - } else { - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, - "?:B->SIGMOID->" + hidden + ":B->SIGMOID->?"); - } - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - "rprop"); - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate a Bayesian network machine learning method. - * @param inputColumns The input column count. - * @param outputColumns The output column count. - */ - private void generateBayesian(final int inputColumns, - final int outputColumns) { - - int segment = this.evidenceSegements; - - if( !this.targetField.isClassify() ) { - throw new AnalystError("Bayesian networks cannot be used for regression."); - } - - StringBuilder a = new StringBuilder(); - for (DataField field : this.analyst.getScript().getFields()) { - a.append("P("); - a.append(field.getName()); - - // handle actual class members - if (field.getClassMembers().size() > 0) { - a.append("["); - boolean first = true; - for (AnalystClassItem item : field.getClassMembers()) { - if (!first) { - a.append(","); - } - a.append(item.getCode()); - first = false; - } - - // append a "fake" member, if there is only one - if( field.getClassMembers().size()==1 ) { - a.append(",Other0"); - } - - a.append("]"); - } else { - a.append("["); - // handle ranges - double size = Math.abs(field.getMax() - field.getMin()); - double per = size / segment; - - if (size < Encog.DEFAULT_DOUBLE_EQUAL) { - double low = field.getMin() - 0.0001; - double hi = field.getMin() + 0.0001; - a.append("BELOW: " + (low - 100) + " to " + hi + ","); - a.append("Type0: " + low + " to " + hi + ","); - a.append("ABOVE: " + hi + " to " + (hi + 100)); - } else { - boolean first = true; - for (int i = 0; i < segment; i++) { - if (!first) { - a.append(","); - } - double low = field.getMin() + (per * i); - double hi = i == (segment - 1) ? (field.getMax()) - : (low + per); - a.append("Type"); - a.append(i); - a.append(":"); - a.append(CSVFormat.EG_FORMAT.format(low, 16)); - a.append(" to "); - a.append(CSVFormat.EG_FORMAT.format(hi, 16)); - first = false; - } - } - a.append("]"); - } - - a.append(") "); - } - - StringBuilder q = new StringBuilder(); - q.append("P("); - q.append(this.targetField.getName()); - q.append("|"); - boolean first = true; - for (DataField field : this.analyst.getScript().getFields()) { - if (!field.getName().equals(this.targetField.getName())) { - if (!first) { - q.append(","); - } - q.append(field.getName()); - first = false; - } - } - q.append(")"); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, MLMethodFactory.TYPE_BAYESIAN); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, a.toString()); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_QUERY, q.toString()); - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - "bayesian"); - - if (this.naiveBayes) { - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_ARGUMENTS, - "maxParents=1,estimator=simple,search=none,init=naive"); - } else { - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_ARGUMENTS, - "maxParents=1,estimator=simple,search=k2,init=naive"); - } - - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate filenames. - * @param rawFile The raw filename. - */ - private void generateFilenames(final File rawFile) { - this.filenameRaw = rawFile.getName(); - this.filenameNorm = FileUtil.addFilenameBase(rawFile, "_norm") - .getName(); - this.filenameRandom = FileUtil.addFilenameBase(rawFile, "_random") - .getName(); - this.filenameTrain = FileUtil.addFilenameBase(rawFile, "_train") - .getName(); - this.filenameEval = FileUtil.addFilenameBase(rawFile, "_eval") - .getName(); - this.filenameEvalNorm = FileUtil.addFilenameBase(rawFile, "_eval_norm") - .getName(); - this.filenameTrainSet = FileUtil.forceExtension(this.filenameTrain, - "egb"); - this.filenameML = FileUtil.forceExtension(this.filenameTrain, "eg"); - this.filenameOutput = FileUtil.addFilenameBase(rawFile, "_output") - .getName(); - this.filenameBalance = FileUtil.addFilenameBase(rawFile, "_balance") - .getName(); - this.filenameCluster = FileUtil.addFilenameBase(rawFile, "_cluster") - .getName(); - this.filenameCode = FileUtil.forceExtension( FileUtil.addFilenameBase(rawFile, "_code").getName(), - this.codeTargetLanguage.getExtension()); - - final ScriptProperties p = this.script.getProperties(); - - p.setFilename(AnalystWizard.FILE_RAW, this.filenameRaw); - if (this.taskNormalize) { - p.setFilename(AnalystWizard.FILE_NORMALIZE, this.filenameNorm); - } - - if (this.taskRandomize) { - p.setFilename(AnalystWizard.FILE_RANDOM, this.filenameRandom); - } - - if (this.taskCluster) { - p.setFilename(AnalystWizard.FILE_CLUSTER, this.filenameCluster); - } - - if (this.taskSegregate) { - p.setFilename(AnalystWizard.FILE_TRAIN, this.filenameTrain); - p.setFilename(AnalystWizard.FILE_EVAL, this.filenameEval); - p.setFilename(AnalystWizard.FILE_EVAL_NORM, this.filenameEvalNorm); - } - - if (this.taskBalance) { - p.setFilename(AnalystWizard.FILE_BALANCE, this.filenameBalance); - } - - if (this.codeTargetLanguage != TargetLanguage.NoGeneration ) { - p.setFilename(AnalystWizard.FILE_CODE, this.filenameCode); - } - - p.setFilename(AnalystWizard.FILE_TRAINSET, this.filenameTrainSet); - p.setFilename(AnalystWizard.FILE_ML, this.filenameML); - p.setFilename(AnalystWizard.FILE_OUTPUT, this.filenameOutput); - - } - - /** - * Generate the generate task. - */ - private void generateGenerate() { - determineTargetField(); - - if (this.targetField == null) { - throw new AnalystError( - "Failed to find normalized version of target field: " - + this.targetField); - } - - final int inputColumns = this.script.getNormalize() - .calculateInputColumns(); - final int idealColumns = this.script.getNormalize() - .calculateOutputColumns(); - - switch (this.methodType) { - case BayesianNetwork: - generateBayesian(inputColumns, idealColumns); - break; - case FeedForward: - generateFeedForward(inputColumns, idealColumns); - break; - case SVM: - generateSVM(inputColumns, idealColumns); - break; - case RBF: - generateRBF(inputColumns, idealColumns); - break; - case SOM: - generateSOM(inputColumns); - break; - case PNN: - generatePNN(inputColumns, idealColumns); - break; - default: - throw new AnalystError("Unknown method type"); - } - } - - /** - * Generate the normalized fields. - */ - private void generateNormalizedFields() { - final List norm = this.script.getNormalize() - .getNormalizedFields(); - norm.clear(); - final DataField[] dataFields = this.script.getFields(); - - for (int i = 0; i < this.script.getFields().length; i++) { - final DataField f = dataFields[i]; - - NormalizationAction action; - final boolean isLast = i == this.script.getFields().length - 1; - - if (this.methodType == WizardMethodType.BayesianNetwork) { - AnalystField af; - if (f.isClass()) { - af = new AnalystField(f.getName(), - NormalizationAction.SingleField, 0, 0); - } else { - af = new AnalystField(f.getName(), - NormalizationAction.PassThrough, 0, 0); - } - norm.add(af); - } else if ((f.isInteger() || f.isReal()) && !f.isClass()) { - action = NormalizationAction.Normalize; - AnalystField af; - if (this.range == NormalizeRange.NegOne2One) { - af = new AnalystField(f.getName(), action, 1, -1); - } else { - af = new AnalystField(f.getName(), action, 1, 0); - } - norm.add(af); - af.setActualHigh(f.getMax()); - af.setActualLow(f.getMin()); - } else if (f.isClass()) { - if (isLast && this.directClassification) { - action = NormalizationAction.SingleField; - } else if (f.getClassMembers().size() > 2) { - action = NormalizationAction.Equilateral; - } else { - action = NormalizationAction.OneOf; - } - - if (this.range == NormalizeRange.NegOne2One) { - norm.add(new AnalystField(f.getName(), action, 1, -1)); - } else { - norm.add(new AnalystField(f.getName(), action, 1, 0)); - } - } else { - action = NormalizationAction.Ignore; - norm.add(new AnalystField(action, f.getName())); - } - } - - this.script.getNormalize().init(this.script); - } - - /** - * Generate a RBF machine learning method. - * @param inputColumns The number of input columns. - * @param outputColumns The number of output columns. - */ - private void generateRBF(final int inputColumns, final int outputColumns) { - final int hidden = (int) ((inputColumns) * 1.5); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, - MLMethodFactory.TYPE_RBFNETWORK); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, - "?->GAUSSIAN(c=" + hidden + ")->?"); - - if (outputColumns > 1) { - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TYPE, "rprop"); - } else { - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TYPE, "svd"); - } - - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate the segregate task. - */ - private void generateSegregate() { - if (this.taskSegregate) { - final AnalystSegregateTarget[] array = new AnalystSegregateTarget[2]; - array[0] = new AnalystSegregateTarget(AnalystWizard.FILE_TRAIN, - DEFAULT_TRAIN_PERCENT); - array[1] = new AnalystSegregateTarget(AnalystWizard.FILE_EVAL, - DEFAULT_EVAL_PERCENT); - this.script.getSegregate().setSegregateTargets(array); - } else { - final AnalystSegregateTarget[] array = new AnalystSegregateTarget[0]; - this.script.getSegregate().setSegregateTargets(array); - } - } - - /** - * Generate the settings. - */ - private void generateSettings() { - - String target; - String evalSource; - - // starting point - target = AnalystWizard.FILE_RAW; - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE, target); - - // randomize - if (!this.timeSeries && this.taskRandomize) { - this.script.getProperties().setProperty( - ScriptProperties.RANDOMIZE_CONFIG_SOURCE_FILE, - AnalystWizard.FILE_RAW); - target = AnalystWizard.FILE_RANDOM; - this.script.getProperties().setProperty( - ScriptProperties.RANDOMIZE_CONFIG_TARGET_FILE, target); - } - - // balance - if (!this.timeSeries && this.taskBalance) { - this.script.getProperties().setProperty( - ScriptProperties.BALANCE_CONFIG_SOURCE_FILE, target); - target = AnalystWizard.FILE_BALANCE; - this.script.getProperties().setProperty( - ScriptProperties.BALANCE_CONFIG_TARGET_FILE, target); - } - - // segregate - if (this.taskSegregate) { - this.script.getProperties().setProperty( - ScriptProperties.SEGREGATE_CONFIG_SOURCE_FILE, target); - target = AnalystWizard.FILE_TRAIN; - } - - // normalize - if (this.taskNormalize) { - this.script.getProperties().setProperty( - ScriptProperties.NORMALIZE_CONFIG_SOURCE_FILE, target); - target = AnalystWizard.FILE_NORMALIZE; - this.script.getProperties().setProperty( - ScriptProperties.NORMALIZE_CONFIG_TARGET_FILE, target); - - this.script.getNormalize().setMissingValues(this.missing); - } - - if (this.taskSegregate) { - evalSource = AnalystWizard.FILE_EVAL; - } else { - evalSource = target; - } - - // cluster - if (this.taskCluster) { - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_SOURCE_FILE, evalSource); - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_TARGET_FILE, - AnalystWizard.FILE_CLUSTER); - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_TYPE, "kmeans"); - } - - // generate - this.script.getProperties().setProperty( - ScriptProperties.GENERATE_CONFIG_SOURCE_FILE, target); - this.script.getProperties().setProperty( - ScriptProperties.GENERATE_CONFIG_TARGET_FILE, - AnalystWizard.FILE_TRAINSET); - - // ML - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TRAINING_FILE, - AnalystWizard.FILE_TRAINSET); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_MACHINE_LEARNING_FILE, - AnalystWizard.FILE_ML); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_OUTPUT_FILE, - AnalystWizard.FILE_OUTPUT); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_EVAL_FILE, evalSource); - - // other - this.script.getProperties().setProperty( - ScriptProperties.SETUP_CONFIG_CSV_FORMAT, format); - } - - /** - * Generate a SOM machine learning method. - * @param inputColumns The number of input columns. - */ - private void generateSOM(final int inputColumns) { - - if( !this.targetField.isClassify() ) { - throw new AnalystError("SOM cannot be used for regression."); - } - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, MLMethodFactory.TYPE_SOM); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, "?->" + this.targetField.getClasses().size()); - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - MLTrainFactory.TYPE_SOM_NEIGHBORHOOD); - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_ARGUMENTS, - "ITERATIONS=1000,NEIGHBORHOOD=rbf1d,RBF_TYPE=gaussian"); - - // ScriptProperties.ML_TRAIN_arguments - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate a SVM machine learning method. - * @param inputColumns The number of input columns. - * @param outputColumns The number of ideal columns. - */ - private void generateSVM(final int inputColumns, final int outputColumns) { - - StringBuilder arch = new StringBuilder(); - arch.append("?->"); - if (this.goal == AnalystGoal.Classification) { - arch.append("C"); - } else { - arch.append("R"); - } - arch.append("(type=new,kernel=rbf)->?"); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, MLMethodFactory.TYPE_SVM); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, arch.toString()); - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - MLTrainFactory.TYPE_SVM_SEARCH); - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate a PNN machine learning method. - * @param inputColumns The number of input columns. - * @param outputColumns The number of ideal columns. - */ - private void generatePNN(final int inputColumns, final int outputColumns) { - - StringBuilder arch = new StringBuilder(); - arch.append("?->"); - if (this.goal == AnalystGoal.Classification) { - arch.append("C"); - } else { - arch.append("R"); - } - arch.append("(kernel=gaussian)->"); - arch.append(this.targetField.getClasses().size()); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, MLMethodFactory.TYPE_PNN); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, arch.toString()); - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - MLTrainFactory.TYPE_PNN); - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate the tasks. - */ - private void generateTasks() { - final AnalystTask task1 = new AnalystTask(EncogAnalyst.TASK_FULL); - if (!this.timeSeries && this.taskRandomize) { - task1.getLines().add("randomize"); - } - - if (!this.timeSeries && this.taskBalance) { - task1.getLines().add("balance"); - } - - if (this.taskSegregate) { - task1.getLines().add("segregate"); - } - - if (this.taskNormalize) { - task1.getLines().add("normalize"); - } - - task1.getLines().add("generate"); - task1.getLines().add("create"); - task1.getLines().add("train"); - task1.getLines().add("evaluate"); - - if( this.codeTargetLanguage!=TargetLanguage.NoGeneration) { - task1.getLines().add("code"); - } - - final AnalystTask task2 = new AnalystTask("task-generate"); - if (!this.timeSeries && this.taskRandomize) { - task2.getLines().add("randomize"); - } - - if (this.taskSegregate) { - task2.getLines().add("segregate"); - } - if (this.taskNormalize) { - task2.getLines().add("normalize"); - } - task2.getLines().add("generate"); - - final AnalystTask task3 = new AnalystTask("task-evaluate-raw"); - task3.getLines().add( - createSet(ScriptProperties.ML_CONFIG_EVAL_FILE, - AnalystWizard.FILE_EVAL_NORM)); - task3.getLines().add( - createSet(ScriptProperties.NORMALIZE_CONFIG_SOURCE_FILE, - AnalystWizard.FILE_EVAL)); - task3.getLines().add( - createSet(ScriptProperties.NORMALIZE_CONFIG_TARGET_FILE, - AnalystWizard.FILE_EVAL_NORM)); - task3.getLines().add("normalize"); - task3.getLines().add("evaluate-raw"); - - final AnalystTask task4 = new AnalystTask("task-create"); - task4.getLines().add("create"); - - final AnalystTask task5 = new AnalystTask("task-train"); - task5.getLines().add("train"); - - final AnalystTask task6 = new AnalystTask("task-evaluate"); - task6.getLines().add("evaluate"); - - final AnalystTask task7 = new AnalystTask("task-cluster"); - task7.getLines().add("cluster"); - - final AnalystTask task8 = new AnalystTask("task-code"); - task7.getLines().add("code"); - - this.script.addTask(task1); - this.script.addTask(task2); - this.script.addTask(task3); - this.script.addTask(task4); - this.script.addTask(task5); - this.script.addTask(task6); - this.script.addTask(task7); - this.script.addTask(task8); - } - - /** - * @return The analyst goal. - */ - public AnalystGoal getGoal() { - return this.goal; - } - - /** - * @return the lagWindowSize - */ - public int getLagWindowSize() { - return this.lagWindowSize; - } - - /** - * @return the leadWindowSize - */ - public int getLeadWindowSize() { - return this.leadWindowSize; - } - - /** - * @return the methodType - */ - public WizardMethodType getMethodType() { - return this.methodType; - } - - /** - * @return the range - */ - public NormalizeRange getRange() { - return this.range; - } - - /** - * @return Get the target field. - */ - public AnalystField getTargetField() { - return this.targetField; - } - - /** - * @return the includeTargetField - */ - public boolean isIncludeTargetField() { - return this.includeTargetField; - } - - /** - * @return the taskBalance - */ - public boolean isTaskBalance() { - return this.taskBalance; - } - - /** - * @return the taskCluster - */ - public boolean isTaskCluster() { - return this.taskCluster; - } - - /** - * @return the taskNormalize - */ - public boolean isTaskNormalize() { - return this.taskNormalize; - } - - /** - * @return the taskRandomize - */ - public boolean isTaskRandomize() { - return this.taskRandomize; - } - - /** - * @return the taskSegregate - */ - public boolean isTaskSegregate() { - return this.taskSegregate; - } - - /** - * Reanalyze column ranges. - */ - public void reanalyze() { - final String rawID = this.script.getProperties().getPropertyFile( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE); - - final File rawFilename = this.analyst.getScript() - .resolveFilename(rawID); - - this.analyst.analyze( - rawFilename, - this.script.getProperties().getPropertyBoolean( - ScriptProperties.SETUP_CONFIG_INPUT_HEADERS), - this.script.getProperties().getPropertyFormat( - ScriptProperties.SETUP_CONFIG_CSV_FORMAT)); - - } - - /** - * Set the goal. - * @param theGoal The goal. - */ - public void setGoal(final AnalystGoal theGoal) { - this.goal = theGoal; - } - - /** - * @param theIncludeTargetField - * the includeTargetField to set - */ - public void setIncludeTargetField(final boolean theIncludeTargetField) { - this.includeTargetField = theIncludeTargetField; - } - - /** - * @param theLagWindowSize - * the lagWindowSize to set - */ - public void setLagWindowSize(final int theLagWindowSize) { - this.lagWindowSize = theLagWindowSize; - } - - /** - * @param theLeadWindowSize - * the leadWindowSize to set - */ - public void setLeadWindowSize(final int theLeadWindowSize) { - this.leadWindowSize = theLeadWindowSize; - } - - /** - * @param theMethodType - * the methodType to set - */ - public void setMethodType(final WizardMethodType theMethodType) { - this.methodType = theMethodType; - } - - /** - * @param theRange - * the range to set - */ - public void setRange(final NormalizeRange theRange) { - this.range = theRange; - } - - /** - * Set the target field. - * @param theTargetField The target field. - */ - public void setTargetField(final AnalystField theTargetField) { - this.targetField = theTargetField; - } - - /** - * @param theTaskBalance - * the taskBalance to set - */ - public void setTaskBalance(final boolean theTaskBalance) { - this.taskBalance = theTaskBalance; - } - - /** - * @param theTaskCluster - * the taskCluster to set - */ - public void setTaskCluster(final boolean theTaskCluster) { - this.taskCluster = theTaskCluster; - } - - /** - * @param theTaskNormalize - * the taskNormalize to set - */ - public void setTaskNormalize(final boolean theTaskNormalize) { - this.taskNormalize = theTaskNormalize; - } - - /** - * @param theTaskRandomize - * the taskRandomize to set - */ - public void setTaskRandomize(final boolean theTaskRandomize) { - this.taskRandomize = theTaskRandomize; - } - - /** - * @param theTaskSegregate - * the taskSegregate to set - */ - public void setTaskSegregate(final boolean theTaskSegregate) { - this.taskSegregate = theTaskSegregate; - } - - public void wizardRealTime(List sourceData, File csvFile) - { - this.script.setBasePath(csvFile.getParent()); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_SOURCE_HEADERS, true); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE, csvFile); - - this.timeSeries = ((this.lagWindowSize > 0) || (this.leadWindowSize > 0)); - this.format = AnalystFileFormat.DECPNT_COMMA; - - determineClassification(); - generateFilenames(csvFile); - generateSettings(); - //this.analyst.analyze(csvFile, b, format); - generateNormalizedFields(); - generateSegregate(); - - generateGenerate(); - - generateTasks(); - if (this.timeSeries && (this.lagWindowSize > 0) - && (this.leadWindowSize > 0)) { - expandTimeSlices(); - } - } - - /** - * Analyze a file. - * @param analyzeFile The file to analyze. - * @param b True if there are headers. - * @param format The file format. - */ - public void wizard(final File analyzeFile, final boolean b, - final AnalystFileFormat format) { - - this.script.setBasePath(analyzeFile.getParent()); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_SOURCE_HEADERS, b); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE, analyzeFile); - - this.timeSeries = ((this.lagWindowSize > 0) || (this.leadWindowSize > 0)); - this.format = format; - - determineClassification(); - generateFilenames(analyzeFile); - generateSettings(); - this.analyst.analyze(analyzeFile, b, format); - generateNormalizedFields(); - generateSegregate(); - generateCode(); - generateGenerate(); - - generateTasks(); - if (this.timeSeries && (this.lagWindowSize > 0) - && (this.leadWindowSize > 0)) { - expandTimeSlices(); - } - } - - private void generateCode() { - this.script.getProperties().setProperty(ScriptProperties.CODE_CONFIG_EMBED_DATA, this.codeEmbedData); - this.script.getProperties().setProperty(ScriptProperties.CODE_CONFIG_TARGET_LANGUAGE, this.codeTargetLanguage); - this.script.getProperties().setProperty(ScriptProperties.CODE_CONFIG_TARGET_FILE, AnalystWizard.FILE_CODE); - } - - /** - * Analyze a file at the specified URL. - * @param url The URL to analyze. - * @param saveFile The save file. - * @param analyzeFile The Encog analyst file. - * @param b True if there are headers. - * @param format The file format. - */ - public void wizard(final URL url, final File saveFile, - final File analyzeFile, final boolean b, - final AnalystFileFormat format) { - - this.script.setBasePath(saveFile.getParent()); - - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_SOURCE_FILE, url); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_SOURCE_HEADERS, b); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE, analyzeFile); - this.format = format; - - generateFilenames(analyzeFile); - generateSettings(); - this.analyst.download(); - - wizard(analyzeFile, b, format); - } - - /** - * @return the missing - */ - public HandleMissingValues getMissing() { - return missing; - } - - /** - * @param missing the missing to set - */ - public void setMissing(HandleMissingValues missing) { - this.missing = missing; - } - - /** - * @return the naiveBayes - */ - public boolean isNaiveBayes() { - return naiveBayes; - } - - /** - * @param naiveBayes the naiveBayes to set - */ - public void setNaiveBayes(boolean naiveBayes) { - this.naiveBayes = naiveBayes; - } - - /** - * @return the evidenceSegements - */ - public int getEvidenceSegements() { - return evidenceSegements; - } - - /** - * @param evidenceSegements the evidenceSegements to set - */ - public void setEvidenceSegements(int evidenceSegements) { - this.evidenceSegements = evidenceSegements; - } - - public double getMaxError() { - return maxError; - } - - public void setMaxError(double maxError) { - this.maxError = maxError; - } - - public void setTargetField(String theTargetField) { - this.targetFieldName = theTargetField; - - } - - /** - * @return the codeTargetLanguage - */ - public TargetLanguage getCodeTargetLanguage() { - return codeTargetLanguage; - } - - /** - * @param codeTargetLanguage the codeTargetLanguage to set - */ - public void setCodeTargetLanguage(TargetLanguage codeTargetLanguage) { - this.codeTargetLanguage = codeTargetLanguage; - } - - /** - * @return the codeEmbedData - */ - public boolean isCodeEmbedData() { - return codeEmbedData; - } - - /** - * @param codeEmbedData the codeEmbedData to set - */ - public void setCodeEmbedData(boolean codeEmbedData) { - this.codeEmbedData = codeEmbedData; - } - - - - - - -} diff --git a/All/Genesis-NP/Genesis#43/old/AnalystWizard.java b/All/Genesis-NP/Genesis#43/old/AnalystWizard.java deleted file mode 100755 index e5cfed5..0000000 --- a/All/Genesis-NP/Genesis#43/old/AnalystWizard.java +++ /dev/null @@ -1,1493 +0,0 @@ -/* - * Encog(tm) Core v3.1 - Java Version - * http://www.heatonresearch.com/encog/ - * http://code.google.com/p/encog-java/ - - * Copyright 2008-2012 Heaton Research, 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. - * - * For more information on Heaton Research copyrights, licenses - * and trademarks visit: - * http://www.heatonresearch.com/copyright - */ -package org.encog.app.analyst.wizard; - -import java.io.File; -import java.net.URL; -import java.util.ArrayList; -import java.util.List; - -import org.encog.Encog; -import org.encog.app.analyst.AnalystError; -import org.encog.app.analyst.AnalystFileFormat; -import org.encog.app.analyst.AnalystGoal; -import org.encog.app.analyst.EncogAnalyst; -import org.encog.app.analyst.missing.DiscardMissing; -import org.encog.app.analyst.missing.HandleMissingValues; -import org.encog.app.analyst.script.AnalystClassItem; -import org.encog.app.analyst.script.AnalystScript; -import org.encog.app.analyst.script.DataField; -import org.encog.app.analyst.script.normalize.AnalystField; -import org.encog.app.analyst.script.prop.ScriptProperties; -import org.encog.app.analyst.script.segregate.AnalystSegregateTarget; -import org.encog.app.analyst.script.task.AnalystTask; -import org.encog.app.generate.TargetLanguage; -import org.encog.ml.factory.MLMethodFactory; -import org.encog.ml.factory.MLTrainFactory; -import org.encog.util.arrayutil.NormalizationAction; -import org.encog.util.csv.CSVFormat; -import org.encog.util.file.FileUtil; - -/** - * The Encog Analyst Wizard can be used to create Encog Analyst script files - * from a CSV file. This class is typically used by the Encog Workbench, but it - * can easily be used from any program to create a starting point for an Encog - * Analyst Script. - * - * Several items must be provided to the wizard. - * - * Desired Machine Learning Method: This is the machine learning method that you - * would like the wizard to use. This might be a neural network, SVM or other - * supported method. - * - * Normalization Range: This is the range that the data should be normalized - * into. Some machine learning methods perform better with different ranges. The - * two ranges supported by the wizard are -1 to 1 and 0 to 1. - * - * Goal: What are we trying to accomplish. Is this a classification, regression - * or autoassociation problem. - * - */ -public class AnalystWizard { - - /** - * The default training percent. - */ - public static final int DEFAULT_TRAIN_PERCENT = 75; - - /** - * The default evaluation percent. - */ - public static final int DEFAULT_EVAL_PERCENT = 25; - - /** - * The default training error. - */ - public static final double DEFAULT_TRAIN_ERROR = 0.05; - - /** - * The raw file. - */ - public static final String FILE_RAW = "FILE_RAW"; - - /** - * The normalized file. - */ - public static final String FILE_NORMALIZE = "FILE_NORMALIZE"; - - /** - * The randomized file. - */ - public static final String FILE_RANDOM = "FILE_RANDOMIZE"; - - /** - * The training file. - */ - public static final String FILE_TRAIN = "FILE_TRAIN"; - - /** - * The evaluation file. - */ - public static final String FILE_EVAL = "FILE_EVAL"; - - /** - * The eval file normalization file. - */ - public static final String FILE_EVAL_NORM = "FILE_EVAL_NORM"; - - /** - * The training set. - */ - public static final String FILE_TRAINSET = "FILE_TRAINSET"; - - /** - * The machine learning file. - */ - public static final String FILE_ML = "FILE_ML"; - - /** - * The output file. - */ - public static final String FILE_OUTPUT = "FILE_OUTPUT"; - - /** - * The balanced file. - */ - public static final String FILE_BALANCE = "FILE_BALANCE"; - - /** - * The clustered file. - */ - public static final String FILE_CLUSTER = "FILE_CLUSTER"; - - /** - * The generated code file. - */ - public static final String FILE_CODE = "FILE_CODE"; - - /** - * The raw filename. - */ - private String filenameRaw; - - /** - * The normalized filename. - */ - private String filenameNorm; - - /** - * The random file name. - */ - private String filenameRandom; - - /** - * The training filename. - */ - private String filenameTrain; - - /** - * The evaluation filename. - */ - private String filenameEval; - - /** - * The normalization eval file name. - */ - private String filenameEvalNorm; - - /** - * The training set filename. - */ - private String filenameTrainSet; - - /** - * The machine learning file name. - */ - private String filenameML; - - /** - * The output filename. - */ - private String filenameOutput; - - /** - * The balance filename. - */ - private String filenameBalance; - - /** - * The cluster filename. - */ - private String filenameCluster; - - /** - * The filename that code will be generated to. - */ - private String filenameCode; - - /** - * The analyst script. - */ - private final AnalystScript script; - - /** - * The analyst. - */ - private final EncogAnalyst analyst; - - /** - * The machine learning method that we will be using. - */ - private WizardMethodType methodType; - - /** - * Are we using single-field(direct) classification. - */ - private boolean directClassification = false; - - /** - * The target field, or "" to detect. - */ - private AnalystField targetField; - - /** - * The analyst goal. - */ - private AnalystGoal goal; - - /** - * The size of the lag window, if we are doing time-series. - */ - private int lagWindowSize; - - /** - * The size of the lead window, if we are doing time-series. - */ - private int leadWindowSize; - - /** - * Should the target field be included in the input, if we are doing - * time-series. - */ - private boolean includeTargetField; - - /** - * True if we are doing time-series. - */ - private boolean timeSeries; - - /** - * True if the segregate command should be generated. - */ - private boolean taskSegregate = true; - - /** - * True if the randomize command should be generated. - */ - private boolean taskRandomize = true; - - /** - * True if the normalize command should be generated. - */ - private boolean taskNormalize = true; - - /** - * True if the balance command should be generated. - */ - private boolean taskBalance = false; - - /** - * True if the cluster command should be generated. - */ - private boolean taskCluster = true; - - /** - * The normalization range. - */ - private NormalizeRange range = NormalizeRange.NegOne2One; - - /** - * What to do with missing values. - */ - private HandleMissingValues missing = new DiscardMissing(); - - /** - * The format being used. - */ - private AnalystFileFormat format; - - private boolean naiveBayes = false; - - private int evidenceSegements = 3; - - private double maxError = DEFAULT_TRAIN_ERROR; - - private String targetFieldName; - - private TargetLanguage codeTargetLanguage; - - private boolean codeEmbedData; - - /** - * Construct the analyst wizard. - * @param theAnalyst The analyst to use. - */ - public AnalystWizard(final EncogAnalyst theAnalyst) { - this.analyst = theAnalyst; - this.script = analyst.getScript(); - this.methodType = WizardMethodType.FeedForward; - this.targetField = null; - this.goal = AnalystGoal.Classification; - this.leadWindowSize = 0; - this.lagWindowSize = 0; - this.includeTargetField = false; - } - - /** - * Create a "set" command to add to a task. - * @param setTarget The target. - * @param setSource The source. - * @return The "set" command. - */ - private String createSet(final String setTarget, final String setSource) { - final StringBuilder result = new StringBuilder(); - result.append("set "); - result.append(ScriptProperties.toDots(setTarget)); - result.append("=\""); - result.append(setSource); - result.append("\""); - return result.toString(); - } - - /** - * Determine the type of classification used. - */ - private void determineClassification() { - this.directClassification = false; - - if ((this.methodType == WizardMethodType.SVM) - || (this.methodType == WizardMethodType.SOM) - || (this.methodType == WizardMethodType.PNN)) { - this.directClassification = true; - } - } - - /** - * Determine the target field. - */ - private void determineTargetField() { - final List fields = this.script.getNormalize() - .getNormalizedFields(); - - if (this.targetFieldName == null || this.targetFieldName.length()==0 ) { - boolean success = false; - - if (this.goal == AnalystGoal.Classification) { - // first try to the last classify field - for (final AnalystField field : fields) { - final DataField df = this.script.findDataField(field - .getName()); - if (field.getAction().isClassify() && df.isClass()) { - this.targetField = field; - success = true; - } - } - } else { - - // otherwise, just return the last regression field - for (final AnalystField field : fields) { - final DataField df = this.script - .findDataField(field.getName()); - if (!df.isClass() && (df.isReal() || df.isInteger())) { - this.targetField = field; - success = true; - } - } - } - - if (!success) { - throw new AnalystError( - "Can't determine target field automatically, " - + "please specify one.\nThis can also happen if you " - + "specified the wrong file format."); - } - } else { - this.targetField = this.script.findAnalystField(this.targetFieldName); - if ( this.targetField == null) { - throw new AnalystError("Invalid target field: " - + this.targetField); - } - } - - this.script.getProperties().setProperty( - ScriptProperties.DATA_CONFIG_GOAL, this.goal); - - if (!this.timeSeries && this.taskBalance) { - this.script.getProperties().setProperty( - ScriptProperties.BALANCE_CONFIG_BALANCE_FIELD, - this.targetField.getName()); - final DataField field = this.analyst.getScript().findDataField( - this.targetField.getName()); - if ((field != null) && field.isClass()) { - final int countPer = field.getMinClassCount(); - this.script.getProperties().setProperty( - ScriptProperties.BALANCE_CONFIG_COUNT_PER, countPer); - } - } - - // determine output field - if (this.methodType != WizardMethodType.BayesianNetwork) { - // now that the target field has been determined, set the analyst fields - AnalystField af = null; - for (final AnalystField field : this.analyst.getScript() - .getNormalize().getNormalizedFields()) { - if ((field.getAction() != NormalizationAction.Ignore) - && field == this.targetField) { - if ((af == null) - || (af.getTimeSlice() < field.getTimeSlice())) { - af = field; - } - } - } - - if (af != null) { - af.setOutput(true); - } - } - - // set the clusters count - if (this.taskCluster) { - if ((this.targetField == null) - || (this.goal != AnalystGoal.Classification)) { - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_CLUSTERS, 2); - } else { - final DataField tf = this.script.findDataField(this.targetField - .getName()); - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_CLUSTERS, - tf.getClassMembers().size()); - } - } - } - - /** - * Expand the time-series fields. - */ - private void expandTimeSlices() { - final List oldList = this.script.getNormalize() - .getNormalizedFields(); - final List newList = new ArrayList(); - - // generate the inputs for the new list - for (final AnalystField field : oldList) { - if (!field.isIgnored()) { - - if (this.includeTargetField || field.isInput()) { - for (int i = 0; i < this.lagWindowSize; i++) { - final AnalystField newField = new AnalystField(field); - newField.setTimeSlice(-i); - newField.setOutput(false); - newList.add(newField); - } - } - } else { - newList.add(field); - } - } - - // generate the outputs for the new list - for (final AnalystField field : oldList) { - if (!field.isIgnored()) { - if (field.isOutput()) { - for (int i = 1; i <= this.leadWindowSize; i++) { - final AnalystField newField = new AnalystField(field); - newField.setTimeSlice(i); - newList.add(newField); - } - } - } - } - - // generate the ignores for the new list - for (final AnalystField field : oldList) { - if (field.isIgnored()) { - newList.add(field); - } - } - - // swap back in - oldList.clear(); - oldList.addAll(newList); - - } - - /** - * Generate a feed forward machine learning method. - * @param inputColumns The input column count. - * @param outputColumns The output column count. - */ - private void generateFeedForward(final int inputColumns, - final int outputColumns) { - final int hidden = (int) ((inputColumns) * 1.5); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, - MLMethodFactory.TYPE_FEEDFORWARD); - - if (this.range == NormalizeRange.NegOne2One) { - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, - "?:B->TANH->" + hidden + ":B->TANH->?"); - } else { - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, - "?:B->SIGMOID->" + hidden + ":B->SIGMOID->?"); - } - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - "rprop"); - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate a Bayesian network machine learning method. - * @param inputColumns The input column count. - * @param outputColumns The output column count. - */ - private void generateBayesian(final int inputColumns, - final int outputColumns) { - - int segment = this.evidenceSegements; - - if( !this.targetField.isClassify() ) { - throw new AnalystError("Bayesian networks cannot be used for regression."); - } - - StringBuilder a = new StringBuilder(); - for (DataField field : this.analyst.getScript().getFields()) { - a.append("P("); - a.append(field.getName()); - - // handle actual class members - if (field.getClassMembers().size() > 0) { - a.append("["); - boolean first = true; - for (AnalystClassItem item : field.getClassMembers()) { - if (!first) { - a.append(","); - } - a.append(item.getCode()); - first = false; - } - - // append a "fake" member, if there is only one - if( field.getClassMembers().size()==1 ) { - a.append(",Other0"); - } - - a.append("]"); - } else { - a.append("["); - // handle ranges - double size = Math.abs(field.getMax() - field.getMin()); - double per = size / segment; - - if (size < Encog.DEFAULT_DOUBLE_EQUAL) { - double low = field.getMin() - 0.0001; - double hi = field.getMin() + 0.0001; - a.append("BELOW: " + (low - 100) + " to " + hi + ","); - a.append("Type0: " + low + " to " + hi + ","); - a.append("ABOVE: " + hi + " to " + (hi + 100)); - } else { - boolean first = true; - for (int i = 0; i < segment; i++) { - if (!first) { - a.append(","); - } - double low = field.getMin() + (per * i); - double hi = i == (segment - 1) ? (field.getMax()) - : (low + per); - a.append("Type"); - a.append(i); - a.append(":"); - a.append(CSVFormat.EG_FORMAT.format(low, 16)); - a.append(" to "); - a.append(CSVFormat.EG_FORMAT.format(hi, 16)); - first = false; - } - } - a.append("]"); - } - - a.append(") "); - } - - StringBuilder q = new StringBuilder(); - q.append("P("); - q.append(this.targetField.getName()); - q.append("|"); - boolean first = true; - for (DataField field : this.analyst.getScript().getFields()) { - if (!field.getName().equals(this.targetField.getName())) { - if (!first) { - q.append(","); - } - q.append(field.getName()); - first = false; - } - } - q.append(")"); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, MLMethodFactory.TYPE_BAYESIAN); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, a.toString()); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_QUERY, q.toString()); - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - "bayesian"); - - if (this.naiveBayes) { - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_ARGUMENTS, - "maxParents=1,estimator=simple,search=none,init=naive"); - } else { - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_ARGUMENTS, - "maxParents=1,estimator=simple,search=k2,init=naive"); - } - - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate filenames. - * @param rawFile The raw filename. - */ - private void generateFilenames(final File rawFile) { - this.filenameRaw = rawFile.getName(); - this.filenameNorm = FileUtil.addFilenameBase(rawFile, "_norm") - .getName(); - this.filenameRandom = FileUtil.addFilenameBase(rawFile, "_random") - .getName(); - this.filenameTrain = FileUtil.addFilenameBase(rawFile, "_train") - .getName(); - this.filenameEval = FileUtil.addFilenameBase(rawFile, "_eval") - .getName(); - this.filenameEvalNorm = FileUtil.addFilenameBase(rawFile, "_eval_norm") - .getName(); - this.filenameTrainSet = FileUtil.forceExtension(this.filenameTrain, - "egb"); - this.filenameML = FileUtil.forceExtension(this.filenameTrain, "eg"); - this.filenameOutput = FileUtil.addFilenameBase(rawFile, "_output") - .getName(); - this.filenameBalance = FileUtil.addFilenameBase(rawFile, "_balance") - .getName(); - this.filenameCluster = FileUtil.addFilenameBase(rawFile, "_cluster") - .getName(); - this.filenameCode = FileUtil.forceExtension( FileUtil.addFilenameBase(rawFile, "_code").getName(), - this.codeTargetLanguage.getExtension()); - - final ScriptProperties p = this.script.getProperties(); - - p.setFilename(AnalystWizard.FILE_RAW, this.filenameRaw); - if (this.taskNormalize) { - p.setFilename(AnalystWizard.FILE_NORMALIZE, this.filenameNorm); - } - - if (this.taskRandomize) { - p.setFilename(AnalystWizard.FILE_RANDOM, this.filenameRandom); - } - - if (this.taskCluster) { - p.setFilename(AnalystWizard.FILE_CLUSTER, this.filenameCluster); - } - - if (this.taskSegregate) { - p.setFilename(AnalystWizard.FILE_TRAIN, this.filenameTrain); - p.setFilename(AnalystWizard.FILE_EVAL, this.filenameEval); - p.setFilename(AnalystWizard.FILE_EVAL_NORM, this.filenameEvalNorm); - } - - if (this.taskBalance) { - p.setFilename(AnalystWizard.FILE_BALANCE, this.filenameBalance); - } - - if (this.codeTargetLanguage != TargetLanguage.NoGeneration ) { - p.setFilename(AnalystWizard.FILE_CODE, this.filenameCode); - } - - p.setFilename(AnalystWizard.FILE_TRAINSET, this.filenameTrainSet); - p.setFilename(AnalystWizard.FILE_ML, this.filenameML); - p.setFilename(AnalystWizard.FILE_OUTPUT, this.filenameOutput); - - } - - /** - * Generate the generate task. - */ - private void generateGenerate() { - determineTargetField(); - - if (this.targetField == null) { - throw new AnalystError( - "Failed to find normalized version of target field: " - + this.targetField); - } - - final int inputColumns = this.script.getNormalize() - .calculateInputColumns(); - final int idealColumns = this.script.getNormalize() - .calculateOutputColumns(); - - switch (this.methodType) { - case BayesianNetwork: - generateBayesian(inputColumns, idealColumns); - break; - case FeedForward: - generateFeedForward(inputColumns, idealColumns); - break; - case SVM: - generateSVM(inputColumns, idealColumns); - break; - case RBF: - generateRBF(inputColumns, idealColumns); - break; - case SOM: - generateSOM(inputColumns); - break; - case PNN: - generatePNN(inputColumns, idealColumns); - break; - default: - throw new AnalystError("Unknown method type"); - } - } - - /** - * Generate the normalized fields. - */ - private void generateNormalizedFields() { - final List norm = this.script.getNormalize() - .getNormalizedFields(); - norm.clear(); - final DataField[] dataFields = this.script.getFields(); - - for (int i = 0; i < this.script.getFields().length; i++) { - final DataField f = dataFields[i]; - - NormalizationAction action; - final boolean isLast = i == this.script.getFields().length - 1; - - if (this.methodType == WizardMethodType.BayesianNetwork) { - AnalystField af; - if (f.isClass()) { - af = new AnalystField(f.getName(), - NormalizationAction.SingleField, 0, 0); - } else { - af = new AnalystField(f.getName(), - NormalizationAction.PassThrough, 0, 0); - } - norm.add(af); - } else if ((f.isInteger() || f.isReal()) && !f.isClass()) { - action = NormalizationAction.Normalize; - AnalystField af; - if (this.range == NormalizeRange.NegOne2One) { - af = new AnalystField(f.getName(), action, 1, -1); - } else { - af = new AnalystField(f.getName(), action, 1, 0); - } - norm.add(af); - af.setActualHigh(f.getMax()); - af.setActualLow(f.getMin()); - } else if (f.isClass()) { - if (isLast && this.directClassification) { - action = NormalizationAction.SingleField; - } else if (f.getClassMembers().size() > 2) { - action = NormalizationAction.Equilateral; - } else { - action = NormalizationAction.OneOf; - } - - if (this.range == NormalizeRange.NegOne2One) { - norm.add(new AnalystField(f.getName(), action, 1, -1)); - } else { - norm.add(new AnalystField(f.getName(), action, 1, 0)); - } - } else { - action = NormalizationAction.Ignore; - norm.add(new AnalystField(action, f.getName())); - } - } - - this.script.getNormalize().init(this.script); - } - - /** - * Generate a RBF machine learning method. - * @param inputColumns The number of input columns. - * @param outputColumns The number of output columns. - */ - private void generateRBF(final int inputColumns, final int outputColumns) { - final int hidden = (int) ((inputColumns) * 1.5); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, - MLMethodFactory.TYPE_RBFNETWORK); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, - "?->GAUSSIAN(c=" + hidden + ")->?"); - - if (outputColumns > 1) { - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TYPE, "rprop"); - } else { - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TYPE, "svd"); - } - - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate the segregate task. - */ - private void generateSegregate() { - if (this.taskSegregate) { - final AnalystSegregateTarget[] array = new AnalystSegregateTarget[2]; - array[0] = new AnalystSegregateTarget(AnalystWizard.FILE_TRAIN, - DEFAULT_TRAIN_PERCENT); - array[1] = new AnalystSegregateTarget(AnalystWizard.FILE_EVAL, - DEFAULT_EVAL_PERCENT); - this.script.getSegregate().setSegregateTargets(array); - } else { - final AnalystSegregateTarget[] array = new AnalystSegregateTarget[0]; - this.script.getSegregate().setSegregateTargets(array); - } - } - - /** - * Generate the settings. - */ - private void generateSettings() { - - String target; - String evalSource; - - // starting point - target = AnalystWizard.FILE_RAW; - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE, target); - - // randomize - if (!this.timeSeries && this.taskRandomize) { - this.script.getProperties().setProperty( - ScriptProperties.RANDOMIZE_CONFIG_SOURCE_FILE, - AnalystWizard.FILE_RAW); - target = AnalystWizard.FILE_RANDOM; - this.script.getProperties().setProperty( - ScriptProperties.RANDOMIZE_CONFIG_TARGET_FILE, target); - } - - // balance - if (!this.timeSeries && this.taskBalance) { - this.script.getProperties().setProperty( - ScriptProperties.BALANCE_CONFIG_SOURCE_FILE, target); - target = AnalystWizard.FILE_BALANCE; - this.script.getProperties().setProperty( - ScriptProperties.BALANCE_CONFIG_TARGET_FILE, target); - } - - // segregate - if (this.taskSegregate) { - this.script.getProperties().setProperty( - ScriptProperties.SEGREGATE_CONFIG_SOURCE_FILE, target); - target = AnalystWizard.FILE_TRAIN; - } - - // normalize - if (this.taskNormalize) { - this.script.getProperties().setProperty( - ScriptProperties.NORMALIZE_CONFIG_SOURCE_FILE, target); - target = AnalystWizard.FILE_NORMALIZE; - this.script.getProperties().setProperty( - ScriptProperties.NORMALIZE_CONFIG_TARGET_FILE, target); - - this.script.getNormalize().setMissingValues(this.missing); - } - - if (this.taskSegregate) { - evalSource = AnalystWizard.FILE_EVAL; - } else { - evalSource = target; - } - - // cluster - if (this.taskCluster) { - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_SOURCE_FILE, evalSource); - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_TARGET_FILE, - AnalystWizard.FILE_CLUSTER); - this.script.getProperties().setProperty( - ScriptProperties.CLUSTER_CONFIG_TYPE, "kmeans"); - } - - // generate - this.script.getProperties().setProperty( - ScriptProperties.GENERATE_CONFIG_SOURCE_FILE, target); - this.script.getProperties().setProperty( - ScriptProperties.GENERATE_CONFIG_TARGET_FILE, - AnalystWizard.FILE_TRAINSET); - - // ML - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TRAINING_FILE, - AnalystWizard.FILE_TRAINSET); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_MACHINE_LEARNING_FILE, - AnalystWizard.FILE_ML); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_OUTPUT_FILE, - AnalystWizard.FILE_OUTPUT); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_EVAL_FILE, evalSource); - - // other - this.script.getProperties().setProperty( - ScriptProperties.SETUP_CONFIG_CSV_FORMAT, format); - } - - /** - * Generate a SOM machine learning method. - * @param inputColumns The number of input columns. - */ - private void generateSOM(final int inputColumns) { - - if( !this.targetField.isClassify() ) { - throw new AnalystError("SOM cannot be used for regression."); - } - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, MLMethodFactory.TYPE_SOM); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, "?->" + this.targetField.getClasses().size()); - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - MLTrainFactory.TYPE_SOM_NEIGHBORHOOD); - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_ARGUMENTS, - "ITERATIONS=1000,NEIGHBORHOOD=rbf1d,RBF_TYPE=gaussian"); - - // ScriptProperties.ML_TRAIN_arguments - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate a SVM machine learning method. - * @param inputColumns The number of input columns. - * @param outputColumns The number of ideal columns. - */ - private void generateSVM(final int inputColumns, final int outputColumns) { - - StringBuilder arch = new StringBuilder(); - arch.append("?->"); - if (this.goal == AnalystGoal.Classification) { - arch.append("C"); - } else { - arch.append("R"); - } - arch.append("(type=new,kernel=rbf)->?"); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, MLMethodFactory.TYPE_SVM); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, arch.toString()); - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - MLTrainFactory.TYPE_SVM_SEARCH); - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate a PNN machine learning method. - * @param inputColumns The number of input columns. - * @param outputColumns The number of ideal columns. - */ - private void generatePNN(final int inputColumns, final int outputColumns) { - - StringBuilder arch = new StringBuilder(); - arch.append("?->"); - if (this.goal == AnalystGoal.Classification) { - arch.append("C"); - } else { - arch.append("R"); - } - arch.append("(kernel=gaussian)->"); - arch.append(this.targetField.getClasses().size()); - - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_TYPE, MLMethodFactory.TYPE_PNN); - this.script.getProperties().setProperty( - ScriptProperties.ML_CONFIG_ARCHITECTURE, arch.toString()); - - this.script.getProperties().setProperty(ScriptProperties.ML_TRAIN_TYPE, - MLTrainFactory.TYPE_PNN); - this.script.getProperties().setProperty( - ScriptProperties.ML_TRAIN_TARGET_ERROR, this.maxError); - } - - /** - * Generate the tasks. - */ - private void generateTasks() { - final AnalystTask task1 = new AnalystTask(EncogAnalyst.TASK_FULL); - if (!this.timeSeries && this.taskRandomize) { - task1.getLines().add("randomize"); - } - - if (!this.timeSeries && this.taskBalance) { - task1.getLines().add("balance"); - } - - if (this.taskSegregate) { - task1.getLines().add("segregate"); - } - - if (this.taskNormalize) { - task1.getLines().add("normalize"); - } - - task1.getLines().add("generate"); - task1.getLines().add("create"); - task1.getLines().add("train"); - task1.getLines().add("evaluate"); - - if( this.codeTargetLanguage!=TargetLanguage.NoGeneration) { - task1.getLines().add("code"); - } - - final AnalystTask task2 = new AnalystTask("task-generate"); - if (!this.timeSeries && this.taskRandomize) { - task2.getLines().add("randomize"); - } - - if (this.taskSegregate) { - task2.getLines().add("segregate"); - } - if (this.taskNormalize) { - task2.getLines().add("normalize"); - } - task2.getLines().add("generate"); - - final AnalystTask task3 = new AnalystTask("task-evaluate-raw"); - task3.getLines().add( - createSet(ScriptProperties.ML_CONFIG_EVAL_FILE, - AnalystWizard.FILE_EVAL_NORM)); - task3.getLines().add( - createSet(ScriptProperties.NORMALIZE_CONFIG_SOURCE_FILE, - AnalystWizard.FILE_EVAL)); - task3.getLines().add( - createSet(ScriptProperties.NORMALIZE_CONFIG_TARGET_FILE, - AnalystWizard.FILE_EVAL_NORM)); - task3.getLines().add("normalize"); - task3.getLines().add("evaluate-raw"); - - final AnalystTask task4 = new AnalystTask("task-create"); - task4.getLines().add("create"); - - final AnalystTask task5 = new AnalystTask("task-train"); - task5.getLines().add("train"); - - final AnalystTask task6 = new AnalystTask("task-evaluate"); - task6.getLines().add("evaluate"); - - final AnalystTask task7 = new AnalystTask("task-cluster"); - task7.getLines().add("cluster"); - - final AnalystTask task8 = new AnalystTask("task-code"); - task7.getLines().add("code"); - - this.script.addTask(task1); - this.script.addTask(task2); - this.script.addTask(task3); - this.script.addTask(task4); - this.script.addTask(task5); - this.script.addTask(task6); - this.script.addTask(task7); - this.script.addTask(task8); - } - - /** - * @return The analyst goal. - */ - public AnalystGoal getGoal() { - return this.goal; - } - - /** - * @return the lagWindowSize - */ - public int getLagWindowSize() { - return this.lagWindowSize; - } - - /** - * @return the leadWindowSize - */ - public int getLeadWindowSize() { - return this.leadWindowSize; - } - - /** - * @return the methodType - */ - public WizardMethodType getMethodType() { - return this.methodType; - } - - /** - * @return the range - */ - public NormalizeRange getRange() { - return this.range; - } - - /** - * @return Get the target field. - */ - public AnalystField getTargetField() { - return this.targetField; - } - - /** - * @return the includeTargetField - */ - public boolean isIncludeTargetField() { - return this.includeTargetField; - } - - /** - * @return the taskBalance - */ - public boolean isTaskBalance() { - return this.taskBalance; - } - - /** - * @return the taskCluster - */ - public boolean isTaskCluster() { - return this.taskCluster; - } - - /** - * @return the taskNormalize - */ - public boolean isTaskNormalize() { - return this.taskNormalize; - } - - /** - * @return the taskRandomize - */ - public boolean isTaskRandomize() { - return this.taskRandomize; - } - - /** - * @return the taskSegregate - */ - public boolean isTaskSegregate() { - return this.taskSegregate; - } - - /** - * Reanalyze column ranges. - */ - public void reanalyze() { - final String rawID = this.script.getProperties().getPropertyFile( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE); - - final File rawFilename = this.analyst.getScript() - .resolveFilename(rawID); - - this.analyst.analyze( - rawFilename, - this.script.getProperties().getPropertyBoolean( - ScriptProperties.SETUP_CONFIG_INPUT_HEADERS), - this.script.getProperties().getPropertyFormat( - ScriptProperties.SETUP_CONFIG_CSV_FORMAT)); - - } - - /** - * Set the goal. - * @param theGoal The goal. - */ - public void setGoal(final AnalystGoal theGoal) { - this.goal = theGoal; - } - - /** - * @param theIncludeTargetField - * the includeTargetField to set - */ - public void setIncludeTargetField(final boolean theIncludeTargetField) { - this.includeTargetField = theIncludeTargetField; - } - - /** - * @param theLagWindowSize - * the lagWindowSize to set - */ - public void setLagWindowSize(final int theLagWindowSize) { - this.lagWindowSize = theLagWindowSize; - } - - /** - * @param theLeadWindowSize - * the leadWindowSize to set - */ - public void setLeadWindowSize(final int theLeadWindowSize) { - this.leadWindowSize = theLeadWindowSize; - } - - /** - * @param theMethodType - * the methodType to set - */ - public void setMethodType(final WizardMethodType theMethodType) { - this.methodType = theMethodType; - } - - /** - * @param theRange - * the range to set - */ - public void setRange(final NormalizeRange theRange) { - this.range = theRange; - } - - /** - * Set the target field. - * @param theTargetField The target field. - */ - public void setTargetField(final AnalystField theTargetField) { - this.targetField = theTargetField; - } - - /** - * @param theTaskBalance - * the taskBalance to set - */ - public void setTaskBalance(final boolean theTaskBalance) { - this.taskBalance = theTaskBalance; - } - - /** - * @param theTaskCluster - * the taskCluster to set - */ - public void setTaskCluster(final boolean theTaskCluster) { - this.taskCluster = theTaskCluster; - } - - /** - * @param theTaskNormalize - * the taskNormalize to set - */ - public void setTaskNormalize(final boolean theTaskNormalize) { - this.taskNormalize = theTaskNormalize; - } - - /** - * @param theTaskRandomize - * the taskRandomize to set - */ - public void setTaskRandomize(final boolean theTaskRandomize) { - this.taskRandomize = theTaskRandomize; - } - - /** - * @param theTaskSegregate - * the taskSegregate to set - */ - public void setTaskSegregate(final boolean theTaskSegregate) { - this.taskSegregate = theTaskSegregate; - } - - public void wizardRealTime(List sourceData, File csvFile) - { - this.script.setBasePath(csvFile.getParent()); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_SOURCE_HEADERS, true); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE, csvFile); - - this.timeSeries = ((this.lagWindowSize > 0) || (this.leadWindowSize > 0)); - this.format = AnalystFileFormat.DECPNT_COMMA; - - determineClassification(); - generateFilenames(csvFile); - generateSettings(); - //this.analyst.analyze(csvFile, b, format); - generateNormalizedFields(); - generateSegregate(); - - generateGenerate(); - - generateTasks(); - if (this.timeSeries && (this.lagWindowSize > 0) - && (this.leadWindowSize > 0)) { - expandTimeSlices(); - } - } - - /** - * Analyze a file. - * @param analyzeFile The file to analyze. - * @param b True if there are headers. - * @param format The file format. - */ - public void wizard(final File analyzeFile, final boolean b, - final AnalystFileFormat format) { - - this.script.setBasePath(analyzeFile.getParent()); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_SOURCE_HEADERS, b); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE, analyzeFile); - - this.timeSeries = ((this.lagWindowSize > 0) || (this.leadWindowSize > 0)); - this.format = format; - - determineClassification(); - generateFilenames(analyzeFile); - generateSettings(); - this.analyst.analyze(analyzeFile, b, format); - generateNormalizedFields(); - generateSegregate(); - generateCode(); - generateGenerate(); - - generateTasks(); - if (this.timeSeries && (this.lagWindowSize > 0) - && (this.leadWindowSize > 0)) { - expandTimeSlices(); - } - } - - private void generateCode() { - this.script.getProperties().setProperty(ScriptProperties.CODE_CONFIG_EMBED_DATA, this.codeEmbedData); - this.script.getProperties().setProperty(ScriptProperties.CODE_CONFIG_TARGET_LANGUAGE, this.codeTargetLanguage); - this.script.getProperties().setProperty(ScriptProperties.CODE_CONFIG_TARGET_FILE, AnalystWizard.FILE_CODE); - } - - /** - * Analyze a file at the specified URL. - * @param url The URL to analyze. - * @param saveFile The save file. - * @param analyzeFile The Encog analyst file. - * @param b True if there are headers. - * @param format The file format. - */ - public void wizard(final URL url, final File saveFile, - final File analyzeFile, final boolean b, - final AnalystFileFormat format) { - - this.script.setBasePath(saveFile.getParent()); - - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_SOURCE_FILE, url); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_SOURCE_HEADERS, b); - this.script.getProperties().setProperty( - ScriptProperties.HEADER_DATASOURCE_RAW_FILE, analyzeFile); - this.format = format; - - generateFilenames(analyzeFile); - generateSettings(); - this.analyst.download(); - - wizard(analyzeFile, b, format); - } - - /** - * @return the missing - */ - public HandleMissingValues getMissing() { - return missing; - } - - /** - * @param missing the missing to set - */ - public void setMissing(HandleMissingValues missing) { - this.missing = missing; - } - - /** - * @return the naiveBayes - */ - public boolean isNaiveBayes() { - return naiveBayes; - } - - /** - * @param naiveBayes the naiveBayes to set - */ - public void setNaiveBayes(boolean naiveBayes) { - this.naiveBayes = naiveBayes; - } - - /** - * @return the evidenceSegements - */ - public int getEvidenceSegements() { - return evidenceSegements; - } - - /** - * @param evidenceSegements the evidenceSegements to set - */ - public void setEvidenceSegements(int evidenceSegements) { - this.evidenceSegements = evidenceSegements; - } - - public double getMaxError() { - return maxError; - } - - public void setMaxError(double maxError) { - this.maxError = maxError; - } - - public void setTargetField(String theTargetField) { - this.targetFieldName = theTargetField; - - } - - /** - * @return the codeTargetLanguage - */ - public TargetLanguage getCodeTargetLanguage() { - return codeTargetLanguage; - } - - /** - * @param codeTargetLanguage the codeTargetLanguage to set - */ - public void setCodeTargetLanguage(TargetLanguage codeTargetLanguage) { - this.codeTargetLanguage = codeTargetLanguage; - } - - /** - * @return the codeEmbedData - */ - public boolean isCodeEmbedData() { - return codeEmbedData; - } - - /** - * @param codeEmbedData the codeEmbedData to set - */ - public void setCodeEmbedData(boolean codeEmbedData) { - this.codeEmbedData = codeEmbedData; - } - - - - - - -} diff --git a/All/Genesis-NP/Genesis#43/pair.info b/All/Genesis-NP/Genesis#43/pair.info deleted file mode 100755 index 22761d6..0000000 --- a/All/Genesis-NP/Genesis#43/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:43 -SATName:Genesis -modifiedFPath:src/main/java/org/encog/app/analyst/wizard/AnalystWizard.java -comSha:e9e4421d0cd59608f828ea441b003f46f4b02d43 -parentComSha:e9e4421d0cd59608f828ea441b003f46f4b02d43^1 -githubUrl:https://github.com/encog/encog-java-core -repoName:encog#encog-java-core \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#430/comMsg.txt b/All/Genesis-NP/Genesis#430/comMsg.txt deleted file mode 100755 index 70f17d7..0000000 --- a/All/Genesis-NP/Genesis#430/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed Nullpointer exception in KafkaWriter diff --git a/All/Genesis-NP/Genesis#430/diff.diff b/All/Genesis-NP/Genesis#430/diff.diff deleted file mode 100755 index f61ecfb..0000000 --- a/All/Genesis-NP/Genesis#430/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/jmxtrans-output/jmxtrans-output-kafka/src/main/java/com/googlecode/jmxtrans/model/output/kafka/KafkaWriter.java b/jmxtrans-output/jmxtrans-output-kafka/src/main/java/com/googlecode/jmxtrans/model/output/kafka/KafkaWriter.java -index 4da1a15..6789f5e 100644 ---- a/jmxtrans-output/jmxtrans-output-kafka/src/main/java/com/googlecode/jmxtrans/model/output/kafka/KafkaWriter.java -+++ b/jmxtrans-output/jmxtrans-output-kafka/src/main/java/com/googlecode/jmxtrans/model/output/kafka/KafkaWriter.java -@@ -32 +31,0 @@ import kafka.producer.ProducerConfig; -- -@@ -73,0 +73,2 @@ public class KafkaWriter extends BaseOutputWriter { -+ if (topics == null) -+ throw new NullPointerException("Topics cannot be null."); -@@ -80 +81 @@ public class KafkaWriter extends BaseOutputWriter { -- this.topics = asList(topics.split(",")); -+ this.topics = asList(Settings.getStringSetting(settings, "topics", "").split(",")); diff --git a/All/Genesis-NP/Genesis#430/new/KafkaWriter.java b/All/Genesis-NP/Genesis#430/new/KafkaWriter.java deleted file mode 100755 index 6789f5e..0000000 --- a/All/Genesis-NP/Genesis#430/new/KafkaWriter.java +++ /dev/null @@ -1,136 +0,0 @@ -package com.googlecode.jmxtrans.model.output.kafka; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerator; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableList; -import com.google.common.io.Closer; -import com.googlecode.jmxtrans.model.Query; -import com.googlecode.jmxtrans.model.Result; -import com.googlecode.jmxtrans.model.Server; -import com.googlecode.jmxtrans.model.ValidationException; -import com.googlecode.jmxtrans.model.output.BaseOutputWriter; -import com.googlecode.jmxtrans.model.output.Settings; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.annotation.concurrent.NotThreadSafe; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Map.Entry; - -import kafka.javaapi.producer.Producer; -import kafka.producer.KeyedMessage; -import kafka.producer.ProducerConfig; -import static com.fasterxml.jackson.core.JsonEncoding.UTF8; -import static com.googlecode.jmxtrans.model.PropertyResolver.resolveProps; -import static com.googlecode.jmxtrans.model.naming.KeyUtils.getKeyString; -import static com.googlecode.jmxtrans.util.NumberUtils.isNumeric; -import static java.util.Arrays.asList; - -/** - * This low latency and thread safe output writer sends data to a kafka topics in JSON format. - * Kafka Topics can be passed as separated by commas such as kafka01,kafka02. - * - * @author : utkarsh bhatnagar - * @github user : utkarshcmu - * @email : utkarsh.cmu@gmail.com - */ - -@NotThreadSafe -public class KafkaWriter extends BaseOutputWriter { - - private static final Logger log = LoggerFactory.getLogger(KafkaWriter.class); - - private static final String DEFAULT_ROOT_PREFIX = "servers"; - private final JsonFactory jsonFactory; - - private Producer producer; - private final Iterable topics; - private final String rootPrefix; - - @JsonCreator - public KafkaWriter( - @JsonProperty("typeNames") ImmutableList typeNames, - @JsonProperty("booleanAsNumber") boolean booleanAsNumber, - @JsonProperty("rootPrefix") String rootPrefix, - @JsonProperty("debug") Boolean debugEnabled, - @JsonProperty("topics") String topics, - @JsonProperty("settings") Map settings) { - super(typeNames, booleanAsNumber, debugEnabled, settings); - this.rootPrefix = resolveProps( - firstNonNull( - rootPrefix, - (String) getSettings().get("rootPrefix"), - DEFAULT_ROOT_PREFIX)); - if (topics == null) - throw new NullPointerException("Topics cannot be null."); - // Setting all the required Kafka Properties - Properties kafkaProperties = new Properties(); - kafkaProperties.setProperty("metadata.broker.list", Settings.getStringSetting(settings, "metadata.broker.list", null)); - kafkaProperties.setProperty("zk.connect", Settings.getStringSetting(settings, "zk.connect", null)); - kafkaProperties.setProperty("serializer.class", Settings.getStringSetting(settings, "serializer.class", null)); - this.producer= new Producer(new ProducerConfig(kafkaProperties)); - this.topics = asList(Settings.getStringSetting(settings, "topics", "").split(",")); - jsonFactory = new JsonFactory(); - } - - public void validateSetup(Server server, Query query) throws ValidationException { - } - - public void internalWrite(Server server, Query query, ImmutableList results) throws Exception { - List typeNames = this.getTypeNames(); - - for (Result result : results) { - log.debug("Query result: [{}]", result); - Map resultValues = result.getValues(); - for (Entry values : resultValues.entrySet()) { - Object value = values.getValue(); - if (isNumeric(value)) { - String message = createJsonMessage(server, query, typeNames, result, values, value); - for(String topic : this.topics) { - log.debug("Topic: [{}] ; Kafka Message: [{}]", topic, message); - producer.send(new KeyedMessage(topic, message)); - } - } else { - log.warn("Unable to submit non-numeric value to Kafka: [{}] from result [{}]", value, result); - } - } - } - } - - private String createJsonMessage(Server server, Query query, List typeNames, Result result, Entry values, Object value) throws IOException { - String keyString = getKeyString(server, query, result, values, typeNames, this.rootPrefix); - String cleanKeyString = keyString.replaceAll("[()]", "_"); - - Closer closer = Closer.create(); - try { - ByteArrayOutputStream out = closer.register(new ByteArrayOutputStream()); - JsonGenerator generator = closer.register(jsonFactory.createGenerator(out, UTF8)); - generator.writeStartObject(); - generator.writeStringField("keyspace", cleanKeyString); - generator.writeStringField("value", value.toString()); - generator.writeNumberField("timestamp", result.getEpoch() / 1000); - generator.writeEndObject(); - generator.close(); - return out.toString("UTF-8"); - } catch (Throwable t) { - throw closer.rethrow(t); - } finally { - closer.close(); - } - } - - @VisibleForTesting - void setProducer(Producer producer) { - this.producer = producer; - } - -} diff --git a/All/Genesis-NP/Genesis#430/old/KafkaWriter.java b/All/Genesis-NP/Genesis#430/old/KafkaWriter.java deleted file mode 100755 index 4da1a15..0000000 --- a/All/Genesis-NP/Genesis#430/old/KafkaWriter.java +++ /dev/null @@ -1,135 +0,0 @@ -package com.googlecode.jmxtrans.model.output.kafka; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; -import com.fasterxml.jackson.core.JsonFactory; -import com.fasterxml.jackson.core.JsonGenerator; -import com.google.common.annotations.VisibleForTesting; -import com.google.common.collect.ImmutableList; -import com.google.common.io.Closer; -import com.googlecode.jmxtrans.model.Query; -import com.googlecode.jmxtrans.model.Result; -import com.googlecode.jmxtrans.model.Server; -import com.googlecode.jmxtrans.model.ValidationException; -import com.googlecode.jmxtrans.model.output.BaseOutputWriter; -import com.googlecode.jmxtrans.model.output.Settings; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import javax.annotation.concurrent.NotThreadSafe; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Map.Entry; - -import kafka.javaapi.producer.Producer; -import kafka.producer.KeyedMessage; -import kafka.producer.ProducerConfig; - -import static com.fasterxml.jackson.core.JsonEncoding.UTF8; -import static com.googlecode.jmxtrans.model.PropertyResolver.resolveProps; -import static com.googlecode.jmxtrans.model.naming.KeyUtils.getKeyString; -import static com.googlecode.jmxtrans.util.NumberUtils.isNumeric; -import static java.util.Arrays.asList; - -/** - * This low latency and thread safe output writer sends data to a kafka topics in JSON format. - * Kafka Topics can be passed as separated by commas such as kafka01,kafka02. - * - * @author : utkarsh bhatnagar - * @github user : utkarshcmu - * @email : utkarsh.cmu@gmail.com - */ - -@NotThreadSafe -public class KafkaWriter extends BaseOutputWriter { - - private static final Logger log = LoggerFactory.getLogger(KafkaWriter.class); - - private static final String DEFAULT_ROOT_PREFIX = "servers"; - private final JsonFactory jsonFactory; - - private Producer producer; - private final Iterable topics; - private final String rootPrefix; - - @JsonCreator - public KafkaWriter( - @JsonProperty("typeNames") ImmutableList typeNames, - @JsonProperty("booleanAsNumber") boolean booleanAsNumber, - @JsonProperty("rootPrefix") String rootPrefix, - @JsonProperty("debug") Boolean debugEnabled, - @JsonProperty("topics") String topics, - @JsonProperty("settings") Map settings) { - super(typeNames, booleanAsNumber, debugEnabled, settings); - this.rootPrefix = resolveProps( - firstNonNull( - rootPrefix, - (String) getSettings().get("rootPrefix"), - DEFAULT_ROOT_PREFIX)); - // Setting all the required Kafka Properties - Properties kafkaProperties = new Properties(); - kafkaProperties.setProperty("metadata.broker.list", Settings.getStringSetting(settings, "metadata.broker.list", null)); - kafkaProperties.setProperty("zk.connect", Settings.getStringSetting(settings, "zk.connect", null)); - kafkaProperties.setProperty("serializer.class", Settings.getStringSetting(settings, "serializer.class", null)); - this.producer= new Producer(new ProducerConfig(kafkaProperties)); - this.topics = asList(topics.split(",")); - jsonFactory = new JsonFactory(); - } - - public void validateSetup(Server server, Query query) throws ValidationException { - } - - public void internalWrite(Server server, Query query, ImmutableList results) throws Exception { - List typeNames = this.getTypeNames(); - - for (Result result : results) { - log.debug("Query result: [{}]", result); - Map resultValues = result.getValues(); - for (Entry values : resultValues.entrySet()) { - Object value = values.getValue(); - if (isNumeric(value)) { - String message = createJsonMessage(server, query, typeNames, result, values, value); - for(String topic : this.topics) { - log.debug("Topic: [{}] ; Kafka Message: [{}]", topic, message); - producer.send(new KeyedMessage(topic, message)); - } - } else { - log.warn("Unable to submit non-numeric value to Kafka: [{}] from result [{}]", value, result); - } - } - } - } - - private String createJsonMessage(Server server, Query query, List typeNames, Result result, Entry values, Object value) throws IOException { - String keyString = getKeyString(server, query, result, values, typeNames, this.rootPrefix); - String cleanKeyString = keyString.replaceAll("[()]", "_"); - - Closer closer = Closer.create(); - try { - ByteArrayOutputStream out = closer.register(new ByteArrayOutputStream()); - JsonGenerator generator = closer.register(jsonFactory.createGenerator(out, UTF8)); - generator.writeStartObject(); - generator.writeStringField("keyspace", cleanKeyString); - generator.writeStringField("value", value.toString()); - generator.writeNumberField("timestamp", result.getEpoch() / 1000); - generator.writeEndObject(); - generator.close(); - return out.toString("UTF-8"); - } catch (Throwable t) { - throw closer.rethrow(t); - } finally { - closer.close(); - } - } - - @VisibleForTesting - void setProducer(Producer producer) { - this.producer = producer; - } - -} diff --git a/All/Genesis-NP/Genesis#430/pair.info b/All/Genesis-NP/Genesis#430/pair.info deleted file mode 100755 index 84885c3..0000000 --- a/All/Genesis-NP/Genesis#430/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:430 -SATName:Genesis -modifiedFPath:jmxtrans-output/jmxtrans-output-kafka/src/main/java/com/googlecode/jmxtrans/model/output/kafka/KafkaWriter.java -comSha:c347052afd1d09ba1e26a03f9c8f1eaab8eb6b6f -parentComSha:c347052afd1d09ba1e26a03f9c8f1eaab8eb6b6f^1 -githubUrl:https://github.com/jmxtrans/jmxtrans -repoName:jmxtrans#jmxtrans \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#432/comMsg.txt b/All/Genesis-NP/Genesis#432/comMsg.txt deleted file mode 100755 index ad7f6e3..0000000 --- a/All/Genesis-NP/Genesis#432/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -SPY-168: isJSONObject should handle null or empty input values. diff --git a/All/Genesis-NP/Genesis#432/diff.diff b/All/Genesis-NP/Genesis#432/diff.diff deleted file mode 100755 index c36acc2..0000000 --- a/All/Genesis-NP/Genesis#432/diff.diff +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/src/main/java/net/spy/memcached/util/StringUtils.java b/src/main/java/net/spy/memcached/util/StringUtils.java -index 32fdade..f72a59d 100644 ---- a/src/main/java/net/spy/memcached/util/StringUtils.java -+++ b/src/main/java/net/spy/memcached/util/StringUtils.java -@@ -24,0 +25,3 @@ package net.spy.memcached.util; -+import net.spy.memcached.KeyUtil; -+import net.spy.memcached.MemcachedClientIF; -+ -@@ -30,3 +32,0 @@ import java.util.regex.Pattern; --import net.spy.memcached.KeyUtil; --import net.spy.memcached.MemcachedClientIF; -- -@@ -108,0 +109,4 @@ public final class StringUtils { -+ if (s == null || s.isEmpty()) { -+ return false; -+ } -+ diff --git a/All/Genesis-NP/Genesis#432/new/StringUtils.java b/All/Genesis-NP/Genesis#432/new/StringUtils.java deleted file mode 100755 index f72a59d..0000000 --- a/All/Genesis-NP/Genesis#432/new/StringUtils.java +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Copyright (C) 2009-2014 Couchbase, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING - * IN THE SOFTWARE. - */ - -package net.spy.memcached.util; - -import net.spy.memcached.KeyUtil; -import net.spy.memcached.MemcachedClientIF; - -import java.util.Collection; -import java.util.Iterator; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Utility methods on string objects. - */ -public final class StringUtils { - - /** - * A pattern to match on a signed integer value. - */ - private static final Pattern decimalPattern = Pattern.compile("^-?\\d+$"); - - /** - * The matcher for the decimal pattern regex. - */ - private static final Matcher decimalMatcher = decimalPattern.matcher(""); - - /** - * Maximum supported key length. - */ - private static final int MAX_KEY_LENGTH = MemcachedClientIF.MAX_KEY_LENGTH; - - /** - * Exception thrown if the input key is too long. - */ - private static final IllegalArgumentException KEY_TOO_LONG_EXCEPTION = - new IllegalArgumentException("Key is too long (maxlen = " - + MAX_KEY_LENGTH + ")"); - - /** - * Exception thrown if the input key is empty. - */ - private static final IllegalArgumentException KEY_EMPTY_EXCEPTION = - new IllegalArgumentException("Key must contain at least one character."); - - /** - * Preset the stack traces for the static exceptions. - */ - static { - KEY_TOO_LONG_EXCEPTION.setStackTrace(new StackTraceElement[0]); - KEY_EMPTY_EXCEPTION.setStackTrace(new StackTraceElement[0]); - } - - /** - * Private constructor, since this is a purely static class. - */ - private StringUtils() { - throw new UnsupportedOperationException(); - } - - /** - * Join a collection of strings together into one. - * - * @param chunks the chunks to join. - * @param delimiter the delimiter between the keys. - * @return the fully joined string. - */ - public static String join(final Collection chunks, - final String delimiter) { - StringBuilder sb = new StringBuilder(); - if (!chunks.isEmpty()) { - Iterator itr = chunks.iterator(); - sb.append(itr.next()); - while (itr.hasNext()) { - sb.append(delimiter); - sb.append(itr.next()); - } - } - return sb.toString(); - } - - /** - * Check if a given string is a JSON object. - * - * @param s the input string. - * @return true if it is a JSON object, false otherwise. - */ - public static boolean isJsonObject(final String s) { - if (s == null || s.isEmpty()) { - return false; - } - - if (s.startsWith("{") || s.startsWith("[") - || "true".equals(s) || "false".equals(s) - || "null".equals(s) || decimalMatcher.reset(s).matches()) { - return true; - } - - return false; - } - - /** - * Check if a given key is valid to transmit. - * - * @param key the key to check. - * @param binary if binary protocol is used. - */ - public static void validateKey(final String key, final boolean binary) { - byte[] keyBytes = KeyUtil.getKeyBytes(key); - int keyLength = keyBytes.length; - - if (keyLength > MAX_KEY_LENGTH) { - throw KEY_TOO_LONG_EXCEPTION; - } - - if (keyLength == 0) { - throw KEY_EMPTY_EXCEPTION; - } - - if(!binary) { - for (byte b : keyBytes) { - if (b == ' ' || b == '\n' || b == '\r' || b == 0) { - throw new IllegalArgumentException( - "Key contains invalid characters: ``" + key + "''"); - } - } - } - - } -} diff --git a/All/Genesis-NP/Genesis#432/old/StringUtils.java b/All/Genesis-NP/Genesis#432/old/StringUtils.java deleted file mode 100755 index 32fdade..0000000 --- a/All/Genesis-NP/Genesis#432/old/StringUtils.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Copyright (C) 2009-2014 Couchbase, Inc. - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING - * IN THE SOFTWARE. - */ - -package net.spy.memcached.util; - -import java.util.Collection; -import java.util.Iterator; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import net.spy.memcached.KeyUtil; -import net.spy.memcached.MemcachedClientIF; - -/** - * Utility methods on string objects. - */ -public final class StringUtils { - - /** - * A pattern to match on a signed integer value. - */ - private static final Pattern decimalPattern = Pattern.compile("^-?\\d+$"); - - /** - * The matcher for the decimal pattern regex. - */ - private static final Matcher decimalMatcher = decimalPattern.matcher(""); - - /** - * Maximum supported key length. - */ - private static final int MAX_KEY_LENGTH = MemcachedClientIF.MAX_KEY_LENGTH; - - /** - * Exception thrown if the input key is too long. - */ - private static final IllegalArgumentException KEY_TOO_LONG_EXCEPTION = - new IllegalArgumentException("Key is too long (maxlen = " - + MAX_KEY_LENGTH + ")"); - - /** - * Exception thrown if the input key is empty. - */ - private static final IllegalArgumentException KEY_EMPTY_EXCEPTION = - new IllegalArgumentException("Key must contain at least one character."); - - /** - * Preset the stack traces for the static exceptions. - */ - static { - KEY_TOO_LONG_EXCEPTION.setStackTrace(new StackTraceElement[0]); - KEY_EMPTY_EXCEPTION.setStackTrace(new StackTraceElement[0]); - } - - /** - * Private constructor, since this is a purely static class. - */ - private StringUtils() { - throw new UnsupportedOperationException(); - } - - /** - * Join a collection of strings together into one. - * - * @param chunks the chunks to join. - * @param delimiter the delimiter between the keys. - * @return the fully joined string. - */ - public static String join(final Collection chunks, - final String delimiter) { - StringBuilder sb = new StringBuilder(); - if (!chunks.isEmpty()) { - Iterator itr = chunks.iterator(); - sb.append(itr.next()); - while (itr.hasNext()) { - sb.append(delimiter); - sb.append(itr.next()); - } - } - return sb.toString(); - } - - /** - * Check if a given string is a JSON object. - * - * @param s the input string. - * @return true if it is a JSON object, false otherwise. - */ - public static boolean isJsonObject(final String s) { - if (s.startsWith("{") || s.startsWith("[") - || "true".equals(s) || "false".equals(s) - || "null".equals(s) || decimalMatcher.reset(s).matches()) { - return true; - } - - return false; - } - - /** - * Check if a given key is valid to transmit. - * - * @param key the key to check. - * @param binary if binary protocol is used. - */ - public static void validateKey(final String key, final boolean binary) { - byte[] keyBytes = KeyUtil.getKeyBytes(key); - int keyLength = keyBytes.length; - - if (keyLength > MAX_KEY_LENGTH) { - throw KEY_TOO_LONG_EXCEPTION; - } - - if (keyLength == 0) { - throw KEY_EMPTY_EXCEPTION; - } - - if(!binary) { - for (byte b : keyBytes) { - if (b == ' ' || b == '\n' || b == '\r' || b == 0) { - throw new IllegalArgumentException( - "Key contains invalid characters: ``" + key + "''"); - } - } - } - - } -} diff --git a/All/Genesis-NP/Genesis#432/pair.info b/All/Genesis-NP/Genesis#432/pair.info deleted file mode 100755 index 137b724..0000000 --- a/All/Genesis-NP/Genesis#432/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:432 -SATName:Genesis -modifiedFPath:src/main/java/net/spy/memcached/util/StringUtils.java -comSha:386a843c57e9b61629e2d07887a0bf0eab37ad43 -parentComSha:386a843c57e9b61629e2d07887a0bf0eab37ad43^1 -githubUrl:https://github.com/dustin/java-memcached-client -repoName:dustin#java-memcached-client \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#434/comMsg.txt b/All/Genesis-NP/Genesis#434/comMsg.txt deleted file mode 100755 index 053cb01..0000000 --- a/All/Genesis-NP/Genesis#434/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -bugfix for NullPointerException when switching off tenured generation (fixes #38) diff --git a/All/Genesis-NP/Genesis#434/diff.diff b/All/Genesis-NP/Genesis#434/diff.diff deleted file mode 100755 index 22dd213..0000000 --- a/All/Genesis-NP/Genesis#434/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/main/java/com/tagtraum/perf/gcviewer/renderer/UsedYoungRenderer.java b/src/main/java/com/tagtraum/perf/gcviewer/renderer/UsedYoungRenderer.java -index 2118e31..0b18797 100644 ---- a/src/main/java/com/tagtraum/perf/gcviewer/renderer/UsedYoungRenderer.java -+++ b/src/main/java/com/tagtraum/perf/gcviewer/renderer/UsedYoungRenderer.java -@@ -37,0 +38,2 @@ public class UsedYoungRenderer extends PolygonChartRenderer { -+ int lastTenuredTotal = 0; -+ int tenuredTotal = 0; -@@ -45,0 +48,3 @@ public class UsedYoungRenderer extends PolygonChartRenderer { -+ -+ lastTenuredTotal = lastTenuredEvent.getTotal(); -+ tenuredTotal = tenuredEvent.getTotal(); -@@ -50,2 +55,2 @@ public class UsedYoungRenderer extends PolygonChartRenderer { -- polygon.addPoint(timestamp, lastTenuredEvent.getTotal() + youngEvent.getPreUsed()); -- polygon.addPoint(timestamp, tenuredEvent.getTotal() + youngEvent.getPostUsed()); -+ polygon.addPoint(timestamp, lastTenuredTotal + youngEvent.getPreUsed()); -+ polygon.addPoint(timestamp, tenuredTotal + youngEvent.getPostUsed()); diff --git a/All/Genesis-NP/Genesis#434/new/UsedYoungRenderer.java b/All/Genesis-NP/Genesis#434/new/UsedYoungRenderer.java deleted file mode 100755 index 0b18797..0000000 --- a/All/Genesis-NP/Genesis#434/new/UsedYoungRenderer.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.tagtraum.perf.gcviewer.renderer; - -import java.awt.Color; -import java.awt.Paint; -import java.awt.Polygon; -import java.util.Iterator; - -import com.tagtraum.perf.gcviewer.ModelChart; -import com.tagtraum.perf.gcviewer.ModelChartImpl; -import com.tagtraum.perf.gcviewer.model.GCEvent; -import com.tagtraum.perf.gcviewer.model.GCModel; - -/** - * UsedYoungRenderer draws a line to indicate the current usage of the young generation. The line - * is drawn inside the young generation (as drawn by the {@link TotalYoungRenderer}). - * - * @author Joerg Wuethrich - *

created on: 22.07.2012

- */ -public class UsedYoungRenderer extends PolygonChartRenderer { - public static final Paint DEFAULT_LINEPAINT = Color.LIGHT_GRAY; - - public UsedYoungRenderer(ModelChartImpl modelChart) { - super(modelChart); - setLinePaint(DEFAULT_LINEPAINT); - setDrawPolygon(false); - setDrawLine(true); - } - - @Override - public Polygon computePolygon(ModelChart modelChart, GCModel model) { - ScaledPolygon polygon = createMemoryScaledPolygon(); - GCEvent lastTenuredEvent = null; - GCEvent tenuredEvent = null; - for (Iterator i = model.getGCEvents(); i.hasNext();) { - GCEvent event = i.next(); - GCEvent youngEvent = event.getYoung(); - int lastTenuredTotal = 0; - int tenuredTotal = 0; - if (youngEvent != null) { - // event contains information about generation (only with -XX:+PrintGCDetails) - if (modelChart.isShowTenured()) { - if (tenuredEvent != null && tenuredEvent.getTotal() > 0) { - lastTenuredEvent = tenuredEvent; - } - if (lastTenuredEvent == null) lastTenuredEvent = event.getTenured(); - tenuredEvent = event.getTenured(); - - lastTenuredTotal = lastTenuredEvent.getTotal(); - tenuredTotal = tenuredEvent.getTotal(); - } - // e.g. "GC remark" of G1 algorithm does not contain memory information - if (youngEvent.getTotal() > 0) { - final double timestamp = event.getTimestamp() - model.getFirstPauseTimeStamp(); - polygon.addPoint(timestamp, lastTenuredTotal + youngEvent.getPreUsed()); - polygon.addPoint(timestamp, tenuredTotal + youngEvent.getPostUsed()); - } - } - } - // dummy point to make the polygon complete - polygon.addPoint(model.getRunningTime(), 0.0d); - return polygon; - } - -} diff --git a/All/Genesis-NP/Genesis#434/old/UsedYoungRenderer.java b/All/Genesis-NP/Genesis#434/old/UsedYoungRenderer.java deleted file mode 100755 index 2118e31..0000000 --- a/All/Genesis-NP/Genesis#434/old/UsedYoungRenderer.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.tagtraum.perf.gcviewer.renderer; - -import java.awt.Color; -import java.awt.Paint; -import java.awt.Polygon; -import java.util.Iterator; - -import com.tagtraum.perf.gcviewer.ModelChart; -import com.tagtraum.perf.gcviewer.ModelChartImpl; -import com.tagtraum.perf.gcviewer.model.GCEvent; -import com.tagtraum.perf.gcviewer.model.GCModel; - -/** - * UsedYoungRenderer draws a line to indicate the current usage of the young generation. The line - * is drawn inside the young generation (as drawn by the {@link TotalYoungRenderer}). - * - * @author Joerg Wuethrich - *

created on: 22.07.2012

- */ -public class UsedYoungRenderer extends PolygonChartRenderer { - public static final Paint DEFAULT_LINEPAINT = Color.LIGHT_GRAY; - - public UsedYoungRenderer(ModelChartImpl modelChart) { - super(modelChart); - setLinePaint(DEFAULT_LINEPAINT); - setDrawPolygon(false); - setDrawLine(true); - } - - @Override - public Polygon computePolygon(ModelChart modelChart, GCModel model) { - ScaledPolygon polygon = createMemoryScaledPolygon(); - GCEvent lastTenuredEvent = null; - GCEvent tenuredEvent = null; - for (Iterator i = model.getGCEvents(); i.hasNext();) { - GCEvent event = i.next(); - GCEvent youngEvent = event.getYoung(); - if (youngEvent != null) { - // event contains information about generation (only with -XX:+PrintGCDetails) - if (modelChart.isShowTenured()) { - if (tenuredEvent != null && tenuredEvent.getTotal() > 0) { - lastTenuredEvent = tenuredEvent; - } - if (lastTenuredEvent == null) lastTenuredEvent = event.getTenured(); - tenuredEvent = event.getTenured(); - } - // e.g. "GC remark" of G1 algorithm does not contain memory information - if (youngEvent.getTotal() > 0) { - final double timestamp = event.getTimestamp() - model.getFirstPauseTimeStamp(); - polygon.addPoint(timestamp, lastTenuredEvent.getTotal() + youngEvent.getPreUsed()); - polygon.addPoint(timestamp, tenuredEvent.getTotal() + youngEvent.getPostUsed()); - } - } - } - // dummy point to make the polygon complete - polygon.addPoint(model.getRunningTime(), 0.0d); - return polygon; - } - -} diff --git a/All/Genesis-NP/Genesis#434/pair.info b/All/Genesis-NP/Genesis#434/pair.info deleted file mode 100755 index b47f820..0000000 --- a/All/Genesis-NP/Genesis#434/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:434 -SATName:Genesis -modifiedFPath:src/main/java/com/tagtraum/perf/gcviewer/renderer/UsedYoungRenderer.java -comSha:0f69c5aa0eff6488b28fe1fee4f878d84459ba84 -parentComSha:0f69c5aa0eff6488b28fe1fee4f878d84459ba84^1 -githubUrl:https://github.com/chewiebug/GCViewer -repoName:chewiebug#GCViewer \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#44/comMsg.txt b/All/Genesis-NP/Genesis#44/comMsg.txt deleted file mode 100755 index 34abd83..0000000 --- a/All/Genesis-NP/Genesis#44/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Issue #52: Fixed NPE that would occur when only one line of data, with no headers, is present (should be ported to C#) diff --git a/All/Genesis-NP/Genesis#44/diff.diff b/All/Genesis-NP/Genesis#44/diff.diff deleted file mode 100755 index dd76527..0000000 --- a/All/Genesis-NP/Genesis#44/diff.diff +++ /dev/null @@ -1,19 +0,0 @@ -diff --git a/src/main/java/org/encog/app/analyst/analyze/PerformAnalysis.java b/src/main/java/org/encog/app/analyst/analyze/PerformAnalysis.java -index e424db1..8c98b78 100644 ---- a/src/main/java/org/encog/app/analyst/analyze/PerformAnalysis.java -+++ b/src/main/java/org/encog/app/analyst/analyze/PerformAnalysis.java -@@ -142,0 +143 @@ public final void process(final EncogAnalyst target) { -+ int count = 0; -@@ -147,4 +147,0 @@ public final void process(final EncogAnalyst target) { -- if( !csv.next() ) { -- throw new AnalystError("Can't analyze file, it is empty."); -- } -- -@@ -159,0 +157 @@ public final void process(final EncogAnalyst target) { -+ count++; -@@ -161,0 +160,5 @@ public final void process(final EncogAnalyst target) { -+ if( count==0 ) { -+ throw new AnalystError("Can't analyze file, it is empty."); -+ } -+ -+ diff --git a/All/Genesis-NP/Genesis#44/new/PerformAnalysis.java b/All/Genesis-NP/Genesis#44/new/PerformAnalysis.java deleted file mode 100755 index 8c98b78..0000000 --- a/All/Genesis-NP/Genesis#44/new/PerformAnalysis.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Encog(tm) Core v3.1 - Java Version - * http://www.heatonresearch.com/encog/ - * http://code.google.com/p/encog-java/ - - * Copyright 2008-2012 Heaton Research, 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. - * - * For more information on Heaton Research copyrights, licenses - * and trademarks visit: - * http://www.heatonresearch.com/copyright - */ -package org.encog.app.analyst.analyze; - -import java.util.List; - -import org.encog.app.analyst.AnalystError; -import org.encog.app.analyst.AnalystFileFormat; -import org.encog.app.analyst.EncogAnalyst; -import org.encog.app.analyst.script.AnalystClassItem; -import org.encog.app.analyst.script.AnalystScript; -import org.encog.app.analyst.script.DataField; -import org.encog.app.analyst.script.prop.ScriptProperties; -import org.encog.app.analyst.util.CSVHeaders; -import org.encog.app.analyst.util.ConvertStringConst; -import org.encog.util.csv.CSVFormat; -import org.encog.util.csv.ReadCSV; - -/** - * This class is used to perform an analysis of a CSV file. This will help Encog - * to determine how the fields should be normalized. - * - */ -public class PerformAnalysis { - - /** - * The file name to analyze. - */ - private final String filename; - - /** - * True, if headers are present. - */ - private final boolean headers; - - /** - * The format of this file. - */ - private final AnalystFileFormat format; - - /** - * The fields to analyze. - */ - private AnalyzedField[] fields; - - /** - * The script to use. - */ - private final AnalystScript script; - - /** - * Construct the analysis object. - * - * @param theScript - * The script to use. - * @param theFilename - * The name of the file to analyze. - * @param theHeaders - * True if headers are present. - * @param theFormat - * The format of the file being analyzed. - */ - public PerformAnalysis(final AnalystScript theScript, - final String theFilename, final boolean theHeaders, - final AnalystFileFormat theFormat) { - this.filename = theFilename; - this.headers = theHeaders; - this.format = theFormat; - this.script = theScript; - } - - /** - * Generate the header fields. - * - * @param csv - * The CSV file to use. - */ - private void generateFields(final ReadCSV csv) { - if (this.headers) { - generateFieldsFromHeaders(csv); - } else { - generateFieldsFromCount(csv); - } - } - - /** - * Generate the fields using counts, no headers provided. - * - * @param csv - * The CSV file to use. - */ - private void generateFieldsFromCount(final ReadCSV csv) { - this.fields = new AnalyzedField[csv.getColumnCount()]; - for (int i = 0; i < this.fields.length; i++) { - this.fields[i] = new AnalyzedField(this.script, "field:" + (i + 1)); - } - } - - /** - * Generate the fields using header values. - * - * @param csv - * The CSV file to use. - */ - private void generateFieldsFromHeaders(final ReadCSV csv) { - final CSVHeaders h = new CSVHeaders(csv.getColumnNames()); - this.fields = new AnalyzedField[csv.getColumnCount()]; - for (int i = 0; i < this.fields.length; i++) { - if (i >= csv.getColumnNames().size()) { - throw new AnalystError( - "CSV header count does not match column count"); - } - this.fields[i] = new AnalyzedField(this.script, h.getHeader(i)); - } - } - - /** - * Perform the analysis. - * @param target The Encog analyst object to analyze. - */ - public final void process(final EncogAnalyst target) { - int count = 0; - final CSVFormat csvFormat = ConvertStringConst - .convertToCSVFormat(this.format); - ReadCSV csv = new ReadCSV(this.filename, this.headers, csvFormat); - - // pass one, calculate the min/max - while (csv.next()) { - if (this.fields == null) { - generateFields(csv); - } - - for (int i = 0; i < csv.getColumnCount(); i++) { - this.fields[i].analyze1(csv.get(i)); - } - count++; - } - - if( count==0 ) { - throw new AnalystError("Can't analyze file, it is empty."); - } - - - for (final AnalyzedField field : this.fields) { - field.completePass1(); - } - - csv.close(); - - // pass two, standard deviation - csv = new ReadCSV(this.filename, this.headers, csvFormat); - while (csv.next()) { - for (int i = 0; i < csv.getColumnCount(); i++) { - this.fields[i].analyze2(csv.get(i)); - } - } - - for (final AnalyzedField field : this.fields) { - field.completePass2(); - } - - csv.close(); - - String str = this.script.getProperties().getPropertyString( - ScriptProperties.SETUP_CONFIG_ALLOWED_CLASSES); - if (str == null) { - str = ""; - } - - final boolean allowInt = str.contains("int"); - final boolean allowReal = str.contains("real") - || str.contains("double"); - final boolean allowString = str.contains("string"); - - // remove any classes that did not qualify - for (final AnalyzedField field : this.fields) { - if (field.isClass()) { - if (!allowInt && field.isInteger()) { - field.setClass(false); - } - - if (!allowString && (!field.isInteger() && !field.isReal())) { - field.setClass(false); - } - - if (!allowReal && field.isReal() && !field.isInteger()) { - field.setClass(false); - } - - if (field.isInteger() - && (field.getAnalyzedClassMembers().size() <= 2)) { - field.setClass(false); - } - } - } - - // merge with existing - if ((target.getScript().getFields() != null) - && (this.fields.length - == target.getScript().getFields().length)) { - for (int i = 0; i < this.fields.length; i++) { - // copy the old field name - this.fields[i].setName(target.getScript().getFields()[i] - .getName()); - - if (this.fields[i].isClass()) { - final List t = this.fields[i] - .getAnalyzedClassMembers(); - final List s = target.getScript() - .getFields()[i].getClassMembers(); - - if (s.size() == t.size()) { - for (int j = 0; j < s.size(); j++) { - if (t.get(j).getCode().equals(s.get(j).getCode())) { - t.get(j).setName(s.get(j).getName()); - } - } - } - } - } - } - - // now copy the fields - final DataField[] df = new DataField[this.fields.length]; - - for (int i = 0; i < df.length; i++) { - df[i] = this.fields[i].finalizeField(); - } - - target.getScript().setFields(df); - - } - - /** {@inheritDoc} */ - @Override - public final String toString() { - final StringBuilder result = new StringBuilder("["); - result.append(getClass().getSimpleName()); - result.append(" filename="); - result.append(this.filename); - result.append(", headers="); - result.append(this.headers); - result.append("]"); - return result.toString(); - } - -} diff --git a/All/Genesis-NP/Genesis#44/old/PerformAnalysis.java b/All/Genesis-NP/Genesis#44/old/PerformAnalysis.java deleted file mode 100755 index e424db1..0000000 --- a/All/Genesis-NP/Genesis#44/old/PerformAnalysis.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Encog(tm) Core v3.1 - Java Version - * http://www.heatonresearch.com/encog/ - * http://code.google.com/p/encog-java/ - - * Copyright 2008-2012 Heaton Research, 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. - * - * For more information on Heaton Research copyrights, licenses - * and trademarks visit: - * http://www.heatonresearch.com/copyright - */ -package org.encog.app.analyst.analyze; - -import java.util.List; - -import org.encog.app.analyst.AnalystError; -import org.encog.app.analyst.AnalystFileFormat; -import org.encog.app.analyst.EncogAnalyst; -import org.encog.app.analyst.script.AnalystClassItem; -import org.encog.app.analyst.script.AnalystScript; -import org.encog.app.analyst.script.DataField; -import org.encog.app.analyst.script.prop.ScriptProperties; -import org.encog.app.analyst.util.CSVHeaders; -import org.encog.app.analyst.util.ConvertStringConst; -import org.encog.util.csv.CSVFormat; -import org.encog.util.csv.ReadCSV; - -/** - * This class is used to perform an analysis of a CSV file. This will help Encog - * to determine how the fields should be normalized. - * - */ -public class PerformAnalysis { - - /** - * The file name to analyze. - */ - private final String filename; - - /** - * True, if headers are present. - */ - private final boolean headers; - - /** - * The format of this file. - */ - private final AnalystFileFormat format; - - /** - * The fields to analyze. - */ - private AnalyzedField[] fields; - - /** - * The script to use. - */ - private final AnalystScript script; - - /** - * Construct the analysis object. - * - * @param theScript - * The script to use. - * @param theFilename - * The name of the file to analyze. - * @param theHeaders - * True if headers are present. - * @param theFormat - * The format of the file being analyzed. - */ - public PerformAnalysis(final AnalystScript theScript, - final String theFilename, final boolean theHeaders, - final AnalystFileFormat theFormat) { - this.filename = theFilename; - this.headers = theHeaders; - this.format = theFormat; - this.script = theScript; - } - - /** - * Generate the header fields. - * - * @param csv - * The CSV file to use. - */ - private void generateFields(final ReadCSV csv) { - if (this.headers) { - generateFieldsFromHeaders(csv); - } else { - generateFieldsFromCount(csv); - } - } - - /** - * Generate the fields using counts, no headers provided. - * - * @param csv - * The CSV file to use. - */ - private void generateFieldsFromCount(final ReadCSV csv) { - this.fields = new AnalyzedField[csv.getColumnCount()]; - for (int i = 0; i < this.fields.length; i++) { - this.fields[i] = new AnalyzedField(this.script, "field:" + (i + 1)); - } - } - - /** - * Generate the fields using header values. - * - * @param csv - * The CSV file to use. - */ - private void generateFieldsFromHeaders(final ReadCSV csv) { - final CSVHeaders h = new CSVHeaders(csv.getColumnNames()); - this.fields = new AnalyzedField[csv.getColumnCount()]; - for (int i = 0; i < this.fields.length; i++) { - if (i >= csv.getColumnNames().size()) { - throw new AnalystError( - "CSV header count does not match column count"); - } - this.fields[i] = new AnalyzedField(this.script, h.getHeader(i)); - } - } - - /** - * Perform the analysis. - * @param target The Encog analyst object to analyze. - */ - public final void process(final EncogAnalyst target) { - final CSVFormat csvFormat = ConvertStringConst - .convertToCSVFormat(this.format); - ReadCSV csv = new ReadCSV(this.filename, this.headers, csvFormat); - - if( !csv.next() ) { - throw new AnalystError("Can't analyze file, it is empty."); - } - - // pass one, calculate the min/max - while (csv.next()) { - if (this.fields == null) { - generateFields(csv); - } - - for (int i = 0; i < csv.getColumnCount(); i++) { - this.fields[i].analyze1(csv.get(i)); - } - } - - for (final AnalyzedField field : this.fields) { - field.completePass1(); - } - - csv.close(); - - // pass two, standard deviation - csv = new ReadCSV(this.filename, this.headers, csvFormat); - while (csv.next()) { - for (int i = 0; i < csv.getColumnCount(); i++) { - this.fields[i].analyze2(csv.get(i)); - } - } - - for (final AnalyzedField field : this.fields) { - field.completePass2(); - } - - csv.close(); - - String str = this.script.getProperties().getPropertyString( - ScriptProperties.SETUP_CONFIG_ALLOWED_CLASSES); - if (str == null) { - str = ""; - } - - final boolean allowInt = str.contains("int"); - final boolean allowReal = str.contains("real") - || str.contains("double"); - final boolean allowString = str.contains("string"); - - // remove any classes that did not qualify - for (final AnalyzedField field : this.fields) { - if (field.isClass()) { - if (!allowInt && field.isInteger()) { - field.setClass(false); - } - - if (!allowString && (!field.isInteger() && !field.isReal())) { - field.setClass(false); - } - - if (!allowReal && field.isReal() && !field.isInteger()) { - field.setClass(false); - } - - if (field.isInteger() - && (field.getAnalyzedClassMembers().size() <= 2)) { - field.setClass(false); - } - } - } - - // merge with existing - if ((target.getScript().getFields() != null) - && (this.fields.length - == target.getScript().getFields().length)) { - for (int i = 0; i < this.fields.length; i++) { - // copy the old field name - this.fields[i].setName(target.getScript().getFields()[i] - .getName()); - - if (this.fields[i].isClass()) { - final List t = this.fields[i] - .getAnalyzedClassMembers(); - final List s = target.getScript() - .getFields()[i].getClassMembers(); - - if (s.size() == t.size()) { - for (int j = 0; j < s.size(); j++) { - if (t.get(j).getCode().equals(s.get(j).getCode())) { - t.get(j).setName(s.get(j).getName()); - } - } - } - } - } - } - - // now copy the fields - final DataField[] df = new DataField[this.fields.length]; - - for (int i = 0; i < df.length; i++) { - df[i] = this.fields[i].finalizeField(); - } - - target.getScript().setFields(df); - - } - - /** {@inheritDoc} */ - @Override - public final String toString() { - final StringBuilder result = new StringBuilder("["); - result.append(getClass().getSimpleName()); - result.append(" filename="); - result.append(this.filename); - result.append(", headers="); - result.append(this.headers); - result.append("]"); - return result.toString(); - } - -} diff --git a/All/Genesis-NP/Genesis#44/pair.info b/All/Genesis-NP/Genesis#44/pair.info deleted file mode 100755 index b3f82ea..0000000 --- a/All/Genesis-NP/Genesis#44/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:44 -SATName:Genesis -modifiedFPath:src/main/java/org/encog/app/analyst/analyze/PerformAnalysis.java -comSha:5d786f3585ef53da0b5c16d0afb3d78bc07b8c57 -parentComSha:5d786f3585ef53da0b5c16d0afb3d78bc07b8c57^1 -githubUrl:https://github.com/encog/encog-java-core -repoName:encog#encog-java-core \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#441/comMsg.txt b/All/Genesis-NP/Genesis#441/comMsg.txt deleted file mode 100755 index 451437f..0000000 --- a/All/Genesis-NP/Genesis#441/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE during the server loop shutdown. diff --git a/All/Genesis-NP/Genesis#441/diff.diff b/All/Genesis-NP/Genesis#441/diff.diff deleted file mode 100755 index eac7c5e..0000000 --- a/All/Genesis-NP/Genesis#441/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/rapidoid-net/src/main/java/org/rapidoid/net/impl/RapidoidServerLoop.java b/rapidoid-net/src/main/java/org/rapidoid/net/impl/RapidoidServerLoop.java -index 965b02b..16bbbdb 100644 ---- a/rapidoid-net/src/main/java/org/rapidoid/net/impl/RapidoidServerLoop.java -+++ b/rapidoid-net/src/main/java/org/rapidoid/net/impl/RapidoidServerLoop.java -@@ -177,0 +178 @@ public class RapidoidServerLoop extends AbstractLoop implements TCPSe -+ if (ioWorkers != null) { -@@ -180,0 +182 @@ public class RapidoidServerLoop extends AbstractLoop implements TCPSe -+ } -@@ -182 +184 @@ public class RapidoidServerLoop extends AbstractLoop implements TCPSe -- if ((serverSocketChannel.isOpen()) && (selector.isOpen())) { -+ if (serverSocketChannel != null && selector != null && serverSocketChannel.isOpen() && selector.isOpen()) { diff --git a/All/Genesis-NP/Genesis#441/new/RapidoidServerLoop.java b/All/Genesis-NP/Genesis#441/new/RapidoidServerLoop.java deleted file mode 100755 index 16bbbdb..0000000 --- a/All/Genesis-NP/Genesis#441/new/RapidoidServerLoop.java +++ /dev/null @@ -1,287 +0,0 @@ -package org.rapidoid.net.impl; - -/* - * #%L - * rapidoid-net - * %% - * Copyright (C) 2014 - 2015 Nikolche Mihajlovski and contributors - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.nio.channels.ClosedSelectorException; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.Iterator; -import java.util.Set; - -import org.rapidoid.annotation.Authors; -import org.rapidoid.annotation.Inject; -import org.rapidoid.annotation.Since; -import org.rapidoid.config.Conf; -import org.rapidoid.log.Log; -import org.rapidoid.net.Protocol; -import org.rapidoid.net.TCPServer; -import org.rapidoid.net.TCPServerInfo; -import org.rapidoid.util.Rnd; -import org.rapidoid.util.U; - -@Authors("Nikolche Mihajlovski") -@Since("2.0.0") -public class RapidoidServerLoop extends AbstractLoop implements TCPServer, TCPServerInfo { - - private volatile RapidoidWorker[] ioWorkers; - - private RapidoidWorker currentWorker; - - @Inject(optional = true) - private int port = 8080; - - @Inject(optional = true) - private String address = "0.0.0.0"; - - @Inject(optional = true) - private int workers = Conf.cpus(); - - @Inject(optional = true) - private boolean blockingAccept = false; - - protected final Protocol protocol; - - private final Class helperClass; - - private final Class> exchangeClass; - - private ServerSocketChannel serverSocketChannel; - - private final Selector selector; - - public RapidoidServerLoop(Protocol protocol, Class> exchangeClass, - Class helperClass) { - super("server"); - this.protocol = protocol; - this.exchangeClass = exchangeClass; - this.helperClass = U.or(helperClass, RapidoidHelper.class); - - try { - this.selector = Selector.open(); - } catch (IOException e) { - Log.error("Cannot open selector!", e); - throw new RuntimeException(e); - } - } - - @Override - protected final void beforeLoop() { - validate(); - - try { - openSocket(); - } catch (IOException e) { - throw U.rte("Cannot open socket!", e); - } - } - - private void validate() { - U.must(workers <= RapidoidWorker.MAX_IO_WORKERS, "Too many workers! Maximum = %s", - RapidoidWorker.MAX_IO_WORKERS); - } - - private void openSocket() throws IOException { - U.notNull(protocol, "protocol"); - U.notNull(helperClass, "helperClass"); - - Log.info("Initializing server", "port", port, "accept", blockingAccept ? "blocking" : "non-blocking"); - - serverSocketChannel = ServerSocketChannel.open(); - - if ((serverSocketChannel.isOpen()) && (selector.isOpen())) { - - serverSocketChannel.configureBlocking(blockingAccept); - - ServerSocket socket = serverSocketChannel.socket(); - - Log.info("Opening port to listen", "port", port); - - InetSocketAddress addr = new InetSocketAddress(address, port); - - socket.setReceiveBufferSize(16 * 1024); - socket.setReuseAddress(true); - socket.bind(addr, 1024); - - Log.info("Opened server socket", "address", addr); - - if (!blockingAccept) { - Log.info("Registering accept selector"); - serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); - } - - Log.info("Waiting for connections..."); - - initWorkers(); - - } else { - throw U.rte("Cannot open socket!"); - } - } - - private void initWorkers() { - ioWorkers = new RapidoidWorker[workers]; - - for (int i = 0; i < ioWorkers.length; i++) { - - RapidoidWorkerThread workerThread = new RapidoidWorkerThread(i, protocol, exchangeClass, helperClass); - workerThread.start(); - - ioWorkers[i] = workerThread.getWorker(); - - if (i > 0) { - ioWorkers[i - 1].next = ioWorkers[i]; - } - } - - ioWorkers[ioWorkers.length - 1].next = ioWorkers[0]; - currentWorker = ioWorkers[0]; - - for (RapidoidWorker worker : ioWorkers) { - worker.waitToStart(); - } - } - - @Override - public synchronized TCPServer start() { - new Thread(this, "server").start(); - - return super.start(); - } - - @Override - public synchronized TCPServer shutdown() { - stopLoop(); - - if (ioWorkers != null) { - for (RapidoidWorker worker : ioWorkers) { - worker.stopLoop(); - } - } - - if (serverSocketChannel != null && selector != null && serverSocketChannel.isOpen() && selector.isOpen()) { - try { - selector.close(); - serverSocketChannel.close(); - } catch (IOException e) { - Log.warn("Cannot close socket or selector!", e); - } - } - - return super.shutdown(); - } - - public synchronized RapidoidConnection newConnection() { - int rndWorker = Rnd.rnd(ioWorkers.length); - return ioWorkers[rndWorker].newConnection(); - } - - public synchronized void process(RapidoidConnection conn) { - conn.worker.process(conn); - } - - @Override - public synchronized String process(String input) { - if (ioWorkers == null) { - initWorkers(); - } - - RapidoidConnection conn = newConnection(); - conn.setInitial(false); - conn.input.append(input); - conn.setProtocol(protocol); - process(conn); - return conn.output.asText(); - } - - public Protocol getProtocol() { - return protocol; - } - - @Override - public TCPServerInfo info() { - return this; - } - - @Override - public long messagesProcessed() { - long total = 0; - - for (int i = 0; i < ioWorkers.length; i++) { - total += ioWorkers[i].getMessagesProcessed(); - } - - return total; - } - - @Override - protected void insideLoop() { - if (blockingAccept) { - processBlocking(); - } else { - processNonBlocking(); - } - } - - private void processNonBlocking() { - try { - selector.select(50); - } catch (IOException e) { - Log.error("Select failed!", e); - } - - try { - Set selectedKeys = selector.selectedKeys(); - synchronized (selectedKeys) { - - Iterator iter = selectedKeys.iterator(); - - while (iter.hasNext()) { - SelectionKey key = (SelectionKey) iter.next(); - iter.remove(); - - acceptChannel((ServerSocketChannel) key.channel()); - } - } - } catch (ClosedSelectorException e) { - // do nothing - } - } - - private void processBlocking() { - acceptChannel(serverSocketChannel); - } - - private void acceptChannel(ServerSocketChannel serverChannel) { - try { - SocketChannel channel = serverSocketChannel.accept(); - currentWorker.accept(channel); - currentWorker = currentWorker.next; - } catch (IOException e) { - Log.error("Acceptor error!", e); - } - } - -} diff --git a/All/Genesis-NP/Genesis#441/old/RapidoidServerLoop.java b/All/Genesis-NP/Genesis#441/old/RapidoidServerLoop.java deleted file mode 100755 index 965b02b..0000000 --- a/All/Genesis-NP/Genesis#441/old/RapidoidServerLoop.java +++ /dev/null @@ -1,285 +0,0 @@ -package org.rapidoid.net.impl; - -/* - * #%L - * rapidoid-net - * %% - * Copyright (C) 2014 - 2015 Nikolche Mihajlovski and contributors - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ - -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.ServerSocket; -import java.nio.channels.ClosedSelectorException; -import java.nio.channels.SelectionKey; -import java.nio.channels.Selector; -import java.nio.channels.ServerSocketChannel; -import java.nio.channels.SocketChannel; -import java.util.Iterator; -import java.util.Set; - -import org.rapidoid.annotation.Authors; -import org.rapidoid.annotation.Inject; -import org.rapidoid.annotation.Since; -import org.rapidoid.config.Conf; -import org.rapidoid.log.Log; -import org.rapidoid.net.Protocol; -import org.rapidoid.net.TCPServer; -import org.rapidoid.net.TCPServerInfo; -import org.rapidoid.util.Rnd; -import org.rapidoid.util.U; - -@Authors("Nikolche Mihajlovski") -@Since("2.0.0") -public class RapidoidServerLoop extends AbstractLoop implements TCPServer, TCPServerInfo { - - private volatile RapidoidWorker[] ioWorkers; - - private RapidoidWorker currentWorker; - - @Inject(optional = true) - private int port = 8080; - - @Inject(optional = true) - private String address = "0.0.0.0"; - - @Inject(optional = true) - private int workers = Conf.cpus(); - - @Inject(optional = true) - private boolean blockingAccept = false; - - protected final Protocol protocol; - - private final Class helperClass; - - private final Class> exchangeClass; - - private ServerSocketChannel serverSocketChannel; - - private final Selector selector; - - public RapidoidServerLoop(Protocol protocol, Class> exchangeClass, - Class helperClass) { - super("server"); - this.protocol = protocol; - this.exchangeClass = exchangeClass; - this.helperClass = U.or(helperClass, RapidoidHelper.class); - - try { - this.selector = Selector.open(); - } catch (IOException e) { - Log.error("Cannot open selector!", e); - throw new RuntimeException(e); - } - } - - @Override - protected final void beforeLoop() { - validate(); - - try { - openSocket(); - } catch (IOException e) { - throw U.rte("Cannot open socket!", e); - } - } - - private void validate() { - U.must(workers <= RapidoidWorker.MAX_IO_WORKERS, "Too many workers! Maximum = %s", - RapidoidWorker.MAX_IO_WORKERS); - } - - private void openSocket() throws IOException { - U.notNull(protocol, "protocol"); - U.notNull(helperClass, "helperClass"); - - Log.info("Initializing server", "port", port, "accept", blockingAccept ? "blocking" : "non-blocking"); - - serverSocketChannel = ServerSocketChannel.open(); - - if ((serverSocketChannel.isOpen()) && (selector.isOpen())) { - - serverSocketChannel.configureBlocking(blockingAccept); - - ServerSocket socket = serverSocketChannel.socket(); - - Log.info("Opening port to listen", "port", port); - - InetSocketAddress addr = new InetSocketAddress(address, port); - - socket.setReceiveBufferSize(16 * 1024); - socket.setReuseAddress(true); - socket.bind(addr, 1024); - - Log.info("Opened server socket", "address", addr); - - if (!blockingAccept) { - Log.info("Registering accept selector"); - serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT); - } - - Log.info("Waiting for connections..."); - - initWorkers(); - - } else { - throw U.rte("Cannot open socket!"); - } - } - - private void initWorkers() { - ioWorkers = new RapidoidWorker[workers]; - - for (int i = 0; i < ioWorkers.length; i++) { - - RapidoidWorkerThread workerThread = new RapidoidWorkerThread(i, protocol, exchangeClass, helperClass); - workerThread.start(); - - ioWorkers[i] = workerThread.getWorker(); - - if (i > 0) { - ioWorkers[i - 1].next = ioWorkers[i]; - } - } - - ioWorkers[ioWorkers.length - 1].next = ioWorkers[0]; - currentWorker = ioWorkers[0]; - - for (RapidoidWorker worker : ioWorkers) { - worker.waitToStart(); - } - } - - @Override - public synchronized TCPServer start() { - new Thread(this, "server").start(); - - return super.start(); - } - - @Override - public synchronized TCPServer shutdown() { - stopLoop(); - - for (RapidoidWorker worker : ioWorkers) { - worker.stopLoop(); - } - - if ((serverSocketChannel.isOpen()) && (selector.isOpen())) { - try { - selector.close(); - serverSocketChannel.close(); - } catch (IOException e) { - Log.warn("Cannot close socket or selector!", e); - } - } - - return super.shutdown(); - } - - public synchronized RapidoidConnection newConnection() { - int rndWorker = Rnd.rnd(ioWorkers.length); - return ioWorkers[rndWorker].newConnection(); - } - - public synchronized void process(RapidoidConnection conn) { - conn.worker.process(conn); - } - - @Override - public synchronized String process(String input) { - if (ioWorkers == null) { - initWorkers(); - } - - RapidoidConnection conn = newConnection(); - conn.setInitial(false); - conn.input.append(input); - conn.setProtocol(protocol); - process(conn); - return conn.output.asText(); - } - - public Protocol getProtocol() { - return protocol; - } - - @Override - public TCPServerInfo info() { - return this; - } - - @Override - public long messagesProcessed() { - long total = 0; - - for (int i = 0; i < ioWorkers.length; i++) { - total += ioWorkers[i].getMessagesProcessed(); - } - - return total; - } - - @Override - protected void insideLoop() { - if (blockingAccept) { - processBlocking(); - } else { - processNonBlocking(); - } - } - - private void processNonBlocking() { - try { - selector.select(50); - } catch (IOException e) { - Log.error("Select failed!", e); - } - - try { - Set selectedKeys = selector.selectedKeys(); - synchronized (selectedKeys) { - - Iterator iter = selectedKeys.iterator(); - - while (iter.hasNext()) { - SelectionKey key = (SelectionKey) iter.next(); - iter.remove(); - - acceptChannel((ServerSocketChannel) key.channel()); - } - } - } catch (ClosedSelectorException e) { - // do nothing - } - } - - private void processBlocking() { - acceptChannel(serverSocketChannel); - } - - private void acceptChannel(ServerSocketChannel serverChannel) { - try { - SocketChannel channel = serverSocketChannel.accept(); - currentWorker.accept(channel); - currentWorker = currentWorker.next; - } catch (IOException e) { - Log.error("Acceptor error!", e); - } - } - -} diff --git a/All/Genesis-NP/Genesis#441/pair.info b/All/Genesis-NP/Genesis#441/pair.info deleted file mode 100755 index 7946b42..0000000 --- a/All/Genesis-NP/Genesis#441/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:441 -SATName:Genesis -modifiedFPath:rapidoid-net/src/main/java/org/rapidoid/net/impl/RapidoidServerLoop.java -comSha:426bbee0ff5cd4a30d7047b14f57f98399134b41 -parentComSha:426bbee0ff5cd4a30d7047b14f57f98399134b41^1 -githubUrl:https://github.com/rapidoid/rapidoid -repoName:rapidoid#rapidoid \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#448/comMsg.txt b/All/Genesis-NP/Genesis#448/comMsg.txt deleted file mode 100755 index 59a4524..0000000 --- a/All/Genesis-NP/Genesis#448/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix NullPointerException while parsing response diff --git a/All/Genesis-NP/Genesis#448/diff.diff b/All/Genesis-NP/Genesis#448/diff.diff deleted file mode 100755 index 67d9c87..0000000 --- a/All/Genesis-NP/Genesis#448/diff.diff +++ /dev/null @@ -1,20 +0,0 @@ -diff --git a/src/main/java/microsoft/exchange/webservices/data/EwsXmlReader.java b/src/main/java/microsoft/exchange/webservices/data/EwsXmlReader.java -index 08b944f..166e952 100644 ---- a/src/main/java/microsoft/exchange/webservices/data/EwsXmlReader.java -+++ b/src/main/java/microsoft/exchange/webservices/data/EwsXmlReader.java -@@ -170 +169,0 @@ class EwsXmlReader { -- * -@@ -420,0 +420 @@ class EwsXmlReader { -+ -@@ -445 +445 @@ class EwsXmlReader { -- if (characters.getData().length() != 0) { -+ if (characters.getData() != null && characters.getData().length() != 0) { -@@ -468,2 +468,3 @@ class EwsXmlReader { -- StringBuffer data = new StringBuffer(this.presentEvent -- .asCharacters().getData()); -+ final String charData = this.presentEvent -+ .asCharacters().getData(); -+ StringBuffer data = new StringBuffer(charData == null ? "" : charData); -@@ -476 +477 @@ class EwsXmlReader { -- if (characters.getData().length() != 0) { -+ if (characters.getData() != null && characters.getData().length() != 0) { diff --git a/All/Genesis-NP/Genesis#448/new/EwsXmlReader.java b/All/Genesis-NP/Genesis#448/new/EwsXmlReader.java deleted file mode 100755 index 166e952..0000000 --- a/All/Genesis-NP/Genesis#448/new/EwsXmlReader.java +++ /dev/null @@ -1,1125 +0,0 @@ -/* - * The MIT License - * Copyright (c) 2012 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package microsoft.exchange.webservices.data; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLEventReader; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.events.*; -import java.io.*; - -/** - * Defines the EwsXmlReader class. - */ -class EwsXmlReader { - - /** - * The Read write buffer size. - */ - private static final int ReadWriteBufferSize = 4096; - - /** - * The xml reader. - */ - private XMLEventReader xmlReader = null; - - /** - * The present event. - */ - private XMLEvent presentEvent; - - /** - * The prev event. - */ - private XMLEvent prevEvent; - - /** - * Initializes a new instance of the EwsXmlReader class. - * - * @param stream the stream - * @throws Exception - */ - public EwsXmlReader(InputStream stream) throws Exception { - this.xmlReader = initializeXmlReader(stream); - } - - /** - * Initializes the XML reader. - * - * @param stream the stream - * @return An XML reader to use. - * @throws Exception - */ - protected XMLEventReader initializeXmlReader(InputStream stream) - throws XMLStreamException, Exception { - - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); - //inputFactory.setProperty(XMLInputFactory.RESOLVER, null); - - return inputFactory.createXMLEventReader(stream); - } - - - /** - * Formats the name of the element. - * - * @param namespacePrefix The namespace prefix - * @param localElementName Element name - * @return the string - */ - private static String formatElementName(String namespacePrefix, - String localElementName) { - - return isNullOrEmpty(namespacePrefix) ? localElementName : - namespacePrefix + ":" + localElementName; - } - - /** - * Read XML element. - * - * @param xmlNamespace The XML namespace - * @param localName Name of the local - * @param nodeType Type of the node - * @throws Exception the exception - */ - private void internalReadElement(XmlNamespace xmlNamespace, - String localName, XmlNodeType nodeType) throws Exception { - - if (xmlNamespace == XmlNamespace.NotSpecified) { - this.internalReadElement("", localName, nodeType); - } else { - this.read(nodeType); - - if ((!this.getLocalName().equals(localName)) || - (!this.getNamespaceUri().equals(EwsUtilities - .getNamespaceUri(xmlNamespace)))) { - throw new ServiceXmlDeserializationException( - String - .format( - Strings.UnexpectedElement, - EwsUtilities - .getNamespacePrefix( - xmlNamespace), - localName, nodeType.toString(), this - .getName(), this.getNodeType() - .toString())); - } - } - } - - /** - * Read XML element. - * - * @param namespacePrefix The namespace prefix - * @param localName Name of the local - * @param nodeType Type of the node - * @throws Exception the exception - */ - private void internalReadElement(String namespacePrefix, String localName, - XmlNodeType nodeType) throws Exception { - read(nodeType); - - if ((!this.getLocalName().equals(localName)) || - (!this.getNamespacePrefix().equals(namespacePrefix))) { - throw new ServiceXmlDeserializationException(String.format( - Strings.UnexpectedElement, namespacePrefix, localName, - nodeType.toString(), this.getName(), this.getNodeType() - .toString())); - } - } - - /** - * Reads the specified node type. - * - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public void read() throws ServiceXmlDeserializationException, - XMLStreamException { - read(false); - } - - /** - * Reads the specified node type. - * - * @param keepWhiteSpace Do not remove whitespace characters if true - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - private void read(boolean keepWhiteSpace) throws ServiceXmlDeserializationException, - XMLStreamException { - // The caller to EwsXmlReader.Read expects - // that there's another node to - // read. Throw an exception if not true. - while (true) { - if (!xmlReader.hasNext()) { - throw new ServiceXmlDeserializationException( - Strings.UnexpectedEndOfXmlDocument); - } else { - XMLEvent event = xmlReader.nextEvent(); - if (event.getEventType() == XMLStreamConstants.CHARACTERS) { - Characters characters = (Characters) event; - if (!keepWhiteSpace) - if (characters.isIgnorableWhiteSpace() - || characters.isWhiteSpace()) { - continue; - } - } - this.prevEvent = this.presentEvent; - this.presentEvent = event; - break; - } - } - } - - /** - * Reads the specified node type. - * - * @param nodeType Type of the node. - * @throws Exception the exception - */ - public void read(XmlNodeType nodeType) throws Exception { - this.read(); - if (!this.getNodeType().equals(nodeType)) { - throw new ServiceXmlDeserializationException(String - .format(Strings.UnexpectedElementType, nodeType, this - .getNodeType())); - } - } - - /** - * Read attribute value from QName. - * - * @param qName QName of the attribute - * @return Attribute Value - * @throws Exception thrown if attribute value can not be read - */ - private String readAttributeValue(QName qName) throws Exception { - if (this.presentEvent.isStartElement()) { - StartElement startElement = this.presentEvent.asStartElement(); - Attribute attr = startElement.getAttributeByName(qName); - if (null != attr) { - return attr.getValue(); - } else { - return null; - } - } else { - String errMsg = String.format("Could not fetch attribute %s", qName - .toString()); - throw new Exception(errMsg); - } - } - - /** - * Reads the attribute value. - * - * @param xmlNamespace The XML namespace. - * @param attributeName Name of the attribute - * @return Attribute Value - * @throws Exception the exception - */ - public String readAttributeValue(XmlNamespace xmlNamespace, - String attributeName) throws Exception { - if (xmlNamespace == XmlNamespace.NotSpecified) { - return this.readAttributeValue(attributeName); - } else { - QName qName = new QName(EwsUtilities.getNamespaceUri(xmlNamespace), - attributeName); - return readAttributeValue(qName); - } - } - - /** - * Reads the attribute value. - * - * @param attributeName Name of the attribute - * @return Attribute value. - * @throws Exception the exception - */ - public String readAttributeValue(String attributeName) throws Exception { - QName qName = new QName(attributeName); - return readAttributeValue(qName); - } - - /** - * Reads the attribute value. - * - * @param the generic type - * @param cls the cls - * @param attributeName the attribute name - * @return T - * @throws Exception the exception - */ - public T readAttributeValue(Class cls, String attributeName) - throws Exception { - return EwsUtilities.parse(cls, this.readAttributeValue(attributeName)); - } - - /** - * Reads a nullable attribute value. - * - * @param the generic type - * @param cls the cls - * @param attributeName the attribute name - * @return T - * @throws Exception the exception - */ - public T readNullableAttributeValue(Class cls, String attributeName) - throws Exception { - String attributeValue = this.readAttributeValue(attributeName); - if (attributeValue == null) { - return null; - } else { - return EwsUtilities.parse(cls, attributeValue); - } - } - - /** - * Reads the element value. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @return String - * @throws Exception the exception - */ - public String readElementValue(String namespacePrefix, String localName) - throws Exception { - if (!this.isStartElement(namespacePrefix, localName)) { - this.readStartElement(namespacePrefix, localName); - } - - String value = null; - - if (!this.isEmptyElement()) { - value = this.readValue(); - } - return value; - } - - /** - * Reads the element value. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @return String - * @throws Exception the exception - */ - public String readElementValue(XmlNamespace xmlNamespace, String localName) - throws Exception { - - if (!this.isStartElement(xmlNamespace, localName)) { - this.readStartElement(xmlNamespace, localName); - } - - String value = null; - - if (!this.isEmptyElement()) { - value = this.readValue(); - } else { - this.read(); - } - - return value; - } - - /** - * Read element value. - * - * @return String - * @throws Exception the exception - */ - public String readElementValue() throws Exception { - this.ensureCurrentNodeIsStartElement(); - - return this.readElementValue(this.getNamespacePrefix(), this - .getLocalName()); - } - - /** - * Reads the element value. - * - * @param the generic type - * @param cls the cls - * @param xmlNamespace the xml namespace - * @param localName the local name - * @return T - * @throws Exception the exception - */ - public T readElementValue(Class cls, XmlNamespace xmlNamespace, - String localName) throws Exception { - if (!this.isStartElement(xmlNamespace, localName)) { - this.readStartElement(xmlNamespace, localName); - } - - T value = null; - - if (!this.isEmptyElement()) { - value = this.readValue(cls); - } - - return value; - } - - /** - * Read element value. - * - * @param the generic type - * @param cls the cls - * @return T - * @throws Exception the exception - */ - public T readElementValue(Class cls) throws Exception { - this.ensureCurrentNodeIsStartElement(); - - T value = null; - - if (!this.isEmptyElement()) { - value = this.readValue(cls); - } - - return value; - } - - /** - * Reads the value. Should return content element or text node as string - * Present event must be START ELEMENT. After executing this function - * Present event will be set on END ELEMENT - * - * @return String - * @throws javax.xml.stream.XMLStreamException the xML stream exception - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public String readValue() throws XMLStreamException, - ServiceXmlDeserializationException { - return readValue(false); - } - - /** - * Reads the value. Should return content element or text node as string - * Present event must be START ELEMENT. After executing this function - * Present event will be set on END ELEMENT - * - * @param keepWhiteSpace Do not remove whitespace characters if true - * @return String - * @throws javax.xml.stream.XMLStreamException the xML stream exception - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public String readValue(boolean keepWhiteSpace) throws XMLStreamException, - ServiceXmlDeserializationException { - String errMsg = String.format("Could not read value from %s.", - XmlNodeType.getString(this.presentEvent.getEventType())); - if (this.presentEvent.isStartElement()) { - // Go to next event and check for Characters event - this.read(keepWhiteSpace); - if (this.presentEvent.isCharacters()) { - StringBuffer elementValue = new StringBuffer(); - do { - if (this.getNodeType().nodeType == XmlNodeType.CHARACTERS) { - Characters characters = (Characters) this.presentEvent; - if (keepWhiteSpace || (!characters.isIgnorableWhiteSpace() - && !characters.isWhiteSpace())) { - if (characters.getData() != null && characters.getData().length() != 0) { - elementValue.append(characters.getData()); - } - } - } - this.read(); - } while (!this.presentEvent.isEndElement()); - // Characters chars = this.presentEvent.asCharacters(); - // String elementValue = chars.getData(); - // Advance to next event post Characters (ideally it will be End - // Element) - // this.read(); - return elementValue.toString(); - } else { - errMsg = errMsg + "Could not find " - + XmlNodeType.getString(XmlNodeType.CHARACTERS); - throw new ServiceXmlDeserializationException(errMsg); - } - } else if (this.presentEvent.getEventType() == XmlNodeType.CHARACTERS - && this.presentEvent.isCharacters()) { - /* - * if(this.presentEvent.asCharacters().getData().equals("<")) { - */ - final String charData = this.presentEvent - .asCharacters().getData(); - StringBuffer data = new StringBuffer(charData == null ? "" : charData); - do { - this.read(keepWhiteSpace); - if (this.getNodeType().nodeType == XmlNodeType.CHARACTERS) { - Characters characters = (Characters) this.presentEvent; - if (keepWhiteSpace || (!characters.isIgnorableWhiteSpace() - && !characters.isWhiteSpace())) { - if (characters.getData() != null && characters.getData().length() != 0) { - data.append(characters.getData()); - } - } - } - } while (!this.presentEvent.isEndElement()); - return data.toString();// this.presentEvent. = new XMLEvent(); - /* - * } else { Characters chars = this.presentEvent.asCharacters(); - * String elementValue = chars.getData(); // Advance to next event - * post Characters (ideally it will be End // Element) this.read(); - * return elementValue; } - */ - } else { - errMsg = errMsg + "Expected is " - + XmlNodeType.getString(XmlNodeType.START_ELEMENT); - throw new ServiceXmlDeserializationException(errMsg); - } - - } - - /** - * Tries to read value. - * - * @param value the value - * @return boolean - * @throws javax.xml.stream.XMLStreamException the xML stream exception - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public boolean tryReadValue(OutParam value) - throws XMLStreamException, ServiceXmlDeserializationException { - if (!this.isEmptyElement()) { - this.read(); - - if (this.presentEvent.isCharacters()) { - value.setParam(this.readValue()); - return true; - } else { - return false; - } - } else { - return false; - } - } - - /** - * Reads the value. - * - * @param the generic type - * @param cls the cls - * @return T - * @throws Exception the exception - */ - public T readValue(Class cls) throws Exception { - return EwsUtilities.parse(cls, this.readValue()); - } - - /** - * Reads the base64 element value. - * - * @return byte[] - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - * @throws java.io.IOException Signals that an I/O exception has occurred. - */ - public byte[] readBase64ElementValue() - throws ServiceXmlDeserializationException, XMLStreamException, - IOException { - this.ensureCurrentNodeIsStartElement(); - - byte[] buffer = null; - - ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(); - - buffer = Base64EncoderStream.decode(this.xmlReader.getElementText() - .toString()); - byteArrayStream.write(buffer); - - return byteArrayStream.toByteArray(); - - } - - /** - * Reads the base64 element value. - * - * @param outputStream the output stream - * @throws Exception the exception - */ - public void readBase64ElementValue(OutputStream outputStream) - throws Exception { - this.ensureCurrentNodeIsStartElement(); - - byte[] buffer = null; - buffer = Base64EncoderStream.decode(this.xmlReader.getElementText() - .toString()); - outputStream.write(buffer); - outputStream.flush(); - } - - /** - * Reads the start element. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @throws Exception the exception - */ - public void readStartElement(String namespacePrefix, String localName) - throws Exception { - this.internalReadElement(namespacePrefix, localName, new XmlNodeType( - XmlNodeType.START_ELEMENT)); - } - - /** - * Reads the start element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void readStartElement(XmlNamespace xmlNamespace, String localName) - throws Exception { - this.internalReadElement(xmlNamespace, localName, new XmlNodeType( - XmlNodeType.START_ELEMENT)); - } - - /** - * Reads the end element. - * - * @param namespacePrefix the namespace prefix - * @param elementName the element name - * @throws Exception the exception - */ - public void readEndElement(String namespacePrefix, String elementName) - throws Exception { - this.internalReadElement(namespacePrefix, elementName, new XmlNodeType( - XmlNodeType.END_ELEMENT)); - } - - /** - * Reads the end element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void readEndElement(XmlNamespace xmlNamespace, String localName) - throws Exception { - - this.internalReadElement(xmlNamespace, localName, new XmlNodeType( - XmlNodeType.END_ELEMENT)); - - } - - /** - * Reads the end element if necessary. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void readEndElementIfNecessary(XmlNamespace xmlNamespace, - String localName) throws Exception { - - if (!(this.isStartElement(xmlNamespace, localName) && this - .isEmptyElement())) { - if (!this.isEndElement(xmlNamespace, localName)) { - this.readEndElement(xmlNamespace, localName); - } - } - } - - /** - * Determines whether current element is a start element. - * - * @return boolean - */ - public boolean isStartElement() { - return this.presentEvent.isStartElement(); - } - - /** - * Determines whether current element is a start element. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @return boolean - */ - public boolean isStartElement(String namespacePrefix, String localName) { - boolean isStart = false; - if (this.presentEvent.isStartElement()) { - StartElement startElement = this.presentEvent.asStartElement(); - QName qName = startElement.getName(); - isStart = qName.getLocalPart().equals(localName) - && qName.getPrefix().equals(namespacePrefix); - } - return isStart; - } - - /** - * Determines whether current element is a start element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @return true for matching start element; false otherwise. - */ - public boolean isStartElement(XmlNamespace xmlNamespace, String localName) { - return this.isStartElement() - && EwsUtilities.stringEquals(this.getLocalName(), localName) - && ( - EwsUtilities.stringEquals(this.getNamespacePrefix(), EwsUtilities.getNamespacePrefix(xmlNamespace)) || - EwsUtilities.stringEquals(this.getNamespaceUri(), EwsUtilities.getNamespaceUri(xmlNamespace))); - } - - /** - * Determines whether current element is a end element. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @return boolean - */ - public boolean isEndElement(String namespacePrefix, String localName) { - boolean isEndElement = false; - if (this.presentEvent.isEndElement()) { - EndElement endElement = this.presentEvent.asEndElement(); - QName qName = endElement.getName(); - isEndElement = qName.getLocalPart().equals(localName) - && qName.getPrefix().equals(namespacePrefix); - - } - return isEndElement; - } - - /** - * Determines whether current element is a end element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @return boolean - */ - public boolean isEndElement(XmlNamespace xmlNamespace, String localName) { - - boolean isEndElement = false; - /* - * if(localName.equals("Body")) { return true; } else - */ - if (this.presentEvent.isEndElement()) { - EndElement endElement = this.presentEvent.asEndElement(); - QName qName = endElement.getName(); - isEndElement = qName.getLocalPart().equals(localName) - && (qName.getPrefix().equals( - EwsUtilities.getNamespacePrefix(xmlNamespace)) || - qName.getNamespaceURI().equals( - EwsUtilities.getNamespaceUri( - xmlNamespace))); - - } - return isEndElement; - } - - /** - * Skips the element. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @throws Exception the exception - */ - public void skipElement(String namespacePrefix, String localName) - throws Exception { - if (!this.isEndElement(namespacePrefix, localName)) { - if (!this.isStartElement(namespacePrefix, localName)) { - this.readStartElement(namespacePrefix, localName); - } - - if (!this.isEmptyElement()) { - do { - this.read(); - } while (!this.isEndElement(namespacePrefix, localName)); - } - } - } - - /** - * Skips the element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void skipElement(XmlNamespace xmlNamespace, String localName) - throws Exception { - if (!this.isEndElement(xmlNamespace, localName)) { - if (!this.isStartElement(xmlNamespace, localName)) { - this.readStartElement(xmlNamespace, localName); - } - - if (!this.isEmptyElement()) { - do { - this.read(); - } while (!this.isEndElement(xmlNamespace, localName)); - } - } - } - - /** - * Skips the current element. - * - * @throws Exception the exception - */ - public void skipCurrentElement() throws Exception { - this.skipElement(this.getNamespacePrefix(), this.getLocalName()); - } - - /** - * Ensures the current node is start element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public void ensureCurrentNodeIsStartElement(XmlNamespace xmlNamespace, - String localName) throws ServiceXmlDeserializationException { - - if (!this.isStartElement(xmlNamespace, localName)) { - throw new ServiceXmlDeserializationException( - String - .format( - Strings.ElementNotFound, - localName, xmlNamespace)); - } - } - - /** - * Ensures the current node is start element. - * - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public void ensureCurrentNodeIsStartElement() - throws ServiceXmlDeserializationException { - XmlNodeType presentNodeType = new XmlNodeType(this.presentEvent - .getEventType()); - if (!this.presentEvent.isStartElement()) { - throw new ServiceXmlDeserializationException(String.format( - Strings.ExpectedStartElement, - this.presentEvent.toString(), presentNodeType.toString())); - } - } - - /** - * Ensures the current node is start element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void ensureCurrentNodeIsEndElement(XmlNamespace xmlNamespace, - String localName) throws Exception { - if (!this.isEndElement(xmlNamespace, localName)) { - if (!(this.isStartElement(xmlNamespace, localName) && this - .isEmptyElement())) { - throw new ServiceXmlDeserializationException( - String - .format( - Strings.ElementNotFound, - xmlNamespace, localName)); - } - } - } - - /** - * Outer XML as string. - * - * @return String - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public String readOuterXml() throws ServiceXmlDeserializationException, - XMLStreamException { - if (!this.isStartElement()) { - throw new ServiceXmlDeserializationException( - Strings.CurrentPositionNotElementStart); - } - - XMLEvent startEvent = this.presentEvent; - XMLEvent event; - StringBuilder str = new StringBuilder(); - str.append(startEvent); - do { - event = this.xmlReader.nextEvent(); - str.append(event); - } while (!checkEndElement(startEvent, event)); - - return str.toString(); - } - - /** - * Reads the Inner XML at the given location. - * - * @return String - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public String readInnerXml() throws ServiceXmlDeserializationException, - XMLStreamException { - if (!this.isStartElement()) { - throw new ServiceXmlDeserializationException( - Strings.CurrentPositionNotElementStart); - } - - XMLEvent startEvent = this.presentEvent; - StringBuilder str = new StringBuilder(); - do { - XMLEvent event = this.xmlReader.nextEvent(); - if (checkEndElement(startEvent, event)) { - break; - } - str.append(event); - } while (true); - - return str.toString(); - } - - /** - * Check end element. - * - * @param startEvent the start event - * @param endEvent the end event - * @return true, if successful - */ - public static boolean checkEndElement(XMLEvent startEvent, - XMLEvent endEvent) { - - boolean isEndElement = false; - if (endEvent.isEndElement()) { - QName qEName = endEvent.asEndElement().getName(); - QName qSName = startEvent.asStartElement().getName(); - isEndElement = qEName.getLocalPart().equals(qSName.getLocalPart()) - && (qEName.getPrefix().equals(qSName.getPrefix()) || qEName - .getNamespaceURI().equals(qSName. - getNamespaceURI())); - - } - return isEndElement; - } - - /** - * Gets the XML reader for node. - * - * @return null - * @throws javax.xml.stream.XMLStreamException - * @throws ServiceXmlDeserializationException - * @throws java.io.FileNotFoundException - */ - protected XMLEventReader getXmlReaderForNode() - throws FileNotFoundException, ServiceXmlDeserializationException, XMLStreamException { - return readSubtree(); //this.xmlReader.ReadSubtree(); - } - - public XMLEventReader readSubtree() - throws XMLStreamException, FileNotFoundException, ServiceXmlDeserializationException { - - if (!this.isStartElement()) { - throw new ServiceXmlDeserializationException( - Strings.CurrentPositionNotElementStart); - } - - XMLEventReader eventReader = null; - InputStream in = null; - XMLEvent startEvent = this.presentEvent; - XMLEvent event = startEvent; - StringBuilder str = new StringBuilder(); - str.append(startEvent); - do { - event = this.xmlReader.nextEvent(); - str.append(event); - } while (!checkEndElement(startEvent, event)); - - try { - - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - - try { - in = new ByteArrayInputStream(str.toString().getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - eventReader = inputFactory.createXMLEventReader(in); - - } catch (Exception e) { - e.printStackTrace(); - } - return eventReader; - } - - /** - * Reads to the next descendant element with the specified local name and - * namespace. - * - * @param xmlNamespace The namespace of the element you with to move to. - * @param localName The local name of the element you wish to move to. - * @throws javax.xml.stream.XMLStreamException - */ - public void ReadToDescendant(XmlNamespace xmlNamespace, String localName) throws XMLStreamException { - readToDescendant(localName, EwsUtilities.getNamespaceUri(xmlNamespace)); - } - - public boolean readToDescendant(String localName, String namespaceURI) throws XMLStreamException { - - if (!this.isStartElement()) { - return false; - } - XMLEvent startEvent = this.presentEvent; - XMLEvent event = this.presentEvent; - do { - if (event.isStartElement()) { - QName qEName = event.asStartElement().getName(); - if (qEName.getLocalPart().equals(localName) && - qEName.getNamespaceURI().equals(namespaceURI)) { - return true; - } - } - event = this.xmlReader.nextEvent(); - } while (!checkEndElement(startEvent, event)); - - return false; - } - - - - /** - * Gets a value indicating whether this instance has attributes. - * - * @return boolean - */ - public boolean hasAttributes() { - - if (this.presentEvent.isStartElement()) { - StartElement startElement = this.presentEvent.asStartElement(); - return startElement.getAttributes().hasNext(); - } else { - return false; - } - } - - /** - * Gets a value indicating whether current element is empty. - * - * @return boolean - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public boolean isEmptyElement() throws XMLStreamException { - boolean isPresentStartElement = this.presentEvent.isStartElement(); - boolean isNextEndElement = this.xmlReader.peek().isEndElement(); - return isPresentStartElement && isNextEndElement; - } - - /** - * Gets the local name of the current element. - * - * @return String - */ - public String getLocalName() { - - String localName = null; - - if (this.presentEvent.isStartElement()) { - localName = this.presentEvent.asStartElement().getName() - .getLocalPart(); - } else { - - localName = this.presentEvent.asEndElement().getName() - .getLocalPart(); - } - return localName; - } - - /** - * Gets the namespace prefix. - * - * @return String - */ - protected String getNamespacePrefix() { - if (this.presentEvent.isStartElement()) { - return this.presentEvent.asStartElement().getName().getPrefix(); - } - if (this.presentEvent.isEndElement()) { - return this.presentEvent.asEndElement().getName().getPrefix(); - } - return null; - } - - /** - * Gets the namespace URI. - * - * @return String - */ - protected String getNamespaceUri() { - - String nameSpaceUri = null; - if (this.presentEvent.isStartElement()) { - nameSpaceUri = this.presentEvent.asStartElement().getName() - .getNamespaceURI(); - } else { - - nameSpaceUri = this.presentEvent.asEndElement().getName() - .getNamespaceURI(); - } - return nameSpaceUri; - } - - /** - * Gets the type of the node. - * - * @return XmlNodeType - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public XmlNodeType getNodeType() throws XMLStreamException { - XMLEvent event = this.presentEvent; - XmlNodeType nodeType = new XmlNodeType(event.getEventType()); - return nodeType; - } - - /** - * Gets the name of the current element. - * - * @return Object - */ - protected Object getName() { - String name = null; - if (this.presentEvent.isStartElement()) { - name = this.presentEvent.asStartElement().getName().toString(); - } else { - - name = this.presentEvent.asEndElement().getName().toString(); - } - return name; - } - - /** - * Checks is the string is null or empty. - * - * @param namespacePrefix the namespace prefix - * @return true, if is null or empty - */ - private static boolean isNullOrEmpty(String namespacePrefix) { - return (namespacePrefix == null || namespacePrefix.isEmpty()); - - } - -} diff --git a/All/Genesis-NP/Genesis#448/old/EwsXmlReader.java b/All/Genesis-NP/Genesis#448/old/EwsXmlReader.java deleted file mode 100755 index 08b944f..0000000 --- a/All/Genesis-NP/Genesis#448/old/EwsXmlReader.java +++ /dev/null @@ -1,1124 +0,0 @@ -/* - * The MIT License - * Copyright (c) 2012 Microsoft Corporation - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ - -package microsoft.exchange.webservices.data; - -import javax.xml.namespace.QName; -import javax.xml.stream.XMLEventReader; -import javax.xml.stream.XMLInputFactory; -import javax.xml.stream.XMLStreamConstants; -import javax.xml.stream.XMLStreamException; -import javax.xml.stream.events.*; -import java.io.*; - -/** - * Defines the EwsXmlReader class. - */ -class EwsXmlReader { - - /** - * The Read write buffer size. - */ - private static final int ReadWriteBufferSize = 4096; - - /** - * The xml reader. - */ - private XMLEventReader xmlReader = null; - - /** - * The present event. - */ - private XMLEvent presentEvent; - - /** - * The prev event. - */ - private XMLEvent prevEvent; - - /** - * Initializes a new instance of the EwsXmlReader class. - * - * @param stream the stream - * @throws Exception - */ - public EwsXmlReader(InputStream stream) throws Exception { - this.xmlReader = initializeXmlReader(stream); - } - - /** - * Initializes the XML reader. - * - * @param stream the stream - * @return An XML reader to use. - * @throws Exception - */ - protected XMLEventReader initializeXmlReader(InputStream stream) - throws XMLStreamException, Exception { - - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); - //inputFactory.setProperty(XMLInputFactory.RESOLVER, null); - - return inputFactory.createXMLEventReader(stream); - } - - - /** - * Formats the name of the element. - * - * @param namespacePrefix The namespace prefix - * @param localElementName Element name - * @return the string - */ - private static String formatElementName(String namespacePrefix, - String localElementName) { - - return isNullOrEmpty(namespacePrefix) ? localElementName : - namespacePrefix + ":" + localElementName; - } - - /** - * Read XML element. - * - * @param xmlNamespace The XML namespace - * @param localName Name of the local - * @param nodeType Type of the node - * @throws Exception the exception - */ - private void internalReadElement(XmlNamespace xmlNamespace, - String localName, XmlNodeType nodeType) throws Exception { - - if (xmlNamespace == XmlNamespace.NotSpecified) { - this.internalReadElement("", localName, nodeType); - } else { - this.read(nodeType); - - if ((!this.getLocalName().equals(localName)) || - (!this.getNamespaceUri().equals(EwsUtilities - .getNamespaceUri(xmlNamespace)))) { - throw new ServiceXmlDeserializationException( - String - .format( - Strings.UnexpectedElement, - EwsUtilities - .getNamespacePrefix( - xmlNamespace), - localName, nodeType.toString(), this - .getName(), this.getNodeType() - .toString())); - } - } - } - - /** - * Read XML element. - * - * @param namespacePrefix The namespace prefix - * @param localName Name of the local - * @param nodeType Type of the node - * @throws Exception the exception - */ - private void internalReadElement(String namespacePrefix, String localName, - XmlNodeType nodeType) throws Exception { - read(nodeType); - - if ((!this.getLocalName().equals(localName)) || - (!this.getNamespacePrefix().equals(namespacePrefix))) { - throw new ServiceXmlDeserializationException(String.format( - Strings.UnexpectedElement, namespacePrefix, localName, - nodeType.toString(), this.getName(), this.getNodeType() - .toString())); - } - } - - /** - * Reads the specified node type. - * - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public void read() throws ServiceXmlDeserializationException, - XMLStreamException { - read(false); - } - - /** - * Reads the specified node type. - * - * @param keepWhiteSpace Do not remove whitespace characters if true - * - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - private void read(boolean keepWhiteSpace) throws ServiceXmlDeserializationException, - XMLStreamException { - // The caller to EwsXmlReader.Read expects - // that there's another node to - // read. Throw an exception if not true. - while (true) { - if (!xmlReader.hasNext()) { - throw new ServiceXmlDeserializationException( - Strings.UnexpectedEndOfXmlDocument); - } else { - XMLEvent event = xmlReader.nextEvent(); - if (event.getEventType() == XMLStreamConstants.CHARACTERS) { - Characters characters = (Characters) event; - if (!keepWhiteSpace) - if (characters.isIgnorableWhiteSpace() - || characters.isWhiteSpace()) { - continue; - } - } - this.prevEvent = this.presentEvent; - this.presentEvent = event; - break; - } - } - } - - /** - * Reads the specified node type. - * - * @param nodeType Type of the node. - * @throws Exception the exception - */ - public void read(XmlNodeType nodeType) throws Exception { - this.read(); - if (!this.getNodeType().equals(nodeType)) { - throw new ServiceXmlDeserializationException(String - .format(Strings.UnexpectedElementType, nodeType, this - .getNodeType())); - } - } - - /** - * Read attribute value from QName. - * - * @param qName QName of the attribute - * @return Attribute Value - * @throws Exception thrown if attribute value can not be read - */ - private String readAttributeValue(QName qName) throws Exception { - if (this.presentEvent.isStartElement()) { - StartElement startElement = this.presentEvent.asStartElement(); - Attribute attr = startElement.getAttributeByName(qName); - if (null != attr) { - return attr.getValue(); - } else { - return null; - } - } else { - String errMsg = String.format("Could not fetch attribute %s", qName - .toString()); - throw new Exception(errMsg); - } - } - - /** - * Reads the attribute value. - * - * @param xmlNamespace The XML namespace. - * @param attributeName Name of the attribute - * @return Attribute Value - * @throws Exception the exception - */ - public String readAttributeValue(XmlNamespace xmlNamespace, - String attributeName) throws Exception { - if (xmlNamespace == XmlNamespace.NotSpecified) { - return this.readAttributeValue(attributeName); - } else { - QName qName = new QName(EwsUtilities.getNamespaceUri(xmlNamespace), - attributeName); - return readAttributeValue(qName); - } - } - - /** - * Reads the attribute value. - * - * @param attributeName Name of the attribute - * @return Attribute value. - * @throws Exception the exception - */ - public String readAttributeValue(String attributeName) throws Exception { - QName qName = new QName(attributeName); - return readAttributeValue(qName); - } - - /** - * Reads the attribute value. - * - * @param the generic type - * @param cls the cls - * @param attributeName the attribute name - * @return T - * @throws Exception the exception - */ - public T readAttributeValue(Class cls, String attributeName) - throws Exception { - return EwsUtilities.parse(cls, this.readAttributeValue(attributeName)); - } - - /** - * Reads a nullable attribute value. - * - * @param the generic type - * @param cls the cls - * @param attributeName the attribute name - * @return T - * @throws Exception the exception - */ - public T readNullableAttributeValue(Class cls, String attributeName) - throws Exception { - String attributeValue = this.readAttributeValue(attributeName); - if (attributeValue == null) { - return null; - } else { - return EwsUtilities.parse(cls, attributeValue); - } - } - - /** - * Reads the element value. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @return String - * @throws Exception the exception - */ - public String readElementValue(String namespacePrefix, String localName) - throws Exception { - if (!this.isStartElement(namespacePrefix, localName)) { - this.readStartElement(namespacePrefix, localName); - } - - String value = null; - - if (!this.isEmptyElement()) { - value = this.readValue(); - } - return value; - } - - /** - * Reads the element value. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @return String - * @throws Exception the exception - */ - public String readElementValue(XmlNamespace xmlNamespace, String localName) - throws Exception { - - if (!this.isStartElement(xmlNamespace, localName)) { - this.readStartElement(xmlNamespace, localName); - } - - String value = null; - - if (!this.isEmptyElement()) { - value = this.readValue(); - } else { - this.read(); - } - - return value; - } - - /** - * Read element value. - * - * @return String - * @throws Exception the exception - */ - public String readElementValue() throws Exception { - this.ensureCurrentNodeIsStartElement(); - - return this.readElementValue(this.getNamespacePrefix(), this - .getLocalName()); - } - - /** - * Reads the element value. - * - * @param the generic type - * @param cls the cls - * @param xmlNamespace the xml namespace - * @param localName the local name - * @return T - * @throws Exception the exception - */ - public T readElementValue(Class cls, XmlNamespace xmlNamespace, - String localName) throws Exception { - if (!this.isStartElement(xmlNamespace, localName)) { - this.readStartElement(xmlNamespace, localName); - } - - T value = null; - - if (!this.isEmptyElement()) { - value = this.readValue(cls); - } - - return value; - } - - /** - * Read element value. - * - * @param the generic type - * @param cls the cls - * @return T - * @throws Exception the exception - */ - public T readElementValue(Class cls) throws Exception { - this.ensureCurrentNodeIsStartElement(); - - T value = null; - - if (!this.isEmptyElement()) { - value = this.readValue(cls); - } - - return value; - } - - /** - * Reads the value. Should return content element or text node as string - * Present event must be START ELEMENT. After executing this function - * Present event will be set on END ELEMENT - * - * @return String - * @throws javax.xml.stream.XMLStreamException the xML stream exception - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public String readValue() throws XMLStreamException, - ServiceXmlDeserializationException { - return readValue(false); - } - /** - * Reads the value. Should return content element or text node as string - * Present event must be START ELEMENT. After executing this function - * Present event will be set on END ELEMENT - * - * @param keepWhiteSpace Do not remove whitespace characters if true - * @return String - * @throws javax.xml.stream.XMLStreamException the xML stream exception - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public String readValue(boolean keepWhiteSpace) throws XMLStreamException, - ServiceXmlDeserializationException { - String errMsg = String.format("Could not read value from %s.", - XmlNodeType.getString(this.presentEvent.getEventType())); - if (this.presentEvent.isStartElement()) { - // Go to next event and check for Characters event - this.read(keepWhiteSpace); - if (this.presentEvent.isCharacters()) { - StringBuffer elementValue = new StringBuffer(); - do { - if (this.getNodeType().nodeType == XmlNodeType.CHARACTERS) { - Characters characters = (Characters) this.presentEvent; - if (keepWhiteSpace || (!characters.isIgnorableWhiteSpace() - && !characters.isWhiteSpace())) { - if (characters.getData().length() != 0) { - elementValue.append(characters.getData()); - } - } - } - this.read(); - } while (!this.presentEvent.isEndElement()); - // Characters chars = this.presentEvent.asCharacters(); - // String elementValue = chars.getData(); - // Advance to next event post Characters (ideally it will be End - // Element) - // this.read(); - return elementValue.toString(); - } else { - errMsg = errMsg + "Could not find " - + XmlNodeType.getString(XmlNodeType.CHARACTERS); - throw new ServiceXmlDeserializationException(errMsg); - } - } else if (this.presentEvent.getEventType() == XmlNodeType.CHARACTERS - && this.presentEvent.isCharacters()) { - /* - * if(this.presentEvent.asCharacters().getData().equals("<")) { - */ - StringBuffer data = new StringBuffer(this.presentEvent - .asCharacters().getData()); - do { - this.read(keepWhiteSpace); - if (this.getNodeType().nodeType == XmlNodeType.CHARACTERS) { - Characters characters = (Characters) this.presentEvent; - if (keepWhiteSpace || (!characters.isIgnorableWhiteSpace() - && !characters.isWhiteSpace())) { - if (characters.getData().length() != 0) { - data.append(characters.getData()); - } - } - } - } while (!this.presentEvent.isEndElement()); - return data.toString();// this.presentEvent. = new XMLEvent(); - /* - * } else { Characters chars = this.presentEvent.asCharacters(); - * String elementValue = chars.getData(); // Advance to next event - * post Characters (ideally it will be End // Element) this.read(); - * return elementValue; } - */ - } else { - errMsg = errMsg + "Expected is " - + XmlNodeType.getString(XmlNodeType.START_ELEMENT); - throw new ServiceXmlDeserializationException(errMsg); - } - - } - - /** - * Tries to read value. - * - * @param value the value - * @return boolean - * @throws javax.xml.stream.XMLStreamException the xML stream exception - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public boolean tryReadValue(OutParam value) - throws XMLStreamException, ServiceXmlDeserializationException { - if (!this.isEmptyElement()) { - this.read(); - - if (this.presentEvent.isCharacters()) { - value.setParam(this.readValue()); - return true; - } else { - return false; - } - } else { - return false; - } - } - - /** - * Reads the value. - * - * @param the generic type - * @param cls the cls - * @return T - * @throws Exception the exception - */ - public T readValue(Class cls) throws Exception { - return EwsUtilities.parse(cls, this.readValue()); - } - - /** - * Reads the base64 element value. - * - * @return byte[] - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - * @throws java.io.IOException Signals that an I/O exception has occurred. - */ - public byte[] readBase64ElementValue() - throws ServiceXmlDeserializationException, XMLStreamException, - IOException { - this.ensureCurrentNodeIsStartElement(); - - byte[] buffer = null; - - ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(); - - buffer = Base64EncoderStream.decode(this.xmlReader.getElementText() - .toString()); - byteArrayStream.write(buffer); - - return byteArrayStream.toByteArray(); - - } - - /** - * Reads the base64 element value. - * - * @param outputStream the output stream - * @throws Exception the exception - */ - public void readBase64ElementValue(OutputStream outputStream) - throws Exception { - this.ensureCurrentNodeIsStartElement(); - - byte[] buffer = null; - buffer = Base64EncoderStream.decode(this.xmlReader.getElementText() - .toString()); - outputStream.write(buffer); - outputStream.flush(); - } - - /** - * Reads the start element. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @throws Exception the exception - */ - public void readStartElement(String namespacePrefix, String localName) - throws Exception { - this.internalReadElement(namespacePrefix, localName, new XmlNodeType( - XmlNodeType.START_ELEMENT)); - } - - /** - * Reads the start element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void readStartElement(XmlNamespace xmlNamespace, String localName) - throws Exception { - this.internalReadElement(xmlNamespace, localName, new XmlNodeType( - XmlNodeType.START_ELEMENT)); - } - - /** - * Reads the end element. - * - * @param namespacePrefix the namespace prefix - * @param elementName the element name - * @throws Exception the exception - */ - public void readEndElement(String namespacePrefix, String elementName) - throws Exception { - this.internalReadElement(namespacePrefix, elementName, new XmlNodeType( - XmlNodeType.END_ELEMENT)); - } - - /** - * Reads the end element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void readEndElement(XmlNamespace xmlNamespace, String localName) - throws Exception { - - this.internalReadElement(xmlNamespace, localName, new XmlNodeType( - XmlNodeType.END_ELEMENT)); - - } - - /** - * Reads the end element if necessary. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void readEndElementIfNecessary(XmlNamespace xmlNamespace, - String localName) throws Exception { - - if (!(this.isStartElement(xmlNamespace, localName) && this - .isEmptyElement())) { - if (!this.isEndElement(xmlNamespace, localName)) { - this.readEndElement(xmlNamespace, localName); - } - } - } - - /** - * Determines whether current element is a start element. - * - * @return boolean - */ - public boolean isStartElement() { - return this.presentEvent.isStartElement(); - } - - /** - * Determines whether current element is a start element. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @return boolean - */ - public boolean isStartElement(String namespacePrefix, String localName) { - boolean isStart = false; - if (this.presentEvent.isStartElement()) { - StartElement startElement = this.presentEvent.asStartElement(); - QName qName = startElement.getName(); - isStart = qName.getLocalPart().equals(localName) - && qName.getPrefix().equals(namespacePrefix); - } - return isStart; - } - - /** - * Determines whether current element is a start element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @return true for matching start element; false otherwise. - */ - public boolean isStartElement(XmlNamespace xmlNamespace, String localName) { - return this.isStartElement() - && EwsUtilities.stringEquals(this.getLocalName(), localName) - && ( - EwsUtilities.stringEquals(this.getNamespacePrefix(), EwsUtilities.getNamespacePrefix(xmlNamespace)) || - EwsUtilities.stringEquals(this.getNamespaceUri(), EwsUtilities.getNamespaceUri(xmlNamespace))); - } - - /** - * Determines whether current element is a end element. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @return boolean - */ - public boolean isEndElement(String namespacePrefix, String localName) { - boolean isEndElement = false; - if (this.presentEvent.isEndElement()) { - EndElement endElement = this.presentEvent.asEndElement(); - QName qName = endElement.getName(); - isEndElement = qName.getLocalPart().equals(localName) - && qName.getPrefix().equals(namespacePrefix); - - } - return isEndElement; - } - - /** - * Determines whether current element is a end element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @return boolean - */ - public boolean isEndElement(XmlNamespace xmlNamespace, String localName) { - - boolean isEndElement = false; - /* - * if(localName.equals("Body")) { return true; } else - */ - if (this.presentEvent.isEndElement()) { - EndElement endElement = this.presentEvent.asEndElement(); - QName qName = endElement.getName(); - isEndElement = qName.getLocalPart().equals(localName) - && (qName.getPrefix().equals( - EwsUtilities.getNamespacePrefix(xmlNamespace)) || - qName.getNamespaceURI().equals( - EwsUtilities.getNamespaceUri( - xmlNamespace))); - - } - return isEndElement; - } - - /** - * Skips the element. - * - * @param namespacePrefix the namespace prefix - * @param localName the local name - * @throws Exception the exception - */ - public void skipElement(String namespacePrefix, String localName) - throws Exception { - if (!this.isEndElement(namespacePrefix, localName)) { - if (!this.isStartElement(namespacePrefix, localName)) { - this.readStartElement(namespacePrefix, localName); - } - - if (!this.isEmptyElement()) { - do { - this.read(); - } while (!this.isEndElement(namespacePrefix, localName)); - } - } - } - - /** - * Skips the element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void skipElement(XmlNamespace xmlNamespace, String localName) - throws Exception { - if (!this.isEndElement(xmlNamespace, localName)) { - if (!this.isStartElement(xmlNamespace, localName)) { - this.readStartElement(xmlNamespace, localName); - } - - if (!this.isEmptyElement()) { - do { - this.read(); - } while (!this.isEndElement(xmlNamespace, localName)); - } - } - } - - /** - * Skips the current element. - * - * @throws Exception the exception - */ - public void skipCurrentElement() throws Exception { - this.skipElement(this.getNamespacePrefix(), this.getLocalName()); - } - - /** - * Ensures the current node is start element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public void ensureCurrentNodeIsStartElement(XmlNamespace xmlNamespace, - String localName) throws ServiceXmlDeserializationException { - - if (!this.isStartElement(xmlNamespace, localName)) { - throw new ServiceXmlDeserializationException( - String - .format( - Strings.ElementNotFound, - localName, xmlNamespace)); - } - } - - /** - * Ensures the current node is start element. - * - * @throws ServiceXmlDeserializationException the service xml deserialization exception - */ - public void ensureCurrentNodeIsStartElement() - throws ServiceXmlDeserializationException { - XmlNodeType presentNodeType = new XmlNodeType(this.presentEvent - .getEventType()); - if (!this.presentEvent.isStartElement()) { - throw new ServiceXmlDeserializationException(String.format( - Strings.ExpectedStartElement, - this.presentEvent.toString(), presentNodeType.toString())); - } - } - - /** - * Ensures the current node is start element. - * - * @param xmlNamespace the xml namespace - * @param localName the local name - * @throws Exception the exception - */ - public void ensureCurrentNodeIsEndElement(XmlNamespace xmlNamespace, - String localName) throws Exception { - if (!this.isEndElement(xmlNamespace, localName)) { - if (!(this.isStartElement(xmlNamespace, localName) && this - .isEmptyElement())) { - throw new ServiceXmlDeserializationException( - String - .format( - Strings.ElementNotFound, - xmlNamespace, localName)); - } - } - } - - /** - * Outer XML as string. - * - * @return String - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public String readOuterXml() throws ServiceXmlDeserializationException, - XMLStreamException { - if (!this.isStartElement()) { - throw new ServiceXmlDeserializationException( - Strings.CurrentPositionNotElementStart); - } - - XMLEvent startEvent = this.presentEvent; - XMLEvent event; - StringBuilder str = new StringBuilder(); - str.append(startEvent); - do { - event = this.xmlReader.nextEvent(); - str.append(event); - } while (!checkEndElement(startEvent, event)); - - return str.toString(); - } - - /** - * Reads the Inner XML at the given location. - * - * @return String - * @throws ServiceXmlDeserializationException the service xml deserialization exception - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public String readInnerXml() throws ServiceXmlDeserializationException, - XMLStreamException { - if (!this.isStartElement()) { - throw new ServiceXmlDeserializationException( - Strings.CurrentPositionNotElementStart); - } - - XMLEvent startEvent = this.presentEvent; - StringBuilder str = new StringBuilder(); - do { - XMLEvent event = this.xmlReader.nextEvent(); - if (checkEndElement(startEvent, event)) { - break; - } - str.append(event); - } while (true); - - return str.toString(); - } - - /** - * Check end element. - * - * @param startEvent the start event - * @param endEvent the end event - * @return true, if successful - */ - public static boolean checkEndElement(XMLEvent startEvent, - XMLEvent endEvent) { - - boolean isEndElement = false; - if (endEvent.isEndElement()) { - QName qEName = endEvent.asEndElement().getName(); - QName qSName = startEvent.asStartElement().getName(); - isEndElement = qEName.getLocalPart().equals(qSName.getLocalPart()) - && (qEName.getPrefix().equals(qSName.getPrefix()) || qEName - .getNamespaceURI().equals(qSName. - getNamespaceURI())); - - } - return isEndElement; - } - - /** - * Gets the XML reader for node. - * - * @return null - * @throws javax.xml.stream.XMLStreamException - * @throws ServiceXmlDeserializationException - * @throws java.io.FileNotFoundException - */ - protected XMLEventReader getXmlReaderForNode() - throws FileNotFoundException, ServiceXmlDeserializationException, XMLStreamException { - return readSubtree(); //this.xmlReader.ReadSubtree(); - } - - public XMLEventReader readSubtree() - throws XMLStreamException, FileNotFoundException, ServiceXmlDeserializationException { - - if (!this.isStartElement()) { - throw new ServiceXmlDeserializationException( - Strings.CurrentPositionNotElementStart); - } - - XMLEventReader eventReader = null; - InputStream in = null; - XMLEvent startEvent = this.presentEvent; - XMLEvent event = startEvent; - StringBuilder str = new StringBuilder(); - str.append(startEvent); - do { - event = this.xmlReader.nextEvent(); - str.append(event); - } while (!checkEndElement(startEvent, event)); - - try { - - XMLInputFactory inputFactory = XMLInputFactory.newInstance(); - - try { - in = new ByteArrayInputStream(str.toString().getBytes("UTF-8")); - } catch (UnsupportedEncodingException e) { - e.printStackTrace(); - } - eventReader = inputFactory.createXMLEventReader(in); - - } catch (Exception e) { - e.printStackTrace(); - } - return eventReader; - } - - /** - * Reads to the next descendant element with the specified local name and - * namespace. - * - * @param xmlNamespace The namespace of the element you with to move to. - * @param localName The local name of the element you wish to move to. - * @throws javax.xml.stream.XMLStreamException - */ - public void ReadToDescendant(XmlNamespace xmlNamespace, String localName) throws XMLStreamException { - readToDescendant(localName, EwsUtilities.getNamespaceUri(xmlNamespace)); - } - - public boolean readToDescendant(String localName, String namespaceURI) throws XMLStreamException { - - if (!this.isStartElement()) { - return false; - } - XMLEvent startEvent = this.presentEvent; - XMLEvent event = this.presentEvent; - do { - if (event.isStartElement()) { - QName qEName = event.asStartElement().getName(); - if (qEName.getLocalPart().equals(localName) && - qEName.getNamespaceURI().equals(namespaceURI)) { - return true; - } - } - event = this.xmlReader.nextEvent(); - } while (!checkEndElement(startEvent, event)); - - return false; - } - - - - /** - * Gets a value indicating whether this instance has attributes. - * - * @return boolean - */ - public boolean hasAttributes() { - - if (this.presentEvent.isStartElement()) { - StartElement startElement = this.presentEvent.asStartElement(); - return startElement.getAttributes().hasNext(); - } else { - return false; - } - } - - /** - * Gets a value indicating whether current element is empty. - * - * @return boolean - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public boolean isEmptyElement() throws XMLStreamException { - boolean isPresentStartElement = this.presentEvent.isStartElement(); - boolean isNextEndElement = this.xmlReader.peek().isEndElement(); - return isPresentStartElement && isNextEndElement; - } - - /** - * Gets the local name of the current element. - * - * @return String - */ - public String getLocalName() { - - String localName = null; - - if (this.presentEvent.isStartElement()) { - localName = this.presentEvent.asStartElement().getName() - .getLocalPart(); - } else { - - localName = this.presentEvent.asEndElement().getName() - .getLocalPart(); - } - return localName; - } - - /** - * Gets the namespace prefix. - * - * @return String - */ - protected String getNamespacePrefix() { - if (this.presentEvent.isStartElement()) { - return this.presentEvent.asStartElement().getName().getPrefix(); - } - if (this.presentEvent.isEndElement()) { - return this.presentEvent.asEndElement().getName().getPrefix(); - } - return null; - } - - /** - * Gets the namespace URI. - * - * @return String - */ - protected String getNamespaceUri() { - - String nameSpaceUri = null; - if (this.presentEvent.isStartElement()) { - nameSpaceUri = this.presentEvent.asStartElement().getName() - .getNamespaceURI(); - } else { - - nameSpaceUri = this.presentEvent.asEndElement().getName() - .getNamespaceURI(); - } - return nameSpaceUri; - } - - /** - * Gets the type of the node. - * - * @return XmlNodeType - * @throws javax.xml.stream.XMLStreamException the xML stream exception - */ - public XmlNodeType getNodeType() throws XMLStreamException { - XMLEvent event = this.presentEvent; - XmlNodeType nodeType = new XmlNodeType(event.getEventType()); - return nodeType; - } - - /** - * Gets the name of the current element. - * - * @return Object - */ - protected Object getName() { - String name = null; - if (this.presentEvent.isStartElement()) { - name = this.presentEvent.asStartElement().getName().toString(); - } else { - - name = this.presentEvent.asEndElement().getName().toString(); - } - return name; - } - - /** - * Checks is the string is null or empty. - * - * @param namespacePrefix the namespace prefix - * @return true, if is null or empty - */ - private static boolean isNullOrEmpty(String namespacePrefix) { - return (namespacePrefix == null || namespacePrefix.isEmpty()); - - } - -} diff --git a/All/Genesis-NP/Genesis#448/pair.info b/All/Genesis-NP/Genesis#448/pair.info deleted file mode 100755 index cbd22dc..0000000 --- a/All/Genesis-NP/Genesis#448/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:448 -SATName:Genesis -modifiedFPath:src/main/java/microsoft/exchange/webservices/data/EwsXmlReader.java -comSha:cd0b89fa303df6cdd07dae2ca89e5a5375c3931c -parentComSha:cd0b89fa303df6cdd07dae2ca89e5a5375c3931c^1 -githubUrl:https://github.com/OfficeDev/ews-java-api -repoName:OfficeDev#ews-java-api \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#449/comMsg.txt b/All/Genesis-NP/Genesis#449/comMsg.txt deleted file mode 100755 index e992a6f..0000000 --- a/All/Genesis-NP/Genesis#449/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix NPE occured on referring Historic Variable(JPAEntityVariableType) diff --git a/All/Genesis-NP/Genesis#449/diff.diff b/All/Genesis-NP/Genesis#449/diff.diff deleted file mode 100755 index bc329b2..0000000 --- a/All/Genesis-NP/Genesis#449/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/ProcessInstanceHistoryLogQueryImpl.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/ProcessInstanceHistoryLogQueryImpl.java -index bcc96fe..332aa63 100644 ---- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/ProcessInstanceHistoryLogQueryImpl.java -+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/ProcessInstanceHistoryLogQueryImpl.java -@@ -13,0 +14,4 @@ import org.activiti.engine.impl.persistence.entity.HistoricProcessInstanceEntity -+import org.activiti.engine.impl.persistence.entity.HistoricVariableInstanceEntity; -+import org.activiti.engine.impl.variable.CacheableVariable; -+import org.activiti.engine.impl.variable.JPAEntityListVariableType; -+import org.activiti.engine.impl.variable.JPAEntityVariableType; -@@ -116,0 +121,6 @@ public class ProcessInstanceHistoryLogQueryImpl implements ProcessInstanceHistor -+ -+ // make sure JPA entities are cached for later retrieval -+ HistoricVariableInstanceEntity variableEntity = (HistoricVariableInstanceEntity) historicVariableInstance; -+ if (JPAEntityVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName()) || JPAEntityListVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName())) { -+ ((CacheableVariable) variableEntity.getVariableType()).setForceCacheable(true); -+ } diff --git a/All/Genesis-NP/Genesis#449/new/ProcessInstanceHistoryLogQueryImpl.java b/All/Genesis-NP/Genesis#449/new/ProcessInstanceHistoryLogQueryImpl.java deleted file mode 100755 index 332aa63..0000000 --- a/All/Genesis-NP/Genesis#449/new/ProcessInstanceHistoryLogQueryImpl.java +++ /dev/null @@ -1,158 +0,0 @@ -package org.activiti.engine.impl; - -import java.util.List; - -import org.activiti.engine.history.HistoricActivityInstance; -import org.activiti.engine.history.HistoricData; -import org.activiti.engine.history.HistoricVariableInstance; -import org.activiti.engine.history.ProcessInstanceHistoryLog; -import org.activiti.engine.history.ProcessInstanceHistoryLogQuery; -import org.activiti.engine.impl.interceptor.Command; -import org.activiti.engine.impl.interceptor.CommandContext; -import org.activiti.engine.impl.interceptor.CommandExecutor; -import org.activiti.engine.impl.persistence.entity.HistoricProcessInstanceEntity; -import org.activiti.engine.impl.persistence.entity.HistoricVariableInstanceEntity; -import org.activiti.engine.impl.variable.CacheableVariable; -import org.activiti.engine.impl.variable.JPAEntityListVariableType; -import org.activiti.engine.impl.variable.JPAEntityVariableType; - -/** - * @author Joram Barrez - */ -public class ProcessInstanceHistoryLogQueryImpl implements ProcessInstanceHistoryLogQuery, Command { - - protected CommandExecutor commandExecutor; - - protected String processInstanceId; - protected boolean includeTasks; - protected boolean includeActivities; - protected boolean includeVariables; - protected boolean includeComments; - protected boolean includeVariableUpdates; - protected boolean includeFormProperties; - - public ProcessInstanceHistoryLogQueryImpl(CommandExecutor commandExecutor, String processInstanceId) { - this.commandExecutor = commandExecutor; - this.processInstanceId = processInstanceId; - } - - @Override - public ProcessInstanceHistoryLogQuery includeTasks() { - this.includeTasks = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeComments() { - this.includeComments = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeActivities() { - this.includeActivities = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeVariables() { - this.includeVariables = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeVariableUpdates() { - this.includeVariableUpdates = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeFormProperties() { - this.includeFormProperties = true; - return this; - } - - @Override - public ProcessInstanceHistoryLog singleResult() { - return commandExecutor.execute(this); - } - - @Override - public ProcessInstanceHistoryLog execute(CommandContext commandContext) { - - // Fetch historic process instance - HistoricProcessInstanceEntity historicProcessInstance = commandContext - .getHistoricProcessInstanceEntityManager().findHistoricProcessInstance(processInstanceId); - - if (historicProcessInstance == null) { - return null; - } - - // Create a log using this historic process instance - ProcessInstanceHistoryLogImpl processInstanceHistoryLog = new ProcessInstanceHistoryLogImpl(historicProcessInstance); - - // Add events, based on query settings - - // Tasks - if (includeTasks) { - List tasks = commandContext.getHistoricTaskInstanceEntityManager() - .findHistoricTaskInstancesByQueryCriteria( - new HistoricTaskInstanceQueryImpl(commandExecutor).processInstanceId(processInstanceId)); - processInstanceHistoryLog.addHistoricData(tasks); - } - - // Activities - if (includeActivities) { - List activities = commandContext.getHistoricActivityInstanceEntityManager() - .findHistoricActivityInstancesByQueryCriteria( - new HistoricActivityInstanceQueryImpl(commandExecutor).processInstanceId(processInstanceId), null); - processInstanceHistoryLog.addHistoricData(activities); - } - - // Variables - if (includeVariables) { - List variables = commandContext.getHistoricVariableInstanceEntityManager() - .findHistoricVariableInstancesByQueryCriteria( - new HistoricVariableInstanceQueryImpl(commandExecutor).processInstanceId(processInstanceId), null); - - // Make sure all variables values are fetched (similar to the HistoricVariableInstance query) - for (HistoricVariableInstance historicVariableInstance : variables) { - historicVariableInstance.getValue(); - - // make sure JPA entities are cached for later retrieval - HistoricVariableInstanceEntity variableEntity = (HistoricVariableInstanceEntity) historicVariableInstance; - if (JPAEntityVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName()) || JPAEntityListVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName())) { - ((CacheableVariable) variableEntity.getVariableType()).setForceCacheable(true); - } - } - - processInstanceHistoryLog.addHistoricData(variables); - } - - // Comment - if (includeComments) { - List comments = commandContext.getCommentEntityManager().findCommentsByProcessInstanceId(processInstanceId); - processInstanceHistoryLog.addHistoricData(comments); - } - - // Details: variables - if (includeVariableUpdates) { - List variableUpdates = commandContext.getHistoricDetailEntityManager() - .findHistoricDetailsByQueryCriteria(new HistoricDetailQueryImpl(commandExecutor).variableUpdates(), null); - processInstanceHistoryLog.addHistoricData(variableUpdates); - } - - // Details: form properties - if (includeFormProperties) { - List formProperties = commandContext.getHistoricDetailEntityManager() - .findHistoricDetailsByQueryCriteria(new HistoricDetailQueryImpl(commandExecutor).formProperties(), null); - processInstanceHistoryLog.addHistoricData(formProperties); - } - - // All events collected. Sort them by date. - processInstanceHistoryLog.orderHistoricData(); - - return processInstanceHistoryLog; - } - -} diff --git a/All/Genesis-NP/Genesis#449/old/ProcessInstanceHistoryLogQueryImpl.java b/All/Genesis-NP/Genesis#449/old/ProcessInstanceHistoryLogQueryImpl.java deleted file mode 100755 index bcc96fe..0000000 --- a/All/Genesis-NP/Genesis#449/old/ProcessInstanceHistoryLogQueryImpl.java +++ /dev/null @@ -1,148 +0,0 @@ -package org.activiti.engine.impl; - -import java.util.List; - -import org.activiti.engine.history.HistoricActivityInstance; -import org.activiti.engine.history.HistoricData; -import org.activiti.engine.history.HistoricVariableInstance; -import org.activiti.engine.history.ProcessInstanceHistoryLog; -import org.activiti.engine.history.ProcessInstanceHistoryLogQuery; -import org.activiti.engine.impl.interceptor.Command; -import org.activiti.engine.impl.interceptor.CommandContext; -import org.activiti.engine.impl.interceptor.CommandExecutor; -import org.activiti.engine.impl.persistence.entity.HistoricProcessInstanceEntity; - -/** - * @author Joram Barrez - */ -public class ProcessInstanceHistoryLogQueryImpl implements ProcessInstanceHistoryLogQuery, Command { - - protected CommandExecutor commandExecutor; - - protected String processInstanceId; - protected boolean includeTasks; - protected boolean includeActivities; - protected boolean includeVariables; - protected boolean includeComments; - protected boolean includeVariableUpdates; - protected boolean includeFormProperties; - - public ProcessInstanceHistoryLogQueryImpl(CommandExecutor commandExecutor, String processInstanceId) { - this.commandExecutor = commandExecutor; - this.processInstanceId = processInstanceId; - } - - @Override - public ProcessInstanceHistoryLogQuery includeTasks() { - this.includeTasks = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeComments() { - this.includeComments = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeActivities() { - this.includeActivities = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeVariables() { - this.includeVariables = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeVariableUpdates() { - this.includeVariableUpdates = true; - return this; - } - - @Override - public ProcessInstanceHistoryLogQuery includeFormProperties() { - this.includeFormProperties = true; - return this; - } - - @Override - public ProcessInstanceHistoryLog singleResult() { - return commandExecutor.execute(this); - } - - @Override - public ProcessInstanceHistoryLog execute(CommandContext commandContext) { - - // Fetch historic process instance - HistoricProcessInstanceEntity historicProcessInstance = commandContext - .getHistoricProcessInstanceEntityManager().findHistoricProcessInstance(processInstanceId); - - if (historicProcessInstance == null) { - return null; - } - - // Create a log using this historic process instance - ProcessInstanceHistoryLogImpl processInstanceHistoryLog = new ProcessInstanceHistoryLogImpl(historicProcessInstance); - - // Add events, based on query settings - - // Tasks - if (includeTasks) { - List tasks = commandContext.getHistoricTaskInstanceEntityManager() - .findHistoricTaskInstancesByQueryCriteria( - new HistoricTaskInstanceQueryImpl(commandExecutor).processInstanceId(processInstanceId)); - processInstanceHistoryLog.addHistoricData(tasks); - } - - // Activities - if (includeActivities) { - List activities = commandContext.getHistoricActivityInstanceEntityManager() - .findHistoricActivityInstancesByQueryCriteria( - new HistoricActivityInstanceQueryImpl(commandExecutor).processInstanceId(processInstanceId), null); - processInstanceHistoryLog.addHistoricData(activities); - } - - // Variables - if (includeVariables) { - List variables = commandContext.getHistoricVariableInstanceEntityManager() - .findHistoricVariableInstancesByQueryCriteria( - new HistoricVariableInstanceQueryImpl(commandExecutor).processInstanceId(processInstanceId), null); - - // Make sure all variables values are fetched (similar to the HistoricVariableInstance query) - for (HistoricVariableInstance historicVariableInstance : variables) { - historicVariableInstance.getValue(); - } - - processInstanceHistoryLog.addHistoricData(variables); - } - - // Comment - if (includeComments) { - List comments = commandContext.getCommentEntityManager().findCommentsByProcessInstanceId(processInstanceId); - processInstanceHistoryLog.addHistoricData(comments); - } - - // Details: variables - if (includeVariableUpdates) { - List variableUpdates = commandContext.getHistoricDetailEntityManager() - .findHistoricDetailsByQueryCriteria(new HistoricDetailQueryImpl(commandExecutor).variableUpdates(), null); - processInstanceHistoryLog.addHistoricData(variableUpdates); - } - - // Details: form properties - if (includeFormProperties) { - List formProperties = commandContext.getHistoricDetailEntityManager() - .findHistoricDetailsByQueryCriteria(new HistoricDetailQueryImpl(commandExecutor).formProperties(), null); - processInstanceHistoryLog.addHistoricData(formProperties); - } - - // All events collected. Sort them by date. - processInstanceHistoryLog.orderHistoricData(); - - return processInstanceHistoryLog; - } - -} diff --git a/All/Genesis-NP/Genesis#449/pair.info b/All/Genesis-NP/Genesis#449/pair.info deleted file mode 100755 index e4740eb..0000000 --- a/All/Genesis-NP/Genesis#449/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:449 -SATName:Genesis -modifiedFPath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/ProcessInstanceHistoryLogQueryImpl.java -comSha:0d83e98dadccfb9874cf19c3b2883987231c3f4e -parentComSha:0d83e98dadccfb9874cf19c3b2883987231c3f4e^1 -githubUrl:https://github.com/Activiti/Activiti -repoName:Activiti#Activiti \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#461/comMsg.txt b/All/Genesis-NP/Genesis#461/comMsg.txt deleted file mode 100755 index e896f0a..0000000 --- a/All/Genesis-NP/Genesis#461/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -prevent NPE diff --git a/All/Genesis-NP/Genesis#461/diff.diff b/All/Genesis-NP/Genesis#461/diff.diff deleted file mode 100755 index 1aa9edf..0000000 --- a/All/Genesis-NP/Genesis#461/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/jobexecutor/TimerDeclarationImpl.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/jobexecutor/TimerDeclarationImpl.java -index d8ddddf..b09c653 100644 ---- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/jobexecutor/TimerDeclarationImpl.java -+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/jobexecutor/TimerDeclarationImpl.java -@@ -14,0 +15 @@ package org.activiti.engine.impl.jobexecutor; -+import org.activiti.engine.ActivitiException; -@@ -28,0 +30 @@ import java.io.Serializable; -+import java.rmi.activation.ActivationException; -@@ -102,0 +105,4 @@ public class TimerDeclarationImpl implements Serializable { -+ if (description==null) { -+ // Prefent NPE from happening in the next line -+ throw new ActivitiException("Timer '"+executionEntity.getActivityId()+"' was not configured with a valid duration/time"); -+ } diff --git a/All/Genesis-NP/Genesis#461/new/TimerDeclarationImpl.java b/All/Genesis-NP/Genesis#461/new/TimerDeclarationImpl.java deleted file mode 100755 index b09c653..0000000 --- a/All/Genesis-NP/Genesis#461/new/TimerDeclarationImpl.java +++ /dev/null @@ -1,132 +0,0 @@ -/* 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.activiti.engine.impl.jobexecutor; - -import org.activiti.engine.ActivitiException; -import org.activiti.engine.delegate.Expression; -import org.activiti.engine.delegate.VariableScope; -import org.activiti.engine.impl.calendar.BusinessCalendar; -import org.activiti.engine.impl.calendar.CycleBusinessCalendar; -import org.activiti.engine.impl.calendar.DueDateBusinessCalendar; -import org.activiti.engine.impl.calendar.DurationBusinessCalendar; -import org.activiti.engine.impl.context.Context; -import org.activiti.engine.impl.persistence.entity.ExecutionEntity; -import org.activiti.engine.impl.persistence.entity.TimerEntity; -import org.activiti.engine.impl.pvm.process.ActivityImpl; -import org.activiti.engine.impl.util.ClockUtil; -import org.springframework.util.StringUtils; - -import java.io.Serializable; -import java.rmi.activation.ActivationException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.regex.Pattern; - - -/** - * @author Tom Baeyens - */ -public class TimerDeclarationImpl implements Serializable { - - private static final long serialVersionUID = 1L; - - protected Expression description; - protected TimerDeclarationType type; - - protected String jobHandlerType; - protected String jobHandlerConfiguration = null; - protected String repeat; - protected boolean exclusive = TimerEntity.DEFAULT_EXCLUSIVE; - protected int retries = TimerEntity.DEFAULT_RETRIES; - - public TimerDeclarationImpl(Expression expression, TimerDeclarationType type, String jobHandlerType) { - this.jobHandlerType = jobHandlerType; - this.description = expression; - this.type= type; - } - - public String getJobHandlerType() { - return jobHandlerType; - } - - public String getJobHandlerConfiguration() { - return jobHandlerConfiguration; - } - - public void setJobHandlerConfiguration(String jobHandlerConfiguration) { - this.jobHandlerConfiguration = jobHandlerConfiguration; - } - - public String getRepeat() { - return repeat; - } - - public void setRepeat(String repeat) { - this.repeat = repeat; - } - - public boolean isExclusive() { - return exclusive; - } - - public void setExclusive(boolean exclusive) { - this.exclusive = exclusive; - } - - public int getRetries() { - return retries; - } - - public void setRetries(int retries) { - this.retries = retries; - } - - public void setJobHandlerType(String jobHandlerType) { - this.jobHandlerType = jobHandlerType; - } - - public TimerEntity prepareTimerEntity(ExecutionEntity executionEntity) { - BusinessCalendar businessCalendar = Context - .getProcessEngineConfiguration() - .getBusinessCalendarManager() - .getBusinessCalendar(type.caledarName); - - if (description==null) { - // Prefent NPE from happening in the next line - throw new ActivitiException("Timer '"+executionEntity.getActivityId()+"' was not configured with a valid duration/time"); - } - String dueDateString = executionEntity == null ? description.getExpressionText() : (String) description.getValue(executionEntity); - Date duedate = businessCalendar.resolveDuedate(dueDateString); - - TimerEntity timer = new TimerEntity(this); - timer.setDuedate(duedate); - if (executionEntity != null) { - timer.setExecution(executionEntity); - } - if (type == TimerDeclarationType.CYCLE) { - String prepared = prepareRepeat(dueDateString); - timer.setRepeat(prepared); - - } - - return timer; - } - private String prepareRepeat(String dueDate) { - if (dueDate.startsWith("R") && dueDate.split("/").length==2) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); - return dueDate.replace("/","/"+sdf.format(ClockUtil.getCurrentTime())+"/"); - } - return dueDate; - } -} diff --git a/All/Genesis-NP/Genesis#461/old/TimerDeclarationImpl.java b/All/Genesis-NP/Genesis#461/old/TimerDeclarationImpl.java deleted file mode 100755 index d8ddddf..0000000 --- a/All/Genesis-NP/Genesis#461/old/TimerDeclarationImpl.java +++ /dev/null @@ -1,126 +0,0 @@ -/* 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.activiti.engine.impl.jobexecutor; - -import org.activiti.engine.delegate.Expression; -import org.activiti.engine.delegate.VariableScope; -import org.activiti.engine.impl.calendar.BusinessCalendar; -import org.activiti.engine.impl.calendar.CycleBusinessCalendar; -import org.activiti.engine.impl.calendar.DueDateBusinessCalendar; -import org.activiti.engine.impl.calendar.DurationBusinessCalendar; -import org.activiti.engine.impl.context.Context; -import org.activiti.engine.impl.persistence.entity.ExecutionEntity; -import org.activiti.engine.impl.persistence.entity.TimerEntity; -import org.activiti.engine.impl.pvm.process.ActivityImpl; -import org.activiti.engine.impl.util.ClockUtil; -import org.springframework.util.StringUtils; - -import java.io.Serializable; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.regex.Pattern; - - -/** - * @author Tom Baeyens - */ -public class TimerDeclarationImpl implements Serializable { - - private static final long serialVersionUID = 1L; - - protected Expression description; - protected TimerDeclarationType type; - - protected String jobHandlerType; - protected String jobHandlerConfiguration = null; - protected String repeat; - protected boolean exclusive = TimerEntity.DEFAULT_EXCLUSIVE; - protected int retries = TimerEntity.DEFAULT_RETRIES; - - public TimerDeclarationImpl(Expression expression, TimerDeclarationType type, String jobHandlerType) { - this.jobHandlerType = jobHandlerType; - this.description = expression; - this.type= type; - } - - public String getJobHandlerType() { - return jobHandlerType; - } - - public String getJobHandlerConfiguration() { - return jobHandlerConfiguration; - } - - public void setJobHandlerConfiguration(String jobHandlerConfiguration) { - this.jobHandlerConfiguration = jobHandlerConfiguration; - } - - public String getRepeat() { - return repeat; - } - - public void setRepeat(String repeat) { - this.repeat = repeat; - } - - public boolean isExclusive() { - return exclusive; - } - - public void setExclusive(boolean exclusive) { - this.exclusive = exclusive; - } - - public int getRetries() { - return retries; - } - - public void setRetries(int retries) { - this.retries = retries; - } - - public void setJobHandlerType(String jobHandlerType) { - this.jobHandlerType = jobHandlerType; - } - - public TimerEntity prepareTimerEntity(ExecutionEntity executionEntity) { - BusinessCalendar businessCalendar = Context - .getProcessEngineConfiguration() - .getBusinessCalendarManager() - .getBusinessCalendar(type.caledarName); - - String dueDateString = executionEntity == null ? description.getExpressionText() : (String) description.getValue(executionEntity); - Date duedate = businessCalendar.resolveDuedate(dueDateString); - - TimerEntity timer = new TimerEntity(this); - timer.setDuedate(duedate); - if (executionEntity != null) { - timer.setExecution(executionEntity); - } - if (type == TimerDeclarationType.CYCLE) { - String prepared = prepareRepeat(dueDateString); - timer.setRepeat(prepared); - - } - - return timer; - } - private String prepareRepeat(String dueDate) { - if (dueDate.startsWith("R") && dueDate.split("/").length==2) { - SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss"); - return dueDate.replace("/","/"+sdf.format(ClockUtil.getCurrentTime())+"/"); - } - return dueDate; - } -} diff --git a/All/Genesis-NP/Genesis#461/pair.info b/All/Genesis-NP/Genesis#461/pair.info deleted file mode 100755 index 4156d49..0000000 --- a/All/Genesis-NP/Genesis#461/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:461 -SATName:Genesis -modifiedFPath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/jobexecutor/TimerDeclarationImpl.java -comSha:bdad8016b9a3482dfe08b85184a079474b100092 -parentComSha:bdad8016b9a3482dfe08b85184a079474b100092^1 -githubUrl:https://github.com/Activiti/Activiti -repoName:Activiti#Activiti \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#466/comMsg.txt b/All/Genesis-NP/Genesis#466/comMsg.txt deleted file mode 100755 index e5537d1..0000000 --- a/All/Genesis-NP/Genesis#466/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE in WSOperation diff --git a/All/Genesis-NP/Genesis#466/diff.diff b/All/Genesis-NP/Genesis#466/diff.diff deleted file mode 100755 index 5defa94..0000000 --- a/All/Genesis-NP/Genesis#466/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/webservice/WSOperation.java b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/webservice/WSOperation.java -index 15f1474..6a814f4 100644 ---- a/modules/activiti-engine/src/main/java/org/activiti/engine/impl/webservice/WSOperation.java -+++ b/modules/activiti-engine/src/main/java/org/activiti/engine/impl/webservice/WSOperation.java -@@ -17,0 +18 @@ import java.util.logging.Logger; -+import org.activiti.engine.impl.bpmn.MessageDefinition; -@@ -86 +87,4 @@ public class WSOperation implements OperationImplementation { -- MessageInstance message = operation.getOutMessage().createInstance(); -+ MessageInstance message = null; -+ MessageDefinition outMessage = operation.getOutMessage(); -+ if (outMessage != null) { -+ message = outMessage.createInstance(); -@@ -87,0 +92 @@ public class WSOperation implements OperationImplementation { -+ } diff --git a/All/Genesis-NP/Genesis#466/new/WSOperation.java b/All/Genesis-NP/Genesis#466/new/WSOperation.java deleted file mode 100755 index 6a814f4..0000000 --- a/All/Genesis-NP/Genesis#466/new/WSOperation.java +++ /dev/null @@ -1,99 +0,0 @@ -/* 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.activiti.engine.impl.webservice; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.activiti.engine.impl.bpmn.MessageDefinition; -import org.activiti.engine.impl.bpmn.MessageInstance; -import org.activiti.engine.impl.bpmn.Operation; -import org.activiti.engine.impl.bpmn.OperationImplementation; - -/** - * Represents a WS implementation of a {@link Operation} - * - * @author Esteban Robles Luna - */ -public class WSOperation implements OperationImplementation { - - private static final Logger LOGGER = Logger.getLogger(WSOperation.class.getName()); - - protected String id; - - protected String name; - - protected WSService service; - - public WSOperation(String id, String operationName, WSService service) { - this.id = id; - this.name = operationName; - this.service = service; - } - - /** - * {@inheritDoc} - */ - public String getId() { - return this.id; - } - - /** - * {@inheritDoc} - */ - public String getName() { - return this.name; - } - - /** - * {@inheritDoc} - */ - public MessageInstance sendFor(MessageInstance message, Operation operation) { - Object[] arguments = this.getArguments(message); - Object[] results = this.safeSend(arguments); - return this.createResponseMessage(results, operation); - } - - private Object[] getArguments(MessageInstance message) { - return message.getStructureInstance().toArray(); - } - - private Object[] safeSend(Object[] arguments) { - Object[] results = null; - - try { - results = this.service.getClient().send(this.name, arguments); - } catch (Exception e) { - LOGGER.log(Level.WARNING, "Error calling WS " + this.service.getName(), e); - } - - if (results == null) { - results = new Object[] {}; - } - return results; - } - - private MessageInstance createResponseMessage(Object[] results, Operation operation) { - MessageInstance message = null; - MessageDefinition outMessage = operation.getOutMessage(); - if (outMessage != null) { - message = outMessage.createInstance(); - message.getStructureInstance().loadFrom(results); - } - return message; - } - - public WSService getService() { - return this.service; - } -} diff --git a/All/Genesis-NP/Genesis#466/old/WSOperation.java b/All/Genesis-NP/Genesis#466/old/WSOperation.java deleted file mode 100755 index 15f1474..0000000 --- a/All/Genesis-NP/Genesis#466/old/WSOperation.java +++ /dev/null @@ -1,94 +0,0 @@ -/* 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.activiti.engine.impl.webservice; - -import java.util.logging.Level; -import java.util.logging.Logger; - -import org.activiti.engine.impl.bpmn.MessageInstance; -import org.activiti.engine.impl.bpmn.Operation; -import org.activiti.engine.impl.bpmn.OperationImplementation; - -/** - * Represents a WS implementation of a {@link Operation} - * - * @author Esteban Robles Luna - */ -public class WSOperation implements OperationImplementation { - - private static final Logger LOGGER = Logger.getLogger(WSOperation.class.getName()); - - protected String id; - - protected String name; - - protected WSService service; - - public WSOperation(String id, String operationName, WSService service) { - this.id = id; - this.name = operationName; - this.service = service; - } - - /** - * {@inheritDoc} - */ - public String getId() { - return this.id; - } - - /** - * {@inheritDoc} - */ - public String getName() { - return this.name; - } - - /** - * {@inheritDoc} - */ - public MessageInstance sendFor(MessageInstance message, Operation operation) { - Object[] arguments = this.getArguments(message); - Object[] results = this.safeSend(arguments); - return this.createResponseMessage(results, operation); - } - - private Object[] getArguments(MessageInstance message) { - return message.getStructureInstance().toArray(); - } - - private Object[] safeSend(Object[] arguments) { - Object[] results = null; - - try { - results = this.service.getClient().send(this.name, arguments); - } catch (Exception e) { - LOGGER.log(Level.WARNING, "Error calling WS " + this.service.getName(), e); - } - - if (results == null) { - results = new Object[] {}; - } - return results; - } - - private MessageInstance createResponseMessage(Object[] results, Operation operation) { - MessageInstance message = operation.getOutMessage().createInstance(); - message.getStructureInstance().loadFrom(results); - return message; - } - - public WSService getService() { - return this.service; - } -} diff --git a/All/Genesis-NP/Genesis#466/pair.info b/All/Genesis-NP/Genesis#466/pair.info deleted file mode 100755 index 7582c3c..0000000 --- a/All/Genesis-NP/Genesis#466/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:466 -SATName:Genesis -modifiedFPath:modules/activiti-engine/src/main/java/org/activiti/engine/impl/webservice/WSOperation.java -comSha:1351e94faf1312fd63b2abec1bf6d26f079cb31b -parentComSha:1351e94faf1312fd63b2abec1bf6d26f079cb31b^1 -githubUrl:https://github.com/Activiti/Activiti -repoName:Activiti#Activiti \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#471/comMsg.txt b/All/Genesis-NP/Genesis#471/comMsg.txt deleted file mode 100755 index b5660d8..0000000 --- a/All/Genesis-NP/Genesis#471/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -RedissonSortedSet NPE fixed. #328 diff --git a/All/Genesis-NP/Genesis#471/diff.diff b/All/Genesis-NP/Genesis#471/diff.diff deleted file mode 100755 index bc406b2..0000000 --- a/All/Genesis-NP/Genesis#471/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/org/redisson/RedissonSortedSet.java b/src/main/java/org/redisson/RedissonSortedSet.java -index 247d15c..95849a7 100644 ---- a/src/main/java/org/redisson/RedissonSortedSet.java -+++ b/src/main/java/org/redisson/RedissonSortedSet.java -@@ -31,2 +30,0 @@ import java.util.SortedSet; --import java.util.concurrent.Callable; --import java.util.concurrent.TimeUnit; -@@ -40 +37,0 @@ import org.redisson.command.CommandExecutor; --import org.redisson.connection.ConnectionManager; -@@ -43 +39,0 @@ import org.redisson.core.RSortedSet; --import io.netty.channel.EventLoop; -@@ -113,0 +110 @@ public class RedissonSortedSet extends RedissonObject implements RSortedSet - */ -public class RedissonSortedSet extends RedissonObject implements RSortedSet { - - private static class NaturalComparator implements Comparator, Serializable { - - private static final long serialVersionUID = 7207038068494060240L; - - static final NaturalComparator NATURAL_ORDER = new NaturalComparator(); - - public int compare(V c1, V c2) { - Comparable c1co = (Comparable) c1; - Comparable c2co = (Comparable) c2; - return c1co.compareTo(c2co); - } - - } - - public static class BinarySearchResult { - - private V value; - private int index; - - public BinarySearchResult(V value) { - super(); - this.value = value; - } - - public BinarySearchResult() { - } - - public void setIndex(int index) { - this.index = index; - } - public int getIndex() { - return index; - } - - public V getValue() { - return value; - } - - - } - - private Comparator comparator = NaturalComparator.NATURAL_ORDER; - - CommandExecutor commandExecutor; - - protected RedissonSortedSet(CommandExecutor commandExecutor, String name) { - super(commandExecutor, name); - this.commandExecutor = commandExecutor; - - loadComparator(); - - commandExecutor.write(getName(), StringCodec.INSTANCE, RedisCommands.SETNX, getCurrentVersionKey(), 0L); - } - - public RedissonSortedSet(Codec codec, CommandExecutor commandExecutor, String name) { - super(codec, commandExecutor, name); - this.commandExecutor = commandExecutor; - - loadComparator(); - - commandExecutor.write(getName(), StringCodec.INSTANCE, RedisCommands.SETNX, getCurrentVersionKey(), 0L); - } - - private void loadComparator() { - commandExecutor.read(getName(), codec, new SyncOperation() { - @Override - public Void execute(Codec codec, RedisConnection conn) { - loadComparator(conn); - return null; - } - }); - } - - private void loadComparator(RedisConnection connection) { - try { - String comparatorSign = connection.sync(StringCodec.INSTANCE, RedisCommands.GET, getComparatorKeyName()); - if (comparatorSign != null) { - String[] parts = comparatorSign.split(":"); - String className = parts[0]; - String sign = parts[1]; - - String result = calcClassSign(className); - if (!result.equals(sign)) { - throw new IllegalStateException("Local class signature of " + className + " differs from used by this SortedSet!"); - } - - Class clazz = Class.forName(className); - comparator = (Comparator) clazz.newInstance(); - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - // TODO cache result - private static String calcClassSign(String name) { - try { - Class clazz = Class.forName(name); - - ByteArrayOutputStream result = new ByteArrayOutputStream(); - ObjectOutputStream outputStream = new ObjectOutputStream(result); - outputStream.writeObject(clazz); - outputStream.close(); - - MessageDigest crypt = MessageDigest.getInstance("SHA-1"); - crypt.reset(); - crypt.update(result.toByteArray()); - - return new BigInteger(1, crypt.digest()).toString(16); - } catch (Exception e) { - throw new IllegalStateException("Can't calculate sign of " + name, e); - } - } - - @Override - public int size() { - return commandExecutor.read(getName(), codec, RedisCommands.LLEN_INT, getName()); - } - - private int size(RedisConnection connection) { - return connection.sync(RedisCommands.LLEN_INT, getName()).intValue(); - } - - @Override - public boolean isEmpty() { - return size() == 0; - } - - @Override - public boolean contains(final Object o) { - return commandExecutor.read(getName(), codec, new SyncOperation() { - @Override - public Boolean execute(Codec codec, RedisConnection conn) { - return binarySearch((V)o, codec, conn).getIndex() >= 0; - } - }); - } - - public Iterator iterator() { - final int ind = 0; - return new Iterator() { - - private int currentIndex = ind - 1; - private boolean removeExecuted; - - @Override - public boolean hasNext() { - int size = size(); - return currentIndex+1 < size && size > 0; - } - - @Override - public V next() { - if (!hasNext()) { - throw new NoSuchElementException("No such element at index " + currentIndex); - } - currentIndex++; - removeExecuted = false; - return RedissonSortedSet.this.get(currentIndex); - } - - @Override - public void remove() { - if (removeExecuted) { - throw new IllegalStateException("Element been already deleted"); - } - RedissonSortedSet.this.remove(currentIndex); - currentIndex--; - removeExecuted = true; - } - - }; -// Double startScore; -// RedisConnection connection = connectionManager.connectionReadOp(); -// try { -// startScore = getScoreAtIndex(0, connection); -// } finally { -// connectionManager.releaseRead(connection); -// } -// if (startScore == null) { -// return new Iterator() { -// @Override -// public boolean hasNext() { -// return false; -// } -// -// @Override -// public V next() { -// throw new NoSuchElementException(); -// } -// -// @Override -// public void remove() { -// } -// }; -// } -// -// return iterator(startScore, Double.MAX_VALUE); - } - - private void remove(final int index) { - commandExecutor.write(getName(), codec, new SyncOperation() { - @Override - public V execute(Codec codec, RedisConnection conn) { - if (index == 0) { - return conn.sync(codec, RedisCommands.LPOP, getName()); - } - while (true) { - conn.sync(RedisCommands.WATCH, getName()); - List tail = conn.sync(codec, RedisCommands.LRANGE, getName(), index + 1, size()); - conn.sync(RedisCommands.MULTI); - conn.sync(codec, RedisCommands.LTRIM, getName(), 0, index - 1); - if (tail.isEmpty()) { - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 1) { - return null; - } - } else { - tail.add(0, getName()); - conn.sync(codec, RedisCommands.RPUSH, tail.toArray()); - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 2) { - return null; - } - } - } - } - }); - } - - private V get(final int index) { - return commandExecutor.read(getName(), codec, RedisCommands.LINDEX, getName(), index); - } - - @Override - public Object[] toArray() { - List res = commandExecutor.read(getName(), codec, RedisCommands.LRANGE, getName(), 0, -1); - return res.toArray(); - } - - @Override - public T[] toArray(T[] a) { - List res = commandExecutor.read(getName(), codec, RedisCommands.LRANGE, getName(), 0, -1); - return res.toArray(a); - } - - private String getCurrentVersionKey() { - return "redisson__sortedset__version__{" + getName() + "}"; - } - - private Long getCurrentVersion(Codec codec, RedisConnection simpleConnection) { - return simpleConnection.sync(LongCodec.INSTANCE, RedisCommands.GET, getCurrentVersionKey()); - } - - @Override - public boolean add(final V value) { - return commandExecutor.write(getName(), codec, new SyncOperation() { - @Override - public Boolean execute(Codec codec, RedisConnection conn) { - return add(value, codec, conn); - } - }); - } - - public Future addAsync(final V value) { - final Promise promise = new DefaultPromise(){}; - GlobalEventExecutor.INSTANCE.execute(new Runnable() { - @Override - public void run() { - try { - boolean res = add(value); - promise.setSuccess(res); - } catch (Exception e) { - promise.setFailure(e); - } - } - }); - return promise; - } - - boolean add(V value, Codec codec, RedisConnection connection) { - while (true) { - connection.sync(RedisCommands.WATCH, getName(), getComparatorKeyName()); - - checkComparator(connection); - - Long version = getCurrentVersion(codec, connection); - BinarySearchResult res = binarySearch(value, codec, connection); - if (res.getIndex() < 0) { -// System.out.println("index: " + res.getIndex() + " value: " + value); - if (!version.equals(getCurrentVersion(codec, connection))) { - connection.sync(RedisCommands.UNWATCH); - continue; - } -// NewScore newScore = calcNewScore(res.getIndex(), connection); -// if (!version.equals(getCurrentVersion(simpleConnection))) { -// connection.unwatch(); -// continue; -// } -// -// String leftScoreKey = getScoreKeyName(newScore.getLeftScore()); -// String rightScoreKey = getScoreKeyName(newScore.getRightScore()); -// -// if (simpleConnection.setnx(leftScoreKey, 1)) { -// if (!version.equals(getCurrentVersion(simpleConnection))) { -// connection.unwatch(); -// -// connection.del(leftScoreKey); -// continue; -// } -// if (rightScoreKey != null) { -// -// if (!simpleConnection.setnx(rightScoreKey, 1)) { -// connection.unwatch(); -// -// connection.del(leftScoreKey); -// continue; -// } -// } -// } else { -// connection.unwatch(); -// continue; -// } - - V pivot = null; - boolean before = false; - int index = -(res.getIndex() + 1); - - if (index < size()) { - before = true; - pivot = connection.sync(codec, RedisCommands.LINDEX, getName(), index); - } - - connection.sync(RedisCommands.MULTI); - if (index >= size()) { - connection.sync(codec, RedisCommands.RPUSH, getName(), value); - } else { - connection.sync(codec, RedisCommands.LINSERT, getName(), before ? "BEFORE" : "AFTER", pivot, value); - } -// System.out.println("adding: " + newScore.getScore() + " " + value); -// connection.zadd(getName(), newScore.getScore(), value); -// if (rightScoreKey != null) { -// connection.del(leftScoreKey, rightScoreKey); -// } else { -// connection.del(leftScoreKey); -// } - connection.sync(RedisCommands.INCR, getCurrentVersionKey()); - List re = connection.sync(codec, RedisCommands.EXEC); - if (re.size() == 2) { -// System.out.println("index: " + index + " value: " + value + " pivot: " + pivot); - return true; -// Number val = (Number) re.get(0); -// Long delCount = (Long) re.get(1); -// if (rightScoreKey != null) { -// if (delCount != 2) { -// throw new IllegalStateException(); -// } -// } else { -// if (delCount != 1) { -// throw new IllegalStateException(); -// } -// } -// return val != null && val.intValue() > 0; - } - } else { - connection.sync(RedisCommands.UNWATCH); - return false; - } - } - } - - private void checkComparator(RedisConnection connection) { - String comparatorSign = connection.sync(StringCodec.INSTANCE, RedisCommands.GET, getComparatorKeyName()); - if (comparatorSign != null) { - String[] vals = comparatorSign.split(":"); - String className = vals[0]; - if (!comparator.getClass().getName().equals(className)) { -// try { - loadComparator(connection); -// } finally { -// connection.sync(RedisCommands.UNWATCH); -// } - } - } - } - - public static double calcIncrement(double value) { - BigDecimal b = BigDecimal.valueOf(value); - BigDecimal r = b.remainder(BigDecimal.ONE); - if (r.compareTo(BigDecimal.ZERO) == 0) { - return 1; - } - double res = 1/Math.pow(10, r.scale()); - return res; - } - - @Override - public Future removeAsync(final V value) { - EventLoopGroup group = commandExecutor.getConnectionManager().getGroup(); - final Promise promise = group.next().newPromise(); - - group.execute(new Runnable() { - @Override - public void run() { - try { - boolean result = remove(value); - promise.setSuccess(result); - } catch (Exception e) { - promise.setFailure(e); - } - } - }); - - return promise; - } - - @Override - public boolean remove(final Object value) { - return commandExecutor.write(getName(), codec, new SyncOperation() { - @Override - public Boolean execute(Codec codec, RedisConnection conn) { - return remove(value, codec, conn); - } - }); - } - - boolean remove(Object value, Codec codec, RedisConnection conn) { - while (true) { - conn.sync(RedisCommands.WATCH, getName()); - BinarySearchResult res = binarySearch((V) value, codec, conn); - if (res.getIndex() < 0) { - conn.sync(RedisCommands.UNWATCH); - return false; - } - - if (res.getIndex() == 0) { - conn.sync(RedisCommands.MULTI); - conn.sync(codec, RedisCommands.LPOP, getName()); - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 1) { - return true; - } - } - - List tail = conn.sync(codec, RedisCommands.LRANGE, getName(), res.getIndex() + 1, size()); - conn.sync(RedisCommands.MULTI); - conn.sync(RedisCommands.LTRIM, getName(), 0, res.getIndex() - 1); - if (tail.isEmpty()) { - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 1) { - return true; - } - } else { - tail.add(0, getName()); - conn.sync(codec, RedisCommands.RPUSH, tail.toArray()); - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 2) { - return true; - } - } - } - } - - @Override - public boolean containsAll(Collection c) { - for (Object object : c) { - if (!contains(object)) { - return false; - } - } - return true; - } - - @Override - public boolean addAll(Collection c) { - boolean changed = false; - for (V v : c) { - if (add(v)) { - changed = true; - } - } - return changed; - } - - @Override - public boolean retainAll(Collection c) { - boolean changed = false; - for (Iterator iterator = iterator(); iterator.hasNext();) { - Object object = (Object) iterator.next(); - if (!c.contains(object)) { - iterator.remove(); - changed = true; - } - } - return changed; - } - - @Override - public boolean removeAll(Collection c) { - boolean changed = false; - for (Object obj : c) { - if (remove(obj)) { - changed = true; - } - } - return changed; - } - - @Override - public void clear() { - delete(); - } - - @Override - public Comparator comparator() { - return comparator; - } - - @Override - public SortedSet subSet(V fromElement, V toElement) { - throw new UnsupportedOperationException(); -// return new RedissonSubSortedSet(this, connectionManager, fromElement, toElement); - } - - @Override - public SortedSet headSet(V toElement) { - return subSet(null, toElement); - } - - @Override - public SortedSet tailSet(V fromElement) { - return subSet(fromElement, null); - } - - @Override - public V first() { - V res = commandExecutor.read(getName(), codec, RedisCommands.LINDEX, getName(), 0); - if (res == null) { - throw new NoSuchElementException(); - } - return res; - } - - @Override - public V last() { - V res = commandExecutor.read(getName(), codec, RedisCommands.LINDEX, getName(), -1); - if (res == null) { - throw new NoSuchElementException(); - } - return res; - } - - private String getScoreKeyName(int index) { - return "redisson__sortedset__score__" + getName() + "__" + index; - } - - private String getComparatorKeyName() { - return "redisson__sortedset__comparator__{" + getName() + "}"; - } - - @Override - public boolean trySetComparator(Comparator comparator) { - String className = comparator.getClass().getName(); - final String comparatorSign = className + ":" + calcClassSign(className); - - Boolean res = commandExecutor.evalWrite(getName(), StringCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, - "if redis.call('llen', KEYS[1]) == 0 then " - + "redis.call('set', KEYS[2], ARGV[1]); " - + "return 1; " - + "else " - + "return 0; " - + "end", - Arrays.asList(getName(), getComparatorKeyName()), comparatorSign); - if (res) { - this.comparator = comparator; - } - return res; - } - - private V getAtIndex(Codec codec, int index, RedisConnection connection) { - return connection.sync(codec, RedisCommands.LINDEX, getName(), index); - } - - /** - * Binary search algorithm - * - * @param value - * @param connection - * @param lowerIndex - * @param upperIndex - * @return - */ - private BinarySearchResult binarySearch(V value, Codec codec, RedisConnection connection, int lowerIndex, int upperIndex) { - while (lowerIndex <= upperIndex) { - int index = lowerIndex + (upperIndex - lowerIndex) / 2; - - V res = getAtIndex(codec, index, connection); - int cmp = comparator.compare(value, res); - - if (cmp == 0) { - BinarySearchResult indexRes = new BinarySearchResult(); - indexRes.setIndex(index); - return indexRes; - } else if (cmp < 0) { - upperIndex = index - 1; - } else { - lowerIndex = index + 1; - } - } - - BinarySearchResult indexRes = new BinarySearchResult(); - indexRes.setIndex(-(lowerIndex + 1)); - return indexRes; - } - - public BinarySearchResult binarySearch(V value, Codec codec, RedisConnection connection) { - int upperIndex = size(connection) - 1; - return binarySearch(value, codec, connection, 0, upperIndex); - } - - double score(V value, RedisConnection connection, int indexDiff, boolean tail) { - return -1; -// BinarySearchResult res = binarySearch(value, connection); -// if (res.getIndex() < 0) { -// V element = getAtIndex(-res.getIndex() + indexDiff, connection); -// if (element.getScore() == null && res.getScore() == null && tail) { -// element = getAtIndex(-res.getIndex() - 2, connection); -// return element.getScore(); -// } -// return element.getScore(); -// } -// int ind = res.getIndex(); -// if (tail) { -// ind = res.getIndex() - indexDiff; -// } -// BinarySearchResult element = getAtIndex(ind, connection); -// return element.getScore(); - } - - public String toString() { - Iterator it = iterator(); - if (! it.hasNext()) - return "[]"; - - StringBuilder sb = new StringBuilder(); - sb.append('['); - for (;;) { - V e = it.next(); - sb.append(e == this ? "(this Collection)" : e); - if (! it.hasNext()) - return sb.append(']').toString(); - sb.append(',').append(' '); - } - } - -} diff --git a/All/Genesis-NP/Genesis#471/old/RedissonSortedSet.java b/All/Genesis-NP/Genesis#471/old/RedissonSortedSet.java deleted file mode 100755 index 247d15c..0000000 --- a/All/Genesis-NP/Genesis#471/old/RedissonSortedSet.java +++ /dev/null @@ -1,707 +0,0 @@ -/** - * Copyright 2014 Nikita Koksharov, Nickolay Borbit - * - * 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.redisson; - -import java.io.ByteArrayOutputStream; -import java.io.ObjectOutputStream; -import java.io.Serializable; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.SortedSet; -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - -import org.redisson.client.RedisConnection; -import org.redisson.client.codec.Codec; -import org.redisson.client.codec.LongCodec; -import org.redisson.client.codec.StringCodec; -import org.redisson.client.protocol.RedisCommands; -import org.redisson.command.CommandExecutor; -import org.redisson.connection.ConnectionManager; -import org.redisson.core.RSortedSet; - -import io.netty.channel.EventLoop; -import io.netty.channel.EventLoopGroup; -import io.netty.util.concurrent.DefaultPromise; -import io.netty.util.concurrent.Future; -import io.netty.util.concurrent.GlobalEventExecutor; -import io.netty.util.concurrent.Promise; - -/** - * - * @author Nikita Koksharov - * - * @param - */ -public class RedissonSortedSet extends RedissonObject implements RSortedSet { - - private static class NaturalComparator implements Comparator, Serializable { - - private static final long serialVersionUID = 7207038068494060240L; - - static final NaturalComparator NATURAL_ORDER = new NaturalComparator(); - - public int compare(V c1, V c2) { - Comparable c1co = (Comparable) c1; - Comparable c2co = (Comparable) c2; - return c1co.compareTo(c2co); - } - - } - - public static class BinarySearchResult { - - private V value; - private int index; - - public BinarySearchResult(V value) { - super(); - this.value = value; - } - - public BinarySearchResult() { - } - - public void setIndex(int index) { - this.index = index; - } - public int getIndex() { - return index; - } - - public V getValue() { - return value; - } - - - } - - private Comparator comparator = NaturalComparator.NATURAL_ORDER; - - CommandExecutor commandExecutor; - - protected RedissonSortedSet(CommandExecutor commandExecutor, String name) { - super(commandExecutor, name); - this.commandExecutor = commandExecutor; - - loadComparator(); - - commandExecutor.write(getName(), StringCodec.INSTANCE, RedisCommands.SETNX, getCurrentVersionKey(), 0L); - } - - public RedissonSortedSet(Codec codec, CommandExecutor commandExecutor, String name) { - super(codec, commandExecutor, name); - - loadComparator(); - - commandExecutor.write(getName(), StringCodec.INSTANCE, RedisCommands.SETNX, getCurrentVersionKey(), 0L); - } - - private void loadComparator() { - commandExecutor.read(getName(), codec, new SyncOperation() { - @Override - public Void execute(Codec codec, RedisConnection conn) { - loadComparator(conn); - return null; - } - }); - } - - private void loadComparator(RedisConnection connection) { - try { - String comparatorSign = connection.sync(StringCodec.INSTANCE, RedisCommands.GET, getComparatorKeyName()); - if (comparatorSign != null) { - String[] parts = comparatorSign.split(":"); - String className = parts[0]; - String sign = parts[1]; - - String result = calcClassSign(className); - if (!result.equals(sign)) { - throw new IllegalStateException("Local class signature of " + className + " differs from used by this SortedSet!"); - } - - Class clazz = Class.forName(className); - comparator = (Comparator) clazz.newInstance(); - } - } catch (Exception e) { - throw new IllegalStateException(e); - } - } - - // TODO cache result - private static String calcClassSign(String name) { - try { - Class clazz = Class.forName(name); - - ByteArrayOutputStream result = new ByteArrayOutputStream(); - ObjectOutputStream outputStream = new ObjectOutputStream(result); - outputStream.writeObject(clazz); - outputStream.close(); - - MessageDigest crypt = MessageDigest.getInstance("SHA-1"); - crypt.reset(); - crypt.update(result.toByteArray()); - - return new BigInteger(1, crypt.digest()).toString(16); - } catch (Exception e) { - throw new IllegalStateException("Can't calculate sign of " + name, e); - } - } - - @Override - public int size() { - return commandExecutor.read(getName(), codec, RedisCommands.LLEN_INT, getName()); - } - - private int size(RedisConnection connection) { - return connection.sync(RedisCommands.LLEN_INT, getName()).intValue(); - } - - @Override - public boolean isEmpty() { - return size() == 0; - } - - @Override - public boolean contains(final Object o) { - return commandExecutor.read(getName(), codec, new SyncOperation() { - @Override - public Boolean execute(Codec codec, RedisConnection conn) { - return binarySearch((V)o, codec, conn).getIndex() >= 0; - } - }); - } - - public Iterator iterator() { - final int ind = 0; - return new Iterator() { - - private int currentIndex = ind - 1; - private boolean removeExecuted; - - @Override - public boolean hasNext() { - int size = size(); - return currentIndex+1 < size && size > 0; - } - - @Override - public V next() { - if (!hasNext()) { - throw new NoSuchElementException("No such element at index " + currentIndex); - } - currentIndex++; - removeExecuted = false; - return RedissonSortedSet.this.get(currentIndex); - } - - @Override - public void remove() { - if (removeExecuted) { - throw new IllegalStateException("Element been already deleted"); - } - RedissonSortedSet.this.remove(currentIndex); - currentIndex--; - removeExecuted = true; - } - - }; -// Double startScore; -// RedisConnection connection = connectionManager.connectionReadOp(); -// try { -// startScore = getScoreAtIndex(0, connection); -// } finally { -// connectionManager.releaseRead(connection); -// } -// if (startScore == null) { -// return new Iterator() { -// @Override -// public boolean hasNext() { -// return false; -// } -// -// @Override -// public V next() { -// throw new NoSuchElementException(); -// } -// -// @Override -// public void remove() { -// } -// }; -// } -// -// return iterator(startScore, Double.MAX_VALUE); - } - - private void remove(final int index) { - commandExecutor.write(getName(), codec, new SyncOperation() { - @Override - public V execute(Codec codec, RedisConnection conn) { - if (index == 0) { - return conn.sync(codec, RedisCommands.LPOP, getName()); - } - while (true) { - conn.sync(RedisCommands.WATCH, getName()); - List tail = conn.sync(codec, RedisCommands.LRANGE, getName(), index + 1, size()); - conn.sync(RedisCommands.MULTI); - conn.sync(codec, RedisCommands.LTRIM, getName(), 0, index - 1); - if (tail.isEmpty()) { - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 1) { - return null; - } - } else { - tail.add(0, getName()); - conn.sync(codec, RedisCommands.RPUSH, tail.toArray()); - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 2) { - return null; - } - } - } - } - }); - } - - private V get(final int index) { - return commandExecutor.read(getName(), codec, RedisCommands.LINDEX, getName(), index); - } - - @Override - public Object[] toArray() { - List res = commandExecutor.read(getName(), codec, RedisCommands.LRANGE, getName(), 0, -1); - return res.toArray(); - } - - @Override - public T[] toArray(T[] a) { - List res = commandExecutor.read(getName(), codec, RedisCommands.LRANGE, getName(), 0, -1); - return res.toArray(a); - } - - private String getCurrentVersionKey() { - return "redisson__sortedset__version__{" + getName() + "}"; - } - - private Long getCurrentVersion(Codec codec, RedisConnection simpleConnection) { - return simpleConnection.sync(LongCodec.INSTANCE, RedisCommands.GET, getCurrentVersionKey()); - } - - @Override - public boolean add(final V value) { - return commandExecutor.write(getName(), codec, new SyncOperation() { - @Override - public Boolean execute(Codec codec, RedisConnection conn) { - return add(value, codec, conn); - } - }); - } - - public Future addAsync(final V value) { - final Promise promise = new DefaultPromise(){}; - GlobalEventExecutor.INSTANCE.execute(new Runnable() { - @Override - public void run() { - try { - boolean res = add(value); - promise.setSuccess(res); - } catch (Exception e) { - promise.setFailure(e); - } - } - }); - return promise; - } - - boolean add(V value, Codec codec, RedisConnection connection) { - while (true) { - connection.sync(RedisCommands.WATCH, getName(), getComparatorKeyName()); - - checkComparator(connection); - - Long version = getCurrentVersion(codec, connection); - BinarySearchResult res = binarySearch(value, codec, connection); - if (res.getIndex() < 0) { -// System.out.println("index: " + res.getIndex() + " value: " + value); - if (!version.equals(getCurrentVersion(codec, connection))) { - connection.sync(RedisCommands.UNWATCH); - continue; - } -// NewScore newScore = calcNewScore(res.getIndex(), connection); -// if (!version.equals(getCurrentVersion(simpleConnection))) { -// connection.unwatch(); -// continue; -// } -// -// String leftScoreKey = getScoreKeyName(newScore.getLeftScore()); -// String rightScoreKey = getScoreKeyName(newScore.getRightScore()); -// -// if (simpleConnection.setnx(leftScoreKey, 1)) { -// if (!version.equals(getCurrentVersion(simpleConnection))) { -// connection.unwatch(); -// -// connection.del(leftScoreKey); -// continue; -// } -// if (rightScoreKey != null) { -// -// if (!simpleConnection.setnx(rightScoreKey, 1)) { -// connection.unwatch(); -// -// connection.del(leftScoreKey); -// continue; -// } -// } -// } else { -// connection.unwatch(); -// continue; -// } - - V pivot = null; - boolean before = false; - int index = -(res.getIndex() + 1); - - if (index < size()) { - before = true; - pivot = connection.sync(codec, RedisCommands.LINDEX, getName(), index); - } - - connection.sync(RedisCommands.MULTI); - if (index >= size()) { - connection.sync(codec, RedisCommands.RPUSH, getName(), value); - } else { - connection.sync(codec, RedisCommands.LINSERT, getName(), before ? "BEFORE" : "AFTER", pivot, value); - } -// System.out.println("adding: " + newScore.getScore() + " " + value); -// connection.zadd(getName(), newScore.getScore(), value); -// if (rightScoreKey != null) { -// connection.del(leftScoreKey, rightScoreKey); -// } else { -// connection.del(leftScoreKey); -// } - connection.sync(RedisCommands.INCR, getCurrentVersionKey()); - List re = connection.sync(codec, RedisCommands.EXEC); - if (re.size() == 2) { -// System.out.println("index: " + index + " value: " + value + " pivot: " + pivot); - return true; -// Number val = (Number) re.get(0); -// Long delCount = (Long) re.get(1); -// if (rightScoreKey != null) { -// if (delCount != 2) { -// throw new IllegalStateException(); -// } -// } else { -// if (delCount != 1) { -// throw new IllegalStateException(); -// } -// } -// return val != null && val.intValue() > 0; - } - } else { - connection.sync(RedisCommands.UNWATCH); - return false; - } - } - } - - private void checkComparator(RedisConnection connection) { - String comparatorSign = connection.sync(StringCodec.INSTANCE, RedisCommands.GET, getComparatorKeyName()); - if (comparatorSign != null) { - String[] vals = comparatorSign.split(":"); - String className = vals[0]; - if (!comparator.getClass().getName().equals(className)) { -// try { - loadComparator(connection); -// } finally { -// connection.sync(RedisCommands.UNWATCH); -// } - } - } - } - - public static double calcIncrement(double value) { - BigDecimal b = BigDecimal.valueOf(value); - BigDecimal r = b.remainder(BigDecimal.ONE); - if (r.compareTo(BigDecimal.ZERO) == 0) { - return 1; - } - double res = 1/Math.pow(10, r.scale()); - return res; - } - - @Override - public Future removeAsync(final V value) { - EventLoopGroup group = commandExecutor.getConnectionManager().getGroup(); - final Promise promise = group.next().newPromise(); - - group.execute(new Runnable() { - @Override - public void run() { - try { - boolean result = remove(value); - promise.setSuccess(result); - } catch (Exception e) { - promise.setFailure(e); - } - } - }); - - return promise; - } - - @Override - public boolean remove(final Object value) { - return commandExecutor.write(getName(), codec, new SyncOperation() { - @Override - public Boolean execute(Codec codec, RedisConnection conn) { - return remove(value, codec, conn); - } - }); - } - - boolean remove(Object value, Codec codec, RedisConnection conn) { - while (true) { - conn.sync(RedisCommands.WATCH, getName()); - BinarySearchResult res = binarySearch((V) value, codec, conn); - if (res.getIndex() < 0) { - conn.sync(RedisCommands.UNWATCH); - return false; - } - - if (res.getIndex() == 0) { - conn.sync(RedisCommands.MULTI); - conn.sync(codec, RedisCommands.LPOP, getName()); - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 1) { - return true; - } - } - - List tail = conn.sync(codec, RedisCommands.LRANGE, getName(), res.getIndex() + 1, size()); - conn.sync(RedisCommands.MULTI); - conn.sync(RedisCommands.LTRIM, getName(), 0, res.getIndex() - 1); - if (tail.isEmpty()) { - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 1) { - return true; - } - } else { - tail.add(0, getName()); - conn.sync(codec, RedisCommands.RPUSH, tail.toArray()); - if (((List)conn.sync(codec, RedisCommands.EXEC)).size() == 2) { - return true; - } - } - } - } - - @Override - public boolean containsAll(Collection c) { - for (Object object : c) { - if (!contains(object)) { - return false; - } - } - return true; - } - - @Override - public boolean addAll(Collection c) { - boolean changed = false; - for (V v : c) { - if (add(v)) { - changed = true; - } - } - return changed; - } - - @Override - public boolean retainAll(Collection c) { - boolean changed = false; - for (Iterator iterator = iterator(); iterator.hasNext();) { - Object object = (Object) iterator.next(); - if (!c.contains(object)) { - iterator.remove(); - changed = true; - } - } - return changed; - } - - @Override - public boolean removeAll(Collection c) { - boolean changed = false; - for (Object obj : c) { - if (remove(obj)) { - changed = true; - } - } - return changed; - } - - @Override - public void clear() { - delete(); - } - - @Override - public Comparator comparator() { - return comparator; - } - - @Override - public SortedSet subSet(V fromElement, V toElement) { - throw new UnsupportedOperationException(); -// return new RedissonSubSortedSet(this, connectionManager, fromElement, toElement); - } - - @Override - public SortedSet headSet(V toElement) { - return subSet(null, toElement); - } - - @Override - public SortedSet tailSet(V fromElement) { - return subSet(fromElement, null); - } - - @Override - public V first() { - V res = commandExecutor.read(getName(), codec, RedisCommands.LINDEX, getName(), 0); - if (res == null) { - throw new NoSuchElementException(); - } - return res; - } - - @Override - public V last() { - V res = commandExecutor.read(getName(), codec, RedisCommands.LINDEX, getName(), -1); - if (res == null) { - throw new NoSuchElementException(); - } - return res; - } - - private String getScoreKeyName(int index) { - return "redisson__sortedset__score__" + getName() + "__" + index; - } - - private String getComparatorKeyName() { - return "redisson__sortedset__comparator__{" + getName() + "}"; - } - - @Override - public boolean trySetComparator(Comparator comparator) { - String className = comparator.getClass().getName(); - final String comparatorSign = className + ":" + calcClassSign(className); - - Boolean res = commandExecutor.evalWrite(getName(), StringCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN, - "if redis.call('llen', KEYS[1]) == 0 then " - + "redis.call('set', KEYS[2], ARGV[1]); " - + "return 1; " - + "else " - + "return 0; " - + "end", - Arrays.asList(getName(), getComparatorKeyName()), comparatorSign); - if (res) { - this.comparator = comparator; - } - return res; - } - - private V getAtIndex(Codec codec, int index, RedisConnection connection) { - return connection.sync(codec, RedisCommands.LINDEX, getName(), index); - } - - /** - * Binary search algorithm - * - * @param value - * @param connection - * @param lowerIndex - * @param upperIndex - * @return - */ - private BinarySearchResult binarySearch(V value, Codec codec, RedisConnection connection, int lowerIndex, int upperIndex) { - while (lowerIndex <= upperIndex) { - int index = lowerIndex + (upperIndex - lowerIndex) / 2; - - V res = getAtIndex(codec, index, connection); - int cmp = comparator.compare(value, res); - - if (cmp == 0) { - BinarySearchResult indexRes = new BinarySearchResult(); - indexRes.setIndex(index); - return indexRes; - } else if (cmp < 0) { - upperIndex = index - 1; - } else { - lowerIndex = index + 1; - } - } - - BinarySearchResult indexRes = new BinarySearchResult(); - indexRes.setIndex(-(lowerIndex + 1)); - return indexRes; - } - - public BinarySearchResult binarySearch(V value, Codec codec, RedisConnection connection) { - int upperIndex = size(connection) - 1; - return binarySearch(value, codec, connection, 0, upperIndex); - } - - double score(V value, RedisConnection connection, int indexDiff, boolean tail) { - return -1; -// BinarySearchResult res = binarySearch(value, connection); -// if (res.getIndex() < 0) { -// V element = getAtIndex(-res.getIndex() + indexDiff, connection); -// if (element.getScore() == null && res.getScore() == null && tail) { -// element = getAtIndex(-res.getIndex() - 2, connection); -// return element.getScore(); -// } -// return element.getScore(); -// } -// int ind = res.getIndex(); -// if (tail) { -// ind = res.getIndex() - indexDiff; -// } -// BinarySearchResult element = getAtIndex(ind, connection); -// return element.getScore(); - } - - public String toString() { - Iterator it = iterator(); - if (! it.hasNext()) - return "[]"; - - StringBuilder sb = new StringBuilder(); - sb.append('['); - for (;;) { - V e = it.next(); - sb.append(e == this ? "(this Collection)" : e); - if (! it.hasNext()) - return sb.append(']').toString(); - sb.append(',').append(' '); - } - } - -} diff --git a/All/Genesis-NP/Genesis#471/pair.info b/All/Genesis-NP/Genesis#471/pair.info deleted file mode 100755 index 96145be..0000000 --- a/All/Genesis-NP/Genesis#471/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:471 -SATName:Genesis -modifiedFPath:src/main/java/org/redisson/RedissonSortedSet.java -comSha:365d1fe63b19d3edecc5131bfa9f2464facd9f0b -parentComSha:365d1fe63b19d3edecc5131bfa9f2464facd9f0b^1 -githubUrl:https://github.com/mrniko/redisson -repoName:mrniko#redisson \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#474/comMsg.txt b/All/Genesis-NP/Genesis#474/comMsg.txt deleted file mode 100755 index fb98923..0000000 --- a/All/Genesis-NP/Genesis#474/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -poll npe fixed. #181 diff --git a/All/Genesis-NP/Genesis#474/diff.diff b/All/Genesis-NP/Genesis#474/diff.diff deleted file mode 100755 index 23794f2..0000000 --- a/All/Genesis-NP/Genesis#474/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/src/main/java/org/redisson/RedissonBlockingQueue.java b/src/main/java/org/redisson/RedissonBlockingQueue.java -index 24843ba..a784e7a 100644 ---- a/src/main/java/org/redisson/RedissonBlockingQueue.java -+++ b/src/main/java/org/redisson/RedissonBlockingQueue.java -@@ -30,0 +31 @@ import org.redisson.core.RBlockingQueue; -+import com.lambdaworks.redis.KeyValue; -@@ -74 +75,5 @@ public class RedissonBlockingQueue extends RedissonQueue implements RBlock -- return conn.blpop(unit.toSeconds(timeout), getName()).value; -+ KeyValue val = conn.blpop(unit.toSeconds(timeout), getName()); -+ if (val != null) { -+ return val.value; -+ } -+ return null; diff --git a/All/Genesis-NP/Genesis#474/new/RedissonBlockingQueue.java b/All/Genesis-NP/Genesis#474/new/RedissonBlockingQueue.java deleted file mode 100755 index a784e7a..0000000 --- a/All/Genesis-NP/Genesis#474/new/RedissonBlockingQueue.java +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Copyright 2014 Nikita Koksharov, Nickolay Borbit - * - * 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.redisson; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - -import org.redisson.async.SyncInterruptedOperation; -import org.redisson.async.SyncOperation; -import org.redisson.connection.ConnectionManager; -import org.redisson.core.RBlockingQueue; - -import com.lambdaworks.redis.KeyValue; -import com.lambdaworks.redis.RedisConnection; -import org.redisson.core.RScript; - -/** - * Offers blocking queue facilities through an intermediary - * {@link LinkedBlockingQueue} where items are added as soon as - * blpop returns. All {@link BlockingQueue} methods are actually - * delegated to this intermediary queue. - * - * @author pdeschen@gmail.com - * @author Nikita Koksharov - */ -public class RedissonBlockingQueue extends RedissonQueue implements RBlockingQueue { - - protected RedissonBlockingQueue(ConnectionManager connection, String name) { - super(connection, name); - } - - @Override - public void put(V e) throws InterruptedException { - offer(e); - } - - @Override - public boolean offer(V e, long timeout, TimeUnit unit) throws InterruptedException { - return offer(e); - } - - @Override - public V take() throws InterruptedException { - return connectionManager.write(getName(), new SyncInterruptedOperation() { - @Override - public V execute(RedisConnection conn) throws InterruptedException { - return conn.blpop(0, getName()).value; - } - }); - } - - @Override - public V poll(final long timeout, final TimeUnit unit) throws InterruptedException { - return connectionManager.write(getName(), new SyncInterruptedOperation() { - @Override - public V execute(RedisConnection conn) throws InterruptedException { - KeyValue val = conn.blpop(unit.toSeconds(timeout), getName()); - if (val != null) { - return val.value; - } - return null; - } - }); - } - - @Override - public V pollLastAndOfferFirstTo(RBlockingQueue queue, long timeout, TimeUnit unit) - throws InterruptedException { - return pollLastAndOfferFirstTo(queue.getName(), timeout, unit); - } - - @Override - public V pollLastAndOfferFirstTo(final String queueName, final long timeout, final TimeUnit unit) throws InterruptedException { - return connectionManager.write(getName(), new SyncInterruptedOperation() { - @Override - public V execute(RedisConnection conn) throws InterruptedException { - return conn.brpoplpush(unit.toSeconds(timeout), getName(), queueName); - } - }); - } - - @Override - public int remainingCapacity() { - return Integer.MAX_VALUE; - } - - @Override - public int drainTo(Collection c) { - if (c == null) { - throw new NullPointerException(); - } - List list = new RedissonScript(connectionManager).eval( - "local vals = redis.call('lrange', KEYS[1], 0, -1); " + - "redis.call('ltrim', KEYS[1], -1, 0); " + - "return vals", - RScript.ReturnType.MAPVALUELIST, - Collections.singletonList(getName())); - c.addAll(list); - return list.size(); - } - - @Override - public int drainTo(Collection c, final int maxElements) { - if (maxElements <= 0) { - return 0; - } - if (c == null) { - throw new NullPointerException(); - } - - List list = new RedissonScript(connectionManager).evalR( - "local elemNum = math.min(ARGV[1], redis.call('llen', KEYS[1])) - 1;" + - "local vals = redis.call('lrange', KEYS[1], 0, elemNum); " + - "redis.call('ltrim', KEYS[1], elemNum + 1, -1); " + - "return vals", - RScript.ReturnType.MAPVALUELIST, - Collections.singletonList(getName()), Collections.emptyList(), Collections.singletonList(maxElements)); - c.addAll(list); - return list.size(); - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#474/old/RedissonBlockingQueue.java b/All/Genesis-NP/Genesis#474/old/RedissonBlockingQueue.java deleted file mode 100755 index 24843ba..0000000 --- a/All/Genesis-NP/Genesis#474/old/RedissonBlockingQueue.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Copyright 2014 Nikita Koksharov, Nickolay Borbit - * - * 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.redisson; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; - -import org.redisson.async.SyncInterruptedOperation; -import org.redisson.async.SyncOperation; -import org.redisson.connection.ConnectionManager; -import org.redisson.core.RBlockingQueue; - -import com.lambdaworks.redis.RedisConnection; -import org.redisson.core.RScript; - -/** - * Offers blocking queue facilities through an intermediary - * {@link LinkedBlockingQueue} where items are added as soon as - * blpop returns. All {@link BlockingQueue} methods are actually - * delegated to this intermediary queue. - * - * @author pdeschen@gmail.com - * @author Nikita Koksharov - */ -public class RedissonBlockingQueue extends RedissonQueue implements RBlockingQueue { - - protected RedissonBlockingQueue(ConnectionManager connection, String name) { - super(connection, name); - } - - @Override - public void put(V e) throws InterruptedException { - offer(e); - } - - @Override - public boolean offer(V e, long timeout, TimeUnit unit) throws InterruptedException { - return offer(e); - } - - @Override - public V take() throws InterruptedException { - return connectionManager.write(getName(), new SyncInterruptedOperation() { - @Override - public V execute(RedisConnection conn) throws InterruptedException { - return conn.blpop(0, getName()).value; - } - }); - } - - @Override - public V poll(final long timeout, final TimeUnit unit) throws InterruptedException { - return connectionManager.write(getName(), new SyncInterruptedOperation() { - @Override - public V execute(RedisConnection conn) throws InterruptedException { - return conn.blpop(unit.toSeconds(timeout), getName()).value; - } - }); - } - - @Override - public V pollLastAndOfferFirstTo(RBlockingQueue queue, long timeout, TimeUnit unit) - throws InterruptedException { - return pollLastAndOfferFirstTo(queue.getName(), timeout, unit); - } - - @Override - public V pollLastAndOfferFirstTo(final String queueName, final long timeout, final TimeUnit unit) throws InterruptedException { - return connectionManager.write(getName(), new SyncInterruptedOperation() { - @Override - public V execute(RedisConnection conn) throws InterruptedException { - return conn.brpoplpush(unit.toSeconds(timeout), getName(), queueName); - } - }); - } - - @Override - public int remainingCapacity() { - return Integer.MAX_VALUE; - } - - @Override - public int drainTo(Collection c) { - if (c == null) { - throw new NullPointerException(); - } - List list = new RedissonScript(connectionManager).eval( - "local vals = redis.call('lrange', KEYS[1], 0, -1); " + - "redis.call('ltrim', KEYS[1], -1, 0); " + - "return vals", - RScript.ReturnType.MAPVALUELIST, - Collections.singletonList(getName())); - c.addAll(list); - return list.size(); - } - - @Override - public int drainTo(Collection c, final int maxElements) { - if (maxElements <= 0) { - return 0; - } - if (c == null) { - throw new NullPointerException(); - } - - List list = new RedissonScript(connectionManager).evalR( - "local elemNum = math.min(ARGV[1], redis.call('llen', KEYS[1])) - 1;" + - "local vals = redis.call('lrange', KEYS[1], 0, elemNum); " + - "redis.call('ltrim', KEYS[1], elemNum + 1, -1); " + - "return vals", - RScript.ReturnType.MAPVALUELIST, - Collections.singletonList(getName()), Collections.emptyList(), Collections.singletonList(maxElements)); - c.addAll(list); - return list.size(); - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#474/pair.info b/All/Genesis-NP/Genesis#474/pair.info deleted file mode 100755 index d67cea9..0000000 --- a/All/Genesis-NP/Genesis#474/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:474 -SATName:Genesis -modifiedFPath:src/main/java/org/redisson/RedissonBlockingQueue.java -comSha:88206c2ab541760715a9f948c81102630184da46 -parentComSha:88206c2ab541760715a9f948c81102630184da46^1 -githubUrl:https://github.com/mrniko/redisson -repoName:mrniko#redisson \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#477/comMsg.txt b/All/Genesis-NP/Genesis#477/comMsg.txt deleted file mode 100755 index 866229d..0000000 --- a/All/Genesis-NP/Genesis#477/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NullPointerException raised in isUserDefinedField diff --git a/All/Genesis-NP/Genesis#477/diff.diff b/All/Genesis-NP/Genesis#477/diff.diff deleted file mode 100755 index a1ce7e2..0000000 --- a/All/Genesis-NP/Genesis#477/diff.diff +++ /dev/null @@ -1,14 +0,0 @@ -diff --git a/src/main/java/org/vafer/jdeb/debian/ControlFile.java b/src/main/java/org/vafer/jdeb/debian/ControlFile.java -index 2ab5db8..bf1a99d 100644 ---- a/src/main/java/org/vafer/jdeb/debian/ControlFile.java -+++ b/src/main/java/org/vafer/jdeb/debian/ControlFile.java -@@ -101,3 +101 @@ public abstract class ControlFile { -- if (!"".equals(field)) { -- -- if (isUserDefinedField(field)) { -+ if (field != null && isUserDefinedField(field)) { -@@ -114 +112 @@ public abstract class ControlFile { -- if (field != null) { -+ if (field != null && !"".equals(field)) { -@@ -118 +115,0 @@ public abstract class ControlFile { -- } diff --git a/All/Genesis-NP/Genesis#477/new/ControlFile.java b/All/Genesis-NP/Genesis#477/new/ControlFile.java deleted file mode 100755 index bf1a99d..0000000 --- a/All/Genesis-NP/Genesis#477/new/ControlFile.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * Copyright 2013 The jdeb developers. - * - * 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.vafer.jdeb.debian; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * A control file as specified by the Debian policy. - * - * @author Torsten Curdt - */ -public abstract class ControlFile { - - protected final Map values = new LinkedHashMap(); - protected final Map userDefinedFields = new LinkedHashMap(); - protected final Set userDefinedFieldNames = new HashSet(); - - public void parse(String input) throws IOException, ParseException { - parse(new ByteArrayInputStream(input.getBytes("UTF-8"))); - } - - public void parse(InputStream input) throws IOException, ParseException { - BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); - StringBuilder buffer = new StringBuilder(); - String field = null; - int linenr = 0; - while (true) { - final String line = reader.readLine(); - - if (line == null) { - // flush value of the previous field - set(field, buffer.toString()); - break; - } - - linenr++; - - if (line.length() == 0) { - throw new ParseException("Empty line", linenr); - } - - final char first = line.charAt(0); - if (Character.isLetter(first)) { - - // new field - - // flush value of the previous field - set(field, buffer.toString()); - buffer = new StringBuilder(); - - - final int i = line.indexOf(':'); - - if (i < 0) { - throw new ParseException("Line misses ':' delimiter", linenr); - } - - field = line.substring(0, i); - buffer.append(line.substring(i + 1).trim()); - - continue; - } - - // continuing old value, lines with only a dot are ignored - buffer.append('\n'); - if (!".".equals(line.substring(1).trim())) { - buffer.append(line.substring(1)); - } - } - reader.close(); - - } - - public void set(String field, final String value) { - if (field != null && isUserDefinedField(field)) { - userDefinedFields.put(field, value); - String fieldName = getUserDefinedFieldName(field); - - if (fieldName != null) { - userDefinedFieldNames.add(new ControlField(fieldName)); - } - - field = fieldName; - } - - if (field != null && !"".equals(field)) { - values.put(field, value); - } - } - - public String get(String field) { - return values.get(field); - } - - protected abstract ControlField[] getFields(); - - protected Map getUserDefinedFields() { - return userDefinedFields; - } - - protected Set getUserDefinedFieldNames() { - return userDefinedFieldNames; - } - - public List getMandatoryFields() { - List fields = new ArrayList(); - - for (ControlField field : getFields()) { - if (field.isMandatory()) { - fields.add(field.getName()); - } - } - - return fields; - } - - public boolean isValid() { - return invalidFields().size() == 0; - } - - public Set invalidFields() { - Set invalid = new HashSet(); - - for (ControlField field : getFields()) { - if (field.isMandatory() && get(field.getName()) == null) { - invalid.add(field.getName()); - } - } - - return invalid; - } - - public String toString(ControlField... fields) { - StringBuilder s = new StringBuilder(); - for (ControlField field : fields) { - String value = values.get(field.getName()); - s.append(field.format(value)); - } - return s.toString(); - } - - public String toString() { - List fields = new ArrayList(); - fields.addAll(Arrays.asList(getFields())); - fields.addAll(getUserDefinedFieldNames()); - return toString(fields.toArray(new ControlField[fields.size()])); - } - - /** - * Returns the letter expected in the prefix of a user defined field - * in order to include the field in this control file. - * - * @return The letter returned is: - *
    - *
  • B: for a binary package
  • - *
  • S: for a source package
  • - *
  • C: for a changes file
  • - *
- * - * @since 1.1 - * @see Debian Policy - User-defined fields - */ - protected abstract char getUserDefinedFieldLetter(); - - /** - * Tells if the specified field name is a user defined field. - * User-defined fields must begin with an 'X', followed by one or more - * letters that specify the output file and a hyphen. - * - * @param field the name of the field - * - * @since 1.1 - * @see Debian Policy - User-defined fields - */ - protected boolean isUserDefinedField(String field) { - return field.startsWith("X") && field.indexOf("-") > 0; - } - - /** - * Returns the user defined field without its prefix. - * - * @param field the name of the user defined field - * @return the user defined field without the prefix, or null if the fields - * doesn't apply to this control file. - * @since 1.1 - */ - protected String getUserDefinedFieldName(String field) { - int index = field.indexOf('-'); - char letter = getUserDefinedFieldLetter(); - - for (int i = 0; i < index; ++i) { - if (field.charAt(i) == letter) { - return field.substring(index + 1); - } - } - - return null; - } -} diff --git a/All/Genesis-NP/Genesis#477/old/ControlFile.java b/All/Genesis-NP/Genesis#477/old/ControlFile.java deleted file mode 100755 index 2ab5db8..0000000 --- a/All/Genesis-NP/Genesis#477/old/ControlFile.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright 2013 The jdeb developers. - * - * 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.vafer.jdeb.debian; - -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * A control file as specified by the Debian policy. - * - * @author Torsten Curdt - */ -public abstract class ControlFile { - - protected final Map values = new LinkedHashMap(); - protected final Map userDefinedFields = new LinkedHashMap(); - protected final Set userDefinedFieldNames = new HashSet(); - - public void parse(String input) throws IOException, ParseException { - parse(new ByteArrayInputStream(input.getBytes("UTF-8"))); - } - - public void parse(InputStream input) throws IOException, ParseException { - BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8")); - StringBuilder buffer = new StringBuilder(); - String field = null; - int linenr = 0; - while (true) { - final String line = reader.readLine(); - - if (line == null) { - // flush value of the previous field - set(field, buffer.toString()); - break; - } - - linenr++; - - if (line.length() == 0) { - throw new ParseException("Empty line", linenr); - } - - final char first = line.charAt(0); - if (Character.isLetter(first)) { - - // new field - - // flush value of the previous field - set(field, buffer.toString()); - buffer = new StringBuilder(); - - - final int i = line.indexOf(':'); - - if (i < 0) { - throw new ParseException("Line misses ':' delimiter", linenr); - } - - field = line.substring(0, i); - buffer.append(line.substring(i + 1).trim()); - - continue; - } - - // continuing old value, lines with only a dot are ignored - buffer.append('\n'); - if (!".".equals(line.substring(1).trim())) { - buffer.append(line.substring(1)); - } - } - reader.close(); - - } - - public void set(String field, final String value) { - if (!"".equals(field)) { - - if (isUserDefinedField(field)) { - userDefinedFields.put(field, value); - String fieldName = getUserDefinedFieldName(field); - - if (fieldName != null) { - userDefinedFieldNames.add(new ControlField(fieldName)); - } - - field = fieldName; - } - - if (field != null) { - values.put(field, value); - } - } - } - - public String get(String field) { - return values.get(field); - } - - protected abstract ControlField[] getFields(); - - protected Map getUserDefinedFields() { - return userDefinedFields; - } - - protected Set getUserDefinedFieldNames() { - return userDefinedFieldNames; - } - - public List getMandatoryFields() { - List fields = new ArrayList(); - - for (ControlField field : getFields()) { - if (field.isMandatory()) { - fields.add(field.getName()); - } - } - - return fields; - } - - public boolean isValid() { - return invalidFields().size() == 0; - } - - public Set invalidFields() { - Set invalid = new HashSet(); - - for (ControlField field : getFields()) { - if (field.isMandatory() && get(field.getName()) == null) { - invalid.add(field.getName()); - } - } - - return invalid; - } - - public String toString(ControlField... fields) { - StringBuilder s = new StringBuilder(); - for (ControlField field : fields) { - String value = values.get(field.getName()); - s.append(field.format(value)); - } - return s.toString(); - } - - public String toString() { - List fields = new ArrayList(); - fields.addAll(Arrays.asList(getFields())); - fields.addAll(getUserDefinedFieldNames()); - return toString(fields.toArray(new ControlField[fields.size()])); - } - - /** - * Returns the letter expected in the prefix of a user defined field - * in order to include the field in this control file. - * - * @return The letter returned is: - *
    - *
  • B: for a binary package
  • - *
  • S: for a source package
  • - *
  • C: for a changes file
  • - *
- * - * @since 1.1 - * @see Debian Policy - User-defined fields - */ - protected abstract char getUserDefinedFieldLetter(); - - /** - * Tells if the specified field name is a user defined field. - * User-defined fields must begin with an 'X', followed by one or more - * letters that specify the output file and a hyphen. - * - * @param field the name of the field - * - * @since 1.1 - * @see Debian Policy - User-defined fields - */ - protected boolean isUserDefinedField(String field) { - return field.startsWith("X") && field.indexOf("-") > 0; - } - - /** - * Returns the user defined field without its prefix. - * - * @param field the name of the user defined field - * @return the user defined field without the prefix, or null if the fields - * doesn't apply to this control file. - * @since 1.1 - */ - protected String getUserDefinedFieldName(String field) { - int index = field.indexOf('-'); - char letter = getUserDefinedFieldLetter(); - - for (int i = 0; i < index; ++i) { - if (field.charAt(i) == letter) { - return field.substring(index + 1); - } - } - - return null; - } -} diff --git a/All/Genesis-NP/Genesis#477/pair.info b/All/Genesis-NP/Genesis#477/pair.info deleted file mode 100755 index 8f53a2f..0000000 --- a/All/Genesis-NP/Genesis#477/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:477 -SATName:Genesis -modifiedFPath:src/main/java/org/vafer/jdeb/debian/ControlFile.java -comSha:0ca04f8294558cbe105699230a73980db93f810a -parentComSha:0ca04f8294558cbe105699230a73980db93f810a^1 -githubUrl:https://github.com/tcurdt/jdeb -repoName:tcurdt#jdeb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#479/comMsg.txt b/All/Genesis-NP/Genesis#479/comMsg.txt deleted file mode 100755 index ad93793..0000000 --- a/All/Genesis-NP/Genesis#479/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -#81, #83 - Fixed potential NullPointerExceptions in HalEmbeddedBuilder. diff --git a/All/Genesis-NP/Genesis#479/diff.diff b/All/Genesis-NP/Genesis#479/diff.diff deleted file mode 100755 index 116153f..0000000 --- a/All/Genesis-NP/Genesis#479/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/src/main/java/org/springframework/hateoas/hal/HalEmbeddedBuilder.java b/src/main/java/org/springframework/hateoas/hal/HalEmbeddedBuilder.java -index 8fea553..f540314 100644 ---- a/src/main/java/org/springframework/hateoas/hal/HalEmbeddedBuilder.java -+++ b/src/main/java/org/springframework/hateoas/hal/HalEmbeddedBuilder.java -@@ -24,0 +25 @@ import org.springframework.hateoas.RelProvider; -+import org.springframework.hateoas.Resource; -@@ -31,0 +33 @@ import org.springframework.hateoas.core.ObjectUtils; -+ * @author Dietrich Schulten -@@ -50 +52,2 @@ class HalEmbeddedBuilder { -- * Adds the given value to the embeddeds. -+ * Adds the given value to the embeddeds. Will skip doing so if the value is {@literal null} or the content of a -+ * {@link Resource} is {@literal null}. -@@ -56,0 +60,5 @@ class HalEmbeddedBuilder { -+ -+ if (type == null) { -+ return; -+ } -+ diff --git a/All/Genesis-NP/Genesis#479/new/HalEmbeddedBuilder.java b/All/Genesis-NP/Genesis#479/new/HalEmbeddedBuilder.java deleted file mode 100755 index f540314..0000000 --- a/All/Genesis-NP/Genesis#479/new/HalEmbeddedBuilder.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2013 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.hateoas.hal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.hateoas.RelProvider; -import org.springframework.hateoas.Resource; -import org.springframework.hateoas.core.ObjectUtils; - -/** - * Builder class that allows collecting objects under the relation types defined for the objects but moving from the - * single resource relation to the collection one, once more than one object of the same type is added. - * - * @author Oliver Gierke - * @author Dietrich Schulten - */ -class HalEmbeddedBuilder { - - private static final String DEFAULT_REL = "content"; - - private final Map> embeddeds = new HashMap>(); - private final RelProvider provider; - - /** - * Creates a new {@link HalEmbeddedBuilder} using the given {@link RelProvider}. - * - * @param provider can be {@literal null}. - */ - public HalEmbeddedBuilder(RelProvider provider) { - this.provider = provider; - } - - /** - * Adds the given value to the embeddeds. Will skip doing so if the value is {@literal null} or the content of a - * {@link Resource} is {@literal null}. - * - * @param value - */ - public void add(Object value) { - - Class type = ObjectUtils.getResourceType(value); - - if (type == null) { - return; - } - - String singleRel = getDefaultedRelFor(type, false); - List currentValue = embeddeds.get(singleRel); - - if (currentValue == null) { - ArrayList arrayList = new ArrayList(); - arrayList.add(value); - embeddeds.put(singleRel, arrayList); - } else if (currentValue.size() == 1) { - currentValue.add(value); - embeddeds.remove(singleRel); - embeddeds.put(getDefaultedRelFor(type, true), currentValue); - } else { - currentValue.add(value); - } - } - - private String getDefaultedRelFor(Class type, boolean forCollection) { - - if (provider == null) { - return DEFAULT_REL; - } - - String rel = forCollection ? provider.getCollectionResourceRelFor(type) : provider.getSingleResourceRelFor(type); - return rel == null ? DEFAULT_REL : rel; - } - - /** - * Returns the added objects keyed up by their relation types. - * - * @return - */ - public Map> asMap() { - return Collections.unmodifiableMap(embeddeds); - } -} diff --git a/All/Genesis-NP/Genesis#479/old/HalEmbeddedBuilder.java b/All/Genesis-NP/Genesis#479/old/HalEmbeddedBuilder.java deleted file mode 100755 index 8fea553..0000000 --- a/All/Genesis-NP/Genesis#479/old/HalEmbeddedBuilder.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2013 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.hateoas.hal; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.springframework.hateoas.RelProvider; -import org.springframework.hateoas.core.ObjectUtils; - -/** - * Builder class that allows collecting objects under the relation types defined for the objects but moving from the - * single resource relation to the collection one, once more than one object of the same type is added. - * - * @author Oliver Gierke - */ -class HalEmbeddedBuilder { - - private static final String DEFAULT_REL = "content"; - - private final Map> embeddeds = new HashMap>(); - private final RelProvider provider; - - /** - * Creates a new {@link HalEmbeddedBuilder} using the given {@link RelProvider}. - * - * @param provider can be {@literal null}. - */ - public HalEmbeddedBuilder(RelProvider provider) { - this.provider = provider; - } - - /** - * Adds the given value to the embeddeds. - * - * @param value - */ - public void add(Object value) { - - Class type = ObjectUtils.getResourceType(value); - String singleRel = getDefaultedRelFor(type, false); - List currentValue = embeddeds.get(singleRel); - - if (currentValue == null) { - ArrayList arrayList = new ArrayList(); - arrayList.add(value); - embeddeds.put(singleRel, arrayList); - } else if (currentValue.size() == 1) { - currentValue.add(value); - embeddeds.remove(singleRel); - embeddeds.put(getDefaultedRelFor(type, true), currentValue); - } else { - currentValue.add(value); - } - } - - private String getDefaultedRelFor(Class type, boolean forCollection) { - - if (provider == null) { - return DEFAULT_REL; - } - - String rel = forCollection ? provider.getCollectionResourceRelFor(type) : provider.getSingleResourceRelFor(type); - return rel == null ? DEFAULT_REL : rel; - } - - /** - * Returns the added objects keyed up by their relation types. - * - * @return - */ - public Map> asMap() { - return Collections.unmodifiableMap(embeddeds); - } -} diff --git a/All/Genesis-NP/Genesis#479/pair.info b/All/Genesis-NP/Genesis#479/pair.info deleted file mode 100755 index 0b05dd3..0000000 --- a/All/Genesis-NP/Genesis#479/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:479 -SATName:Genesis -modifiedFPath:src/main/java/org/springframework/hateoas/hal/HalEmbeddedBuilder.java -comSha:693faae0fec691d940eb5f90a36995edee53d530 -parentComSha:693faae0fec691d940eb5f90a36995edee53d530^1 -githubUrl:https://github.com/spring-projects/spring-hateoas -repoName:spring-projects#spring-hateoas \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#480/comMsg.txt b/All/Genesis-NP/Genesis#480/comMsg.txt deleted file mode 100755 index 8b7cb73..0000000 --- a/All/Genesis-NP/Genesis#480/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed logging could not be enabled due to NPE. diff --git a/All/Genesis-NP/Genesis#480/diff.diff b/All/Genesis-NP/Genesis#480/diff.diff deleted file mode 100755 index 18be956..0000000 --- a/All/Genesis-NP/Genesis#480/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/src/main/java/org/imgscalr/Scalr.java b/src/main/java/org/imgscalr/Scalr.java -index 0e3b9af..f31f6c3 100644 ---- a/src/main/java/org/imgscalr/Scalr.java -+++ b/src/main/java/org/imgscalr/Scalr.java -@@ -348 +348 @@ public class Scalr { -- log(0, null, "Debug output ENABLED"); -+ log(0, "Debug output ENABLED"); diff --git a/All/Genesis-NP/Genesis#480/new/Scalr.java b/All/Genesis-NP/Genesis#480/new/Scalr.java deleted file mode 100755 index f31f6c3..0000000 --- a/All/Genesis-NP/Genesis#480/new/Scalr.java +++ /dev/null @@ -1,2245 +0,0 @@ -/** - * Copyright 2011 The Buzz Media, LLC - * - * 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.imgscalr; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.Transparency; -import java.awt.color.ColorSpace; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.AreaAveragingScaleFilter; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ColorConvertOp; -import java.awt.image.ColorModel; -import java.awt.image.ConvolveOp; -import java.awt.image.ImagingOpException; -import java.awt.image.IndexColorModel; -import java.awt.image.Kernel; -import java.awt.image.RasterFormatException; -import java.awt.image.RescaleOp; - -import javax.imageio.ImageIO; - -/** - * Class used to implement performant, good-quality and intelligent image - * scaling and manipulation algorithms in native Java 2D. - *

- * This class utilizes the Java2D "best practices" for image manipulation, - * ensuring that all operations (even most passed in {@link BufferedImageOp}s) - * are hardware accelerated if provided by the platform and host-VM. - *

- *

Image Proportions

- * All scaling operations implemented by this class maintain the proportions of - * the original image unless a mode of {@link Mode#FIT_EXACT} is specified; in - * which case the orientation and proportion of the source image is ignored and - * the image is stretched (if necessary) to fit the exact dimensions given. - *

- * When not using {@link Mode#FIT_EXACT}, in order to maintain the - * proportionality of the original images, this class implements the following - * behavior: - *

    - *
  1. If the image is LANDSCAPE-oriented or SQUARE, treat the - * targetWidth as the primary dimension and re-calculate the - * targetHeight regardless of what is passed in.
  2. - *
  3. If image is PORTRAIT-oriented, treat the targetHeight as the - * primary dimension and re-calculate the targetWidth regardless of - * what is passed in.
  4. - *
  5. If a {@link Mode} value of {@link Mode#FIT_TO_WIDTH} or - * {@link Mode#FIT_TO_HEIGHT} is passed in to the resize method, - * the image's orientation is ignored and the scaled image is fit to the - * preferred dimension by using the value passed in by the user for that - * dimension and recalculating the other (regardless of image orientation). This - * is useful, for example, when working with PORTRAIT oriented images that you - * need to all be the same width or visa-versa (e.g. showing user profile - * pictures in a directory listing).
  6. - *
- *

Image Quality

- * This class implements a few different methods for scaling an image, providing - * either the best-looking result, the fastest result or a balanced result - * between the two depending on the scaling hint provided (see {@link Method}). - *

- * This class also implements the incremental scaling algorithm presented by - * Chris Campbell in his Perils of - * Image.getScaledInstance() article in order to give the best-looking - * results to images scaled down below roughly 800px in size (e.g. generating - * thumbnails that aren't blurry). - *

- * The results generated by imgscalr using this method, as compared to a single - * {@link RenderingHints#VALUE_INTERPOLATION_BICUBIC} scale operation look much - * better. - *

- * Only when scaling using the {@link Method#AUTOMATIC} method will this class - * look at the size of the image before selecting an approach to scaling the - * image. If {@link Method#QUALITY} is specified, the best-looking algorithm - * possible is always used. - *

- * Minor modifications are made to Campbell's original implementation in the - * form of: - *

    - *
  1. Instead of accepting a user-supplied interpolation method, - * {@link RenderingHints#VALUE_INTERPOLATION_BICUBIC} interpolation is always - * used. This was done after A/B comparison testing with large images - * down-scaled to thumbnail sizes showed noticeable "blurring" when BILINEAR - * interpolation was used. Given that Campbell's algorithm is only used in - * QUALITY mode when down-scaling, it was determined that the user's expectation - * of a much less blurry picture would require that BICUBIC be the default - * interpolation in order to meet the QUALITY expectation.
  2. - *
  3. After each iteration of the do-while loop that incrementally scales the - * source image down, an explicit effort is made to call - * {@link BufferedImage#flush()} on the interim temporary {@link BufferedImage} - * instances created by the algorithm in an attempt to ensure a more complete GC - * cycle by the VM when cleaning up the temporary instances (this is in addition - * to disposing of the temporary {@link Graphics2D} references as well).
  4. - *
  5. Extensive comments have been added to increase readability of the code.
  6. - *
  7. Variable names have been expanded to increase readability of the code.
  8. - *
- *

- * NOTE: This class does not call {@link BufferedImage#flush()} - * on any of the source images passed in by calling code; it is up to - * the original caller to dispose of their source images when they are no longer - * needed so the VM can most efficiently GC them. - *

Optimized Image Handling

- * Java2D provides support for a number of different image types defined as - * BufferedImage.TYPE_* variables, unfortunately not all image - * types are supported equally in the Java2D rendering pipeline. - *

- * Some more obscure image types either have poor or no support, leading to - * severely degraded quality and processing performance when an attempt is made - * by imgscalr to create a scaled instance of the same type as the - * source image. In many cases, especially when applying {@link BufferedImageOp} - * s, using poorly supported image types can even lead to exceptions or total - * corruption of the image (e.g. solid black image). - *

- * imgscalr specifically accounts for and automatically hands - * ALL of these pain points for you internally by shuffling all - * images into one of two types: - *

    - *
  1. {@link BufferedImage#TYPE_INT_RGB}
  2. - *
  3. {@link BufferedImage#TYPE_INT_ARGB}
  4. - *
- * depending on if the source image utilizes transparency or not. - *

- * This is a recommended approach by the Java2D team for dealing with poorly (or - * non) supported image types. More can be read about this issue here. - *

- * This is also the reason we recommend using - * {@link #apply(BufferedImage, BufferedImageOp...)} to apply your own ops to - * images even if you aren't using imgscalr for anything else. - *

GIF Transparency

- * Unfortunately in Java 6 and earlier, support for GIF's - * {@link IndexColorModel} is sub-par, both in accurate color-selection and in - * maintaining transparency when moving to an image of type - * {@link BufferedImage#TYPE_INT_ARGB}; because of this issue when a GIF image - * is processed by imgscalr and the result saved as a GIF file (instead of PNG), - * it is possible to lose the alpha channel of a transparent image or in the - * case of applying an optional {@link BufferedImageOp}, lose the entire picture - * all together in the result (long standing JDK bugs are filed for all of these - * issues). - *

- * imgscalr currently does nothing to work around this manually because it is a - * defect in the native platform code itself. Fortunately it looks like the - * issues are half-fixed in Java 7 and any manual workarounds we could attempt - * internally are relatively expensive, in the form of hand-creating and setting - * RGB values pixel-by-pixel with a custom {@link ColorModel} in the scaled - * image. This would lead to a very measurable negative impact on performance - * without the caller understanding why. - *

- * Workaround: A workaround to this issue with all version of - * Java is to simply save a GIF as a PNG; no change to your code needs to be - * made except when the image is saved out, e.g. using {@link ImageIO}. - *

- * When a file type of "PNG" is used, both the transparency and high color - * quality will be maintained as the PNG code path in Java2D is superior to the - * GIF implementation. - *

- * If the issue with optional {@link BufferedImageOp}s destroying GIF image - * content is ever fixed in the platform, saving out resulting images as GIFs - * should suddenly start working. - *

- * More can be read about the issue here and here. - *

Logging

- * This class implements all its debug logging via the - * {@link #log(int, String, Object...)} method. At this time logging is done - * directly to System.out via the printf method. This - * allows the logging to be light weight and easy to capture while adding no - * dependencies to the library. - *

- * Implementation of logging in this class is as efficient as possible; avoiding - * any calls to the logger method or passing of arguments if logging is not - * enabled to avoid the (hidden) cost of constructing the Object[] argument for - * the varargs-based method call. - * - * @author Riyad Kalla (software@thebuzzmedia.com) - * @since 1.1 - */ -public class Scalr { - /** - * System property name used to define the debug boolean flag. - *

- * Value is "imgscalr.debug". - */ - public static final String DEBUG_PROPERTY_NAME = "imgscalr.debug"; - - /** - * System property name used to define a custom log prefix. - *

- * Value is "imgscalr.logPrefix". - */ - public static final String LOG_PREFIX_PROPERTY_NAME = "imgscalr.logPrefix"; - - /** - * Flag used to indicate if debugging output has been enabled by setting the - * "imgscalr.debug" system property to true. This - * value will be false if the "imgscalr.debug" - * system property is undefined or set to false. - *

- * This property can be set on startup with:
- * - * -Dimgscalr.debug=true - * or by calling {@link System#setProperty(String, String)} to set a - * new property value for {@link #DEBUG_PROPERTY_NAME} before this class is - * loaded. - *

- * Default value is false. - */ - public static final boolean DEBUG = Boolean.getBoolean(DEBUG_PROPERTY_NAME); - - /** - * Prefix to every log message this library logs. Using a well-defined - * prefix helps make it easier both visually and programmatically to scan - * log files for messages produced by this library. - *

- * This property can be set on startup with:
- * - * -Dimgscalr.logPrefix=<YOUR PREFIX HERE> - * or by calling {@link System#setProperty(String, String)} to set a - * new property value for {@link #LOG_PREFIX_PROPERTY_NAME} before this - * class is loaded. - *

- * Default value is "[imgscalr] " (including the space). - */ - public static final String LOG_PREFIX = System.getProperty( - LOG_PREFIX_PROPERTY_NAME, "[imgscalr] "); - - /** - * A {@link ConvolveOp} using a very light "blur" kernel that acts like an - * anti-aliasing filter (softens the image a bit) when applied to an image. - *

- * A common request by users of the library was that they wished to "soften" - * resulting images when scaling them down drastically. After quite a bit of - * A/B testing, the kernel used by this Op was selected as the closest match - * for the target which was the softer results from the deprecated - * {@link AreaAveragingScaleFilter} (which is used internally by the - * deprecated {@link Image#getScaledInstance(int, int, int)} method in the - * JDK that imgscalr is meant to replace). - *

- * This ConvolveOp uses a 3x3 kernel with the values: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
.0f.08f.0f
.08f.68f.08f
.0f.08f.0f
- *

- * For those that have worked with ConvolveOps before, this Op uses the - * {@link ConvolveOp#EDGE_NO_OP} instruction to not process the pixels along - * the very edge of the image (otherwise EDGE_ZERO_FILL would create a - * black-border around the image). If you have not worked with a ConvolveOp - * before, it just means this default OP will "do the right thing" and not - * give you garbage results. - *

- * This ConvolveOp uses no {@link RenderingHints} values as internally the - * {@link ConvolveOp} class only uses hints when doing a color conversion - * between the source and destination {@link BufferedImage} targets. - * imgscalr allows the {@link ConvolveOp} to create its own destination - * image every time, so no color conversion is ever needed and thus no - * hints. - *

Performance

- * Use of this (and other) {@link ConvolveOp}s are hardware accelerated when - * possible. For more information on if your image op is hardware - * accelerated or not, check the source code of the underlying JDK class - * that actually executes the Op code, sun.awt.image.ImagingLib. - *

Known Issues

- * In all versions of Java (tested up to Java 7 preview Build 131), running - * this op against a GIF with transparency and attempting to save the - * resulting image as a GIF results in a corrupted/empty file. The file must - * be saved out as a PNG to maintain the transparency. - * - * @since 3.0 - */ - public static final ConvolveOp OP_ANTIALIAS = new ConvolveOp( - new Kernel(3, 3, new float[] { .0f, .08f, .0f, .08f, .68f, .08f, - .0f, .08f, .0f }), ConvolveOp.EDGE_NO_OP, null); - - /** - * A {@link RescaleOp} used to make any input image 10% darker. - *

- * This operation can be applied multiple times in a row if greater than 10% - * changes in brightness are desired. - * - * @since 4.0 - */ - public static final RescaleOp OP_DARKER = new RescaleOp(0.9f, 0, null); - - /** - * A {@link RescaleOp} used to make any input image 10% brighter. - *

- * This operation can be applied multiple times in a row if greater than 10% - * changes in brightness are desired. - * - * @since 4.0 - */ - public static final RescaleOp OP_BRIGHTER = new RescaleOp(1.1f, 0, null); - - /** - * A {@link ColorConvertOp} used to convert any image to a grayscale color - * palette. - *

- * Applying this op multiple times to the same image has no compounding - * effects. - * - * @since 4.0 - */ - public static final ColorConvertOp OP_GRAYSCALE = new ColorConvertOp( - ColorSpace.getInstance(ColorSpace.CS_GRAY), null); - - /** - * Static initializer used to prepare some of the variables used by this - * class. - */ - static { - log(0, "Debug output ENABLED"); - } - - /** - * Used to define the different scaling hints that the algorithm can use. - * - * @author Riyad Kalla (software@thebuzzmedia.com) - * @since 1.1 - */ - public static enum Method { - /** - * Used to indicate that the scaling implementation should decide which - * method to use in order to get the best looking scaled image in the - * least amount of time. - *

- * The scaling algorithm will use the - * {@link Scalr#THRESHOLD_QUALITY_BALANCED} or - * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds as cut-offs to - * decide between selecting the QUALITY, - * BALANCED or SPEED scaling algorithms. - *

- * By default the thresholds chosen will give nearly the best looking - * result in the fastest amount of time. We intend this method to work - * for 80% of people looking to scale an image quickly and get a good - * looking result. - */ - AUTOMATIC, - /** - * Used to indicate that the scaling implementation should scale as fast - * as possible and return a result. For smaller images (800px in size) - * this can result in noticeable aliasing but it can be a few magnitudes - * times faster than using the QUALITY method. - */ - SPEED, - /** - * Used to indicate that the scaling implementation should use a scaling - * operation balanced between SPEED and QUALITY. Sometimes SPEED looks - * too low quality to be useful (e.g. text can become unreadable when - * scaled using SPEED) but using QUALITY mode will increase the - * processing time too much. This mode provides a "better than SPEED" - * quality in a "less than QUALITY" amount of time. - */ - BALANCED, - /** - * Used to indicate that the scaling implementation should do everything - * it can to create as nice of a result as possible. This approach is - * most important for smaller pictures (800px or smaller) and less - * important for larger pictures as the difference between this method - * and the SPEED method become less and less noticeable as the - * source-image size increases. Using the AUTOMATIC method will - * automatically prefer the QUALITY method when scaling an image down - * below 800px in size. - */ - QUALITY; - } - - /** - * Used to define the different modes of resizing that the algorithm can - * use. - * - * @author Riyad Kalla (software@thebuzzmedia.com) - * @since 3.1 - */ - public static enum Mode { - /** - * Used to indicate that the scaling implementation should calculate - * dimensions for the resultant image by looking at the image's - * orientation and generating proportional dimensions that best fit into - * the target width and height given - * - * See "Image Proportions" in the {@link Scalr} class description for - * more detail. - */ - AUTOMATIC, - /** - * Used to fit the image to the exact dimensions given regardless of the - * image's proportions. If the dimensions are not proportionally - * correct, this will introduce vertical or horizontal stretching to the - * image. - *

- * It is recommended that you use one of the other FIT_TO - * modes or {@link Mode#AUTOMATIC} if you want the image to look - * correct, but if dimension-fitting is the #1 priority regardless of - * how it makes the image look, that is what this mode is for. - */ - FIT_EXACT, - /** - * Used to indicate that the scaling implementation should calculate - * dimensions for the resultant image that best-fit within the given - * width, regardless of the orientation of the image. - */ - FIT_TO_WIDTH, - /** - * Used to indicate that the scaling implementation should calculate - * dimensions for the resultant image that best-fit within the given - * height, regardless of the orientation of the image. - */ - FIT_TO_HEIGHT; - } - - /** - * Used to define the different types of rotations that can be applied to an - * image during a resize operation. - * - * @author Riyad Kalla (software@thebuzzmedia.com) - * @since 3.2 - */ - public static enum Rotation { - /** - * 90-degree, clockwise rotation (to the right). This is equivalent to a - * quarter-turn of the image to the right; moving the picture on to its - * right side. - */ - CW_90, - /** - * 180-degree, clockwise rotation (to the right). This is equivalent to - * 1 half-turn of the image to the right; rotating the picture around - * until it is upside down from the original position. - */ - CW_180, - /** - * 270-degree, clockwise rotation (to the right). This is equivalent to - * a quarter-turn of the image to the left; moving the picture on to its - * left side. - */ - CW_270, - /** - * Flip the image horizontally by reflecting it around the y axis. - *

- * This is not a standard rotation around a center point, but instead - * creates the mirrored reflection of the image horizontally. - *

- * More specifically, the vertical orientation of the image stays the - * same (the top stays on top, and the bottom on bottom), but the right - * and left sides flip. This is different than a standard rotation where - * the top and bottom would also have been flipped. - */ - FLIP_HORZ, - /** - * Flip the image vertically by reflecting it around the x axis. - *

- * This is not a standard rotation around a center point, but instead - * creates the mirrored reflection of the image vertically. - *

- * More specifically, the horizontal orientation of the image stays the - * same (the left stays on the left and the right stays on the right), - * but the top and bottom sides flip. This is different than a standard - * rotation where the left and right would also have been flipped. - */ - FLIP_VERT; - } - - /** - * Threshold (in pixels) at which point the scaling operation using the - * {@link Method#AUTOMATIC} method will decide if a {@link Method#BALANCED} - * method will be used (if smaller than or equal to threshold) or a - * {@link Method#SPEED} method will be used (if larger than threshold). - *

- * The bigger the image is being scaled to, the less noticeable degradations - * in the image becomes and the faster algorithms can be selected. - *

- * The value of this threshold (1600) was chosen after visual, by-hand, A/B - * testing between different types of images scaled with this library; both - * photographs and screenshots. It was determined that images below this - * size need to use a {@link Method#BALANCED} scale method to look decent in - * most all cases while using the faster {@link Method#SPEED} method for - * images bigger than this threshold showed no noticeable degradation over a - * BALANCED scale. - */ - public static final int THRESHOLD_BALANCED_SPEED = 1600; - - /** - * Threshold (in pixels) at which point the scaling operation using the - * {@link Method#AUTOMATIC} method will decide if a {@link Method#QUALITY} - * method will be used (if smaller than or equal to threshold) or a - * {@link Method#BALANCED} method will be used (if larger than threshold). - *

- * The bigger the image is being scaled to, the less noticeable degradations - * in the image becomes and the faster algorithms can be selected. - *

- * The value of this threshold (800) was chosen after visual, by-hand, A/B - * testing between different types of images scaled with this library; both - * photographs and screenshots. It was determined that images below this - * size need to use a {@link Method#QUALITY} scale method to look decent in - * most all cases while using the faster {@link Method#BALANCED} method for - * images bigger than this threshold showed no noticeable degradation over a - * QUALITY scale. - */ - public static final int THRESHOLD_QUALITY_BALANCED = 800; - - /** - * Used to apply, in the order given, 1 or more {@link BufferedImageOp}s to - * a given {@link BufferedImage} and return the result. - *

- * Feature: This implementation works around a - * decade-old JDK bug that can cause a {@link RasterFormatException} - * when applying a perfectly valid {@link BufferedImageOp}s to images. - *

- * Feature: This implementation also works around - * {@link BufferedImageOp}s failing to apply and throwing - * {@link ImagingOpException}s when run against a src image - * type that is poorly supported. Unfortunately using {@link ImageIO} and - * standard Java methods to load images provides no consistency in getting - * images in well-supported formats. This method automatically accounts and - * corrects for all those problems (if necessary). - *

- * It is recommended you always use this method to apply any - * {@link BufferedImageOp}s instead of relying on directly using the - * {@link BufferedImageOp#filter(BufferedImage, BufferedImage)} method. - *

- * Performance: Not all {@link BufferedImageOp}s are - * hardware accelerated operations, but many of the most popular (like - * {@link ConvolveOp}) are. For more information on if your image op is - * hardware accelerated or not, check the source code of the underlying JDK - * class that actually executes the Op code, sun.awt.image.ImagingLib. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will have the ops applied to it. - * @param ops - * 1 or more ops to apply to the image. - * - * @return a new {@link BufferedImage} that represents the src - * with all the given operations applied to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if ops is null or empty. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (ops == null || ops.length == 0) - throw new IllegalArgumentException("ops cannot be null or empty"); - - int type = src.getType(); - - /* - * Ensure the src image is in the best supported image type before we - * continue, otherwise it is possible our calls below to getBounds2D and - * certainly filter(...) may fail if not. - * - * Java2D makes an attempt at applying most BufferedImageOps using - * hardware acceleration via the ImagingLib internal library. - * - * Unfortunately may of the BufferedImageOp are written to simply fail - * with an ImagingOpException if the operation cannot be applied with no - * additional information about what went wrong or attempts at - * re-applying it in different ways. - * - * This is assuming the failing BufferedImageOp even returns a null - * image after failing to apply; some simply return a corrupted/black - * image that result in no exception and it is up to the user to - * discover this. - * - * In internal testing, EVERY failure I've ever seen was the result of - * the source image being in a poorly-supported BufferedImage Type like - * BGR or ABGR (even though it was loaded with ImageIO). - * - * To avoid this nasty/stupid surprise with BufferedImageOps, we always - * ensure that the src image starts in an optimally supported format - * before we try and apply the filter. - */ - if (!(type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB)) - src = copyToOptimalImage(src); - - if (DEBUG) - log(0, "Applying %d BufferedImageOps...", ops.length); - - boolean hasReassignedSrc = false; - - for (int i = 0; i < ops.length; i++) { - long subT = System.currentTimeMillis(); - BufferedImageOp op = ops[i]; - - // Skip null ops instead of throwing an exception. - if (op == null) - continue; - - if (DEBUG) - log(1, "Applying BufferedImageOp [class=%s, toString=%s]...", - op.getClass(), op.toString()); - - /* - * Must use op.getBounds instead of src.getWidth and src.getHeight - * because we are trying to create an image big enough to hold the - * result of this operation (which may be to scale the image - * smaller), in that case the bounds reported by this op and the - * bounds reported by the source image will be different. - */ - Rectangle2D resultBounds = op.getBounds2D(src); - - // Watch out for flaky/misbehaving ops that fail to work right. - if (resultBounds == null) - throw new ImagingOpException( - "BufferedImageOp [" - + op.toString() - + "] getBounds2D(src) returned null bounds for the target image; this should not happen and indicates a problem with application of this type of op."); - - /* - * We must manually create the target image; we cannot rely on the - * null-destination filter() method to create a valid destination - * for us thanks to this JDK bug that has been filed for almost a - * decade: - * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606 - */ - BufferedImage dest = createOptimalImage(src, - (int) Math.round(resultBounds.getWidth()), - (int) Math.round(resultBounds.getHeight())); - - // Perform the operation, update our result to return. - BufferedImage result = op.filter(src, dest); - - /* - * Flush the 'src' image ONLY IF it is one of our interim temporary - * images being used when applying 2 or more operations back to - * back. We never want to flush the original image passed in. - */ - if (hasReassignedSrc) - src.flush(); - - /* - * Incase there are more operations to perform, update what we - * consider the 'src' reference to our last result so on the next - * iteration the next op is applied to this result and not back - * against the original src passed in. - */ - src = result; - - /* - * Keep track of when we re-assign 'src' to an interim temporary - * image, so we know when we can explicitly flush it and clean up - * references on future iterations. - */ - hasReassignedSrc = true; - - if (DEBUG) - log(1, - "Applied BufferedImageOp in %d ms, result [width=%d, height=%d]", - System.currentTimeMillis() - subT, result.getWidth(), - result.getHeight()); - } - - if (DEBUG) - log(0, "All %d BufferedImageOps applied in %d ms", ops.length, - System.currentTimeMillis() - t); - - return src; - } - - /** - * Used to crop the given src image from the top-left corner - * and applying any optional {@link BufferedImageOp}s to the result before - * returning it. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image to crop. - * @param width - * The width of the bounding cropping box. - * @param height - * The height of the bounding cropping box. - * @param ops - * 0 or more ops to apply to the image. If - * null or empty then src is return - * unmodified. - * - * @return a new {@link BufferedImage} representing the cropped region of - * the src image with any optional operations applied - * to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if any coordinates of the bounding crop box is invalid within - * the bounds of the src image (e.g. negative or - * too big). - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage crop(BufferedImage src, int width, int height, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - return crop(src, 0, 0, width, height, ops); - } - - /** - * Used to crop the given src image and apply any optional - * {@link BufferedImageOp}s to it before returning the result. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image to crop. - * @param x - * The x-coordinate of the top-left corner of the bounding box - * used for cropping. - * @param y - * The y-coordinate of the top-left corner of the bounding box - * used for cropping. - * @param width - * The width of the bounding cropping box. - * @param height - * The height of the bounding cropping box. - * @param ops - * 0 or more ops to apply to the image. If - * null or empty then src is return - * unmodified. - * - * @return a new {@link BufferedImage} representing the cropped region of - * the src image with any optional operations applied - * to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if any coordinates of the bounding crop box is invalid within - * the bounds of the src image (e.g. negative or - * too big). - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage crop(BufferedImage src, int x, int y, - int width, int height, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (x < 0 || y < 0 || width < 0 || height < 0) - throw new IllegalArgumentException("Invalid crop bounds: x [" + x - + "], y [" + y + "], width [" + width + "] and height [" - + height + "] must all be >= 0"); - - int srcWidth = src.getWidth(); - int srcHeight = src.getHeight(); - - if ((x + width) > srcWidth) - throw new IllegalArgumentException( - "Invalid crop bounds: x + width [" + (x + width) - + "] must be <= src.getWidth() [" + srcWidth + "]"); - if ((y + height) > srcHeight) - throw new IllegalArgumentException( - "Invalid crop bounds: y + height [" + (y + height) - + "] must be <= src.getHeight() [" + srcHeight - + "]"); - - if (DEBUG) - log(0, - "Cropping Image [width=%d, height=%d] to [x=%d, y=%d, width=%d, height=%d]...", - srcWidth, srcHeight, x, y, width, height); - - // Create a target image of an optimal type to render into. - BufferedImage result = createOptimalImage(src, width, height); - Graphics g = result.getGraphics(); - - /* - * Render the region specified by our crop bounds from the src image - * directly into our result image (which is the exact size of the crop - * region). - */ - g.drawImage(src, 0, 0, width, height, x, y, (x + width), (y + height), - null); - g.dispose(); - - if (DEBUG) - log(0, "Cropped Image in %d ms", System.currentTimeMillis() - t); - - // Apply any optional operations (if specified). - if (ops != null && ops.length > 0) - result = apply(result, ops); - - return result; - } - - /** - * Used to apply padding around the edges of an image using - * {@link Color#BLACK} to fill the extra padded space and then return the - * result. - *

- * The amount of padding specified is applied to all sides; - * more specifically, a padding of 2 would add 2 - * extra pixels of space (filled by the given color) on the - * top, bottom, left and right sides of the resulting image causing the - * result to be 4 pixels wider and 4 pixels taller than the src - * image. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image the padding will be added to. - * @param padding - * The number of pixels of padding to add to each side in the - * resulting image. If this value is 0 then - * src is returned unmodified. - * @param ops - * 0 or more ops to apply to the image. If - * null or empty then src is return - * unmodified. - * - * @return a new {@link BufferedImage} representing src with - * the given padding applied to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if padding is < 1. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage pad(BufferedImage src, int padding, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - return pad(src, padding, Color.BLACK); - } - - /** - * Used to apply padding around the edges of an image using the given color - * to fill the extra padded space and then return the result. {@link Color}s - * using an alpha channel (i.e. transparency) are supported. - *

- * The amount of padding specified is applied to all sides; - * more specifically, a padding of 2 would add 2 - * extra pixels of space (filled by the given color) on the - * top, bottom, left and right sides of the resulting image causing the - * result to be 4 pixels wider and 4 pixels taller than the src - * image. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image the padding will be added to. - * @param padding - * The number of pixels of padding to add to each side in the - * resulting image. If this value is 0 then - * src is returned unmodified. - * @param color - * The color to fill the padded space with. {@link Color}s using - * an alpha channel (i.e. transparency) are supported. - * @param ops - * 0 or more ops to apply to the image. If - * null or empty then src is return - * unmodified. - * - * @return a new {@link BufferedImage} representing src with - * the given padding applied to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if padding is < 1. - * @throws IllegalArgumentException - * if color is null. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage pad(BufferedImage src, int padding, - Color color, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (padding < 1) - throw new IllegalArgumentException("padding [" + padding - + "] must be > 0"); - if (color == null) - throw new IllegalArgumentException("color cannot be null"); - - int srcWidth = src.getWidth(); - int srcHeight = src.getHeight(); - - /* - * Double the padding to account for all sides of the image. More - * specifically, if padding is "1" we add 2 pixels to width and 2 to - * height, so we have 1 new pixel of padding all the way around our - * image. - */ - int sizeDiff = (padding * 2); - int newWidth = srcWidth + sizeDiff; - int newHeight = srcHeight + sizeDiff; - - if (DEBUG) - log(0, - "Padding Image from [originalWidth=%d, originalHeight=%d, padding=%d] to [newWidth=%d, newHeight=%d]...", - srcWidth, srcHeight, padding, newWidth, newHeight); - - boolean colorHasAlpha = (color.getAlpha() != 255); - boolean imageHasAlpha = (src.getTransparency() != BufferedImage.OPAQUE); - - BufferedImage result; - - /* - * We need to make sure our resulting image that we render into contains - * alpha if either our original image OR the padding color we are using - * contain it. - */ - if (colorHasAlpha || imageHasAlpha) { - if (DEBUG) - log(1, - "Transparency FOUND in source image or color, using ARGB image type..."); - - result = new BufferedImage(newWidth, newHeight, - BufferedImage.TYPE_INT_ARGB); - } else { - if (DEBUG) - log(1, - "Transparency NOT FOUND in source image or color, using RGB image type..."); - - result = new BufferedImage(newWidth, newHeight, - BufferedImage.TYPE_INT_RGB); - } - - Graphics g = result.getGraphics(); - - // "Clear" the background of the new image with our padding color first. - g.setColor(color); - g.fillRect(0, 0, newWidth, newHeight); - - // Draw the image into the center of the new padded image. - g.drawImage(src, padding, padding, null); - g.dispose(); - - if (DEBUG) - log(0, "Padding Applied in %d ms", System.currentTimeMillis() - t); - - // Apply any optional operations (if specified). - if (ops != null && ops.length > 0) - result = apply(result, ops); - - return result; - } - - /** - * Resize a given image (maintaining its original proportion) to a width and - * height no bigger than targetSize and apply the given - * {@link BufferedImageOp}s (if any) to the result before returning it. - *

- * A scaling method of {@link Method#AUTOMATIC} and mode of - * {@link Mode#AUTOMATIC} are used. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param targetSize - * The target width and height (square) that you wish the image - * to fit within. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if targetSize is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage resize(BufferedImage src, int targetSize, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetSize, - targetSize, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to a width and - * height no bigger than targetSize using the given scaling - * method and apply the given {@link BufferedImageOp}s (if any) to the - * result before returning it. - *

- * A mode of {@link Mode#AUTOMATIC} is used. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param scalingMethod - * The method used for scaling the image; preferring speed to - * quality or a balance of both. - * @param targetSize - * The target width and height (square) that you wish the image - * to fit within. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if scalingMethod is null. - * @throws IllegalArgumentException - * if targetSize is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Method - */ - public static BufferedImage resize(BufferedImage src, Method scalingMethod, - int targetSize, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, scalingMethod, Mode.AUTOMATIC, targetSize, - targetSize, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to a width and - * height no bigger than targetSize (or fitting the image to - * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode} - * specified) and apply the given {@link BufferedImageOp}s (if any) to the - * result before returning it. - *

- * A scaling method of {@link Method#AUTOMATIC} is used. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param resizeMode - * Used to indicate how imgscalr should calculate the final - * target size for the image, either fitting the image to the - * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image - * to the given height ({@link Mode#FIT_TO_HEIGHT}). If - * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate - * proportional dimensions for the scaled image based on its - * orientation (landscape, square or portrait). Unless you have - * very specific size requirements, most of the time you just - * want to use {@link Mode#AUTOMATIC} to "do the right thing". - * @param targetSize - * The target width and height (square) that you wish the image - * to fit within. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if resizeMode is null. - * @throws IllegalArgumentException - * if targetSize is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Mode - */ - public static BufferedImage resize(BufferedImage src, Mode resizeMode, - int targetSize, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, Method.AUTOMATIC, resizeMode, targetSize, - targetSize, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to a width and - * height no bigger than targetSize (or fitting the image to - * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode} - * specified) using the given scaling method and apply the given - * {@link BufferedImageOp}s (if any) to the result before returning it. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param scalingMethod - * The method used for scaling the image; preferring speed to - * quality or a balance of both. - * @param resizeMode - * Used to indicate how imgscalr should calculate the final - * target size for the image, either fitting the image to the - * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image - * to the given height ({@link Mode#FIT_TO_HEIGHT}). If - * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate - * proportional dimensions for the scaled image based on its - * orientation (landscape, square or portrait). Unless you have - * very specific size requirements, most of the time you just - * want to use {@link Mode#AUTOMATIC} to "do the right thing". - * @param targetSize - * The target width and height (square) that you wish the image - * to fit within. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if scalingMethod is null. - * @throws IllegalArgumentException - * if resizeMode is null. - * @throws IllegalArgumentException - * if targetSize is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Method - * @see Mode - */ - public static BufferedImage resize(BufferedImage src, Method scalingMethod, - Mode resizeMode, int targetSize, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, scalingMethod, resizeMode, targetSize, targetSize, - ops); - } - - /** - * Resize a given image (maintaining its original proportion) to the target - * width and height and apply the given {@link BufferedImageOp}s (if any) to - * the result before returning it. - *

- * A scaling method of {@link Method#AUTOMATIC} and mode of - * {@link Mode#AUTOMATIC} are used. - *

- * TIP: See the class description to understand how this - * class handles recalculation of the targetWidth or - * targetHeight depending on the image's orientation in order - * to maintain the original proportion. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param targetWidth - * The target width that you wish the image to have. - * @param targetHeight - * The target height that you wish the image to have. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if targetWidth is < 0 or if - * targetHeight is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage resize(BufferedImage src, int targetWidth, - int targetHeight, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetWidth, - targetHeight, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to the target - * width and height using the given scaling method and apply the given - * {@link BufferedImageOp}s (if any) to the result before returning it. - *

- * A mode of {@link Mode#AUTOMATIC} is used. - *

- * TIP: See the class description to understand how this - * class handles recalculation of the targetWidth or - * targetHeight depending on the image's orientation in order - * to maintain the original proportion. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param scalingMethod - * The method used for scaling the image; preferring speed to - * quality or a balance of both. - * @param targetWidth - * The target width that you wish the image to have. - * @param targetHeight - * The target height that you wish the image to have. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if scalingMethod is null. - * @throws IllegalArgumentException - * if targetWidth is < 0 or if - * targetHeight is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Method - */ - public static BufferedImage resize(BufferedImage src, Method scalingMethod, - int targetWidth, int targetHeight, BufferedImageOp... ops) { - return resize(src, scalingMethod, Mode.AUTOMATIC, targetWidth, - targetHeight, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to the target - * width and height (or fitting the image to the given WIDTH or HEIGHT - * explicitly, depending on the {@link Mode} specified) and apply the given - * {@link BufferedImageOp}s (if any) to the result before returning it. - *

- * A scaling method of {@link Method#AUTOMATIC} is used. - *

- * TIP: See the class description to understand how this - * class handles recalculation of the targetWidth or - * targetHeight depending on the image's orientation in order - * to maintain the original proportion. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param resizeMode - * Used to indicate how imgscalr should calculate the final - * target size for the image, either fitting the image to the - * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image - * to the given height ({@link Mode#FIT_TO_HEIGHT}). If - * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate - * proportional dimensions for the scaled image based on its - * orientation (landscape, square or portrait). Unless you have - * very specific size requirements, most of the time you just - * want to use {@link Mode#AUTOMATIC} to "do the right thing". - * @param targetWidth - * The target width that you wish the image to have. - * @param targetHeight - * The target height that you wish the image to have. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if resizeMode is null. - * @throws IllegalArgumentException - * if targetWidth is < 0 or if - * targetHeight is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Mode - */ - public static BufferedImage resize(BufferedImage src, Mode resizeMode, - int targetWidth, int targetHeight, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, Method.AUTOMATIC, resizeMode, targetWidth, - targetHeight, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to the target - * width and height (or fitting the image to the given WIDTH or HEIGHT - * explicitly, depending on the {@link Mode} specified) using the given - * scaling method and apply the given {@link BufferedImageOp}s (if any) to - * the result before returning it. - *

- * TIP: See the class description to understand how this - * class handles recalculation of the targetWidth or - * targetHeight depending on the image's orientation in order - * to maintain the original proportion. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param scalingMethod - * The method used for scaling the image; preferring speed to - * quality or a balance of both. - * @param resizeMode - * Used to indicate how imgscalr should calculate the final - * target size for the image, either fitting the image to the - * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image - * to the given height ({@link Mode#FIT_TO_HEIGHT}). If - * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate - * proportional dimensions for the scaled image based on its - * orientation (landscape, square or portrait). Unless you have - * very specific size requirements, most of the time you just - * want to use {@link Mode#AUTOMATIC} to "do the right thing". - * @param targetWidth - * The target width that you wish the image to have. - * @param targetHeight - * The target height that you wish the image to have. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if scalingMethod is null. - * @throws IllegalArgumentException - * if resizeMode is null. - * @throws IllegalArgumentException - * if targetWidth is < 0 or if - * targetHeight is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Method - * @see Mode - */ - public static BufferedImage resize(BufferedImage src, Method scalingMethod, - Mode resizeMode, int targetWidth, int targetHeight, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (targetWidth < 0) - throw new IllegalArgumentException("targetWidth must be >= 0"); - if (targetHeight < 0) - throw new IllegalArgumentException("targetHeight must be >= 0"); - if (scalingMethod == null) - throw new IllegalArgumentException( - "scalingMethod cannot be null. A good default value is Method.AUTOMATIC."); - if (resizeMode == null) - throw new IllegalArgumentException( - "resizeMode cannot be null. A good default value is Mode.AUTOMATIC."); - - BufferedImage result = null; - - int currentWidth = src.getWidth(); - int currentHeight = src.getHeight(); - - // <= 1 is a square or landscape-oriented image, > 1 is a portrait. - float ratio = ((float) currentHeight / (float) currentWidth); - - if (DEBUG) - log(0, - "Resizing Image [size=%dx%d, resizeMode=%s, orientation=%s, ratio(H/W)=%f] to [targetSize=%dx%d]", - currentWidth, currentHeight, resizeMode, - (ratio <= 1 ? "Landscape/Square" : "Portrait"), ratio, - targetWidth, targetHeight); - - /* - * First determine if ANY size calculation needs to be done, in the case - * of FIT_EXACT, ignore image proportions and orientation and just use - * what the user sent in, otherwise the proportion of the picture must - * be honored. - * - * The way that is done is to figure out if the image is in a - * LANDSCAPE/SQUARE or PORTRAIT orientation and depending on its - * orientation, use the primary dimension (width for LANDSCAPE/SQUARE - * and height for PORTRAIT) to recalculate the alternative (height and - * width respectively) value that adheres to the existing ratio. - * - * This helps make life easier for the caller as they don't need to - * pre-compute proportional dimensions before calling the API, they can - * just specify the dimensions they would like the image to roughly fit - * within and it will do the right thing without mangling the result. - */ - if (resizeMode != Mode.FIT_EXACT) { - if ((ratio <= 1 && resizeMode == Mode.AUTOMATIC) - || (resizeMode == Mode.FIT_TO_WIDTH)) { - // First make sure we need to do any work in the first place - if (targetWidth == src.getWidth()) - return src; - - // Save for detailed logging (this is cheap). - int originalTargetHeight = targetHeight; - - /* - * Landscape or Square Orientation: Ignore the given height and - * re-calculate a proportionally correct value based on the - * targetWidth. - */ - targetHeight = Math.round((float) targetWidth * ratio); - - if (DEBUG && originalTargetHeight != targetHeight) - log(1, - "Auto-Corrected targetHeight [from=%d to=%d] to honor image proportions.", - originalTargetHeight, targetHeight); - } else { - // First make sure we need to do any work in the first place - if (targetHeight == src.getHeight()) - return src; - - // Save for detailed logging (this is cheap). - int originalTargetWidth = targetWidth; - - /* - * Portrait Orientation: Ignore the given width and re-calculate - * a proportionally correct value based on the targetHeight. - */ - targetWidth = Math.round((float) targetHeight / ratio); - - if (DEBUG && originalTargetWidth != targetWidth) - log(1, - "Auto-Corrected targetWidth [from=%d to=%d] to honor image proportions.", - originalTargetWidth, targetWidth); - } - } else { - if (DEBUG) - log(1, - "Resize Mode FIT_EXACT used, no width/height checking or re-calculation will be done."); - } - - // If AUTOMATIC was specified, determine the real scaling method. - if (scalingMethod == Scalr.Method.AUTOMATIC) - scalingMethod = determineScalingMethod(targetWidth, targetHeight, - ratio); - - if (DEBUG) - log(1, "Using Scaling Method: %s", scalingMethod); - - // Now we scale the image - if (scalingMethod == Scalr.Method.SPEED) { - result = scaleImage(src, targetWidth, targetHeight, - RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); - } else if (scalingMethod == Scalr.Method.BALANCED) { - result = scaleImage(src, targetWidth, targetHeight, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - } else if (scalingMethod == Scalr.Method.QUALITY) { - /* - * If we are scaling up (in either width or height - since we know - * the image will stay proportional we just check if either are - * being scaled up), directly using a single BICUBIC will give us - * better results then using Chris Campbell's incremental scaling - * operation (and take a lot less time). - * - * If we are scaling down, we must use the incremental scaling - * algorithm for the best result. - */ - if (targetWidth > currentWidth || targetHeight > currentHeight) { - if (DEBUG) - log(1, - "QUALITY scale-up, a single BICUBIC scale operation will be used..."); - - /* - * BILINEAR and BICUBIC look similar the smaller the scale jump - * upwards is, if the scale is larger BICUBIC looks sharper and - * less fuzzy. But most importantly we have to use BICUBIC to - * match the contract of the QUALITY rendering scalingMethod. - * This note is just here for anyone reading the code and - * wondering how they can speed their own calls up. - */ - result = scaleImage(src, targetWidth, targetHeight, - RenderingHints.VALUE_INTERPOLATION_BICUBIC); - } else { - if (DEBUG) - log(1, - "QUALITY scale-down, incremental scaling will be used..."); - - /* - * Originally we wanted to use BILINEAR interpolation here - * because it takes 1/3rd the time that the BICUBIC - * interpolation does, however, when scaling large images down - * to most sizes bigger than a thumbnail we witnessed noticeable - * "softening" in the resultant image with BILINEAR that would - * be unexpectedly annoying to a user expecting a "QUALITY" - * scale of their original image. Instead BICUBIC was chosen to - * honor the contract of a QUALITY scale of the original image. - */ - result = scaleImageIncrementally(src, targetWidth, - targetHeight, - RenderingHints.VALUE_INTERPOLATION_BICUBIC); - } - } - - if (DEBUG) - log(0, "Resized Image in %d ms", System.currentTimeMillis() - t); - - // Apply any optional operations (if specified). - if (ops != null && ops.length > 0) - result = apply(result, ops); - - return result; - } - - /** - * Used to apply a {@link Rotation} and then 0 or more - * {@link BufferedImageOp}s to a given image and return the result. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will have the rotation applied to it. - * @param rotation - * The rotation that will be applied to the image. - * @param ops - * Zero or more optional image operations (e.g. sharpen, blur, - * etc.) that can be applied to the final result before returning - * the image. - * - * @return a new {@link BufferedImage} representing src rotated - * by the given amount and any optional ops applied to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if rotation is null. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Rotation - */ - public static BufferedImage rotate(BufferedImage src, Rotation rotation, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (rotation == null) - throw new IllegalArgumentException("rotation cannot be null"); - - if (DEBUG) - log(0, "Rotating Image [%s]...", rotation); - - /* - * Setup the default width/height values from our image. - * - * In the case of a 90 or 270 (-90) degree rotation, these two values - * flip-flop and we will correct those cases down below in the switch - * statement. - */ - int newWidth = src.getWidth(); - int newHeight = src.getHeight(); - - /* - * We create a transform per operation request as (oddly enough) it ends - * up being faster for the VM to create, use and destroy these instances - * than it is to re-use a single AffineTransform per-thread via the - * AffineTransform.setTo(...) methods which was my first choice (less - * object creation); after benchmarking this explicit case and looking - * at just how much code gets run inside of setTo() I opted for a new AT - * for every rotation. - * - * Besides the performance win, trying to safely reuse AffineTransforms - * via setTo(...) would have required ThreadLocal instances to avoid - * race conditions where two or more resize threads are manipulating the - * same transform before applying it. - * - * Misusing ThreadLocals are one of the #1 reasons for memory leaks in - * server applications and since we have no nice way to hook into the - * init/destroy Servlet cycle or any other initialization cycle for this - * library to automatically call ThreadLocal.remove() to avoid the - * memory leak, it would have made using this library *safely* on the - * server side much harder. - * - * So we opt for creating individual transforms per rotation op and let - * the VM clean them up in a GC. I only clarify all this reasoning here - * for anyone else reading this code and being tempted to reuse the AT - * instances of performance gains; there aren't any AND you get a lot of - * pain along with it. - */ - AffineTransform tx = new AffineTransform(); - - switch (rotation) { - case CW_90: - /* - * A 90 or -90 degree rotation will cause the height and width to - * flip-flop from the original image to the rotated one. - */ - newWidth = src.getHeight(); - newHeight = src.getWidth(); - - // Reminder: newWidth == result.getHeight() at this point - tx.translate(newWidth, 0); - tx.rotate(Math.toRadians(90)); - - break; - - case CW_270: - /* - * A 90 or -90 degree rotation will cause the height and width to - * flip-flop from the original image to the rotated one. - */ - newWidth = src.getHeight(); - newHeight = src.getWidth(); - - // Reminder: newHeight == result.getWidth() at this point - tx.translate(0, newHeight); - tx.rotate(Math.toRadians(-90)); - break; - - case CW_180: - tx.translate(newWidth, newHeight); - tx.rotate(Math.toRadians(180)); - break; - - case FLIP_HORZ: - tx.translate(newWidth, 0); - tx.scale(-1.0, 1.0); - break; - - case FLIP_VERT: - tx.translate(0, newHeight); - tx.scale(1.0, -1.0); - break; - } - - // Create our target image we will render the rotated result to. - BufferedImage result = createOptimalImage(src, newWidth, newHeight); - Graphics2D g2d = (Graphics2D) result.createGraphics(); - - /* - * Render the resultant image to our new rotatedImage buffer, applying - * the AffineTransform that we calculated above during rendering so the - * pixels from the old position are transposed to the new positions in - * the resulting image correctly. - */ - g2d.drawImage(src, tx, null); - g2d.dispose(); - - if (DEBUG) - log(0, "Rotation Applied in %d ms, result [width=%d, height=%d]", - System.currentTimeMillis() - t, result.getWidth(), - result.getHeight()); - - // Apply any optional operations (if specified). - if (ops != null && ops.length > 0) - result = apply(result, ops); - - return result; - } - - /** - * Used to write out a useful and well-formatted log message by any piece of - * code inside of the imgscalr library. - *

- * If a message cannot be logged (logging is disabled) then this method - * returns immediately. - *

- * NOTE: Because Java will auto-box primitive arguments - * into Objects when building out the params array, care should - * be taken not to call this method with primitive values unless - * {@link Scalr#DEBUG} is true; otherwise the VM will be - * spending time performing unnecessary auto-boxing calculations. - * - * @param depth - * The indentation level of the log message. - * @param message - * The log message in format string syntax that will be logged. - * @param params - * The parameters that will be swapped into all the place holders - * in the original messages before being logged. - * - * @see Scalr#LOG_PREFIX - * @see Scalr#LOG_PREFIX_PROPERTY_NAME - */ - protected static void log(int depth, String message, Object... params) { - if (Scalr.DEBUG) { - System.out.print(Scalr.LOG_PREFIX); - - for (int i = 0; i < depth; i++) - System.out.print("\t"); - - System.out.printf(message, params); - System.out.println(); - } - } - - /** - * Used to create a {@link BufferedImage} with the most optimal RGB TYPE ( - * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB} - * ) capable of being rendered into from the given src. The - * width and height of both images will be identical. - *

- * This does not perform a copy of the image data from src into - * the result image; see {@link #copyToOptimalImage(BufferedImage)} for - * that. - *

- * We force all rendering results into one of these two types, avoiding the - * case where a source image is of an unsupported (or poorly supported) - * format by Java2D causing the rendering result to end up looking terrible - * (common with GIFs) or be totally corrupt (e.g. solid black image). - *

- * Originally reported by Magnus Kvalheim from Movellas when scaling certain - * GIF and PNG images. - * - * @param src - * The source image that will be analyzed to determine the most - * optimal image type it can be rendered into. - * - * @return a new {@link BufferedImage} representing the most optimal target - * image type that src can be rendered into. - * - * @see How - * Java2D handles poorly supported image types - * @see Thanks - * to Morten Nobel for implementation hint - */ - protected static BufferedImage createOptimalImage(BufferedImage src) { - return createOptimalImage(src, src.getWidth(), src.getHeight()); - } - - /** - * Used to create a {@link BufferedImage} with the given dimensions and the - * most optimal RGB TYPE ( {@link BufferedImage#TYPE_INT_RGB} or - * {@link BufferedImage#TYPE_INT_ARGB} ) capable of being rendered into from - * the given src. - *

- * This does not perform a copy of the image data from src into - * the result image; see {@link #copyToOptimalImage(BufferedImage)} for - * that. - *

- * We force all rendering results into one of these two types, avoiding the - * case where a source image is of an unsupported (or poorly supported) - * format by Java2D causing the rendering result to end up looking terrible - * (common with GIFs) or be totally corrupt (e.g. solid black image). - *

- * Originally reported by Magnus Kvalheim from Movellas when scaling certain - * GIF and PNG images. - * - * @param src - * The source image that will be analyzed to determine the most - * optimal image type it can be rendered into. - * @param width - * The width of the newly created resulting image. - * @param height - * The height of the newly created resulting image. - * - * @return a new {@link BufferedImage} representing the most optimal target - * image type that src can be rendered into. - * - * @throws IllegalArgumentException - * if width or height are < 0. - * - * @see How - * Java2D handles poorly supported image types - * @see Thanks - * to Morten Nobel for implementation hint - */ - protected static BufferedImage createOptimalImage(BufferedImage src, - int width, int height) throws IllegalArgumentException { - if (width < 0 || height < 0) - throw new IllegalArgumentException("width [" + width - + "] and height [" + height + "] must be >= 0"); - - return new BufferedImage( - width, - height, - (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB - : BufferedImage.TYPE_INT_ARGB)); - } - - /** - * Used to copy a {@link BufferedImage} from a non-optimal type into a new - * {@link BufferedImage} instance of an optimal type (RGB or ARGB). If - * src is already of an optimal type, then it is returned - * unmodified. - *

- * This method is meant to be used by any calling code (imgscalr's or - * otherwise) to convert any inbound image from a poorly supported image - * type into the 2 most well-supported image types in Java2D ( - * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB} - * ) in order to ensure all subsequent graphics operations are performed as - * efficiently and correctly as possible. - *

- * When using Java2D to work with image types that are not well supported, - * the results can be anything from exceptions bubbling up from the depths - * of Java2D to images being completely corrupted and just returned as solid - * black. - * - * @param src - * The image to copy (if necessary) into an optimally typed - * {@link BufferedImage}. - * - * @return a representation of the src image in an optimally - * typed {@link BufferedImage}, otherwise src if it was - * already of an optimal type. - * - * @throws IllegalArgumentException - * if src is null. - */ - protected static BufferedImage copyToOptimalImage(BufferedImage src) - throws IllegalArgumentException { - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - - // Calculate the type depending on the presence of alpha. - int type = (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB - : BufferedImage.TYPE_INT_ARGB); - BufferedImage result = new BufferedImage(src.getWidth(), - src.getHeight(), type); - - // Render the src image into our new optimal source. - Graphics g = result.getGraphics(); - g.drawImage(src, 0, 0, null); - g.dispose(); - - return result; - } - - /** - * Used to determine the scaling {@link Method} that is best suited for - * scaling the image to the targeted dimensions. - *

- * This method is intended to be used to select a specific scaling - * {@link Method} when a {@link Method#AUTOMATIC} method is specified. This - * method utilizes the {@link Scalr#THRESHOLD_QUALITY_BALANCED} and - * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds when selecting which - * method should be used by comparing the primary dimension (width or - * height) against the threshold and seeing where the image falls. The - * primary dimension is determined by looking at the orientation of the - * image: landscape or square images use their width and portrait-oriented - * images use their height. - * - * @param targetWidth - * The target width for the scaled image. - * @param targetHeight - * The target height for the scaled image. - * @param ratio - * A height/width ratio used to determine the orientation of the - * image so the primary dimension (width or height) can be - * selected to test if it is greater than or less than a - * particular threshold. - * - * @return the fastest {@link Method} suited for scaling the image to the - * specified dimensions while maintaining a good-looking result. - */ - protected static Method determineScalingMethod(int targetWidth, - int targetHeight, float ratio) { - // Get the primary dimension based on the orientation of the image - int length = (ratio <= 1 ? targetWidth : targetHeight); - - // Default to speed - Method result = Method.SPEED; - - // Figure out which scalingMethod should be used - if (length <= Scalr.THRESHOLD_QUALITY_BALANCED) - result = Method.QUALITY; - else if (length <= Scalr.THRESHOLD_BALANCED_SPEED) - result = Method.BALANCED; - - if (DEBUG) - log(2, "AUTOMATIC scaling method selected: %s", result.name()); - - return result; - } - - /** - * Used to implement a straight-forward image-scaling operation using Java - * 2D. - *

- * This method uses the Oracle-encouraged method of - * Graphics2D.drawImage(...) to scale the given image with the - * given interpolation hint. - * - * @param src - * The image that will be scaled. - * @param targetWidth - * The target width for the scaled image. - * @param targetHeight - * The target height for the scaled image. - * @param interpolationHintValue - * The {@link RenderingHints} interpolation value used to - * indicate the method that {@link Graphics2D} should use when - * scaling the image. - * - * @return the result of scaling the original src to the given - * dimensions using the given interpolation method. - */ - protected static BufferedImage scaleImage(BufferedImage src, - int targetWidth, int targetHeight, Object interpolationHintValue) { - // Setup the rendering resources to match the source image's - BufferedImage result = createOptimalImage(src, targetWidth, - targetHeight); - Graphics2D resultGraphics = result.createGraphics(); - - // Scale the image to the new buffer using the specified rendering hint. - resultGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - interpolationHintValue); - resultGraphics.drawImage(src, 0, 0, targetWidth, targetHeight, null); - - // Just to be clean, explicitly dispose our temporary graphics object - resultGraphics.dispose(); - - // Return the scaled image to the caller. - return result; - } - - /** - * Used to implement Chris Campbell's incremental-scaling algorithm: http://today.java.net/pub/a/today/2007/04/03/perils - * -of-image-getscaledinstance.html. - *

- * Modifications to the original algorithm are variable names and comments - * added for clarity and the hard-coding of using BICUBIC interpolation as - * well as the explicit "flush()" operation on the interim BufferedImage - * instances to avoid resource leaking. - * - * @param src - * The image that will be scaled. - * @param targetWidth - * The target width for the scaled image. - * @param targetHeight - * The target height for the scaled image. - * @param interpolationHintValue - * The {@link RenderingHints} interpolation value used to - * indicate the method that {@link Graphics2D} should use when - * scaling the image. - * - * @return an image scaled to the given dimensions using the given rendering - * hint. - */ - protected static BufferedImage scaleImageIncrementally(BufferedImage src, - int targetWidth, int targetHeight, Object interpolationHintValue) { - boolean hasReassignedSrc = false; - int incrementCount = 0; - int currentWidth = src.getWidth(); - int currentHeight = src.getHeight(); - - do { - /* - * If the current width is bigger than our target, cut it in half - * and sample again. - */ - if (currentWidth > targetWidth) { - currentWidth /= 2; - - /* - * If we cut the width too far it means we are on our last - * iteration. Just set it to the target width and finish up. - */ - if (currentWidth < targetWidth) - currentWidth = targetWidth; - } - - /* - * If the current height is bigger than our target, cut it in half - * and sample again. - */ - - if (currentHeight > targetHeight) { - currentHeight /= 2; - - /* - * If we cut the height too far it means we are on our last - * iteration. Just set it to the target height and finish up. - */ - - if (currentHeight < targetHeight) - currentHeight = targetHeight; - } - - // Render the incremental scaled image. - BufferedImage incrementalImage = scaleImage(src, currentWidth, - currentHeight, interpolationHintValue); - - /* - * Before re-assigning our interim (partially scaled) - * incrementalImage to be the new src image before we iterate around - * again to process it down further, we want to flush() the previous - * src image IF (and only IF) it was one of our own temporary - * BufferedImages created during this incremental down-sampling - * cycle. If it wasn't one of ours, then it was the original - * caller-supplied BufferedImage in which case we don't want to - * flush() it and just leave it alone. - */ - if (hasReassignedSrc) - src.flush(); - - /* - * Now treat our incremental partially scaled image as the src image - * and cycle through our loop again to do another incremental - * scaling of it (if necessary). - */ - src = incrementalImage; - - /* - * Keep track of us re-assigning the original caller-supplied source - * image with one of our interim BufferedImages so we know when to - * explicitly flush the interim "src" on the next cycle through. - */ - hasReassignedSrc = true; - - // Track how many times we go through this cycle to scale the image. - incrementCount++; - } while (currentWidth != targetWidth || currentHeight != targetHeight); - - if (DEBUG) - log(2, "Incrementally Scaled Image in %d steps.", incrementCount); - - /* - * Once the loop has exited, the src image argument is now our scaled - * result image that we want to return. - */ - return src; - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#480/old/Scalr.java b/All/Genesis-NP/Genesis#480/old/Scalr.java deleted file mode 100755 index 0e3b9af..0000000 --- a/All/Genesis-NP/Genesis#480/old/Scalr.java +++ /dev/null @@ -1,2245 +0,0 @@ -/** - * Copyright 2011 The Buzz Media, LLC - * - * 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.imgscalr; - -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.RenderingHints; -import java.awt.Transparency; -import java.awt.color.ColorSpace; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.AreaAveragingScaleFilter; -import java.awt.image.BufferedImage; -import java.awt.image.BufferedImageOp; -import java.awt.image.ColorConvertOp; -import java.awt.image.ColorModel; -import java.awt.image.ConvolveOp; -import java.awt.image.ImagingOpException; -import java.awt.image.IndexColorModel; -import java.awt.image.Kernel; -import java.awt.image.RasterFormatException; -import java.awt.image.RescaleOp; - -import javax.imageio.ImageIO; - -/** - * Class used to implement performant, good-quality and intelligent image - * scaling and manipulation algorithms in native Java 2D. - *

- * This class utilizes the Java2D "best practices" for image manipulation, - * ensuring that all operations (even most passed in {@link BufferedImageOp}s) - * are hardware accelerated if provided by the platform and host-VM. - *

- *

Image Proportions

- * All scaling operations implemented by this class maintain the proportions of - * the original image unless a mode of {@link Mode#FIT_EXACT} is specified; in - * which case the orientation and proportion of the source image is ignored and - * the image is stretched (if necessary) to fit the exact dimensions given. - *

- * When not using {@link Mode#FIT_EXACT}, in order to maintain the - * proportionality of the original images, this class implements the following - * behavior: - *

    - *
  1. If the image is LANDSCAPE-oriented or SQUARE, treat the - * targetWidth as the primary dimension and re-calculate the - * targetHeight regardless of what is passed in.
  2. - *
  3. If image is PORTRAIT-oriented, treat the targetHeight as the - * primary dimension and re-calculate the targetWidth regardless of - * what is passed in.
  4. - *
  5. If a {@link Mode} value of {@link Mode#FIT_TO_WIDTH} or - * {@link Mode#FIT_TO_HEIGHT} is passed in to the resize method, - * the image's orientation is ignored and the scaled image is fit to the - * preferred dimension by using the value passed in by the user for that - * dimension and recalculating the other (regardless of image orientation). This - * is useful, for example, when working with PORTRAIT oriented images that you - * need to all be the same width or visa-versa (e.g. showing user profile - * pictures in a directory listing).
  6. - *
- *

Image Quality

- * This class implements a few different methods for scaling an image, providing - * either the best-looking result, the fastest result or a balanced result - * between the two depending on the scaling hint provided (see {@link Method}). - *

- * This class also implements the incremental scaling algorithm presented by - * Chris Campbell in his Perils of - * Image.getScaledInstance() article in order to give the best-looking - * results to images scaled down below roughly 800px in size (e.g. generating - * thumbnails that aren't blurry). - *

- * The results generated by imgscalr using this method, as compared to a single - * {@link RenderingHints#VALUE_INTERPOLATION_BICUBIC} scale operation look much - * better. - *

- * Only when scaling using the {@link Method#AUTOMATIC} method will this class - * look at the size of the image before selecting an approach to scaling the - * image. If {@link Method#QUALITY} is specified, the best-looking algorithm - * possible is always used. - *

- * Minor modifications are made to Campbell's original implementation in the - * form of: - *

    - *
  1. Instead of accepting a user-supplied interpolation method, - * {@link RenderingHints#VALUE_INTERPOLATION_BICUBIC} interpolation is always - * used. This was done after A/B comparison testing with large images - * down-scaled to thumbnail sizes showed noticeable "blurring" when BILINEAR - * interpolation was used. Given that Campbell's algorithm is only used in - * QUALITY mode when down-scaling, it was determined that the user's expectation - * of a much less blurry picture would require that BICUBIC be the default - * interpolation in order to meet the QUALITY expectation.
  2. - *
  3. After each iteration of the do-while loop that incrementally scales the - * source image down, an explicit effort is made to call - * {@link BufferedImage#flush()} on the interim temporary {@link BufferedImage} - * instances created by the algorithm in an attempt to ensure a more complete GC - * cycle by the VM when cleaning up the temporary instances (this is in addition - * to disposing of the temporary {@link Graphics2D} references as well).
  4. - *
  5. Extensive comments have been added to increase readability of the code.
  6. - *
  7. Variable names have been expanded to increase readability of the code.
  8. - *
- *

- * NOTE: This class does not call {@link BufferedImage#flush()} - * on any of the source images passed in by calling code; it is up to - * the original caller to dispose of their source images when they are no longer - * needed so the VM can most efficiently GC them. - *

Optimized Image Handling

- * Java2D provides support for a number of different image types defined as - * BufferedImage.TYPE_* variables, unfortunately not all image - * types are supported equally in the Java2D rendering pipeline. - *

- * Some more obscure image types either have poor or no support, leading to - * severely degraded quality and processing performance when an attempt is made - * by imgscalr to create a scaled instance of the same type as the - * source image. In many cases, especially when applying {@link BufferedImageOp} - * s, using poorly supported image types can even lead to exceptions or total - * corruption of the image (e.g. solid black image). - *

- * imgscalr specifically accounts for and automatically hands - * ALL of these pain points for you internally by shuffling all - * images into one of two types: - *

    - *
  1. {@link BufferedImage#TYPE_INT_RGB}
  2. - *
  3. {@link BufferedImage#TYPE_INT_ARGB}
  4. - *
- * depending on if the source image utilizes transparency or not. - *

- * This is a recommended approach by the Java2D team for dealing with poorly (or - * non) supported image types. More can be read about this issue here. - *

- * This is also the reason we recommend using - * {@link #apply(BufferedImage, BufferedImageOp...)} to apply your own ops to - * images even if you aren't using imgscalr for anything else. - *

GIF Transparency

- * Unfortunately in Java 6 and earlier, support for GIF's - * {@link IndexColorModel} is sub-par, both in accurate color-selection and in - * maintaining transparency when moving to an image of type - * {@link BufferedImage#TYPE_INT_ARGB}; because of this issue when a GIF image - * is processed by imgscalr and the result saved as a GIF file (instead of PNG), - * it is possible to lose the alpha channel of a transparent image or in the - * case of applying an optional {@link BufferedImageOp}, lose the entire picture - * all together in the result (long standing JDK bugs are filed for all of these - * issues). - *

- * imgscalr currently does nothing to work around this manually because it is a - * defect in the native platform code itself. Fortunately it looks like the - * issues are half-fixed in Java 7 and any manual workarounds we could attempt - * internally are relatively expensive, in the form of hand-creating and setting - * RGB values pixel-by-pixel with a custom {@link ColorModel} in the scaled - * image. This would lead to a very measurable negative impact on performance - * without the caller understanding why. - *

- * Workaround: A workaround to this issue with all version of - * Java is to simply save a GIF as a PNG; no change to your code needs to be - * made except when the image is saved out, e.g. using {@link ImageIO}. - *

- * When a file type of "PNG" is used, both the transparency and high color - * quality will be maintained as the PNG code path in Java2D is superior to the - * GIF implementation. - *

- * If the issue with optional {@link BufferedImageOp}s destroying GIF image - * content is ever fixed in the platform, saving out resulting images as GIFs - * should suddenly start working. - *

- * More can be read about the issue here and here. - *

Logging

- * This class implements all its debug logging via the - * {@link #log(int, String, Object...)} method. At this time logging is done - * directly to System.out via the printf method. This - * allows the logging to be light weight and easy to capture while adding no - * dependencies to the library. - *

- * Implementation of logging in this class is as efficient as possible; avoiding - * any calls to the logger method or passing of arguments if logging is not - * enabled to avoid the (hidden) cost of constructing the Object[] argument for - * the varargs-based method call. - * - * @author Riyad Kalla (software@thebuzzmedia.com) - * @since 1.1 - */ -public class Scalr { - /** - * System property name used to define the debug boolean flag. - *

- * Value is "imgscalr.debug". - */ - public static final String DEBUG_PROPERTY_NAME = "imgscalr.debug"; - - /** - * System property name used to define a custom log prefix. - *

- * Value is "imgscalr.logPrefix". - */ - public static final String LOG_PREFIX_PROPERTY_NAME = "imgscalr.logPrefix"; - - /** - * Flag used to indicate if debugging output has been enabled by setting the - * "imgscalr.debug" system property to true. This - * value will be false if the "imgscalr.debug" - * system property is undefined or set to false. - *

- * This property can be set on startup with:
- * - * -Dimgscalr.debug=true - * or by calling {@link System#setProperty(String, String)} to set a - * new property value for {@link #DEBUG_PROPERTY_NAME} before this class is - * loaded. - *

- * Default value is false. - */ - public static final boolean DEBUG = Boolean.getBoolean(DEBUG_PROPERTY_NAME); - - /** - * Prefix to every log message this library logs. Using a well-defined - * prefix helps make it easier both visually and programmatically to scan - * log files for messages produced by this library. - *

- * This property can be set on startup with:
- * - * -Dimgscalr.logPrefix=<YOUR PREFIX HERE> - * or by calling {@link System#setProperty(String, String)} to set a - * new property value for {@link #LOG_PREFIX_PROPERTY_NAME} before this - * class is loaded. - *

- * Default value is "[imgscalr] " (including the space). - */ - public static final String LOG_PREFIX = System.getProperty( - LOG_PREFIX_PROPERTY_NAME, "[imgscalr] "); - - /** - * A {@link ConvolveOp} using a very light "blur" kernel that acts like an - * anti-aliasing filter (softens the image a bit) when applied to an image. - *

- * A common request by users of the library was that they wished to "soften" - * resulting images when scaling them down drastically. After quite a bit of - * A/B testing, the kernel used by this Op was selected as the closest match - * for the target which was the softer results from the deprecated - * {@link AreaAveragingScaleFilter} (which is used internally by the - * deprecated {@link Image#getScaledInstance(int, int, int)} method in the - * JDK that imgscalr is meant to replace). - *

- * This ConvolveOp uses a 3x3 kernel with the values: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
.0f.08f.0f
.08f.68f.08f
.0f.08f.0f
- *

- * For those that have worked with ConvolveOps before, this Op uses the - * {@link ConvolveOp#EDGE_NO_OP} instruction to not process the pixels along - * the very edge of the image (otherwise EDGE_ZERO_FILL would create a - * black-border around the image). If you have not worked with a ConvolveOp - * before, it just means this default OP will "do the right thing" and not - * give you garbage results. - *

- * This ConvolveOp uses no {@link RenderingHints} values as internally the - * {@link ConvolveOp} class only uses hints when doing a color conversion - * between the source and destination {@link BufferedImage} targets. - * imgscalr allows the {@link ConvolveOp} to create its own destination - * image every time, so no color conversion is ever needed and thus no - * hints. - *

Performance

- * Use of this (and other) {@link ConvolveOp}s are hardware accelerated when - * possible. For more information on if your image op is hardware - * accelerated or not, check the source code of the underlying JDK class - * that actually executes the Op code, sun.awt.image.ImagingLib. - *

Known Issues

- * In all versions of Java (tested up to Java 7 preview Build 131), running - * this op against a GIF with transparency and attempting to save the - * resulting image as a GIF results in a corrupted/empty file. The file must - * be saved out as a PNG to maintain the transparency. - * - * @since 3.0 - */ - public static final ConvolveOp OP_ANTIALIAS = new ConvolveOp( - new Kernel(3, 3, new float[] { .0f, .08f, .0f, .08f, .68f, .08f, - .0f, .08f, .0f }), ConvolveOp.EDGE_NO_OP, null); - - /** - * A {@link RescaleOp} used to make any input image 10% darker. - *

- * This operation can be applied multiple times in a row if greater than 10% - * changes in brightness are desired. - * - * @since 4.0 - */ - public static final RescaleOp OP_DARKER = new RescaleOp(0.9f, 0, null); - - /** - * A {@link RescaleOp} used to make any input image 10% brighter. - *

- * This operation can be applied multiple times in a row if greater than 10% - * changes in brightness are desired. - * - * @since 4.0 - */ - public static final RescaleOp OP_BRIGHTER = new RescaleOp(1.1f, 0, null); - - /** - * A {@link ColorConvertOp} used to convert any image to a grayscale color - * palette. - *

- * Applying this op multiple times to the same image has no compounding - * effects. - * - * @since 4.0 - */ - public static final ColorConvertOp OP_GRAYSCALE = new ColorConvertOp( - ColorSpace.getInstance(ColorSpace.CS_GRAY), null); - - /** - * Static initializer used to prepare some of the variables used by this - * class. - */ - static { - log(0, null, "Debug output ENABLED"); - } - - /** - * Used to define the different scaling hints that the algorithm can use. - * - * @author Riyad Kalla (software@thebuzzmedia.com) - * @since 1.1 - */ - public static enum Method { - /** - * Used to indicate that the scaling implementation should decide which - * method to use in order to get the best looking scaled image in the - * least amount of time. - *

- * The scaling algorithm will use the - * {@link Scalr#THRESHOLD_QUALITY_BALANCED} or - * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds as cut-offs to - * decide between selecting the QUALITY, - * BALANCED or SPEED scaling algorithms. - *

- * By default the thresholds chosen will give nearly the best looking - * result in the fastest amount of time. We intend this method to work - * for 80% of people looking to scale an image quickly and get a good - * looking result. - */ - AUTOMATIC, - /** - * Used to indicate that the scaling implementation should scale as fast - * as possible and return a result. For smaller images (800px in size) - * this can result in noticeable aliasing but it can be a few magnitudes - * times faster than using the QUALITY method. - */ - SPEED, - /** - * Used to indicate that the scaling implementation should use a scaling - * operation balanced between SPEED and QUALITY. Sometimes SPEED looks - * too low quality to be useful (e.g. text can become unreadable when - * scaled using SPEED) but using QUALITY mode will increase the - * processing time too much. This mode provides a "better than SPEED" - * quality in a "less than QUALITY" amount of time. - */ - BALANCED, - /** - * Used to indicate that the scaling implementation should do everything - * it can to create as nice of a result as possible. This approach is - * most important for smaller pictures (800px or smaller) and less - * important for larger pictures as the difference between this method - * and the SPEED method become less and less noticeable as the - * source-image size increases. Using the AUTOMATIC method will - * automatically prefer the QUALITY method when scaling an image down - * below 800px in size. - */ - QUALITY; - } - - /** - * Used to define the different modes of resizing that the algorithm can - * use. - * - * @author Riyad Kalla (software@thebuzzmedia.com) - * @since 3.1 - */ - public static enum Mode { - /** - * Used to indicate that the scaling implementation should calculate - * dimensions for the resultant image by looking at the image's - * orientation and generating proportional dimensions that best fit into - * the target width and height given - * - * See "Image Proportions" in the {@link Scalr} class description for - * more detail. - */ - AUTOMATIC, - /** - * Used to fit the image to the exact dimensions given regardless of the - * image's proportions. If the dimensions are not proportionally - * correct, this will introduce vertical or horizontal stretching to the - * image. - *

- * It is recommended that you use one of the other FIT_TO - * modes or {@link Mode#AUTOMATIC} if you want the image to look - * correct, but if dimension-fitting is the #1 priority regardless of - * how it makes the image look, that is what this mode is for. - */ - FIT_EXACT, - /** - * Used to indicate that the scaling implementation should calculate - * dimensions for the resultant image that best-fit within the given - * width, regardless of the orientation of the image. - */ - FIT_TO_WIDTH, - /** - * Used to indicate that the scaling implementation should calculate - * dimensions for the resultant image that best-fit within the given - * height, regardless of the orientation of the image. - */ - FIT_TO_HEIGHT; - } - - /** - * Used to define the different types of rotations that can be applied to an - * image during a resize operation. - * - * @author Riyad Kalla (software@thebuzzmedia.com) - * @since 3.2 - */ - public static enum Rotation { - /** - * 90-degree, clockwise rotation (to the right). This is equivalent to a - * quarter-turn of the image to the right; moving the picture on to its - * right side. - */ - CW_90, - /** - * 180-degree, clockwise rotation (to the right). This is equivalent to - * 1 half-turn of the image to the right; rotating the picture around - * until it is upside down from the original position. - */ - CW_180, - /** - * 270-degree, clockwise rotation (to the right). This is equivalent to - * a quarter-turn of the image to the left; moving the picture on to its - * left side. - */ - CW_270, - /** - * Flip the image horizontally by reflecting it around the y axis. - *

- * This is not a standard rotation around a center point, but instead - * creates the mirrored reflection of the image horizontally. - *

- * More specifically, the vertical orientation of the image stays the - * same (the top stays on top, and the bottom on bottom), but the right - * and left sides flip. This is different than a standard rotation where - * the top and bottom would also have been flipped. - */ - FLIP_HORZ, - /** - * Flip the image vertically by reflecting it around the x axis. - *

- * This is not a standard rotation around a center point, but instead - * creates the mirrored reflection of the image vertically. - *

- * More specifically, the horizontal orientation of the image stays the - * same (the left stays on the left and the right stays on the right), - * but the top and bottom sides flip. This is different than a standard - * rotation where the left and right would also have been flipped. - */ - FLIP_VERT; - } - - /** - * Threshold (in pixels) at which point the scaling operation using the - * {@link Method#AUTOMATIC} method will decide if a {@link Method#BALANCED} - * method will be used (if smaller than or equal to threshold) or a - * {@link Method#SPEED} method will be used (if larger than threshold). - *

- * The bigger the image is being scaled to, the less noticeable degradations - * in the image becomes and the faster algorithms can be selected. - *

- * The value of this threshold (1600) was chosen after visual, by-hand, A/B - * testing between different types of images scaled with this library; both - * photographs and screenshots. It was determined that images below this - * size need to use a {@link Method#BALANCED} scale method to look decent in - * most all cases while using the faster {@link Method#SPEED} method for - * images bigger than this threshold showed no noticeable degradation over a - * BALANCED scale. - */ - public static final int THRESHOLD_BALANCED_SPEED = 1600; - - /** - * Threshold (in pixels) at which point the scaling operation using the - * {@link Method#AUTOMATIC} method will decide if a {@link Method#QUALITY} - * method will be used (if smaller than or equal to threshold) or a - * {@link Method#BALANCED} method will be used (if larger than threshold). - *

- * The bigger the image is being scaled to, the less noticeable degradations - * in the image becomes and the faster algorithms can be selected. - *

- * The value of this threshold (800) was chosen after visual, by-hand, A/B - * testing between different types of images scaled with this library; both - * photographs and screenshots. It was determined that images below this - * size need to use a {@link Method#QUALITY} scale method to look decent in - * most all cases while using the faster {@link Method#BALANCED} method for - * images bigger than this threshold showed no noticeable degradation over a - * QUALITY scale. - */ - public static final int THRESHOLD_QUALITY_BALANCED = 800; - - /** - * Used to apply, in the order given, 1 or more {@link BufferedImageOp}s to - * a given {@link BufferedImage} and return the result. - *

- * Feature: This implementation works around a - * decade-old JDK bug that can cause a {@link RasterFormatException} - * when applying a perfectly valid {@link BufferedImageOp}s to images. - *

- * Feature: This implementation also works around - * {@link BufferedImageOp}s failing to apply and throwing - * {@link ImagingOpException}s when run against a src image - * type that is poorly supported. Unfortunately using {@link ImageIO} and - * standard Java methods to load images provides no consistency in getting - * images in well-supported formats. This method automatically accounts and - * corrects for all those problems (if necessary). - *

- * It is recommended you always use this method to apply any - * {@link BufferedImageOp}s instead of relying on directly using the - * {@link BufferedImageOp#filter(BufferedImage, BufferedImage)} method. - *

- * Performance: Not all {@link BufferedImageOp}s are - * hardware accelerated operations, but many of the most popular (like - * {@link ConvolveOp}) are. For more information on if your image op is - * hardware accelerated or not, check the source code of the underlying JDK - * class that actually executes the Op code, sun.awt.image.ImagingLib. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will have the ops applied to it. - * @param ops - * 1 or more ops to apply to the image. - * - * @return a new {@link BufferedImage} that represents the src - * with all the given operations applied to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if ops is null or empty. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage apply(BufferedImage src, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (ops == null || ops.length == 0) - throw new IllegalArgumentException("ops cannot be null or empty"); - - int type = src.getType(); - - /* - * Ensure the src image is in the best supported image type before we - * continue, otherwise it is possible our calls below to getBounds2D and - * certainly filter(...) may fail if not. - * - * Java2D makes an attempt at applying most BufferedImageOps using - * hardware acceleration via the ImagingLib internal library. - * - * Unfortunately may of the BufferedImageOp are written to simply fail - * with an ImagingOpException if the operation cannot be applied with no - * additional information about what went wrong or attempts at - * re-applying it in different ways. - * - * This is assuming the failing BufferedImageOp even returns a null - * image after failing to apply; some simply return a corrupted/black - * image that result in no exception and it is up to the user to - * discover this. - * - * In internal testing, EVERY failure I've ever seen was the result of - * the source image being in a poorly-supported BufferedImage Type like - * BGR or ABGR (even though it was loaded with ImageIO). - * - * To avoid this nasty/stupid surprise with BufferedImageOps, we always - * ensure that the src image starts in an optimally supported format - * before we try and apply the filter. - */ - if (!(type == BufferedImage.TYPE_INT_RGB || type == BufferedImage.TYPE_INT_ARGB)) - src = copyToOptimalImage(src); - - if (DEBUG) - log(0, "Applying %d BufferedImageOps...", ops.length); - - boolean hasReassignedSrc = false; - - for (int i = 0; i < ops.length; i++) { - long subT = System.currentTimeMillis(); - BufferedImageOp op = ops[i]; - - // Skip null ops instead of throwing an exception. - if (op == null) - continue; - - if (DEBUG) - log(1, "Applying BufferedImageOp [class=%s, toString=%s]...", - op.getClass(), op.toString()); - - /* - * Must use op.getBounds instead of src.getWidth and src.getHeight - * because we are trying to create an image big enough to hold the - * result of this operation (which may be to scale the image - * smaller), in that case the bounds reported by this op and the - * bounds reported by the source image will be different. - */ - Rectangle2D resultBounds = op.getBounds2D(src); - - // Watch out for flaky/misbehaving ops that fail to work right. - if (resultBounds == null) - throw new ImagingOpException( - "BufferedImageOp [" - + op.toString() - + "] getBounds2D(src) returned null bounds for the target image; this should not happen and indicates a problem with application of this type of op."); - - /* - * We must manually create the target image; we cannot rely on the - * null-destination filter() method to create a valid destination - * for us thanks to this JDK bug that has been filed for almost a - * decade: - * http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4965606 - */ - BufferedImage dest = createOptimalImage(src, - (int) Math.round(resultBounds.getWidth()), - (int) Math.round(resultBounds.getHeight())); - - // Perform the operation, update our result to return. - BufferedImage result = op.filter(src, dest); - - /* - * Flush the 'src' image ONLY IF it is one of our interim temporary - * images being used when applying 2 or more operations back to - * back. We never want to flush the original image passed in. - */ - if (hasReassignedSrc) - src.flush(); - - /* - * Incase there are more operations to perform, update what we - * consider the 'src' reference to our last result so on the next - * iteration the next op is applied to this result and not back - * against the original src passed in. - */ - src = result; - - /* - * Keep track of when we re-assign 'src' to an interim temporary - * image, so we know when we can explicitly flush it and clean up - * references on future iterations. - */ - hasReassignedSrc = true; - - if (DEBUG) - log(1, - "Applied BufferedImageOp in %d ms, result [width=%d, height=%d]", - System.currentTimeMillis() - subT, result.getWidth(), - result.getHeight()); - } - - if (DEBUG) - log(0, "All %d BufferedImageOps applied in %d ms", ops.length, - System.currentTimeMillis() - t); - - return src; - } - - /** - * Used to crop the given src image from the top-left corner - * and applying any optional {@link BufferedImageOp}s to the result before - * returning it. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image to crop. - * @param width - * The width of the bounding cropping box. - * @param height - * The height of the bounding cropping box. - * @param ops - * 0 or more ops to apply to the image. If - * null or empty then src is return - * unmodified. - * - * @return a new {@link BufferedImage} representing the cropped region of - * the src image with any optional operations applied - * to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if any coordinates of the bounding crop box is invalid within - * the bounds of the src image (e.g. negative or - * too big). - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage crop(BufferedImage src, int width, int height, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - return crop(src, 0, 0, width, height, ops); - } - - /** - * Used to crop the given src image and apply any optional - * {@link BufferedImageOp}s to it before returning the result. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image to crop. - * @param x - * The x-coordinate of the top-left corner of the bounding box - * used for cropping. - * @param y - * The y-coordinate of the top-left corner of the bounding box - * used for cropping. - * @param width - * The width of the bounding cropping box. - * @param height - * The height of the bounding cropping box. - * @param ops - * 0 or more ops to apply to the image. If - * null or empty then src is return - * unmodified. - * - * @return a new {@link BufferedImage} representing the cropped region of - * the src image with any optional operations applied - * to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if any coordinates of the bounding crop box is invalid within - * the bounds of the src image (e.g. negative or - * too big). - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage crop(BufferedImage src, int x, int y, - int width, int height, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (x < 0 || y < 0 || width < 0 || height < 0) - throw new IllegalArgumentException("Invalid crop bounds: x [" + x - + "], y [" + y + "], width [" + width + "] and height [" - + height + "] must all be >= 0"); - - int srcWidth = src.getWidth(); - int srcHeight = src.getHeight(); - - if ((x + width) > srcWidth) - throw new IllegalArgumentException( - "Invalid crop bounds: x + width [" + (x + width) - + "] must be <= src.getWidth() [" + srcWidth + "]"); - if ((y + height) > srcHeight) - throw new IllegalArgumentException( - "Invalid crop bounds: y + height [" + (y + height) - + "] must be <= src.getHeight() [" + srcHeight - + "]"); - - if (DEBUG) - log(0, - "Cropping Image [width=%d, height=%d] to [x=%d, y=%d, width=%d, height=%d]...", - srcWidth, srcHeight, x, y, width, height); - - // Create a target image of an optimal type to render into. - BufferedImage result = createOptimalImage(src, width, height); - Graphics g = result.getGraphics(); - - /* - * Render the region specified by our crop bounds from the src image - * directly into our result image (which is the exact size of the crop - * region). - */ - g.drawImage(src, 0, 0, width, height, x, y, (x + width), (y + height), - null); - g.dispose(); - - if (DEBUG) - log(0, "Cropped Image in %d ms", System.currentTimeMillis() - t); - - // Apply any optional operations (if specified). - if (ops != null && ops.length > 0) - result = apply(result, ops); - - return result; - } - - /** - * Used to apply padding around the edges of an image using - * {@link Color#BLACK} to fill the extra padded space and then return the - * result. - *

- * The amount of padding specified is applied to all sides; - * more specifically, a padding of 2 would add 2 - * extra pixels of space (filled by the given color) on the - * top, bottom, left and right sides of the resulting image causing the - * result to be 4 pixels wider and 4 pixels taller than the src - * image. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image the padding will be added to. - * @param padding - * The number of pixels of padding to add to each side in the - * resulting image. If this value is 0 then - * src is returned unmodified. - * @param ops - * 0 or more ops to apply to the image. If - * null or empty then src is return - * unmodified. - * - * @return a new {@link BufferedImage} representing src with - * the given padding applied to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if padding is < 1. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage pad(BufferedImage src, int padding, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - return pad(src, padding, Color.BLACK); - } - - /** - * Used to apply padding around the edges of an image using the given color - * to fill the extra padded space and then return the result. {@link Color}s - * using an alpha channel (i.e. transparency) are supported. - *

- * The amount of padding specified is applied to all sides; - * more specifically, a padding of 2 would add 2 - * extra pixels of space (filled by the given color) on the - * top, bottom, left and right sides of the resulting image causing the - * result to be 4 pixels wider and 4 pixels taller than the src - * image. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image the padding will be added to. - * @param padding - * The number of pixels of padding to add to each side in the - * resulting image. If this value is 0 then - * src is returned unmodified. - * @param color - * The color to fill the padded space with. {@link Color}s using - * an alpha channel (i.e. transparency) are supported. - * @param ops - * 0 or more ops to apply to the image. If - * null or empty then src is return - * unmodified. - * - * @return a new {@link BufferedImage} representing src with - * the given padding applied to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if padding is < 1. - * @throws IllegalArgumentException - * if color is null. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage pad(BufferedImage src, int padding, - Color color, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (padding < 1) - throw new IllegalArgumentException("padding [" + padding - + "] must be > 0"); - if (color == null) - throw new IllegalArgumentException("color cannot be null"); - - int srcWidth = src.getWidth(); - int srcHeight = src.getHeight(); - - /* - * Double the padding to account for all sides of the image. More - * specifically, if padding is "1" we add 2 pixels to width and 2 to - * height, so we have 1 new pixel of padding all the way around our - * image. - */ - int sizeDiff = (padding * 2); - int newWidth = srcWidth + sizeDiff; - int newHeight = srcHeight + sizeDiff; - - if (DEBUG) - log(0, - "Padding Image from [originalWidth=%d, originalHeight=%d, padding=%d] to [newWidth=%d, newHeight=%d]...", - srcWidth, srcHeight, padding, newWidth, newHeight); - - boolean colorHasAlpha = (color.getAlpha() != 255); - boolean imageHasAlpha = (src.getTransparency() != BufferedImage.OPAQUE); - - BufferedImage result; - - /* - * We need to make sure our resulting image that we render into contains - * alpha if either our original image OR the padding color we are using - * contain it. - */ - if (colorHasAlpha || imageHasAlpha) { - if (DEBUG) - log(1, - "Transparency FOUND in source image or color, using ARGB image type..."); - - result = new BufferedImage(newWidth, newHeight, - BufferedImage.TYPE_INT_ARGB); - } else { - if (DEBUG) - log(1, - "Transparency NOT FOUND in source image or color, using RGB image type..."); - - result = new BufferedImage(newWidth, newHeight, - BufferedImage.TYPE_INT_RGB); - } - - Graphics g = result.getGraphics(); - - // "Clear" the background of the new image with our padding color first. - g.setColor(color); - g.fillRect(0, 0, newWidth, newHeight); - - // Draw the image into the center of the new padded image. - g.drawImage(src, padding, padding, null); - g.dispose(); - - if (DEBUG) - log(0, "Padding Applied in %d ms", System.currentTimeMillis() - t); - - // Apply any optional operations (if specified). - if (ops != null && ops.length > 0) - result = apply(result, ops); - - return result; - } - - /** - * Resize a given image (maintaining its original proportion) to a width and - * height no bigger than targetSize and apply the given - * {@link BufferedImageOp}s (if any) to the result before returning it. - *

- * A scaling method of {@link Method#AUTOMATIC} and mode of - * {@link Mode#AUTOMATIC} are used. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param targetSize - * The target width and height (square) that you wish the image - * to fit within. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if targetSize is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage resize(BufferedImage src, int targetSize, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetSize, - targetSize, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to a width and - * height no bigger than targetSize using the given scaling - * method and apply the given {@link BufferedImageOp}s (if any) to the - * result before returning it. - *

- * A mode of {@link Mode#AUTOMATIC} is used. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param scalingMethod - * The method used for scaling the image; preferring speed to - * quality or a balance of both. - * @param targetSize - * The target width and height (square) that you wish the image - * to fit within. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if scalingMethod is null. - * @throws IllegalArgumentException - * if targetSize is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Method - */ - public static BufferedImage resize(BufferedImage src, Method scalingMethod, - int targetSize, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, scalingMethod, Mode.AUTOMATIC, targetSize, - targetSize, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to a width and - * height no bigger than targetSize (or fitting the image to - * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode} - * specified) and apply the given {@link BufferedImageOp}s (if any) to the - * result before returning it. - *

- * A scaling method of {@link Method#AUTOMATIC} is used. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param resizeMode - * Used to indicate how imgscalr should calculate the final - * target size for the image, either fitting the image to the - * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image - * to the given height ({@link Mode#FIT_TO_HEIGHT}). If - * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate - * proportional dimensions for the scaled image based on its - * orientation (landscape, square or portrait). Unless you have - * very specific size requirements, most of the time you just - * want to use {@link Mode#AUTOMATIC} to "do the right thing". - * @param targetSize - * The target width and height (square) that you wish the image - * to fit within. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if resizeMode is null. - * @throws IllegalArgumentException - * if targetSize is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Mode - */ - public static BufferedImage resize(BufferedImage src, Mode resizeMode, - int targetSize, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, Method.AUTOMATIC, resizeMode, targetSize, - targetSize, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to a width and - * height no bigger than targetSize (or fitting the image to - * the given WIDTH or HEIGHT explicitly, depending on the {@link Mode} - * specified) using the given scaling method and apply the given - * {@link BufferedImageOp}s (if any) to the result before returning it. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param scalingMethod - * The method used for scaling the image; preferring speed to - * quality or a balance of both. - * @param resizeMode - * Used to indicate how imgscalr should calculate the final - * target size for the image, either fitting the image to the - * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image - * to the given height ({@link Mode#FIT_TO_HEIGHT}). If - * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate - * proportional dimensions for the scaled image based on its - * orientation (landscape, square or portrait). Unless you have - * very specific size requirements, most of the time you just - * want to use {@link Mode#AUTOMATIC} to "do the right thing". - * @param targetSize - * The target width and height (square) that you wish the image - * to fit within. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if scalingMethod is null. - * @throws IllegalArgumentException - * if resizeMode is null. - * @throws IllegalArgumentException - * if targetSize is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Method - * @see Mode - */ - public static BufferedImage resize(BufferedImage src, Method scalingMethod, - Mode resizeMode, int targetSize, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, scalingMethod, resizeMode, targetSize, targetSize, - ops); - } - - /** - * Resize a given image (maintaining its original proportion) to the target - * width and height and apply the given {@link BufferedImageOp}s (if any) to - * the result before returning it. - *

- * A scaling method of {@link Method#AUTOMATIC} and mode of - * {@link Mode#AUTOMATIC} are used. - *

- * TIP: See the class description to understand how this - * class handles recalculation of the targetWidth or - * targetHeight depending on the image's orientation in order - * to maintain the original proportion. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param targetWidth - * The target width that you wish the image to have. - * @param targetHeight - * The target height that you wish the image to have. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if targetWidth is < 0 or if - * targetHeight is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - */ - public static BufferedImage resize(BufferedImage src, int targetWidth, - int targetHeight, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, Method.AUTOMATIC, Mode.AUTOMATIC, targetWidth, - targetHeight, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to the target - * width and height using the given scaling method and apply the given - * {@link BufferedImageOp}s (if any) to the result before returning it. - *

- * A mode of {@link Mode#AUTOMATIC} is used. - *

- * TIP: See the class description to understand how this - * class handles recalculation of the targetWidth or - * targetHeight depending on the image's orientation in order - * to maintain the original proportion. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param scalingMethod - * The method used for scaling the image; preferring speed to - * quality or a balance of both. - * @param targetWidth - * The target width that you wish the image to have. - * @param targetHeight - * The target height that you wish the image to have. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if scalingMethod is null. - * @throws IllegalArgumentException - * if targetWidth is < 0 or if - * targetHeight is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Method - */ - public static BufferedImage resize(BufferedImage src, Method scalingMethod, - int targetWidth, int targetHeight, BufferedImageOp... ops) { - return resize(src, scalingMethod, Mode.AUTOMATIC, targetWidth, - targetHeight, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to the target - * width and height (or fitting the image to the given WIDTH or HEIGHT - * explicitly, depending on the {@link Mode} specified) and apply the given - * {@link BufferedImageOp}s (if any) to the result before returning it. - *

- * A scaling method of {@link Method#AUTOMATIC} is used. - *

- * TIP: See the class description to understand how this - * class handles recalculation of the targetWidth or - * targetHeight depending on the image's orientation in order - * to maintain the original proportion. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param resizeMode - * Used to indicate how imgscalr should calculate the final - * target size for the image, either fitting the image to the - * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image - * to the given height ({@link Mode#FIT_TO_HEIGHT}). If - * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate - * proportional dimensions for the scaled image based on its - * orientation (landscape, square or portrait). Unless you have - * very specific size requirements, most of the time you just - * want to use {@link Mode#AUTOMATIC} to "do the right thing". - * @param targetWidth - * The target width that you wish the image to have. - * @param targetHeight - * The target height that you wish the image to have. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if resizeMode is null. - * @throws IllegalArgumentException - * if targetWidth is < 0 or if - * targetHeight is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Mode - */ - public static BufferedImage resize(BufferedImage src, Mode resizeMode, - int targetWidth, int targetHeight, BufferedImageOp... ops) - throws IllegalArgumentException, ImagingOpException { - return resize(src, Method.AUTOMATIC, resizeMode, targetWidth, - targetHeight, ops); - } - - /** - * Resize a given image (maintaining its original proportion) to the target - * width and height (or fitting the image to the given WIDTH or HEIGHT - * explicitly, depending on the {@link Mode} specified) using the given - * scaling method and apply the given {@link BufferedImageOp}s (if any) to - * the result before returning it. - *

- * TIP: See the class description to understand how this - * class handles recalculation of the targetWidth or - * targetHeight depending on the image's orientation in order - * to maintain the original proportion. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will be scaled. - * @param scalingMethod - * The method used for scaling the image; preferring speed to - * quality or a balance of both. - * @param resizeMode - * Used to indicate how imgscalr should calculate the final - * target size for the image, either fitting the image to the - * given width ({@link Mode#FIT_TO_WIDTH}) or fitting the image - * to the given height ({@link Mode#FIT_TO_HEIGHT}). If - * {@link Mode#AUTOMATIC} is passed in, imgscalr will calculate - * proportional dimensions for the scaled image based on its - * orientation (landscape, square or portrait). Unless you have - * very specific size requirements, most of the time you just - * want to use {@link Mode#AUTOMATIC} to "do the right thing". - * @param targetWidth - * The target width that you wish the image to have. - * @param targetHeight - * The target height that you wish the image to have. - * @param ops - * 0 or more optional image operations (e.g. - * sharpen, blur, etc.) that can be applied to the final result - * before returning the image. - * - * @return a new {@link BufferedImage} representing the scaled - * src image. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if scalingMethod is null. - * @throws IllegalArgumentException - * if resizeMode is null. - * @throws IllegalArgumentException - * if targetWidth is < 0 or if - * targetHeight is < 0. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Method - * @see Mode - */ - public static BufferedImage resize(BufferedImage src, Method scalingMethod, - Mode resizeMode, int targetWidth, int targetHeight, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (targetWidth < 0) - throw new IllegalArgumentException("targetWidth must be >= 0"); - if (targetHeight < 0) - throw new IllegalArgumentException("targetHeight must be >= 0"); - if (scalingMethod == null) - throw new IllegalArgumentException( - "scalingMethod cannot be null. A good default value is Method.AUTOMATIC."); - if (resizeMode == null) - throw new IllegalArgumentException( - "resizeMode cannot be null. A good default value is Mode.AUTOMATIC."); - - BufferedImage result = null; - - int currentWidth = src.getWidth(); - int currentHeight = src.getHeight(); - - // <= 1 is a square or landscape-oriented image, > 1 is a portrait. - float ratio = ((float) currentHeight / (float) currentWidth); - - if (DEBUG) - log(0, - "Resizing Image [size=%dx%d, resizeMode=%s, orientation=%s, ratio(H/W)=%f] to [targetSize=%dx%d]", - currentWidth, currentHeight, resizeMode, - (ratio <= 1 ? "Landscape/Square" : "Portrait"), ratio, - targetWidth, targetHeight); - - /* - * First determine if ANY size calculation needs to be done, in the case - * of FIT_EXACT, ignore image proportions and orientation and just use - * what the user sent in, otherwise the proportion of the picture must - * be honored. - * - * The way that is done is to figure out if the image is in a - * LANDSCAPE/SQUARE or PORTRAIT orientation and depending on its - * orientation, use the primary dimension (width for LANDSCAPE/SQUARE - * and height for PORTRAIT) to recalculate the alternative (height and - * width respectively) value that adheres to the existing ratio. - * - * This helps make life easier for the caller as they don't need to - * pre-compute proportional dimensions before calling the API, they can - * just specify the dimensions they would like the image to roughly fit - * within and it will do the right thing without mangling the result. - */ - if (resizeMode != Mode.FIT_EXACT) { - if ((ratio <= 1 && resizeMode == Mode.AUTOMATIC) - || (resizeMode == Mode.FIT_TO_WIDTH)) { - // First make sure we need to do any work in the first place - if (targetWidth == src.getWidth()) - return src; - - // Save for detailed logging (this is cheap). - int originalTargetHeight = targetHeight; - - /* - * Landscape or Square Orientation: Ignore the given height and - * re-calculate a proportionally correct value based on the - * targetWidth. - */ - targetHeight = Math.round((float) targetWidth * ratio); - - if (DEBUG && originalTargetHeight != targetHeight) - log(1, - "Auto-Corrected targetHeight [from=%d to=%d] to honor image proportions.", - originalTargetHeight, targetHeight); - } else { - // First make sure we need to do any work in the first place - if (targetHeight == src.getHeight()) - return src; - - // Save for detailed logging (this is cheap). - int originalTargetWidth = targetWidth; - - /* - * Portrait Orientation: Ignore the given width and re-calculate - * a proportionally correct value based on the targetHeight. - */ - targetWidth = Math.round((float) targetHeight / ratio); - - if (DEBUG && originalTargetWidth != targetWidth) - log(1, - "Auto-Corrected targetWidth [from=%d to=%d] to honor image proportions.", - originalTargetWidth, targetWidth); - } - } else { - if (DEBUG) - log(1, - "Resize Mode FIT_EXACT used, no width/height checking or re-calculation will be done."); - } - - // If AUTOMATIC was specified, determine the real scaling method. - if (scalingMethod == Scalr.Method.AUTOMATIC) - scalingMethod = determineScalingMethod(targetWidth, targetHeight, - ratio); - - if (DEBUG) - log(1, "Using Scaling Method: %s", scalingMethod); - - // Now we scale the image - if (scalingMethod == Scalr.Method.SPEED) { - result = scaleImage(src, targetWidth, targetHeight, - RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); - } else if (scalingMethod == Scalr.Method.BALANCED) { - result = scaleImage(src, targetWidth, targetHeight, - RenderingHints.VALUE_INTERPOLATION_BILINEAR); - } else if (scalingMethod == Scalr.Method.QUALITY) { - /* - * If we are scaling up (in either width or height - since we know - * the image will stay proportional we just check if either are - * being scaled up), directly using a single BICUBIC will give us - * better results then using Chris Campbell's incremental scaling - * operation (and take a lot less time). - * - * If we are scaling down, we must use the incremental scaling - * algorithm for the best result. - */ - if (targetWidth > currentWidth || targetHeight > currentHeight) { - if (DEBUG) - log(1, - "QUALITY scale-up, a single BICUBIC scale operation will be used..."); - - /* - * BILINEAR and BICUBIC look similar the smaller the scale jump - * upwards is, if the scale is larger BICUBIC looks sharper and - * less fuzzy. But most importantly we have to use BICUBIC to - * match the contract of the QUALITY rendering scalingMethod. - * This note is just here for anyone reading the code and - * wondering how they can speed their own calls up. - */ - result = scaleImage(src, targetWidth, targetHeight, - RenderingHints.VALUE_INTERPOLATION_BICUBIC); - } else { - if (DEBUG) - log(1, - "QUALITY scale-down, incremental scaling will be used..."); - - /* - * Originally we wanted to use BILINEAR interpolation here - * because it takes 1/3rd the time that the BICUBIC - * interpolation does, however, when scaling large images down - * to most sizes bigger than a thumbnail we witnessed noticeable - * "softening" in the resultant image with BILINEAR that would - * be unexpectedly annoying to a user expecting a "QUALITY" - * scale of their original image. Instead BICUBIC was chosen to - * honor the contract of a QUALITY scale of the original image. - */ - result = scaleImageIncrementally(src, targetWidth, - targetHeight, - RenderingHints.VALUE_INTERPOLATION_BICUBIC); - } - } - - if (DEBUG) - log(0, "Resized Image in %d ms", System.currentTimeMillis() - t); - - // Apply any optional operations (if specified). - if (ops != null && ops.length > 0) - result = apply(result, ops); - - return result; - } - - /** - * Used to apply a {@link Rotation} and then 0 or more - * {@link BufferedImageOp}s to a given image and return the result. - *

- * TIP: This operation leaves the original src - * image unmodified. If the caller is done with the src image - * after getting the result of this operation, remember to call - * {@link BufferedImage#flush()} on the src to free up native - * resources and make it easier for the GC to collect the unused image. - * - * @param src - * The image that will have the rotation applied to it. - * @param rotation - * The rotation that will be applied to the image. - * @param ops - * Zero or more optional image operations (e.g. sharpen, blur, - * etc.) that can be applied to the final result before returning - * the image. - * - * @return a new {@link BufferedImage} representing src rotated - * by the given amount and any optional ops applied to it. - * - * @throws IllegalArgumentException - * if src is null. - * @throws IllegalArgumentException - * if rotation is null. - * @throws ImagingOpException - * if one of the given {@link BufferedImageOp}s fails to apply. - * These exceptions bubble up from the inside of most of the - * {@link BufferedImageOp} implementations and are explicitly - * defined on the imgscalr API to make it easier for callers to - * catch the exception (if they are passing along optional ops - * to be applied). imgscalr takes detailed steps to avoid the - * most common pitfalls that will cause {@link BufferedImageOp}s - * to fail, even when using straight forward JDK-image - * operations. - * - * @see Rotation - */ - public static BufferedImage rotate(BufferedImage src, Rotation rotation, - BufferedImageOp... ops) throws IllegalArgumentException, - ImagingOpException { - long t = System.currentTimeMillis(); - - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - if (rotation == null) - throw new IllegalArgumentException("rotation cannot be null"); - - if (DEBUG) - log(0, "Rotating Image [%s]...", rotation); - - /* - * Setup the default width/height values from our image. - * - * In the case of a 90 or 270 (-90) degree rotation, these two values - * flip-flop and we will correct those cases down below in the switch - * statement. - */ - int newWidth = src.getWidth(); - int newHeight = src.getHeight(); - - /* - * We create a transform per operation request as (oddly enough) it ends - * up being faster for the VM to create, use and destroy these instances - * than it is to re-use a single AffineTransform per-thread via the - * AffineTransform.setTo(...) methods which was my first choice (less - * object creation); after benchmarking this explicit case and looking - * at just how much code gets run inside of setTo() I opted for a new AT - * for every rotation. - * - * Besides the performance win, trying to safely reuse AffineTransforms - * via setTo(...) would have required ThreadLocal instances to avoid - * race conditions where two or more resize threads are manipulating the - * same transform before applying it. - * - * Misusing ThreadLocals are one of the #1 reasons for memory leaks in - * server applications and since we have no nice way to hook into the - * init/destroy Servlet cycle or any other initialization cycle for this - * library to automatically call ThreadLocal.remove() to avoid the - * memory leak, it would have made using this library *safely* on the - * server side much harder. - * - * So we opt for creating individual transforms per rotation op and let - * the VM clean them up in a GC. I only clarify all this reasoning here - * for anyone else reading this code and being tempted to reuse the AT - * instances of performance gains; there aren't any AND you get a lot of - * pain along with it. - */ - AffineTransform tx = new AffineTransform(); - - switch (rotation) { - case CW_90: - /* - * A 90 or -90 degree rotation will cause the height and width to - * flip-flop from the original image to the rotated one. - */ - newWidth = src.getHeight(); - newHeight = src.getWidth(); - - // Reminder: newWidth == result.getHeight() at this point - tx.translate(newWidth, 0); - tx.rotate(Math.toRadians(90)); - - break; - - case CW_270: - /* - * A 90 or -90 degree rotation will cause the height and width to - * flip-flop from the original image to the rotated one. - */ - newWidth = src.getHeight(); - newHeight = src.getWidth(); - - // Reminder: newHeight == result.getWidth() at this point - tx.translate(0, newHeight); - tx.rotate(Math.toRadians(-90)); - break; - - case CW_180: - tx.translate(newWidth, newHeight); - tx.rotate(Math.toRadians(180)); - break; - - case FLIP_HORZ: - tx.translate(newWidth, 0); - tx.scale(-1.0, 1.0); - break; - - case FLIP_VERT: - tx.translate(0, newHeight); - tx.scale(1.0, -1.0); - break; - } - - // Create our target image we will render the rotated result to. - BufferedImage result = createOptimalImage(src, newWidth, newHeight); - Graphics2D g2d = (Graphics2D) result.createGraphics(); - - /* - * Render the resultant image to our new rotatedImage buffer, applying - * the AffineTransform that we calculated above during rendering so the - * pixels from the old position are transposed to the new positions in - * the resulting image correctly. - */ - g2d.drawImage(src, tx, null); - g2d.dispose(); - - if (DEBUG) - log(0, "Rotation Applied in %d ms, result [width=%d, height=%d]", - System.currentTimeMillis() - t, result.getWidth(), - result.getHeight()); - - // Apply any optional operations (if specified). - if (ops != null && ops.length > 0) - result = apply(result, ops); - - return result; - } - - /** - * Used to write out a useful and well-formatted log message by any piece of - * code inside of the imgscalr library. - *

- * If a message cannot be logged (logging is disabled) then this method - * returns immediately. - *

- * NOTE: Because Java will auto-box primitive arguments - * into Objects when building out the params array, care should - * be taken not to call this method with primitive values unless - * {@link Scalr#DEBUG} is true; otherwise the VM will be - * spending time performing unnecessary auto-boxing calculations. - * - * @param depth - * The indentation level of the log message. - * @param message - * The log message in format string syntax that will be logged. - * @param params - * The parameters that will be swapped into all the place holders - * in the original messages before being logged. - * - * @see Scalr#LOG_PREFIX - * @see Scalr#LOG_PREFIX_PROPERTY_NAME - */ - protected static void log(int depth, String message, Object... params) { - if (Scalr.DEBUG) { - System.out.print(Scalr.LOG_PREFIX); - - for (int i = 0; i < depth; i++) - System.out.print("\t"); - - System.out.printf(message, params); - System.out.println(); - } - } - - /** - * Used to create a {@link BufferedImage} with the most optimal RGB TYPE ( - * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB} - * ) capable of being rendered into from the given src. The - * width and height of both images will be identical. - *

- * This does not perform a copy of the image data from src into - * the result image; see {@link #copyToOptimalImage(BufferedImage)} for - * that. - *

- * We force all rendering results into one of these two types, avoiding the - * case where a source image is of an unsupported (or poorly supported) - * format by Java2D causing the rendering result to end up looking terrible - * (common with GIFs) or be totally corrupt (e.g. solid black image). - *

- * Originally reported by Magnus Kvalheim from Movellas when scaling certain - * GIF and PNG images. - * - * @param src - * The source image that will be analyzed to determine the most - * optimal image type it can be rendered into. - * - * @return a new {@link BufferedImage} representing the most optimal target - * image type that src can be rendered into. - * - * @see How - * Java2D handles poorly supported image types - * @see Thanks - * to Morten Nobel for implementation hint - */ - protected static BufferedImage createOptimalImage(BufferedImage src) { - return createOptimalImage(src, src.getWidth(), src.getHeight()); - } - - /** - * Used to create a {@link BufferedImage} with the given dimensions and the - * most optimal RGB TYPE ( {@link BufferedImage#TYPE_INT_RGB} or - * {@link BufferedImage#TYPE_INT_ARGB} ) capable of being rendered into from - * the given src. - *

- * This does not perform a copy of the image data from src into - * the result image; see {@link #copyToOptimalImage(BufferedImage)} for - * that. - *

- * We force all rendering results into one of these two types, avoiding the - * case where a source image is of an unsupported (or poorly supported) - * format by Java2D causing the rendering result to end up looking terrible - * (common with GIFs) or be totally corrupt (e.g. solid black image). - *

- * Originally reported by Magnus Kvalheim from Movellas when scaling certain - * GIF and PNG images. - * - * @param src - * The source image that will be analyzed to determine the most - * optimal image type it can be rendered into. - * @param width - * The width of the newly created resulting image. - * @param height - * The height of the newly created resulting image. - * - * @return a new {@link BufferedImage} representing the most optimal target - * image type that src can be rendered into. - * - * @throws IllegalArgumentException - * if width or height are < 0. - * - * @see How - * Java2D handles poorly supported image types - * @see Thanks - * to Morten Nobel for implementation hint - */ - protected static BufferedImage createOptimalImage(BufferedImage src, - int width, int height) throws IllegalArgumentException { - if (width < 0 || height < 0) - throw new IllegalArgumentException("width [" + width - + "] and height [" + height + "] must be >= 0"); - - return new BufferedImage( - width, - height, - (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB - : BufferedImage.TYPE_INT_ARGB)); - } - - /** - * Used to copy a {@link BufferedImage} from a non-optimal type into a new - * {@link BufferedImage} instance of an optimal type (RGB or ARGB). If - * src is already of an optimal type, then it is returned - * unmodified. - *

- * This method is meant to be used by any calling code (imgscalr's or - * otherwise) to convert any inbound image from a poorly supported image - * type into the 2 most well-supported image types in Java2D ( - * {@link BufferedImage#TYPE_INT_RGB} or {@link BufferedImage#TYPE_INT_ARGB} - * ) in order to ensure all subsequent graphics operations are performed as - * efficiently and correctly as possible. - *

- * When using Java2D to work with image types that are not well supported, - * the results can be anything from exceptions bubbling up from the depths - * of Java2D to images being completely corrupted and just returned as solid - * black. - * - * @param src - * The image to copy (if necessary) into an optimally typed - * {@link BufferedImage}. - * - * @return a representation of the src image in an optimally - * typed {@link BufferedImage}, otherwise src if it was - * already of an optimal type. - * - * @throws IllegalArgumentException - * if src is null. - */ - protected static BufferedImage copyToOptimalImage(BufferedImage src) - throws IllegalArgumentException { - if (src == null) - throw new IllegalArgumentException("src cannot be null"); - - // Calculate the type depending on the presence of alpha. - int type = (src.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB - : BufferedImage.TYPE_INT_ARGB); - BufferedImage result = new BufferedImage(src.getWidth(), - src.getHeight(), type); - - // Render the src image into our new optimal source. - Graphics g = result.getGraphics(); - g.drawImage(src, 0, 0, null); - g.dispose(); - - return result; - } - - /** - * Used to determine the scaling {@link Method} that is best suited for - * scaling the image to the targeted dimensions. - *

- * This method is intended to be used to select a specific scaling - * {@link Method} when a {@link Method#AUTOMATIC} method is specified. This - * method utilizes the {@link Scalr#THRESHOLD_QUALITY_BALANCED} and - * {@link Scalr#THRESHOLD_BALANCED_SPEED} thresholds when selecting which - * method should be used by comparing the primary dimension (width or - * height) against the threshold and seeing where the image falls. The - * primary dimension is determined by looking at the orientation of the - * image: landscape or square images use their width and portrait-oriented - * images use their height. - * - * @param targetWidth - * The target width for the scaled image. - * @param targetHeight - * The target height for the scaled image. - * @param ratio - * A height/width ratio used to determine the orientation of the - * image so the primary dimension (width or height) can be - * selected to test if it is greater than or less than a - * particular threshold. - * - * @return the fastest {@link Method} suited for scaling the image to the - * specified dimensions while maintaining a good-looking result. - */ - protected static Method determineScalingMethod(int targetWidth, - int targetHeight, float ratio) { - // Get the primary dimension based on the orientation of the image - int length = (ratio <= 1 ? targetWidth : targetHeight); - - // Default to speed - Method result = Method.SPEED; - - // Figure out which scalingMethod should be used - if (length <= Scalr.THRESHOLD_QUALITY_BALANCED) - result = Method.QUALITY; - else if (length <= Scalr.THRESHOLD_BALANCED_SPEED) - result = Method.BALANCED; - - if (DEBUG) - log(2, "AUTOMATIC scaling method selected: %s", result.name()); - - return result; - } - - /** - * Used to implement a straight-forward image-scaling operation using Java - * 2D. - *

- * This method uses the Oracle-encouraged method of - * Graphics2D.drawImage(...) to scale the given image with the - * given interpolation hint. - * - * @param src - * The image that will be scaled. - * @param targetWidth - * The target width for the scaled image. - * @param targetHeight - * The target height for the scaled image. - * @param interpolationHintValue - * The {@link RenderingHints} interpolation value used to - * indicate the method that {@link Graphics2D} should use when - * scaling the image. - * - * @return the result of scaling the original src to the given - * dimensions using the given interpolation method. - */ - protected static BufferedImage scaleImage(BufferedImage src, - int targetWidth, int targetHeight, Object interpolationHintValue) { - // Setup the rendering resources to match the source image's - BufferedImage result = createOptimalImage(src, targetWidth, - targetHeight); - Graphics2D resultGraphics = result.createGraphics(); - - // Scale the image to the new buffer using the specified rendering hint. - resultGraphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, - interpolationHintValue); - resultGraphics.drawImage(src, 0, 0, targetWidth, targetHeight, null); - - // Just to be clean, explicitly dispose our temporary graphics object - resultGraphics.dispose(); - - // Return the scaled image to the caller. - return result; - } - - /** - * Used to implement Chris Campbell's incremental-scaling algorithm: http://today.java.net/pub/a/today/2007/04/03/perils - * -of-image-getscaledinstance.html. - *

- * Modifications to the original algorithm are variable names and comments - * added for clarity and the hard-coding of using BICUBIC interpolation as - * well as the explicit "flush()" operation on the interim BufferedImage - * instances to avoid resource leaking. - * - * @param src - * The image that will be scaled. - * @param targetWidth - * The target width for the scaled image. - * @param targetHeight - * The target height for the scaled image. - * @param interpolationHintValue - * The {@link RenderingHints} interpolation value used to - * indicate the method that {@link Graphics2D} should use when - * scaling the image. - * - * @return an image scaled to the given dimensions using the given rendering - * hint. - */ - protected static BufferedImage scaleImageIncrementally(BufferedImage src, - int targetWidth, int targetHeight, Object interpolationHintValue) { - boolean hasReassignedSrc = false; - int incrementCount = 0; - int currentWidth = src.getWidth(); - int currentHeight = src.getHeight(); - - do { - /* - * If the current width is bigger than our target, cut it in half - * and sample again. - */ - if (currentWidth > targetWidth) { - currentWidth /= 2; - - /* - * If we cut the width too far it means we are on our last - * iteration. Just set it to the target width and finish up. - */ - if (currentWidth < targetWidth) - currentWidth = targetWidth; - } - - /* - * If the current height is bigger than our target, cut it in half - * and sample again. - */ - - if (currentHeight > targetHeight) { - currentHeight /= 2; - - /* - * If we cut the height too far it means we are on our last - * iteration. Just set it to the target height and finish up. - */ - - if (currentHeight < targetHeight) - currentHeight = targetHeight; - } - - // Render the incremental scaled image. - BufferedImage incrementalImage = scaleImage(src, currentWidth, - currentHeight, interpolationHintValue); - - /* - * Before re-assigning our interim (partially scaled) - * incrementalImage to be the new src image before we iterate around - * again to process it down further, we want to flush() the previous - * src image IF (and only IF) it was one of our own temporary - * BufferedImages created during this incremental down-sampling - * cycle. If it wasn't one of ours, then it was the original - * caller-supplied BufferedImage in which case we don't want to - * flush() it and just leave it alone. - */ - if (hasReassignedSrc) - src.flush(); - - /* - * Now treat our incremental partially scaled image as the src image - * and cycle through our loop again to do another incremental - * scaling of it (if necessary). - */ - src = incrementalImage; - - /* - * Keep track of us re-assigning the original caller-supplied source - * image with one of our interim BufferedImages so we know when to - * explicitly flush the interim "src" on the next cycle through. - */ - hasReassignedSrc = true; - - // Track how many times we go through this cycle to scale the image. - incrementCount++; - } while (currentWidth != targetWidth || currentHeight != targetHeight); - - if (DEBUG) - log(2, "Incrementally Scaled Image in %d steps.", incrementCount); - - /* - * Once the loop has exited, the src image argument is now our scaled - * result image that we want to return. - */ - return src; - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#480/pair.info b/All/Genesis-NP/Genesis#480/pair.info deleted file mode 100755 index bd3f804..0000000 --- a/All/Genesis-NP/Genesis#480/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:480 -SATName:Genesis -modifiedFPath:src/main/java/org/imgscalr/Scalr.java -comSha:1e8b8a2137b200194f599abfb419c7ef4b25e559 -parentComSha:1e8b8a2137b200194f599abfb419c7ef4b25e559^1 -githubUrl:https://github.com/thebuzzmedia/imgscalr -repoName:thebuzzmedia#imgscalr \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#485/comMsg.txt b/All/Genesis-NP/Genesis#485/comMsg.txt deleted file mode 100755 index 7ed7983..0000000 --- a/All/Genesis-NP/Genesis#485/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Null pointer with Query auth when calling a method with no parameters diff --git a/All/Genesis-NP/Genesis#485/diff.diff b/All/Genesis-NP/Genesis#485/diff.diff deleted file mode 100755 index 4585a4e..0000000 --- a/All/Genesis-NP/Genesis#485/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/com/mashape/client/http/HttpClient.java b/src/main/java/com/mashape/client/http/HttpClient.java -index c1bf673..2595312 100644 ---- a/src/main/java/com/mashape/client/http/HttpClient.java -+++ b/src/main/java/com/mashape/client/http/HttpClient.java -@@ -32,0 +33 @@ import java.util.ArrayList; -+import java.util.HashMap; -@@ -88,0 +90,3 @@ public class HttpClient { -+ if (parameters == null) { -+ parameters = new HashMap(); -+ } diff --git a/All/Genesis-NP/Genesis#485/new/HttpClient.java b/All/Genesis-NP/Genesis#485/new/HttpClient.java deleted file mode 100755 index 2595312..0000000 --- a/All/Genesis-NP/Genesis#485/new/HttpClient.java +++ /dev/null @@ -1,207 +0,0 @@ -/* - * - * Mashape Java Client library. - * Copyright (C) 2011 Mashape, Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - * - * - * The author of this software is Mashape, Inc. - * For any question or feedback please contact us at: support@mashape.com - * - */ - -package com.mashape.client.http; - -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.protocol.HTTP; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import com.mashape.client.exceptions.ExceptionConstants; -import com.mashape.client.exceptions.MashapeClientException; -import com.mashape.client.http.auth.Auth; -import com.mashape.client.http.auth.HeaderAuth; -import com.mashape.client.http.auth.QueryAuth; -import com.mashape.client.http.callback.MashapeCallback; -import com.mashape.client.http.ssl.SSLVerifierFactory; -import com.mashape.client.http.utils.MapUtil; -import com.mashape.client.http.utils.RequestPrepareResult; -import com.mashape.client.http.utils.StreamUtils; -import com.mashape.client.http.utils.UrlUtils; - -public class HttpClient { - - public static Thread doRequest(HttpMethod httpMethod, String url, Map parameters, boolean encodeJson, List authHandlers, MashapeCallback callback) { - Thread t = new HttpRequestThread(httpMethod, url, parameters, encodeJson, authHandlers, callback); - t.start(); - return t; - } - - public static Object doRequest(HttpMethod httpMethod, String url, Map parameters, boolean encodeJson, List authHandlers) throws MashapeClientException { - return execRequest(httpMethod, url, parameters, authHandlers, encodeJson, false, null, null); - } - - public static Object doRequest(HttpMethod httpMethod, String url, Map parameters, String clientName, String clientVersion, List authHandlers) throws MashapeClientException { - return execRequest(httpMethod, url, parameters, authHandlers, false, true, clientName, clientVersion); - } - - static Object execRequest(HttpMethod httpMethod, String url, Map parameters, List authHandlers, boolean encodeJson, boolean isConsole, String clientName, String clientVersion) throws MashapeClientException { - if (authHandlers == null) { - authHandlers = new ArrayList(); - } - if (parameters == null) { - parameters = new HashMap(); - } - List

clientHeaders = new LinkedList
(); - // Add headers - if (isConsole) { - clientHeaders = UrlUtils.generateClientHeaders(); - } else { - clientHeaders = UrlUtils.generateClientHeaders(); - } - - // Handle all other auths - for (Auth authHandler : authHandlers) { - if (authHandler instanceof HeaderAuth) { - clientHeaders.add(authHandler.handleHeader()); - } else if (authHandler instanceof QueryAuth) { - parameters.putAll(authHandler.handleParams()); - } - } - - RequestPrepareResult prepareRequest = null; - try { - prepareRequest = UrlUtils.prepareRequest(url, parameters, (httpMethod == HttpMethod.GET) ? false : true); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - - HttpUriRequest request; - - switch (httpMethod) { - case GET: - request = new HttpGet(prepareRequest.getUrl()); - break; - case POST: - request = new HttpPost(prepareRequest.getUrl()); - break; - case PUT: - request = new HttpPut(prepareRequest.getUrl()); - break; - case DELETE: - request = new HttpDeleteWithBody(prepareRequest.getUrl()); - break; - default: - throw new MashapeClientException(ExceptionConstants.EXCEPTION_NOTSUPPORTED_HTTPMETHOD, ExceptionConstants.EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE); - } - - for (Header header : clientHeaders) { - request.addHeader(header); - } - - if (httpMethod != HttpMethod.GET) { - try { - ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8)); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } - - org.apache.http.client.HttpClient client = new DefaultHttpClient(); - configureSSLHttpClient(client); - - HttpResponse httpResponse; - try { - httpResponse = client.execute(request); - } catch (Exception e2) { - throw new RuntimeException(e2); - } - HttpEntity entity = httpResponse.getEntity(); - - if (entity != null) { - InputStream instream; - try { - instream = entity.getContent(); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - if (!encodeJson) { - return instream; - } - String response = StreamUtils.convertStreamToString(instream); - try { - // It may be an object - return new JSONObject(response); - } catch (JSONException e) { - try { - // or an array - return new JSONArray(response); - } catch (JSONException e1) { - throw new MashapeClientException(String.format(ExceptionConstants.EXCEPTION_INVALID_REQUEST,response),ExceptionConstants.EXCEPTION_SYSTEM_ERROR_CODE); - } - } - - } - return null; - } - - private static void configureSSLHttpClient(org.apache.http.client.HttpClient client) { - // Accept any SSL certificate - SSLContext sslContext; - try { - sslContext = SSLContext.getInstance("SSL"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - - try { - sslContext.init(null, new TrustManager[] { SSLVerifierFactory.getCustomSSLVerifier() }, new SecureRandom()); - } catch (KeyManagementException e) { - throw new RuntimeException(e); - } - SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - Scheme https = new Scheme("https", 443, socketFactory); - client.getConnectionManager().getSchemeRegistry().register(https); - } - - - -} diff --git a/All/Genesis-NP/Genesis#485/new/pom.xml b/All/Genesis-NP/Genesis#485/new/pom.xml deleted file mode 100755 index 98e6102..0000000 --- a/All/Genesis-NP/Genesis#485/new/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - 4.0.0 - com.mashape.clients - mashape-java-client - 1.2.3 - mashape-java-client - - UTF-8 - - - - - maven-compiler-plugin - 2.3.1 - - true - 128m - 512m - 1.5 - 1.5 - - - - - - - org.apache.httpcomponents - httpclient - 4.1.1 - - - org.json - json - 20090211 - - - junit - junit - 4.5 - test - - - diff --git a/All/Genesis-NP/Genesis#485/old/HttpClient.java b/All/Genesis-NP/Genesis#485/old/HttpClient.java deleted file mode 100755 index c1bf673..0000000 --- a/All/Genesis-NP/Genesis#485/old/HttpClient.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * - * Mashape Java Client library. - * Copyright (C) 2011 Mashape, Inc. - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Affero General Public License for more details. - * - * You should have received a copy of the GNU Affero General Public License - * along with this program. If not, see . - * - * - * The author of this software is Mashape, Inc. - * For any question or feedback please contact us at: support@mashape.com - * - */ - -package com.mashape.client.http; - -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.security.KeyManagementException; -import java.security.NoSuchAlgorithmException; -import java.security.SecureRandom; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; - -import javax.net.ssl.SSLContext; -import javax.net.ssl.TrustManager; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpResponse; -import org.apache.http.client.entity.UrlEncodedFormEntity; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPost; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.conn.scheme.Scheme; -import org.apache.http.conn.ssl.SSLSocketFactory; -import org.apache.http.impl.client.DefaultHttpClient; -import org.apache.http.protocol.HTTP; -import org.json.JSONArray; -import org.json.JSONException; -import org.json.JSONObject; - -import com.mashape.client.exceptions.ExceptionConstants; -import com.mashape.client.exceptions.MashapeClientException; -import com.mashape.client.http.auth.Auth; -import com.mashape.client.http.auth.HeaderAuth; -import com.mashape.client.http.auth.QueryAuth; -import com.mashape.client.http.callback.MashapeCallback; -import com.mashape.client.http.ssl.SSLVerifierFactory; -import com.mashape.client.http.utils.MapUtil; -import com.mashape.client.http.utils.RequestPrepareResult; -import com.mashape.client.http.utils.StreamUtils; -import com.mashape.client.http.utils.UrlUtils; - -public class HttpClient { - - public static Thread doRequest(HttpMethod httpMethod, String url, Map parameters, boolean encodeJson, List authHandlers, MashapeCallback callback) { - Thread t = new HttpRequestThread(httpMethod, url, parameters, encodeJson, authHandlers, callback); - t.start(); - return t; - } - - public static Object doRequest(HttpMethod httpMethod, String url, Map parameters, boolean encodeJson, List authHandlers) throws MashapeClientException { - return execRequest(httpMethod, url, parameters, authHandlers, encodeJson, false, null, null); - } - - public static Object doRequest(HttpMethod httpMethod, String url, Map parameters, String clientName, String clientVersion, List authHandlers) throws MashapeClientException { - return execRequest(httpMethod, url, parameters, authHandlers, false, true, clientName, clientVersion); - } - - static Object execRequest(HttpMethod httpMethod, String url, Map parameters, List authHandlers, boolean encodeJson, boolean isConsole, String clientName, String clientVersion) throws MashapeClientException { - if (authHandlers == null) { - authHandlers = new ArrayList(); - } - List
clientHeaders = new LinkedList
(); - // Add headers - if (isConsole) { - clientHeaders = UrlUtils.generateClientHeaders(); - } else { - clientHeaders = UrlUtils.generateClientHeaders(); - } - - // Handle all other auths - for (Auth authHandler : authHandlers) { - if (authHandler instanceof HeaderAuth) { - clientHeaders.add(authHandler.handleHeader()); - } else if (authHandler instanceof QueryAuth) { - parameters.putAll(authHandler.handleParams()); - } - } - - RequestPrepareResult prepareRequest = null; - try { - prepareRequest = UrlUtils.prepareRequest(url, parameters, (httpMethod == HttpMethod.GET) ? false : true); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - - HttpUriRequest request; - - switch (httpMethod) { - case GET: - request = new HttpGet(prepareRequest.getUrl()); - break; - case POST: - request = new HttpPost(prepareRequest.getUrl()); - break; - case PUT: - request = new HttpPut(prepareRequest.getUrl()); - break; - case DELETE: - request = new HttpDeleteWithBody(prepareRequest.getUrl()); - break; - default: - throw new MashapeClientException(ExceptionConstants.EXCEPTION_NOTSUPPORTED_HTTPMETHOD, ExceptionConstants.EXCEPTION_NOTSUPPORTED_HTTPMETHOD_CODE); - } - - for (Header header : clientHeaders) { - request.addHeader(header); - } - - if (httpMethod != HttpMethod.GET) { - try { - ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(MapUtil.getList(parameters), HTTP.UTF_8)); - } catch (UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } - - org.apache.http.client.HttpClient client = new DefaultHttpClient(); - configureSSLHttpClient(client); - - HttpResponse httpResponse; - try { - httpResponse = client.execute(request); - } catch (Exception e2) { - throw new RuntimeException(e2); - } - HttpEntity entity = httpResponse.getEntity(); - - if (entity != null) { - InputStream instream; - try { - instream = entity.getContent(); - } catch (Exception e1) { - throw new RuntimeException(e1); - } - if (!encodeJson) { - return instream; - } - String response = StreamUtils.convertStreamToString(instream); - try { - // It may be an object - return new JSONObject(response); - } catch (JSONException e) { - try { - // or an array - return new JSONArray(response); - } catch (JSONException e1) { - throw new MashapeClientException(String.format(ExceptionConstants.EXCEPTION_INVALID_REQUEST,response),ExceptionConstants.EXCEPTION_SYSTEM_ERROR_CODE); - } - } - - } - return null; - } - - private static void configureSSLHttpClient(org.apache.http.client.HttpClient client) { - // Accept any SSL certificate - SSLContext sslContext; - try { - sslContext = SSLContext.getInstance("SSL"); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException(e); - } - - try { - sslContext.init(null, new TrustManager[] { SSLVerifierFactory.getCustomSSLVerifier() }, new SecureRandom()); - } catch (KeyManagementException e) { - throw new RuntimeException(e); - } - SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); - Scheme https = new Scheme("https", 443, socketFactory); - client.getConnectionManager().getSchemeRegistry().register(https); - } - - - -} diff --git a/All/Genesis-NP/Genesis#485/old/pom.xml b/All/Genesis-NP/Genesis#485/old/pom.xml deleted file mode 100755 index 66fc69b..0000000 --- a/All/Genesis-NP/Genesis#485/old/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - - 4.0.0 - com.mashape.clients - mashape-java-client - 1.2.2 - mashape-java-client - - UTF-8 - - - - - maven-compiler-plugin - 2.3.1 - - true - 128m - 512m - 1.5 - 1.5 - - - - - - - org.apache.httpcomponents - httpclient - 4.1.1 - - - org.json - json - 20090211 - - - junit - junit - 4.5 - test - - - diff --git a/All/Genesis-NP/Genesis#485/pair.info b/All/Genesis-NP/Genesis#485/pair.info deleted file mode 100755 index c02d907..0000000 --- a/All/Genesis-NP/Genesis#485/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:485 -SATName:Genesis -modifiedFPath:src/main/java/com/mashape/client/http/HttpClient.java -comSha:3beae8f3373537aed80be0f0fcabdac87c431f2b -parentComSha:3beae8f3373537aed80be0f0fcabdac87c431f2b^1 -githubUrl:https://github.com/Mashape/unirest-java -repoName:Mashape#unirest-java \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#487/new/pom.xml b/All/Genesis-NP/Genesis#487/new/pom.xml deleted file mode 100755 index 577eb25..0000000 --- a/All/Genesis-NP/Genesis#487/new/pom.xml +++ /dev/null @@ -1,210 +0,0 @@ - - - 4.0.0 - - - org.jboss.resteasy - resteasy-jaxrs-all - 3.0.15.Final-SNAPSHOT - ../../pom.xml - - - RESTEASY-TEST-WF10 - jar - RESTEASY-TEST-WF10 - http://maven.apache.org - - - UTF-8 - 10.0.0.Final - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 2.3.2 - - 1.6 - 1.6 - - - - maven-surefire-plugin - 2.12 - - - maven-dependency-plugin - - - unpack - process-test-classes - - unpack - - - - - org.wildfly - wildfly-dist - ${wildfly-version} - zip - false - target - - - - - - - - org.apache.maven.plugins - maven-antrun-plugin - 1.6 - - - unpack resteasy - process-test-classes - - - - - - - - - - - run - - - - - - - - - - - org.jboss.arquillian - arquillian-bom - 1.0.3.Final - import - pom - - - - - - - org.jboss.spec - jboss-javaee-6.0 - 1.0.0.Final - pom - provided - - - org.jboss.resteasy - jaxrs-api - - - - - junit - junit - 4.8.1 - test - - - org.jboss.arquillian.junit - arquillian-junit-container - test - - - org.wildfly - wildfly-arquillian-container-managed - ${dep.arquillian-wildfly.version} - test - - - org.jboss.arquillian.protocol - arquillian-protocol-servlet - test - - - org.jboss.spec.javax.ws.rs - jboss-jaxrs-api_2.0_spec - - - log4j - log4j - provided - - - org.slf4j - slf4j-api - provided - - - org.jboss.resteasy - resteasy-jaxrs - ${project.version} - - - org.jboss.resteasy - resteasy-validator-provider-11 - ${project.version} - - - javax.validation - validation-api - 1.1.0.Final - - - org.hibernate - hibernate-validator - 5.0.1.Final - - - org.hibernate - hibernate-validator-cdi - 5.0.1.Final - - - javax.el - javax.el-api - 2.2.4 - - - org.glassfish.web - javax.el - 2.2.4 - - - org.jboss.spec.javax.xml.bind - jboss-jaxb-api_2.2_spec - 1.0.4.Final - - - org.jboss.resteasy - resteasy-multipart-provider - ${project.version} - - - org.jboss.resteasy - resteasy-jaxb-provider - ${project.version} - test - - - org.jboss.resteasy - resteasy-client - ${project.version} - test - - - diff --git a/All/Genesis-NP/Genesis#488/comMsg.txt b/All/Genesis-NP/Genesis#488/comMsg.txt deleted file mode 100755 index 9d3d162..0000000 --- a/All/Genesis-NP/Genesis#488/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Prevention for NullPointerException in WeightedMediaType diff --git a/All/Genesis-NP/Genesis#488/diff.diff b/All/Genesis-NP/Genesis#488/diff.diff deleted file mode 100755 index 76d326d..0000000 --- a/All/Genesis-NP/Genesis#488/diff.diff +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/WeightedMediaType.java b/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/WeightedMediaType.java -index 19d40e0..1e0d626 100755 ---- a/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/WeightedMediaType.java -+++ b/jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/WeightedMediaType.java -@@ -74 +74 @@ public class WeightedMediaType extends MediaType implements ComparableBill Burke - * @version $Revision: 1 $ - */ -public class WeightedMediaType extends MediaType implements Comparable -{ - private float weight = 1.0f; - - - private WeightedMediaType(String type, String subtype, Map parameters) - { - super(type, subtype, parameters); - } - - public float getWeight() - { - return weight; - } - - - public int compareTo(WeightedMediaType o) - { - WeightedMediaType type2 = this; - WeightedMediaType type1 = o; - - if (type1.weight < type2.weight) return -1; - if (type1.weight > type2.weight) return 1; - - - if (type1.isWildcardType() && !type2.isWildcardType()) return -1; - if (!type1.isWildcardType() && type2.isWildcardType()) return 1; - if (type1.isWildcardSubtype() && !type2.isWildcardSubtype()) return -1; - if (!type1.isWildcardSubtype() && type2.isWildcardSubtype()) return 1; - - int numNonQ = 0; - if (type1.getParameters() != null) - { - numNonQ = type1.getParameters().size(); - } - - int numNonQ2 = 0; - if (type2.getParameters() != null) - { - numNonQ2 = type2.getParameters().size(); - } - - if (numNonQ < numNonQ2) return -1; - if (numNonQ > numNonQ2) return 1; - - - return 0; - } - - /** - * Non-equal properties should not be compatible - */ - @Override - public boolean isCompatible(MediaType other) - { - boolean result; - if (other == null) - result = false; - if (getType().equals(MEDIA_TYPE_WILDCARD) || (other != null && other.getType().equals(MEDIA_TYPE_WILDCARD))) - result = true; - else if (other != null && getType().equalsIgnoreCase(other.getType()) && (getSubtype().equals(MEDIA_TYPE_WILDCARD) || (other != null && other.getSubtype().equals(MEDIA_TYPE_WILDCARD)))) - result = true; - else - { - if (other!= null && getType().equalsIgnoreCase(other.getType()) - && this.getSubtype().equalsIgnoreCase(other.getSubtype())) - { - if (getParameters() == null || getParameters().size() == 0) - { - result = true; - } - else - { - result = this.equals(other); - } - } - else - { - result = false; - } - } - return result; - } - - public static WeightedMediaType valueOf(String type) - { - MediaType tmp = MediaTypeHeaderDelegate.parse(type); - if (tmp.getParameters() == null || !tmp.getParameters().containsKey("q")) - { - return new WeightedMediaType(tmp.getType(), tmp.getSubtype(), tmp.getParameters()); - } - HashMap params = new HashMap(); - params.putAll(tmp.getParameters()); - String q = params.remove("q"); - - - WeightedMediaType mediaType = new WeightedMediaType(tmp.getType(), tmp.getSubtype(), params); - mediaType.weight = getQWithParamInfo(mediaType, q); - - return mediaType; - - } - - public static WeightedMediaType parse(MediaType tmp) - { - if (tmp.getParameters() == null || !tmp.getParameters().containsKey("q")) - { - return new WeightedMediaType(tmp.getType(), tmp.getSubtype(), tmp.getParameters()); - } - HashMap params = new HashMap(); - params.putAll(tmp.getParameters()); - String q = params.remove("q"); - - - WeightedMediaType mediaType = new WeightedMediaType(tmp.getType(), tmp.getSubtype(), params); - mediaType.weight = getQWithParamInfo(mediaType, q); - - return mediaType; - - } - - private static float getQWithParamInfo(MediaType type, String val) - { - try - { - if (val != null) - { - float rtn = Float.valueOf(val); -// if (rtn > 1.0F) -// throw new LoggableFailure("MediaType q value cannot be greater than 1.0: " + type.toString(), HttpResponseCodes.SC_BAD_REQUEST); - return rtn; - } - } - catch (NumberFormatException e) - { - throw new LoggableFailure(Messages.MESSAGES.mediaTypeQMustBeFloat(type), HttpResponseCodes.SC_BAD_REQUEST); - } - return 1.0f; - } - - @Override - public boolean equals(Object obj) - { - return super.equals(obj); - } - -} diff --git a/All/Genesis-NP/Genesis#488/old/WeightedMediaType.java b/All/Genesis-NP/Genesis#488/old/WeightedMediaType.java deleted file mode 100755 index 19d40e0..0000000 --- a/All/Genesis-NP/Genesis#488/old/WeightedMediaType.java +++ /dev/null @@ -1,162 +0,0 @@ -package org.jboss.resteasy.util; - -import org.jboss.resteasy.plugins.delegates.MediaTypeHeaderDelegate; -import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages; -import org.jboss.resteasy.spi.LoggableFailure; - -import javax.ws.rs.core.MediaType; - -import java.util.HashMap; -import java.util.Map; - -/** - * @author Bill Burke - * @version $Revision: 1 $ - */ -public class WeightedMediaType extends MediaType implements Comparable -{ - private float weight = 1.0f; - - - private WeightedMediaType(String type, String subtype, Map parameters) - { - super(type, subtype, parameters); - } - - public float getWeight() - { - return weight; - } - - - public int compareTo(WeightedMediaType o) - { - WeightedMediaType type2 = this; - WeightedMediaType type1 = o; - - if (type1.weight < type2.weight) return -1; - if (type1.weight > type2.weight) return 1; - - - if (type1.isWildcardType() && !type2.isWildcardType()) return -1; - if (!type1.isWildcardType() && type2.isWildcardType()) return 1; - if (type1.isWildcardSubtype() && !type2.isWildcardSubtype()) return -1; - if (!type1.isWildcardSubtype() && type2.isWildcardSubtype()) return 1; - - int numNonQ = 0; - if (type1.getParameters() != null) - { - numNonQ = type1.getParameters().size(); - } - - int numNonQ2 = 0; - if (type2.getParameters() != null) - { - numNonQ2 = type2.getParameters().size(); - } - - if (numNonQ < numNonQ2) return -1; - if (numNonQ > numNonQ2) return 1; - - - return 0; - } - - /** - * Non-equal properties should not be compatible - */ - @Override - public boolean isCompatible(MediaType other) - { - boolean result; - if (other == null) - result = false; - if (getType().equals(MEDIA_TYPE_WILDCARD) || other.getType().equals(MEDIA_TYPE_WILDCARD)) - result = true; - else if (getType().equalsIgnoreCase(other.getType()) && (getSubtype().equals(MEDIA_TYPE_WILDCARD) || other.getSubtype().equals(MEDIA_TYPE_WILDCARD))) - result = true; - else - { - if (getType().equalsIgnoreCase(other.getType()) - && this.getSubtype().equalsIgnoreCase(other.getSubtype())) - { - if (getParameters() == null || getParameters().size() == 0) - { - result = true; - } - else - { - result = this.equals(other); - } - } - else - { - result = false; - } - } - return result; - } - - public static WeightedMediaType valueOf(String type) - { - MediaType tmp = MediaTypeHeaderDelegate.parse(type); - if (tmp.getParameters() == null || !tmp.getParameters().containsKey("q")) - { - return new WeightedMediaType(tmp.getType(), tmp.getSubtype(), tmp.getParameters()); - } - HashMap params = new HashMap(); - params.putAll(tmp.getParameters()); - String q = params.remove("q"); - - - WeightedMediaType mediaType = new WeightedMediaType(tmp.getType(), tmp.getSubtype(), params); - mediaType.weight = getQWithParamInfo(mediaType, q); - - return mediaType; - - } - - public static WeightedMediaType parse(MediaType tmp) - { - if (tmp.getParameters() == null || !tmp.getParameters().containsKey("q")) - { - return new WeightedMediaType(tmp.getType(), tmp.getSubtype(), tmp.getParameters()); - } - HashMap params = new HashMap(); - params.putAll(tmp.getParameters()); - String q = params.remove("q"); - - - WeightedMediaType mediaType = new WeightedMediaType(tmp.getType(), tmp.getSubtype(), params); - mediaType.weight = getQWithParamInfo(mediaType, q); - - return mediaType; - - } - - private static float getQWithParamInfo(MediaType type, String val) - { - try - { - if (val != null) - { - float rtn = Float.valueOf(val); -// if (rtn > 1.0F) -// throw new LoggableFailure("MediaType q value cannot be greater than 1.0: " + type.toString(), HttpResponseCodes.SC_BAD_REQUEST); - return rtn; - } - } - catch (NumberFormatException e) - { - throw new LoggableFailure(Messages.MESSAGES.mediaTypeQMustBeFloat(type), HttpResponseCodes.SC_BAD_REQUEST); - } - return 1.0f; - } - - @Override - public boolean equals(Object obj) - { - return super.equals(obj); - } - -} diff --git a/All/Genesis-NP/Genesis#488/pair.info b/All/Genesis-NP/Genesis#488/pair.info deleted file mode 100755 index ccdfaec..0000000 --- a/All/Genesis-NP/Genesis#488/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:488 -SATName:Genesis -modifiedFPath:jaxrs/resteasy-jaxrs/src/main/java/org/jboss/resteasy/util/WeightedMediaType.java -comSha:6727bdffc87d9523877eecf2b727cad0c4b7234e -parentComSha:6727bdffc87d9523877eecf2b727cad0c4b7234e^1 -githubUrl:https://github.com/resteasy/Resteasy -repoName:resteasy#Resteasy \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#493/comMsg.txt b/All/Genesis-NP/Genesis#493/comMsg.txt deleted file mode 100755 index 6dc85a8..0000000 --- a/All/Genesis-NP/Genesis#493/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE in thread CPU reported diff --git a/All/Genesis-NP/Genesis#493/diff.diff b/All/Genesis-NP/Genesis#493/diff.diff deleted file mode 100755 index 9f4bf49..0000000 --- a/All/Genesis-NP/Genesis#493/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/sjk-core/src/main/java/org/gridkit/jvmtool/MBeanCpuUsageReporter.java b/sjk-core/src/main/java/org/gridkit/jvmtool/MBeanCpuUsageReporter.java -index 7ac19f6..8070176 100644 ---- a/sjk-core/src/main/java/org/gridkit/jvmtool/MBeanCpuUsageReporter.java -+++ b/sjk-core/src/main/java/org/gridkit/jvmtool/MBeanCpuUsageReporter.java -@@ -186,0 +187,3 @@ public class MBeanCpuUsageReporter { -+ if (threadDump.get(ids[i]) == null) { -+ continue; -+ } -@@ -194,0 +198,3 @@ public class MBeanCpuUsageReporter { -+ if (threadDump.get(ids[i]) == null) { -+ continue; -+ } -@@ -200,0 +207,3 @@ public class MBeanCpuUsageReporter { -+ if (threadDump.get(id) == null) { -+ continue; -+ } diff --git a/All/Genesis-NP/Genesis#493/new/MBeanCpuUsageReporter.java b/All/Genesis-NP/Genesis#493/new/MBeanCpuUsageReporter.java deleted file mode 100755 index 8070176..0000000 --- a/All/Genesis-NP/Genesis#493/new/MBeanCpuUsageReporter.java +++ /dev/null @@ -1,468 +0,0 @@ -/** - * Copyright 2013 Alexey Ragozin - * - * 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.gridkit.jvmtool; - -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeSet; -import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; - -import javax.management.MBeanServerConnection; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -import org.gridkit.jvmtool.stacktrace.ThreadMXBeanEx; -import org.gridkit.util.formating.Formats; - -/** - * Thread CPU tracker. - * - * @author Alexey Ragozin (alexey.ragozin@gmail.com) - */ -public class MBeanCpuUsageReporter { - - private static final ObjectName THREADING_MBEAN = name("java.lang:type=Threading"); - private static ObjectName name(String name) { - try { - return new ObjectName(name); - } catch (MalformedObjectNameException e) { - throw new RuntimeException(e); - } - } - - private MBeanServerConnection mserver; - private ThreadMXBean mbean; - - private long lastTimestamp; - private long lastProcessCpuTime; - private long lastYougGcCpuTime; - private long lastOldGcCpuTime; - private long lastSafePointCount; - private long lastSafePointTime; - private long lastSafePointSyncTime; - private BigInteger lastCummulativeCpuTime = BigInteger.valueOf(0); - private BigInteger lastCummulativeUserTime = BigInteger.valueOf(0); - private BigInteger lastCummulativeAllocatedAmount = BigInteger.valueOf(0); - - private Map threadDump = new HashMap(); - private Map notes = new HashMap(); - - private List> comparators = new ArrayList>(); - - private int topLimit = Integer.MAX_VALUE; - - private Pattern filter; - - private boolean bulkCpuEnabled; - private boolean threadAllocatedMemoryEnabled; - - private GcCpuUsageMonitor gcMon; - private SafePointMonitor spMon; - - public MBeanCpuUsageReporter(MBeanServerConnection mserver) { - this.mserver = mserver; - this.mbean = ThreadMXBeanEx.BeanHelper.connectThreadMXBean(mserver); - - threadAllocatedMemoryEnabled = getThreadingMBeanCapability("ThreadAllocatedMemoryEnabled"); - bulkCpuEnabled = verifyBulkCpu(); - - lastTimestamp = System.nanoTime(); - lastProcessCpuTime = getProcessCpuTime(); - } - - public void setGcCpuUsageMonitor(GcCpuUsageMonitor gcMon) { - this.gcMon = gcMon; - } - - public void setSafePointMonitor(SafePointMonitor spMon) { - this.spMon = spMon; - } - - private boolean getThreadingMBeanCapability(String attrName) { - try { - Object val = mserver.getAttribute(THREADING_MBEAN, attrName); - return Boolean.TRUE.equals(val); - } - catch(Exception e) { - return false; - } - } - - private boolean verifyBulkCpu() { - try { - long[] ids = mbean.getAllThreadIds(); - ((ThreadMXBeanEx)mbean).getThreadCpuTime(ids); - ((ThreadMXBeanEx)mbean).getThreadUserTime(ids); - return true; - } catch (Exception e) { - return false; - } - } - - public void sortByThreadName() { - comparators.add(0, new ThreadNameComparator()); - } - - public void sortByUserCpu() { - comparators.add(0, new UserTimeComparator()); - } - - public void sortBySysCpu() { - comparators.add(0, new SysTimeComparator()); - } - - public void sortByTotalCpu() { - comparators.add(0, new CpuTimeComparator()); - } - - public void sortByAllocRate() { - comparators.add(0, new AllocRateComparator()); - } - - public void setTopLimit(int n) { - topLimit = n; - } - - public void setThreadFilter(Pattern regEx) { - filter = regEx; - } - - public void probe() { - try { - long[] ids = mbean.getAllThreadIds(); - ThreadInfo[] ti = mbean.getThreadInfo(ids); - - Map buf = new HashMap(); - for(ThreadInfo t: ti) { - if (t != null) { - buf.put(t.getThreadId(), t); - } - } - - for(Long key: threadDump.keySet()) { - ThreadTrac tt = threadDump.get(key); - ThreadInfo t = buf.remove(key); - if (t != null) { - tt.name = t.getThreadName(); - tt.lastThreadInfo = t; - } - else { - tt.dead = true; - } - } - - for(ThreadInfo t: buf.values()) { - ThreadTrac tt = new ThreadTrac(); - tt.name = t.getThreadName(); - tt.lastThreadInfo = t; - threadDump.put(t.getThreadId(), tt); - } - - if (threadAllocatedMemoryEnabled) { - long[] alloc = ((ThreadMXBeanEx)mbean).getThreadAllocatedBytes(ids); - for (int i = 0 ; i != ids.length; ++i) { - if (threadDump.get(ids[i]) == null) { - continue; - } - threadDump.get(ids[i]).lastAllocatedBytes = alloc[i]; - } - } - - if (bulkCpuEnabled) { - long[] cpu = ((ThreadMXBeanEx)mbean).getThreadCpuTime(ids); - long[] usr = ((ThreadMXBeanEx)mbean).getThreadUserTime(ids); - for (int i = 0 ; i != ids.length; ++i) { - if (threadDump.get(ids[i]) == null) { - continue; - } - threadDump.get(ids[i]).lastCpuTime = cpu[i]; - threadDump.get(ids[i]).lastUserTime = usr[i]; - } - } - else { - for(long id: ids) { - if (threadDump.get(id) == null) { - continue; - } - ThreadTrac tt = threadDump.get(id); - tt.lastCpuTime = mbean.getThreadCpuTime(id); - tt.lastUserTime = mbean.getThreadCpuTime(id); - } - } - - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private void cleanDead() { - Iterator it = threadDump.values().iterator(); - while(it.hasNext()) { - ThreadTrac tt = it.next(); - if (tt.dead) { - it.remove(); - } - } - } - - public String report() { - - probe(); - - StringBuilder sb = new StringBuilder(); - - long currentTime = System.nanoTime(); - long timeSplit = currentTime - lastTimestamp; - long currentCpuTime = getProcessCpuTime(); - long currentYoungGcCpuTime = gcMon == null ? 0 : gcMon.getYoungGcCpu(); - long currentOldGcCpuTime = gcMon == null ? 0 : gcMon.getOldGcCpu(); - long currentSafePointCount = spMon == null ? 0 : spMon.getSafePointCount(); - long currentSafePointTime = spMon == null ? 0 : spMon.getSafePointTime(); - long currentSafePointSyncTime = spMon == null ? 0 : spMon.getSafePointSyncTime(); - - Map newNotes = new HashMap(); - - BigInteger deltaCpu = BigInteger.valueOf(0); - BigInteger deltaUser = BigInteger.valueOf(0); - BigInteger deltaAlloc = BigInteger.valueOf(0); - - List table = new ArrayList(); - - for(long tid: getAllThreadIds()) { - - String threadName = getThreadName(tid); - - ThreadNote lastNote = notes.get(tid); - ThreadNote newNote = new ThreadNote(); - newNote.lastCpuTime = getThreadCpuTime(tid); - newNote.lastUserTime = getThreadUserTime(tid); - newNote.lastAllocatedBytes = getThreadAllocatedBytes(tid); - - newNotes.put(tid, newNote); - - long lastCpu = lastNote == null ? 0 : lastNote.lastCpuTime; - long lastUser = lastNote == null ? 0 : lastNote.lastUserTime; - long lastAlloc = lastNote == null ? 0 : lastNote.lastAllocatedBytes; - - deltaCpu = deltaCpu.add(BigInteger.valueOf(newNote.lastCpuTime - lastCpu)); - deltaUser = deltaUser.add(BigInteger.valueOf(newNote.lastUserTime - lastUser)); - deltaAlloc = deltaAlloc.add(BigInteger.valueOf(newNote.lastAllocatedBytes - lastAlloc)); - - if (lastNote != null) { - - if (filter != null && !filter.matcher(threadName).matches()) { - continue; - } - - double cpuT = ((double)(newNote.lastCpuTime - lastNote.lastCpuTime)) / timeSplit; - double userT = ((double)(newNote.lastUserTime - lastNote.lastUserTime)) / timeSplit; - double allocRate = ((double)(newNote.lastAllocatedBytes - lastNote.lastAllocatedBytes)) * TimeUnit.SECONDS.toNanos(1) / timeSplit; - - table.add(new ThreadLine(tid, 100 * userT, 100 * (cpuT - userT), allocRate, getThreadName(tid))); - } - } - - if (table.size() >0) { - - for(Comparator cmp: comparators) { - Collections.sort(table, cmp); - } - - if (table.size() > topLimit) { - table = table.subList(0, topLimit); - } - - double processT = ((double)(currentCpuTime - lastProcessCpuTime)) / timeSplit; - double cpuT = ((double)(deltaCpu.longValue())) / timeSplit; - double userT = ((double)(deltaUser.longValue())) / timeSplit; - double allocRate = ((double)(deltaAlloc.longValue())) * TimeUnit.SECONDS.toNanos(1) / timeSplit; - - double youngGcT = ((double)currentYoungGcCpuTime - lastYougGcCpuTime) / timeSplit; - double oldGcT = ((double)currentOldGcCpuTime - lastOldGcCpuTime) / timeSplit; - - sb.append(Formats.toDatestamp(System.currentTimeMillis())); - sb.append(String.format(" Process summary \n process cpu=%.2f%%\n application cpu=%.2f%% (user=%.2f%% sys=%.2f%%)\n other: cpu=%.2f%% \n", 100 * processT, 100 * cpuT, 100 * userT, 100 * (cpuT - userT), 100 * (processT - cpuT))); - if (currentYoungGcCpuTime > 0) { - sb.append(String.format(" GC cpu=%.2f%% (young=%.2f%%, old=%.2f%%)\n", 100 * (youngGcT + oldGcT), 100 * youngGcT, 100 * oldGcT)); - } - if (threadAllocatedMemoryEnabled) { - sb.append(String.format(" heap allocation rate %sb/s\n", Formats.toMemorySize((long) allocRate))); - } - if (currentSafePointCount > 0) { - if (currentSafePointCount == lastSafePointCount) { - sb.append(String.format(" no safe points")); - } - else { - double spRate = (TimeUnit.SECONDS.toNanos(1) * (double)(currentSafePointCount - lastSafePointCount)) / timeSplit; - double spCpuUsage = ((double)(currentSafePointTime - lastSafePointTime)) / timeSplit; - double spSyncCpuUsage = ((double)(currentSafePointSyncTime - lastSafePointSyncTime)) / timeSplit; - double spAvg = ((double)(currentSafePointTime + currentSafePointSyncTime - lastSafePointTime - lastSafePointSyncTime)) / (currentSafePointCount - lastSafePointCount) / TimeUnit.MILLISECONDS.toNanos(1); - sb.append(String.format(" safe point rate: %.1f (events/s) avg. safe point pause: %.2fms\n", spRate, spAvg)); - sb.append(String.format(" safe point sync time: %.2f%% processing time: %.2f%% (wallclock time)\n", 100 * spSyncCpuUsage, 100 * spCpuUsage)); - } - } - for(ThreadLine line: table) { - sb.append(format(line)).append('\n'); - } - sb.append("\n"); - } - - lastTimestamp = currentTime; - notes = newNotes; - lastCummulativeCpuTime = lastCummulativeCpuTime.add(deltaCpu); - lastCummulativeUserTime = lastCummulativeUserTime.add(deltaUser); - lastCummulativeAllocatedAmount = lastCummulativeAllocatedAmount.add(deltaAlloc); - lastProcessCpuTime = currentCpuTime; - lastYougGcCpuTime = currentYoungGcCpuTime; - lastOldGcCpuTime = currentOldGcCpuTime; - lastSafePointCount = currentSafePointCount; - lastSafePointTime = currentSafePointTime; - lastSafePointSyncTime = currentSafePointSyncTime; - - cleanDead(); - - return sb.toString(); - } - - private Object format(ThreadLine line) { - if (threadAllocatedMemoryEnabled) { - return String.format("[%06d] user=%5.2f%% sys=%5.2f%% alloc=%6sb/s - %s", line.id, line.userT, (line.sysT), Formats.toMemorySize((long)line.allocRate), line.name); - } - else { - return String.format("[%06d] user=%5.2f%% sys=%5.2f%% - %s", line.id, line.userT, (line.sysT), line.name); - } - } - - private String getThreadName(long tid) { - return threadDump.get(tid).name; - } - - private Collection getAllThreadIds() { - return new TreeSet(threadDump.keySet()); - } - - private long getThreadCpuTime(long tid) { - return threadDump.get(tid).lastCpuTime; - } - - private long getThreadUserTime(long tid) { - return threadDump.get(tid).lastUserTime; - } - - private long getThreadAllocatedBytes(long tid) { - return threadDump.get(tid).lastAllocatedBytes; - } - - private long getProcessCpuTime() { - try { - ObjectName bean = new ObjectName("java.lang:type=OperatingSystem"); - return (Long) mserver.getAttribute(bean, "ProcessCpuTime"); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static class ThreadTrac { - - private String name; - private long lastCpuTime; - private long lastUserTime; - private long lastAllocatedBytes; - @SuppressWarnings("unused") - private ThreadInfo lastThreadInfo; - - private boolean dead; - - } - - private static class ThreadNote { - - private long lastCpuTime; - private long lastUserTime; - private long lastAllocatedBytes; - } - - private static class ThreadLine { - - long id; - double userT; - double sysT; - double allocRate; - String name; - - public ThreadLine(long id, double userT, double sysT, double allocRate, String name) { - this.id = id; - this.userT = userT; - this.sysT = sysT; - this.allocRate = allocRate; - this.name = name; - } - - public String toString() { - return String.format("[%06d] user=%5.2f%% sys=%5.2f%% - %s", id, userT, (sysT), name); - } - } - - private static class UserTimeComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return Double.compare(o2.userT, o1.userT); - } - } - - private static class SysTimeComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return Double.compare(o2.sysT, o1.sysT); - } - } - - private static class CpuTimeComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return Double.compare(o2.userT + o2.sysT, o1.userT + o1.sysT); - } - } - - private static class ThreadNameComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return o1.name.compareTo(o2.name); - } - } - - private static class AllocRateComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return Double.compare(o2.allocRate, o1.allocRate); - } - } -} diff --git a/All/Genesis-NP/Genesis#493/old/MBeanCpuUsageReporter.java b/All/Genesis-NP/Genesis#493/old/MBeanCpuUsageReporter.java deleted file mode 100755 index 7ac19f6..0000000 --- a/All/Genesis-NP/Genesis#493/old/MBeanCpuUsageReporter.java +++ /dev/null @@ -1,459 +0,0 @@ -/** - * Copyright 2013 Alexey Ragozin - * - * 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.gridkit.jvmtool; - -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeSet; -import java.util.concurrent.TimeUnit; -import java.util.regex.Pattern; - -import javax.management.MBeanServerConnection; -import javax.management.MalformedObjectNameException; -import javax.management.ObjectName; - -import org.gridkit.jvmtool.stacktrace.ThreadMXBeanEx; -import org.gridkit.util.formating.Formats; - -/** - * Thread CPU tracker. - * - * @author Alexey Ragozin (alexey.ragozin@gmail.com) - */ -public class MBeanCpuUsageReporter { - - private static final ObjectName THREADING_MBEAN = name("java.lang:type=Threading"); - private static ObjectName name(String name) { - try { - return new ObjectName(name); - } catch (MalformedObjectNameException e) { - throw new RuntimeException(e); - } - } - - private MBeanServerConnection mserver; - private ThreadMXBean mbean; - - private long lastTimestamp; - private long lastProcessCpuTime; - private long lastYougGcCpuTime; - private long lastOldGcCpuTime; - private long lastSafePointCount; - private long lastSafePointTime; - private long lastSafePointSyncTime; - private BigInteger lastCummulativeCpuTime = BigInteger.valueOf(0); - private BigInteger lastCummulativeUserTime = BigInteger.valueOf(0); - private BigInteger lastCummulativeAllocatedAmount = BigInteger.valueOf(0); - - private Map threadDump = new HashMap(); - private Map notes = new HashMap(); - - private List> comparators = new ArrayList>(); - - private int topLimit = Integer.MAX_VALUE; - - private Pattern filter; - - private boolean bulkCpuEnabled; - private boolean threadAllocatedMemoryEnabled; - - private GcCpuUsageMonitor gcMon; - private SafePointMonitor spMon; - - public MBeanCpuUsageReporter(MBeanServerConnection mserver) { - this.mserver = mserver; - this.mbean = ThreadMXBeanEx.BeanHelper.connectThreadMXBean(mserver); - - threadAllocatedMemoryEnabled = getThreadingMBeanCapability("ThreadAllocatedMemoryEnabled"); - bulkCpuEnabled = verifyBulkCpu(); - - lastTimestamp = System.nanoTime(); - lastProcessCpuTime = getProcessCpuTime(); - } - - public void setGcCpuUsageMonitor(GcCpuUsageMonitor gcMon) { - this.gcMon = gcMon; - } - - public void setSafePointMonitor(SafePointMonitor spMon) { - this.spMon = spMon; - } - - private boolean getThreadingMBeanCapability(String attrName) { - try { - Object val = mserver.getAttribute(THREADING_MBEAN, attrName); - return Boolean.TRUE.equals(val); - } - catch(Exception e) { - return false; - } - } - - private boolean verifyBulkCpu() { - try { - long[] ids = mbean.getAllThreadIds(); - ((ThreadMXBeanEx)mbean).getThreadCpuTime(ids); - ((ThreadMXBeanEx)mbean).getThreadUserTime(ids); - return true; - } catch (Exception e) { - return false; - } - } - - public void sortByThreadName() { - comparators.add(0, new ThreadNameComparator()); - } - - public void sortByUserCpu() { - comparators.add(0, new UserTimeComparator()); - } - - public void sortBySysCpu() { - comparators.add(0, new SysTimeComparator()); - } - - public void sortByTotalCpu() { - comparators.add(0, new CpuTimeComparator()); - } - - public void sortByAllocRate() { - comparators.add(0, new AllocRateComparator()); - } - - public void setTopLimit(int n) { - topLimit = n; - } - - public void setThreadFilter(Pattern regEx) { - filter = regEx; - } - - public void probe() { - try { - long[] ids = mbean.getAllThreadIds(); - ThreadInfo[] ti = mbean.getThreadInfo(ids); - - Map buf = new HashMap(); - for(ThreadInfo t: ti) { - if (t != null) { - buf.put(t.getThreadId(), t); - } - } - - for(Long key: threadDump.keySet()) { - ThreadTrac tt = threadDump.get(key); - ThreadInfo t = buf.remove(key); - if (t != null) { - tt.name = t.getThreadName(); - tt.lastThreadInfo = t; - } - else { - tt.dead = true; - } - } - - for(ThreadInfo t: buf.values()) { - ThreadTrac tt = new ThreadTrac(); - tt.name = t.getThreadName(); - tt.lastThreadInfo = t; - threadDump.put(t.getThreadId(), tt); - } - - if (threadAllocatedMemoryEnabled) { - long[] alloc = ((ThreadMXBeanEx)mbean).getThreadAllocatedBytes(ids); - for (int i = 0 ; i != ids.length; ++i) { - threadDump.get(ids[i]).lastAllocatedBytes = alloc[i]; - } - } - - if (bulkCpuEnabled) { - long[] cpu = ((ThreadMXBeanEx)mbean).getThreadCpuTime(ids); - long[] usr = ((ThreadMXBeanEx)mbean).getThreadUserTime(ids); - for (int i = 0 ; i != ids.length; ++i) { - threadDump.get(ids[i]).lastCpuTime = cpu[i]; - threadDump.get(ids[i]).lastUserTime = usr[i]; - } - } - else { - for(long id: ids) { - ThreadTrac tt = threadDump.get(id); - tt.lastCpuTime = mbean.getThreadCpuTime(id); - tt.lastUserTime = mbean.getThreadCpuTime(id); - } - } - - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private void cleanDead() { - Iterator it = threadDump.values().iterator(); - while(it.hasNext()) { - ThreadTrac tt = it.next(); - if (tt.dead) { - it.remove(); - } - } - } - - public String report() { - - probe(); - - StringBuilder sb = new StringBuilder(); - - long currentTime = System.nanoTime(); - long timeSplit = currentTime - lastTimestamp; - long currentCpuTime = getProcessCpuTime(); - long currentYoungGcCpuTime = gcMon == null ? 0 : gcMon.getYoungGcCpu(); - long currentOldGcCpuTime = gcMon == null ? 0 : gcMon.getOldGcCpu(); - long currentSafePointCount = spMon == null ? 0 : spMon.getSafePointCount(); - long currentSafePointTime = spMon == null ? 0 : spMon.getSafePointTime(); - long currentSafePointSyncTime = spMon == null ? 0 : spMon.getSafePointSyncTime(); - - Map newNotes = new HashMap(); - - BigInteger deltaCpu = BigInteger.valueOf(0); - BigInteger deltaUser = BigInteger.valueOf(0); - BigInteger deltaAlloc = BigInteger.valueOf(0); - - List table = new ArrayList(); - - for(long tid: getAllThreadIds()) { - - String threadName = getThreadName(tid); - - ThreadNote lastNote = notes.get(tid); - ThreadNote newNote = new ThreadNote(); - newNote.lastCpuTime = getThreadCpuTime(tid); - newNote.lastUserTime = getThreadUserTime(tid); - newNote.lastAllocatedBytes = getThreadAllocatedBytes(tid); - - newNotes.put(tid, newNote); - - long lastCpu = lastNote == null ? 0 : lastNote.lastCpuTime; - long lastUser = lastNote == null ? 0 : lastNote.lastUserTime; - long lastAlloc = lastNote == null ? 0 : lastNote.lastAllocatedBytes; - - deltaCpu = deltaCpu.add(BigInteger.valueOf(newNote.lastCpuTime - lastCpu)); - deltaUser = deltaUser.add(BigInteger.valueOf(newNote.lastUserTime - lastUser)); - deltaAlloc = deltaAlloc.add(BigInteger.valueOf(newNote.lastAllocatedBytes - lastAlloc)); - - if (lastNote != null) { - - if (filter != null && !filter.matcher(threadName).matches()) { - continue; - } - - double cpuT = ((double)(newNote.lastCpuTime - lastNote.lastCpuTime)) / timeSplit; - double userT = ((double)(newNote.lastUserTime - lastNote.lastUserTime)) / timeSplit; - double allocRate = ((double)(newNote.lastAllocatedBytes - lastNote.lastAllocatedBytes)) * TimeUnit.SECONDS.toNanos(1) / timeSplit; - - table.add(new ThreadLine(tid, 100 * userT, 100 * (cpuT - userT), allocRate, getThreadName(tid))); - } - } - - if (table.size() >0) { - - for(Comparator cmp: comparators) { - Collections.sort(table, cmp); - } - - if (table.size() > topLimit) { - table = table.subList(0, topLimit); - } - - double processT = ((double)(currentCpuTime - lastProcessCpuTime)) / timeSplit; - double cpuT = ((double)(deltaCpu.longValue())) / timeSplit; - double userT = ((double)(deltaUser.longValue())) / timeSplit; - double allocRate = ((double)(deltaAlloc.longValue())) * TimeUnit.SECONDS.toNanos(1) / timeSplit; - - double youngGcT = ((double)currentYoungGcCpuTime - lastYougGcCpuTime) / timeSplit; - double oldGcT = ((double)currentOldGcCpuTime - lastOldGcCpuTime) / timeSplit; - - sb.append(Formats.toDatestamp(System.currentTimeMillis())); - sb.append(String.format(" Process summary \n process cpu=%.2f%%\n application cpu=%.2f%% (user=%.2f%% sys=%.2f%%)\n other: cpu=%.2f%% \n", 100 * processT, 100 * cpuT, 100 * userT, 100 * (cpuT - userT), 100 * (processT - cpuT))); - if (currentYoungGcCpuTime > 0) { - sb.append(String.format(" GC cpu=%.2f%% (young=%.2f%%, old=%.2f%%)\n", 100 * (youngGcT + oldGcT), 100 * youngGcT, 100 * oldGcT)); - } - if (threadAllocatedMemoryEnabled) { - sb.append(String.format(" heap allocation rate %sb/s\n", Formats.toMemorySize((long) allocRate))); - } - if (currentSafePointCount > 0) { - if (currentSafePointCount == lastSafePointCount) { - sb.append(String.format(" no safe points")); - } - else { - double spRate = (TimeUnit.SECONDS.toNanos(1) * (double)(currentSafePointCount - lastSafePointCount)) / timeSplit; - double spCpuUsage = ((double)(currentSafePointTime - lastSafePointTime)) / timeSplit; - double spSyncCpuUsage = ((double)(currentSafePointSyncTime - lastSafePointSyncTime)) / timeSplit; - double spAvg = ((double)(currentSafePointTime + currentSafePointSyncTime - lastSafePointTime - lastSafePointSyncTime)) / (currentSafePointCount - lastSafePointCount) / TimeUnit.MILLISECONDS.toNanos(1); - sb.append(String.format(" safe point rate: %.1f (events/s) avg. safe point pause: %.2fms\n", spRate, spAvg)); - sb.append(String.format(" safe point sync time: %.2f%% processing time: %.2f%% (wallclock time)\n", 100 * spSyncCpuUsage, 100 * spCpuUsage)); - } - } - for(ThreadLine line: table) { - sb.append(format(line)).append('\n'); - } - sb.append("\n"); - } - - lastTimestamp = currentTime; - notes = newNotes; - lastCummulativeCpuTime = lastCummulativeCpuTime.add(deltaCpu); - lastCummulativeUserTime = lastCummulativeUserTime.add(deltaUser); - lastCummulativeAllocatedAmount = lastCummulativeAllocatedAmount.add(deltaAlloc); - lastProcessCpuTime = currentCpuTime; - lastYougGcCpuTime = currentYoungGcCpuTime; - lastOldGcCpuTime = currentOldGcCpuTime; - lastSafePointCount = currentSafePointCount; - lastSafePointTime = currentSafePointTime; - lastSafePointSyncTime = currentSafePointSyncTime; - - cleanDead(); - - return sb.toString(); - } - - private Object format(ThreadLine line) { - if (threadAllocatedMemoryEnabled) { - return String.format("[%06d] user=%5.2f%% sys=%5.2f%% alloc=%6sb/s - %s", line.id, line.userT, (line.sysT), Formats.toMemorySize((long)line.allocRate), line.name); - } - else { - return String.format("[%06d] user=%5.2f%% sys=%5.2f%% - %s", line.id, line.userT, (line.sysT), line.name); - } - } - - private String getThreadName(long tid) { - return threadDump.get(tid).name; - } - - private Collection getAllThreadIds() { - return new TreeSet(threadDump.keySet()); - } - - private long getThreadCpuTime(long tid) { - return threadDump.get(tid).lastCpuTime; - } - - private long getThreadUserTime(long tid) { - return threadDump.get(tid).lastUserTime; - } - - private long getThreadAllocatedBytes(long tid) { - return threadDump.get(tid).lastAllocatedBytes; - } - - private long getProcessCpuTime() { - try { - ObjectName bean = new ObjectName("java.lang:type=OperatingSystem"); - return (Long) mserver.getAttribute(bean, "ProcessCpuTime"); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - private static class ThreadTrac { - - private String name; - private long lastCpuTime; - private long lastUserTime; - private long lastAllocatedBytes; - @SuppressWarnings("unused") - private ThreadInfo lastThreadInfo; - - private boolean dead; - - } - - private static class ThreadNote { - - private long lastCpuTime; - private long lastUserTime; - private long lastAllocatedBytes; - } - - private static class ThreadLine { - - long id; - double userT; - double sysT; - double allocRate; - String name; - - public ThreadLine(long id, double userT, double sysT, double allocRate, String name) { - this.id = id; - this.userT = userT; - this.sysT = sysT; - this.allocRate = allocRate; - this.name = name; - } - - public String toString() { - return String.format("[%06d] user=%5.2f%% sys=%5.2f%% - %s", id, userT, (sysT), name); - } - } - - private static class UserTimeComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return Double.compare(o2.userT, o1.userT); - } - } - - private static class SysTimeComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return Double.compare(o2.sysT, o1.sysT); - } - } - - private static class CpuTimeComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return Double.compare(o2.userT + o2.sysT, o1.userT + o1.sysT); - } - } - - private static class ThreadNameComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return o1.name.compareTo(o2.name); - } - } - - private static class AllocRateComparator implements Comparator { - - @Override - public int compare(ThreadLine o1, ThreadLine o2) { - return Double.compare(o2.allocRate, o1.allocRate); - } - } -} diff --git a/All/Genesis-NP/Genesis#493/pair.info b/All/Genesis-NP/Genesis#493/pair.info deleted file mode 100755 index ab6401c..0000000 --- a/All/Genesis-NP/Genesis#493/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:493 -SATName:Genesis -modifiedFPath:sjk-core/src/main/java/org/gridkit/jvmtool/MBeanCpuUsageReporter.java -comSha:9be6226ee2561f0ede74aedef57b787dfeb66c08 -parentComSha:9be6226ee2561f0ede74aedef57b787dfeb66c08^1 -githubUrl:https://github.com/aragozin/jvm-tools -repoName:aragozin#jvm-tools \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#55/comMsg.txt b/All/Genesis-NP/Genesis#55/comMsg.txt deleted file mode 100755 index 0e679ff..0000000 --- a/All/Genesis-NP/Genesis#55/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed: NPE with calling getCommandDescription() of an unknown command diff --git a/All/Genesis-NP/Genesis#55/diff.diff b/All/Genesis-NP/Genesis#55/diff.diff deleted file mode 100755 index 3e0cb91..0000000 --- a/All/Genesis-NP/Genesis#55/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/src/main/java/com/beust/jcommander/JCommander.java b/src/main/java/com/beust/jcommander/JCommander.java -index 46f3b9b..f715620 100644 ---- a/src/main/java/com/beust/jcommander/JCommander.java -+++ b/src/main/java/com/beust/jcommander/JCommander.java -@@ -704,0 +705,4 @@ public class JCommander { -+ if (jc == null) { -+ throw new ParameterException("Asking description for unknown command: " + commandName); -+ } -+ diff --git a/All/Genesis-NP/Genesis#55/new/JCommander.java b/All/Genesis-NP/Genesis#55/new/JCommander.java deleted file mode 100755 index f715620..0000000 --- a/All/Genesis-NP/Genesis#55/new/JCommander.java +++ /dev/null @@ -1,981 +0,0 @@ -/** - * Copyright (C) 2010 the original author or authors. - * See the notice.md file distributed with this work for additional - * information regarding copyright ownership. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.beust.jcommander; - -import com.beust.jcommander.converters.NoConverter; -import com.beust.jcommander.converters.StringConverter; -import com.beust.jcommander.internal.DefaultConverterFactory; -import com.beust.jcommander.internal.Lists; -import com.beust.jcommander.internal.Maps; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -/** - * The main class for JCommander. It's responsible for parsing the object that contains - * all the annotated fields, parse the command line and assign the fields with the correct - * values and a few other helper methods, such as usage(). - * - * The object(s) you pass in the constructor are expected to have one or more - * \@Parameter annotations on them. You can pass either a single object, an array of objects - * or an instance of Iterable. In the case of an array or Iterable, JCommander will collect - * the \@Parameter annotations from all the objects passed in parameter. - * - * @author cbeust - */ -public class JCommander { - public static final String DEBUG_PROPERTY = "jcommander.debug"; - - /** - * A map to look up parameter description per option name. - */ - private Map m_descriptions; - - /** - * The objects that contain fields annotated with @Parameter. - */ - private List m_objects = Lists.newArrayList(); - - /** - * This field will contain whatever command line parameter is not an option. - * It is expected to be a List. - */ - private Field m_mainParameterField = null; - - /** - * The object on which we found the main parameter field. - */ - private Object m_mainParameterObject; - - /** - * The annotation found on the main parameter field. - */ - private Parameter m_mainParameterAnnotation; - - private ParameterDescription m_mainParameterDescription; - - /** - * A set of all the fields that are required. During the reflection phase, - * this field receives all the fields that are annotated with required=true - * and during the parsing phase, all the fields that are assigned a value - * are removed from it. At the end of the parsing phase, if it's not empty, - * then some required fields did not receive a value and an exception is - * thrown. - */ - private Map m_requiredFields = Maps.newHashMap(); - - /** - * A map of all the annotated fields. - */ - private Map m_fields = Maps.newHashMap(); - - private ResourceBundle m_bundle; - - /** - * A default provider returns default values for the parameters. - */ - private IDefaultProvider m_defaultProvider; - - /** - * List of commands and their instance. - */ - private Map m_commands = Maps.newLinkedHashMap(); - - /** - * The name of the command after the parsing has run. - */ - private String m_parsedCommand; - - private String m_programName; - - /** - * The factories used to look up string converters. - */ - private static List CONVERTER_FACTORIES = Lists.newArrayList(); - - static { - CONVERTER_FACTORIES.add(new DefaultConverterFactory()); - }; - - /** - * Creates a new un-configured JCommander object. - */ - public JCommander() { - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - */ - public JCommander(Object object) { - addObject(object); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param bundle The bundle to use for the descriptions. Can be null. - */ - public JCommander(Object object, ResourceBundle bundle) { - addObject(object); - setDescriptionsBundle(bundle); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param bundle The bundle to use for the descriptions. Can be null. - * @param args The arguments to parse (optional). - */ - public JCommander(Object object, ResourceBundle bundle, String... args) { - addObject(object); - setDescriptionsBundle(bundle); - parse(args); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param args The arguments to parse (optional). - */ - public JCommander(Object object, String... args) { - addObject(object); - parse(args); - } - - /** - * Adds the provided arg object to the set of objects that this commander - * will parse arguments into. - * - * @param object The arg object expected to contain {@link Parameter} - * annotations. If object is an array or is {@link Iterable}, - * the child objects will be added instead. - */ - // declared final since this is invoked from constructors - public final void addObject(Object object) { - if (object instanceof Iterable) { - // Iterable - for (Object o : (Iterable) object) { - m_objects.add(o); - } - } else if (object.getClass().isArray()) { - // Array - for (Object o : (Object[]) object) { - m_objects.add(o); - } - } else { - // Single object - m_objects.add(object); - } - } - - /** - * Sets the {@link ResourceBundle} to use for looking up descriptions. - * Set this to null to use description text directly. - */ - // declared final since this is invoked from constructors - public final void setDescriptionsBundle(ResourceBundle bundle) { - m_bundle = bundle; - } - - /** - * Parse the command line parameters. - */ - public void parse(String... args) { - StringBuilder sb = new StringBuilder("Parsing \""); - sb.append(join(args).append("\"\n with:").append(join(m_objects.toArray()))); - p(sb.toString()); - - if (m_descriptions == null) createDescriptions(); - initializeDefaultValues(); - parseValues(expandArgs(args)); - validateOptions(); - } - - private StringBuilder join(Object[] args) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < args.length; i++) { - if (i > 0) result.append(" "); - result.append(args[i]); - } - return result; - } - - private void initializeDefaultValues() { - if (m_defaultProvider != null) { - for (ParameterDescription pd : m_descriptions.values()) { - initializeDefaultValue(pd); - } - } - } - - /** - * Make sure that all the required parameters have received a value. - */ - private void validateOptions() { - if (! m_requiredFields.isEmpty()) { - StringBuilder missingFields = new StringBuilder(); - for (ParameterDescription pd : m_requiredFields.values()) { - missingFields.append(pd.getNames()).append(" "); - } - throw new ParameterException("The following options are required: " + missingFields); - } - - if (m_mainParameterDescription != null) { - if (m_mainParameterDescription.getParameter().required() && - !m_mainParameterDescription.isAssigned()) { - throw new ParameterException("Main parameters are required (\"" - + m_mainParameterDescription.getDescription() + "\")"); - } - } - } - - /** - * Expand the command line parameters to take @ parameters into account. - * When @ is encountered, the content of the file that follows is inserted - * in the command line. - * - * @param originalArgv the original command line parameters - * @return the new and enriched command line parameters - */ - private String[] expandArgs(String[] originalArgv) { - List vResult1 = Lists.newArrayList(); - - // - // Expand @ - // - for (String arg : originalArgv) { - - if (arg.startsWith("@")) { - String fileName = arg.substring(1); - vResult1.addAll(readFile(fileName)); - } - else { - vResult1.add(arg); - } - } - - // - // Expand separators - // - List vResult2 = Lists.newArrayList(); - for (int i = 0; i < vResult1.size(); i++) { - String arg = vResult1.get(i); - String[] v1 = vResult1.toArray(new String[0]); - if (isOption(v1, arg)) { - String sep = getSeparatorFor(v1, arg); - if (! " ".equals(sep)) { - String[] sp = arg.split("[" + sep + "]"); - for (String ssp : sp) { - vResult2.add(ssp); - } - } else { - vResult2.add(arg); - } - } else { - vResult2.add(arg); - } - } - - return vResult2.toArray(new String[vResult2.size()]); - } - - private boolean isOption(String[] args, String arg) { - String prefixes = getOptionPrefixes(args, arg); - return prefixes.indexOf(arg.charAt(0)) >= 0; - } - - private ParameterDescription getPrefixDescriptionFor(String arg) { - for (Map.Entry es : m_descriptions.entrySet()) { - if (arg.startsWith(es.getKey())) return es.getValue(); - } - - return null; - } - - /** - * If arg is an option, we can look it up directly, but if it's a value, - * we need to find the description for the option that precedes it. - */ - private ParameterDescription getDescriptionFor(String[] args, String arg) { - ParameterDescription result = getPrefixDescriptionFor(arg); - if (result != null) return result; - - for (String a : args) { - ParameterDescription pd = getPrefixDescriptionFor(arg); - if (pd != null) result = pd; - if (a.equals(arg)) return result; - } - - throw new ParameterException("Unknown parameter: " + arg); - } - - private String getSeparatorFor(String[] args, String arg) { - ParameterDescription pd = getDescriptionFor(args, arg); - - // Could be null if only main parameters were passed - if (pd != null) { - Parameters p = pd.getObject().getClass().getAnnotation(Parameters.class); - if (p != null) return p.separators(); - } - - return " "; - } - - private String getOptionPrefixes(String[] args, String arg) { - ParameterDescription pd = getDescriptionFor(args, arg); - - // Could be null if only main parameters were passed - if (pd != null) { - Parameters p = pd.getObject().getClass() - .getAnnotation(Parameters.class); - if (p != null) return p.optionPrefixes(); - } - - return Parameters.DEFAULT_OPTION_PREFIXES; - } - - /** - * Reads the file specified by filename and returns the file content as a string. - * End of lines are replaced by a space. - * - * @param fileName the command line filename - * @return the file content as a string. - */ - private static List readFile(String fileName) { - List result = Lists.newArrayList(); - - try { - BufferedReader bufRead = new BufferedReader(new FileReader(fileName)); - - String line; - - // Read through file one line at time. Print line # and line - while ((line = bufRead.readLine()) != null) { - result.add(line); - } - - bufRead.close(); - } - catch (IOException e) { - throw new ParameterException("Could not read file " + fileName + ": " + e); - } - - return result; - } - - /** - * Remove spaces at both ends and handle double quotes. - */ - private static String trim(String string) { - String result = string.trim(); - if (result.startsWith("\"")) { - if (result.endsWith("\"")) { - return result.substring(1, result.length() - 1); - } - return result.substring(1); - } - return result; - } - - /** - * Create the ParameterDescriptions for all the \@Parameter found. - */ - private void createDescriptions() { - m_descriptions = Maps.newHashMap(); - - for (Object object : m_objects) { - addDescription(object); - } - } - - private void addDescription(Object object) { - Class cls = object.getClass(); - - while (!Object.class.equals(cls)) { - for (Field f : cls.getDeclaredFields()) { - p("Field:" + cls.getSimpleName() + "." + f.getName()); - f.setAccessible(true); - Annotation annotation = f.getAnnotation(Parameter.class); - if (annotation != null) { - Parameter p = (Parameter) annotation; - if (p.names().length == 0) { - p("Found main parameter:" + f); - if (m_mainParameterField != null) { - throw new ParameterException("Only one @Parameter with no names attribute is" - + " allowed, found:" + m_mainParameterField + " and " + f); - } - m_mainParameterField = f; - m_mainParameterObject = object; - m_mainParameterAnnotation = p; - m_mainParameterDescription = new ParameterDescription(object, p, f, m_bundle, this); - } else { - for (String name : p.names()) { - if (m_descriptions.containsKey(name)) { - throw new ParameterException("Found the option " + name + " multiple times"); - } - p("Adding description for " + name); - ParameterDescription pd = new ParameterDescription(object, p, f, m_bundle, this); - m_fields.put(f, pd); - m_descriptions.put(name, pd); - - if (p.required()) m_requiredFields.put(f, pd); - } - } - } - } - // Traverse the super class until we find Object.class - cls = cls.getSuperclass(); - } - } - - private void initializeDefaultValue(ParameterDescription pd) { - String optionName = pd.getParameter().names()[0]; - String def = m_defaultProvider.getDefaultValueFor(optionName); - if (def != null) { - p("Initializing " + optionName + " with default value:" + def); - pd.addValue(def, true /* default */); - } - } - - /** - * Main method that parses the values and initializes the fields accordingly. - */ - private void parseValues(String[] args) { - // This boolean becomes true if we encounter a command, which indicates we need - // to stop parsing (the parsing of the command will be done in a sub JCommander - // object) - boolean commandParsed = false; - int i = 0; - while (i < args.length && ! commandParsed) { - String arg = args[i]; - String a = trim(arg); - p("Parsing arg:" + a); - - if (isOption(args, a)) { - // - // Option - // - ParameterDescription pd = m_descriptions.get(a); - - if (pd != null) { - if (pd.getParameter().password()) { - // - // Password option, use the Console to retrieve the password - // - char[] password = readPassword(pd.getDescription()); - pd.addValue(new String(password)); - } else { - // - // Regular option - // - Class fieldType = pd.getField().getType(); - - // Boolean, set to true as soon as we see it, unless it specified - // an arity of 1, in which case we need to read the next value - if ((fieldType == boolean.class || fieldType == Boolean.class) - && pd.getParameter().arity() == -1) { - pd.addValue("true"); - m_requiredFields.remove(pd.getField()); - } else { - // Regular parameter, use the arity to tell use how many values - // we need to consume - int arity = pd.getParameter().arity(); - int n = (arity != -1 ? arity : 1); - - // Special case for boolean parameters of arity 0 - if (n == 0 && - (Boolean.class.isAssignableFrom(fieldType) - || boolean.class.isAssignableFrom(fieldType))) { - pd.addValue("true"); - m_requiredFields.remove(pd.getField()); - } else if (i < args.length - 1) { - int offset = "--".equals(args[i + 1]) ? 1 : 0; - - if (i + n < args.length) { - for (int j = 1; j <= n; j++) { - pd.addValue(trim(args[i + j + offset])); - m_requiredFields.remove(pd.getField()); - } - i += n + offset; - } else { - throw new ParameterException("Expected " + n + " values after " + arg); - } - } else { - throw new ParameterException("Expected a value after parameter " + arg); - } - } - } - } else { - throw new ParameterException("Unknown option: " + a); - } - } - else { - // - // Main parameter - // - if (! isStringEmpty(arg)) { - if (m_commands.isEmpty()) { - // - // Regular (non-command) parsing - // - List mp = getMainParameter(arg); - String value = arg; - Object convertedValue = value; - - if (m_mainParameterField.getGenericType() instanceof ParameterizedType) { - ParameterizedType p = (ParameterizedType) m_mainParameterField.getGenericType(); - Type cls = p.getActualTypeArguments()[0]; - if (cls instanceof Class) { - convertedValue = convertValue(m_mainParameterField, (Class) cls, value); - } - } - - m_mainParameterDescription.setAssigned(true); - mp.add(convertedValue); - } - else { - // - // Command parsing - // - JCommander jc = m_commands.get(arg); - if (jc == null) throw new ParameterException("Expected a command, got " + arg); - m_parsedCommand = arg; - - // Found a valid command, ask it to parse the remainder of the arguments. - // Setting the boolean commandParsed to true will force the current - // loop to end. - jc.parse(subArray(args, i + 1)); - commandParsed = true; - } - } - } - i++; - } - } - - /** - * Invoke Console.readPassword through reflection to avoid depending - * on Java 6. - */ - private char[] readPassword(String description) { - System.out.print(description + ": "); - try { - Method consoleMethod = System.class.getDeclaredMethod("console", new Class[0]); - Object console = consoleMethod.invoke(null, new Object[0]); - Method readPassword = console.getClass().getDeclaredMethod("readPassword", new Class[0]); - return (char[]) readPassword.invoke(console, new Object[0]); - } catch (Throwable t) { - return readLine(description); - } - } - - /** - * Read a line from stdin (used when java.io.Console is not available) - */ - private char[] readLine(String description) { - try { - InputStreamReader isr = new InputStreamReader(System.in); - BufferedReader in = new BufferedReader(isr); - String result = in.readLine(); - in.close(); - isr.close(); - return result.toCharArray(); - } catch (IOException e) { - throw new ParameterException(e); - } - } - - private String[] subArray(String[] args, int index) { - int l = args.length - index; - String[] result = new String[l]; - System.arraycopy(args, index, result, 0, l); - - return result; - } - - private static boolean isStringEmpty(String s) { - return s == null || "".equals(s); - } - - /** - * @return the field that's meant to receive all the parameters that are not options. - * - * @param arg the arg that we're about to add (only passed here to ouput a meaningful - * error message). - */ - private List getMainParameter(String arg) { - if (m_mainParameterField == null) { - throw new ParameterException( - "Was passed main parameter '" + arg + "' but no main parameter was defined"); - } - - try { - @SuppressWarnings("unchecked") - List result = (List) m_mainParameterField.get(m_mainParameterObject); - if (result == null) { - result = Lists.newArrayList(); - m_mainParameterField.set(m_mainParameterObject, result); - } - return result; - } - catch(IllegalAccessException ex) { - throw new ParameterException("Couldn't access main parameter: " + ex.getMessage()); - } - } - - private String getMainParameterDescription() { - if (m_descriptions == null) createDescriptions(); - return m_mainParameterAnnotation != null ? m_mainParameterAnnotation.description() - : null; - } - - private int longestName(Collection objects) { - int result = 0; - for (Object o : objects) { - int l = o.toString().length(); - if (l > result) result = l; - } - - return result; - } - - /** - * Set the program name (used only in the usage). - */ - public void setProgramName(String name) { - m_programName = name; - } - - /** - * Display the usage for this command. - */ - public void usage(String commandName) { - StringBuilder sb = new StringBuilder(); - usage(commandName, sb); - System.out.println(sb.toString()); - } - - /** - * Store the help for the command in the passed string builder. - */ - public void usage(String commandName, StringBuilder out) { - String description = getCommandDescription(commandName); - JCommander jc = m_commands.get(commandName); - if (description != null) { - out.append(description); - out.append("\n"); - } - jc.usage(out); - } - - /** - * @return the description of the command. - */ - public String getCommandDescription(String commandName) { - JCommander jc = m_commands.get(commandName); - if (jc == null) { - throw new ParameterException("Asking description for unknown command: " + commandName); - } - - Parameters p = jc.getObjects().get(0).getClass().getAnnotation(Parameters.class); - String result = jc.getMainParameterDescription(); - if (p != null) result = p.commandDescription(); - - return result; - } - - /** - * Display a the help on System.out. - */ - public void usage() { - StringBuilder sb = new StringBuilder(); - usage(sb); - System.out.println(sb.toString()); - } - - /** - * Store the help in the passed string builder. - */ - public void usage(StringBuilder out) { - if (m_descriptions == null) createDescriptions(); - boolean hasCommands = ! m_commands.isEmpty(); - - // - // First line of the usage - // - String programName = m_programName != null ? m_programName : "
"; - out.append("Usage: " + programName + " [options]"); - if (hasCommands) out.append(" [command] [command options]"); - out.append("\n"); - if (m_mainParameterAnnotation != null) { - out.append(" " + m_mainParameterAnnotation.description() + "\n"); - } - out.append(" Options:\n"); - - // - // Align the descriptions at the "longestName" column - // - int longestName = 0; - List sorted = Lists.newArrayList(); - for (ParameterDescription pd : m_fields.values()) { - if (! pd.getParameter().hidden()) { - sorted.add(pd); - // + to have an extra space between the name and the description - int length = pd.getNames().length() + 2; - if (length > longestName) { - longestName = length; - } - } - } - - // - // Sort the options - // - Collections.sort(sorted, new Comparator() { - public int compare(ParameterDescription p0, ParameterDescription p1) { - return p0.getLongestName().compareTo(p1.getLongestName()); - } - }); - - // - // Display all the names and descriptions - // - for (ParameterDescription pd : sorted) { - int l = pd.getNames().length(); - int spaceCount = longestName - l; - int start = out.length(); - out.append(" " - + (pd.getParameter().required() ? "* " : " ") - + pd.getNames() + s(spaceCount)); - int indent = out.length() - start; - wrapDescription(out, indent, pd.getDescription()); - Object def = pd.getDefault(); - if (def != null) out.append("\n" + spaces(indent + 1)).append("Default: " + def); - out.append("\n"); - } - - // - // If commands were specified, show them as well - // - if (hasCommands) { - out.append(" Commands:\n"); - // The magic value 3 is the number of spaces between the name of the option - // and its description - int ln = longestName(m_commands.keySet()) + 3; - for (Map.Entry commands : m_commands.entrySet()) { - String name = commands.getKey(); - int spaceCount = ln - name.length(); - out.append(" " + name + s(spaceCount) + getCommandDescription(name) + "\n"); - } - } - } - - private void wrapDescription(StringBuilder out, int indent, String description) { - int max = 79; - String[] words = description.split(" "); - int current = indent; - int i = 0; - while (i < words.length) { - String word = words[i]; - if (word.length() > max || current + word.length() <= max) { - out.append(" ").append(word); - current += word.length() + 1; - i++; - } else { - out.append("\n").append(spaces(indent)); - current = indent; - } - } - } - - private String spaces(int indent) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < indent; i++) sb.append(" "); - return sb.toString(); - } - - /** - * @return a Collection of all the \@Parameter annotations found on the - * target class. This can be used to display the usage() in a different - * format (e.g. HTML). - */ - public List getParameters() { - return new ArrayList(m_fields.values()); - } - - private void p(String string) { - if (System.getProperty(JCommander.DEBUG_PROPERTY) != null) { - System.out.println("[JCommander] " + string); - } - } - - /** - * Define the default provider for this instance. - */ - public void setDefaultProvider(IDefaultProvider defaultProvider) { - m_defaultProvider = defaultProvider; - } - - public void addConverterFactory(IStringConverterFactory converterFactory) { - CONVERTER_FACTORIES.add(converterFactory); - } - - public Class> findConverter(Class cls) { - for (IStringConverterFactory f : CONVERTER_FACTORIES) { - Class> result = f.getConverter(cls); - if (result != null) return result; - } - - return null; - } - - public Object convertValue(ParameterDescription pd, String value) { - return convertValue(pd.getField(), pd.getField().getType(), value); - } - - /** - * @param field The field - * @param type The type of the actual parameter - * @param value The value to convert - */ - public Object convertValue(Field field, Class type, String value) { - Parameter annotation = field.getAnnotation(Parameter.class); - Class> converterClass = annotation.converter(); - - // - // Try to find a converter on the annotation - // - if (converterClass == null || converterClass == NoConverter.class) { - converterClass = findConverter(type); - } - if (converterClass == null) { - converterClass = StringConverter.class; - } - if (converterClass == null && Collection.class.isAssignableFrom(type)) { - converterClass = StringConverter.class; - } - - // -// // -// // Try to find a converter in the factory -// // -// IStringConverter converter = null; -// if (converterClass == null && m_converterFactories != null) { -// // Mmmh, javac requires a cast here -// converter = (IStringConverter) m_converterFactories.getConverter(type); -// } - - if (converterClass == null) { - throw new ParameterException("Don't know how to convert " + value - + " to type " + type + " (field: " + field.getName() + ")"); - } - - IStringConverter converter; - Object result = null; - try { - String[] names = annotation.names(); - String optionName = names.length > 0 ? names[0] : "[Main class]"; - converter = instantiateConverter(optionName, converterClass); - result = converter.convert(value); - } catch (InstantiationException e) { - throw new ParameterException(e); - } catch (IllegalAccessException e) { - throw new ParameterException(e); - } catch (InvocationTargetException e) { - throw new ParameterException(e); - } - - return result; - } - - private IStringConverter instantiateConverter(String optionName, - Class> converterClass) - throws IllegalArgumentException, InstantiationException, IllegalAccessException, - InvocationTargetException { - Constructor> ctor = null; - Constructor> stringCtor = null; - Constructor>[] ctors - = (Constructor>[]) converterClass.getDeclaredConstructors(); - for (Constructor> c : ctors) { - Class[] types = c.getParameterTypes(); - if (types.length == 1 && types[0].equals(String.class)) { - stringCtor = c; - } else if (types.length == 0) { - ctor = c; - } - } - - IStringConverter result = stringCtor != null - ? stringCtor.newInstance(optionName) - : ctor.newInstance(); - - return result; - } - - /** - * Add a command object. - */ - public void addCommand(String name, Object object) { - JCommander jc = new JCommander(object); - jc.setProgramName(name); - m_commands.put(name, jc); - } - - public Map getCommands() { - return m_commands; - } - - public String getParsedCommand() { - return m_parsedCommand; - } - - /** - * @return n spaces - */ - private String s(int count) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < count; i++) { - result.append(" "); - } - - return result.toString(); - } - - /** - * @return the objects that JCommander will fill with the result of - * parsing the command line. - */ - public List getObjects() { - return m_objects; - } -} - diff --git a/All/Genesis-NP/Genesis#55/old/JCommander.java b/All/Genesis-NP/Genesis#55/old/JCommander.java deleted file mode 100755 index 46f3b9b..0000000 --- a/All/Genesis-NP/Genesis#55/old/JCommander.java +++ /dev/null @@ -1,977 +0,0 @@ -/** - * Copyright (C) 2010 the original author or authors. - * See the notice.md file distributed with this work for additional - * information regarding copyright ownership. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.beust.jcommander; - -import com.beust.jcommander.converters.NoConverter; -import com.beust.jcommander.converters.StringConverter; -import com.beust.jcommander.internal.DefaultConverterFactory; -import com.beust.jcommander.internal.Lists; -import com.beust.jcommander.internal.Maps; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - -/** - * The main class for JCommander. It's responsible for parsing the object that contains - * all the annotated fields, parse the command line and assign the fields with the correct - * values and a few other helper methods, such as usage(). - * - * The object(s) you pass in the constructor are expected to have one or more - * \@Parameter annotations on them. You can pass either a single object, an array of objects - * or an instance of Iterable. In the case of an array or Iterable, JCommander will collect - * the \@Parameter annotations from all the objects passed in parameter. - * - * @author cbeust - */ -public class JCommander { - public static final String DEBUG_PROPERTY = "jcommander.debug"; - - /** - * A map to look up parameter description per option name. - */ - private Map m_descriptions; - - /** - * The objects that contain fields annotated with @Parameter. - */ - private List m_objects = Lists.newArrayList(); - - /** - * This field will contain whatever command line parameter is not an option. - * It is expected to be a List. - */ - private Field m_mainParameterField = null; - - /** - * The object on which we found the main parameter field. - */ - private Object m_mainParameterObject; - - /** - * The annotation found on the main parameter field. - */ - private Parameter m_mainParameterAnnotation; - - private ParameterDescription m_mainParameterDescription; - - /** - * A set of all the fields that are required. During the reflection phase, - * this field receives all the fields that are annotated with required=true - * and during the parsing phase, all the fields that are assigned a value - * are removed from it. At the end of the parsing phase, if it's not empty, - * then some required fields did not receive a value and an exception is - * thrown. - */ - private Map m_requiredFields = Maps.newHashMap(); - - /** - * A map of all the annotated fields. - */ - private Map m_fields = Maps.newHashMap(); - - private ResourceBundle m_bundle; - - /** - * A default provider returns default values for the parameters. - */ - private IDefaultProvider m_defaultProvider; - - /** - * List of commands and their instance. - */ - private Map m_commands = Maps.newLinkedHashMap(); - - /** - * The name of the command after the parsing has run. - */ - private String m_parsedCommand; - - private String m_programName; - - /** - * The factories used to look up string converters. - */ - private static List CONVERTER_FACTORIES = Lists.newArrayList(); - - static { - CONVERTER_FACTORIES.add(new DefaultConverterFactory()); - }; - - /** - * Creates a new un-configured JCommander object. - */ - public JCommander() { - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - */ - public JCommander(Object object) { - addObject(object); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param bundle The bundle to use for the descriptions. Can be null. - */ - public JCommander(Object object, ResourceBundle bundle) { - addObject(object); - setDescriptionsBundle(bundle); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param bundle The bundle to use for the descriptions. Can be null. - * @param args The arguments to parse (optional). - */ - public JCommander(Object object, ResourceBundle bundle, String... args) { - addObject(object); - setDescriptionsBundle(bundle); - parse(args); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param args The arguments to parse (optional). - */ - public JCommander(Object object, String... args) { - addObject(object); - parse(args); - } - - /** - * Adds the provided arg object to the set of objects that this commander - * will parse arguments into. - * - * @param object The arg object expected to contain {@link Parameter} - * annotations. If object is an array or is {@link Iterable}, - * the child objects will be added instead. - */ - // declared final since this is invoked from constructors - public final void addObject(Object object) { - if (object instanceof Iterable) { - // Iterable - for (Object o : (Iterable) object) { - m_objects.add(o); - } - } else if (object.getClass().isArray()) { - // Array - for (Object o : (Object[]) object) { - m_objects.add(o); - } - } else { - // Single object - m_objects.add(object); - } - } - - /** - * Sets the {@link ResourceBundle} to use for looking up descriptions. - * Set this to null to use description text directly. - */ - // declared final since this is invoked from constructors - public final void setDescriptionsBundle(ResourceBundle bundle) { - m_bundle = bundle; - } - - /** - * Parse the command line parameters. - */ - public void parse(String... args) { - StringBuilder sb = new StringBuilder("Parsing \""); - sb.append(join(args).append("\"\n with:").append(join(m_objects.toArray()))); - p(sb.toString()); - - if (m_descriptions == null) createDescriptions(); - initializeDefaultValues(); - parseValues(expandArgs(args)); - validateOptions(); - } - - private StringBuilder join(Object[] args) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < args.length; i++) { - if (i > 0) result.append(" "); - result.append(args[i]); - } - return result; - } - - private void initializeDefaultValues() { - if (m_defaultProvider != null) { - for (ParameterDescription pd : m_descriptions.values()) { - initializeDefaultValue(pd); - } - } - } - - /** - * Make sure that all the required parameters have received a value. - */ - private void validateOptions() { - if (! m_requiredFields.isEmpty()) { - StringBuilder missingFields = new StringBuilder(); - for (ParameterDescription pd : m_requiredFields.values()) { - missingFields.append(pd.getNames()).append(" "); - } - throw new ParameterException("The following options are required: " + missingFields); - } - - if (m_mainParameterDescription != null) { - if (m_mainParameterDescription.getParameter().required() && - !m_mainParameterDescription.isAssigned()) { - throw new ParameterException("Main parameters are required (\"" - + m_mainParameterDescription.getDescription() + "\")"); - } - } - } - - /** - * Expand the command line parameters to take @ parameters into account. - * When @ is encountered, the content of the file that follows is inserted - * in the command line. - * - * @param originalArgv the original command line parameters - * @return the new and enriched command line parameters - */ - private String[] expandArgs(String[] originalArgv) { - List vResult1 = Lists.newArrayList(); - - // - // Expand @ - // - for (String arg : originalArgv) { - - if (arg.startsWith("@")) { - String fileName = arg.substring(1); - vResult1.addAll(readFile(fileName)); - } - else { - vResult1.add(arg); - } - } - - // - // Expand separators - // - List vResult2 = Lists.newArrayList(); - for (int i = 0; i < vResult1.size(); i++) { - String arg = vResult1.get(i); - String[] v1 = vResult1.toArray(new String[0]); - if (isOption(v1, arg)) { - String sep = getSeparatorFor(v1, arg); - if (! " ".equals(sep)) { - String[] sp = arg.split("[" + sep + "]"); - for (String ssp : sp) { - vResult2.add(ssp); - } - } else { - vResult2.add(arg); - } - } else { - vResult2.add(arg); - } - } - - return vResult2.toArray(new String[vResult2.size()]); - } - - private boolean isOption(String[] args, String arg) { - String prefixes = getOptionPrefixes(args, arg); - return prefixes.indexOf(arg.charAt(0)) >= 0; - } - - private ParameterDescription getPrefixDescriptionFor(String arg) { - for (Map.Entry es : m_descriptions.entrySet()) { - if (arg.startsWith(es.getKey())) return es.getValue(); - } - - return null; - } - - /** - * If arg is an option, we can look it up directly, but if it's a value, - * we need to find the description for the option that precedes it. - */ - private ParameterDescription getDescriptionFor(String[] args, String arg) { - ParameterDescription result = getPrefixDescriptionFor(arg); - if (result != null) return result; - - for (String a : args) { - ParameterDescription pd = getPrefixDescriptionFor(arg); - if (pd != null) result = pd; - if (a.equals(arg)) return result; - } - - throw new ParameterException("Unknown parameter: " + arg); - } - - private String getSeparatorFor(String[] args, String arg) { - ParameterDescription pd = getDescriptionFor(args, arg); - - // Could be null if only main parameters were passed - if (pd != null) { - Parameters p = pd.getObject().getClass().getAnnotation(Parameters.class); - if (p != null) return p.separators(); - } - - return " "; - } - - private String getOptionPrefixes(String[] args, String arg) { - ParameterDescription pd = getDescriptionFor(args, arg); - - // Could be null if only main parameters were passed - if (pd != null) { - Parameters p = pd.getObject().getClass() - .getAnnotation(Parameters.class); - if (p != null) return p.optionPrefixes(); - } - - return Parameters.DEFAULT_OPTION_PREFIXES; - } - - /** - * Reads the file specified by filename and returns the file content as a string. - * End of lines are replaced by a space. - * - * @param fileName the command line filename - * @return the file content as a string. - */ - private static List readFile(String fileName) { - List result = Lists.newArrayList(); - - try { - BufferedReader bufRead = new BufferedReader(new FileReader(fileName)); - - String line; - - // Read through file one line at time. Print line # and line - while ((line = bufRead.readLine()) != null) { - result.add(line); - } - - bufRead.close(); - } - catch (IOException e) { - throw new ParameterException("Could not read file " + fileName + ": " + e); - } - - return result; - } - - /** - * Remove spaces at both ends and handle double quotes. - */ - private static String trim(String string) { - String result = string.trim(); - if (result.startsWith("\"")) { - if (result.endsWith("\"")) { - return result.substring(1, result.length() - 1); - } - return result.substring(1); - } - return result; - } - - /** - * Create the ParameterDescriptions for all the \@Parameter found. - */ - private void createDescriptions() { - m_descriptions = Maps.newHashMap(); - - for (Object object : m_objects) { - addDescription(object); - } - } - - private void addDescription(Object object) { - Class cls = object.getClass(); - - while (!Object.class.equals(cls)) { - for (Field f : cls.getDeclaredFields()) { - p("Field:" + cls.getSimpleName() + "." + f.getName()); - f.setAccessible(true); - Annotation annotation = f.getAnnotation(Parameter.class); - if (annotation != null) { - Parameter p = (Parameter) annotation; - if (p.names().length == 0) { - p("Found main parameter:" + f); - if (m_mainParameterField != null) { - throw new ParameterException("Only one @Parameter with no names attribute is" - + " allowed, found:" + m_mainParameterField + " and " + f); - } - m_mainParameterField = f; - m_mainParameterObject = object; - m_mainParameterAnnotation = p; - m_mainParameterDescription = new ParameterDescription(object, p, f, m_bundle, this); - } else { - for (String name : p.names()) { - if (m_descriptions.containsKey(name)) { - throw new ParameterException("Found the option " + name + " multiple times"); - } - p("Adding description for " + name); - ParameterDescription pd = new ParameterDescription(object, p, f, m_bundle, this); - m_fields.put(f, pd); - m_descriptions.put(name, pd); - - if (p.required()) m_requiredFields.put(f, pd); - } - } - } - } - // Traverse the super class until we find Object.class - cls = cls.getSuperclass(); - } - } - - private void initializeDefaultValue(ParameterDescription pd) { - String optionName = pd.getParameter().names()[0]; - String def = m_defaultProvider.getDefaultValueFor(optionName); - if (def != null) { - p("Initializing " + optionName + " with default value:" + def); - pd.addValue(def, true /* default */); - } - } - - /** - * Main method that parses the values and initializes the fields accordingly. - */ - private void parseValues(String[] args) { - // This boolean becomes true if we encounter a command, which indicates we need - // to stop parsing (the parsing of the command will be done in a sub JCommander - // object) - boolean commandParsed = false; - int i = 0; - while (i < args.length && ! commandParsed) { - String arg = args[i]; - String a = trim(arg); - p("Parsing arg:" + a); - - if (isOption(args, a)) { - // - // Option - // - ParameterDescription pd = m_descriptions.get(a); - - if (pd != null) { - if (pd.getParameter().password()) { - // - // Password option, use the Console to retrieve the password - // - char[] password = readPassword(pd.getDescription()); - pd.addValue(new String(password)); - } else { - // - // Regular option - // - Class fieldType = pd.getField().getType(); - - // Boolean, set to true as soon as we see it, unless it specified - // an arity of 1, in which case we need to read the next value - if ((fieldType == boolean.class || fieldType == Boolean.class) - && pd.getParameter().arity() == -1) { - pd.addValue("true"); - m_requiredFields.remove(pd.getField()); - } else { - // Regular parameter, use the arity to tell use how many values - // we need to consume - int arity = pd.getParameter().arity(); - int n = (arity != -1 ? arity : 1); - - // Special case for boolean parameters of arity 0 - if (n == 0 && - (Boolean.class.isAssignableFrom(fieldType) - || boolean.class.isAssignableFrom(fieldType))) { - pd.addValue("true"); - m_requiredFields.remove(pd.getField()); - } else if (i < args.length - 1) { - int offset = "--".equals(args[i + 1]) ? 1 : 0; - - if (i + n < args.length) { - for (int j = 1; j <= n; j++) { - pd.addValue(trim(args[i + j + offset])); - m_requiredFields.remove(pd.getField()); - } - i += n + offset; - } else { - throw new ParameterException("Expected " + n + " values after " + arg); - } - } else { - throw new ParameterException("Expected a value after parameter " + arg); - } - } - } - } else { - throw new ParameterException("Unknown option: " + a); - } - } - else { - // - // Main parameter - // - if (! isStringEmpty(arg)) { - if (m_commands.isEmpty()) { - // - // Regular (non-command) parsing - // - List mp = getMainParameter(arg); - String value = arg; - Object convertedValue = value; - - if (m_mainParameterField.getGenericType() instanceof ParameterizedType) { - ParameterizedType p = (ParameterizedType) m_mainParameterField.getGenericType(); - Type cls = p.getActualTypeArguments()[0]; - if (cls instanceof Class) { - convertedValue = convertValue(m_mainParameterField, (Class) cls, value); - } - } - - m_mainParameterDescription.setAssigned(true); - mp.add(convertedValue); - } - else { - // - // Command parsing - // - JCommander jc = m_commands.get(arg); - if (jc == null) throw new ParameterException("Expected a command, got " + arg); - m_parsedCommand = arg; - - // Found a valid command, ask it to parse the remainder of the arguments. - // Setting the boolean commandParsed to true will force the current - // loop to end. - jc.parse(subArray(args, i + 1)); - commandParsed = true; - } - } - } - i++; - } - } - - /** - * Invoke Console.readPassword through reflection to avoid depending - * on Java 6. - */ - private char[] readPassword(String description) { - System.out.print(description + ": "); - try { - Method consoleMethod = System.class.getDeclaredMethod("console", new Class[0]); - Object console = consoleMethod.invoke(null, new Object[0]); - Method readPassword = console.getClass().getDeclaredMethod("readPassword", new Class[0]); - return (char[]) readPassword.invoke(console, new Object[0]); - } catch (Throwable t) { - return readLine(description); - } - } - - /** - * Read a line from stdin (used when java.io.Console is not available) - */ - private char[] readLine(String description) { - try { - InputStreamReader isr = new InputStreamReader(System.in); - BufferedReader in = new BufferedReader(isr); - String result = in.readLine(); - in.close(); - isr.close(); - return result.toCharArray(); - } catch (IOException e) { - throw new ParameterException(e); - } - } - - private String[] subArray(String[] args, int index) { - int l = args.length - index; - String[] result = new String[l]; - System.arraycopy(args, index, result, 0, l); - - return result; - } - - private static boolean isStringEmpty(String s) { - return s == null || "".equals(s); - } - - /** - * @return the field that's meant to receive all the parameters that are not options. - * - * @param arg the arg that we're about to add (only passed here to ouput a meaningful - * error message). - */ - private List getMainParameter(String arg) { - if (m_mainParameterField == null) { - throw new ParameterException( - "Was passed main parameter '" + arg + "' but no main parameter was defined"); - } - - try { - @SuppressWarnings("unchecked") - List result = (List) m_mainParameterField.get(m_mainParameterObject); - if (result == null) { - result = Lists.newArrayList(); - m_mainParameterField.set(m_mainParameterObject, result); - } - return result; - } - catch(IllegalAccessException ex) { - throw new ParameterException("Couldn't access main parameter: " + ex.getMessage()); - } - } - - private String getMainParameterDescription() { - if (m_descriptions == null) createDescriptions(); - return m_mainParameterAnnotation != null ? m_mainParameterAnnotation.description() - : null; - } - - private int longestName(Collection objects) { - int result = 0; - for (Object o : objects) { - int l = o.toString().length(); - if (l > result) result = l; - } - - return result; - } - - /** - * Set the program name (used only in the usage). - */ - public void setProgramName(String name) { - m_programName = name; - } - - /** - * Display the usage for this command. - */ - public void usage(String commandName) { - StringBuilder sb = new StringBuilder(); - usage(commandName, sb); - System.out.println(sb.toString()); - } - - /** - * Store the help for the command in the passed string builder. - */ - public void usage(String commandName, StringBuilder out) { - String description = getCommandDescription(commandName); - JCommander jc = m_commands.get(commandName); - if (description != null) { - out.append(description); - out.append("\n"); - } - jc.usage(out); - } - - /** - * @return the description of the command. - */ - public String getCommandDescription(String commandName) { - JCommander jc = m_commands.get(commandName); - Parameters p = jc.getObjects().get(0).getClass().getAnnotation(Parameters.class); - String result = jc.getMainParameterDescription(); - if (p != null) result = p.commandDescription(); - - return result; - } - - /** - * Display a the help on System.out. - */ - public void usage() { - StringBuilder sb = new StringBuilder(); - usage(sb); - System.out.println(sb.toString()); - } - - /** - * Store the help in the passed string builder. - */ - public void usage(StringBuilder out) { - if (m_descriptions == null) createDescriptions(); - boolean hasCommands = ! m_commands.isEmpty(); - - // - // First line of the usage - // - String programName = m_programName != null ? m_programName : "
"; - out.append("Usage: " + programName + " [options]"); - if (hasCommands) out.append(" [command] [command options]"); - out.append("\n"); - if (m_mainParameterAnnotation != null) { - out.append(" " + m_mainParameterAnnotation.description() + "\n"); - } - out.append(" Options:\n"); - - // - // Align the descriptions at the "longestName" column - // - int longestName = 0; - List sorted = Lists.newArrayList(); - for (ParameterDescription pd : m_fields.values()) { - if (! pd.getParameter().hidden()) { - sorted.add(pd); - // + to have an extra space between the name and the description - int length = pd.getNames().length() + 2; - if (length > longestName) { - longestName = length; - } - } - } - - // - // Sort the options - // - Collections.sort(sorted, new Comparator() { - public int compare(ParameterDescription p0, ParameterDescription p1) { - return p0.getLongestName().compareTo(p1.getLongestName()); - } - }); - - // - // Display all the names and descriptions - // - for (ParameterDescription pd : sorted) { - int l = pd.getNames().length(); - int spaceCount = longestName - l; - int start = out.length(); - out.append(" " - + (pd.getParameter().required() ? "* " : " ") - + pd.getNames() + s(spaceCount)); - int indent = out.length() - start; - wrapDescription(out, indent, pd.getDescription()); - Object def = pd.getDefault(); - if (def != null) out.append("\n" + spaces(indent + 1)).append("Default: " + def); - out.append("\n"); - } - - // - // If commands were specified, show them as well - // - if (hasCommands) { - out.append(" Commands:\n"); - // The magic value 3 is the number of spaces between the name of the option - // and its description - int ln = longestName(m_commands.keySet()) + 3; - for (Map.Entry commands : m_commands.entrySet()) { - String name = commands.getKey(); - int spaceCount = ln - name.length(); - out.append(" " + name + s(spaceCount) + getCommandDescription(name) + "\n"); - } - } - } - - private void wrapDescription(StringBuilder out, int indent, String description) { - int max = 79; - String[] words = description.split(" "); - int current = indent; - int i = 0; - while (i < words.length) { - String word = words[i]; - if (word.length() > max || current + word.length() <= max) { - out.append(" ").append(word); - current += word.length() + 1; - i++; - } else { - out.append("\n").append(spaces(indent)); - current = indent; - } - } - } - - private String spaces(int indent) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < indent; i++) sb.append(" "); - return sb.toString(); - } - - /** - * @return a Collection of all the \@Parameter annotations found on the - * target class. This can be used to display the usage() in a different - * format (e.g. HTML). - */ - public List getParameters() { - return new ArrayList(m_fields.values()); - } - - private void p(String string) { - if (System.getProperty(JCommander.DEBUG_PROPERTY) != null) { - System.out.println("[JCommander] " + string); - } - } - - /** - * Define the default provider for this instance. - */ - public void setDefaultProvider(IDefaultProvider defaultProvider) { - m_defaultProvider = defaultProvider; - } - - public void addConverterFactory(IStringConverterFactory converterFactory) { - CONVERTER_FACTORIES.add(converterFactory); - } - - public Class> findConverter(Class cls) { - for (IStringConverterFactory f : CONVERTER_FACTORIES) { - Class> result = f.getConverter(cls); - if (result != null) return result; - } - - return null; - } - - public Object convertValue(ParameterDescription pd, String value) { - return convertValue(pd.getField(), pd.getField().getType(), value); - } - - /** - * @param field The field - * @param type The type of the actual parameter - * @param value The value to convert - */ - public Object convertValue(Field field, Class type, String value) { - Parameter annotation = field.getAnnotation(Parameter.class); - Class> converterClass = annotation.converter(); - - // - // Try to find a converter on the annotation - // - if (converterClass == null || converterClass == NoConverter.class) { - converterClass = findConverter(type); - } - if (converterClass == null) { - converterClass = StringConverter.class; - } - if (converterClass == null && Collection.class.isAssignableFrom(type)) { - converterClass = StringConverter.class; - } - - // -// // -// // Try to find a converter in the factory -// // -// IStringConverter converter = null; -// if (converterClass == null && m_converterFactories != null) { -// // Mmmh, javac requires a cast here -// converter = (IStringConverter) m_converterFactories.getConverter(type); -// } - - if (converterClass == null) { - throw new ParameterException("Don't know how to convert " + value - + " to type " + type + " (field: " + field.getName() + ")"); - } - - IStringConverter converter; - Object result = null; - try { - String[] names = annotation.names(); - String optionName = names.length > 0 ? names[0] : "[Main class]"; - converter = instantiateConverter(optionName, converterClass); - result = converter.convert(value); - } catch (InstantiationException e) { - throw new ParameterException(e); - } catch (IllegalAccessException e) { - throw new ParameterException(e); - } catch (InvocationTargetException e) { - throw new ParameterException(e); - } - - return result; - } - - private IStringConverter instantiateConverter(String optionName, - Class> converterClass) - throws IllegalArgumentException, InstantiationException, IllegalAccessException, - InvocationTargetException { - Constructor> ctor = null; - Constructor> stringCtor = null; - Constructor>[] ctors - = (Constructor>[]) converterClass.getDeclaredConstructors(); - for (Constructor> c : ctors) { - Class[] types = c.getParameterTypes(); - if (types.length == 1 && types[0].equals(String.class)) { - stringCtor = c; - } else if (types.length == 0) { - ctor = c; - } - } - - IStringConverter result = stringCtor != null - ? stringCtor.newInstance(optionName) - : ctor.newInstance(); - - return result; - } - - /** - * Add a command object. - */ - public void addCommand(String name, Object object) { - JCommander jc = new JCommander(object); - jc.setProgramName(name); - m_commands.put(name, jc); - } - - public Map getCommands() { - return m_commands; - } - - public String getParsedCommand() { - return m_parsedCommand; - } - - /** - * @return n spaces - */ - private String s(int count) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < count; i++) { - result.append(" "); - } - - return result.toString(); - } - - /** - * @return the objects that JCommander will fill with the result of - * parsing the command line. - */ - public List getObjects() { - return m_objects; - } -} - diff --git a/All/Genesis-NP/Genesis#55/pair.info b/All/Genesis-NP/Genesis#55/pair.info deleted file mode 100755 index 9acf0f2..0000000 --- a/All/Genesis-NP/Genesis#55/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:55 -SATName:Genesis -modifiedFPath:src/main/java/com/beust/jcommander/JCommander.java -comSha:e2d8da7b584b6a13c23de32ce2df0799a4d3513d -parentComSha:e2d8da7b584b6a13c23de32ce2df0799a4d3513d^1 -githubUrl:https://github.com/cbeust/jcommander -repoName:cbeust#jcommander \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#56/comMsg.txt b/All/Genesis-NP/Genesis#56/comMsg.txt deleted file mode 100755 index 9fd5719..0000000 --- a/All/Genesis-NP/Genesis#56/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -[MNG-5971] Imported dependencies should be available to inheritance processing diff --git a/All/Genesis-NP/Genesis#56/diff.diff b/All/Genesis-NP/Genesis#56/diff.diff deleted file mode 100755 index d35cb53..0000000 --- a/All/Genesis-NP/Genesis#56/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/maven-model-builder/src/main/java/org/apache/maven/model/composition/DefaultDependencyManagementImporter.java b/maven-model-builder/src/main/java/org/apache/maven/model/composition/DefaultDependencyManagementImporter.java -index 0854477..831e754 100644 ---- a/maven-model-builder/src/main/java/org/apache/maven/model/composition/DefaultDependencyManagementImporter.java -+++ b/maven-model-builder/src/main/java/org/apache/maven/model/composition/DefaultDependencyManagementImporter.java -@@ -110 +110 @@ public void importManagement( final Model target, final List sources, - final ModelBuildingRequest request, final ModelProblemCollector problems ) - { - // Intentionally does not check for conflicts in the source dependencies. We want such conflicts to be resolved - // manually instead of silently getting dropped. - - if ( sources != null && !sources.isEmpty() ) - { - final Map targetDependencies = new LinkedHashMap<>(); - final DependencyManagement targetDependencyManagement = target.getDependencyManagement() != null - ? target.getDependencyManagement() - : new DependencyManagement(); - - target.setDependencyManagement( targetDependencyManagement ); - - for ( final Dependency targetDependency : targetDependencyManagement.getDependencies() ) - { - targetDependencies.put( targetDependency.getManagementKey(), targetDependency ); - } - - final Map> sourceDependencies = new LinkedHashMap<>(); - - for ( final DependencyManagement source : sources ) - { - for ( final Dependency sourceDependency : source.getDependencies() ) - { - if ( !targetDependencies.containsKey( sourceDependency.getManagementKey() ) ) - { - List conflictCanditates = - sourceDependencies.get( sourceDependency.getManagementKey() ); - - if ( conflictCanditates == null ) - { - conflictCanditates = new ArrayList<>(); - sourceDependencies.put( sourceDependency.getManagementKey(), conflictCanditates ); - } - - conflictCanditates.add( sourceDependency ); - } - } - } - - for ( final List conflictCanditates : sourceDependencies.values() ) - { - final List conflictingDependencies = - this.removeRedundantDependencies( conflictCanditates ); - - targetDependencyManagement.getDependencies().addAll( conflictingDependencies ); - - if ( conflictingDependencies.size() > 1 ) - { - final StringBuilder conflictsBuilder = new StringBuilder( conflictingDependencies.size() * 128 ); - - for ( final Dependency dependency : conflictingDependencies ) - { - conflictsBuilder.append( ", '" ).append( dependency.getLocation( "" ) ).append( '\'' ); - } - - problems.add( new ModelProblemCollectorRequest( ModelProblem.Severity.WARNING, - ModelProblem.Version.BASE ). - setMessage( String.format( - "Multiple conflicting imports of dependency '%1$s' into model '%2$s'%3$s(%4$s). " - + "To resolve this conflict, either declare the dependency directly " - + "in model '%2$s' to override what gets imported or rearrange the causing " - + "imports in the inheritance hierarchy to apply standard override logic. " - + "Without resolving this conflict, your build relies on indeterministic " - + "behaviour.", - conflictingDependencies.get( 0 ).getManagementKey(), target.getId(), - target.getPomFile() != null - ? " @ '" + target.getPomFile().getAbsolutePath() + "' " - : " ", conflictsBuilder.substring( 2 ) ) ) ); - - } - } - } - } - - private List removeRedundantDependencies( final List candidateDependencies ) - { - final List resultDependencies = new ArrayList<>( candidateDependencies.size() ); - - while ( !candidateDependencies.isEmpty() ) - { - final Dependency resultDependency = candidateDependencies.remove( 0 ); - resultDependencies.add( resultDependency ); - - // Removes redundant dependencies. - for ( final Iterator it = candidateDependencies.iterator(); it.hasNext(); ) - { - final Dependency candidateDependency = it.next(); - it.remove(); - - boolean redundant = true; - - redundancy_check: - { - if ( !( resultDependency.getOptional() != null - ? resultDependency.getOptional().equals( candidateDependency.getOptional() ) - : candidateDependency.getOptional() == null ) ) - { - redundant = false; - break redundancy_check; - } - - if ( !( resultDependency.getScope() != null - ? resultDependency.getScope().equals( candidateDependency.getScope() ) - : candidateDependency.getScope() == null ) ) - { - redundant = false; - break redundancy_check; - } - - if ( !( resultDependency.getSystemPath() != null - ? resultDependency.getSystemPath().equals( candidateDependency.getSystemPath() ) - : candidateDependency.getSystemPath() == null ) ) - { - redundant = false; - break redundancy_check; - } - - if ( !( resultDependency.getVersion() != null - ? resultDependency.getVersion().equals( candidateDependency.getVersion() ) - : candidateDependency.getVersion() == null ) ) - { - redundant = false; - break redundancy_check; - } - - for ( int i = 0, s0 = resultDependency.getExclusions().size(); i < s0; i++ ) - { - final Exclusion resultExclusion = resultDependency.getExclusions().get( i ); - - if ( !containsExclusion( candidateDependency.getExclusions(), resultExclusion ) ) - { - redundant = false; - break redundancy_check; - } - } - - for ( int i = 0, s0 = candidateDependency.getExclusions().size(); i < s0; i++ ) - { - final Exclusion candidateExclusion = candidateDependency.getExclusions().get( i ); - - if ( !containsExclusion( resultDependency.getExclusions(), candidateExclusion ) ) - { - redundant = false; - break redundancy_check; - } - } - } - - if ( !redundant ) - { - resultDependencies.add( candidateDependency ); - } - } - } - - return resultDependencies; - } - - private static boolean containsExclusion( final List exclusions, final Exclusion exclusion ) - { - for ( int i = 0, s0 = exclusions.size(); i < s0; i++ ) - { - final Exclusion current = exclusions.get( i ); - - if ( ( exclusion.getArtifactId() != null - ? exclusion.getArtifactId().equals( current.getArtifactId() ) - : current.getArtifactId() == null ) - && ( exclusion.getGroupId() != null - ? exclusion.getGroupId().equals( current.getGroupId() ) - : current.getGroupId() == null ) ) - { - return true; - } - } - - return false; - } - -} diff --git a/All/Genesis-NP/Genesis#56/old/DefaultDependencyManagementImporter.java b/All/Genesis-NP/Genesis#56/old/DefaultDependencyManagementImporter.java deleted file mode 100755 index 0854477..0000000 --- a/All/Genesis-NP/Genesis#56/old/DefaultDependencyManagementImporter.java +++ /dev/null @@ -1,228 +0,0 @@ -package org.apache.maven.model.composition; - -/* - * 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. - */ - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.maven.model.Dependency; -import org.apache.maven.model.DependencyManagement; -import org.apache.maven.model.Exclusion; -import org.apache.maven.model.Model; -import org.apache.maven.model.building.ModelBuildingRequest; -import org.apache.maven.model.building.ModelProblem; -import org.apache.maven.model.building.ModelProblemCollector; -import org.apache.maven.model.building.ModelProblemCollectorRequest; -import org.codehaus.plexus.component.annotations.Component; - -/** - * Handles the import of dependency management from other models into the target model. - * - * @author Benjamin Bentmann - */ -@Component( role = DependencyManagementImporter.class ) -public class DefaultDependencyManagementImporter - implements DependencyManagementImporter -{ - - @Override - public void importManagement( final Model target, final List sources, - final ModelBuildingRequest request, final ModelProblemCollector problems ) - { - // Intentionally does not check for conflicts in the source dependencies. We want such conflicts to be resolved - // manually instead of silently getting dropped. - - if ( sources != null && !sources.isEmpty() ) - { - final Map targetDependencies = new LinkedHashMap<>(); - final DependencyManagement targetDependencyManagement = target.getDependencyManagement() != null - ? target.getDependencyManagement() - : new DependencyManagement(); - - target.setDependencyManagement( targetDependencyManagement ); - - for ( final Dependency targetDependency : targetDependencyManagement.getDependencies() ) - { - targetDependencies.put( targetDependency.getManagementKey(), targetDependency ); - } - - final Map> sourceDependencies = new LinkedHashMap<>(); - - for ( final DependencyManagement source : sources ) - { - for ( final Dependency sourceDependency : source.getDependencies() ) - { - if ( !targetDependencies.containsKey( sourceDependency.getManagementKey() ) ) - { - List conflictCanditates = - sourceDependencies.get( sourceDependency.getManagementKey() ); - - if ( conflictCanditates == null ) - { - conflictCanditates = new ArrayList<>(); - sourceDependencies.put( sourceDependency.getManagementKey(), conflictCanditates ); - } - - conflictCanditates.add( sourceDependency ); - } - } - } - - for ( final List conflictCanditates : sourceDependencies.values() ) - { - final List conflictingDependencies = - this.removeRedundantDependencies( conflictCanditates ); - - targetDependencyManagement.getDependencies().addAll( conflictingDependencies ); - - if ( conflictingDependencies.size() > 1 ) - { - final StringBuilder conflictsBuilder = new StringBuilder( conflictingDependencies.size() * 128 ); - - for ( final Dependency dependency : conflictingDependencies ) - { - conflictsBuilder.append( ", '" ).append( dependency.getLocation( "" ) ).append( '\'' ); - } - - problems.add( new ModelProblemCollectorRequest( ModelProblem.Severity.WARNING, - ModelProblem.Version.BASE ). - setMessage( String.format( - "Multiple conflicting imports of dependency '%1$s' into model '%2$s' @ '%3$s' (%4$s). " - + "To resolve this conflict, either declare the dependency directly " - + "in model '%2$s' to override what gets imported or rearrange the causing " - + "imports in the inheritance hierarchy to apply standard override logic. " - + "Without resolving this conflict, your build relies on indeterministic " - + "behaviour.", - conflictingDependencies.get( 0 ).getManagementKey(), target.getId(), - target.getPomFile().getAbsolutePath(), conflictsBuilder.substring( 2 ) ) ) ); - - } - } - } - } - - private List removeRedundantDependencies( final List candidateDependencies ) - { - final List resultDependencies = new ArrayList<>( candidateDependencies.size() ); - - while ( !candidateDependencies.isEmpty() ) - { - final Dependency resultDependency = candidateDependencies.remove( 0 ); - resultDependencies.add( resultDependency ); - - // Removes redundant dependencies. - for ( final Iterator it = candidateDependencies.iterator(); it.hasNext(); ) - { - final Dependency candidateDependency = it.next(); - it.remove(); - - boolean redundant = true; - - redundancy_check: - { - if ( !( resultDependency.getOptional() != null - ? resultDependency.getOptional().equals( candidateDependency.getOptional() ) - : candidateDependency.getOptional() == null ) ) - { - redundant = false; - break redundancy_check; - } - - if ( !( resultDependency.getScope() != null - ? resultDependency.getScope().equals( candidateDependency.getScope() ) - : candidateDependency.getScope() == null ) ) - { - redundant = false; - break redundancy_check; - } - - if ( !( resultDependency.getSystemPath() != null - ? resultDependency.getSystemPath().equals( candidateDependency.getSystemPath() ) - : candidateDependency.getSystemPath() == null ) ) - { - redundant = false; - break redundancy_check; - } - - if ( !( resultDependency.getVersion() != null - ? resultDependency.getVersion().equals( candidateDependency.getVersion() ) - : candidateDependency.getVersion() == null ) ) - { - redundant = false; - break redundancy_check; - } - - for ( int i = 0, s0 = resultDependency.getExclusions().size(); i < s0; i++ ) - { - final Exclusion resultExclusion = resultDependency.getExclusions().get( i ); - - if ( !containsExclusion( candidateDependency.getExclusions(), resultExclusion ) ) - { - redundant = false; - break redundancy_check; - } - } - - for ( int i = 0, s0 = candidateDependency.getExclusions().size(); i < s0; i++ ) - { - final Exclusion candidateExclusion = candidateDependency.getExclusions().get( i ); - - if ( !containsExclusion( resultDependency.getExclusions(), candidateExclusion ) ) - { - redundant = false; - break redundancy_check; - } - } - } - - if ( !redundant ) - { - resultDependencies.add( candidateDependency ); - } - } - } - - return resultDependencies; - } - - private static boolean containsExclusion( final List exclusions, final Exclusion exclusion ) - { - for ( int i = 0, s0 = exclusions.size(); i < s0; i++ ) - { - final Exclusion current = exclusions.get( i ); - - if ( ( exclusion.getArtifactId() != null - ? exclusion.getArtifactId().equals( current.getArtifactId() ) - : current.getArtifactId() == null ) - && ( exclusion.getGroupId() != null - ? exclusion.getGroupId().equals( current.getGroupId() ) - : current.getGroupId() == null ) ) - { - return true; - } - } - - return false; - } - -} diff --git a/All/Genesis-NP/Genesis#56/pair.info b/All/Genesis-NP/Genesis#56/pair.info deleted file mode 100755 index 05fd56e..0000000 --- a/All/Genesis-NP/Genesis#56/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:56 -SATName:Genesis -modifiedFPath:maven-model-builder/src/main/java/org/apache/maven/model/composition/DefaultDependencyManagementImporter.java -comSha:f08e9558df564319efe91839d03c1be03b6833f8 -parentComSha:f08e9558df564319efe91839d03c1be03b6833f8^1 -githubUrl:https://github.com/apache/maven -repoName:apache#maven \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#63/comMsg.txt b/All/Genesis-NP/Genesis#63/comMsg.txt deleted file mode 100755 index 0494d1b..0000000 --- a/All/Genesis-NP/Genesis#63/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -o Reduced NPE risk diff --git a/All/Genesis-NP/Genesis#63/diff.diff b/All/Genesis-NP/Genesis#63/diff.diff deleted file mode 100755 index 6b68b12..0000000 --- a/All/Genesis-NP/Genesis#63/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionResult.java b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionResult.java -index 5616f38..bdb4532 100644 ---- a/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionResult.java -+++ b/maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionResult.java -@@ -37 +37 @@ -- private List topologicallySortedProjects; -+ private List topologicallySortedProjects = Collections.emptyList(); diff --git a/All/Genesis-NP/Genesis#63/new/DefaultMavenExecutionResult.java b/All/Genesis-NP/Genesis#63/new/DefaultMavenExecutionResult.java deleted file mode 100755 index bdb4532..0000000 --- a/All/Genesis-NP/Genesis#63/new/DefaultMavenExecutionResult.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.apache.maven.execution; - -/* - * 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. - */ - -import java.util.ArrayList; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.maven.project.DependencyResolutionResult; -import org.apache.maven.project.MavenProject; - -/** @author Jason van Zyl */ -public class DefaultMavenExecutionResult - implements MavenExecutionResult -{ - private MavenProject project; - - private List topologicallySortedProjects = Collections.emptyList(); - - private DependencyResolutionResult dependencyResolutionResult; - - private List exceptions; - - private Map buildSummaries; - - public MavenExecutionResult setProject( MavenProject project ) - { - this.project = project; - - return this; - } - - public MavenProject getProject() - { - return project; - } - - public MavenExecutionResult setTopologicallySortedProjects( List topologicallySortedProjects ) - { - this.topologicallySortedProjects = topologicallySortedProjects; - - return this; - } - - public List getTopologicallySortedProjects() - { - return topologicallySortedProjects; - } - - public DependencyResolutionResult getDependencyResolutionResult() - { - return dependencyResolutionResult; - } - - public MavenExecutionResult setDependencyResolutionResult( DependencyResolutionResult dependencyResolutionResult ) - { - this.dependencyResolutionResult = dependencyResolutionResult; - - return this; - } - - public List getExceptions() - { - return exceptions == null ? Collections. emptyList() : exceptions; - } - - public MavenExecutionResult addException( Throwable t ) - { - if ( exceptions == null ) - { - exceptions = new ArrayList(); - } - - exceptions.add( t ); - - return this; - } - - public boolean hasExceptions() - { - return !getExceptions().isEmpty(); - } - - public BuildSummary getBuildSummary( MavenProject project ) - { - return ( buildSummaries != null ) ? buildSummaries.get( project ) : null; - } - - public void addBuildSummary( BuildSummary summary ) - { - if ( buildSummaries == null ) - { - buildSummaries = new IdentityHashMap(); - } - buildSummaries.put( summary.getProject(), summary ); - } - -} diff --git a/All/Genesis-NP/Genesis#63/old/DefaultMavenExecutionResult.java b/All/Genesis-NP/Genesis#63/old/DefaultMavenExecutionResult.java deleted file mode 100755 index 5616f38..0000000 --- a/All/Genesis-NP/Genesis#63/old/DefaultMavenExecutionResult.java +++ /dev/null @@ -1,117 +0,0 @@ -package org.apache.maven.execution; - -/* - * 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. - */ - -import java.util.ArrayList; -import java.util.Collections; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; - -import org.apache.maven.project.DependencyResolutionResult; -import org.apache.maven.project.MavenProject; - -/** @author Jason van Zyl */ -public class DefaultMavenExecutionResult - implements MavenExecutionResult -{ - private MavenProject project; - - private List topologicallySortedProjects; - - private DependencyResolutionResult dependencyResolutionResult; - - private List exceptions; - - private Map buildSummaries; - - public MavenExecutionResult setProject( MavenProject project ) - { - this.project = project; - - return this; - } - - public MavenProject getProject() - { - return project; - } - - public MavenExecutionResult setTopologicallySortedProjects( List topologicallySortedProjects ) - { - this.topologicallySortedProjects = topologicallySortedProjects; - - return this; - } - - public List getTopologicallySortedProjects() - { - return topologicallySortedProjects; - } - - public DependencyResolutionResult getDependencyResolutionResult() - { - return dependencyResolutionResult; - } - - public MavenExecutionResult setDependencyResolutionResult( DependencyResolutionResult dependencyResolutionResult ) - { - this.dependencyResolutionResult = dependencyResolutionResult; - - return this; - } - - public List getExceptions() - { - return exceptions == null ? Collections. emptyList() : exceptions; - } - - public MavenExecutionResult addException( Throwable t ) - { - if ( exceptions == null ) - { - exceptions = new ArrayList(); - } - - exceptions.add( t ); - - return this; - } - - public boolean hasExceptions() - { - return !getExceptions().isEmpty(); - } - - public BuildSummary getBuildSummary( MavenProject project ) - { - return ( buildSummaries != null ) ? buildSummaries.get( project ) : null; - } - - public void addBuildSummary( BuildSummary summary ) - { - if ( buildSummaries == null ) - { - buildSummaries = new IdentityHashMap(); - } - buildSummaries.put( summary.getProject(), summary ); - } - -} diff --git a/All/Genesis-NP/Genesis#63/pair.info b/All/Genesis-NP/Genesis#63/pair.info deleted file mode 100755 index 26b7dd7..0000000 --- a/All/Genesis-NP/Genesis#63/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:63 -SATName:Genesis -modifiedFPath:maven-core/src/main/java/org/apache/maven/execution/DefaultMavenExecutionResult.java -comSha:ab0d04456686a700bd0720688c6003dc3eaf6493 -parentComSha:ab0d04456686a700bd0720688c6003dc3eaf6493^1 -githubUrl:https://github.com/apache/maven -repoName:apache#maven \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#65/comMsg.txt b/All/Genesis-NP/Genesis#65/comMsg.txt deleted file mode 100755 index 76f1913..0000000 --- a/All/Genesis-NP/Genesis#65/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -[MNG-4785] NPE in dependency resolution code for TC plugin diff --git a/All/Genesis-NP/Genesis#65/diff.diff b/All/Genesis-NP/Genesis#65/diff.diff deleted file mode 100755 index 673133d..0000000 --- a/All/Genesis-NP/Genesis#65/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java -index 81e69d9..dfd3f40 100644 ---- a/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java -+++ b/maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java -@@ -40 +40 @@ -- private ThreadLocal session = new ThreadLocal(); -+ private ThreadLocal session = new InheritableThreadLocal(); diff --git a/All/Genesis-NP/Genesis#65/new/DefaultLegacySupport.java b/All/Genesis-NP/Genesis#65/new/DefaultLegacySupport.java deleted file mode 100755 index dfd3f40..0000000 --- a/All/Genesis-NP/Genesis#65/new/DefaultLegacySupport.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.apache.maven.plugin.internal; - -/* - * 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. - */ - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.LegacySupport; -import org.codehaus.plexus.component.annotations.Component; -import org.sonatype.aether.RepositorySystemSession; - -/** - * Helps to provide backward-compatibility with plugins that use legacy components. Warning: This is an - * internal utility component that is only public for technical reasons, it is not part of the public API. In - * particular, this component can be changed or deleted without prior notice. - * - * @since 3.0 - * @author Benjamin Bentmann - */ -@Component( role = LegacySupport.class ) -public class DefaultLegacySupport - implements LegacySupport -{ - - private ThreadLocal session = new InheritableThreadLocal(); - - public void setSession( MavenSession session ) - { - if ( session == null ) - { - this.session.remove(); - } - else - { - this.session.set( session ); - } - } - - public MavenSession getSession() - { - return session.get(); - } - - public RepositorySystemSession getRepositorySession() - { - MavenSession session = getSession(); - return ( session != null ) ? session.getRepositorySession() : null; - } - -} diff --git a/All/Genesis-NP/Genesis#65/old/DefaultLegacySupport.java b/All/Genesis-NP/Genesis#65/old/DefaultLegacySupport.java deleted file mode 100755 index 81e69d9..0000000 --- a/All/Genesis-NP/Genesis#65/old/DefaultLegacySupport.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.apache.maven.plugin.internal; - -/* - * 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. - */ - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.LegacySupport; -import org.codehaus.plexus.component.annotations.Component; -import org.sonatype.aether.RepositorySystemSession; - -/** - * Helps to provide backward-compatibility with plugins that use legacy components. Warning: This is an - * internal utility component that is only public for technical reasons, it is not part of the public API. In - * particular, this component can be changed or deleted without prior notice. - * - * @since 3.0 - * @author Benjamin Bentmann - */ -@Component( role = LegacySupport.class ) -public class DefaultLegacySupport - implements LegacySupport -{ - - private ThreadLocal session = new ThreadLocal(); - - public void setSession( MavenSession session ) - { - if ( session == null ) - { - this.session.remove(); - } - else - { - this.session.set( session ); - } - } - - public MavenSession getSession() - { - return session.get(); - } - - public RepositorySystemSession getRepositorySession() - { - MavenSession session = getSession(); - return ( session != null ) ? session.getRepositorySession() : null; - } - -} diff --git a/All/Genesis-NP/Genesis#65/pair.info b/All/Genesis-NP/Genesis#65/pair.info deleted file mode 100755 index e227fb6..0000000 --- a/All/Genesis-NP/Genesis#65/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:65 -SATName:Genesis -modifiedFPath:maven-core/src/main/java/org/apache/maven/plugin/internal/DefaultLegacySupport.java -comSha:90ac0847b697b07ed643dab5fcafc15f12f31ec4 -parentComSha:90ac0847b697b07ed643dab5fcafc15f12f31ec4^1 -githubUrl:https://github.com/apache/maven -repoName:apache#maven \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#68/comMsg.txt b/All/Genesis-NP/Genesis#68/comMsg.txt deleted file mode 100755 index df9837b..0000000 --- a/All/Genesis-NP/Genesis#68/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -DATAMONGO-897 - Fixed potential NullPointerException in QueryMapper. diff --git a/All/Genesis-NP/Genesis#68/diff.diff b/All/Genesis-NP/Genesis#68/diff.diff deleted file mode 100755 index 127944d..0000000 --- a/All/Genesis-NP/Genesis#68/diff.diff +++ /dev/null @@ -1,31 +0,0 @@ -diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java -index 83abddb..1237573 100644 ---- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java -+++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java -@@ -253 +253 @@ public class QueryMapper { -- * @param documentField -+ * @param documentField must not be {@literal null}. -@@ -258,3 +258,20 @@ public class QueryMapper { -- return documentField.isAssociation() && value != null -- && (documentField.getProperty().getActualType().isAssignableFrom(value.getClass()) // -- || documentField.getPropertyEntity().getIdProperty().getActualType().isAssignableFrom(value.getClass())); -+ -+ Assert.notNull(documentField, "Document field must not be null!"); -+ -+ if (value == null) { -+ return false; -+ } -+ -+ if (!documentField.isAssociation()) { -+ return false; -+ } -+ -+ Class type = value.getClass(); -+ MongoPersistentProperty property = documentField.getProperty(); -+ -+ if (property.getActualType().isAssignableFrom(type)) { -+ return true; -+ } -+ -+ MongoPersistentEntity entity = documentField.getPropertyEntity(); -+ return entity.hasIdProperty() && entity.getIdProperty().getActualType().isAssignableFrom(type); diff --git a/All/Genesis-NP/Genesis#68/new/QueryMapper.java b/All/Genesis-NP/Genesis#68/new/QueryMapper.java deleted file mode 100755 index 1237573..0000000 --- a/All/Genesis-NP/Genesis#68/new/QueryMapper.java +++ /dev/null @@ -1,766 +0,0 @@ -/* - * Copyright 2011-2014 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.data.mongodb.core.convert; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -import org.bson.types.ObjectId; -import org.springframework.core.convert.ConversionException; -import org.springframework.core.convert.ConversionService; -import org.springframework.core.convert.converter.Converter; -import org.springframework.data.mapping.Association; -import org.springframework.data.mapping.PersistentEntity; -import org.springframework.data.mapping.PropertyPath; -import org.springframework.data.mapping.PropertyReferenceException; -import org.springframework.data.mapping.context.MappingContext; -import org.springframework.data.mapping.context.PersistentPropertyPath; -import org.springframework.data.mapping.model.MappingException; -import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; -import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; -import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty.PropertyToFieldNameConverter; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.util.Assert; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.DBRef; - -/** - * A helper class to encapsulate any modifications of a Query object before it gets submitted to the database. - * - * @author Jon Brisbin - * @author Oliver Gierke - * @author Patryk Wasik - * @author Thomas Darimont - * @author Christoph Strobl - */ -public class QueryMapper { - - private static final List DEFAULT_ID_NAMES = Arrays.asList("id", "_id"); - - private final ConversionService conversionService; - private final MongoConverter converter; - private final MappingContext, MongoPersistentProperty> mappingContext; - - /** - * Creates a new {@link QueryMapper} with the given {@link MongoConverter}. - * - * @param converter must not be {@literal null}. - */ - public QueryMapper(MongoConverter converter) { - - Assert.notNull(converter); - - this.conversionService = converter.getConversionService(); - this.converter = converter; - this.mappingContext = converter.getMappingContext(); - } - - /** - * Replaces the property keys used in the given {@link DBObject} with the appropriate keys by using the - * {@link PersistentEntity} metadata. - * - * @param query must not be {@literal null}. - * @param entity can be {@literal null}. - * @return - */ - @SuppressWarnings("deprecation") - public DBObject getMappedObject(DBObject query, MongoPersistentEntity entity) { - - if (isNestedKeyword(query)) { - return getMappedKeyword(new Keyword(query), entity); - } - - DBObject result = new BasicDBObject(); - - for (String key : query.keySet()) { - - // TODO: remove one once QueryMapper can work with Query instances directly - if (Query.isRestrictedTypeKey(key)) { - - @SuppressWarnings("unchecked") - Set> restrictedTypes = (Set>) query.get(key); - this.converter.getTypeMapper().writeTypeRestrictions(result, restrictedTypes); - - continue; - } - - if (isKeyword(key)) { - result.putAll(getMappedKeyword(new Keyword(query, key), entity)); - continue; - } - - Field field = createPropertyField(entity, key, mappingContext); - Entry entry = getMappedObjectForField(field, query.get(key)); - - result.put(entry.getKey(), entry.getValue()); - } - - return result; - } - - /** - * Extracts the mapped object value for given field out of rawValue taking nested {@link Keyword}s into account - * - * @param field - * @param rawValue - * @return - */ - protected Entry getMappedObjectForField(Field field, Object rawValue) { - - String key = field.getMappedKey(); - Object value; - - if (isNestedKeyword(rawValue) && !field.isIdField()) { - Keyword keyword = new Keyword((DBObject) rawValue); - value = getMappedKeyword(field, keyword); - } else { - value = getMappedValue(field, rawValue); - } - - return createMapEntry(key, value); - } - - /** - * @param entity - * @param key - * @param mappingContext - * @return - */ - protected Field createPropertyField(MongoPersistentEntity entity, String key, - MappingContext, MongoPersistentProperty> mappingContext) { - return entity == null ? new Field(key) : new MetadataBackedField(key, entity, mappingContext); - } - - /** - * Returns the given {@link DBObject} representing a keyword by mapping the keyword's value. - * - * @param keyword the {@link DBObject} representing a keyword (e.g. {@code $ne : … } ) - * @param entity - * @return - */ - protected DBObject getMappedKeyword(Keyword keyword, MongoPersistentEntity entity) { - - // $or/$nor - if (keyword.isOrOrNor() || keyword.hasIterableValue()) { - - Iterable conditions = keyword.getValue(); - BasicDBList newConditions = new BasicDBList(); - - for (Object condition : conditions) { - newConditions.add(isDBObject(condition) ? getMappedObject((DBObject) condition, entity) - : convertSimpleOrDBObject(condition, entity)); - } - - return new BasicDBObject(keyword.getKey(), newConditions); - } - - return new BasicDBObject(keyword.getKey(), convertSimpleOrDBObject(keyword.getValue(), entity)); - } - - /** - * Returns the mapped keyword considered defining a criteria for the given property. - * - * @param property - * @param keyword - * @return - */ - protected DBObject getMappedKeyword(Field property, Keyword keyword) { - - boolean needsAssociationConversion = property.isAssociation() && !keyword.isExists(); - Object value = keyword.getValue(); - - Object convertedValue = needsAssociationConversion ? convertAssociation(value, property) : getMappedValue( - property.with(keyword.getKey()), value); - - return new BasicDBObject(keyword.key, convertedValue); - } - - /** - * Returns the mapped value for the given source object assuming it's a value for the given - * {@link MongoPersistentProperty}. - * - * @param value the source object to be mapped - * @param property the property the value is a value for - * @param newKey the key the value will be bound to eventually - * @return - */ - protected Object getMappedValue(Field documentField, Object value) { - - if (documentField.isIdField()) { - - if (isDBObject(value)) { - DBObject valueDbo = (DBObject) value; - DBObject resultDbo = new BasicDBObject(valueDbo.toMap()); - - if (valueDbo.containsField("$in") || valueDbo.containsField("$nin")) { - String inKey = valueDbo.containsField("$in") ? "$in" : "$nin"; - List ids = new ArrayList(); - for (Object id : (Iterable) valueDbo.get(inKey)) { - ids.add(convertId(id)); - } - resultDbo.put(inKey, ids.toArray(new Object[ids.size()])); - } else if (valueDbo.containsField("$ne")) { - resultDbo.put("$ne", convertId(valueDbo.get("$ne"))); - } else { - return getMappedObject(resultDbo, null); - } - - return resultDbo; - - } else { - return convertId(value); - } - } - - if (isNestedKeyword(value)) { - return getMappedKeyword(new Keyword((DBObject) value), null); - } - - if (isAssociationConversionNecessary(documentField, value)) { - return convertAssociation(value, documentField); - } - - return convertSimpleOrDBObject(value, documentField.getPropertyEntity()); - } - - /** - * Returns whether the given {@link Field} represents an association reference that together with the given value - * requires conversion to a {@link org.springframework.data.mongodb.core.mapping.DBRef} object. We check whether the - * type of the given value is compatible with the type of the given document field in order to deal with potential - * query field exclusions, since MongoDB uses the {@code int} {@literal 0} as an indicator for an excluded field. - * - * @param documentField must not be {@literal null}. - * @param value - * @return - */ - protected boolean isAssociationConversionNecessary(Field documentField, Object value) { - - Assert.notNull(documentField, "Document field must not be null!"); - - if (value == null) { - return false; - } - - if (!documentField.isAssociation()) { - return false; - } - - Class type = value.getClass(); - MongoPersistentProperty property = documentField.getProperty(); - - if (property.getActualType().isAssignableFrom(type)) { - return true; - } - - MongoPersistentEntity entity = documentField.getPropertyEntity(); - return entity.hasIdProperty() && entity.getIdProperty().getActualType().isAssignableFrom(type); - } - - /** - * Retriggers mapping if the given source is a {@link DBObject} or simply invokes the - * - * @param source - * @param entity - * @return - */ - protected Object convertSimpleOrDBObject(Object source, MongoPersistentEntity entity) { - - if (source instanceof BasicDBList) { - return delegateConvertToMongoType(source, entity); - } - - if (isDBObject(source)) { - return getMappedObject((DBObject) source, entity); - } - - return delegateConvertToMongoType(source, entity); - } - - /** - * Converts the given source Object to a mongo type with the type information of the original source type omitted. - * Subclasses may overwrite this method to retain the type information of the source type on the resulting mongo type. - * - * @param source - * @param entity - * @return the converted mongo type or null if source is null - */ - protected Object delegateConvertToMongoType(Object source, MongoPersistentEntity entity) { - return converter.convertToMongoType(source); - } - - protected Object convertAssociation(Object source, Field field) { - return convertAssociation(source, field.getProperty()); - } - - /** - * Converts the given source assuming it's actually an association to another object. - * - * @param source - * @param property - * @return - */ - protected Object convertAssociation(Object source, MongoPersistentProperty property) { - - if (property == null || source == null || source instanceof DBRef || source instanceof DBObject) { - return source; - } - - if (source instanceof Iterable) { - BasicDBList result = new BasicDBList(); - for (Object element : (Iterable) source) { - result.add(createDbRefFor(element, property)); - } - return result; - } - - if (property.isMap()) { - BasicDBObject result = new BasicDBObject(); - DBObject dbObject = (DBObject) source; - for (String key : dbObject.keySet()) { - result.put(key, createDbRefFor(dbObject.get(key), property)); - } - return result; - } - - return createDbRefFor(source, property); - } - - /** - * Checks whether the given value is a {@link DBObject}. - * - * @param value can be {@literal null}. - * @return - */ - protected final boolean isDBObject(Object value) { - return value instanceof DBObject; - } - - /** - * Creates a new {@link Entry} for the given {@link Field} with the given value. - * - * @param field must not be {@literal null}. - * @param value can be {@literal null}. - * @return - */ - protected final Entry createMapEntry(Field field, Object value) { - return createMapEntry(field.getMappedKey(), value); - } - - /** - * Creates a new {@link Entry} with the given key and value. - * - * @param key must not be {@literal null} or empty. - * @param value can be {@literal null} - * @return - */ - private Entry createMapEntry(String key, Object value) { - - Assert.hasText(key, "Key must not be null or empty!"); - return Collections.singletonMap(key, value).entrySet().iterator().next(); - } - - private DBRef createDbRefFor(Object source, MongoPersistentProperty property) { - - if (source instanceof DBRef) { - return (DBRef) source; - } - - return converter.toDBRef(source, property); - } - - /** - * Converts the given raw id value into either {@link ObjectId} or {@link String}. - * - * @param id - * @return - */ - public Object convertId(Object id) { - - try { - return conversionService.convert(id, ObjectId.class); - } catch (ConversionException e) { - // Ignore - } - - return delegateConvertToMongoType(id, null); - } - - /** - * Returns whether the given {@link Object} is a keyword, i.e. if it's a {@link DBObject} with a keyword key. - * - * @param candidate - * @return - */ - protected boolean isNestedKeyword(Object candidate) { - - if (!(candidate instanceof BasicDBObject)) { - return false; - } - - BasicDBObject dbObject = (BasicDBObject) candidate; - Set keys = dbObject.keySet(); - - if (keys.size() != 1) { - return false; - } - - return isKeyword(keys.iterator().next().toString()); - } - - /** - * Returns whether the given {@link String} is a MongoDB keyword. The default implementation will check against the - * set of registered keywords returned by {@link #getKeywords()}. - * - * @param candidate - * @return - */ - protected boolean isKeyword(String candidate) { - return candidate.startsWith("$"); - } - - /** - * Value object to capture a query keyword representation. - * - * @author Oliver Gierke - */ - static class Keyword { - - private static final String N_OR_PATTERN = "\\$.*or"; - - private final String key; - private final Object value; - - public Keyword(DBObject source, String key) { - this.key = key; - this.value = source.get(key); - } - - public Keyword(DBObject dbObject) { - - Set keys = dbObject.keySet(); - Assert.isTrue(keys.size() == 1, "Can only use a single value DBObject!"); - - this.key = keys.iterator().next(); - this.value = dbObject.get(key); - } - - /** - * Returns whether the current keyword is the {@code $exists} keyword. - * - * @return - */ - public boolean isExists() { - return "$exists".equalsIgnoreCase(key); - } - - public boolean isOrOrNor() { - return key.matches(N_OR_PATTERN); - } - - public boolean hasIterableValue() { - return value instanceof Iterable; - } - - public String getKey() { - return key; - } - - @SuppressWarnings("unchecked") - public T getValue() { - return (T) value; - } - } - - /** - * Value object to represent a field and its meta-information. - * - * @author Oliver Gierke - */ - protected static class Field { - - private static final String ID_KEY = "_id"; - - protected final String name; - - /** - * Creates a new {@link DocumentField} without meta-information but the given name. - * - * @param name must not be {@literal null} or empty. - */ - public Field(String name) { - - Assert.hasText(name, "Name must not be null!"); - this.name = name; - } - - /** - * Returns a new {@link DocumentField} with the given name. - * - * @param name must not be {@literal null} or empty. - * @return - */ - public Field with(String name) { - return new Field(name); - } - - /** - * Returns whether the current field is the id field. - * - * @return - */ - public boolean isIdField() { - return ID_KEY.equals(name); - } - - /** - * Returns the underlying {@link MongoPersistentProperty} backing the field. For path traversals this will be the - * property that represents the value to handle. This means it'll be the leaf property for plain paths or the - * association property in case we refer to an association somewhere in the path. - * - * @return - */ - public MongoPersistentProperty getProperty() { - return null; - } - - /** - * Returns the {@link MongoPersistentEntity} that field is conatined in. - * - * @return - */ - public MongoPersistentEntity getPropertyEntity() { - return null; - } - - /** - * Returns whether the field represents an association. - * - * @return - */ - public boolean isAssociation() { - return false; - } - - /** - * Returns the key to be used in the mapped document eventually. - * - * @return - */ - public String getMappedKey() { - return isIdField() ? ID_KEY : name; - } - - /** - * Returns whether the field references an association in case it refers to a nested field. - * - * @return - */ - public boolean containsAssociation() { - return false; - } - - public Association getAssociation() { - return null; - } - } - - /** - * Extension of {@link DocumentField} to be backed with mapping metadata. - * - * @author Oliver Gierke - * @author Thomas Darimont - */ - protected static class MetadataBackedField extends Field { - - private static final String INVALID_ASSOCIATION_REFERENCE = "Invalid path reference %s! Associations can only be pointed to directly or via their id property!"; - - private final MongoPersistentEntity entity; - private final MappingContext, MongoPersistentProperty> mappingContext; - private final MongoPersistentProperty property; - private final PersistentPropertyPath path; - private final Association association; - - /** - * Creates a new {@link MetadataBackedField} with the given name, {@link MongoPersistentEntity} and - * {@link MappingContext}. - * - * @param name must not be {@literal null} or empty. - * @param entity must not be {@literal null}. - * @param context must not be {@literal null}. - */ - public MetadataBackedField(String name, MongoPersistentEntity entity, - MappingContext, MongoPersistentProperty> context) { - - super(name); - - Assert.notNull(entity, "MongoPersistentEntity must not be null!"); - - this.entity = entity; - this.mappingContext = context; - - this.path = getPath(name); - this.property = path == null ? null : path.getLeafProperty(); - this.association = findAssociation(); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#with(java.lang.String) - */ - @Override - public MetadataBackedField with(String name) { - return new MetadataBackedField(name, entity, mappingContext); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#isIdKey() - */ - @Override - public boolean isIdField() { - - MongoPersistentProperty idProperty = entity.getIdProperty(); - - if (idProperty != null) { - return idProperty.getName().equals(name) || idProperty.getFieldName().equals(name); - } - - return DEFAULT_ID_NAMES.contains(name); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getProperty() - */ - @Override - public MongoPersistentProperty getProperty() { - return association == null ? property : association.getInverse(); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getEntity() - */ - @Override - public MongoPersistentEntity getPropertyEntity() { - MongoPersistentProperty property = getProperty(); - return property == null ? null : mappingContext.getPersistentEntity(property); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#isAssociation() - */ - @Override - public boolean isAssociation() { - return association != null; - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getAssociation() - */ - @Override - public Association getAssociation() { - return association; - } - - /** - * Finds the association property in the {@link PersistentPropertyPath}. - * - * @return - */ - private final Association findAssociation() { - - if (this.path != null) { - for (MongoPersistentProperty p : this.path) { - if (p.isAssociation()) { - return p.getAssociation(); - } - } - } - - return null; - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getTargetKey() - */ - @Override - public String getMappedKey() { - return path == null ? name : path.toDotPath(getPropertyConverter()); - } - - protected PersistentPropertyPath getPath() { - return path; - } - - /** - * Returns the {@link PersistentPropertyPath} for the given pathExpression. - * - * @param pathExpression - * @return - */ - private PersistentPropertyPath getPath(String pathExpression) { - - try { - - PropertyPath path = PropertyPath.from(pathExpression, entity.getTypeInformation()); - PersistentPropertyPath propertyPath = mappingContext.getPersistentPropertyPath(path); - - Iterator iterator = propertyPath.iterator(); - boolean associationDetected = false; - - while (iterator.hasNext()) { - - MongoPersistentProperty property = iterator.next(); - - if (property.isAssociation()) { - associationDetected = true; - continue; - } - - if (associationDetected && !property.isIdProperty()) { - throw new MappingException(String.format(INVALID_ASSOCIATION_REFERENCE, pathExpression)); - } - } - - return propertyPath; - } catch (PropertyReferenceException e) { - return null; - } - } - - /** - * Return the {@link Converter} to be used to created the mapped key. Default implementation will use - * {@link PropertyToFieldNameConverter}. - * - * @return - */ - protected Converter getPropertyConverter() { - return PropertyToFieldNameConverter.INSTANCE; - } - } -} diff --git a/All/Genesis-NP/Genesis#68/old/QueryMapper.java b/All/Genesis-NP/Genesis#68/old/QueryMapper.java deleted file mode 100755 index 83abddb..0000000 --- a/All/Genesis-NP/Genesis#68/old/QueryMapper.java +++ /dev/null @@ -1,749 +0,0 @@ -/* - * Copyright 2011-2014 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.data.mongodb.core.convert; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map.Entry; -import java.util.Set; - -import org.bson.types.ObjectId; -import org.springframework.core.convert.ConversionException; -import org.springframework.core.convert.ConversionService; -import org.springframework.core.convert.converter.Converter; -import org.springframework.data.mapping.Association; -import org.springframework.data.mapping.PersistentEntity; -import org.springframework.data.mapping.PropertyPath; -import org.springframework.data.mapping.PropertyReferenceException; -import org.springframework.data.mapping.context.MappingContext; -import org.springframework.data.mapping.context.PersistentPropertyPath; -import org.springframework.data.mapping.model.MappingException; -import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; -import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; -import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty.PropertyToFieldNameConverter; -import org.springframework.data.mongodb.core.query.Query; -import org.springframework.util.Assert; - -import com.mongodb.BasicDBList; -import com.mongodb.BasicDBObject; -import com.mongodb.DBObject; -import com.mongodb.DBRef; - -/** - * A helper class to encapsulate any modifications of a Query object before it gets submitted to the database. - * - * @author Jon Brisbin - * @author Oliver Gierke - * @author Patryk Wasik - * @author Thomas Darimont - * @author Christoph Strobl - */ -public class QueryMapper { - - private static final List DEFAULT_ID_NAMES = Arrays.asList("id", "_id"); - - private final ConversionService conversionService; - private final MongoConverter converter; - private final MappingContext, MongoPersistentProperty> mappingContext; - - /** - * Creates a new {@link QueryMapper} with the given {@link MongoConverter}. - * - * @param converter must not be {@literal null}. - */ - public QueryMapper(MongoConverter converter) { - - Assert.notNull(converter); - - this.conversionService = converter.getConversionService(); - this.converter = converter; - this.mappingContext = converter.getMappingContext(); - } - - /** - * Replaces the property keys used in the given {@link DBObject} with the appropriate keys by using the - * {@link PersistentEntity} metadata. - * - * @param query must not be {@literal null}. - * @param entity can be {@literal null}. - * @return - */ - @SuppressWarnings("deprecation") - public DBObject getMappedObject(DBObject query, MongoPersistentEntity entity) { - - if (isNestedKeyword(query)) { - return getMappedKeyword(new Keyword(query), entity); - } - - DBObject result = new BasicDBObject(); - - for (String key : query.keySet()) { - - // TODO: remove one once QueryMapper can work with Query instances directly - if (Query.isRestrictedTypeKey(key)) { - - @SuppressWarnings("unchecked") - Set> restrictedTypes = (Set>) query.get(key); - this.converter.getTypeMapper().writeTypeRestrictions(result, restrictedTypes); - - continue; - } - - if (isKeyword(key)) { - result.putAll(getMappedKeyword(new Keyword(query, key), entity)); - continue; - } - - Field field = createPropertyField(entity, key, mappingContext); - Entry entry = getMappedObjectForField(field, query.get(key)); - - result.put(entry.getKey(), entry.getValue()); - } - - return result; - } - - /** - * Extracts the mapped object value for given field out of rawValue taking nested {@link Keyword}s into account - * - * @param field - * @param rawValue - * @return - */ - protected Entry getMappedObjectForField(Field field, Object rawValue) { - - String key = field.getMappedKey(); - Object value; - - if (isNestedKeyword(rawValue) && !field.isIdField()) { - Keyword keyword = new Keyword((DBObject) rawValue); - value = getMappedKeyword(field, keyword); - } else { - value = getMappedValue(field, rawValue); - } - - return createMapEntry(key, value); - } - - /** - * @param entity - * @param key - * @param mappingContext - * @return - */ - protected Field createPropertyField(MongoPersistentEntity entity, String key, - MappingContext, MongoPersistentProperty> mappingContext) { - return entity == null ? new Field(key) : new MetadataBackedField(key, entity, mappingContext); - } - - /** - * Returns the given {@link DBObject} representing a keyword by mapping the keyword's value. - * - * @param keyword the {@link DBObject} representing a keyword (e.g. {@code $ne : … } ) - * @param entity - * @return - */ - protected DBObject getMappedKeyword(Keyword keyword, MongoPersistentEntity entity) { - - // $or/$nor - if (keyword.isOrOrNor() || keyword.hasIterableValue()) { - - Iterable conditions = keyword.getValue(); - BasicDBList newConditions = new BasicDBList(); - - for (Object condition : conditions) { - newConditions.add(isDBObject(condition) ? getMappedObject((DBObject) condition, entity) - : convertSimpleOrDBObject(condition, entity)); - } - - return new BasicDBObject(keyword.getKey(), newConditions); - } - - return new BasicDBObject(keyword.getKey(), convertSimpleOrDBObject(keyword.getValue(), entity)); - } - - /** - * Returns the mapped keyword considered defining a criteria for the given property. - * - * @param property - * @param keyword - * @return - */ - protected DBObject getMappedKeyword(Field property, Keyword keyword) { - - boolean needsAssociationConversion = property.isAssociation() && !keyword.isExists(); - Object value = keyword.getValue(); - - Object convertedValue = needsAssociationConversion ? convertAssociation(value, property) : getMappedValue( - property.with(keyword.getKey()), value); - - return new BasicDBObject(keyword.key, convertedValue); - } - - /** - * Returns the mapped value for the given source object assuming it's a value for the given - * {@link MongoPersistentProperty}. - * - * @param value the source object to be mapped - * @param property the property the value is a value for - * @param newKey the key the value will be bound to eventually - * @return - */ - protected Object getMappedValue(Field documentField, Object value) { - - if (documentField.isIdField()) { - - if (isDBObject(value)) { - DBObject valueDbo = (DBObject) value; - DBObject resultDbo = new BasicDBObject(valueDbo.toMap()); - - if (valueDbo.containsField("$in") || valueDbo.containsField("$nin")) { - String inKey = valueDbo.containsField("$in") ? "$in" : "$nin"; - List ids = new ArrayList(); - for (Object id : (Iterable) valueDbo.get(inKey)) { - ids.add(convertId(id)); - } - resultDbo.put(inKey, ids.toArray(new Object[ids.size()])); - } else if (valueDbo.containsField("$ne")) { - resultDbo.put("$ne", convertId(valueDbo.get("$ne"))); - } else { - return getMappedObject(resultDbo, null); - } - - return resultDbo; - - } else { - return convertId(value); - } - } - - if (isNestedKeyword(value)) { - return getMappedKeyword(new Keyword((DBObject) value), null); - } - - if (isAssociationConversionNecessary(documentField, value)) { - return convertAssociation(value, documentField); - } - - return convertSimpleOrDBObject(value, documentField.getPropertyEntity()); - } - - /** - * Returns whether the given {@link Field} represents an association reference that together with the given value - * requires conversion to a {@link org.springframework.data.mongodb.core.mapping.DBRef} object. We check whether the - * type of the given value is compatible with the type of the given document field in order to deal with potential - * query field exclusions, since MongoDB uses the {@code int} {@literal 0} as an indicator for an excluded field. - * - * @param documentField - * @param value - * @return - */ - protected boolean isAssociationConversionNecessary(Field documentField, Object value) { - return documentField.isAssociation() && value != null - && (documentField.getProperty().getActualType().isAssignableFrom(value.getClass()) // - || documentField.getPropertyEntity().getIdProperty().getActualType().isAssignableFrom(value.getClass())); - } - - /** - * Retriggers mapping if the given source is a {@link DBObject} or simply invokes the - * - * @param source - * @param entity - * @return - */ - protected Object convertSimpleOrDBObject(Object source, MongoPersistentEntity entity) { - - if (source instanceof BasicDBList) { - return delegateConvertToMongoType(source, entity); - } - - if (isDBObject(source)) { - return getMappedObject((DBObject) source, entity); - } - - return delegateConvertToMongoType(source, entity); - } - - /** - * Converts the given source Object to a mongo type with the type information of the original source type omitted. - * Subclasses may overwrite this method to retain the type information of the source type on the resulting mongo type. - * - * @param source - * @param entity - * @return the converted mongo type or null if source is null - */ - protected Object delegateConvertToMongoType(Object source, MongoPersistentEntity entity) { - return converter.convertToMongoType(source); - } - - protected Object convertAssociation(Object source, Field field) { - return convertAssociation(source, field.getProperty()); - } - - /** - * Converts the given source assuming it's actually an association to another object. - * - * @param source - * @param property - * @return - */ - protected Object convertAssociation(Object source, MongoPersistentProperty property) { - - if (property == null || source == null || source instanceof DBRef || source instanceof DBObject) { - return source; - } - - if (source instanceof Iterable) { - BasicDBList result = new BasicDBList(); - for (Object element : (Iterable) source) { - result.add(createDbRefFor(element, property)); - } - return result; - } - - if (property.isMap()) { - BasicDBObject result = new BasicDBObject(); - DBObject dbObject = (DBObject) source; - for (String key : dbObject.keySet()) { - result.put(key, createDbRefFor(dbObject.get(key), property)); - } - return result; - } - - return createDbRefFor(source, property); - } - - /** - * Checks whether the given value is a {@link DBObject}. - * - * @param value can be {@literal null}. - * @return - */ - protected final boolean isDBObject(Object value) { - return value instanceof DBObject; - } - - /** - * Creates a new {@link Entry} for the given {@link Field} with the given value. - * - * @param field must not be {@literal null}. - * @param value can be {@literal null}. - * @return - */ - protected final Entry createMapEntry(Field field, Object value) { - return createMapEntry(field.getMappedKey(), value); - } - - /** - * Creates a new {@link Entry} with the given key and value. - * - * @param key must not be {@literal null} or empty. - * @param value can be {@literal null} - * @return - */ - private Entry createMapEntry(String key, Object value) { - - Assert.hasText(key, "Key must not be null or empty!"); - return Collections.singletonMap(key, value).entrySet().iterator().next(); - } - - private DBRef createDbRefFor(Object source, MongoPersistentProperty property) { - - if (source instanceof DBRef) { - return (DBRef) source; - } - - return converter.toDBRef(source, property); - } - - /** - * Converts the given raw id value into either {@link ObjectId} or {@link String}. - * - * @param id - * @return - */ - public Object convertId(Object id) { - - try { - return conversionService.convert(id, ObjectId.class); - } catch (ConversionException e) { - // Ignore - } - - return delegateConvertToMongoType(id, null); - } - - /** - * Returns whether the given {@link Object} is a keyword, i.e. if it's a {@link DBObject} with a keyword key. - * - * @param candidate - * @return - */ - protected boolean isNestedKeyword(Object candidate) { - - if (!(candidate instanceof BasicDBObject)) { - return false; - } - - BasicDBObject dbObject = (BasicDBObject) candidate; - Set keys = dbObject.keySet(); - - if (keys.size() != 1) { - return false; - } - - return isKeyword(keys.iterator().next().toString()); - } - - /** - * Returns whether the given {@link String} is a MongoDB keyword. The default implementation will check against the - * set of registered keywords returned by {@link #getKeywords()}. - * - * @param candidate - * @return - */ - protected boolean isKeyword(String candidate) { - return candidate.startsWith("$"); - } - - /** - * Value object to capture a query keyword representation. - * - * @author Oliver Gierke - */ - static class Keyword { - - private static final String N_OR_PATTERN = "\\$.*or"; - - private final String key; - private final Object value; - - public Keyword(DBObject source, String key) { - this.key = key; - this.value = source.get(key); - } - - public Keyword(DBObject dbObject) { - - Set keys = dbObject.keySet(); - Assert.isTrue(keys.size() == 1, "Can only use a single value DBObject!"); - - this.key = keys.iterator().next(); - this.value = dbObject.get(key); - } - - /** - * Returns whether the current keyword is the {@code $exists} keyword. - * - * @return - */ - public boolean isExists() { - return "$exists".equalsIgnoreCase(key); - } - - public boolean isOrOrNor() { - return key.matches(N_OR_PATTERN); - } - - public boolean hasIterableValue() { - return value instanceof Iterable; - } - - public String getKey() { - return key; - } - - @SuppressWarnings("unchecked") - public T getValue() { - return (T) value; - } - } - - /** - * Value object to represent a field and its meta-information. - * - * @author Oliver Gierke - */ - protected static class Field { - - private static final String ID_KEY = "_id"; - - protected final String name; - - /** - * Creates a new {@link DocumentField} without meta-information but the given name. - * - * @param name must not be {@literal null} or empty. - */ - public Field(String name) { - - Assert.hasText(name, "Name must not be null!"); - this.name = name; - } - - /** - * Returns a new {@link DocumentField} with the given name. - * - * @param name must not be {@literal null} or empty. - * @return - */ - public Field with(String name) { - return new Field(name); - } - - /** - * Returns whether the current field is the id field. - * - * @return - */ - public boolean isIdField() { - return ID_KEY.equals(name); - } - - /** - * Returns the underlying {@link MongoPersistentProperty} backing the field. For path traversals this will be the - * property that represents the value to handle. This means it'll be the leaf property for plain paths or the - * association property in case we refer to an association somewhere in the path. - * - * @return - */ - public MongoPersistentProperty getProperty() { - return null; - } - - /** - * Returns the {@link MongoPersistentEntity} that field is conatined in. - * - * @return - */ - public MongoPersistentEntity getPropertyEntity() { - return null; - } - - /** - * Returns whether the field represents an association. - * - * @return - */ - public boolean isAssociation() { - return false; - } - - /** - * Returns the key to be used in the mapped document eventually. - * - * @return - */ - public String getMappedKey() { - return isIdField() ? ID_KEY : name; - } - - /** - * Returns whether the field references an association in case it refers to a nested field. - * - * @return - */ - public boolean containsAssociation() { - return false; - } - - public Association getAssociation() { - return null; - } - } - - /** - * Extension of {@link DocumentField} to be backed with mapping metadata. - * - * @author Oliver Gierke - * @author Thomas Darimont - */ - protected static class MetadataBackedField extends Field { - - private static final String INVALID_ASSOCIATION_REFERENCE = "Invalid path reference %s! Associations can only be pointed to directly or via their id property!"; - - private final MongoPersistentEntity entity; - private final MappingContext, MongoPersistentProperty> mappingContext; - private final MongoPersistentProperty property; - private final PersistentPropertyPath path; - private final Association association; - - /** - * Creates a new {@link MetadataBackedField} with the given name, {@link MongoPersistentEntity} and - * {@link MappingContext}. - * - * @param name must not be {@literal null} or empty. - * @param entity must not be {@literal null}. - * @param context must not be {@literal null}. - */ - public MetadataBackedField(String name, MongoPersistentEntity entity, - MappingContext, MongoPersistentProperty> context) { - - super(name); - - Assert.notNull(entity, "MongoPersistentEntity must not be null!"); - - this.entity = entity; - this.mappingContext = context; - - this.path = getPath(name); - this.property = path == null ? null : path.getLeafProperty(); - this.association = findAssociation(); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#with(java.lang.String) - */ - @Override - public MetadataBackedField with(String name) { - return new MetadataBackedField(name, entity, mappingContext); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#isIdKey() - */ - @Override - public boolean isIdField() { - - MongoPersistentProperty idProperty = entity.getIdProperty(); - - if (idProperty != null) { - return idProperty.getName().equals(name) || idProperty.getFieldName().equals(name); - } - - return DEFAULT_ID_NAMES.contains(name); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getProperty() - */ - @Override - public MongoPersistentProperty getProperty() { - return association == null ? property : association.getInverse(); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getEntity() - */ - @Override - public MongoPersistentEntity getPropertyEntity() { - MongoPersistentProperty property = getProperty(); - return property == null ? null : mappingContext.getPersistentEntity(property); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#isAssociation() - */ - @Override - public boolean isAssociation() { - return association != null; - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getAssociation() - */ - @Override - public Association getAssociation() { - return association; - } - - /** - * Finds the association property in the {@link PersistentPropertyPath}. - * - * @return - */ - private final Association findAssociation() { - - if (this.path != null) { - for (MongoPersistentProperty p : this.path) { - if (p.isAssociation()) { - return p.getAssociation(); - } - } - } - - return null; - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.core.convert.QueryMapper.Field#getTargetKey() - */ - @Override - public String getMappedKey() { - return path == null ? name : path.toDotPath(getPropertyConverter()); - } - - protected PersistentPropertyPath getPath() { - return path; - } - - /** - * Returns the {@link PersistentPropertyPath} for the given pathExpression. - * - * @param pathExpression - * @return - */ - private PersistentPropertyPath getPath(String pathExpression) { - - try { - - PropertyPath path = PropertyPath.from(pathExpression, entity.getTypeInformation()); - PersistentPropertyPath propertyPath = mappingContext.getPersistentPropertyPath(path); - - Iterator iterator = propertyPath.iterator(); - boolean associationDetected = false; - - while (iterator.hasNext()) { - - MongoPersistentProperty property = iterator.next(); - - if (property.isAssociation()) { - associationDetected = true; - continue; - } - - if (associationDetected && !property.isIdProperty()) { - throw new MappingException(String.format(INVALID_ASSOCIATION_REFERENCE, pathExpression)); - } - } - - return propertyPath; - } catch (PropertyReferenceException e) { - return null; - } - } - - /** - * Return the {@link Converter} to be used to created the mapped key. Default implementation will use - * {@link PropertyToFieldNameConverter}. - * - * @return - */ - protected Converter getPropertyConverter() { - return PropertyToFieldNameConverter.INSTANCE; - } - } -} diff --git a/All/Genesis-NP/Genesis#68/pair.info b/All/Genesis-NP/Genesis#68/pair.info deleted file mode 100755 index 7be982b..0000000 --- a/All/Genesis-NP/Genesis#68/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:68 -SATName:Genesis -modifiedFPath:spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java -comSha:599291e8b782760003928fd7d83d55c73fcea9fe -parentComSha:599291e8b782760003928fd7d83d55c73fcea9fe^1 -githubUrl:https://github.com/spring-projects/spring-data-mongodb -repoName:spring-projects#spring-data-mongodb \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#7/comMsg.txt b/All/Genesis-NP/Genesis#7/comMsg.txt deleted file mode 100755 index cef0251..0000000 --- a/All/Genesis-NP/Genesis#7/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Improve error message: turn NPE into a clear error message diff --git a/All/Genesis-NP/Genesis#7/diff.diff b/All/Genesis-NP/Genesis#7/diff.diff deleted file mode 100755 index 545e8fb..0000000 --- a/All/Genesis-NP/Genesis#7/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/value/ValueSelectorConfig.java b/optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/value/ValueSelectorConfig.java -index 8345e1f..cf59e04 100644 ---- a/optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/value/ValueSelectorConfig.java -+++ b/optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/value/ValueSelectorConfig.java -@@ -28,0 +29 @@ import org.optaplanner.core.impl.domain.entity.descriptor.EntityDescriptor; -+import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor; -@@ -187 +188,10 @@ public class ValueSelectorConfig extends SelectorConfig { -- entityDescriptor = configPolicy.getSolutionDescriptor().getEntityDescriptorStrict(downcastEntityClass); -+ SolutionDescriptor solutionDescriptor = configPolicy.getSolutionDescriptor(); -+ entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(downcastEntityClass); -+ if (entityDescriptor == null) { -+ throw new IllegalArgumentException("The selectorConfig (" + this -+ + ") has an downcastEntityClass (" + downcastEntityClass -+ + ") that is not a known planning entity.\n" -+ + "Check your solver configuration. If that class (" + downcastEntityClass.getSimpleName() -+ + ") is not in the planningEntityClassSet (" + solutionDescriptor.getEntityClassSet() -+ + "), check your Solution implementation's annotated methods too."); -+ } diff --git a/All/Genesis-NP/Genesis#7/new/ValueSelectorConfig.java b/All/Genesis-NP/Genesis#7/new/ValueSelectorConfig.java deleted file mode 100755 index cf59e04..0000000 --- a/All/Genesis-NP/Genesis#7/new/ValueSelectorConfig.java +++ /dev/null @@ -1,541 +0,0 @@ -/* - * Copyright 2012 JBoss 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 org.optaplanner.core.config.heuristic.selector.value; - -import java.util.Comparator; - -import com.thoughtworks.xstream.annotations.XStreamAlias; -import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; -import org.optaplanner.core.api.domain.variable.PlanningVariable; -import org.optaplanner.core.config.heuristic.policy.HeuristicConfigPolicy; -import org.optaplanner.core.config.heuristic.selector.SelectorConfig; -import org.optaplanner.core.config.heuristic.selector.common.SelectionOrder; -import org.optaplanner.core.config.util.ConfigUtils; -import org.optaplanner.core.impl.domain.entity.descriptor.EntityDescriptor; -import org.optaplanner.core.impl.domain.solution.descriptor.SolutionDescriptor; -import org.optaplanner.core.impl.domain.valuerange.descriptor.EntityIndependentValueRangeDescriptor; -import org.optaplanner.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor; -import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; -import org.optaplanner.core.impl.heuristic.selector.common.SelectionCacheType; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.ComparatorSelectionSorter; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionSorter; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionSorterOrder; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionSorterWeightFactory; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.WeightFactorySelectionSorter; -import org.optaplanner.core.impl.heuristic.selector.entity.EntitySelector; -import org.optaplanner.core.impl.heuristic.selector.value.EntityIndependentValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.FromEntityPropertyValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.FromSolutionPropertyValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.ValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.CachingValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.DowncastingValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.EntityDependentSortingValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.InitializedValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.ProbabilityValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.ReinitializeVariableValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.SelectedCountLimitValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.ShufflingValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.SortingValueSelector; - -@XStreamAlias("valueSelector") -public class ValueSelectorConfig extends SelectorConfig { - - protected Class downcastEntityClass = null; - protected String variableName = null; - - protected SelectionCacheType cacheType = null; - protected SelectionOrder selectionOrder = null; - - // TODO filterClass - - protected ValueSorterManner sorterManner = null; - protected Class sorterComparatorClass = null; - protected Class sorterWeightFactoryClass = null; - protected SelectionSorterOrder sorterOrder = null; - protected Class sorterClass = null; - - protected Class probabilityWeightFactoryClass = null; - - protected Long selectedCountLimit = null; - - public Class getDowncastEntityClass() { - return downcastEntityClass; - } - - public void setDowncastEntityClass(Class downcastEntityClass) { - this.downcastEntityClass = downcastEntityClass; - } - - public String getVariableName() { - return variableName; - } - - public void setVariableName(String variableName) { - this.variableName = variableName; - } - - public SelectionCacheType getCacheType() { - return cacheType; - } - - public void setCacheType(SelectionCacheType cacheType) { - this.cacheType = cacheType; - } - - public SelectionOrder getSelectionOrder() { - return selectionOrder; - } - - public void setSelectionOrder(SelectionOrder selectionOrder) { - this.selectionOrder = selectionOrder; - } - - public ValueSorterManner getSorterManner() { - return sorterManner; - } - - public void setSorterManner(ValueSorterManner sorterManner) { - this.sorterManner = sorterManner; - } - - public Class getSorterComparatorClass() { - return sorterComparatorClass; - } - - public void setSorterComparatorClass(Class sorterComparatorClass) { - this.sorterComparatorClass = sorterComparatorClass; - } - - public Class getSorterWeightFactoryClass() { - return sorterWeightFactoryClass; - } - - public void setSorterWeightFactoryClass(Class sorterWeightFactoryClass) { - this.sorterWeightFactoryClass = sorterWeightFactoryClass; - } - - public SelectionSorterOrder getSorterOrder() { - return sorterOrder; - } - - public void setSorterOrder(SelectionSorterOrder sorterOrder) { - this.sorterOrder = sorterOrder; - } - - public Class getSorterClass() { - return sorterClass; - } - - public void setSorterClass(Class sorterClass) { - this.sorterClass = sorterClass; - } - - public Class getProbabilityWeightFactoryClass() { - return probabilityWeightFactoryClass; - } - - public void setProbabilityWeightFactoryClass(Class probabilityWeightFactoryClass) { - this.probabilityWeightFactoryClass = probabilityWeightFactoryClass; - } - - public Long getSelectedCountLimit() { - return selectedCountLimit; - } - - public void setSelectedCountLimit(Long selectedCountLimit) { - this.selectedCountLimit = selectedCountLimit; - } - - // ************************************************************************ - // Builder methods - // ************************************************************************ - - /** - * - * @param configPolicy never null - * @param entityDescriptor never null - * @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}), - * then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching - * and less would be pointless. - * @param inheritedSelectionOrder never null - * @return never null - */ - public ValueSelector buildValueSelector(HeuristicConfigPolicy configPolicy, - EntityDescriptor entityDescriptor, - SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) { - if (downcastEntityClass != null) { - Class parentEntityClass = entityDescriptor.getEntityClass(); - if (!parentEntityClass.isAssignableFrom(downcastEntityClass)) { - throw new IllegalStateException("The downcastEntityClass (" + downcastEntityClass - + ") is not a subclass of the parentEntityClass (" + parentEntityClass - + ") configured by the " + EntitySelector.class.getSimpleName() + "."); - } - SolutionDescriptor solutionDescriptor = configPolicy.getSolutionDescriptor(); - entityDescriptor = solutionDescriptor.getEntityDescriptorStrict(downcastEntityClass); - if (entityDescriptor == null) { - throw new IllegalArgumentException("The selectorConfig (" + this - + ") has an downcastEntityClass (" + downcastEntityClass - + ") that is not a known planning entity.\n" - + "Check your solver configuration. If that class (" + downcastEntityClass.getSimpleName() - + ") is not in the planningEntityClassSet (" + solutionDescriptor.getEntityClassSet() - + "), check your Solution implementation's annotated methods too."); - } - } - GenuineVariableDescriptor variableDescriptor = deduceVariableDescriptor(entityDescriptor, variableName); - SelectionCacheType resolvedCacheType = SelectionCacheType.resolve(cacheType, minimumCacheType); - SelectionOrder resolvedSelectionOrder = SelectionOrder.resolve(selectionOrder, - inheritedSelectionOrder); - - validateCacheTypeVersusSelectionOrder(resolvedCacheType, resolvedSelectionOrder); - validateSorting(resolvedSelectionOrder); - validateProbability(resolvedSelectionOrder); - validateSelectedLimit(minimumCacheType); - - // baseValueSelector and lower should be SelectionOrder.ORIGINAL if they are going to get cached completely - ValueSelector valueSelector = buildBaseValueSelector(configPolicy, variableDescriptor, - SelectionCacheType.max(minimumCacheType, resolvedCacheType), - determineBaseRandomSelection(variableDescriptor, resolvedCacheType, resolvedSelectionOrder)); - -// valueSelector = applyFiltering(variableDescriptor, resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyInitializedChainedValueFilter(configPolicy, variableDescriptor, - resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applySorting(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyProbability(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyShuffling(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyCaching(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applySelectedLimit(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyReinitializeVariableFiltering(configPolicy, valueSelector); - valueSelector = applyDowncasting(configPolicy, valueSelector); - return valueSelector; - } - - protected boolean determineBaseRandomSelection(GenuineVariableDescriptor variableDescriptor, - SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder) { - switch (resolvedSelectionOrder) { - case ORIGINAL: - return false; - case SORTED: - case SHUFFLED: - case PROBABILISTIC: - // baseValueSelector and lower should be ORIGINAL if they are going to get cached completely - return false; - case RANDOM: - // Predict if caching will occur - return resolvedCacheType.isNotCached() || (isBaseInherentlyCached(variableDescriptor) && !hasFiltering()); - default: - throw new IllegalStateException("The selectionOrder (" + resolvedSelectionOrder - + ") is not implemented."); - } - } - - protected boolean isBaseInherentlyCached(GenuineVariableDescriptor variableDescriptor) { - return variableDescriptor.isValueRangeEntityIndependent(); - } - - private ValueSelector buildBaseValueSelector( - HeuristicConfigPolicy configPolicy, GenuineVariableDescriptor variableDescriptor, - SelectionCacheType minimumCacheType, boolean randomSelection) { - ValueRangeDescriptor valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor(); - // TODO minimumCacheType SOLVER is only a problem if the valueRange includes entities or custom weird cloning - if (minimumCacheType == SelectionCacheType.SOLVER) { - // TODO Solver cached entities are not compatible with DroolsScoreCalculator and IncrementalScoreDirector - // because between phases the entities get cloned and the KieSession/Maps contains those clones afterwards - // https://issues.jboss.org/browse/PLANNER-54 - throw new IllegalArgumentException("The minimumCacheType (" + minimumCacheType - + ") is not yet supported. Please use " + SelectionCacheType.PHASE + " instead."); - } - if (valueRangeDescriptor.isEntityIndependent()) { - return new FromSolutionPropertyValueSelector( - (EntityIndependentValueRangeDescriptor) valueRangeDescriptor, minimumCacheType, randomSelection); - } else { - // TODO Do not allow PHASE cache on FromEntityPropertyValueSelector, except if the moveSelector is PHASE cached too. - return new FromEntityPropertyValueSelector(valueRangeDescriptor, randomSelection); - } - } - - private boolean hasFiltering() { - return false; // NOT yet implemented - } - - protected ValueSelector applyInitializedChainedValueFilter(HeuristicConfigPolicy configPolicy, - GenuineVariableDescriptor variableDescriptor, - SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (configPolicy.isInitializedChainedValueFilterEnabled() - && variableDescriptor.isChained()) { - valueSelector = new InitializedValueSelector(valueSelector); - } - return valueSelector; - } - - private void validateSorting(SelectionOrder resolvedSelectionOrder) { - if ((sorterManner != null || sorterComparatorClass != null || sorterWeightFactoryClass != null - || sorterOrder != null || sorterClass != null) - && resolvedSelectionOrder != SelectionOrder.SORTED) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with sorterManner (" + sorterManner - + ") and sorterComparatorClass (" + sorterComparatorClass - + ") and sorterWeightFactoryClass (" + sorterWeightFactoryClass - + ") and sorterOrder (" + sorterOrder - + ") and sorterClass (" + sorterClass - + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder - + ") that is not " + SelectionOrder.SORTED + "."); - } - if (sorterManner != null && sorterComparatorClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterManner (" + sorterManner - + ") and a sorterComparatorClass (" + sorterComparatorClass + ")."); - } - if (sorterManner != null && sorterWeightFactoryClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterManner (" + sorterManner - + ") and a sorterWeightFactoryClass (" + sorterWeightFactoryClass + ")."); - } - if (sorterManner != null && sorterClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterManner (" + sorterManner - + ") and a sorterClass (" + sorterClass + ")."); - } - if (sorterManner != null && sorterOrder != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with sorterManner (" + sorterManner - + ") has a non-null sorterOrder (" + sorterOrder + ")."); - } - if (sorterComparatorClass != null && sorterWeightFactoryClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterComparatorClass (" + sorterComparatorClass - + ") and a sorterWeightFactoryClass (" + sorterWeightFactoryClass + ")."); - } - if (sorterComparatorClass != null && sorterClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterComparatorClass (" + sorterComparatorClass - + ") and a sorterClass (" + sorterClass + ")."); - } - if (sorterWeightFactoryClass != null && sorterClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterWeightFactoryClass (" + sorterWeightFactoryClass - + ") and a sorterClass (" + sorterClass + ")."); - } - if (sorterClass != null && sorterOrder != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with sorterClass (" + sorterClass - + ") has a non-null sorterOrder (" + sorterOrder + ")."); - } - } - - private ValueSelector applySorting(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (resolvedSelectionOrder == SelectionOrder.SORTED) { - SelectionSorter sorter; - if (sorterManner != null) { - sorter = sorterManner.determineSorter(valueSelector.getVariableDescriptor()); - } else if (sorterComparatorClass != null) { - Comparator sorterComparator = ConfigUtils.newInstance(this, - "sorterComparatorClass", sorterComparatorClass); - sorter = new ComparatorSelectionSorter(sorterComparator, - SelectionSorterOrder.resolve(sorterOrder)); - } else if (sorterWeightFactoryClass != null) { - SelectionSorterWeightFactory sorterWeightFactory = ConfigUtils.newInstance(this, - "sorterWeightFactoryClass", sorterWeightFactoryClass); - sorter = new WeightFactorySelectionSorter(sorterWeightFactory, - SelectionSorterOrder.resolve(sorterOrder)); - } else if (sorterClass != null) { - sorter = ConfigUtils.newInstance(this, "sorterClass", sorterClass); - } else { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs a sorterManner (" + sorterManner - + ") or a sorterComparatorClass (" + sorterComparatorClass - + ") or a sorterWeightFactoryClass (" + sorterWeightFactoryClass - + ") or a sorterClass (" + sorterClass + ")."); - } - if (!valueSelector.getVariableDescriptor().isValueRangeEntityIndependent() - && resolvedCacheType == SelectionCacheType.STEP) { - valueSelector = new EntityDependentSortingValueSelector(valueSelector, - resolvedCacheType, sorter); - } else { - if (!(valueSelector instanceof EntityIndependentValueSelector)) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedCacheType (" + resolvedCacheType - + ") and resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs to be based on a EntityIndependentValueSelector (" + valueSelector + ")." - + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); - } - valueSelector = new SortingValueSelector((EntityIndependentValueSelector) valueSelector, - resolvedCacheType, sorter); - } - } - return valueSelector; - } - - private void validateProbability(SelectionOrder resolvedSelectionOrder) { - if (probabilityWeightFactoryClass != null - && resolvedSelectionOrder != SelectionOrder.PROBABILISTIC) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with probabilityWeightFactoryClass (" + probabilityWeightFactoryClass - + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder - + ") that is not " + SelectionOrder.PROBABILISTIC + "."); - } - } - - private ValueSelector applyProbability(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (resolvedSelectionOrder == SelectionOrder.PROBABILISTIC) { - if (probabilityWeightFactoryClass == null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs a probabilityWeightFactoryClass (" - + probabilityWeightFactoryClass + ")."); - } - SelectionProbabilityWeightFactory probabilityWeightFactory = ConfigUtils.newInstance(this, - "probabilityWeightFactoryClass", probabilityWeightFactoryClass); - if (!(valueSelector instanceof EntityIndependentValueSelector)) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedCacheType (" + resolvedCacheType - + ") and resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs to be based on a EntityIndependentValueSelector (" + valueSelector + ")." - + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); - } - valueSelector = new ProbabilityValueSelector((EntityIndependentValueSelector) valueSelector, - resolvedCacheType, probabilityWeightFactory); - } - return valueSelector; - } - - private ValueSelector applyShuffling(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) { - if (!(valueSelector instanceof EntityIndependentValueSelector)) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedCacheType (" + resolvedCacheType - + ") and resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs to be based on a EntityIndependentValueSelector (" + valueSelector + ")." - + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); - } - valueSelector = new ShufflingValueSelector((EntityIndependentValueSelector) valueSelector, - resolvedCacheType); - } - return valueSelector; - } - - private ValueSelector applyCaching(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (resolvedCacheType.isCached() && resolvedCacheType.compareTo(valueSelector.getCacheType()) > 0) { - if (!(valueSelector instanceof EntityIndependentValueSelector)) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedCacheType (" + resolvedCacheType - + ") and resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs to be based on a EntityIndependentValueSelector (" + valueSelector + ")." - + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); - } - valueSelector = new CachingValueSelector((EntityIndependentValueSelector) valueSelector, resolvedCacheType, - resolvedSelectionOrder.toRandomSelectionBoolean()); - } - return valueSelector; - } - - private void validateSelectedLimit(SelectionCacheType minimumCacheType) { - if (selectedCountLimit != null - && minimumCacheType.compareTo(SelectionCacheType.JUST_IN_TIME) > 0) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with selectedCountLimit (" + selectedCountLimit - + ") has a minimumCacheType (" + minimumCacheType - + ") that is higher than " + SelectionCacheType.JUST_IN_TIME + "."); - } - } - - private ValueSelector applySelectedLimit( - SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (selectedCountLimit != null) { - valueSelector = new SelectedCountLimitValueSelector(valueSelector, selectedCountLimit); - } - return valueSelector; - } - - private ValueSelector applyReinitializeVariableFiltering(HeuristicConfigPolicy configPolicy, - ValueSelector valueSelector) { - if (configPolicy.isReinitializeVariableFilterEnabled()) { - valueSelector = new ReinitializeVariableValueSelector(valueSelector); - } - return valueSelector; - } - - private ValueSelector applyDowncasting(HeuristicConfigPolicy configPolicy, ValueSelector valueSelector) { - if (downcastEntityClass != null) { - valueSelector = new DowncastingValueSelector(valueSelector, downcastEntityClass); - } - return valueSelector; - } - - public void inherit(ValueSelectorConfig inheritedConfig) { - super.inherit(inheritedConfig); - downcastEntityClass = ConfigUtils.inheritOverwritableProperty(downcastEntityClass, - inheritedConfig.getDowncastEntityClass()); - variableName = ConfigUtils.inheritOverwritableProperty(variableName, inheritedConfig.getVariableName()); - cacheType = ConfigUtils.inheritOverwritableProperty(cacheType, inheritedConfig.getCacheType()); - selectionOrder = ConfigUtils.inheritOverwritableProperty(selectionOrder, inheritedConfig.getSelectionOrder()); - sorterManner = ConfigUtils.inheritOverwritableProperty( - sorterManner, inheritedConfig.getSorterManner()); - sorterComparatorClass = ConfigUtils.inheritOverwritableProperty( - sorterComparatorClass, inheritedConfig.getSorterComparatorClass()); - sorterWeightFactoryClass = ConfigUtils.inheritOverwritableProperty( - sorterWeightFactoryClass, inheritedConfig.getSorterWeightFactoryClass()); - sorterOrder = ConfigUtils.inheritOverwritableProperty( - sorterOrder, inheritedConfig.getSorterOrder()); - sorterClass = ConfigUtils.inheritOverwritableProperty( - sorterClass, inheritedConfig.getSorterClass()); - probabilityWeightFactoryClass = ConfigUtils.inheritOverwritableProperty( - probabilityWeightFactoryClass, inheritedConfig.getProbabilityWeightFactoryClass()); - selectedCountLimit = ConfigUtils.inheritOverwritableProperty( - selectedCountLimit, inheritedConfig.getSelectedCountLimit()); - } - - @Override - public String toString() { - return getClass().getSimpleName() + "(" + variableName + ")"; - } - - /** - * Build-in ways of sorting. - */ - public static enum ValueSorterManner { - INCREASING_STRENGTH; - - public SelectionSorter determineSorter(GenuineVariableDescriptor variableDescriptor) { - SelectionSorter sorter; - switch (this) { - case INCREASING_STRENGTH: - sorter = variableDescriptor.getIncreasingStrengthSorter(); - if (sorter == null) { - throw new IllegalArgumentException("The sorterManner (" + this - + ") on entity class (" - + variableDescriptor.getEntityDescriptor().getEntityClass() - + ")'s variable (" + variableDescriptor.getVariableName() - + ") fails because that variable getter's " + PlanningVariable.class.getSimpleName() - + " annotation does not declare any strength comparison."); - } - return sorter; - default: - throw new IllegalStateException("The sorterManner (" - + this + ") is not implemented."); - } - } - } - -} diff --git a/All/Genesis-NP/Genesis#7/old/ValueSelectorConfig.java b/All/Genesis-NP/Genesis#7/old/ValueSelectorConfig.java deleted file mode 100755 index 8345e1f..0000000 --- a/All/Genesis-NP/Genesis#7/old/ValueSelectorConfig.java +++ /dev/null @@ -1,531 +0,0 @@ -/* - * Copyright 2012 JBoss 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 org.optaplanner.core.config.heuristic.selector.value; - -import java.util.Comparator; - -import com.thoughtworks.xstream.annotations.XStreamAlias; -import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider; -import org.optaplanner.core.api.domain.variable.PlanningVariable; -import org.optaplanner.core.config.heuristic.policy.HeuristicConfigPolicy; -import org.optaplanner.core.config.heuristic.selector.SelectorConfig; -import org.optaplanner.core.config.heuristic.selector.common.SelectionOrder; -import org.optaplanner.core.config.util.ConfigUtils; -import org.optaplanner.core.impl.domain.entity.descriptor.EntityDescriptor; -import org.optaplanner.core.impl.domain.valuerange.descriptor.EntityIndependentValueRangeDescriptor; -import org.optaplanner.core.impl.domain.valuerange.descriptor.ValueRangeDescriptor; -import org.optaplanner.core.impl.domain.variable.descriptor.GenuineVariableDescriptor; -import org.optaplanner.core.impl.heuristic.selector.common.SelectionCacheType; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.ComparatorSelectionSorter; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionSorter; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionSorterOrder; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.SelectionSorterWeightFactory; -import org.optaplanner.core.impl.heuristic.selector.common.decorator.WeightFactorySelectionSorter; -import org.optaplanner.core.impl.heuristic.selector.entity.EntitySelector; -import org.optaplanner.core.impl.heuristic.selector.value.EntityIndependentValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.FromEntityPropertyValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.FromSolutionPropertyValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.ValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.CachingValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.DowncastingValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.EntityDependentSortingValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.InitializedValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.ProbabilityValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.ReinitializeVariableValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.SelectedCountLimitValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.ShufflingValueSelector; -import org.optaplanner.core.impl.heuristic.selector.value.decorator.SortingValueSelector; - -@XStreamAlias("valueSelector") -public class ValueSelectorConfig extends SelectorConfig { - - protected Class downcastEntityClass = null; - protected String variableName = null; - - protected SelectionCacheType cacheType = null; - protected SelectionOrder selectionOrder = null; - - // TODO filterClass - - protected ValueSorterManner sorterManner = null; - protected Class sorterComparatorClass = null; - protected Class sorterWeightFactoryClass = null; - protected SelectionSorterOrder sorterOrder = null; - protected Class sorterClass = null; - - protected Class probabilityWeightFactoryClass = null; - - protected Long selectedCountLimit = null; - - public Class getDowncastEntityClass() { - return downcastEntityClass; - } - - public void setDowncastEntityClass(Class downcastEntityClass) { - this.downcastEntityClass = downcastEntityClass; - } - - public String getVariableName() { - return variableName; - } - - public void setVariableName(String variableName) { - this.variableName = variableName; - } - - public SelectionCacheType getCacheType() { - return cacheType; - } - - public void setCacheType(SelectionCacheType cacheType) { - this.cacheType = cacheType; - } - - public SelectionOrder getSelectionOrder() { - return selectionOrder; - } - - public void setSelectionOrder(SelectionOrder selectionOrder) { - this.selectionOrder = selectionOrder; - } - - public ValueSorterManner getSorterManner() { - return sorterManner; - } - - public void setSorterManner(ValueSorterManner sorterManner) { - this.sorterManner = sorterManner; - } - - public Class getSorterComparatorClass() { - return sorterComparatorClass; - } - - public void setSorterComparatorClass(Class sorterComparatorClass) { - this.sorterComparatorClass = sorterComparatorClass; - } - - public Class getSorterWeightFactoryClass() { - return sorterWeightFactoryClass; - } - - public void setSorterWeightFactoryClass(Class sorterWeightFactoryClass) { - this.sorterWeightFactoryClass = sorterWeightFactoryClass; - } - - public SelectionSorterOrder getSorterOrder() { - return sorterOrder; - } - - public void setSorterOrder(SelectionSorterOrder sorterOrder) { - this.sorterOrder = sorterOrder; - } - - public Class getSorterClass() { - return sorterClass; - } - - public void setSorterClass(Class sorterClass) { - this.sorterClass = sorterClass; - } - - public Class getProbabilityWeightFactoryClass() { - return probabilityWeightFactoryClass; - } - - public void setProbabilityWeightFactoryClass(Class probabilityWeightFactoryClass) { - this.probabilityWeightFactoryClass = probabilityWeightFactoryClass; - } - - public Long getSelectedCountLimit() { - return selectedCountLimit; - } - - public void setSelectedCountLimit(Long selectedCountLimit) { - this.selectedCountLimit = selectedCountLimit; - } - - // ************************************************************************ - // Builder methods - // ************************************************************************ - - /** - * - * @param configPolicy never null - * @param entityDescriptor never null - * @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}), - * then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching - * and less would be pointless. - * @param inheritedSelectionOrder never null - * @return never null - */ - public ValueSelector buildValueSelector(HeuristicConfigPolicy configPolicy, - EntityDescriptor entityDescriptor, - SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) { - if (downcastEntityClass != null) { - Class parentEntityClass = entityDescriptor.getEntityClass(); - if (!parentEntityClass.isAssignableFrom(downcastEntityClass)) { - throw new IllegalStateException("The downcastEntityClass (" + downcastEntityClass - + ") is not a subclass of the parentEntityClass (" + parentEntityClass - + ") configured by the " + EntitySelector.class.getSimpleName() + "."); - } - entityDescriptor = configPolicy.getSolutionDescriptor().getEntityDescriptorStrict(downcastEntityClass); - } - GenuineVariableDescriptor variableDescriptor = deduceVariableDescriptor(entityDescriptor, variableName); - SelectionCacheType resolvedCacheType = SelectionCacheType.resolve(cacheType, minimumCacheType); - SelectionOrder resolvedSelectionOrder = SelectionOrder.resolve(selectionOrder, - inheritedSelectionOrder); - - validateCacheTypeVersusSelectionOrder(resolvedCacheType, resolvedSelectionOrder); - validateSorting(resolvedSelectionOrder); - validateProbability(resolvedSelectionOrder); - validateSelectedLimit(minimumCacheType); - - // baseValueSelector and lower should be SelectionOrder.ORIGINAL if they are going to get cached completely - ValueSelector valueSelector = buildBaseValueSelector(configPolicy, variableDescriptor, - SelectionCacheType.max(minimumCacheType, resolvedCacheType), - determineBaseRandomSelection(variableDescriptor, resolvedCacheType, resolvedSelectionOrder)); - -// valueSelector = applyFiltering(variableDescriptor, resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyInitializedChainedValueFilter(configPolicy, variableDescriptor, - resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applySorting(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyProbability(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyShuffling(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyCaching(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applySelectedLimit(resolvedCacheType, resolvedSelectionOrder, valueSelector); - valueSelector = applyReinitializeVariableFiltering(configPolicy, valueSelector); - valueSelector = applyDowncasting(configPolicy, valueSelector); - return valueSelector; - } - - protected boolean determineBaseRandomSelection(GenuineVariableDescriptor variableDescriptor, - SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder) { - switch (resolvedSelectionOrder) { - case ORIGINAL: - return false; - case SORTED: - case SHUFFLED: - case PROBABILISTIC: - // baseValueSelector and lower should be ORIGINAL if they are going to get cached completely - return false; - case RANDOM: - // Predict if caching will occur - return resolvedCacheType.isNotCached() || (isBaseInherentlyCached(variableDescriptor) && !hasFiltering()); - default: - throw new IllegalStateException("The selectionOrder (" + resolvedSelectionOrder - + ") is not implemented."); - } - } - - protected boolean isBaseInherentlyCached(GenuineVariableDescriptor variableDescriptor) { - return variableDescriptor.isValueRangeEntityIndependent(); - } - - private ValueSelector buildBaseValueSelector( - HeuristicConfigPolicy configPolicy, GenuineVariableDescriptor variableDescriptor, - SelectionCacheType minimumCacheType, boolean randomSelection) { - ValueRangeDescriptor valueRangeDescriptor = variableDescriptor.getValueRangeDescriptor(); - // TODO minimumCacheType SOLVER is only a problem if the valueRange includes entities or custom weird cloning - if (minimumCacheType == SelectionCacheType.SOLVER) { - // TODO Solver cached entities are not compatible with DroolsScoreCalculator and IncrementalScoreDirector - // because between phases the entities get cloned and the KieSession/Maps contains those clones afterwards - // https://issues.jboss.org/browse/PLANNER-54 - throw new IllegalArgumentException("The minimumCacheType (" + minimumCacheType - + ") is not yet supported. Please use " + SelectionCacheType.PHASE + " instead."); - } - if (valueRangeDescriptor.isEntityIndependent()) { - return new FromSolutionPropertyValueSelector( - (EntityIndependentValueRangeDescriptor) valueRangeDescriptor, minimumCacheType, randomSelection); - } else { - // TODO Do not allow PHASE cache on FromEntityPropertyValueSelector, except if the moveSelector is PHASE cached too. - return new FromEntityPropertyValueSelector(valueRangeDescriptor, randomSelection); - } - } - - private boolean hasFiltering() { - return false; // NOT yet implemented - } - - protected ValueSelector applyInitializedChainedValueFilter(HeuristicConfigPolicy configPolicy, - GenuineVariableDescriptor variableDescriptor, - SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (configPolicy.isInitializedChainedValueFilterEnabled() - && variableDescriptor.isChained()) { - valueSelector = new InitializedValueSelector(valueSelector); - } - return valueSelector; - } - - private void validateSorting(SelectionOrder resolvedSelectionOrder) { - if ((sorterManner != null || sorterComparatorClass != null || sorterWeightFactoryClass != null - || sorterOrder != null || sorterClass != null) - && resolvedSelectionOrder != SelectionOrder.SORTED) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with sorterManner (" + sorterManner - + ") and sorterComparatorClass (" + sorterComparatorClass - + ") and sorterWeightFactoryClass (" + sorterWeightFactoryClass - + ") and sorterOrder (" + sorterOrder - + ") and sorterClass (" + sorterClass - + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder - + ") that is not " + SelectionOrder.SORTED + "."); - } - if (sorterManner != null && sorterComparatorClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterManner (" + sorterManner - + ") and a sorterComparatorClass (" + sorterComparatorClass + ")."); - } - if (sorterManner != null && sorterWeightFactoryClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterManner (" + sorterManner - + ") and a sorterWeightFactoryClass (" + sorterWeightFactoryClass + ")."); - } - if (sorterManner != null && sorterClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterManner (" + sorterManner - + ") and a sorterClass (" + sorterClass + ")."); - } - if (sorterManner != null && sorterOrder != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with sorterManner (" + sorterManner - + ") has a non-null sorterOrder (" + sorterOrder + ")."); - } - if (sorterComparatorClass != null && sorterWeightFactoryClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterComparatorClass (" + sorterComparatorClass - + ") and a sorterWeightFactoryClass (" + sorterWeightFactoryClass + ")."); - } - if (sorterComparatorClass != null && sorterClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterComparatorClass (" + sorterComparatorClass - + ") and a sorterClass (" + sorterClass + ")."); - } - if (sorterWeightFactoryClass != null && sorterClass != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") has both a sorterWeightFactoryClass (" + sorterWeightFactoryClass - + ") and a sorterClass (" + sorterClass + ")."); - } - if (sorterClass != null && sorterOrder != null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with sorterClass (" + sorterClass - + ") has a non-null sorterOrder (" + sorterOrder + ")."); - } - } - - private ValueSelector applySorting(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (resolvedSelectionOrder == SelectionOrder.SORTED) { - SelectionSorter sorter; - if (sorterManner != null) { - sorter = sorterManner.determineSorter(valueSelector.getVariableDescriptor()); - } else if (sorterComparatorClass != null) { - Comparator sorterComparator = ConfigUtils.newInstance(this, - "sorterComparatorClass", sorterComparatorClass); - sorter = new ComparatorSelectionSorter(sorterComparator, - SelectionSorterOrder.resolve(sorterOrder)); - } else if (sorterWeightFactoryClass != null) { - SelectionSorterWeightFactory sorterWeightFactory = ConfigUtils.newInstance(this, - "sorterWeightFactoryClass", sorterWeightFactoryClass); - sorter = new WeightFactorySelectionSorter(sorterWeightFactory, - SelectionSorterOrder.resolve(sorterOrder)); - } else if (sorterClass != null) { - sorter = ConfigUtils.newInstance(this, "sorterClass", sorterClass); - } else { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs a sorterManner (" + sorterManner - + ") or a sorterComparatorClass (" + sorterComparatorClass - + ") or a sorterWeightFactoryClass (" + sorterWeightFactoryClass - + ") or a sorterClass (" + sorterClass + ")."); - } - if (!valueSelector.getVariableDescriptor().isValueRangeEntityIndependent() - && resolvedCacheType == SelectionCacheType.STEP) { - valueSelector = new EntityDependentSortingValueSelector(valueSelector, - resolvedCacheType, sorter); - } else { - if (!(valueSelector instanceof EntityIndependentValueSelector)) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedCacheType (" + resolvedCacheType - + ") and resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs to be based on a EntityIndependentValueSelector (" + valueSelector + ")." - + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); - } - valueSelector = new SortingValueSelector((EntityIndependentValueSelector) valueSelector, - resolvedCacheType, sorter); - } - } - return valueSelector; - } - - private void validateProbability(SelectionOrder resolvedSelectionOrder) { - if (probabilityWeightFactoryClass != null - && resolvedSelectionOrder != SelectionOrder.PROBABILISTIC) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with probabilityWeightFactoryClass (" + probabilityWeightFactoryClass - + ") has a resolvedSelectionOrder (" + resolvedSelectionOrder - + ") that is not " + SelectionOrder.PROBABILISTIC + "."); - } - } - - private ValueSelector applyProbability(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (resolvedSelectionOrder == SelectionOrder.PROBABILISTIC) { - if (probabilityWeightFactoryClass == null) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs a probabilityWeightFactoryClass (" - + probabilityWeightFactoryClass + ")."); - } - SelectionProbabilityWeightFactory probabilityWeightFactory = ConfigUtils.newInstance(this, - "probabilityWeightFactoryClass", probabilityWeightFactoryClass); - if (!(valueSelector instanceof EntityIndependentValueSelector)) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedCacheType (" + resolvedCacheType - + ") and resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs to be based on a EntityIndependentValueSelector (" + valueSelector + ")." - + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); - } - valueSelector = new ProbabilityValueSelector((EntityIndependentValueSelector) valueSelector, - resolvedCacheType, probabilityWeightFactory); - } - return valueSelector; - } - - private ValueSelector applyShuffling(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) { - if (!(valueSelector instanceof EntityIndependentValueSelector)) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedCacheType (" + resolvedCacheType - + ") and resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs to be based on a EntityIndependentValueSelector (" + valueSelector + ")." - + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); - } - valueSelector = new ShufflingValueSelector((EntityIndependentValueSelector) valueSelector, - resolvedCacheType); - } - return valueSelector; - } - - private ValueSelector applyCaching(SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (resolvedCacheType.isCached() && resolvedCacheType.compareTo(valueSelector.getCacheType()) > 0) { - if (!(valueSelector instanceof EntityIndependentValueSelector)) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with resolvedCacheType (" + resolvedCacheType - + ") and resolvedSelectionOrder (" + resolvedSelectionOrder - + ") needs to be based on a EntityIndependentValueSelector (" + valueSelector + ")." - + " Check your @" + ValueRangeProvider.class.getSimpleName() + " annotations."); - } - valueSelector = new CachingValueSelector((EntityIndependentValueSelector) valueSelector, resolvedCacheType, - resolvedSelectionOrder.toRandomSelectionBoolean()); - } - return valueSelector; - } - - private void validateSelectedLimit(SelectionCacheType minimumCacheType) { - if (selectedCountLimit != null - && minimumCacheType.compareTo(SelectionCacheType.JUST_IN_TIME) > 0) { - throw new IllegalArgumentException("The valueSelectorConfig (" + this - + ") with selectedCountLimit (" + selectedCountLimit - + ") has a minimumCacheType (" + minimumCacheType - + ") that is higher than " + SelectionCacheType.JUST_IN_TIME + "."); - } - } - - private ValueSelector applySelectedLimit( - SelectionCacheType resolvedCacheType, SelectionOrder resolvedSelectionOrder, - ValueSelector valueSelector) { - if (selectedCountLimit != null) { - valueSelector = new SelectedCountLimitValueSelector(valueSelector, selectedCountLimit); - } - return valueSelector; - } - - private ValueSelector applyReinitializeVariableFiltering(HeuristicConfigPolicy configPolicy, - ValueSelector valueSelector) { - if (configPolicy.isReinitializeVariableFilterEnabled()) { - valueSelector = new ReinitializeVariableValueSelector(valueSelector); - } - return valueSelector; - } - - private ValueSelector applyDowncasting(HeuristicConfigPolicy configPolicy, ValueSelector valueSelector) { - if (downcastEntityClass != null) { - valueSelector = new DowncastingValueSelector(valueSelector, downcastEntityClass); - } - return valueSelector; - } - - public void inherit(ValueSelectorConfig inheritedConfig) { - super.inherit(inheritedConfig); - downcastEntityClass = ConfigUtils.inheritOverwritableProperty(downcastEntityClass, - inheritedConfig.getDowncastEntityClass()); - variableName = ConfigUtils.inheritOverwritableProperty(variableName, inheritedConfig.getVariableName()); - cacheType = ConfigUtils.inheritOverwritableProperty(cacheType, inheritedConfig.getCacheType()); - selectionOrder = ConfigUtils.inheritOverwritableProperty(selectionOrder, inheritedConfig.getSelectionOrder()); - sorterManner = ConfigUtils.inheritOverwritableProperty( - sorterManner, inheritedConfig.getSorterManner()); - sorterComparatorClass = ConfigUtils.inheritOverwritableProperty( - sorterComparatorClass, inheritedConfig.getSorterComparatorClass()); - sorterWeightFactoryClass = ConfigUtils.inheritOverwritableProperty( - sorterWeightFactoryClass, inheritedConfig.getSorterWeightFactoryClass()); - sorterOrder = ConfigUtils.inheritOverwritableProperty( - sorterOrder, inheritedConfig.getSorterOrder()); - sorterClass = ConfigUtils.inheritOverwritableProperty( - sorterClass, inheritedConfig.getSorterClass()); - probabilityWeightFactoryClass = ConfigUtils.inheritOverwritableProperty( - probabilityWeightFactoryClass, inheritedConfig.getProbabilityWeightFactoryClass()); - selectedCountLimit = ConfigUtils.inheritOverwritableProperty( - selectedCountLimit, inheritedConfig.getSelectedCountLimit()); - } - - @Override - public String toString() { - return getClass().getSimpleName() + "(" + variableName + ")"; - } - - /** - * Build-in ways of sorting. - */ - public static enum ValueSorterManner { - INCREASING_STRENGTH; - - public SelectionSorter determineSorter(GenuineVariableDescriptor variableDescriptor) { - SelectionSorter sorter; - switch (this) { - case INCREASING_STRENGTH: - sorter = variableDescriptor.getIncreasingStrengthSorter(); - if (sorter == null) { - throw new IllegalArgumentException("The sorterManner (" + this - + ") on entity class (" - + variableDescriptor.getEntityDescriptor().getEntityClass() - + ")'s variable (" + variableDescriptor.getVariableName() - + ") fails because that variable getter's " + PlanningVariable.class.getSimpleName() - + " annotation does not declare any strength comparison."); - } - return sorter; - default: - throw new IllegalStateException("The sorterManner (" - + this + ") is not implemented."); - } - } - } - -} diff --git a/All/Genesis-NP/Genesis#7/pair.info b/All/Genesis-NP/Genesis#7/pair.info deleted file mode 100755 index 3ac57d2..0000000 --- a/All/Genesis-NP/Genesis#7/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:7 -SATName:Genesis -modifiedFPath:optaplanner-core/src/main/java/org/optaplanner/core/config/heuristic/selector/value/ValueSelectorConfig.java -comSha:1559c1e2f14ed8858cf0d90feec81fba465a03df -parentComSha:1559c1e2f14ed8858cf0d90feec81fba465a03df^1 -githubUrl:https://github.com/droolsjbpm/optaplanner -repoName:droolsjbpm#optaplanner \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#82/comMsg.txt b/All/Genesis-NP/Genesis#82/comMsg.txt deleted file mode 100755 index 8569731..0000000 --- a/All/Genesis-NP/Genesis#82/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -ROO-3304: NullPointerException at ConversionServiceMetadata when push in method of ApplicationConversionServiceFactoryBean diff --git a/All/Genesis-NP/Genesis#82/diff.diff b/All/Genesis-NP/Genesis#82/diff.diff deleted file mode 100755 index 547d13d..0000000 --- a/All/Genesis-NP/Genesis#82/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/converter/ConversionServiceMetadata.java b/addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/converter/ConversionServiceMetadata.java -index 8b71097..eff0571 100644 ---- a/addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/converter/ConversionServiceMetadata.java -+++ b/addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/converter/ConversionServiceMetadata.java -@@ -183,0 +184 @@ public class ConversionServiceMetadata extends -+ if (jsonToConverterMethod != null) { -@@ -187,0 +189 @@ public class ConversionServiceMetadata extends -+ } -@@ -191,0 +194 @@ public class ConversionServiceMetadata extends -+ if (toJsonConverterMethod != null) { -@@ -196,0 +200 @@ public class ConversionServiceMetadata extends -+ } diff --git a/All/Genesis-NP/Genesis#82/new/ConversionServiceMetadata.java b/All/Genesis-NP/Genesis#82/new/ConversionServiceMetadata.java deleted file mode 100755 index eff0571..0000000 --- a/All/Genesis-NP/Genesis#82/new/ConversionServiceMetadata.java +++ /dev/null @@ -1,419 +0,0 @@ -package org.springframework.roo.addon.web.mvc.controller.converter; - -import static org.springframework.roo.model.SpringJavaType.CONFIGURABLE; -import static org.springframework.roo.model.SpringJavaType.FORMATTER_REGISTRY; - -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.Validate; -import org.springframework.roo.addon.json.CustomDataJsonTags; -import org.springframework.roo.classpath.PhysicalTypeMetadata; -import org.springframework.roo.classpath.details.MethodMetadata; -import org.springframework.roo.classpath.details.MethodMetadataBuilder; -import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType; -import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem; -import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder; -import org.springframework.roo.classpath.layers.MemberTypeAdditions; -import org.springframework.roo.model.JavaSymbolName; -import org.springframework.roo.model.JavaType; -import org.springframework.roo.model.SpringJavaType; - -/** - * Represents metadata for the application-wide conversion service. Generates - * the following ITD methods: - *
    - *
  • afterPropertiesSet() - overrides InitializingBean lifecycle parent method - *
  • - *
  • installLabelConverters(FormatterRegistry registry) - registers all - * converter methods
  • - *
  • a converter method for all scaffolded domain types as well their - * associations
  • - *
- * - * @author Rossen Stoyanchev - * @author Stefan Schmidt - * @since 1.1.1 - */ -public class ConversionServiceMetadata extends - AbstractItdTypeDetailsProvidingMetadataItem { - - private static final JavaType BASE_64 = new JavaType( - "org.apache.commons.codec.binary.Base64"); - private static final String CONVERTER = "Converter"; - private static final JavaSymbolName INSTALL_LABEL_CONVERTERS = new JavaSymbolName( - "installLabelConverters"); - - private Map> compositePrimaryKeyTypes; - private Map findMethods; - private Map idTypes; - private Set relevantDomainTypes; - private Map> toStringMethods; - - /** - * Production constructor - * - * @param identifier - * @param aspectName - * @param governorPhysicalTypeMetadata - * @param findMethods - * @param idTypes the ID types of the domain types for which to generate - * converters (required); must be one for each domain type - * @param relevantDomainTypes the types for which to generate converters - * (required) - * @param compositePrimaryKeyTypes (required) - */ - public ConversionServiceMetadata( - final String identifier, - final JavaType aspectName, - final PhysicalTypeMetadata governorPhysicalTypeMetadata, - final Map findMethods, - final Map idTypes, - final Set relevantDomainTypes, - final Map> compositePrimaryKeyTypes, - final Map> toStringMethods) { - super(identifier, aspectName, governorPhysicalTypeMetadata); - Validate.notNull(findMethods, "Find methods required"); - Validate.notNull(compositePrimaryKeyTypes, "List of PK types required"); - Validate.notNull(idTypes, "List of ID types required"); - Validate.notNull(relevantDomainTypes, - "List of relevant domain types required"); - Validate.isTrue(relevantDomainTypes.size() == idTypes.size(), - "Expected " + relevantDomainTypes.size() - + " ID types, but was " + idTypes.size()); - Validate.notNull(toStringMethods, "ToString methods required"); - - if (!isValid() || relevantDomainTypes.isEmpty() - && compositePrimaryKeyTypes.isEmpty()) { - valid = false; - return; - } - - this.findMethods = findMethods; - this.compositePrimaryKeyTypes = compositePrimaryKeyTypes; - this.idTypes = idTypes; - this.relevantDomainTypes = relevantDomainTypes; - this.toStringMethods = toStringMethods; - - builder.addAnnotation(getTypeAnnotation(CONFIGURABLE)); - builder.addMethod(getInstallLabelConvertersMethod()); - builder.addMethod(getAfterPropertiesSetMethod()); - - itdTypeDetails = builder.build(); - } - - private MethodMetadataBuilder getAfterPropertiesSetMethod() { - final JavaSymbolName methodName = new JavaSymbolName( - "afterPropertiesSet"); - if (governorHasMethod(methodName)) { - return null; - } - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("super.afterPropertiesSet();"); - bodyBuilder.appendFormalLine(INSTALL_LABEL_CONVERTERS.getSymbolName() - + "(getObject());"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - JavaType.VOID_PRIMITIVE, bodyBuilder); - } - - private MethodMetadataBuilder getInstallLabelConvertersMethod() { - final List sortedRelevantDomainTypes = new ArrayList( - relevantDomainTypes); - Collections.sort(sortedRelevantDomainTypes); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - - final Set methodNames = new HashSet(); - for (final JavaType formBackingObject : sortedRelevantDomainTypes) { - String simpleName = formBackingObject.getSimpleTypeName(); - while (methodNames.contains(simpleName)) { - simpleName += "_"; - } - methodNames.add(simpleName); - - final JavaSymbolName toIdMethodName = new JavaSymbolName("get" - + simpleName + "ToStringConverter"); - builder.addMethod(getToStringConverterMethod(formBackingObject, - toIdMethodName, toStringMethods.get(formBackingObject))); - bodyBuilder.appendFormalLine("registry.addConverter(" - + toIdMethodName.getSymbolName() + "());"); - - final JavaSymbolName toTypeMethodName = new JavaSymbolName( - "getIdTo" + simpleName + CONVERTER); - final MethodMetadataBuilder toTypeConverterMethod = getToTypeConverterMethod( - formBackingObject, toTypeMethodName, - findMethods.get(formBackingObject), - idTypes.get(formBackingObject)); - if (toTypeConverterMethod != null) { - builder.addMethod(toTypeConverterMethod); - bodyBuilder.appendFormalLine("registry.addConverter(" - + toTypeMethodName.getSymbolName() + "());"); - } - - // Only allow conversion if ID type is not String already. - if (!idTypes.get(formBackingObject).equals(JavaType.STRING)) { - final JavaSymbolName stringToTypeMethodName = new JavaSymbolName( - "getStringTo" + simpleName + CONVERTER); - builder.addMethod(getStringToTypeConverterMethod( - formBackingObject, stringToTypeMethodName, - idTypes.get(formBackingObject))); - bodyBuilder.appendFormalLine("registry.addConverter(" - + stringToTypeMethodName.getSymbolName() + "());"); - } - } - - for (final Entry> entry : compositePrimaryKeyTypes - .entrySet()) { - final JavaType targetType = entry.getKey(); - final Map jsonMethodNames = entry - .getValue(); - - final MethodMetadataBuilder jsonToConverterMethod = getJsonToConverterMethod( - targetType, - jsonMethodNames.get(CustomDataJsonTags.FROM_JSON_METHOD)); - if (jsonToConverterMethod != null) { - builder.addMethod(jsonToConverterMethod); - bodyBuilder.appendFormalLine("registry.addConverter(" - + jsonToConverterMethod.getMethodName().getSymbolName() - + "());"); - } - - final MethodMetadataBuilder toJsonConverterMethod = getToJsonConverterMethod( - targetType, - jsonMethodNames.get(CustomDataJsonTags.TO_JSON_METHOD)); - if (toJsonConverterMethod != null) { - builder.addMethod(toJsonConverterMethod); - bodyBuilder.appendFormalLine("registry.addConverter(" - + toJsonConverterMethod.getMethodName().getSymbolName() - + "());"); - } - } - - final JavaType parameterType = FORMATTER_REGISTRY; - if (governorHasMethod(INSTALL_LABEL_CONVERTERS, parameterType)) { - return null; - } - - final List parameterNames = Arrays - .asList(new JavaSymbolName("registry")); - builder.getImportRegistrationResolver().addImport(parameterType); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, - INSTALL_LABEL_CONVERTERS, JavaType.VOID_PRIMITIVE, - AnnotatedJavaType.convertFromJavaTypes(parameterType), - parameterNames, bodyBuilder); - } - - private MethodMetadataBuilder getJsonToConverterMethod( - final JavaType targetType, final JavaSymbolName jsonMethodName) { - final JavaSymbolName methodName = new JavaSymbolName("getJsonTo" - + targetType.getSimpleTypeName() + CONVERTER); - if (governorHasMethod(methodName)) { - return null; - } - - final JavaType converterJavaType = SpringJavaType.getConverterType( - JavaType.STRING, targetType); - - final String base64Name = BASE_64.getNameIncludingTypeParameters(false, - builder.getImportRegistrationResolver()); - final String typeName = targetType.getNameIncludingTypeParameters( - false, builder.getImportRegistrationResolver()); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("public " + targetType.getSimpleTypeName() - + " convert(String encodedJson) {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("return " + typeName + "." - + jsonMethodName.getSymbolName() + "(new String(" + base64Name - + ".decodeBase64(encodedJson)));"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } - - /** - * Returns the "string to type" converter method to be generated, if any - * - * @param targetType the type being converted into (required) - * @param methodName the name of the method to generate if necessary - * (required) - * @param idType the ID type of the given target type (required) - * @return null if none is to be generated - */ - private MethodMetadataBuilder getStringToTypeConverterMethod( - final JavaType targetType, final JavaSymbolName methodName, - final JavaType idType) { - if (governorHasMethod(methodName)) { - return null; - } - - final JavaType converterJavaType = SpringJavaType.getConverterType( - JavaType.STRING, targetType); - final String idTypeName = idType.getNameIncludingTypeParameters(false, - builder.getImportRegistrationResolver()); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("public " - + targetType.getFullyQualifiedTypeName() - + " convert(String id) {"); - bodyBuilder.indent(); - bodyBuilder - .appendFormalLine("return getObject().convert(getObject().convert(id, " - + idTypeName - + ".class), " - + targetType.getSimpleTypeName() + ".class);"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } - - private MethodMetadataBuilder getToJsonConverterMethod( - final JavaType targetType, final JavaSymbolName jsonMethodName) { - final JavaSymbolName methodName = new JavaSymbolName("get" - + targetType.getSimpleTypeName() + "ToJsonConverter"); - if (governorHasMethod(methodName)) { - return null; - } - - final JavaType converterJavaType = SpringJavaType.getConverterType( - targetType, JavaType.STRING); - - final String base64Name = BASE_64.getNameIncludingTypeParameters(false, - builder.getImportRegistrationResolver()); - final String targetTypeName = StringUtils.uncapitalize(targetType - .getSimpleTypeName()); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder - .appendFormalLine("public String convert(" - + targetType.getSimpleTypeName() + " " + targetTypeName - + ") {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("return " + base64Name - + ".encodeBase64URLSafeString(" + targetTypeName + "." - + jsonMethodName.getSymbolName() + "().getBytes());"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } - - private MethodMetadataBuilder getToStringConverterMethod( - final JavaType targetType, final JavaSymbolName methodName, - final List toStringMethods) { - if (governorHasMethod(methodName)) { - return null; - } - - final JavaType converterJavaType = SpringJavaType.getConverterType( - targetType, JavaType.STRING); - final String targetTypeName = StringUtils.uncapitalize(targetType - .getSimpleTypeName()); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder - .appendFormalLine("public String convert(" - + targetType.getSimpleTypeName() + " " + targetTypeName - + ") {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine(getTypeToStringLine(targetType, - targetTypeName, toStringMethods)); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } - - private String getTypeToStringLine(final JavaType targetType, - final String targetTypeName, - final List toStringMethods) { - if (toStringMethods.isEmpty()) { - return "return \"(no displayable fields)\";"; - } - - final StringBuilder sb = new StringBuilder("return new StringBuilder()"); - for (int i = 0; i < toStringMethods.size(); i++) { - if (i > 0) { - sb.append(".append(' ')"); - } - sb.append(".append("); - sb.append(targetTypeName); - sb.append("."); - sb.append(toStringMethods.get(i).getMethodName().getSymbolName()); - sb.append("())"); - } - sb.append(".toString();"); - return sb.toString(); - } - - private MethodMetadataBuilder getToTypeConverterMethod( - final JavaType targetType, final JavaSymbolName methodName, - final MemberTypeAdditions findMethod, final JavaType idType) { - final MethodMetadata toTypeConverterMethod = getGovernorMethod(methodName); - if (findMethod == null) { - return null; - } - if (toTypeConverterMethod != null) { - return new MethodMetadataBuilder(toTypeConverterMethod); - } - - findMethod.copyAdditionsTo(builder, governorTypeDetails); - final JavaType converterJavaType = SpringJavaType.getConverterType( - idType, targetType); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("public " - + targetType.getFullyQualifiedTypeName() + " convert(" + idType - + " id) {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("return " + findMethod.getMethodCall() - + ";"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#82/old/ConversionServiceMetadata.java b/All/Genesis-NP/Genesis#82/old/ConversionServiceMetadata.java deleted file mode 100755 index 8b71097..0000000 --- a/All/Genesis-NP/Genesis#82/old/ConversionServiceMetadata.java +++ /dev/null @@ -1,415 +0,0 @@ -package org.springframework.roo.addon.web.mvc.controller.converter; - -import static org.springframework.roo.model.SpringJavaType.CONFIGURABLE; -import static org.springframework.roo.model.SpringJavaType.FORMATTER_REGISTRY; - -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.Validate; -import org.springframework.roo.addon.json.CustomDataJsonTags; -import org.springframework.roo.classpath.PhysicalTypeMetadata; -import org.springframework.roo.classpath.details.MethodMetadata; -import org.springframework.roo.classpath.details.MethodMetadataBuilder; -import org.springframework.roo.classpath.details.annotations.AnnotatedJavaType; -import org.springframework.roo.classpath.itd.AbstractItdTypeDetailsProvidingMetadataItem; -import org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder; -import org.springframework.roo.classpath.layers.MemberTypeAdditions; -import org.springframework.roo.model.JavaSymbolName; -import org.springframework.roo.model.JavaType; -import org.springframework.roo.model.SpringJavaType; - -/** - * Represents metadata for the application-wide conversion service. Generates - * the following ITD methods: - *
    - *
  • afterPropertiesSet() - overrides InitializingBean lifecycle parent method - *
  • - *
  • installLabelConverters(FormatterRegistry registry) - registers all - * converter methods
  • - *
  • a converter method for all scaffolded domain types as well their - * associations
  • - *
- * - * @author Rossen Stoyanchev - * @author Stefan Schmidt - * @since 1.1.1 - */ -public class ConversionServiceMetadata extends - AbstractItdTypeDetailsProvidingMetadataItem { - - private static final JavaType BASE_64 = new JavaType( - "org.apache.commons.codec.binary.Base64"); - private static final String CONVERTER = "Converter"; - private static final JavaSymbolName INSTALL_LABEL_CONVERTERS = new JavaSymbolName( - "installLabelConverters"); - - private Map> compositePrimaryKeyTypes; - private Map findMethods; - private Map idTypes; - private Set relevantDomainTypes; - private Map> toStringMethods; - - /** - * Production constructor - * - * @param identifier - * @param aspectName - * @param governorPhysicalTypeMetadata - * @param findMethods - * @param idTypes the ID types of the domain types for which to generate - * converters (required); must be one for each domain type - * @param relevantDomainTypes the types for which to generate converters - * (required) - * @param compositePrimaryKeyTypes (required) - */ - public ConversionServiceMetadata( - final String identifier, - final JavaType aspectName, - final PhysicalTypeMetadata governorPhysicalTypeMetadata, - final Map findMethods, - final Map idTypes, - final Set relevantDomainTypes, - final Map> compositePrimaryKeyTypes, - final Map> toStringMethods) { - super(identifier, aspectName, governorPhysicalTypeMetadata); - Validate.notNull(findMethods, "Find methods required"); - Validate.notNull(compositePrimaryKeyTypes, "List of PK types required"); - Validate.notNull(idTypes, "List of ID types required"); - Validate.notNull(relevantDomainTypes, - "List of relevant domain types required"); - Validate.isTrue(relevantDomainTypes.size() == idTypes.size(), - "Expected " + relevantDomainTypes.size() - + " ID types, but was " + idTypes.size()); - Validate.notNull(toStringMethods, "ToString methods required"); - - if (!isValid() || relevantDomainTypes.isEmpty() - && compositePrimaryKeyTypes.isEmpty()) { - valid = false; - return; - } - - this.findMethods = findMethods; - this.compositePrimaryKeyTypes = compositePrimaryKeyTypes; - this.idTypes = idTypes; - this.relevantDomainTypes = relevantDomainTypes; - this.toStringMethods = toStringMethods; - - builder.addAnnotation(getTypeAnnotation(CONFIGURABLE)); - builder.addMethod(getInstallLabelConvertersMethod()); - builder.addMethod(getAfterPropertiesSetMethod()); - - itdTypeDetails = builder.build(); - } - - private MethodMetadataBuilder getAfterPropertiesSetMethod() { - final JavaSymbolName methodName = new JavaSymbolName( - "afterPropertiesSet"); - if (governorHasMethod(methodName)) { - return null; - } - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("super.afterPropertiesSet();"); - bodyBuilder.appendFormalLine(INSTALL_LABEL_CONVERTERS.getSymbolName() - + "(getObject());"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - JavaType.VOID_PRIMITIVE, bodyBuilder); - } - - private MethodMetadataBuilder getInstallLabelConvertersMethod() { - final List sortedRelevantDomainTypes = new ArrayList( - relevantDomainTypes); - Collections.sort(sortedRelevantDomainTypes); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - - final Set methodNames = new HashSet(); - for (final JavaType formBackingObject : sortedRelevantDomainTypes) { - String simpleName = formBackingObject.getSimpleTypeName(); - while (methodNames.contains(simpleName)) { - simpleName += "_"; - } - methodNames.add(simpleName); - - final JavaSymbolName toIdMethodName = new JavaSymbolName("get" - + simpleName + "ToStringConverter"); - builder.addMethod(getToStringConverterMethod(formBackingObject, - toIdMethodName, toStringMethods.get(formBackingObject))); - bodyBuilder.appendFormalLine("registry.addConverter(" - + toIdMethodName.getSymbolName() + "());"); - - final JavaSymbolName toTypeMethodName = new JavaSymbolName( - "getIdTo" + simpleName + CONVERTER); - final MethodMetadataBuilder toTypeConverterMethod = getToTypeConverterMethod( - formBackingObject, toTypeMethodName, - findMethods.get(formBackingObject), - idTypes.get(formBackingObject)); - if (toTypeConverterMethod != null) { - builder.addMethod(toTypeConverterMethod); - bodyBuilder.appendFormalLine("registry.addConverter(" - + toTypeMethodName.getSymbolName() + "());"); - } - - // Only allow conversion if ID type is not String already. - if (!idTypes.get(formBackingObject).equals(JavaType.STRING)) { - final JavaSymbolName stringToTypeMethodName = new JavaSymbolName( - "getStringTo" + simpleName + CONVERTER); - builder.addMethod(getStringToTypeConverterMethod( - formBackingObject, stringToTypeMethodName, - idTypes.get(formBackingObject))); - bodyBuilder.appendFormalLine("registry.addConverter(" - + stringToTypeMethodName.getSymbolName() + "());"); - } - } - - for (final Entry> entry : compositePrimaryKeyTypes - .entrySet()) { - final JavaType targetType = entry.getKey(); - final Map jsonMethodNames = entry - .getValue(); - - final MethodMetadataBuilder jsonToConverterMethod = getJsonToConverterMethod( - targetType, - jsonMethodNames.get(CustomDataJsonTags.FROM_JSON_METHOD)); - builder.addMethod(jsonToConverterMethod); - bodyBuilder.appendFormalLine("registry.addConverter(" - + jsonToConverterMethod.getMethodName().getSymbolName() - + "());"); - - final MethodMetadataBuilder toJsonConverterMethod = getToJsonConverterMethod( - targetType, - jsonMethodNames.get(CustomDataJsonTags.TO_JSON_METHOD)); - builder.addMethod(toJsonConverterMethod); - bodyBuilder.appendFormalLine("registry.addConverter(" - + toJsonConverterMethod.getMethodName().getSymbolName() - + "());"); - } - - final JavaType parameterType = FORMATTER_REGISTRY; - if (governorHasMethod(INSTALL_LABEL_CONVERTERS, parameterType)) { - return null; - } - - final List parameterNames = Arrays - .asList(new JavaSymbolName("registry")); - builder.getImportRegistrationResolver().addImport(parameterType); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, - INSTALL_LABEL_CONVERTERS, JavaType.VOID_PRIMITIVE, - AnnotatedJavaType.convertFromJavaTypes(parameterType), - parameterNames, bodyBuilder); - } - - private MethodMetadataBuilder getJsonToConverterMethod( - final JavaType targetType, final JavaSymbolName jsonMethodName) { - final JavaSymbolName methodName = new JavaSymbolName("getJsonTo" - + targetType.getSimpleTypeName() + CONVERTER); - if (governorHasMethod(methodName)) { - return null; - } - - final JavaType converterJavaType = SpringJavaType.getConverterType( - JavaType.STRING, targetType); - - final String base64Name = BASE_64.getNameIncludingTypeParameters(false, - builder.getImportRegistrationResolver()); - final String typeName = targetType.getNameIncludingTypeParameters( - false, builder.getImportRegistrationResolver()); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("public " + targetType.getSimpleTypeName() - + " convert(String encodedJson) {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("return " + typeName + "." - + jsonMethodName.getSymbolName() + "(new String(" + base64Name - + ".decodeBase64(encodedJson)));"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } - - /** - * Returns the "string to type" converter method to be generated, if any - * - * @param targetType the type being converted into (required) - * @param methodName the name of the method to generate if necessary - * (required) - * @param idType the ID type of the given target type (required) - * @return null if none is to be generated - */ - private MethodMetadataBuilder getStringToTypeConverterMethod( - final JavaType targetType, final JavaSymbolName methodName, - final JavaType idType) { - if (governorHasMethod(methodName)) { - return null; - } - - final JavaType converterJavaType = SpringJavaType.getConverterType( - JavaType.STRING, targetType); - final String idTypeName = idType.getNameIncludingTypeParameters(false, - builder.getImportRegistrationResolver()); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("public " - + targetType.getFullyQualifiedTypeName() - + " convert(String id) {"); - bodyBuilder.indent(); - bodyBuilder - .appendFormalLine("return getObject().convert(getObject().convert(id, " - + idTypeName - + ".class), " - + targetType.getSimpleTypeName() + ".class);"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } - - private MethodMetadataBuilder getToJsonConverterMethod( - final JavaType targetType, final JavaSymbolName jsonMethodName) { - final JavaSymbolName methodName = new JavaSymbolName("get" - + targetType.getSimpleTypeName() + "ToJsonConverter"); - if (governorHasMethod(methodName)) { - return null; - } - - final JavaType converterJavaType = SpringJavaType.getConverterType( - targetType, JavaType.STRING); - - final String base64Name = BASE_64.getNameIncludingTypeParameters(false, - builder.getImportRegistrationResolver()); - final String targetTypeName = StringUtils.uncapitalize(targetType - .getSimpleTypeName()); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder - .appendFormalLine("public String convert(" - + targetType.getSimpleTypeName() + " " + targetTypeName - + ") {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("return " + base64Name - + ".encodeBase64URLSafeString(" + targetTypeName + "." - + jsonMethodName.getSymbolName() + "().getBytes());"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } - - private MethodMetadataBuilder getToStringConverterMethod( - final JavaType targetType, final JavaSymbolName methodName, - final List toStringMethods) { - if (governorHasMethod(methodName)) { - return null; - } - - final JavaType converterJavaType = SpringJavaType.getConverterType( - targetType, JavaType.STRING); - final String targetTypeName = StringUtils.uncapitalize(targetType - .getSimpleTypeName()); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder - .appendFormalLine("public String convert(" - + targetType.getSimpleTypeName() + " " + targetTypeName - + ") {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine(getTypeToStringLine(targetType, - targetTypeName, toStringMethods)); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } - - private String getTypeToStringLine(final JavaType targetType, - final String targetTypeName, - final List toStringMethods) { - if (toStringMethods.isEmpty()) { - return "return \"(no displayable fields)\";"; - } - - final StringBuilder sb = new StringBuilder("return new StringBuilder()"); - for (int i = 0; i < toStringMethods.size(); i++) { - if (i > 0) { - sb.append(".append(' ')"); - } - sb.append(".append("); - sb.append(targetTypeName); - sb.append("."); - sb.append(toStringMethods.get(i).getMethodName().getSymbolName()); - sb.append("())"); - } - sb.append(".toString();"); - return sb.toString(); - } - - private MethodMetadataBuilder getToTypeConverterMethod( - final JavaType targetType, final JavaSymbolName methodName, - final MemberTypeAdditions findMethod, final JavaType idType) { - final MethodMetadata toTypeConverterMethod = getGovernorMethod(methodName); - if (findMethod == null) { - return null; - } - if (toTypeConverterMethod != null) { - return new MethodMetadataBuilder(toTypeConverterMethod); - } - - findMethod.copyAdditionsTo(builder, governorTypeDetails); - final JavaType converterJavaType = SpringJavaType.getConverterType( - idType, targetType); - - final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder(); - bodyBuilder.appendFormalLine("return new " - + converterJavaType.getNameIncludingTypeParameters() + "() {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("public " - + targetType.getFullyQualifiedTypeName() + " convert(" + idType - + " id) {"); - bodyBuilder.indent(); - bodyBuilder.appendFormalLine("return " + findMethod.getMethodCall() - + ";"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("}"); - bodyBuilder.indentRemove(); - bodyBuilder.appendFormalLine("};"); - - return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, - converterJavaType, bodyBuilder); - } -} \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#82/pair.info b/All/Genesis-NP/Genesis#82/pair.info deleted file mode 100755 index 4a8f3d3..0000000 --- a/All/Genesis-NP/Genesis#82/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:82 -SATName:Genesis -modifiedFPath:addon-web-mvc-controller/src/main/java/org/springframework/roo/addon/web/mvc/controller/converter/ConversionServiceMetadata.java -comSha:e0c4cb463f04fb8813e7cdc436d63a826060554e -parentComSha:e0c4cb463f04fb8813e7cdc436d63a826060554e^1 -githubUrl:https://github.com/spring-projects/spring-roo -repoName:spring-projects#spring-roo \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#84/comMsg.txt b/All/Genesis-NP/Genesis#84/comMsg.txt deleted file mode 100755 index 013f258..0000000 --- a/All/Genesis-NP/Genesis#84/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ - tempSchema == null schema name NullPointerException diff --git a/All/Genesis-NP/Genesis#84/diff.diff b/All/Genesis-NP/Genesis#84/diff.diff deleted file mode 100755 index 30ba649..0000000 --- a/All/Genesis-NP/Genesis#84/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/main/java/io/mycat/route/handler/HintSchemaHandler.java b/src/main/java/io/mycat/route/handler/HintSchemaHandler.java -index 5430fdf..66214a3 100644 ---- a/src/main/java/io/mycat/route/handler/HintSchemaHandler.java -+++ b/src/main/java/io/mycat/route/handler/HintSchemaHandler.java -@@ -49,2 +49,2 @@ public class HintSchemaHandler implements HintHandler { -- SchemaConfig tempSchema = MycatServer.getInstance().getConfig().getSchemas() -- .get(hintSQLValue); -+ -+ SchemaConfig tempSchema = MycatServer.getInstance().getConfig().getSchemas().get(hintSQLValue); -@@ -52,2 +52 @@ public class HintSchemaHandler implements HintHandler { -- return routeStrategy.route(sysConfig, tempSchema, -- sqlType, realSQL, charset, sc, cachePool); -+ return routeStrategy.route(sysConfig, tempSchema, sqlType, realSQL, charset, sc, cachePool); -@@ -55 +54 @@ public class HintSchemaHandler implements HintHandler { -- String msg = "can't find schema:" + tempSchema.getName(); -+ String msg = "can't find hint schema:" + hintSQLValue; diff --git a/All/Genesis-NP/Genesis#84/new/HintSchemaHandler.java b/All/Genesis-NP/Genesis#84/new/HintSchemaHandler.java deleted file mode 100755 index 66214a3..0000000 --- a/All/Genesis-NP/Genesis#84/new/HintSchemaHandler.java +++ /dev/null @@ -1,59 +0,0 @@ -package io.mycat.route.handler; - -import io.mycat.MycatServer; -import io.mycat.cache.LayerCachePool; -import io.mycat.route.RouteResultset; -import io.mycat.route.RouteStrategy; -import io.mycat.route.factory.RouteStrategyFactory; -import io.mycat.server.MySQLFrontConnection; -import io.mycat.server.config.node.SchemaConfig; -import io.mycat.server.config.node.SystemConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.SQLNonTransientException; - -/** - * 处理注释中类型为schema 的情况(按照指定schema做路由解析) - */ -public class HintSchemaHandler implements HintHandler { - - private static final Logger LOGGER = LoggerFactory - .getLogger(HintSchemaHandler.class); - - private RouteStrategy routeStrategy; - - public HintSchemaHandler() { - this.routeStrategy = RouteStrategyFactory.getRouteStrategy(); - } - /** - * 从全局的schema列表中查询指定的schema是否存在, 如果存在则替换connection属性中原有的schema, - * 如果不存在,则throws SQLNonTransientException,表示指定的schema 不存在 - * - * @param sysConfig - * @param schema - * @param sqlType - * @param realSQL - * @param charset - * @param info - * @param cachePool - * @param hintSQLValue - * @return - * @throws SQLNonTransientException - */ - @Override - public RouteResultset route(SystemConfig sysConfig, SchemaConfig schema, - int sqlType, String realSQL, String charset, MySQLFrontConnection sc, - LayerCachePool cachePool, String hintSQLValue) - throws SQLNonTransientException { - - SchemaConfig tempSchema = MycatServer.getInstance().getConfig().getSchemas().get(hintSQLValue); - if (tempSchema != null) { - return routeStrategy.route(sysConfig, tempSchema, sqlType, realSQL, charset, sc, cachePool); - } else { - String msg = "can't find hint schema:" + hintSQLValue; - LOGGER.warn(msg); - throw new SQLNonTransientException(msg); - } - } -} diff --git a/All/Genesis-NP/Genesis#84/old/HintSchemaHandler.java b/All/Genesis-NP/Genesis#84/old/HintSchemaHandler.java deleted file mode 100755 index 5430fdf..0000000 --- a/All/Genesis-NP/Genesis#84/old/HintSchemaHandler.java +++ /dev/null @@ -1,60 +0,0 @@ -package io.mycat.route.handler; - -import io.mycat.MycatServer; -import io.mycat.cache.LayerCachePool; -import io.mycat.route.RouteResultset; -import io.mycat.route.RouteStrategy; -import io.mycat.route.factory.RouteStrategyFactory; -import io.mycat.server.MySQLFrontConnection; -import io.mycat.server.config.node.SchemaConfig; -import io.mycat.server.config.node.SystemConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.sql.SQLNonTransientException; - -/** - * 处理注释中类型为schema 的情况(按照指定schema做路由解析) - */ -public class HintSchemaHandler implements HintHandler { - - private static final Logger LOGGER = LoggerFactory - .getLogger(HintSchemaHandler.class); - - private RouteStrategy routeStrategy; - - public HintSchemaHandler() { - this.routeStrategy = RouteStrategyFactory.getRouteStrategy(); - } - /** - * 从全局的schema列表中查询指定的schema是否存在, 如果存在则替换connection属性中原有的schema, - * 如果不存在,则throws SQLNonTransientException,表示指定的schema 不存在 - * - * @param sysConfig - * @param schema - * @param sqlType - * @param realSQL - * @param charset - * @param info - * @param cachePool - * @param hintSQLValue - * @return - * @throws SQLNonTransientException - */ - @Override - public RouteResultset route(SystemConfig sysConfig, SchemaConfig schema, - int sqlType, String realSQL, String charset, MySQLFrontConnection sc, - LayerCachePool cachePool, String hintSQLValue) - throws SQLNonTransientException { - SchemaConfig tempSchema = MycatServer.getInstance().getConfig().getSchemas() - .get(hintSQLValue); - if (tempSchema != null) { - return routeStrategy.route(sysConfig, tempSchema, - sqlType, realSQL, charset, sc, cachePool); - } else { - String msg = "can't find schema:" + tempSchema.getName(); - LOGGER.warn(msg); - throw new SQLNonTransientException(msg); - } - } -} diff --git a/All/Genesis-NP/Genesis#84/pair.info b/All/Genesis-NP/Genesis#84/pair.info deleted file mode 100755 index fcb063d..0000000 --- a/All/Genesis-NP/Genesis#84/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:84 -SATName:Genesis -modifiedFPath:src/main/java/io/mycat/route/handler/HintSchemaHandler.java -comSha:92ca48baf9abb3ff0468913080ae85e73a50c18f -parentComSha:92ca48baf9abb3ff0468913080ae85e73a50c18f^1 -githubUrl:https://github.com/MyCATApache/Mycat-Server -repoName:MyCATApache#Mycat-Server \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#99/comMsg.txt b/All/Genesis-NP/Genesis#99/comMsg.txt deleted file mode 100755 index ce0a6ad..0000000 --- a/All/Genesis-NP/Genesis#99/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed NPE when NewHandler is used with java 8 method reference diff --git a/All/Genesis-NP/Genesis#99/diff.diff b/All/Genesis-NP/Genesis#99/diff.diff deleted file mode 100755 index 080b364..0000000 --- a/All/Genesis-NP/Genesis#99/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/NewHandler.java b/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/NewHandler.java -index 7a6566c..56f7742 100644 ---- a/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/NewHandler.java -+++ b/src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/NewHandler.java -@@ -26 +25,0 @@ import com.puppycrawl.tools.checkstyle.api.TokenTypes; -- * -@@ -27,0 +27 @@ import com.puppycrawl.tools.checkstyle.api.TokenTypes; -+ * @author Ilja Dubinin -@@ -49,0 +50 @@ public class NewHandler extends ExpressionHandler -+ if (type != null) { -@@ -50,0 +52 @@ public class NewHandler extends ExpressionHandler -+ } diff --git a/All/Genesis-NP/Genesis#99/new/NewHandler.java b/All/Genesis-NP/Genesis#99/new/NewHandler.java deleted file mode 100755 index 56f7742..0000000 --- a/All/Genesis-NP/Genesis#99/new/NewHandler.java +++ /dev/null @@ -1,98 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2014 Oliver Burn -// -// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// -package com.puppycrawl.tools.checkstyle.checks.indentation; - -import com.puppycrawl.tools.checkstyle.api.DetailAST; -import com.puppycrawl.tools.checkstyle.api.TokenTypes; - -/** - * Handler for operator new. - * @author o_sukhodolsky - * @author Ilja Dubinin - */ -public class NewHandler extends ExpressionHandler -{ - /** - * Construct an instance of this handler with the given indentation check, - * abstract syntax tree, and parent handler. - * - * @param aIndentCheck the indentation check - * @param aAST the abstract syntax tree - * @param aParent the parent handler - */ - public NewHandler(IndentationCheck aIndentCheck, - DetailAST aAST, - ExpressionHandler aParent) - { - super(aIndentCheck, "operator new", aAST, aParent); - } - - @Override - public void checkIndentation() - { - final DetailAST type = getMainAst().getFirstChild(); - if (type != null) { - checkExpressionSubtree(type, getLevel(), false, false); - } - - final DetailAST lparen = getMainAst().findFirstToken(TokenTypes.LPAREN); - final DetailAST rparen = getMainAst().findFirstToken(TokenTypes.RPAREN); - checkLParen(lparen); - - if ((rparen == null) || (lparen == null) - || (rparen.getLineNo() == lparen.getLineNo())) - { - return; - } - - // if this method name is on the same line as a containing - // method, don't indent, this allows expressions like: - // method("my str" + method2( - // "my str2")); - // as well as - // method("my str" + - // method2( - // "my str2")); - // - - checkExpressionSubtree( - getMainAst().findFirstToken(TokenTypes.ELIST), - new IndentLevel(getLevel(), getBasicOffset()), - false, true); - - checkRParen(lparen, rparen); - } - - @Override - protected IndentLevel getLevelImpl() - { - // if our expression isn't first on the line, just use the start - // of the line - if (getLineStart(getMainAst()) != getMainAst().getColumnNo()) { - return new IndentLevel(getLineStart(getMainAst())); - } - return super.getLevelImpl(); - } - - @Override - protected boolean shouldIncreaseIndent() - { - return false; - } -} diff --git a/All/Genesis-NP/Genesis#99/old/NewHandler.java b/All/Genesis-NP/Genesis#99/old/NewHandler.java deleted file mode 100755 index 7a6566c..0000000 --- a/All/Genesis-NP/Genesis#99/old/NewHandler.java +++ /dev/null @@ -1,96 +0,0 @@ -//////////////////////////////////////////////////////////////////////////////// -// checkstyle: Checks Java source code for adherence to a set of rules. -// Copyright (C) 2001-2014 Oliver Burn -// -// 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -//////////////////////////////////////////////////////////////////////////////// -package com.puppycrawl.tools.checkstyle.checks.indentation; - -import com.puppycrawl.tools.checkstyle.api.DetailAST; -import com.puppycrawl.tools.checkstyle.api.TokenTypes; - -/** - * Handler for operator new. - * - * @author o_sukhodolsky - */ -public class NewHandler extends ExpressionHandler -{ - /** - * Construct an instance of this handler with the given indentation check, - * abstract syntax tree, and parent handler. - * - * @param aIndentCheck the indentation check - * @param aAST the abstract syntax tree - * @param aParent the parent handler - */ - public NewHandler(IndentationCheck aIndentCheck, - DetailAST aAST, - ExpressionHandler aParent) - { - super(aIndentCheck, "operator new", aAST, aParent); - } - - @Override - public void checkIndentation() - { - final DetailAST type = getMainAst().getFirstChild(); - checkExpressionSubtree(type, getLevel(), false, false); - - final DetailAST lparen = getMainAst().findFirstToken(TokenTypes.LPAREN); - final DetailAST rparen = getMainAst().findFirstToken(TokenTypes.RPAREN); - checkLParen(lparen); - - if ((rparen == null) || (lparen == null) - || (rparen.getLineNo() == lparen.getLineNo())) - { - return; - } - - // if this method name is on the same line as a containing - // method, don't indent, this allows expressions like: - // method("my str" + method2( - // "my str2")); - // as well as - // method("my str" + - // method2( - // "my str2")); - // - - checkExpressionSubtree( - getMainAst().findFirstToken(TokenTypes.ELIST), - new IndentLevel(getLevel(), getBasicOffset()), - false, true); - - checkRParen(lparen, rparen); - } - - @Override - protected IndentLevel getLevelImpl() - { - // if our expression isn't first on the line, just use the start - // of the line - if (getLineStart(getMainAst()) != getMainAst().getColumnNo()) { - return new IndentLevel(getLineStart(getMainAst())); - } - return super.getLevelImpl(); - } - - @Override - protected boolean shouldIncreaseIndent() - { - return false; - } -} diff --git a/All/Genesis-NP/Genesis#99/pair.info b/All/Genesis-NP/Genesis#99/pair.info deleted file mode 100755 index f1f2684..0000000 --- a/All/Genesis-NP/Genesis#99/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:99 -SATName:Genesis -modifiedFPath:src/main/java/com/puppycrawl/tools/checkstyle/checks/indentation/NewHandler.java -comSha:47ce2a333dc5d8858772ca0a63666a0a440c8d57 -parentComSha:47ce2a333dc5d8858772ca0a63666a0a440c8d57^1 -githubUrl:https://github.com/checkstyle/checkstyle -repoName:checkstyle#checkstyle \ No newline at end of file diff --git a/All/Genesis-NP/Genesis#eval_11/comMsg.txt b/All/Genesis-NP/Genesis#eval_11/comMsg.txt deleted file mode 100755 index d001144..0000000 --- a/All/Genesis-NP/Genesis#eval_11/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix NullPointerException thrown by getOnly when a value is not present for a given tag. diff --git a/All/Genesis-NP/Genesis#eval_11/diff.diff b/All/Genesis-NP/Genesis#eval_11/diff.diff deleted file mode 100755 index 7b2a2c8..0000000 --- a/All/Genesis-NP/Genesis#eval_11/diff.diff +++ /dev/null @@ -1,9 +0,0 @@ -diff --git a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResult.java b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResult.java -index cbacb5f..56fc3fc 100644 ---- a/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResult.java -+++ b/sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResult.java -@@ -227,0 +228 @@ public class CoGbkResult { -+ @Override -@@ -320 +321 @@ public class CoGbkResult { -- if (unions.isEmpty()) { -+ if (unions == null || unions.isEmpty()) { diff --git a/All/Genesis-NP/Genesis#eval_11/new/CoGbkResult.java b/All/Genesis-NP/Genesis#eval_11/new/CoGbkResult.java deleted file mode 100755 index 56fc3fc..0000000 --- a/All/Genesis-NP/Genesis#eval_11/new/CoGbkResult.java +++ /dev/null @@ -1,369 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.cloud.dataflow.sdk.transforms.join; - -import static com.google.cloud.dataflow.sdk.util.Structs.addObject; - -import com.google.api.client.util.Preconditions; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.MapCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * A row result of a CoGroupByKey. This is a tuple of Iterables produced for - * a given key, and these can be accessed in different ways. - */ -public class CoGbkResult { - // TODO: If we keep this representation for any amount of time, - // optimize it so that the union tag does not have to be repeated in the - // values stored under the union tag key. - /** - * A map of integer union tags to a list of union objects. - * Note: the key and the embedded union tag are the same, so it is redundant - * to store it multiple times, but for now it makes encoding easier. - */ - private final Map> valueMap; - - private final CoGbkResultSchema schema; - - /** - * A row in the PCollection resulting from a CoGroupByKey transform. - * Currently, this row must fit into memory. - * - * @param schema the set of tuple tags used to refer to input tables and - * result values - * @param values the raw results from a group-by-key - */ - @SuppressWarnings("unchecked") - public CoGbkResult( - CoGbkResultSchema schema, - Iterable values) { - this.schema = schema; - valueMap = new TreeMap<>(); - for (RawUnionValue value : values) { - // Make sure the given union tag has a corresponding tuple tag in the - // schema. - int unionTag = value.getUnionTag(); - if (schema.size() <= unionTag) { - throw new IllegalStateException("union tag " + unionTag + - " has no corresponding tuple tag in the result schema"); - } - List taggedValueList = valueMap.get(unionTag); - if (taggedValueList == null) { - taggedValueList = new ArrayList<>(); - valueMap.put(unionTag, taggedValueList); - } - taggedValueList.add(value); - } - } - - public boolean isEmpty() { - return valueMap == null || valueMap.isEmpty(); - } - - /** - * Returns the schema used by this CoGbkResult. - */ - public CoGbkResultSchema getSchema() { - return schema; - } - - @Override - public String toString() { - return valueMap.toString(); - } - - /** - * Returns the values from the table represented by the given - * {@code TupleTag} as an {@code Iterable} (which may be empty if there - * are no results). - */ - public Iterable getAll(TupleTag tag) { - int index = schema.getIndex(tag); - if (index < 0) { - throw new IllegalArgumentException("TupleTag " + tag + - " is not in the schema"); - } - List unions = valueMap.get(index); - if (unions == null) { - return buildEmptyIterable(tag); - } - return new UnionValueIterable<>(unions); - } - - /** - * If there is a singleton value for the given tag, returns it. - * Otherwise, throws an IllegalArgumentException. - */ - public V getOnly(TupleTag tag) { - return innerGetOnly(tag, null, false); - } - - /** - * If there is a singleton value for the given tag, returns it. If there is - * no value for the given tag, returns the defaultValue. - * Otherwise, throws an IllegalArgumentException. - */ - public V getOnly(TupleTag tag, V defaultValue) { - return innerGetOnly(tag, defaultValue, true); - } - - /** - * A coder for CoGbkResults. - */ - @SuppressWarnings("serial") - public static class CoGbkResultCoder extends StandardCoder { - - private final CoGbkResultSchema schema; - private final MapCoder> mapCoder; - - /** - * Returns a CoGbkResultCoder for the given schema and unionCoder. - */ - public static CoGbkResultCoder of( - CoGbkResultSchema schema, - UnionCoder unionCoder) { - return new CoGbkResultCoder(schema, unionCoder); - } - - @JsonCreator - public static CoGbkResultCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components, - @JsonProperty(PropertyNames.CO_GBK_RESULT_SCHEMA) CoGbkResultSchema schema) { - Preconditions.checkArgument(components.size() == 1, - "Expecting 1 component, got " + components.size()); - return new CoGbkResultCoder(schema, (MapCoder) components.get(0)); - } - - private CoGbkResultCoder( - CoGbkResultSchema tupleTags, - UnionCoder unionCoder) { - this.schema = tupleTags; - this.mapCoder = MapCoder.of(VarIntCoder.of(), - ListCoder.of(unionCoder)); - } - - private CoGbkResultCoder( - CoGbkResultSchema tupleTags, - MapCoder mapCoder) { - this.schema = tupleTags; - this.mapCoder = mapCoder; - } - - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public List> getComponents() { - return Arrays.>asList(mapCoder); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addObject(result, PropertyNames.CO_GBK_RESULT_SCHEMA, schema.asCloudObject()); - return result; - } - - @Override - public void encode( - CoGbkResult value, - OutputStream outStream, - Context context) throws CoderException, - IOException { - if (!schema.equals(value.getSchema())) { - throw new CoderException("input schema does not match coder schema"); - } - mapCoder.encode(value.valueMap, outStream, context); - } - - @Override - public CoGbkResult decode( - InputStream inStream, - Context context) - throws CoderException, IOException { - Map> map = mapCoder.decode( - inStream, context); - return new CoGbkResult(schema, map); - } - - @Override - public boolean equals(Object other) { - if (!super.equals(other)) { - return false; - } - return schema.equals(((CoGbkResultCoder) other).schema); - } - - @Override - public boolean isDeterministic() { - return mapCoder.isDeterministic(); - } - } - - - ////////////////////////////////////////////////////////////////////////////// - // Methods for testing purposes - - /** - * Returns a new CoGbkResult that contains just the given tag the given data. - */ - public static CoGbkResult of(TupleTag tag, List data) { - return CoGbkResult.empty().and(tag, data); - } - - /** - * Returns a new CoGbkResult based on this, with the given tag and given data - * added to it. - */ - public CoGbkResult and(TupleTag tag, List data) { - if (nextTestUnionId != schema.size()) { - throw new IllegalArgumentException( - "Attempting to call and() on a CoGbkResult apparently not created by" - + " of()."); - } - Map> valueMap = new TreeMap<>(this.valueMap); - valueMap.put(nextTestUnionId, - convertValueListToUnionList(nextTestUnionId, data)); - return new CoGbkResult( - new CoGbkResultSchema(schema.getTupleTagList().and(tag)), valueMap, - nextTestUnionId + 1); - } - - /** - * Returns an empty CoGbkResult. - */ - public static CoGbkResult empty() { - return new CoGbkResult(new CoGbkResultSchema(TupleTagList.empty()), - new TreeMap>()); - } - - ////////////////////////////////////////////////////////////////////////////// - - private int nextTestUnionId = 0; - - private CoGbkResult( - CoGbkResultSchema schema, - Map> valueMap, - int nextTestUnionId) { - this(schema, valueMap); - this.nextTestUnionId = nextTestUnionId; - } - - private CoGbkResult( - CoGbkResultSchema schema, - Map> valueMap) { - this.schema = schema; - this.valueMap = valueMap; - } - - private static List convertValueListToUnionList( - int unionTag, List data) { - List unionList = new ArrayList<>(); - for (V value : data) { - unionList.add(new RawUnionValue(unionTag, value)); - } - return unionList; - } - - private Iterable buildEmptyIterable(TupleTag tag) { - return new ArrayList<>(); - } - - private V innerGetOnly( - TupleTag tag, - V defaultValue, - boolean useDefault) { - int index = schema.getIndex(tag); - if (index < 0) { - throw new IllegalArgumentException("TupleTag " + tag - + " is not in the schema"); - } - List unions = valueMap.get(index); - if (unions == null || unions.isEmpty()) { - if (useDefault) { - return defaultValue; - } else { - throw new IllegalArgumentException("TupleTag " + tag - + " corresponds to an empty result, and no default was provided"); - } - } - if (unions.size() != 1) { - throw new IllegalArgumentException("TupleTag " + tag - + " corresponds to a non-singleton result of size " + unions.size()); - } - return (V) unions.get(0).getValue(); - } - - /** - * Lazily converts and recasts an {@code Iterable} into an - * {@code Iterable}, where V is the type of the raw union value's contents. - */ - private static class UnionValueIterable implements Iterable { - - private final Iterable unions; - - private UnionValueIterable(Iterable unions) { - this.unions = unions; - } - - @Override - public Iterator iterator() { - final Iterator unionsIterator = unions.iterator(); - return new Iterator() { - @Override - public boolean hasNext() { - return unionsIterator.hasNext(); - } - - @Override - public V next() { - return (V) unionsIterator.next().getValue(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - } -} diff --git a/All/Genesis-NP/Genesis#eval_11/old/CoGbkResult.java b/All/Genesis-NP/Genesis#eval_11/old/CoGbkResult.java deleted file mode 100755 index cbacb5f..0000000 --- a/All/Genesis-NP/Genesis#eval_11/old/CoGbkResult.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Copyright (C) 2014 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not - * use this file except in compliance with the License. You may obtain a copy of - * the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT - * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the - * License for the specific language governing permissions and limitations under - * the License. - */ - -package com.google.cloud.dataflow.sdk.transforms.join; - -import static com.google.cloud.dataflow.sdk.util.Structs.addObject; - -import com.google.api.client.util.Preconditions; -import com.google.cloud.dataflow.sdk.coders.Coder; -import com.google.cloud.dataflow.sdk.coders.CoderException; -import com.google.cloud.dataflow.sdk.coders.ListCoder; -import com.google.cloud.dataflow.sdk.coders.MapCoder; -import com.google.cloud.dataflow.sdk.coders.StandardCoder; -import com.google.cloud.dataflow.sdk.coders.VarIntCoder; -import com.google.cloud.dataflow.sdk.util.CloudObject; -import com.google.cloud.dataflow.sdk.util.PropertyNames; -import com.google.cloud.dataflow.sdk.values.TupleTag; -import com.google.cloud.dataflow.sdk.values.TupleTagList; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * A row result of a CoGroupByKey. This is a tuple of Iterables produced for - * a given key, and these can be accessed in different ways. - */ -public class CoGbkResult { - // TODO: If we keep this representation for any amount of time, - // optimize it so that the union tag does not have to be repeated in the - // values stored under the union tag key. - /** - * A map of integer union tags to a list of union objects. - * Note: the key and the embedded union tag are the same, so it is redundant - * to store it multiple times, but for now it makes encoding easier. - */ - private final Map> valueMap; - - private final CoGbkResultSchema schema; - - /** - * A row in the PCollection resulting from a CoGroupByKey transform. - * Currently, this row must fit into memory. - * - * @param schema the set of tuple tags used to refer to input tables and - * result values - * @param values the raw results from a group-by-key - */ - @SuppressWarnings("unchecked") - public CoGbkResult( - CoGbkResultSchema schema, - Iterable values) { - this.schema = schema; - valueMap = new TreeMap<>(); - for (RawUnionValue value : values) { - // Make sure the given union tag has a corresponding tuple tag in the - // schema. - int unionTag = value.getUnionTag(); - if (schema.size() <= unionTag) { - throw new IllegalStateException("union tag " + unionTag + - " has no corresponding tuple tag in the result schema"); - } - List taggedValueList = valueMap.get(unionTag); - if (taggedValueList == null) { - taggedValueList = new ArrayList<>(); - valueMap.put(unionTag, taggedValueList); - } - taggedValueList.add(value); - } - } - - public boolean isEmpty() { - return valueMap == null || valueMap.isEmpty(); - } - - /** - * Returns the schema used by this CoGbkResult. - */ - public CoGbkResultSchema getSchema() { - return schema; - } - - @Override - public String toString() { - return valueMap.toString(); - } - - /** - * Returns the values from the table represented by the given - * {@code TupleTag} as an {@code Iterable} (which may be empty if there - * are no results). - */ - public Iterable getAll(TupleTag tag) { - int index = schema.getIndex(tag); - if (index < 0) { - throw new IllegalArgumentException("TupleTag " + tag + - " is not in the schema"); - } - List unions = valueMap.get(index); - if (unions == null) { - return buildEmptyIterable(tag); - } - return new UnionValueIterable<>(unions); - } - - /** - * If there is a singleton value for the given tag, returns it. - * Otherwise, throws an IllegalArgumentException. - */ - public V getOnly(TupleTag tag) { - return innerGetOnly(tag, null, false); - } - - /** - * If there is a singleton value for the given tag, returns it. If there is - * no value for the given tag, returns the defaultValue. - * Otherwise, throws an IllegalArgumentException. - */ - public V getOnly(TupleTag tag, V defaultValue) { - return innerGetOnly(tag, defaultValue, true); - } - - /** - * A coder for CoGbkResults. - */ - @SuppressWarnings("serial") - public static class CoGbkResultCoder extends StandardCoder { - - private final CoGbkResultSchema schema; - private final MapCoder> mapCoder; - - /** - * Returns a CoGbkResultCoder for the given schema and unionCoder. - */ - public static CoGbkResultCoder of( - CoGbkResultSchema schema, - UnionCoder unionCoder) { - return new CoGbkResultCoder(schema, unionCoder); - } - - @JsonCreator - public static CoGbkResultCoder of( - @JsonProperty(PropertyNames.COMPONENT_ENCODINGS) - List> components, - @JsonProperty(PropertyNames.CO_GBK_RESULT_SCHEMA) CoGbkResultSchema schema) { - Preconditions.checkArgument(components.size() == 1, - "Expecting 1 component, got " + components.size()); - return new CoGbkResultCoder(schema, (MapCoder) components.get(0)); - } - - private CoGbkResultCoder( - CoGbkResultSchema tupleTags, - UnionCoder unionCoder) { - this.schema = tupleTags; - this.mapCoder = MapCoder.of(VarIntCoder.of(), - ListCoder.of(unionCoder)); - } - - private CoGbkResultCoder( - CoGbkResultSchema tupleTags, - MapCoder mapCoder) { - this.schema = tupleTags; - this.mapCoder = mapCoder; - } - - - @Override - public List> getCoderArguments() { - return null; - } - - @Override - public List> getComponents() { - return Arrays.>asList(mapCoder); - } - - @Override - public CloudObject asCloudObject() { - CloudObject result = super.asCloudObject(); - addObject(result, PropertyNames.CO_GBK_RESULT_SCHEMA, schema.asCloudObject()); - return result; - } - - @Override - public void encode( - CoGbkResult value, - OutputStream outStream, - Context context) throws CoderException, - IOException { - if (!schema.equals(value.getSchema())) { - throw new CoderException("input schema does not match coder schema"); - } - mapCoder.encode(value.valueMap, outStream, context); - } - - @Override - public CoGbkResult decode( - InputStream inStream, - Context context) - throws CoderException, IOException { - Map> map = mapCoder.decode( - inStream, context); - return new CoGbkResult(schema, map); - } - - public boolean equals(Object other) { - if (!super.equals(other)) { - return false; - } - return schema.equals(((CoGbkResultCoder) other).schema); - } - - @Override - public boolean isDeterministic() { - return mapCoder.isDeterministic(); - } - } - - - ////////////////////////////////////////////////////////////////////////////// - // Methods for testing purposes - - /** - * Returns a new CoGbkResult that contains just the given tag the given data. - */ - public static CoGbkResult of(TupleTag tag, List data) { - return CoGbkResult.empty().and(tag, data); - } - - /** - * Returns a new CoGbkResult based on this, with the given tag and given data - * added to it. - */ - public CoGbkResult and(TupleTag tag, List data) { - if (nextTestUnionId != schema.size()) { - throw new IllegalArgumentException( - "Attempting to call and() on a CoGbkResult apparently not created by" - + " of()."); - } - Map> valueMap = new TreeMap<>(this.valueMap); - valueMap.put(nextTestUnionId, - convertValueListToUnionList(nextTestUnionId, data)); - return new CoGbkResult( - new CoGbkResultSchema(schema.getTupleTagList().and(tag)), valueMap, - nextTestUnionId + 1); - } - - /** - * Returns an empty CoGbkResult. - */ - public static CoGbkResult empty() { - return new CoGbkResult(new CoGbkResultSchema(TupleTagList.empty()), - new TreeMap>()); - } - - ////////////////////////////////////////////////////////////////////////////// - - private int nextTestUnionId = 0; - - private CoGbkResult( - CoGbkResultSchema schema, - Map> valueMap, - int nextTestUnionId) { - this(schema, valueMap); - this.nextTestUnionId = nextTestUnionId; - } - - private CoGbkResult( - CoGbkResultSchema schema, - Map> valueMap) { - this.schema = schema; - this.valueMap = valueMap; - } - - private static List convertValueListToUnionList( - int unionTag, List data) { - List unionList = new ArrayList<>(); - for (V value : data) { - unionList.add(new RawUnionValue(unionTag, value)); - } - return unionList; - } - - private Iterable buildEmptyIterable(TupleTag tag) { - return new ArrayList<>(); - } - - private V innerGetOnly( - TupleTag tag, - V defaultValue, - boolean useDefault) { - int index = schema.getIndex(tag); - if (index < 0) { - throw new IllegalArgumentException("TupleTag " + tag - + " is not in the schema"); - } - List unions = valueMap.get(index); - if (unions.isEmpty()) { - if (useDefault) { - return defaultValue; - } else { - throw new IllegalArgumentException("TupleTag " + tag - + " corresponds to an empty result, and no default was provided"); - } - } - if (unions.size() != 1) { - throw new IllegalArgumentException("TupleTag " + tag - + " corresponds to a non-singleton result of size " + unions.size()); - } - return (V) unions.get(0).getValue(); - } - - /** - * Lazily converts and recasts an {@code Iterable} into an - * {@code Iterable}, where V is the type of the raw union value's contents. - */ - private static class UnionValueIterable implements Iterable { - - private final Iterable unions; - - private UnionValueIterable(Iterable unions) { - this.unions = unions; - } - - @Override - public Iterator iterator() { - final Iterator unionsIterator = unions.iterator(); - return new Iterator() { - @Override - public boolean hasNext() { - return unionsIterator.hasNext(); - } - - @Override - public V next() { - return (V) unionsIterator.next().getValue(); - } - - @Override - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - } -} diff --git a/All/Genesis-NP/Genesis#eval_11/pair.info b/All/Genesis-NP/Genesis#eval_11/pair.info deleted file mode 100755 index 65aa402..0000000 --- a/All/Genesis-NP/Genesis#eval_11/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:11 -SATName:Genesis -modifiedFPath:sdk/src/main/java/com/google/cloud/dataflow/sdk/transforms/join/CoGbkResult.java -comSha:c06125d29229309b8e2d2070d7fa140c9a2e14f5 -parentComSha:c06125d29229309b8e2d2070d7fa140c9a2e14f5^1 -githubUrl:https://github.com/GoogleCloudPlatform/DataflowJavaSDK -repoName:GoogleCloudPlatform#DataflowJavaSDK diff --git a/All/Genesis-NP/Genesis#eval_15/comMsg.txt b/All/Genesis-NP/Genesis#eval_15/comMsg.txt deleted file mode 100755 index 88818e5..0000000 --- a/All/Genesis-NP/Genesis#eval_15/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix an NPE in mapsubject with tests that catch the error, plus a few extra tests. diff --git a/All/Genesis-NP/Genesis#eval_15/diff.diff b/All/Genesis-NP/Genesis#eval_15/diff.diff deleted file mode 100755 index df16b37..0000000 --- a/All/Genesis-NP/Genesis#eval_15/diff.diff +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/core/src/main/java/org/truth0/subjects/MapSubject.java b/core/src/main/java/org/truth0/subjects/MapSubject.java -index 3c2027f..c4548d7 100644 ---- a/core/src/main/java/org/truth0/subjects/MapSubject.java -+++ b/core/src/main/java/org/truth0/subjects/MapSubject.java -@@ -18,0 +19 @@ package org.truth0.subjects; -+import java.util.Arrays; -@@ -24 +24,0 @@ import com.google.common.annotations.GwtCompatible; --import com.google.common.collect.ImmutableList; -@@ -64,4 +64,4 @@ public class MapSubject, K, V, M extends Map, K, V, M extends Map> extends Subject { - - public MapSubject(FailureStrategy failureStrategy, M map) { - super(failureStrategy, map); - } - - /** - * Attests that the subject holds no objects, or fails. - */ - public void isEmpty() { - if (!getSubject().isEmpty()) { - fail("is empty"); - } - } - - /** - * Attests that the subject holds one or more objects, or fails - */ - public void isNotEmpty() { - if (getSubject().isEmpty()) { - fail("is not empty"); - } - } - - /** - * Attests that the subject contains the provided key or fails. - */ - public WithValue hasKey(final K key) { - if (!getSubject().containsKey(key)) { - fail("has key", key); - } - return new WithValue() { - @Override public void withValue(V expected) { - V actual = getSubject().get(key); - if ((actual == null && expected != null) || - !(actual == expected || actual.equals(expected))) { - fail("has key/value pair", Arrays.asList(key, expected), - "actually has key/value pair", Arrays.asList(key, actual)); - } - } - }; - } - - public void lacksKey(K key) { - if (getSubject().containsKey(key)) { - fail("lacks key", key); - } - } - - public void hasValue(V key) { - if (!getSubject().containsValue(key)) { - fail("has value", key); - } - } - - public void lacksValue(V key) { - if (getSubject().containsValue(key)) { - fail("lacks value", key); - } - } - - public interface WithValue { - void withValue(V value); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static > MapSubject, K, V, M> create( - FailureStrategy failureStrategy, Map map) { - return new MapSubject(failureStrategy, map); - } - -} diff --git a/All/Genesis-NP/Genesis#eval_15/old/MapSubject.java b/All/Genesis-NP/Genesis#eval_15/old/MapSubject.java deleted file mode 100755 index 3c2027f..0000000 --- a/All/Genesis-NP/Genesis#eval_15/old/MapSubject.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright (c) 2011 David Saff - * Copyright (c) 2011 Christian Gruber - * - * 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.truth0.subjects; - -import java.util.Map; - -import org.truth0.FailureStrategy; - -import com.google.common.annotations.GwtCompatible; -import com.google.common.collect.ImmutableList; - -/** - * @author Christian Gruber (cgruber@israfil.net) - */ -@GwtCompatible -public class MapSubject, K, V, M extends Map> extends Subject { - - public MapSubject(FailureStrategy failureStrategy, M map) { - super(failureStrategy, map); - } - - /** - * Attests that the subject holds no objects, or fails. - */ - public void isEmpty() { - if (!getSubject().isEmpty()) { - fail("is empty"); - } - } - - /** - * Attests that the subject holds one or more objects, or fails - */ - public void isNotEmpty() { - if (getSubject().isEmpty()) { - fail("is not empty"); - } - } - - /** - * Attests that the subject contains the provided key or fails. - */ - public WithValue hasKey(final K key) { - if (!getSubject().containsKey(key)) { - fail("has key", key); - } - return new WithValue() { - @Override public void withValue(V expected) { - V actual = getSubject().get(key); - if ((actual == null && key != null) || - !actual.equals(expected)) { - fail("has key/value pair", ImmutableList.of(key, expected), - "actually has key/value pair", ImmutableList.of(key, actual)); - } - } - }; - } - - public void lacksKey(K key) { - if (getSubject().containsKey(key)) { - fail("lacks key", key); - } - } - - public void hasValue(V key) { - if (!getSubject().containsValue(key)) { - fail("has value", key); - } - } - - public void lacksValue(V key) { - if (getSubject().containsValue(key)) { - fail("lacks value", key); - } - } - - public interface WithValue { - void withValue(V value); - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public static > MapSubject, K, V, M> create( - FailureStrategy failureStrategy, Map map) { - return new MapSubject(failureStrategy, map); - } - -} diff --git a/All/Genesis-NP/Genesis#eval_15/pair.info b/All/Genesis-NP/Genesis#eval_15/pair.info deleted file mode 100755 index b4d00ca..0000000 --- a/All/Genesis-NP/Genesis#eval_15/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:15 -SATName:Genesis -modifiedFPath:core/src/main/java/org/truth0/subjects/MapSubject.java -comSha:99b314e930e8f7f1b783c468c0f2284b52a9dcac -parentComSha:99b314e930e8f7f1b783c468c0f2284b52a9dcac^1 -githubUrl:https://github.com/google/truth -repoName:google#truth diff --git a/All/Genesis-OOB/Genesis#10/comMsg.txt b/All/Genesis-OOB/Genesis#10/comMsg.txt deleted file mode 100755 index f5f6828..0000000 --- a/All/Genesis-OOB/Genesis#10/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed: StringIndexOutOfBoundsException if passing an empty parameter (bomanz) diff --git a/All/Genesis-OOB/Genesis#10/diff.diff b/All/Genesis-OOB/Genesis#10/diff.diff deleted file mode 100755 index 798a9e7..0000000 --- a/All/Genesis-OOB/Genesis#10/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/src/main/java/com/beust/jcommander/JCommander.java b/src/main/java/com/beust/jcommander/JCommander.java -index 3a1b684..5899bb8 100644 ---- a/src/main/java/com/beust/jcommander/JCommander.java -+++ b/src/main/java/com/beust/jcommander/JCommander.java -@@ -386 +386 @@ public class JCommander { -- return prefixes.indexOf(arg.charAt(0)) >= 0; -+ return arg.length() > 0 && prefixes.indexOf(arg.charAt(0)) >= 0; diff --git a/All/Genesis-OOB/Genesis#10/new/JCommander.java b/All/Genesis-OOB/Genesis#10/new/JCommander.java deleted file mode 100755 index 5899bb8..0000000 --- a/All/Genesis-OOB/Genesis#10/new/JCommander.java +++ /dev/null @@ -1,1392 +0,0 @@ -/** - * Copyright (C) 2010 the original author or authors. - * See the notice.md file distributed with this work for additional - * information regarding copyright ownership. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.beust.jcommander; - -import com.beust.jcommander.converters.IParameterSplitter; -import com.beust.jcommander.converters.NoConverter; -import com.beust.jcommander.converters.StringConverter; -import com.beust.jcommander.internal.Console; -import com.beust.jcommander.internal.DefaultConsole; -import com.beust.jcommander.internal.DefaultConverterFactory; -import com.beust.jcommander.internal.JDK6Console; -import com.beust.jcommander.internal.Lists; -import com.beust.jcommander.internal.Maps; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - - - -/** - * The main class for JCommander. It's responsible for parsing the object that contains - * all the annotated fields, parse the command line and assign the fields with the correct - * values and a few other helper methods, such as usage(). - * - * The object(s) you pass in the constructor are expected to have one or more - * \@Parameter annotations on them. You can pass either a single object, an array of objects - * or an instance of Iterable. In the case of an array or Iterable, JCommander will collect - * the \@Parameter annotations from all the objects passed in parameter. - * - * @author cbeust - */ -public class JCommander { - public static final String DEBUG_PROPERTY = "jcommander.debug"; - - /** - * A map to look up parameter description per option name. - */ - private Map m_descriptions; - - /** - * The objects that contain fields annotated with @Parameter. - */ - private List m_objects = Lists.newArrayList(); - - /** - * This field will contain whatever command line parameter is not an option. - * It is expected to be a List. - */ - private Field m_mainParameterField = null; - - /** - * The object on which we found the main parameter field. - */ - private Object m_mainParameterObject; - - /** - * The annotation found on the main parameter field. - */ - private Parameter m_mainParameterAnnotation; - - private ParameterDescription m_mainParameterDescription; - - /** - * A set of all the fields that are required. During the reflection phase, - * this field receives all the fields that are annotated with required=true - * and during the parsing phase, all the fields that are assigned a value - * are removed from it. At the end of the parsing phase, if it's not empty, - * then some required fields did not receive a value and an exception is - * thrown. - */ - private Map m_requiredFields = Maps.newHashMap(); - - /** - * A map of all the annotated fields. - */ - private Map m_fields = Maps.newHashMap(); - - private ResourceBundle m_bundle; - - /** - * A default provider returns default values for the parameters. - */ - private IDefaultProvider m_defaultProvider; - - /** - * List of commands and their instance. - */ - private Map m_commands = Maps.newLinkedHashMap(); - /** - * Alias database for reverse lookup - */ - private Map aliasMap = Maps.newLinkedHashMap(); - - /** - * The name of the command after the parsing has run. - */ - private String m_parsedCommand; - - /** - * The name of command or alias as it was passed to the - * command line - */ - private String m_parsedAlias; - - private ProgramName m_programName; - - private Comparator m_parameterDescriptionComparator - = new Comparator() { - public int compare(ParameterDescription p0, ParameterDescription p1) { - return p0.getLongestName().compareTo(p1.getLongestName()); - } - }; - - private int m_columnSize = 79; - - private static Console m_console; - - /** - * The factories used to look up string converters. - */ - private static LinkedList CONVERTER_FACTORIES = Lists.newLinkedList(); - - static { - CONVERTER_FACTORIES.addFirst(new DefaultConverterFactory()); - }; - - /** - * Creates a new un-configured JCommander object. - */ - public JCommander() { - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - */ - public JCommander(Object object) { - addObject(object); - createDescriptions(); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param bundle The bundle to use for the descriptions. Can be null. - */ - public JCommander(Object object, ResourceBundle bundle) { - addObject(object); - setDescriptionsBundle(bundle); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param bundle The bundle to use for the descriptions. Can be null. - * @param args The arguments to parse (optional). - */ - public JCommander(Object object, ResourceBundle bundle, String... args) { - addObject(object); - setDescriptionsBundle(bundle); - parse(args); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param args The arguments to parse (optional). - */ - public JCommander(Object object, String... args) { - addObject(object); - parse(args); - } - - public static Console getConsole() { - if (m_console == null) { - try { - Method consoleMethod = System.class.getDeclaredMethod("console", new Class[0]); - Object console = consoleMethod.invoke(null, new Object[0]); - m_console = new JDK6Console(console); - } catch (Throwable t) { - m_console = new DefaultConsole(); - } - } - return m_console; - } - - /** - * Adds the provided arg object to the set of objects that this commander - * will parse arguments into. - * - * @param object The arg object expected to contain {@link Parameter} - * annotations. If object is an array or is {@link Iterable}, - * the child objects will be added instead. - */ - // declared final since this is invoked from constructors - public final void addObject(Object object) { - if (object instanceof Iterable) { - // Iterable - for (Object o : (Iterable) object) { - m_objects.add(o); - } - } else if (object.getClass().isArray()) { - // Array - for (Object o : (Object[]) object) { - m_objects.add(o); - } - } else { - // Single object - m_objects.add(object); - } - } - - /** - * Sets the {@link ResourceBundle} to use for looking up descriptions. - * Set this to null to use description text directly. - */ - // declared final since this is invoked from constructors - public final void setDescriptionsBundle(ResourceBundle bundle) { - m_bundle = bundle; - } - - /** - * Parse and validate the command line parameters. - */ - public void parse(String... args) { - parse(true /* validate */, args); - } - - /** - * Parse the command line parameters without validating them. - */ - public void parseWithoutValidation(String... args) { - parse(false /* no validation */, args); - } - - private void parse(boolean validate, String... args) { - StringBuilder sb = new StringBuilder("Parsing \""); - sb.append(join(args).append("\"\n with:").append(join(m_objects.toArray()))); - p(sb.toString()); - - if (m_descriptions == null) createDescriptions(); - initializeDefaultValues(); - parseValues(expandArgs(args)); - if (validate) validateOptions(); - } - - private StringBuilder join(Object[] args) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < args.length; i++) { - if (i > 0) result.append(" "); - result.append(args[i]); - } - return result; - } - - private void initializeDefaultValues() { - if (m_defaultProvider != null) { - for (ParameterDescription pd : m_descriptions.values()) { - initializeDefaultValue(pd); - } - - for (Map.Entry entry : m_commands.entrySet()) { - entry.getValue().initializeDefaultValues(); - } - } - } - - /** - * Make sure that all the required parameters have received a value. - */ - private void validateOptions() { - if (! m_requiredFields.isEmpty()) { - StringBuilder missingFields = new StringBuilder(); - for (ParameterDescription pd : m_requiredFields.values()) { - missingFields.append(pd.getNames()).append(" "); - } - throw new ParameterException("The following options are required: " + missingFields); - } - - if (m_mainParameterDescription != null) { - if (m_mainParameterDescription.getParameter().required() && - !m_mainParameterDescription.isAssigned()) { - throw new ParameterException("Main parameters are required (\"" - + m_mainParameterDescription.getDescription() + "\")"); - } - } - } - - /** - * Expand the command line parameters to take @ parameters into account. - * When @ is encountered, the content of the file that follows is inserted - * in the command line. - * - * @param originalArgv the original command line parameters - * @return the new and enriched command line parameters - */ - private String[] expandArgs(String[] originalArgv) { - List vResult1 = Lists.newArrayList(); - - // - // Expand @ - // - for (String arg : originalArgv) { - - if (arg.startsWith("@")) { - String fileName = arg.substring(1); - vResult1.addAll(readFile(fileName)); - } - else { - List expanded = expandDynamicArg(arg); - vResult1.addAll(expanded); - } - } - - // Expand separators - // - List vResult2 = Lists.newArrayList(); - for (int i = 0; i < vResult1.size(); i++) { - String arg = vResult1.get(i); - String[] v1 = vResult1.toArray(new String[0]); - if (isOption(v1, arg)) { - String sep = getSeparatorFor(v1, arg); - if (! " ".equals(sep)) { - String[] sp = arg.split("[" + sep + "]", 2); - for (String ssp : sp) { - vResult2.add(ssp); - } - } else { - vResult2.add(arg); - } - } else { - vResult2.add(arg); - } - } - - return vResult2.toArray(new String[vResult2.size()]); - } - - private List expandDynamicArg(String arg) { - for (ParameterDescription pd : m_descriptions.values()) { - if (pd.isDynamicParameter()) { - for (String name : pd.getParameter().names()) { - if (arg.startsWith(name) && !arg.equals(name)) { - return Arrays.asList(name, arg.substring(name.length())); - } - } - } - } - - return Arrays.asList(arg); - } - - private boolean isOption(String[] args, String arg) { - String prefixes = getOptionPrefixes(args, arg); - return arg.length() > 0 && prefixes.indexOf(arg.charAt(0)) >= 0; - } - - private ParameterDescription getPrefixDescriptionFor(String arg) { - for (Map.Entry es : m_descriptions.entrySet()) { - if (arg.startsWith(es.getKey())) return es.getValue(); - } - - return null; - } - - /** - * If arg is an option, we can look it up directly, but if it's a value, - * we need to find the description for the option that precedes it. - */ - private ParameterDescription getDescriptionFor(String[] args, String arg) { - ParameterDescription result = getPrefixDescriptionFor(arg); - if (result != null) return result; - - for (String a : args) { - ParameterDescription pd = getPrefixDescriptionFor(arg); - if (pd != null) result = pd; - if (a.equals(arg)) return result; - } - - throw new ParameterException("Unknown parameter: " + arg); - } - - private String getSeparatorFor(String[] args, String arg) { - ParameterDescription pd = getDescriptionFor(args, arg); - - // Could be null if only main parameters were passed - if (pd != null) { - Parameters p = pd.getObject().getClass().getAnnotation(Parameters.class); - if (p != null) return p.separators(); - } - - return " "; - } - - private String getOptionPrefixes(String[] args, String arg) { - ParameterDescription pd = getDescriptionFor(args, arg); - - // Could be null if only main parameters were passed - if (pd != null) { - Parameters p = pd.getObject().getClass() - .getAnnotation(Parameters.class); - if (p != null) return p.optionPrefixes(); - } - - return Parameters.DEFAULT_OPTION_PREFIXES; - } - - /** - * Reads the file specified by filename and returns the file content as a string. - * End of lines are replaced by a space. - * - * @param fileName the command line filename - * @return the file content as a string. - */ - private static List readFile(String fileName) { - List result = Lists.newArrayList(); - - try { - BufferedReader bufRead = new BufferedReader(new FileReader(fileName)); - - String line; - - // Read through file one line at time. Print line # and line - while ((line = bufRead.readLine()) != null) { - // Allow empty lines in these at files - if (line.length() > 0) result.add(line); - } - - bufRead.close(); - } - catch (IOException e) { - throw new ParameterException("Could not read file " + fileName + ": " + e); - } - - return result; - } - - /** - * Remove spaces at both ends and handle double quotes. - */ - private static String trim(String string) { - String result = string.trim(); - if (result.startsWith("\"")) { - if (result.endsWith("\"")) { - return result.substring(1, result.length() - 1); - } - return result.substring(1); - } - return result; - } - - /** - * Create the ParameterDescriptions for all the \@Parameter found. - */ - private void createDescriptions() { - m_descriptions = Maps.newHashMap(); - - for (Object object : m_objects) { - addDescription(object); - } - } - - private void addDescription(Object object) { - Class cls = object.getClass(); - - while (!Object.class.equals(cls)) { - for (Field f : cls.getDeclaredFields()) { - p("Field:" + cls.getSimpleName() + "." + f.getName()); - f.setAccessible(true); - Annotation annotation = f.getAnnotation(Parameter.class); - Annotation delegateAnnotation = f.getAnnotation(ParametersDelegate.class); - Annotation dynamicParameter = f.getAnnotation(DynamicParameter.class); - if (annotation != null) { - // - // @Parameter - // - Parameter p = (Parameter) annotation; - if (p.names().length == 0) { - p("Found main parameter:" + f); - if (m_mainParameterField != null) { - throw new ParameterException("Only one @Parameter with no names attribute is" - + " allowed, found:" + m_mainParameterField + " and " + f); - } - m_mainParameterField = f; - m_mainParameterObject = object; - m_mainParameterAnnotation = p; - m_mainParameterDescription = new ParameterDescription(object, p, f, m_bundle, this); - } else { - for (String name : p.names()) { - if (m_descriptions.containsKey(name)) { - throw new ParameterException("Found the option " + name + " multiple times"); - } - p("Adding description for " + name); - ParameterDescription pd = new ParameterDescription(object, p, f, m_bundle, this); - m_fields.put(f, pd); - m_descriptions.put(name, pd); - - if (p.required()) m_requiredFields.put(f, pd); - } - } - } else if (delegateAnnotation != null) { - // - // @ParametersDelegate - // - try { - Object delegateObject = f.get(object); - if (delegateObject == null){ - throw new ParameterException("Delegate field '" + f.getName() + "' cannot be null."); - } - addDescription(delegateObject); - } catch (IllegalAccessException e) { - } - } else if (dynamicParameter != null) { - // - // @DynamicParameter - // - DynamicParameter dp = (DynamicParameter) dynamicParameter; - for (String name : dp.names()) { - if (m_descriptions.containsKey(name)) { - throw new ParameterException("Found the option " + name + " multiple times"); - } - p("Adding description for " + name); - ParameterDescription pd = new ParameterDescription(object, dp, f, m_bundle, this); - m_fields.put(f, pd); - m_descriptions.put(name, pd); - - if (dp.required()) m_requiredFields.put(f, pd); - } - } - } - // Traverse the super class until we find Object.class - cls = cls.getSuperclass(); - } - } - - private void initializeDefaultValue(ParameterDescription pd) { - for (String optionName : pd.getParameter().names()) { - String def = m_defaultProvider.getDefaultValueFor(optionName); - if (def != null) { - p("Initializing " + optionName + " with default value:" + def); - pd.addValue(def, true /* default */); - return; - } - } - } - - /** - * Main method that parses the values and initializes the fields accordingly. - */ - private void parseValues(String[] args) { - // This boolean becomes true if we encounter a command, which indicates we need - // to stop parsing (the parsing of the command will be done in a sub JCommander - // object) - boolean commandParsed = false; - int i = 0; - while (i < args.length && ! commandParsed) { - String arg = args[i]; - String a = trim(arg); - p("Parsing arg:" + a); - - JCommander jc = findCommandByAlias(arg); - if (isOption(args, a) && jc == null) { - // - // Option - // - ParameterDescription pd = m_descriptions.get(a); - - if (pd != null) { - if (pd.getParameter().password()) { - // - // Password option, use the Console to retrieve the password - // - char[] password = readPassword(pd.getDescription()); - pd.addValue(new String(password)); - m_requiredFields.remove(pd.getField()); - } else { - if (pd.getParameter().variableArity()) { - // - // Variable arity? - // - i = processVariableArity(args, i, pd); - } else { - // - // Regular option - // - Class fieldType = pd.getField().getType(); - - // Boolean, set to true as soon as we see it, unless it specified - // an arity of 1, in which case we need to read the next value - if ((fieldType == boolean.class || fieldType == Boolean.class) - && pd.getParameter().arity() == -1) { - pd.addValue("true"); - m_requiredFields.remove(pd.getField()); - } else { - i = processFixedArity(args, i, pd, fieldType); - } - } - } - } else { - throw new ParameterException("Unknown option: " + arg); - } - } - else { - // - // Main parameter - // - if (! isStringEmpty(arg)) { - if (m_commands.isEmpty()) { - // - // Regular (non-command) parsing - // - List mp = getMainParameter(arg); - String value = arg; - Object convertedValue = value; - - if (m_mainParameterField.getGenericType() instanceof ParameterizedType) { - ParameterizedType p = (ParameterizedType) m_mainParameterField.getGenericType(); - Type cls = p.getActualTypeArguments()[0]; - if (cls instanceof Class) { - convertedValue = convertValue(m_mainParameterField, (Class) cls, value); - } - } - - ParameterDescription.validateParameter(m_mainParameterAnnotation.validateWith(), - "Default", value); - - m_mainParameterDescription.setAssigned(true); - mp.add(convertedValue); - } - else { - // - // Command parsing - // - if (jc == null) throw new MissingCommandException("Expected a command, got " + arg); - m_parsedCommand = jc.m_programName.m_name; - m_parsedAlias = arg; //preserve the original form - - // Found a valid command, ask it to parse the remainder of the arguments. - // Setting the boolean commandParsed to true will force the current - // loop to end. - jc.parse(subArray(args, i + 1)); - commandParsed = true; - } - } - } - i++; - } - - // Mark the parameter descriptions held in m_fields as assigned - for (ParameterDescription parameterDescription : m_descriptions.values()) { - if (parameterDescription.isAssigned()) { - m_fields.get(parameterDescription.getField()).setAssigned(true); - } - } - - } - - /** - * @return the generic type of the collection for this field, or null if not applicable. - */ - private Type findFieldGenericType(Field field) { - if (field.getGenericType() instanceof ParameterizedType) { - ParameterizedType p = (ParameterizedType) field.getGenericType(); - Type cls = p.getActualTypeArguments()[0]; - if (cls instanceof Class) { - return cls; - } - } - - return null; - } - - /** - * @return the number of options that were processed. - */ - private int processVariableArity(String[] args, int index, ParameterDescription pd) { - Object arg = pd.getObject(); - if (! (arg instanceof IVariableArity)) { - throw new ParameterException("Arg class " + arg.getClass() - + " should implement IVariableArity"); - } - - IVariableArity va = (IVariableArity) arg; - List currentArgs = Lists.newArrayList(); - for (int j = index + 1; j < args.length; j++) { - currentArgs.add(args[j]); - } - int result = va.processVariableArity(pd.getParameter().names()[0], - currentArgs.toArray(new String[0])); - return result; - } - - private int processFixedArity(String[] args, int index, ParameterDescription pd, - Class fieldType) { - // Regular parameter, use the arity to tell use how many values - // we need to consume - String arg = args[index]; - int arity = pd.getParameter().arity(); - int n = (arity != -1 ? arity : 1); - - // Special case for boolean parameters of arity 0 - if (n == 0 && - (Boolean.class.isAssignableFrom(fieldType) - || boolean.class.isAssignableFrom(fieldType))) { - pd.addValue("true"); - m_requiredFields.remove(pd.getField()); - } else if (index < args.length - 1) { - int offset = "--".equals(args[index + 1]) ? 1 : 0; - - if (index + n < args.length) { - for (int j = 1; j <= n; j++) { - pd.addValue(trim(args[index + j + offset])); - m_requiredFields.remove(pd.getField()); - } - index += n + offset; - } else { - throw new ParameterException("Expected " + n + " values after " + arg); - } - } else { - throw new ParameterException("Expected a value after parameter " + arg); - } - - return index; - } - - /** - * Invoke Console.readPassword through reflection to avoid depending - * on Java 6. - */ - private char[] readPassword(String description) { - getConsole().print(description + ": "); - return getConsole().readPassword(); - } - - private String[] subArray(String[] args, int index) { - int l = args.length - index; - String[] result = new String[l]; - System.arraycopy(args, index, result, 0, l); - - return result; - } - - private static boolean isStringEmpty(String s) { - return s == null || "".equals(s); - } - - /** - * @return the field that's meant to receive all the parameters that are not options. - * - * @param arg the arg that we're about to add (only passed here to output a meaningful - * error message). - */ - private List getMainParameter(String arg) { - if (m_mainParameterField == null) { - throw new ParameterException( - "Was passed main parameter '" + arg + "' but no main parameter was defined"); - } - - try { - List result = (List) m_mainParameterField.get(m_mainParameterObject); - if (result == null) { - result = Lists.newArrayList(); - if (! List.class.isAssignableFrom(m_mainParameterField.getType())) { - throw new ParameterException("Main parameter field " + m_mainParameterField - + " needs to be of type List, not " + m_mainParameterField.getType()); - } - m_mainParameterField.set(m_mainParameterObject, result); - } - return result; - } - catch(IllegalAccessException ex) { - throw new ParameterException("Couldn't access main parameter: " + ex.getMessage()); - } - } - - public String getMainParameterDescription() { - if (m_descriptions == null) createDescriptions(); - return m_mainParameterAnnotation != null ? m_mainParameterAnnotation.description() - : null; - } - - private int longestName(Collection objects) { - int result = 0; - for (Object o : objects) { - int l = o.toString().length(); - if (l > result) result = l; - } - - return result; - } - - /** - * Set the program name (used only in the usage). - */ - public void setProgramName(String name) { - setProgramName(name, new String[0]); - } - - /** - * Set the program name - * - * @param name program name - * @param aliases aliases to the program name - */ - public void setProgramName(String name, String... aliases) { - m_programName = new ProgramName(name, Arrays.asList(aliases)); - } - - /** - * Display the usage for this command. - */ - public void usage(String commandName) { - StringBuilder sb = new StringBuilder(); - usage(commandName, sb); - getConsole().println(sb.toString()); - } - - /** - * Store the help for the command in the passed string builder. - */ - public void usage(String commandName, StringBuilder out) { - usage(commandName, out, ""); - } - - /** - * Store the help for the command in the passed string builder, indenting - * every line with "indent". - */ - public void usage(String commandName, StringBuilder out, String indent) { - String description = getCommandDescription(commandName); - JCommander jc = findCommandByAlias(commandName); - if (description != null) { - out.append(indent).append(description); - out.append("\n"); - } - jc.usage(out, indent); - } - - /** - * @return the description of the command. - */ - public String getCommandDescription(String commandName) { - JCommander jc = findCommandByAlias(commandName); - if (jc == null) { - throw new ParameterException("Asking description for unknown command: " + commandName); - } - - Parameters p = jc.getObjects().get(0).getClass().getAnnotation(Parameters.class); - String result = jc.getMainParameterDescription(); - if (p != null) result = getI18nString(p.commandDescriptionKey(), p.commandDescription()); - - return result; - } - - /** - * @return The internationalized version of the string if available, otherwise - * return def. - */ - private String getI18nString(String key, String def) { - String s = m_bundle != null ? m_bundle.getString(key) : null; - return s != null ? s : def; - } - - /** - * Display the help on System.out. - */ - public void usage() { - StringBuilder sb = new StringBuilder(); - usage(sb); - getConsole().println(sb.toString()); - } - - /** - * Store the help in the passed string builder. - */ - public void usage(StringBuilder out) { - usage(out, ""); - } - - public void usage(StringBuilder out, String indent) { - if (m_descriptions == null) createDescriptions(); - boolean hasCommands = !m_commands.isEmpty(); - - // - // First line of the usage - // - String programName = m_programName != null ? m_programName.getDisplayName() : "
"; - out.append(indent).append("Usage: " + programName + " [options]"); - if (hasCommands) out.append(indent).append(" [command] [command options]"); -// out.append("\n"); - if (m_mainParameterDescription != null) { - out.append(" " + m_mainParameterDescription.getDescription()); - } - - // - // Align the descriptions at the "longestName" column - // - int longestName = 0; - List sorted = Lists.newArrayList(); - for (ParameterDescription pd : m_fields.values()) { - if (! pd.getParameter().hidden()) { - sorted.add(pd); - // + to have an extra space between the name and the description - int length = pd.getNames().length() + 2; - if (length > longestName) { - longestName = length; - } - } - } - - // - // Sort the options - // - Collections.sort(sorted, getParameterDescriptionComparator()); - - // - // Display all the names and descriptions - // - if (sorted.size() > 0) out.append(indent).append("\n").append(indent).append(" Options:\n"); - for (ParameterDescription pd : sorted) { - int l = pd.getNames().length(); - int spaceCount = longestName - l; - int start = out.length(); - WrappedParameter parameter = pd.getParameter(); - out.append(indent).append(" " - + (parameter.required() ? "* " : " ") - + pd.getNames() + s(spaceCount)); - int indentCount = out.length() - start; - wrapDescription(out, indentCount, pd.getDescription()); - Object def = pd.getDefault(); - if (pd.isDynamicParameter()) { - out.append("\n" + spaces(indentCount + 1)) - .append("Syntax: " + parameter.names()[0] - + "key" + parameter.getAssignment() - + "value"); - } - if (def != null && ! "".equals(def)) { - out.append("\n" + spaces(indentCount + 1)) - .append("Default: " + def); - } - out.append("\n"); - } - - // - // If commands were specified, show them as well - // - if (hasCommands) { - out.append(" Commands:\n"); - // The magic value 3 is the number of spaces between the name of the option - // and its description - for (Map.Entry commands : m_commands.entrySet()) { - ProgramName progName = commands.getKey(); - String dispName = progName.getDisplayName(); - out.append(indent).append(" " + dispName); // + s(spaceCount) + getCommandDescription(progName.name) + "\n"); - - // Options for this command - usage(progName.getName(), out, " "); - out.append("\n"); - } - } - } - - private Comparator getParameterDescriptionComparator() { - return m_parameterDescriptionComparator; - } - - public void setParameterDescriptionComparator(Comparator c) { - m_parameterDescriptionComparator = c; - } - - public void setColumnSize(int columnSize) { - m_columnSize = columnSize; - } - - public int getColumnSize() { - return m_columnSize; - } - - private void wrapDescription(StringBuilder out, int indent, String description) { - int max = getColumnSize(); - String[] words = description.split(" "); - int current = indent; - int i = 0; - while (i < words.length) { - String word = words[i]; - if (word.length() > max || current + word.length() <= max) { - out.append(" ").append(word); - current += word.length() + 1; - } else { - out.append("\n").append(spaces(indent + 1)).append(word); - current = indent; - } - i++; - } - } - - private String spaces(int indent) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < indent; i++) sb.append(" "); - return sb.toString(); - } - - /** - * @return a Collection of all the \@Parameter annotations found on the - * target class. This can be used to display the usage() in a different - * format (e.g. HTML). - */ - public List getParameters() { - return new ArrayList(m_fields.values()); - } - - /** - * @return the main parameter description or null if none is defined. - */ - public ParameterDescription getMainParameter() { - return m_mainParameterDescription; - } - - private void p(String string) { - if (System.getProperty(JCommander.DEBUG_PROPERTY) != null) { - getConsole().println("[JCommander] " + string); - } - } - - /** - * Define the default provider for this instance. - */ - public void setDefaultProvider(IDefaultProvider defaultProvider) { - m_defaultProvider = defaultProvider; - - for (Map.Entry entry : m_commands.entrySet()) { - entry.getValue().setDefaultProvider(defaultProvider); - } - } - - public void addConverterFactory(IStringConverterFactory converterFactory) { - CONVERTER_FACTORIES.addFirst(converterFactory); - } - - public Class> findConverter(Class cls) { - for (IStringConverterFactory f : CONVERTER_FACTORIES) { - Class> result = f.getConverter(cls); - if (result != null) return result; - } - - return null; - } - - public Object convertValue(ParameterDescription pd, String value) { - return convertValue(pd.getField(), pd.getField().getType(), value); - } - - /** - * @param field The field - * @param type The type of the actual parameter - * @param value The value to convert - */ - public Object convertValue(Field field, Class type, String value) { - Parameter annotation = field.getAnnotation(Parameter.class); - - // Do nothing if it's a @DynamicParameter - if (annotation == null) return value; - - Class> converterClass = annotation.converter(); - boolean listConverterWasSpecified = annotation.listConverter() != NoConverter.class; - - // - // Try to find a converter on the annotation - // - if (converterClass == null || converterClass == NoConverter.class) { - // If no converter specified and type is enum, used enum values to convert - if (type.isEnum()){ - converterClass = type; - } else { - converterClass = findConverter(type); - } - } - - if (converterClass == null) { - Type elementType = findFieldGenericType(field); - converterClass = elementType != null - ? findConverter((Class>) elementType) - : StringConverter.class; - } - - // -// // -// // Try to find a converter in the factory -// // -// IStringConverter converter = null; -// if (converterClass == null && m_converterFactories != null) { -// // Mmmh, javac requires a cast here -// converter = (IStringConverter) m_converterFactories.getConverter(type); -// } - -// if (converterClass == null) { -// throw new ParameterException("Don't know how to convert " + value -// + " to type " + type + " (field: " + field.getName() + ")"); -// } - - IStringConverter converter; - Object result = null; - try { - String[] names = annotation.names(); - String optionName = names.length > 0 ? names[0] : "[Main class]"; - if (converterClass.isEnum()) { - try { - result = Enum.valueOf((Class) converterClass, value.toUpperCase()); - } catch (Exception e) { - throw new ParameterException("Invalid value for " + optionName + " parameter. Allowed values:" + - EnumSet.allOf((Class) converterClass)); - } - } else { - converter = instantiateConverter(optionName, converterClass); - if (type.isAssignableFrom(List.class) - && field.getGenericType() instanceof ParameterizedType) { - - // The field is a List - if (listConverterWasSpecified) { - // If a list converter was specified, pass the value to it - // for direct conversion - IStringConverter listConverter = - instantiateConverter(optionName, annotation.listConverter()); - result = listConverter.convert(value); - } else { - // No list converter: use the single value converter and pass each - // parsed value to it individually - result = convertToList(value, converter, annotation.splitter()); - } - } else { - result = converter.convert(value); - } - } - } catch (InstantiationException e) { - throw new ParameterException(e); - } catch (IllegalAccessException e) { - throw new ParameterException(e); - } catch (InvocationTargetException e) { - throw new ParameterException(e); - } - - return result; - } - - /** - * Use the splitter to split the value into multiple values and then convert - * each of them individually. - */ - private Object convertToList(String value, IStringConverter converter, - Class splitterClass) - throws InstantiationException, IllegalAccessException { - IParameterSplitter splitter = splitterClass.newInstance(); - List result = Lists.newArrayList(); - for (String param : splitter.split(value)) { - result.add(converter.convert(param)); - } - return result; - } - - private IStringConverter instantiateConverter(String optionName, - Class> converterClass) - throws IllegalArgumentException, InstantiationException, IllegalAccessException, - InvocationTargetException { - Constructor> ctor = null; - Constructor> stringCtor = null; - Constructor>[] ctors - = (Constructor>[]) converterClass.getDeclaredConstructors(); - for (Constructor> c : ctors) { - Class[] types = c.getParameterTypes(); - if (types.length == 1 && types[0].equals(String.class)) { - stringCtor = c; - } else if (types.length == 0) { - ctor = c; - } - } - - IStringConverter result = stringCtor != null - ? stringCtor.newInstance(optionName) - : ctor.newInstance(); - - return result; - } - - /** - * Add a command object. - */ - public void addCommand(String name, Object object) { - addCommand(name, object, new String[0]); - } - - public void addCommand(Object object) { - Parameters p = object.getClass().getAnnotation(Parameters.class); - if (p != null && p.commandNames().length > 0) { - for (String commandName : p.commandNames()) { - addCommand(commandName, object); - } - } else { - throw new ParameterException("Trying to add command " + object.getClass().getName() - + " without specifying its names in @Parameters"); - } - } - - /** - * Add a command object and its aliases. - */ - public void addCommand(String name, Object object, String... aliases) { - JCommander jc = new JCommander(object); - jc.setProgramName(name, aliases); - jc.setDefaultProvider(m_defaultProvider); - ProgramName progName = jc.m_programName; - m_commands.put(progName, jc); - - /* - * Register aliases - */ - //register command name as an alias of itself for reverse lookup - //Note: Name clash check is intentionally omitted to resemble the - // original behaviour of clashing commands. - // Aliases are, however, are strictly checked for name clashes. - aliasMap.put(name, progName); - for (String alias : aliases) { - //omit pointless aliases to avoid name clash exception - if (!alias.equals(name)) { - ProgramName mappedName = aliasMap.get(alias); - if (mappedName != null && !mappedName.equals(progName)) { - throw new ParameterException("Cannot set alias " + alias - + " for " + name - + " command because it has already been defined for " - + mappedName.m_name + " command"); - } - aliasMap.put(alias, progName); - } - } - } - - public Map getCommands() { - Map res = Maps.newLinkedHashMap(); - for (Map.Entry entry : m_commands.entrySet()) { - res.put(entry.getKey().m_name, entry.getValue()); - } - return res; - } - - public String getParsedCommand() { - return m_parsedCommand; - } - - /** - * The name of the command or the alias in the form it was - * passed to the command line. null if no - * command or alias was specified. - * - * @return Name of command or alias passed to command line. If none passed: null. - */ - public String getParsedAlias() { - return m_parsedAlias; - } - - /** - * @return n spaces - */ - private String s(int count) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < count; i++) { - result.append(" "); - } - - return result.toString(); - } - - /** - * @return the objects that JCommander will fill with the result of - * parsing the command line. - */ - public List getObjects() { - return m_objects; - } - - /* - * Reverse lookup JCommand object by command's name or its alias - */ - private JCommander findCommandByAlias(String commandOrAlias) { - ProgramName progName = aliasMap.get(commandOrAlias); - if (progName == null) { - return null; - } - JCommander jc = m_commands.get(progName); - if (jc == null) { - throw new IllegalStateException( - "There appears to be inconsistency in the internal command database. " + - " This is likely a bug. Please report."); - } - return jc; - } - - private static final class ProgramName { - private final String m_name; - private final List m_aliases; - - ProgramName(String name, List aliases) { - m_name = name; - m_aliases = aliases; - } - - public String getName() { - return m_name; - } - - private String getDisplayName() { - StringBuilder sb = new StringBuilder(); - sb.append(m_name); - if (!m_aliases.isEmpty()) { - sb.append("("); - Iterator aliasesIt = m_aliases.iterator(); - while (aliasesIt.hasNext()) { - sb.append(aliasesIt.next()); - if (aliasesIt.hasNext()) { - sb.append(","); - } - } - sb.append(")"); - } - return sb.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((m_name == null) ? 0 : m_name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ProgramName other = (ProgramName) obj; - if (m_name == null) { - if (other.m_name != null) - return false; - } else if (!m_name.equals(other.m_name)) - return false; - return true; - } - - /* - * Important: ProgramName#toString() is used by longestName(Collection) function - * to format usage output. - */ - @Override - public String toString() { - return getDisplayName(); - - } - } -} diff --git a/All/Genesis-OOB/Genesis#10/old/JCommander.java b/All/Genesis-OOB/Genesis#10/old/JCommander.java deleted file mode 100755 index 3a1b684..0000000 --- a/All/Genesis-OOB/Genesis#10/old/JCommander.java +++ /dev/null @@ -1,1392 +0,0 @@ -/** - * Copyright (C) 2010 the original author or authors. - * See the notice.md file distributed with this work for additional - * information regarding copyright ownership. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.beust.jcommander; - -import com.beust.jcommander.converters.IParameterSplitter; -import com.beust.jcommander.converters.NoConverter; -import com.beust.jcommander.converters.StringConverter; -import com.beust.jcommander.internal.Console; -import com.beust.jcommander.internal.DefaultConsole; -import com.beust.jcommander.internal.DefaultConverterFactory; -import com.beust.jcommander.internal.JDK6Console; -import com.beust.jcommander.internal.Lists; -import com.beust.jcommander.internal.Maps; - -import java.io.BufferedReader; -import java.io.FileReader; -import java.io.IOException; -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.EnumSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.ResourceBundle; - - - -/** - * The main class for JCommander. It's responsible for parsing the object that contains - * all the annotated fields, parse the command line and assign the fields with the correct - * values and a few other helper methods, such as usage(). - * - * The object(s) you pass in the constructor are expected to have one or more - * \@Parameter annotations on them. You can pass either a single object, an array of objects - * or an instance of Iterable. In the case of an array or Iterable, JCommander will collect - * the \@Parameter annotations from all the objects passed in parameter. - * - * @author cbeust - */ -public class JCommander { - public static final String DEBUG_PROPERTY = "jcommander.debug"; - - /** - * A map to look up parameter description per option name. - */ - private Map m_descriptions; - - /** - * The objects that contain fields annotated with @Parameter. - */ - private List m_objects = Lists.newArrayList(); - - /** - * This field will contain whatever command line parameter is not an option. - * It is expected to be a List. - */ - private Field m_mainParameterField = null; - - /** - * The object on which we found the main parameter field. - */ - private Object m_mainParameterObject; - - /** - * The annotation found on the main parameter field. - */ - private Parameter m_mainParameterAnnotation; - - private ParameterDescription m_mainParameterDescription; - - /** - * A set of all the fields that are required. During the reflection phase, - * this field receives all the fields that are annotated with required=true - * and during the parsing phase, all the fields that are assigned a value - * are removed from it. At the end of the parsing phase, if it's not empty, - * then some required fields did not receive a value and an exception is - * thrown. - */ - private Map m_requiredFields = Maps.newHashMap(); - - /** - * A map of all the annotated fields. - */ - private Map m_fields = Maps.newHashMap(); - - private ResourceBundle m_bundle; - - /** - * A default provider returns default values for the parameters. - */ - private IDefaultProvider m_defaultProvider; - - /** - * List of commands and their instance. - */ - private Map m_commands = Maps.newLinkedHashMap(); - /** - * Alias database for reverse lookup - */ - private Map aliasMap = Maps.newLinkedHashMap(); - - /** - * The name of the command after the parsing has run. - */ - private String m_parsedCommand; - - /** - * The name of command or alias as it was passed to the - * command line - */ - private String m_parsedAlias; - - private ProgramName m_programName; - - private Comparator m_parameterDescriptionComparator - = new Comparator() { - public int compare(ParameterDescription p0, ParameterDescription p1) { - return p0.getLongestName().compareTo(p1.getLongestName()); - } - }; - - private int m_columnSize = 79; - - private static Console m_console; - - /** - * The factories used to look up string converters. - */ - private static LinkedList CONVERTER_FACTORIES = Lists.newLinkedList(); - - static { - CONVERTER_FACTORIES.addFirst(new DefaultConverterFactory()); - }; - - /** - * Creates a new un-configured JCommander object. - */ - public JCommander() { - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - */ - public JCommander(Object object) { - addObject(object); - createDescriptions(); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param bundle The bundle to use for the descriptions. Can be null. - */ - public JCommander(Object object, ResourceBundle bundle) { - addObject(object); - setDescriptionsBundle(bundle); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param bundle The bundle to use for the descriptions. Can be null. - * @param args The arguments to parse (optional). - */ - public JCommander(Object object, ResourceBundle bundle, String... args) { - addObject(object); - setDescriptionsBundle(bundle); - parse(args); - } - - /** - * @param object The arg object expected to contain {@link Parameter} annotations. - * @param args The arguments to parse (optional). - */ - public JCommander(Object object, String... args) { - addObject(object); - parse(args); - } - - public static Console getConsole() { - if (m_console == null) { - try { - Method consoleMethod = System.class.getDeclaredMethod("console", new Class[0]); - Object console = consoleMethod.invoke(null, new Object[0]); - m_console = new JDK6Console(console); - } catch (Throwable t) { - m_console = new DefaultConsole(); - } - } - return m_console; - } - - /** - * Adds the provided arg object to the set of objects that this commander - * will parse arguments into. - * - * @param object The arg object expected to contain {@link Parameter} - * annotations. If object is an array or is {@link Iterable}, - * the child objects will be added instead. - */ - // declared final since this is invoked from constructors - public final void addObject(Object object) { - if (object instanceof Iterable) { - // Iterable - for (Object o : (Iterable) object) { - m_objects.add(o); - } - } else if (object.getClass().isArray()) { - // Array - for (Object o : (Object[]) object) { - m_objects.add(o); - } - } else { - // Single object - m_objects.add(object); - } - } - - /** - * Sets the {@link ResourceBundle} to use for looking up descriptions. - * Set this to null to use description text directly. - */ - // declared final since this is invoked from constructors - public final void setDescriptionsBundle(ResourceBundle bundle) { - m_bundle = bundle; - } - - /** - * Parse and validate the command line parameters. - */ - public void parse(String... args) { - parse(true /* validate */, args); - } - - /** - * Parse the command line parameters without validating them. - */ - public void parseWithoutValidation(String... args) { - parse(false /* no validation */, args); - } - - private void parse(boolean validate, String... args) { - StringBuilder sb = new StringBuilder("Parsing \""); - sb.append(join(args).append("\"\n with:").append(join(m_objects.toArray()))); - p(sb.toString()); - - if (m_descriptions == null) createDescriptions(); - initializeDefaultValues(); - parseValues(expandArgs(args)); - if (validate) validateOptions(); - } - - private StringBuilder join(Object[] args) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < args.length; i++) { - if (i > 0) result.append(" "); - result.append(args[i]); - } - return result; - } - - private void initializeDefaultValues() { - if (m_defaultProvider != null) { - for (ParameterDescription pd : m_descriptions.values()) { - initializeDefaultValue(pd); - } - - for (Map.Entry entry : m_commands.entrySet()) { - entry.getValue().initializeDefaultValues(); - } - } - } - - /** - * Make sure that all the required parameters have received a value. - */ - private void validateOptions() { - if (! m_requiredFields.isEmpty()) { - StringBuilder missingFields = new StringBuilder(); - for (ParameterDescription pd : m_requiredFields.values()) { - missingFields.append(pd.getNames()).append(" "); - } - throw new ParameterException("The following options are required: " + missingFields); - } - - if (m_mainParameterDescription != null) { - if (m_mainParameterDescription.getParameter().required() && - !m_mainParameterDescription.isAssigned()) { - throw new ParameterException("Main parameters are required (\"" - + m_mainParameterDescription.getDescription() + "\")"); - } - } - } - - /** - * Expand the command line parameters to take @ parameters into account. - * When @ is encountered, the content of the file that follows is inserted - * in the command line. - * - * @param originalArgv the original command line parameters - * @return the new and enriched command line parameters - */ - private String[] expandArgs(String[] originalArgv) { - List vResult1 = Lists.newArrayList(); - - // - // Expand @ - // - for (String arg : originalArgv) { - - if (arg.startsWith("@")) { - String fileName = arg.substring(1); - vResult1.addAll(readFile(fileName)); - } - else { - List expanded = expandDynamicArg(arg); - vResult1.addAll(expanded); - } - } - - // Expand separators - // - List vResult2 = Lists.newArrayList(); - for (int i = 0; i < vResult1.size(); i++) { - String arg = vResult1.get(i); - String[] v1 = vResult1.toArray(new String[0]); - if (isOption(v1, arg)) { - String sep = getSeparatorFor(v1, arg); - if (! " ".equals(sep)) { - String[] sp = arg.split("[" + sep + "]", 2); - for (String ssp : sp) { - vResult2.add(ssp); - } - } else { - vResult2.add(arg); - } - } else { - vResult2.add(arg); - } - } - - return vResult2.toArray(new String[vResult2.size()]); - } - - private List expandDynamicArg(String arg) { - for (ParameterDescription pd : m_descriptions.values()) { - if (pd.isDynamicParameter()) { - for (String name : pd.getParameter().names()) { - if (arg.startsWith(name) && !arg.equals(name)) { - return Arrays.asList(name, arg.substring(name.length())); - } - } - } - } - - return Arrays.asList(arg); - } - - private boolean isOption(String[] args, String arg) { - String prefixes = getOptionPrefixes(args, arg); - return prefixes.indexOf(arg.charAt(0)) >= 0; - } - - private ParameterDescription getPrefixDescriptionFor(String arg) { - for (Map.Entry es : m_descriptions.entrySet()) { - if (arg.startsWith(es.getKey())) return es.getValue(); - } - - return null; - } - - /** - * If arg is an option, we can look it up directly, but if it's a value, - * we need to find the description for the option that precedes it. - */ - private ParameterDescription getDescriptionFor(String[] args, String arg) { - ParameterDescription result = getPrefixDescriptionFor(arg); - if (result != null) return result; - - for (String a : args) { - ParameterDescription pd = getPrefixDescriptionFor(arg); - if (pd != null) result = pd; - if (a.equals(arg)) return result; - } - - throw new ParameterException("Unknown parameter: " + arg); - } - - private String getSeparatorFor(String[] args, String arg) { - ParameterDescription pd = getDescriptionFor(args, arg); - - // Could be null if only main parameters were passed - if (pd != null) { - Parameters p = pd.getObject().getClass().getAnnotation(Parameters.class); - if (p != null) return p.separators(); - } - - return " "; - } - - private String getOptionPrefixes(String[] args, String arg) { - ParameterDescription pd = getDescriptionFor(args, arg); - - // Could be null if only main parameters were passed - if (pd != null) { - Parameters p = pd.getObject().getClass() - .getAnnotation(Parameters.class); - if (p != null) return p.optionPrefixes(); - } - - return Parameters.DEFAULT_OPTION_PREFIXES; - } - - /** - * Reads the file specified by filename and returns the file content as a string. - * End of lines are replaced by a space. - * - * @param fileName the command line filename - * @return the file content as a string. - */ - private static List readFile(String fileName) { - List result = Lists.newArrayList(); - - try { - BufferedReader bufRead = new BufferedReader(new FileReader(fileName)); - - String line; - - // Read through file one line at time. Print line # and line - while ((line = bufRead.readLine()) != null) { - // Allow empty lines in these at files - if (line.length() > 0) result.add(line); - } - - bufRead.close(); - } - catch (IOException e) { - throw new ParameterException("Could not read file " + fileName + ": " + e); - } - - return result; - } - - /** - * Remove spaces at both ends and handle double quotes. - */ - private static String trim(String string) { - String result = string.trim(); - if (result.startsWith("\"")) { - if (result.endsWith("\"")) { - return result.substring(1, result.length() - 1); - } - return result.substring(1); - } - return result; - } - - /** - * Create the ParameterDescriptions for all the \@Parameter found. - */ - private void createDescriptions() { - m_descriptions = Maps.newHashMap(); - - for (Object object : m_objects) { - addDescription(object); - } - } - - private void addDescription(Object object) { - Class cls = object.getClass(); - - while (!Object.class.equals(cls)) { - for (Field f : cls.getDeclaredFields()) { - p("Field:" + cls.getSimpleName() + "." + f.getName()); - f.setAccessible(true); - Annotation annotation = f.getAnnotation(Parameter.class); - Annotation delegateAnnotation = f.getAnnotation(ParametersDelegate.class); - Annotation dynamicParameter = f.getAnnotation(DynamicParameter.class); - if (annotation != null) { - // - // @Parameter - // - Parameter p = (Parameter) annotation; - if (p.names().length == 0) { - p("Found main parameter:" + f); - if (m_mainParameterField != null) { - throw new ParameterException("Only one @Parameter with no names attribute is" - + " allowed, found:" + m_mainParameterField + " and " + f); - } - m_mainParameterField = f; - m_mainParameterObject = object; - m_mainParameterAnnotation = p; - m_mainParameterDescription = new ParameterDescription(object, p, f, m_bundle, this); - } else { - for (String name : p.names()) { - if (m_descriptions.containsKey(name)) { - throw new ParameterException("Found the option " + name + " multiple times"); - } - p("Adding description for " + name); - ParameterDescription pd = new ParameterDescription(object, p, f, m_bundle, this); - m_fields.put(f, pd); - m_descriptions.put(name, pd); - - if (p.required()) m_requiredFields.put(f, pd); - } - } - } else if (delegateAnnotation != null) { - // - // @ParametersDelegate - // - try { - Object delegateObject = f.get(object); - if (delegateObject == null){ - throw new ParameterException("Delegate field '" + f.getName() + "' cannot be null."); - } - addDescription(delegateObject); - } catch (IllegalAccessException e) { - } - } else if (dynamicParameter != null) { - // - // @DynamicParameter - // - DynamicParameter dp = (DynamicParameter) dynamicParameter; - for (String name : dp.names()) { - if (m_descriptions.containsKey(name)) { - throw new ParameterException("Found the option " + name + " multiple times"); - } - p("Adding description for " + name); - ParameterDescription pd = new ParameterDescription(object, dp, f, m_bundle, this); - m_fields.put(f, pd); - m_descriptions.put(name, pd); - - if (dp.required()) m_requiredFields.put(f, pd); - } - } - } - // Traverse the super class until we find Object.class - cls = cls.getSuperclass(); - } - } - - private void initializeDefaultValue(ParameterDescription pd) { - for (String optionName : pd.getParameter().names()) { - String def = m_defaultProvider.getDefaultValueFor(optionName); - if (def != null) { - p("Initializing " + optionName + " with default value:" + def); - pd.addValue(def, true /* default */); - return; - } - } - } - - /** - * Main method that parses the values and initializes the fields accordingly. - */ - private void parseValues(String[] args) { - // This boolean becomes true if we encounter a command, which indicates we need - // to stop parsing (the parsing of the command will be done in a sub JCommander - // object) - boolean commandParsed = false; - int i = 0; - while (i < args.length && ! commandParsed) { - String arg = args[i]; - String a = trim(arg); - p("Parsing arg:" + a); - - JCommander jc = findCommandByAlias(arg); - if (isOption(args, a) && jc == null) { - // - // Option - // - ParameterDescription pd = m_descriptions.get(a); - - if (pd != null) { - if (pd.getParameter().password()) { - // - // Password option, use the Console to retrieve the password - // - char[] password = readPassword(pd.getDescription()); - pd.addValue(new String(password)); - m_requiredFields.remove(pd.getField()); - } else { - if (pd.getParameter().variableArity()) { - // - // Variable arity? - // - i = processVariableArity(args, i, pd); - } else { - // - // Regular option - // - Class fieldType = pd.getField().getType(); - - // Boolean, set to true as soon as we see it, unless it specified - // an arity of 1, in which case we need to read the next value - if ((fieldType == boolean.class || fieldType == Boolean.class) - && pd.getParameter().arity() == -1) { - pd.addValue("true"); - m_requiredFields.remove(pd.getField()); - } else { - i = processFixedArity(args, i, pd, fieldType); - } - } - } - } else { - throw new ParameterException("Unknown option: " + arg); - } - } - else { - // - // Main parameter - // - if (! isStringEmpty(arg)) { - if (m_commands.isEmpty()) { - // - // Regular (non-command) parsing - // - List mp = getMainParameter(arg); - String value = arg; - Object convertedValue = value; - - if (m_mainParameterField.getGenericType() instanceof ParameterizedType) { - ParameterizedType p = (ParameterizedType) m_mainParameterField.getGenericType(); - Type cls = p.getActualTypeArguments()[0]; - if (cls instanceof Class) { - convertedValue = convertValue(m_mainParameterField, (Class) cls, value); - } - } - - ParameterDescription.validateParameter(m_mainParameterAnnotation.validateWith(), - "Default", value); - - m_mainParameterDescription.setAssigned(true); - mp.add(convertedValue); - } - else { - // - // Command parsing - // - if (jc == null) throw new MissingCommandException("Expected a command, got " + arg); - m_parsedCommand = jc.m_programName.m_name; - m_parsedAlias = arg; //preserve the original form - - // Found a valid command, ask it to parse the remainder of the arguments. - // Setting the boolean commandParsed to true will force the current - // loop to end. - jc.parse(subArray(args, i + 1)); - commandParsed = true; - } - } - } - i++; - } - - // Mark the parameter descriptions held in m_fields as assigned - for (ParameterDescription parameterDescription : m_descriptions.values()) { - if (parameterDescription.isAssigned()) { - m_fields.get(parameterDescription.getField()).setAssigned(true); - } - } - - } - - /** - * @return the generic type of the collection for this field, or null if not applicable. - */ - private Type findFieldGenericType(Field field) { - if (field.getGenericType() instanceof ParameterizedType) { - ParameterizedType p = (ParameterizedType) field.getGenericType(); - Type cls = p.getActualTypeArguments()[0]; - if (cls instanceof Class) { - return cls; - } - } - - return null; - } - - /** - * @return the number of options that were processed. - */ - private int processVariableArity(String[] args, int index, ParameterDescription pd) { - Object arg = pd.getObject(); - if (! (arg instanceof IVariableArity)) { - throw new ParameterException("Arg class " + arg.getClass() - + " should implement IVariableArity"); - } - - IVariableArity va = (IVariableArity) arg; - List currentArgs = Lists.newArrayList(); - for (int j = index + 1; j < args.length; j++) { - currentArgs.add(args[j]); - } - int result = va.processVariableArity(pd.getParameter().names()[0], - currentArgs.toArray(new String[0])); - return result; - } - - private int processFixedArity(String[] args, int index, ParameterDescription pd, - Class fieldType) { - // Regular parameter, use the arity to tell use how many values - // we need to consume - String arg = args[index]; - int arity = pd.getParameter().arity(); - int n = (arity != -1 ? arity : 1); - - // Special case for boolean parameters of arity 0 - if (n == 0 && - (Boolean.class.isAssignableFrom(fieldType) - || boolean.class.isAssignableFrom(fieldType))) { - pd.addValue("true"); - m_requiredFields.remove(pd.getField()); - } else if (index < args.length - 1) { - int offset = "--".equals(args[index + 1]) ? 1 : 0; - - if (index + n < args.length) { - for (int j = 1; j <= n; j++) { - pd.addValue(trim(args[index + j + offset])); - m_requiredFields.remove(pd.getField()); - } - index += n + offset; - } else { - throw new ParameterException("Expected " + n + " values after " + arg); - } - } else { - throw new ParameterException("Expected a value after parameter " + arg); - } - - return index; - } - - /** - * Invoke Console.readPassword through reflection to avoid depending - * on Java 6. - */ - private char[] readPassword(String description) { - getConsole().print(description + ": "); - return getConsole().readPassword(); - } - - private String[] subArray(String[] args, int index) { - int l = args.length - index; - String[] result = new String[l]; - System.arraycopy(args, index, result, 0, l); - - return result; - } - - private static boolean isStringEmpty(String s) { - return s == null || "".equals(s); - } - - /** - * @return the field that's meant to receive all the parameters that are not options. - * - * @param arg the arg that we're about to add (only passed here to output a meaningful - * error message). - */ - private List getMainParameter(String arg) { - if (m_mainParameterField == null) { - throw new ParameterException( - "Was passed main parameter '" + arg + "' but no main parameter was defined"); - } - - try { - List result = (List) m_mainParameterField.get(m_mainParameterObject); - if (result == null) { - result = Lists.newArrayList(); - if (! List.class.isAssignableFrom(m_mainParameterField.getType())) { - throw new ParameterException("Main parameter field " + m_mainParameterField - + " needs to be of type List, not " + m_mainParameterField.getType()); - } - m_mainParameterField.set(m_mainParameterObject, result); - } - return result; - } - catch(IllegalAccessException ex) { - throw new ParameterException("Couldn't access main parameter: " + ex.getMessage()); - } - } - - public String getMainParameterDescription() { - if (m_descriptions == null) createDescriptions(); - return m_mainParameterAnnotation != null ? m_mainParameterAnnotation.description() - : null; - } - - private int longestName(Collection objects) { - int result = 0; - for (Object o : objects) { - int l = o.toString().length(); - if (l > result) result = l; - } - - return result; - } - - /** - * Set the program name (used only in the usage). - */ - public void setProgramName(String name) { - setProgramName(name, new String[0]); - } - - /** - * Set the program name - * - * @param name program name - * @param aliases aliases to the program name - */ - public void setProgramName(String name, String... aliases) { - m_programName = new ProgramName(name, Arrays.asList(aliases)); - } - - /** - * Display the usage for this command. - */ - public void usage(String commandName) { - StringBuilder sb = new StringBuilder(); - usage(commandName, sb); - getConsole().println(sb.toString()); - } - - /** - * Store the help for the command in the passed string builder. - */ - public void usage(String commandName, StringBuilder out) { - usage(commandName, out, ""); - } - - /** - * Store the help for the command in the passed string builder, indenting - * every line with "indent". - */ - public void usage(String commandName, StringBuilder out, String indent) { - String description = getCommandDescription(commandName); - JCommander jc = findCommandByAlias(commandName); - if (description != null) { - out.append(indent).append(description); - out.append("\n"); - } - jc.usage(out, indent); - } - - /** - * @return the description of the command. - */ - public String getCommandDescription(String commandName) { - JCommander jc = findCommandByAlias(commandName); - if (jc == null) { - throw new ParameterException("Asking description for unknown command: " + commandName); - } - - Parameters p = jc.getObjects().get(0).getClass().getAnnotation(Parameters.class); - String result = jc.getMainParameterDescription(); - if (p != null) result = getI18nString(p.commandDescriptionKey(), p.commandDescription()); - - return result; - } - - /** - * @return The internationalized version of the string if available, otherwise - * return def. - */ - private String getI18nString(String key, String def) { - String s = m_bundle != null ? m_bundle.getString(key) : null; - return s != null ? s : def; - } - - /** - * Display the help on System.out. - */ - public void usage() { - StringBuilder sb = new StringBuilder(); - usage(sb); - getConsole().println(sb.toString()); - } - - /** - * Store the help in the passed string builder. - */ - public void usage(StringBuilder out) { - usage(out, ""); - } - - public void usage(StringBuilder out, String indent) { - if (m_descriptions == null) createDescriptions(); - boolean hasCommands = !m_commands.isEmpty(); - - // - // First line of the usage - // - String programName = m_programName != null ? m_programName.getDisplayName() : "
"; - out.append(indent).append("Usage: " + programName + " [options]"); - if (hasCommands) out.append(indent).append(" [command] [command options]"); -// out.append("\n"); - if (m_mainParameterDescription != null) { - out.append(" " + m_mainParameterDescription.getDescription()); - } - - // - // Align the descriptions at the "longestName" column - // - int longestName = 0; - List sorted = Lists.newArrayList(); - for (ParameterDescription pd : m_fields.values()) { - if (! pd.getParameter().hidden()) { - sorted.add(pd); - // + to have an extra space between the name and the description - int length = pd.getNames().length() + 2; - if (length > longestName) { - longestName = length; - } - } - } - - // - // Sort the options - // - Collections.sort(sorted, getParameterDescriptionComparator()); - - // - // Display all the names and descriptions - // - if (sorted.size() > 0) out.append(indent).append("\n").append(indent).append(" Options:\n"); - for (ParameterDescription pd : sorted) { - int l = pd.getNames().length(); - int spaceCount = longestName - l; - int start = out.length(); - WrappedParameter parameter = pd.getParameter(); - out.append(indent).append(" " - + (parameter.required() ? "* " : " ") - + pd.getNames() + s(spaceCount)); - int indentCount = out.length() - start; - wrapDescription(out, indentCount, pd.getDescription()); - Object def = pd.getDefault(); - if (pd.isDynamicParameter()) { - out.append("\n" + spaces(indentCount + 1)) - .append("Syntax: " + parameter.names()[0] - + "key" + parameter.getAssignment() - + "value"); - } - if (def != null && ! "".equals(def)) { - out.append("\n" + spaces(indentCount + 1)) - .append("Default: " + def); - } - out.append("\n"); - } - - // - // If commands were specified, show them as well - // - if (hasCommands) { - out.append(" Commands:\n"); - // The magic value 3 is the number of spaces between the name of the option - // and its description - for (Map.Entry commands : m_commands.entrySet()) { - ProgramName progName = commands.getKey(); - String dispName = progName.getDisplayName(); - out.append(indent).append(" " + dispName); // + s(spaceCount) + getCommandDescription(progName.name) + "\n"); - - // Options for this command - usage(progName.getName(), out, " "); - out.append("\n"); - } - } - } - - private Comparator getParameterDescriptionComparator() { - return m_parameterDescriptionComparator; - } - - public void setParameterDescriptionComparator(Comparator c) { - m_parameterDescriptionComparator = c; - } - - public void setColumnSize(int columnSize) { - m_columnSize = columnSize; - } - - public int getColumnSize() { - return m_columnSize; - } - - private void wrapDescription(StringBuilder out, int indent, String description) { - int max = getColumnSize(); - String[] words = description.split(" "); - int current = indent; - int i = 0; - while (i < words.length) { - String word = words[i]; - if (word.length() > max || current + word.length() <= max) { - out.append(" ").append(word); - current += word.length() + 1; - } else { - out.append("\n").append(spaces(indent + 1)).append(word); - current = indent; - } - i++; - } - } - - private String spaces(int indent) { - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < indent; i++) sb.append(" "); - return sb.toString(); - } - - /** - * @return a Collection of all the \@Parameter annotations found on the - * target class. This can be used to display the usage() in a different - * format (e.g. HTML). - */ - public List getParameters() { - return new ArrayList(m_fields.values()); - } - - /** - * @return the main parameter description or null if none is defined. - */ - public ParameterDescription getMainParameter() { - return m_mainParameterDescription; - } - - private void p(String string) { - if (System.getProperty(JCommander.DEBUG_PROPERTY) != null) { - getConsole().println("[JCommander] " + string); - } - } - - /** - * Define the default provider for this instance. - */ - public void setDefaultProvider(IDefaultProvider defaultProvider) { - m_defaultProvider = defaultProvider; - - for (Map.Entry entry : m_commands.entrySet()) { - entry.getValue().setDefaultProvider(defaultProvider); - } - } - - public void addConverterFactory(IStringConverterFactory converterFactory) { - CONVERTER_FACTORIES.addFirst(converterFactory); - } - - public Class> findConverter(Class cls) { - for (IStringConverterFactory f : CONVERTER_FACTORIES) { - Class> result = f.getConverter(cls); - if (result != null) return result; - } - - return null; - } - - public Object convertValue(ParameterDescription pd, String value) { - return convertValue(pd.getField(), pd.getField().getType(), value); - } - - /** - * @param field The field - * @param type The type of the actual parameter - * @param value The value to convert - */ - public Object convertValue(Field field, Class type, String value) { - Parameter annotation = field.getAnnotation(Parameter.class); - - // Do nothing if it's a @DynamicParameter - if (annotation == null) return value; - - Class> converterClass = annotation.converter(); - boolean listConverterWasSpecified = annotation.listConverter() != NoConverter.class; - - // - // Try to find a converter on the annotation - // - if (converterClass == null || converterClass == NoConverter.class) { - // If no converter specified and type is enum, used enum values to convert - if (type.isEnum()){ - converterClass = type; - } else { - converterClass = findConverter(type); - } - } - - if (converterClass == null) { - Type elementType = findFieldGenericType(field); - converterClass = elementType != null - ? findConverter((Class>) elementType) - : StringConverter.class; - } - - // -// // -// // Try to find a converter in the factory -// // -// IStringConverter converter = null; -// if (converterClass == null && m_converterFactories != null) { -// // Mmmh, javac requires a cast here -// converter = (IStringConverter) m_converterFactories.getConverter(type); -// } - -// if (converterClass == null) { -// throw new ParameterException("Don't know how to convert " + value -// + " to type " + type + " (field: " + field.getName() + ")"); -// } - - IStringConverter converter; - Object result = null; - try { - String[] names = annotation.names(); - String optionName = names.length > 0 ? names[0] : "[Main class]"; - if (converterClass.isEnum()) { - try { - result = Enum.valueOf((Class) converterClass, value.toUpperCase()); - } catch (Exception e) { - throw new ParameterException("Invalid value for " + optionName + " parameter. Allowed values:" + - EnumSet.allOf((Class) converterClass)); - } - } else { - converter = instantiateConverter(optionName, converterClass); - if (type.isAssignableFrom(List.class) - && field.getGenericType() instanceof ParameterizedType) { - - // The field is a List - if (listConverterWasSpecified) { - // If a list converter was specified, pass the value to it - // for direct conversion - IStringConverter listConverter = - instantiateConverter(optionName, annotation.listConverter()); - result = listConverter.convert(value); - } else { - // No list converter: use the single value converter and pass each - // parsed value to it individually - result = convertToList(value, converter, annotation.splitter()); - } - } else { - result = converter.convert(value); - } - } - } catch (InstantiationException e) { - throw new ParameterException(e); - } catch (IllegalAccessException e) { - throw new ParameterException(e); - } catch (InvocationTargetException e) { - throw new ParameterException(e); - } - - return result; - } - - /** - * Use the splitter to split the value into multiple values and then convert - * each of them individually. - */ - private Object convertToList(String value, IStringConverter converter, - Class splitterClass) - throws InstantiationException, IllegalAccessException { - IParameterSplitter splitter = splitterClass.newInstance(); - List result = Lists.newArrayList(); - for (String param : splitter.split(value)) { - result.add(converter.convert(param)); - } - return result; - } - - private IStringConverter instantiateConverter(String optionName, - Class> converterClass) - throws IllegalArgumentException, InstantiationException, IllegalAccessException, - InvocationTargetException { - Constructor> ctor = null; - Constructor> stringCtor = null; - Constructor>[] ctors - = (Constructor>[]) converterClass.getDeclaredConstructors(); - for (Constructor> c : ctors) { - Class[] types = c.getParameterTypes(); - if (types.length == 1 && types[0].equals(String.class)) { - stringCtor = c; - } else if (types.length == 0) { - ctor = c; - } - } - - IStringConverter result = stringCtor != null - ? stringCtor.newInstance(optionName) - : ctor.newInstance(); - - return result; - } - - /** - * Add a command object. - */ - public void addCommand(String name, Object object) { - addCommand(name, object, new String[0]); - } - - public void addCommand(Object object) { - Parameters p = object.getClass().getAnnotation(Parameters.class); - if (p != null && p.commandNames().length > 0) { - for (String commandName : p.commandNames()) { - addCommand(commandName, object); - } - } else { - throw new ParameterException("Trying to add command " + object.getClass().getName() - + " without specifying its names in @Parameters"); - } - } - - /** - * Add a command object and its aliases. - */ - public void addCommand(String name, Object object, String... aliases) { - JCommander jc = new JCommander(object); - jc.setProgramName(name, aliases); - jc.setDefaultProvider(m_defaultProvider); - ProgramName progName = jc.m_programName; - m_commands.put(progName, jc); - - /* - * Register aliases - */ - //register command name as an alias of itself for reverse lookup - //Note: Name clash check is intentionally omitted to resemble the - // original behaviour of clashing commands. - // Aliases are, however, are strictly checked for name clashes. - aliasMap.put(name, progName); - for (String alias : aliases) { - //omit pointless aliases to avoid name clash exception - if (!alias.equals(name)) { - ProgramName mappedName = aliasMap.get(alias); - if (mappedName != null && !mappedName.equals(progName)) { - throw new ParameterException("Cannot set alias " + alias - + " for " + name - + " command because it has already been defined for " - + mappedName.m_name + " command"); - } - aliasMap.put(alias, progName); - } - } - } - - public Map getCommands() { - Map res = Maps.newLinkedHashMap(); - for (Map.Entry entry : m_commands.entrySet()) { - res.put(entry.getKey().m_name, entry.getValue()); - } - return res; - } - - public String getParsedCommand() { - return m_parsedCommand; - } - - /** - * The name of the command or the alias in the form it was - * passed to the command line. null if no - * command or alias was specified. - * - * @return Name of command or alias passed to command line. If none passed: null. - */ - public String getParsedAlias() { - return m_parsedAlias; - } - - /** - * @return n spaces - */ - private String s(int count) { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < count; i++) { - result.append(" "); - } - - return result.toString(); - } - - /** - * @return the objects that JCommander will fill with the result of - * parsing the command line. - */ - public List getObjects() { - return m_objects; - } - - /* - * Reverse lookup JCommand object by command's name or its alias - */ - private JCommander findCommandByAlias(String commandOrAlias) { - ProgramName progName = aliasMap.get(commandOrAlias); - if (progName == null) { - return null; - } - JCommander jc = m_commands.get(progName); - if (jc == null) { - throw new IllegalStateException( - "There appears to be inconsistency in the internal command database. " + - " This is likely a bug. Please report."); - } - return jc; - } - - private static final class ProgramName { - private final String m_name; - private final List m_aliases; - - ProgramName(String name, List aliases) { - m_name = name; - m_aliases = aliases; - } - - public String getName() { - return m_name; - } - - private String getDisplayName() { - StringBuilder sb = new StringBuilder(); - sb.append(m_name); - if (!m_aliases.isEmpty()) { - sb.append("("); - Iterator aliasesIt = m_aliases.iterator(); - while (aliasesIt.hasNext()) { - sb.append(aliasesIt.next()); - if (aliasesIt.hasNext()) { - sb.append(","); - } - } - sb.append(")"); - } - return sb.toString(); - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((m_name == null) ? 0 : m_name.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ProgramName other = (ProgramName) obj; - if (m_name == null) { - if (other.m_name != null) - return false; - } else if (!m_name.equals(other.m_name)) - return false; - return true; - } - - /* - * Important: ProgramName#toString() is used by longestName(Collection) function - * to format usage output. - */ - @Override - public String toString() { - return getDisplayName(); - - } - } -} diff --git a/All/Genesis-OOB/Genesis#10/pair.info b/All/Genesis-OOB/Genesis#10/pair.info deleted file mode 100755 index 48aaf2a..0000000 --- a/All/Genesis-OOB/Genesis#10/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:10 -SATName:Genesis -modifiedFPath:src/main/java/com/beust/jcommander/JCommander.java -comSha:ca0789ba868746845d31c2ee9e354d8bfbdeca6e -parentComSha:ca0789ba868746845d31c2ee9e354d8bfbdeca6e^1 -githubUrl:https://github.com/cbeust/jcommander -repoName:cbeust#jcommander \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#100/comMsg.txt b/All/Genesis-OOB/Genesis#100/comMsg.txt deleted file mode 100755 index d509c2a..0000000 --- a/All/Genesis-OOB/Genesis#100/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -IndexOutOfBoundsException would occur if response is less than 128 characters long... Fixed that. diff --git a/All/Genesis-OOB/Genesis#100/diff.diff b/All/Genesis-OOB/Genesis#100/diff.diff deleted file mode 100755 index 117a5b4..0000000 --- a/All/Genesis-OOB/Genesis#100/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/org/wicketstuff/htmlvalidator/HtmlValidationResponseFilter.java b/src/main/java/org/wicketstuff/htmlvalidator/HtmlValidationResponseFilter.java -index 400315f..c099207 100644 ---- a/src/main/java/org/wicketstuff/htmlvalidator/HtmlValidationResponseFilter.java -+++ b/src/main/java/org/wicketstuff/htmlvalidator/HtmlValidationResponseFilter.java -@@ -9,2 +8,0 @@ import org.apache.wicket.RequestCycle; --import org.apache.wicket.RestartResponseException; --import org.apache.wicket.protocol.http.WebRequestCycle; -@@ -45 +43,2 @@ public class HtmlValidationResponseFilter implements IResponseFilter { -- String contentSoFar = response.substring(0, 128); -+ int maxLength = Math.min(response.length(), 128); -+ String contentSoFar = response.substring(0, maxLength); diff --git a/All/Genesis-OOB/Genesis#100/new/HtmlValidationResponseFilter.java b/All/Genesis-OOB/Genesis#100/new/HtmlValidationResponseFilter.java deleted file mode 100755 index c099207..0000000 --- a/All/Genesis-OOB/Genesis#100/new/HtmlValidationResponseFilter.java +++ /dev/null @@ -1,64 +0,0 @@ -package org.wicketstuff.htmlvalidator; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import org.apache.wicket.IResponseFilter; -import org.apache.wicket.Page; -import org.apache.wicket.RequestCycle; -import org.apache.wicket.util.string.AppendingStringBuffer; -import org.tuckey.web.filters.validation.ValidationHandler; -import org.tuckey.web.filters.validation.generated.GeneratedValidationReport; - -public class HtmlValidationResponseFilter implements IResponseFilter { - public AppendingStringBuffer filter(AppendingStringBuffer responseBuffer) { - Page responsePage = RequestCycle.get().getResponsePage(); - - // when the responsepage is an error page, don't filter the page - if (responsePage.isErrorPage()) { - return responseBuffer; - } - - String response = responseBuffer.toString(); - - if (isXHtml(responseBuffer)) { - try { - ValidationHandler handler = new ValidationHandler(response, ""); - handler.parse(); - if (!handler.isValid()) { - insertMarkup(responseBuffer, handler); - } - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return responseBuffer; - } - - private boolean isXHtml(AppendingStringBuffer response) { - int maxLength = Math.min(response.length(), 128); - String contentSoFar = response.substring(0, maxLength); - return contentSoFar.indexOf(""); - original.insert(indexOfHeadClose, head); - - int indexOfBodyClose = original.lastIndexOf(""); - original.insert(indexOfBodyClose, body); - } -} diff --git a/All/Genesis-OOB/Genesis#100/old/HtmlValidationResponseFilter.java b/All/Genesis-OOB/Genesis#100/old/HtmlValidationResponseFilter.java deleted file mode 100755 index 400315f..0000000 --- a/All/Genesis-OOB/Genesis#100/old/HtmlValidationResponseFilter.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.wicketstuff.htmlvalidator; - -import java.io.FileNotFoundException; -import java.io.IOException; - -import org.apache.wicket.IResponseFilter; -import org.apache.wicket.Page; -import org.apache.wicket.RequestCycle; -import org.apache.wicket.RestartResponseException; -import org.apache.wicket.protocol.http.WebRequestCycle; -import org.apache.wicket.util.string.AppendingStringBuffer; -import org.tuckey.web.filters.validation.ValidationHandler; -import org.tuckey.web.filters.validation.generated.GeneratedValidationReport; - -public class HtmlValidationResponseFilter implements IResponseFilter { - public AppendingStringBuffer filter(AppendingStringBuffer responseBuffer) { - Page responsePage = RequestCycle.get().getResponsePage(); - - // when the responsepage is an error page, don't filter the page - if (responsePage.isErrorPage()) { - return responseBuffer; - } - - String response = responseBuffer.toString(); - - if (isXHtml(responseBuffer)) { - try { - ValidationHandler handler = new ValidationHandler(response, ""); - handler.parse(); - if (!handler.isValid()) { - insertMarkup(responseBuffer, handler); - } - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (IOException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - return responseBuffer; - } - - private boolean isXHtml(AppendingStringBuffer response) { - String contentSoFar = response.substring(0, 128); - return contentSoFar.indexOf(""); - original.insert(indexOfHeadClose, head); - - int indexOfBodyClose = original.lastIndexOf(""); - original.insert(indexOfBodyClose, body); - } -} diff --git a/All/Genesis-OOB/Genesis#100/pair.info b/All/Genesis-OOB/Genesis#100/pair.info deleted file mode 100755 index 0600617..0000000 --- a/All/Genesis-OOB/Genesis#100/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:100 -SATName:Genesis -modifiedFPath:src/main/java/org/wicketstuff/htmlvalidator/HtmlValidationResponseFilter.java -comSha:5911914 -parentComSha:5911914^1 -githubUrl:https://github.com/papegaaij/wicket-stuff-markup-validator -repoName:papegaaij#wicket-stuff-markup-validator \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#108/comMsg.txt b/All/Genesis-OOB/Genesis#108/comMsg.txt deleted file mode 100755 index 1fbebda..0000000 --- a/All/Genesis-OOB/Genesis#108/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Issue 285: WebURL.java causes IndexOutOfBoundException Issue 206: StringIndexOutOfBoundsException in WebURL diff --git a/All/Genesis-OOB/Genesis#108/diff.diff b/All/Genesis-OOB/Genesis#108/diff.diff deleted file mode 100755 index c4d7bb9..0000000 --- a/All/Genesis-OOB/Genesis#108/diff.diff +++ /dev/null @@ -1,6 +0,0 @@ -diff --git a/src/main/java/edu/uci/ics/crawler4j/url/WebURL.java b/src/main/java/edu/uci/ics/crawler4j/url/WebURL.java -index ae5986a..422917c 100644 ---- a/src/main/java/edu/uci/ics/crawler4j/url/WebURL.java -+++ b/src/main/java/edu/uci/ics/crawler4j/url/WebURL.java -@@ -93,0 +94 @@ public class WebURL implements Serializable { -+ domainEndIdx = domainEndIdx > domainStartIdx ? domainEndIdx : url.length(); diff --git a/All/Genesis-OOB/Genesis#108/new/CHANGES.txt b/All/Genesis-OOB/Genesis#108/new/CHANGES.txt deleted file mode 100755 index b815fe0..0000000 --- a/All/Genesis-OOB/Genesis#108/new/CHANGES.txt +++ /dev/null @@ -1,68 +0,0 @@ -Crawler4J Change Log - -Version 4.0 -Major Features -- Issue 272: Parse Binary Content parsing, Now the crawler can really parse binary content. Based on Tero Jankilla's code (Avi) - -Features -- Issue 278: Add hooks in the webcrawler for better error handling (Avi) -- Issue 239: Add an option to tweak the URL before processing the page Added hooks to several errors where by default we log the error but allow the user to override those methods in order to do anything they want with those URLs (maybe list them and then try to process them later etc) Added a method which can be overridden by the user which enables the user to tweak the url before fetching it (Avi) -- Issue 276: Don't let a crawled URL to be dropped without proper logging. Each URL should be logged somehow so the user will know it was crawled. We shouldn't just drop URLs without logging them (warn / debug, depends on the case) (Avi) -- Issue 213: Upgrade all logging statements to use {} of slf4j - Slf4j optimizes string concatenation in logging statements by using {} placeholder. Upgrade all logging statements to use it. (Avi) -- Issue 213: Changed from log4j implementation to slf4j API - Removed any reference to log4j - Logging Implementations should be the user's choice and not the library choice. Instead I have inserted the slf4j API. (Avi) -- Updated pom.xml project Dependencies were updated to their latest (Avi) -- Added log messages to PageFetcher These logs were taken from: ind9/crawler4j 153eb752bef5a57bd39016807423683ab22f3913 (Avi) -- Issue 282: Add CHANGES.TXT with the changelog to the root -- Issue 288: Upgrade Unit Tests to v4 - -BugFixes -- Issue 284: Cathing any exception and hidding the log. Upgraded logging in webcrawler Clarified a little statuscode 1005 (Avi) -- Issue 251: Fix a typo, Fix a typo in line #92. 'cuncurrent' -> 'concurrent' (Avi) -- Issue 279: TikaException is thrown while crawling several PDFs in a row The problem was the wrong re-use of the metadata (Avi) -- Issue 139: A URL with a backslash was rejected (Avi) -- Issue 231: Memory leakage in crawler4j caused by database environment, Closing the environment solves the leak. (Avi) -- Issue 206: StringIndexOutOfBoundsException in WebURL -- Issue 285: WebURL.java causes IndexOutOfBoundException - -Version 3.5 (March 2013) -- Fixed issues #184, #169, #136, #156, #191, #192, #127 (Yasser) -- Fixed issue #101 in normalizing Urls (Yasser) -- Fixed issue #143 : Anchor text is now provided correctly (Yasser) -- Access to response headers is now provided as a field in Page object (Yasser) -- Added support for handling content fetch and parsing issues. (Yasser) -- Added meta refresh and location to outgoing links (Yasser) -- Upgraded to Java 7 (Yasser) -- Updated dependencies to their latest versions (Yasser) - -Version 3.3 -- Updated URL canonicalizer based on RFC1808 and fixed bugs (Yasser) -- Added Parent Url and Path to WebURL (Yasser) -- Added support for domain and sub-domain detection. (Yasser) -- Added support for handling http status codes for fetched pages (Yasser) - -Version 3.1 -- Fixed thread-safety bug in page fetcher. (Yasser) -- Improved URL canonicalizer. (Yasser) - -Version 3.0 -- Major re-design of crawler4j to add many new features and make it extendable. (Yasser) -- Multiple distinct crawlers can now run concurrently. (Yasser) -- Maven support (Yasser) -- Automatic detection of character encoding of pages to support crawling of non UTF-8 pages. (Yasser) -- Implemented graceful shutdown of the crawlers. (Yasser) -- Crawlers are now configurable through a config objects and the static crawler4j.properties file is removed. (Yasser) -- Fixed several bugs in handling redirects, resuming crawling, ... (Yasser) - -Version 2.6.1 -- Added Javadocs (Yasser) -- Fixed bug in parsing robots.txt files (Yasser) - -Version 2.6 -- Added support for robots.txt files (Yasser) -- Added the feature to specify maximum number of pages to crawl (Yasser) - -Version 2.5 -- Added support for specifying maximum crawl depth (Yasser) -- Fixed bug in terminating all threads (Yasser) -- Fixed bug in handling redirected pages (Yasser) -- Fixed bug in handling pages with base url (Yasser) \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#108/new/WebURL.java b/All/Genesis-OOB/Genesis#108/new/WebURL.java deleted file mode 100755 index 422917c..0000000 --- a/All/Genesis-OOB/Genesis#108/new/WebURL.java +++ /dev/null @@ -1,204 +0,0 @@ -/** - * 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 edu.uci.ics.crawler4j.url; - -import java.io.Serializable; - -import com.sleepycat.persist.model.Entity; -import com.sleepycat.persist.model.PrimaryKey; - -/** - * @author Yasser Ganjisaffar - */ - -@Entity -public class WebURL implements Serializable { - - private static final long serialVersionUID = 1L; - - @PrimaryKey - private String url; - - private int docid; - private int parentDocid; - private String parentUrl; - private short depth; - private String domain; - private String subDomain; - private String path; - private String anchor; - private byte priority; - - /** - * Returns the unique document id assigned to this Url. - */ - public int getDocid() { - return docid; - } - - public void setDocid(int docid) { - this.docid = docid; - } - - @Override - public int hashCode() { - return url.hashCode(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - WebURL otherUrl = (WebURL) o; - return url != null && url.equals(otherUrl.getURL()); - - } - - @Override - public String toString() { - return url; - } - - /** - * Returns the Url string - */ - public String getURL() { - return url; - } - - public void setURL(String url) { - this.url = url; - - int domainStartIdx = url.indexOf("//") + 2; - int domainEndIdx = url.indexOf('/', domainStartIdx); - domainEndIdx = domainEndIdx > domainStartIdx ? domainEndIdx : url.length(); - domain = url.substring(domainStartIdx, domainEndIdx); - subDomain = ""; - String[] parts = domain.split("\\."); - if (parts.length > 2) { - domain = parts[parts.length - 2] + "." + parts[parts.length - 1]; - int limit = 2; - if (TLDList.getInstance().contains(domain)) { - domain = parts[parts.length - 3] + "." + domain; - limit = 3; - } - for (int i = 0; i < parts.length - limit; i++) { - if (subDomain.length() > 0) { - subDomain += "."; - } - subDomain += parts[i]; - } - } - path = url.substring(domainEndIdx); - int pathEndIdx = path.indexOf('?'); - if (pathEndIdx >= 0) { - path = path.substring(0, pathEndIdx); - } - } - - /** - * Returns the unique document id of the parent page. The parent page is the - * page in which the Url of this page is first observed. - */ - public int getParentDocid() { - return parentDocid; - } - - public void setParentDocid(int parentDocid) { - this.parentDocid = parentDocid; - } - - /** - * Returns the url of the parent page. The parent page is the page in which - * the Url of this page is first observed. - */ - public String getParentUrl() { - return parentUrl; - } - - public void setParentUrl(String parentUrl) { - this.parentUrl = parentUrl; - } - - /** - * Returns the crawl depth at which this Url is first observed. Seed Urls - * are at depth 0. Urls that are extracted from seed Urls are at depth 1, - * etc. - */ - public short getDepth() { - return depth; - } - - public void setDepth(short depth) { - this.depth = depth; - } - - /** - * Returns the domain of this Url. For 'http://www.example.com/sample.htm', - * domain will be 'example.com' - */ - public String getDomain() { - return domain; - } - - public String getSubDomain() { - return subDomain; - } - - /** - * Returns the path of this Url. For 'http://www.example.com/sample.htm', - * domain will be 'sample.htm' - */ - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - /** - * Returns the anchor string. For example, in A sample anchor - * the anchor string is 'A sample anchor' - */ - public String getAnchor() { - return anchor; - } - - public void setAnchor(String anchor) { - this.anchor = anchor; - } - - /** - * Returns the priority for crawling this URL. - * A lower number results in higher priority. - */ - public byte getPriority() { - return priority; - } - - public void setPriority(byte priority) { - this.priority = priority; - } - -} diff --git a/All/Genesis-OOB/Genesis#108/old/CHANGES.txt b/All/Genesis-OOB/Genesis#108/old/CHANGES.txt deleted file mode 100755 index 335136f..0000000 --- a/All/Genesis-OOB/Genesis#108/old/CHANGES.txt +++ /dev/null @@ -1,66 +0,0 @@ -Crawler4J Change Log - -Version 4.0 -Major Features -- Issue 272: Parse Binary Content parsing, Now the crawler can really parse binary content. Based on Tero Jankilla's code (Avi) - -Features -- Issue 278: Add hooks in the webcrawler for better error handling (Avi) -- Issue 239: Add an option to tweak the URL before processing the page Added hooks to several errors where by default we log the error but allow the user to override those methods in order to do anything they want with those URLs (maybe list them and then try to process them later etc) Added a method which can be overridden by the user which enables the user to tweak the url before fetching it (Avi) -- Issue 276: Don't let a crawled URL to be dropped without proper logging. Each URL should be logged somehow so the user will know it was crawled. We shouldn't just drop URLs without logging them (warn / debug, depends on the case) (Avi) -- Issue 213: Upgrade all logging statements to use {} of slf4j - Slf4j optimizes string concatenation in logging statements by using {} placeholder. Upgrade all logging statements to use it. (Avi) -- Issue 213: Changed from log4j implementation to slf4j API - Removed any reference to log4j - Logging Implementations should be the user's choice and not the library choice. Instead I have inserted the slf4j API. (Avi) -- Updated pom.xml project Dependencies were updated to their latest (Avi) -- Added log messages to PageFetcher These logs were taken from: ind9/crawler4j 153eb752bef5a57bd39016807423683ab22f3913 (Avi) -- Issue 282: Add CHANGES.TXT with the changelog to the root -- Issue 288: Upgrade Unit Tests to v4 - -BugFixes -- Issue 284: Cathing any exception and hidding the log. Upgraded logging in webcrawler Clarified a little statuscode 1005 (Avi) -- Issue 251: Fix a typo, Fix a typo in line #92. 'cuncurrent' -> 'concurrent' (Avi) -- Issue 279: TikaException is thrown while crawling several PDFs in a row The problem was the wrong re-use of the metadata (Avi) -- Issue 139: A URL with a backslash was rejected (Avi) -- Issue 231: Memory leakage in crawler4j caused by database environment, Closing the environment solves the leak. (Avi) - -Version 3.5 (March 2013) -- Fixed issues #184, #169, #136, #156, #191, #192, #127 (Yasser) -- Fixed issue #101 in normalizing Urls (Yasser) -- Fixed issue #143 : Anchor text is now provided correctly (Yasser) -- Access to response headers is now provided as a field in Page object (Yasser) -- Added support for handling content fetch and parsing issues. (Yasser) -- Added meta refresh and location to outgoing links (Yasser) -- Upgraded to Java 7 (Yasser) -- Updated dependencies to their latest versions (Yasser) - -Version 3.3 -- Updated URL canonicalizer based on RFC1808 and fixed bugs (Yasser) -- Added Parent Url and Path to WebURL (Yasser) -- Added support for domain and sub-domain detection. (Yasser) -- Added support for handling http status codes for fetched pages (Yasser) - -Version 3.1 -- Fixed thread-safety bug in page fetcher. (Yasser) -- Improved URL canonicalizer. (Yasser) - -Version 3.0 -- Major re-design of crawler4j to add many new features and make it extendable. (Yasser) -- Multiple distinct crawlers can now run concurrently. (Yasser) -- Maven support (Yasser) -- Automatic detection of character encoding of pages to support crawling of non UTF-8 pages. (Yasser) -- Implemented graceful shutdown of the crawlers. (Yasser) -- Crawlers are now configurable through a config objects and the static crawler4j.properties file is removed. (Yasser) -- Fixed several bugs in handling redirects, resuming crawling, ... (Yasser) - -Version 2.6.1 -- Added Javadocs (Yasser) -- Fixed bug in parsing robots.txt files (Yasser) - -Version 2.6 -- Added support for robots.txt files (Yasser) -- Added the feature to specify maximum number of pages to crawl (Yasser) - -Version 2.5 -- Added support for specifying maximum crawl depth (Yasser) -- Fixed bug in terminating all threads (Yasser) -- Fixed bug in handling redirected pages (Yasser) -- Fixed bug in handling pages with base url (Yasser) \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#108/old/WebURL.java b/All/Genesis-OOB/Genesis#108/old/WebURL.java deleted file mode 100755 index ae5986a..0000000 --- a/All/Genesis-OOB/Genesis#108/old/WebURL.java +++ /dev/null @@ -1,203 +0,0 @@ -/** - * 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 edu.uci.ics.crawler4j.url; - -import java.io.Serializable; - -import com.sleepycat.persist.model.Entity; -import com.sleepycat.persist.model.PrimaryKey; - -/** - * @author Yasser Ganjisaffar - */ - -@Entity -public class WebURL implements Serializable { - - private static final long serialVersionUID = 1L; - - @PrimaryKey - private String url; - - private int docid; - private int parentDocid; - private String parentUrl; - private short depth; - private String domain; - private String subDomain; - private String path; - private String anchor; - private byte priority; - - /** - * Returns the unique document id assigned to this Url. - */ - public int getDocid() { - return docid; - } - - public void setDocid(int docid) { - this.docid = docid; - } - - @Override - public int hashCode() { - return url.hashCode(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - - WebURL otherUrl = (WebURL) o; - return url != null && url.equals(otherUrl.getURL()); - - } - - @Override - public String toString() { - return url; - } - - /** - * Returns the Url string - */ - public String getURL() { - return url; - } - - public void setURL(String url) { - this.url = url; - - int domainStartIdx = url.indexOf("//") + 2; - int domainEndIdx = url.indexOf('/', domainStartIdx); - domain = url.substring(domainStartIdx, domainEndIdx); - subDomain = ""; - String[] parts = domain.split("\\."); - if (parts.length > 2) { - domain = parts[parts.length - 2] + "." + parts[parts.length - 1]; - int limit = 2; - if (TLDList.getInstance().contains(domain)) { - domain = parts[parts.length - 3] + "." + domain; - limit = 3; - } - for (int i = 0; i < parts.length - limit; i++) { - if (subDomain.length() > 0) { - subDomain += "."; - } - subDomain += parts[i]; - } - } - path = url.substring(domainEndIdx); - int pathEndIdx = path.indexOf('?'); - if (pathEndIdx >= 0) { - path = path.substring(0, pathEndIdx); - } - } - - /** - * Returns the unique document id of the parent page. The parent page is the - * page in which the Url of this page is first observed. - */ - public int getParentDocid() { - return parentDocid; - } - - public void setParentDocid(int parentDocid) { - this.parentDocid = parentDocid; - } - - /** - * Returns the url of the parent page. The parent page is the page in which - * the Url of this page is first observed. - */ - public String getParentUrl() { - return parentUrl; - } - - public void setParentUrl(String parentUrl) { - this.parentUrl = parentUrl; - } - - /** - * Returns the crawl depth at which this Url is first observed. Seed Urls - * are at depth 0. Urls that are extracted from seed Urls are at depth 1, - * etc. - */ - public short getDepth() { - return depth; - } - - public void setDepth(short depth) { - this.depth = depth; - } - - /** - * Returns the domain of this Url. For 'http://www.example.com/sample.htm', - * domain will be 'example.com' - */ - public String getDomain() { - return domain; - } - - public String getSubDomain() { - return subDomain; - } - - /** - * Returns the path of this Url. For 'http://www.example.com/sample.htm', - * domain will be 'sample.htm' - */ - public String getPath() { - return path; - } - - public void setPath(String path) { - this.path = path; - } - - /** - * Returns the anchor string. For example, in A sample anchor - * the anchor string is 'A sample anchor' - */ - public String getAnchor() { - return anchor; - } - - public void setAnchor(String anchor) { - this.anchor = anchor; - } - - /** - * Returns the priority for crawling this URL. - * A lower number results in higher priority. - */ - public byte getPriority() { - return priority; - } - - public void setPriority(byte priority) { - this.priority = priority; - } - -} diff --git a/All/Genesis-OOB/Genesis#108/pair.info b/All/Genesis-OOB/Genesis#108/pair.info deleted file mode 100755 index 1102484..0000000 --- a/All/Genesis-OOB/Genesis#108/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:108 -SATName:Genesis -modifiedFPath:src/main/java/edu/uci/ics/crawler4j/url/WebURL.java -comSha:65954e3 -parentComSha:65954e3^1 -githubUrl:https://github.com/yasserg/crawler4j -repoName:yasserg#crawler4j \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#128/new/CHANGES.txt b/All/Genesis-OOB/Genesis#128/new/CHANGES.txt new file mode 100755 index 0000000..7083fc5 --- /dev/null +++ b/All/Genesis-OOB/Genesis#128/new/CHANGES.txt @@ -0,0 +1,1266 @@ +Release 1.5 - Current Development + + * Fixed invalid asterisks from master slide in PPT (TIKA-1171). + + * Added test cases to confirm handling of auto-date in PPT and PPTX (TIKA-817). + + * Text from tables in PPT files is once again extracted correctly (TIKA-1076). + + * Text is extracted from text boxes in XLSX (TIKA-1100). + + * Tika no longer hangs when processing Excel files with custom fraction format (TIKA-1132). + + * Disconcerting stacktrace from missing beans no longer printed for some DOCX files (TIKA-792). + + * Upgraded POI to 3.10-beta2 (TIKA-1173). + + * Upgraded PDFBox to 1.8.2 (TIKA-1153). + + * Made HtmlEncodingDetector more flexible in finding meta + header charset (TIKA-1001). + + * Added sanitized test HTML file for local file test (TIKA-1139). + + * Fixed bug that prevented attachments within a PDF from being processed + if the PDF itself was an attachment (TIKA-1124). + + * Text from paragraph-level structured document tags is now extracted (TIKA-1130). + + * RTF: Fixed ArrayIndexOutOfBoundsException when parsing list override (TIKA-1192). + +Release 1.4 - 06/15/2013 + + * Removed a test HTML file with a poorly chosen GPL text in it (TIKA-1129). + + * Improvements to tika-server to allow it to produce text/html and + text/xml content (TIKA-1126, TIKA-1127). + + * Improvements were made to the Compressor Parser to handle g'zipped files + that require the decompressConcatenated option set to true (TIKA-1096). + + * Addressed a typographic error that was preventing from detection of + awk files (TIKA-1081). + + * Added a new end-point to Tika's JAX-RS REST server that only detects + the media-type based on a small portion of the document submitted + (TIKA-1047). + + * RTF: Ordered and unordered lists are now extracted (TIKA-1062). + + * MP3: Audio duration is now extracted (TIKA-991) + + * Java .class files: upgraded from ASM 3.1 to ASM 4.1 for parsing + the Java bytecodes (TIKA-1053). + + * Mime Types: Definitions extended to optionally include Link (URL) and + UTI, along with details for several common formats (TIKA-1012 / TIKA-1083) + + * Exceptions when parsing OLE10 embedded documents, when parsing + summary information from Office documents, and when saving + embedded documennts in TikaCLI are now logged instead + of aborting extraction (TIKA-1074) + + * MS Word: line tabular character is now replaced with newline + (TIKA-1128) + + * XML: ElementMetadataHandlers can now optionally accept duplicate + and empty values (TIKA-1133) + +Release 1.3 - 01/19/2013 + + * Mimetype definitions added for more common programming languages, + including common extensions, but not magic patterns. (TIKA-1055) + + * MS Word: When a Word (.doc) document contains embedded files or + links to external documents, Tika now places a
placeholder into the XHTML so you can + see where in the main text the embedded document occurred + (TIKA-956, TIKA-1019). Embedded Wordpad/RTF documents are now + recognized (TIKA-982). + + * PDF: Text from pop-up annotations is now extracted (TIKA-981). + Text from bookmarks is now extracted (TIKA-1035). + + * PKCS7: Detached signatures no longer through NullPointerException + (TIKA-986). + + * iWork: The chart name for charts embedded in numbers documents is + now extracted (TIKA-918). + + * CLI: TikaCLI -m now handles multi-valued metadata keys correctly + (previously it only printed the first value). (TIKA-920) + + * MS Word (.docx): When a Word (.docx) document contains embedded + files, Tika now places a
into the + XHTML so you can see where in the main text the embedded document + occurred. The id (rId) is included in the Metadata of each + embedded document as the new Metadata.EMBEDDED_RELATIONSHIP_ID + key, and TikaCLI prepends the rId (if present) onto the filename + it extracts (TIKA-989). Fixed NullPointerException when style is + null (TIKA-1006). Text inside text boxes is now extracted + (TIKA-1005). + + * RTF: Page, word, character count and creation date metadata are + now extracted for RTF documents (TIKA-999). + + * MS PowerPoint (.pptx): When a PowerPoint (.pptx) document contains + embedded files, Tika now places a
into the + XHTML so you can see where in the main text the embedded document + occurred. The id (rId) is included in the Metadata of each + embedded document as the new Metadata.EMBEDDED_RELATIONSHIP_ID + key, and TikaCLI prepends the rId (if present) onto the filename + it extracts (TIKA-997, TIKA-1032). + + * MS PowerPoint (.ppt): When a PowerPoint (.ppt) document contains + embedded files, Tika now places a
into the + XHTML so you can see where in the main text the embedded document + occurred (TIKA-1025). Text from the master slide is now extracted + (TIKA-712). + + * MHTML: fixed Null charset name exception when a mime part has an + unrecognized charset (TIKA-1011). + + * MP3: if an ID3 tag was encoded in UTF-16 with only the BOM then on + certain JVMs this would incorrectly extract the BOM as the tag's + value (TIKA-1024). + + * ZIP: placeholders (
) are + now left in the XHTML so you can see where each archive member + appears (TIKA-1036). TikaCLI would hit FileNotFoundException when + extracting files that were under sub-directories from a ZIP + archive, because it failed to create the parent directories first + (TIKA-1031). + + * XML: a space character is now added before each element + (TIKA-1048) + +Release 1.2 - 07/10/2012 +--------------------------------- + + * Tika's JAX-RS based Network server now is based on Apache CXF, + which is available in Maven Central and now allows the server + module to be packaged and included in our release + (TIKA-593, TIKA-901). + + * Tika: parseToString now lets you specify the max string length + per-call, in addition to per-Tika-instance. (TIKA-870) + + * Tika now has the ability to detect FITS (Flexible Image Transport System) + files (TIKA-874). + + * Images: Fixed file handle leak in ImageParser. (TIKA-875) + + * iWork: Comments in Pages files are now extracted (TIKA-907). + Headers, footers and footnotes in Pages files are now extracted + (TIKA-906). Don't throw NullPointerException on passsword + protected iWork files, even though we can't parse their contents + yet (TIKA-903). Text extracted from Keynote text boxes and bullet + points no longer runs together (TIKA-910). Also extract text for + Pages documents created in layout mode (TIKA-904). Table names + are now extracted in Numbers documents (TIKA-924). Content added + to master slides is also extracted (TIKA-923). + + * Archive and compression formats: The Commons Compress dependency was + upgraded from 1.3 to 1.4.1. With this change Tika can now parse also + Unix dump archives and documents compressed using the XZ and Pack200 + compression formats. (TIKA-932) + + * KML: Tika now has basic support for Keyhole Markup Language documents + (KML and KMZ) used by tools like Google Earth. See also + http://www.opengeospatial.org/standards/kml/. (TIKA-941) + + * CLI: You can now use the TIKA_PASSWORD environment variable or the + --password=X command line option to specify the password that Tika CLI + should use for opening encrypted documents (TIKA-943). + + * Character encodings: Tika's character encoding detection mechanism was + improved by adding integration to the juniversalchardet library that + implements Mozilla's universal charset detection algorithm. The slower + ICU4J algorithms are still used as a fallback thanks to their wider + coverage of custom character encodings. (TIKA-322, TIKA-471) + + * Charset parameter: Related to the character encoding improvements + mentioned above, Tika now returns the detected character encoding as + a "charset" parameter of the content type metadata field for text/plain + and text/html documents. For example, instead of just "text/plain", the + returned content type will be something like "text/plain; charset=UTF-8" + for a UTF-8 encoded text document. Character encoding information is still + present also in the content encoding metadata field for backwards + compatibility, but that field should be considered deprecated. (TIKA-431) + + * Extraction of embedded resources from OLE2 Office Documents, where + the resource isn't another office document, has been fixed (TIKA-948) + +Release 1.1 - 3/7/2012 +--------------------------------- + + * Link Extraction: The rel attribute is now extracted from + links per the LinkConteHandler. (TIKA-824) + + * MP3: Fixed handling of UTF-16 (two byte) ID3v2 tags (previously + the last character in a UTF-16 tag could be corrupted) (TIKA-793) + + * Performance: Loading of the default media type registry is now + significantly faster. (TIKA-780) + + * PDF: Allow controlling whether overlapping duplicated text should + be removed. Disabling this (the default) can give big + speedups to text extraction and may workaround cases where + non-duplicated characters were incorrectly removed (TIKA-767). + Allow controlling whether text tokens should be sorted by their x/y + position before extracting text (TIKA-612); this is necessary for + certain PDFs. Fixed cases where too many

tags appear in the + XHTML output, causing NPE when opening some PDFs with the GUI + (TIKA-778). + + * RTF: Fixed case where a font change would result in processing + bytes in the wrong font's charset, producing bogus text output + (TIKA-777). Don't output whitespace in ignored group states, + avoiding excessive whitespace output (TIKA-781). Binary embedded + content (using \bin control word) is now skipped correctly; + previously it could cause the parser to incorrectly extract binary + content as text (TIKA-782). + + * CLI: New TikaCLI option "--list-detectors", which displays the + mimetype detectors that are available, similar to the existing + "--list-parsers" option for parsers. (TIKA-785). + + * Detectors: The order of detectors, as supplied via the service + registry loader, is now controlled. User supplied detectors are + prefered, then Tika detectors (such as the container aware ones), + and finally the core Tika MimeTypes is used as a backup. This + allows for specific, detailed detectors to take preference over + the default mime magic + filename detector. (TIKA-786) + + * Microsoft Project (MPP): Filetype detection has been fixed, + and basic metadata (but no text) is now extracted. (TIKA-789) + + * Outlook: fixed NullPointerException in TikaGUI when messages with + embedded RTF or HTML content were filtered (TIKA-801). + + * Ogg Vorbis and FLAC: Parser added for Ogg Vorbis and FLAC audio + files, which extract audio metadata and tags (TIKA-747) + + * MP4: Improved mime magic detection for MP4 based formats (including + QuickTime, MP4 Video and Audio, and 3GPP) (TIKA-851) + + * MP4: Basic metadata extracting parser for MP4 files added, which includes + limited audio and video metadata, along with the iTunes media metadata + (such as Artist and Title) (TIKA-852) + + * Document Passwords: A new ParseContext object, PasswordProvider, + has been added. This provides a way to supply the password for + a document during processing. Currently, only password protected + PDFs and Microsoft OOXML Files are supported. (TIKA-850) + +Release 1.0 - 11/4/2011 +--------------------------------- + +The most notable changes in Tika 1.0 over previous releases are: + + * API: All methods, classes and interfaces that were marked as + deprecated in Tika 0.10 have been removed to clean up the API + (TIKA-703). You may need to adjust and recompile client code + accordingly. The declared OSGi package versions are now 1.0, and + will thus not resolve for client bundles that still refer to 0.x + versions (TIKA-565). + + * Configuration: The context class loader of the current thread is + no longer used as the default for loading configured parser and + detector classes. You can still pass an explicit class loader + to the configuration mechanism to get the previous behaviour. + (TIKA-565) + + * OSGi: The tika-core bundle will now automatically pick up and use + any available Parser and Detector services when deployed to an OSGi + environment. The tika-parsers bundle provides such services based on + for all the supported file formats for which the upstream parser library + is available. If you don't want to track all the parser libraries as + separate OSGi bundles, you can use the tika-bundle bundle that packages + tika-parsers together with all its upstream dependencies. (TIKA-565) + + * RTF: Hyperlinks in RTF documents are now extracted as an ... element (TIKA-632). The RTF parser is also now + more robust when encountering too many closing {'s vs. opening {'s + (TIKA-733). + + * MS Word: From Word (.doc) documents we now extract optional hyphen + as Unicode zero-width space (U+200B), and non-breaking hyphen as + Unicode non-breaking hyphen (U+2011). (TIKA-711) + + * Outlook: Tika can now process also attachments in Outlook messages. + (TIKA-396) + + * MS Office: Performance of extracting embedded office docs was improved. + (TIKA-753) + + * PDF: The PDF parser now extracts paragraphs within each page + (TIKA-742) and can now optionally extract text from PDF + annotations (TIKA-738). There's also an option to enable (the + default) or disable auto-space insertion (TIKA-724). + + * Language detection: Tika can now detect Belarusian, Catalan, + Esperanto, Galician, Lithuanian (TIKA-582), Romanian, Slovak, + Slovenian, and Ukrainian (TIKA-681). + + * Java: Tika no longer ships retrotranslated Java 1.4 binaries along + with the normal ones that work with Java 5 and higher. (TIKA-744) + + * OpenOffice documents: header/footer text is now extracted for text, + presentation and spreadsheet documents (TIKA-736) + +Tika 1.0 relies on the following set of major dependencies (generated using +mvn dependency:tree from tika-parsers): + + org.apache.tika:tika-parsers:bundle:1.0 + +- org.apache.tika:tika-core:jar:1.0:compile + +- edu.ucar:netcdf:jar:4.2-min:compile + | \- org.slf4j:slf4j-api:jar:1.5.6:compile + +- org.apache.james:apache-mime4j-core:jar:0.7:compile + +- org.apache.james:apache-mime4j-dom:jar:0.7:compile + +- org.apache.commons:commons-compress:jar:1.3:compile + +- commons-codec:commons-codec:jar:1.5:compile + +- org.apache.pdfbox:pdfbox:jar:1.6.0:compile + | +- org.apache.pdfbox:fontbox:jar:1.6.0:compile + | +- org.apache.pdfbox:jempbox:jar:1.6.0:compile + | \- commons-logging:commons-logging:jar:1.1.1:compile + +- org.bouncycastle:bcmail-jdk15:jar:1.45:compile + +- org.bouncycastle:bcprov-jdk15:jar:1.45:compile + +- org.apache.poi:poi:jar:3.8-beta4:compile + +- org.apache.poi:poi-scratchpad:jar:3.8-beta4:compile + +- org.apache.poi:poi-ooxml:jar:3.8-beta4:compile + | +- org.apache.poi:poi-ooxml-schemas:jar:3.8-beta4:compile + | | \- org.apache.xmlbeans:xmlbeans:jar:2.3.0:compile + | \- dom4j:dom4j:jar:1.6.1:compile + +- org.apache.geronimo.specs:geronimo-stax-api_1.0_spec:jar:1.0.1:compile + +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2.1:compile + +- asm:asm:jar:3.1:compile + +- com.drewnoakes:metadata-extractor:jar:2.4.0-beta-1:compile + +- de.l3s.boilerpipe:boilerpipe:jar:1.1.0:compile + +- rome:rome:jar:0.9:compile + \- jdom:jdom:jar:1.0:compile + +The following people have contributed to Tika 1.0 by submitting or commenting +on the issues resolved in this release: + +Andrzej Bialecki +Antoni Mylka +Benson Margulies +Chris A. Mattmann +Cristian Vat +Dave Meikle +David Smiley +Dennis Adler +Erik Hetzner +Ingo Renner +Jeremias Maerki +Jeremy Anderson +Jeroen van Vianen +John Bartak +Jukka Zitting +Julien Nioche +Ken Krugler +Mark Butler +Maxim Valyanskiy +Michael Bryant +Michael McCandless +Nick Burch +Pablo Queixalos +Uwe Schindler +Žygimantas Medelis + + +See http://s.apache.org/Zk6 for more details on these contributions. + + +Release 0.10 - 09/25/2011 +------------------------- + +The most notable changes in Tika 0.10 over previous releases are: + + * A parser for CHM help files was added. (TIKA-245) + + * TIKA-698: Invalid characters are now replaced with the Unicode + replacement character (U+FFFD), whereas before such characters were + replaced with spaces, so you may need to change your processing of + Tika's output to now handle U+FFFD. + + * The RTF parser was rewritten to perform its own direct shallow + parse of the RTF content, instead of using RTFEditorKit from + javax.swing. This fixes several issues in the old parser, + including doubling of Unicode characters in certain cases + (TIKA-683), exceptions on mal-formed RTF docs (TIKA-666), and + missing text from some elements (header/footer, hyperlinks, + footnotes, text inside pictures). + + * Handling of temporary files within Tika was much improved + (TIKA-701, TIKA-654, TIKA-645, TIKA-153) + + * The Tika GUI got a facelift and some extra features (TIKA-635) + + * The apache-mime4j dependency of the email message parser was upgraded + from version 0.6 to 0.7 (TIKA-716). The parser also now accepts a + MimeConfig object in the ParseContext as configuration (TIKA-640). + +Tika 0.10 relies on the following set of major dependencies (generated using +mvn dependency:tree from tika-parsers): + + org.apache.tika:tika-parsers:bundle:0.10 + +- org.apache.tika:tika-core:jar:0.10:compile + +- edu.ucar:netcdf:jar:4.2-min:compile + | \- org.slf4j:slf4j-api:jar:1.5.6:compile + +- org.apache.james:apache-mime4j-core:jar:0.7:compile + +- org.apache.james:apache-mime4j-dom:jar:0.7:compile + +- org.apache.commons:commons-compress:jar:1.1:compile + +- commons-codec:commons-codec:jar:1.4:compile + +- org.apache.pdfbox:pdfbox:jar:1.6.0:compile + | +- org.apache.pdfbox:fontbox:jar:1.6.0:compile + | +- org.apache.pdfbox:jempbox:jar:1.6.0:compile + | \- commons-logging:commons-logging:jar:1.1.1:compile + +- org.bouncycastle:bcmail-jdk15:jar:1.45:compile + +- org.bouncycastle:bcprov-jdk15:jar:1.45:compile + +- org.apache.poi:poi:jar:3.8-beta4:compile + +- org.apache.poi:poi-scratchpad:jar:3.8-beta4:compile + +- org.apache.poi:poi-ooxml:jar:3.8-beta4:compile + | +- org.apache.poi:poi-ooxml-schemas:jar:3.8-beta4:compile + | | \- org.apache.xmlbeans:xmlbeans:jar:2.3.0:compile + | \- dom4j:dom4j:jar:1.6.1:compile + +- org.apache.geronimo.specs:geronimo-stax-api_1.0_spec:jar:1.0.1:compile + +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2.1:compile + +- asm:asm:jar:3.1:compile + +- com.drewnoakes:metadata-extractor:jar:2.4.0-beta-1:compile + +- de.l3s.boilerpipe:boilerpipe:jar:1.1.0:compile + +- rome:rome:jar:0.9:compile + \- jdom:jdom:jar:1.0:compile + +The following people have contributed to Tika 0.10 by submitting or commenting +on the issues resolved in this release: + + Alain Viret + Alex Ott + Alexander Chow + Andreas Kemkes + Andrew Khoury + Babak Farhang + Benjamin Douglas + Benson Margulies + Chris A. Mattmann + chris hudson + Chris Lott + Cristian Vat + Curt Arnold + Cynthia L Wong + Dave Brosius + David Benson + Enrico Donelli + Erik Hetzner + Erna de Groot + Gabriele Columbro + Gavin + Geoff Jarrad + Gregory Kanevsky + gunter rombauts + Henning Gross + Henri Bergius + Ingo Renner + Ingo Wiarda + Izaak Alpert + Jan H√∏ydahl + Jens Wilmer + Jeremy Anderson + Joseph Vychtrle + Joshua Turner + Jukka Zitting + Julien Nioche + Karl Heinz Marbaise + Ken Krugler + Kostya Gribov + Luciano Leggieri + Mads Hansen + Mark Butler + Matt Sheppard + Maxim Valyanskiy + Michael McCandless + Michael Pisula + Murad Shahid + Nick Burch + Oleg Tikhonov + Pablo Queixalos + Paul Jakubik + Raimund Merkert + Rajiv Kumar + Robert Trickey + Sami Siren + samraj + Selva Ganesan + Sjoerd Smeets + Stephen Duncan Jr + Tran Nam Quang + Uwe Schindler + Vitaliy Filippov + +See http://s.apache.org/vR for more details on these contributions. + + +Release 0.9 - 02/13/2011 +------------------------ + +The most notable changes in Tika 0.9 over previous releases are: + + * A critical bugfix preventing metadata from printing to the + command line when the underlying Parser didn't generate + XHTML output was fixed. (TIKA-596) + + * The 0.8 version of Tika included a NetCDF jar file that pulled + in tremendous amounts of redundant dependencies. This has + been addressed in Tika 0.9 by republishing a minimal NetCDF + jar and changing Tika to depend on that. (TIKA-556) + + * MIME detection for iWork, and OpenXML documents has been + improved. (TIKA-533, TIKA-562, TIKA-588) + + * A critical backwards incompatible bug in PDF parsing that + was introduced in Tika 0.8 has been fixed. (TIKA-548) + + * Support for forked parsing in separate processes was added. + (TIKA-416) + + * Tika's language identifier now supports the Lithuanian + language. (TIKA-582) + +Tika 0.9 relies on the following set of major dependencies (generated using +mvn dependency:tree from tika-parsers): + + org.apache.tika:tika-parsers:bundle:0.9 + +- org.apache.tika:tika-core:jar:0.9:compile + +- edu.ucar:netcdf:jar:4.2-min:compile + | \- org.slf4j:slf4j-api:jar:1.5.6:compile + +- commons-httpclient:commons-httpclient:jar:3.1:compile + | +- commons-logging:commons-logging:jar:1.1.1:compile (version managed from 1.0.4) + | \- commons-codec:commons-codec:jar:1.2:compile + +- org.apache.james:apache-mime4j:jar:0.6:compile + +- org.apache.commons:commons-compress:jar:1.1:compile + +- org.apache.pdfbox:pdfbox:jar:1.4.0:compile + | +- org.apache.pdfbox:fontbox:jar:1.4.0:compile + | \- org.apache.pdfbox:jempbox:jar:1.4.0:compile + +- org.bouncycastle:bcmail-jdk15:jar:1.45:compile + +- org.bouncycastle:bcprov-jdk15:jar:1.45:compile + +- org.apache.poi:poi:jar:3.7:compile + +- org.apache.poi:poi-scratchpad:jar:3.7:compile + +- org.apache.poi:poi-ooxml:jar:3.7:compile + | +- org.apache.poi:poi-ooxml-schemas:jar:3.7:compile + | | \- org.apache.xmlbeans:xmlbeans:jar:2.3.0:compile + | \- dom4j:dom4j:jar:1.6.1:compile + +- org.apache.geronimo.specs:geronimo-stax-api_1.0_spec:jar:1.0.1:compile + +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2:compile + +- asm:asm:jar:3.1:compile + +- com.drewnoakes:metadata-extractor:jar:2.4.0-beta-1:compile + +- de.l3s.boilerpipe:boilerpipe:jar:1.1.0:compile + +- rome:rome:jar:0.9:compile + \- jdom:jdom:jar:1.0:compile + +The following people have contributed to Tika 0.9 by submitting or commenting +on the issues resolved in this release: + + Alex Skochin + Alexander Chow + Antoine L. + Antoni Mylka + Benjamin Douglas + Benson Margulies + Chris A. Mattmann + Cristian Vat + Cyriel Vringer + David Benson + Erik Hetzner + Gabriel Miklos + Geoff Jarrad + Jukka Zitting + Ken Krugler + Kostya Gribov + Leszek Piotrowicz + Martijn van Groningen + Maxim Valyanskiy + Michel Tremblay + Nick Burch + paul + Paul Pearcy + Peter van Raamsdonk + Piotr Bartosiewicz + Reinhard Schwab + Scott Severtson + Shinsuke Sugaya + Staffan Olsson + Steve Kearns + Tom Klonikowski + ≈Ωygimantas Medelis + +See http://s.apache.org/qi for more details on these contributions. + + +Release 0.8 - 11/07/2010 +------------------------ + +The most notable changes in Tika 0.8 over previous releases are: + + * Language identification is now dynamically configurable, + managed via a config file loaded from the classpath. (TIKA-490) + + * Tika now supports parsing Feeds by wrapping the underlying + Rome library. (TIKA-466) + + * A quick-start guide for Tika parsing was contributed. (TIKA-464) + + * An approach for plumbing through XHTML attributes was added. (TIKA-379) + + * Media type hierarchy information is now taken into account when + selecting the best parser for a given input document. (TIKA-298) + + * Support for parsing common scientific data formats including netCDF + and HDF4/5 was added (TIKA-400 and TIKA-399). + + * Unit tests for Windows have been fixed, allowing TestParsers + to complete. (TIKA-398) + +Tika 0.8 relies on the following set of major dependencies (generated using +mvn dependency:tree from tika-parsers): + + org.apache.tika:tika-parsers:bundle:0.8 + +- org.apache.tika:tika-core:jar:0.8:compile + +- edu.ucar:netcdf:jar:4.2:compile + | \- org.slf4j:slf4j-api:jar:1.5.6:compile + +- commons-httpclient:commons-httpclient:jar:3.1:compile + | +- commons-logging:commons-logging:jar:1.1.1:compile (version managed from 1.0.4) + | \- commons-codec:commons-codec:jar:1.2:compile + +- org.apache.commons:commons-compress:jar:1.1:compile + +- org.apache.pdfbox:pdfbox:jar:1.3.1:compile + | +- org.apache.pdfbox:fontbox:jar:1.3.1:compile + | \- org.apache.pdfbox:jempbox:jar:1.3.1:compile + +- org.bouncycastle:bcmail-jdk15:jar:1.45:compile + +- org.bouncycastle:bcprov-jdk15:jar:1.45:compile + +- org.apache.poi:poi:jar:3.7:compile + +- org.apache.poi:poi-scratchpad:jar:3.7:compile + +- org.apache.poi:poi-ooxml:jar:3.7:compile + | +- org.apache.poi:poi-ooxml-schemas:jar:3.7:compile + | | \- org.apache.xmlbeans:xmlbeans:jar:2.3.0:compile + | \- dom4j:dom4j:jar:1.6.1:compile + +- org.apache.geronimo.specs:geronimo-stax-api_1.0_spec:jar:1.0.1:compile + +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2:compile + +- asm:asm:jar:3.1:compile + +- com.drewnoakes:metadata-extractor:jar:2.4.0-beta-1:compile + +- de.l3s.boilerpipe:boilerpipe:jar:1.1.0:compile + +- rome:rome:jar:0.9:compile + \- jdom:jdom:jar:1.0:compile + +The following people have contributed to Tika 0.8 by submitting or commenting +on the issues resolved in this release: + + ≈Åukasz Wiktor + Adam Wilmer + Alex Baranau + Alex Ott + Andr√© Ricardo + Andrey Barhatov + Andrey Sidorenko + Antoni Mylka + Arturo Beltran + Attila Kir√°ly + Brad Greenlee + Bruno Dumon + Chris A. Mattmann + Chris Bamford + Christophe Gourmelon + Dave Meikle + David Weekly + Dmitry Kuzmenko + Erik Hetzner + Geoff Jarrad + Gerd Bremer + Grant Ingersoll + Jan H√∏ydahl + Jean-Philippe Ricard + Jeremias Maerki + Joao Garcia + Jukka Zitting + Julien Nioche + Ken Krugler + Liam O'Boyle + Mads Hansen + Marcel May + Markus Goldbach + Martijn van Groningen + Maxim Valyanskiy + Mike Hays + Miroslav Pokorny + Nick Burch + Otis Gospodnetic + Peter van Raamsdonk + Peter Wolanin + Peter_Lenahan@ibi.com + Piotr Bartosiewicz + Radek + Rajiv Kumar + Reinhard Schwab + rick cameron + Robert Muir + Sanjeev Rao + Simon Tyler + Sjoerd Smeets + Slavomir Varchula + Staffan Olsson + Tom De Leu + Uwe Schindler + Victor Kazakov + +See http://s.apache.org/ab0 for more details on these contributions. + + +Release 0.7 - 3/31/2010 +----------------------- + +The most notable changes in Tika 0.7 over previous releases are: + + * MP3 file parsing was improved, including Channel and SampleRate + extraction and ID3v2 support (TIKA-368, TIKA-372). Further, audio + parsing mime detection was also improved for the MIDI format. (TIKA-199) + + * Tika no longer relies on X11 for its RTF parsing functionality. (TIKA-386) + + * A Thread-safe bug in the AutoDetectParser was discovered and + addressed. (TIKA-374) + + * Upgrade to PDFBox 1.0.0. The new PDFBox version improves PDF parsing + performance and fixes a number of text extraction issues. (TIKA-380) + +The following people have contributed to Tika 0.7 by submitting or commenting +on the issues resolved in this release: + + Adam Rauch + Benson Margulies + Brett S. + Chris A. Mattmann + Daan de Wit + Dave Meikle + Durville + Ingo Renner + Jukka Zitting + Ken Krugler + Kenny Neal + Markus Goldbach + Maxim Valyanskiy + Nick Burch + Sami Siren + Uwe Schindler + +See http://tinyurl.com/yklopby for more details on these contributions. + + +Release 0.6 - 01/20/2010 +------------------------ + +The most notable changes in Tika 0.6 over the previous release are: + + * Mime-type detection for HTML (and all types) has been improved, allowing malformed + HTML files and those HTML files that require a bit more observed content + before the type is properly detected, are now correctly identified by + the AutoDetectParser. (TIKA-327, TIKA-357, TIKA-366, TIKA-367) + + * Tika now has an additional OSGi bundle packaging that includes all the + required parser libraries. This bundle package makes it easy to use all + Tika features in an OSGi environment. (TIKA-340, TIKA-342) + + * The Apache POI dependency used for parsing Microsoft Office file formats + has been upgraded to version 3.6. The most visible improvement in this + version is the notably reduced ooxml jar file size. The tika-app jar size + is now down to 15MB from the 25MB in Tika 0.5. (TIKA-353) + + * Handling of character encoding information in input metadata and HTML + tags has been improved. When no applicable encoding information is + available, the encoding is detected by looking at the input data. + (TIKA-332, TIKA-334, TIKA-335, TIKA-341) + + * Some document types like Excel spreadsheets contain content like + numbers or formulas whose exact text format depends on the current locale. + So far Tika has used the platform default locale in such cases, but + clients can now explicitly specify the locale by passing a Locale instance + in the parse context. (TIKA-125) + + * The default text output encoding of the tika-app jar is now UTF-8 + when running on Mac OS X. This is because the default encoding used + by Java is not compatible with the console application in Mac OS X. + On all other platforms the text output from tika-app still uses + the platform default encoding. (TIKA-324) + + * A flash video (video/x-flv) parser has been added. (TIKA-328) + + * The handling of Number and Date cell formatting within the Microsoft Excel + documents has been added. This include currencies, percentages and + scientific formats. (TIKA-103) + +The following people have contributed to Tika 0.6 by submitting or commenting +on the issues resolved in this release: + + Andrzej Bialecki + Bertrand Delacretaz + Chris A. Mattmann + Dave Meikle + Erik Hetzner + Felix Meschberger + Jukka Zitting + Julien Nioche + Ken Krugler + Luke Nezda + Maxim Valyanskiy + Niall Pemberton + Peter Wolanin + Piotr B. + Sami Siren + Yuan-Fang Li + +See http://tinyurl.com/yc3dk67 for more details on these contributions. + + +Release 0.5 - 11/14/2009 +------------------------ + +The most notable changes in Tika 0.5 over the previous release are: + + * Improved RDF/OWL mime detection using both MIME magic as well as + pattern matching (TIKA-309) + + * An org.apache.tika.Tika facade class has been added to simplify common + text extraction and type detection use cases. (TIKA-269) + + * A new parse context argument was added to the Parser.parse() method. + This context map can be used to pass things like a delegate parser or + other settings to the parsing process. The previous parse() method + signature has been deprecated and will be removed in Tika 1.0. (TIKA-275) + + * A simple ngram-based language detection mechanism has been added along + with predefined language profiles for 18 languages. (TIKA-209) + + * The media type registry in Tika was synchronized with the MIME type + configuration in the Apache HTTP Server. Tika now knows about 1274 + different media types and can detect 672 of those using 927 file + extension and 280 magic byte patterns. (TIKA-285) + + * Tika now uses the Apache PDFBox version 0.8.0-incubating for parsing PDF + documents. This version is notably better than the 0.7.3 release used + earlier. (TIKA-158) + +The following people have contributed to Tika 0.5 by submitting or commenting +on the issues resolved in this release: + + Alex Baranov + Bart Hanssens + Benson Margulies + Chris A. Mattmann + Daan de Wit + Erik Hetzner + Frank Hellwig + Jeff Cadow + Joachim Zittmayr + Jukka Zitting + Julien Nioche + Ken Krugler + Maxim Valyanskiy + MRIT64 + Paul Borgermans + Piotr B. + Robert Newson + Sascha Szott + Ted Dunning + Thilo Goetz + Uwe Schindler + Yuan-Fang Li + +See http://tinyurl.com/yl9prwp for more details on these contributions. + + +Release 0.4 - 07/14/2009 +------------------------ + +The most notable changes in Tika 0.4 over the previous release are: + + * Tika has been split to three different components for increased + modularity. The tika-core component contains the key interfaces and + core functionality of Tika, tika-parsers contains all the adapters + to external parser libraries, and tika-app bundles everything together + in a single executable jar file. (TIKA-219) + + * All the three Tika components are packaged as OSGi bundles. (TIKA-228) + + * Tika now uses the new Commons Compress library for improved support + of compression and packaging formats like gzip, bzip2, tar, cpio, + ar, zip and jar. (TIKA-204) + + * The memory use of parsing Excel sheets with lots of numbers + has been considerably reduced. (TIKA-211) + + * The AutoDetectParser now has basic protection against "zip bomb" + attacks, where a specially crafted input document can expand to + practically infinite amount of output text. (TIKA-216) + + * The ParsingReader class can now use a thread pool or a more complex + execution model (java.util.concurrent.Executor) for the background + parsing task. (TIKA-215) + + * Automatic type detection of text- and XML-based documents has been + improved. (TIKA-225) + + * Charset detection functionality from the ICU4J library was inlined + in Tika to avoid the dependency to the large ICU4J jar. (TIKA-229) + + * Composite parsers like the AutoDetectParser now make sure that any + RuntimeExceptions, IOExceptions or SAXExceptions unrelated to the given + document stream or content handler are converted to TikaExceptions + before being passed to the client. (TIKA-198, TIKA-237) + +The following people have contributed to Tika 0.4 by submitting or commenting +on the issues resolved in this release: + + Chris A. Mattmann + Daan de Wit + Dave Meikle + David Weekly + Jeremias Maerki + Jonathan Koren + Jukka Zitting + Karl Heinz Marbaise + Keith R. Bennett + Maxim Valyanskiy + Niall Pemberton + Robert Burrell Donkin + Sami Siren + Siddharth Gargate + Uwe Schindler + +See http://tinyurl.com/mgv9o3 for more details on these contributions. + + +Release 0.3 - 03/09/2009 +------------------------ + +The most notable changes in Tika 0.3 over the previous release are: + + * Tika now supports mime type glob patterns specified using + standard JDK 1.4 (and beyond) syntax via the isregex attribute + on the glob tag. See: + + http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html + + for more information. (TIKA-194) + + * Tika now supports the Office Open XML format used by + Microsoft Office 2007. (TIKA-152) + + * All the metadata keys for Microsoft Office document properties are now + included as constants in the MSOffice interface. Clients should use + these constants instead of the raw string values to refer to specific + metadata items. (TIKA-186) + + * Automatic detection of document types in Tika has been improved. + For example Tika can now detect plain text just by looking at the first + few bytes of the document. (TIKA-154) + + * Tika now disables the loading of all external entities in XML files + that it parses as input documents. This improves security and avoids + problems with potentially broken references. (TIKA-185) + + * Tika now replaces all invalid XML characters in the extracted text + content with spaces. This prevents problems when output from Tika + is processed with XML tools. (TIKA-180) + + * The Tika CLI now correctly flushes its buffers when invoked with the + --text argument. This prevents the end of the text output from being + lost. (TIKA-179) + + * Embedded text in MIDI files is now extracted. For example many karaoke + files contain song lyrics embedded as MIDI text. + + * The text content of Microsoft Outlook message files no longer appears as + multiple copies in the extracted text. (TIKA-197) + + * The ParsingReader class now makes most document metadata available + already before any of the extracted text is consumed. This makes it + easier for example to construct Lucene Document instances that contain + both extracted text and metadata. (TIKA-203) + +See http://tinyurl.com/tika-0-3-changes for a list of all changes in Tika 0.3. + +The following people have contributed to Tika 0.3 by submitting or commenting +on the issues resolved in this release: + + Andrzej Rusin + Chris A. Mattmann + Dave Meikle + Georger Ara√∫jo + Guillermo Arribas + Jonathan Koren + Jukka Zitting + Karl Heinz Marbaise + Kumar Raja Jana + Paul Borgermans + Peter Becker + S√©bastien Michel + Uwe Schindler + +See http://tinyurl.com/tika-0-3-contributions for more details on +these contributions. + + +Release 0.2 - 12/04/2008 +------------------------ + +1. TIKA-109 - WordParser fails on some Word files (Dave Meikle) + +2. TIKA-105 - Excel parser implementation based on POI's Event API + (Niall Pemberton) + +3. TIKA-116 - Streaming parser for OpenDocument files (Jukka Zitting) + +4. TIKA-117 - Drop JDOM and Jaxen dependencies (Jukka Zitting) + +5. TIKA-115 - Tika package with all the dependencies (Jukka Zitting) + +6. TIKA-97 - Tika GUI (Jukka Zitting) + +7. TIKA-96 - Tika CLI (Jukka Zitting) + +8. TIKA-112 - Use Commons IO 1.4 (Jukka Zitting) + +9. TIKA-127 - Add support for Visio files (Jukka Zitting) + +10. TIKA-129 - node() support for the streaming XPath utility (Jukka Zitting) + +11. TIKA-130 - self-or-descendant axis does not match self in streaming XPath + (Jukka Zitting) + +12. TIKA-131 - Lazy XHTML prefix generation (Jukka Zitting) + +13. TIKA-128 - HTML parser should produce XHTML SAX events (Jukka Zitting) + +14. TIKA-133 - TeeContentHandler constructor should use varargs (Jukka Zitting) + +15. TIKA-132 - Refactor Excel extractor to parse per sheet and add + hyperlink support (Niall Pemberton) + +16. TIKA-134 - mvn package does not produce packages for bin/src + (Karl Heinz Marbaise) + +17. TIKA-138 - Ignore HTML style and script content (Jukka Zitting) + +18. TIKA-113 - Metadata (such as title) should not be part of content + (Jukka Zitting) + +19. TIKA-139 - Add a composite parser (Jukka Zitting) + +20. TIKA-142 - Include application/xhtml+xml as valid mime type for XMLParser + (mattmann) + +21. TIKA-143 - Add ParsingReader (Jukka Zitting) + +22. TIKA-144 - Upgrade nekohtml dependency (Jukka Zitting) + +23. TIKA-145 - Separate NOTICEs and LICENSEs for binary and source packages + (Jukka Zitting) + +24. TIKA-146 - Upgrade to POI 3.1 (Jukka Zitting) + +25. TIKA-99 - Support external parser programs (Jukka Zitting) + +26. TIKA-149 - Parser for Zip files (Dave Meikle & Jukka Zitting) + +27. TIKA-150 - Parser for tar files (Jukka Zitting) + +28. TIKA-151 - Stream compression support (Jukka Zitting) + +29. TIKA-156 - Some MIME magic patterns are ignored by MimeTypes + (Jukka Zitting) + +30. TIKA-155 - Java class file parser (Dave Brosius & Jukka Zitting) + +31. TIKA-108 - New Tika logos (Yongqian Li & Jukka Zitting) + +32. TIKA-120 - Add support for retrieving ID3 tags from MP3 files + (Dave Meikle & Jukka Zitting) + +33. TIKA-54 - Outlook msg parser + (Rida Benjelloun, Dave Meikle & Jukka Zitting) + +34. TIKA-114 - PDFParser : Getting content of the document using + "writer.ToString ()" , some words are stuck together + (Dave Meikle) + +35. TIKA-161 - Enable PMD reports (Jukka Zitting) + +36. TIKA-159 - Add support for parsing basic audio types: wav, aiff, au, midi + (Sami Siren) + +37. TIKA-140 - HTML parser unable to extract text + (Julien Nioche & Jukka Zitting) + +38. TIKA-163 - GUI does not support drag and drop in Gnome or KDE (Dave Meikle) + +39. TIKA-166 - Update HTMLParser to parse contents of meta tags (Dave Meikle) + +40. TIKA-164 - Upgrade of the nekohtml dependency to 1.9.9 (Jukka Zitting) + +41. TIKA-165 - Upgrade of the ICU4J dependency to version 3.8 (Jukka Zitting) + +42. TIKA-172 - New Open Document Parser that emits structured XHTML content + (Uwe Schindler & Jukka Zitting) + +43. TIKA-175 - Retrotranslate Tika for use in Java 1.4 environments (Jukka Zitting) + +44. TIKA-177 - Improvements to build instruction in README (Chris Hostetter & Jukka Zitting) + +45. TIKA-171 - New ContentHandler for plain text output that has no problem with + missing white space after XHTML block tags (Uwe Schindler & Jukka Zitting) + + +Release 0.1-incubating - 12/27/2007 +----------------------------------- + +1. TIKA-5 - Port Metadata Framework from Nutch (mattmann) + +2. TIKA-11 - Consolidate test classes into a src/test/java directory tree (mattmann) + +3. TIKA-15 - Utils.print does not print a Content having no value (jukka) + +4. TIKA-19 - org.apache.tika.TestParsers fails (bdelacretaz) + +5. TIKA-16 - Issues with data files used for testing by TestParsers (bdelacretaz) + +6. TIKA-14 - MimeTypeUtils.getMimeType() returns the default mime type for + .odt (Open Office) file (bdelacretaz) + +7. TIKA-12 - Add URL capability to MimeTypesUtils (jukka) + +8. TIKA-13 - Fix obsolete package names in config.xml (siren) + +9. TIKA-10 - Remove MimeInfoException catch clauses and import from TestParsers (siren) + +10. TIKA-8 - Replaced the jmimeinfo dependency with a trivial mime type detector (jukka) + +11. TIKA-7 - Added the Lius Lite code. Added missing dependencies to POM (jukka) + +12. TIKA-18 - "Office" interface should be renamed "MSOffice" (mattmann) + +13. TIKA-23 - Decouple Parser from ParserConfig (jukka) + +14. TIKA-6 - Port Nutch (or better) MimeType detection system into Tika (J. Charron & mattmann) + +15. TIKA-25 - Removed hardcoded reference to C:\oo.xml in OpenOfficeParser (K. Bennett & jukka) + +16. TIKA-17 - Need to support URL's for input resources. (K. Bennett & mattmann) + +17. TIKA-22 - Remove @author tags from the java source (mattmann) + +18. TIKA-21 - Simplified configuration code (jukka) + +19. TIKA-17 - Rename all "Lius" classes to be "Tika" classes (jukka) + +20. TIKA-30 - Added utility constructors to TikaConfig (K. Bennett & jukka) + +21. TIKA-28 - Rename config.xml to tika-config.xml or similar (mattmann) + +22. TIKA-26 - Use Map instead of List (jukka) + +23. TIKA-31 - protected Parser.parse(InputStream stream, + Iterable contents) (jukka & K. Bennett) + +24. TIKA-36 - A convenience method for getting a document's content's text + would be helpful (K. Bennett & mattmann) + +25. TIKA-33 - Stateless parsers (jukka) + +26. TIKA-38 - TXTParser adds a space to the content it reads from a file (K. Bennett & ridabenjelloun) + +27. TIKA-35 - Extract MsOffice properties, use RereadableInputStream devloped by K. Bennett (ridabenjelloun & K. Bennett) + +28. TIKA-39 - Excel parsing improvements (siren & ridabenjelloun) + +29. TIKA-34 - Provide a method that will return a default configuration + (TikaConfig) (K. Bennett & mattmann) + +30. TIKA-42 - Content class needs (String, String, String) constructor (K. Bennett) + +31. TIKA-43 - Parser interface (jukka) + +32. TIKA-47 - Remove TikaLogger (jukka) + +33. TIKA-46 - Use Metadata in Parser (jukka & mattmann) + +34. TIKA-48 - Merge MS Extractors and Parsers (jukka) + +35. TIKA-45 - RereadableInputStream needs to be able to read to + the end of the original stream on first rewind. (K. Bennett) + +36. TIKA-41 - Resource files occur twice in jar file. (jukka) + +37. TIKA-49 - Some files have old-style license headers, fixed (Robert Burrell Donkin & bdelacretaz) + +38. TIKA-51 - Leftover temp files after running Tika tests, fixed (bdelacretaz) + +39. TIKA-40 - Tika needs to support diverse character encodings (jukka) + +40. TIKA-55 - ParseUtils.getParser() method variants should have consistent parameter orders + (K. Bennett) + +41. TIKA-52 - RereadableInputStream needs to support not closing the input stream it wraps. + (K. Bennett via bdelacretaz) + +42. TIKA-53 - XHTML SAX events from parsers (jukka) + +43. TIKA-57 - Rename org.apache.tika.ms to org.apache.tika.parser.ms (jukka) + +44. TIKA-62 - Use TikaConfig.getDefaultConfig() instead of a hardcoded + config path in TestParsers (jukka) + +45. TIKA-58 - Replace jtidy html parser with nekohtml based parser (siren) + +46. TIKA-60 - Rename Microsoft parser classes (jukka) + +47. TIKA-63 - Avoid multiple passes over the input stream in Microsoft parsers + (jukka) + +48. TIKA-66 - Use Java 5 features in org.apache.tika.mime (jukka) + +49. TIKA-56 - Mime type detection fails with upper case file extensions such as "PDF" + (mattmann) + +50. TIKA-65 - Add encode detection support for HTML parser (siren) + +51. TIKA-68 - Add dummy parser classes to be used as sentinels (jukka) + +52. TIKA-67 - Add an auto-detecting Parser implementation (jukka) + +53. TIKA-70 - Better MIME information for the Open Document formats (jukka) + +54. TIKA-71 - Remove ParserConfig and ParserFactory (jukka) + +55. TIKA-83 - Create a org.apache.tika.sax package for SAX utilities (jukka) + +56. TIKA-84 - Add MimeTypes.getMimeType(InputStream) (jukka) + +57. TIKA-85 - Add glob patterns from the ASF svn:eol-style documentation (jukka) + +58. TIKA-100 - Structured PDF parsing (jukka) + +59. TIKA-101 - Improve site and build (mattmann) + +60. TIKA-102 - Parser implementations loading a large amount of content + into a single String could be problematic (Niall Pemberton) + +61. TIKA-107 - Remove use of assertions for argument checking (Niall Pemberton) + +62. TIKA-104 - Add utility methods to throw IOException with the caused + intialized (jukka & Niall Pemberton) + +63. TIKA-106 - Remove dependency on Jakarta ORO - use JDK 1.4 Regex + (Niall Pemberton) + +64. TIKA-111 - Missing license headers (jukka) + +65. TIKA-112 - XMLParser improvement (ridabenjelloun) diff --git a/All/Genesis-OOB/Genesis#128/old/CHANGES.txt b/All/Genesis-OOB/Genesis#128/old/CHANGES.txt new file mode 100755 index 0000000..f862f5c --- /dev/null +++ b/All/Genesis-OOB/Genesis#128/old/CHANGES.txt @@ -0,0 +1,1264 @@ +Release 1.5 - Current Development + + * Fixed invalid asterisks from master slide in PPT (TIKA-1171). + + * Added test cases to confirm handling of auto-date in PPT and PPTX (TIKA-817). + + * Text from tables in PPT files is once again extracted correctly (TIKA-1076). + + * Text is extracted from text boxes in XLSX (TIKA-1100). + + * Tika no longer hangs when processing Excel files with custom fraction format (TIKA-1132). + + * Disconcerting stacktrace from missing beans no longer printed for some DOCX files (TIKA-792). + + * Upgraded POI to 3.10-beta2 (TIKA-1173). + + * Upgraded PDFBox to 1.8.2 (TIKA-1153). + + * Made HtmlEncodingDetector more flexible in finding meta + header charset (TIKA-1001). + + * Added sanitized test HTML file for local file test (TIKA-1139). + + * Fixed bug that prevented attachments within a PDF from being processed + if the PDF itself was an attachment (TIKA-1124). + + * Text from paragraph-level structured document tags is now extracted (TIKA-1130). + +Release 1.4 - 06/15/2013 + + * Removed a test HTML file with a poorly chosen GPL text in it (TIKA-1129). + + * Improvements to tika-server to allow it to produce text/html and + text/xml content (TIKA-1126, TIKA-1127). + + * Improvements were made to the Compressor Parser to handle g'zipped files + that require the decompressConcatenated option set to true (TIKA-1096). + + * Addressed a typographic error that was preventing from detection of + awk files (TIKA-1081). + + * Added a new end-point to Tika's JAX-RS REST server that only detects + the media-type based on a small portion of the document submitted + (TIKA-1047). + + * RTF: Ordered and unordered lists are now extracted (TIKA-1062). + + * MP3: Audio duration is now extracted (TIKA-991) + + * Java .class files: upgraded from ASM 3.1 to ASM 4.1 for parsing + the Java bytecodes (TIKA-1053). + + * Mime Types: Definitions extended to optionally include Link (URL) and + UTI, along with details for several common formats (TIKA-1012 / TIKA-1083) + + * Exceptions when parsing OLE10 embedded documents, when parsing + summary information from Office documents, and when saving + embedded documennts in TikaCLI are now logged instead + of aborting extraction (TIKA-1074) + + * MS Word: line tabular character is now replaced with newline + (TIKA-1128) + + * XML: ElementMetadataHandlers can now optionally accept duplicate + and empty values (TIKA-1133) + +Release 1.3 - 01/19/2013 + + * Mimetype definitions added for more common programming languages, + including common extensions, but not magic patterns. (TIKA-1055) + + * MS Word: When a Word (.doc) document contains embedded files or + links to external documents, Tika now places a
placeholder into the XHTML so you can + see where in the main text the embedded document occurred + (TIKA-956, TIKA-1019). Embedded Wordpad/RTF documents are now + recognized (TIKA-982). + + * PDF: Text from pop-up annotations is now extracted (TIKA-981). + Text from bookmarks is now extracted (TIKA-1035). + + * PKCS7: Detached signatures no longer through NullPointerException + (TIKA-986). + + * iWork: The chart name for charts embedded in numbers documents is + now extracted (TIKA-918). + + * CLI: TikaCLI -m now handles multi-valued metadata keys correctly + (previously it only printed the first value). (TIKA-920) + + * MS Word (.docx): When a Word (.docx) document contains embedded + files, Tika now places a
into the + XHTML so you can see where in the main text the embedded document + occurred. The id (rId) is included in the Metadata of each + embedded document as the new Metadata.EMBEDDED_RELATIONSHIP_ID + key, and TikaCLI prepends the rId (if present) onto the filename + it extracts (TIKA-989). Fixed NullPointerException when style is + null (TIKA-1006). Text inside text boxes is now extracted + (TIKA-1005). + + * RTF: Page, word, character count and creation date metadata are + now extracted for RTF documents (TIKA-999). + + * MS PowerPoint (.pptx): When a PowerPoint (.pptx) document contains + embedded files, Tika now places a
into the + XHTML so you can see where in the main text the embedded document + occurred. The id (rId) is included in the Metadata of each + embedded document as the new Metadata.EMBEDDED_RELATIONSHIP_ID + key, and TikaCLI prepends the rId (if present) onto the filename + it extracts (TIKA-997, TIKA-1032). + + * MS PowerPoint (.ppt): When a PowerPoint (.ppt) document contains + embedded files, Tika now places a
into the + XHTML so you can see where in the main text the embedded document + occurred (TIKA-1025). Text from the master slide is now extracted + (TIKA-712). + + * MHTML: fixed Null charset name exception when a mime part has an + unrecognized charset (TIKA-1011). + + * MP3: if an ID3 tag was encoded in UTF-16 with only the BOM then on + certain JVMs this would incorrectly extract the BOM as the tag's + value (TIKA-1024). + + * ZIP: placeholders (
) are + now left in the XHTML so you can see where each archive member + appears (TIKA-1036). TikaCLI would hit FileNotFoundException when + extracting files that were under sub-directories from a ZIP + archive, because it failed to create the parent directories first + (TIKA-1031). + + * XML: a space character is now added before each element + (TIKA-1048) + +Release 1.2 - 07/10/2012 +--------------------------------- + + * Tika's JAX-RS based Network server now is based on Apache CXF, + which is available in Maven Central and now allows the server + module to be packaged and included in our release + (TIKA-593, TIKA-901). + + * Tika: parseToString now lets you specify the max string length + per-call, in addition to per-Tika-instance. (TIKA-870) + + * Tika now has the ability to detect FITS (Flexible Image Transport System) + files (TIKA-874). + + * Images: Fixed file handle leak in ImageParser. (TIKA-875) + + * iWork: Comments in Pages files are now extracted (TIKA-907). + Headers, footers and footnotes in Pages files are now extracted + (TIKA-906). Don't throw NullPointerException on passsword + protected iWork files, even though we can't parse their contents + yet (TIKA-903). Text extracted from Keynote text boxes and bullet + points no longer runs together (TIKA-910). Also extract text for + Pages documents created in layout mode (TIKA-904). Table names + are now extracted in Numbers documents (TIKA-924). Content added + to master slides is also extracted (TIKA-923). + + * Archive and compression formats: The Commons Compress dependency was + upgraded from 1.3 to 1.4.1. With this change Tika can now parse also + Unix dump archives and documents compressed using the XZ and Pack200 + compression formats. (TIKA-932) + + * KML: Tika now has basic support for Keyhole Markup Language documents + (KML and KMZ) used by tools like Google Earth. See also + http://www.opengeospatial.org/standards/kml/. (TIKA-941) + + * CLI: You can now use the TIKA_PASSWORD environment variable or the + --password=X command line option to specify the password that Tika CLI + should use for opening encrypted documents (TIKA-943). + + * Character encodings: Tika's character encoding detection mechanism was + improved by adding integration to the juniversalchardet library that + implements Mozilla's universal charset detection algorithm. The slower + ICU4J algorithms are still used as a fallback thanks to their wider + coverage of custom character encodings. (TIKA-322, TIKA-471) + + * Charset parameter: Related to the character encoding improvements + mentioned above, Tika now returns the detected character encoding as + a "charset" parameter of the content type metadata field for text/plain + and text/html documents. For example, instead of just "text/plain", the + returned content type will be something like "text/plain; charset=UTF-8" + for a UTF-8 encoded text document. Character encoding information is still + present also in the content encoding metadata field for backwards + compatibility, but that field should be considered deprecated. (TIKA-431) + + * Extraction of embedded resources from OLE2 Office Documents, where + the resource isn't another office document, has been fixed (TIKA-948) + +Release 1.1 - 3/7/2012 +--------------------------------- + + * Link Extraction: The rel attribute is now extracted from + links per the LinkConteHandler. (TIKA-824) + + * MP3: Fixed handling of UTF-16 (two byte) ID3v2 tags (previously + the last character in a UTF-16 tag could be corrupted) (TIKA-793) + + * Performance: Loading of the default media type registry is now + significantly faster. (TIKA-780) + + * PDF: Allow controlling whether overlapping duplicated text should + be removed. Disabling this (the default) can give big + speedups to text extraction and may workaround cases where + non-duplicated characters were incorrectly removed (TIKA-767). + Allow controlling whether text tokens should be sorted by their x/y + position before extracting text (TIKA-612); this is necessary for + certain PDFs. Fixed cases where too many

tags appear in the + XHTML output, causing NPE when opening some PDFs with the GUI + (TIKA-778). + + * RTF: Fixed case where a font change would result in processing + bytes in the wrong font's charset, producing bogus text output + (TIKA-777). Don't output whitespace in ignored group states, + avoiding excessive whitespace output (TIKA-781). Binary embedded + content (using \bin control word) is now skipped correctly; + previously it could cause the parser to incorrectly extract binary + content as text (TIKA-782). + + * CLI: New TikaCLI option "--list-detectors", which displays the + mimetype detectors that are available, similar to the existing + "--list-parsers" option for parsers. (TIKA-785). + + * Detectors: The order of detectors, as supplied via the service + registry loader, is now controlled. User supplied detectors are + prefered, then Tika detectors (such as the container aware ones), + and finally the core Tika MimeTypes is used as a backup. This + allows for specific, detailed detectors to take preference over + the default mime magic + filename detector. (TIKA-786) + + * Microsoft Project (MPP): Filetype detection has been fixed, + and basic metadata (but no text) is now extracted. (TIKA-789) + + * Outlook: fixed NullPointerException in TikaGUI when messages with + embedded RTF or HTML content were filtered (TIKA-801). + + * Ogg Vorbis and FLAC: Parser added for Ogg Vorbis and FLAC audio + files, which extract audio metadata and tags (TIKA-747) + + * MP4: Improved mime magic detection for MP4 based formats (including + QuickTime, MP4 Video and Audio, and 3GPP) (TIKA-851) + + * MP4: Basic metadata extracting parser for MP4 files added, which includes + limited audio and video metadata, along with the iTunes media metadata + (such as Artist and Title) (TIKA-852) + + * Document Passwords: A new ParseContext object, PasswordProvider, + has been added. This provides a way to supply the password for + a document during processing. Currently, only password protected + PDFs and Microsoft OOXML Files are supported. (TIKA-850) + +Release 1.0 - 11/4/2011 +--------------------------------- + +The most notable changes in Tika 1.0 over previous releases are: + + * API: All methods, classes and interfaces that were marked as + deprecated in Tika 0.10 have been removed to clean up the API + (TIKA-703). You may need to adjust and recompile client code + accordingly. The declared OSGi package versions are now 1.0, and + will thus not resolve for client bundles that still refer to 0.x + versions (TIKA-565). + + * Configuration: The context class loader of the current thread is + no longer used as the default for loading configured parser and + detector classes. You can still pass an explicit class loader + to the configuration mechanism to get the previous behaviour. + (TIKA-565) + + * OSGi: The tika-core bundle will now automatically pick up and use + any available Parser and Detector services when deployed to an OSGi + environment. The tika-parsers bundle provides such services based on + for all the supported file formats for which the upstream parser library + is available. If you don't want to track all the parser libraries as + separate OSGi bundles, you can use the tika-bundle bundle that packages + tika-parsers together with all its upstream dependencies. (TIKA-565) + + * RTF: Hyperlinks in RTF documents are now extracted as an ... element (TIKA-632). The RTF parser is also now + more robust when encountering too many closing {'s vs. opening {'s + (TIKA-733). + + * MS Word: From Word (.doc) documents we now extract optional hyphen + as Unicode zero-width space (U+200B), and non-breaking hyphen as + Unicode non-breaking hyphen (U+2011). (TIKA-711) + + * Outlook: Tika can now process also attachments in Outlook messages. + (TIKA-396) + + * MS Office: Performance of extracting embedded office docs was improved. + (TIKA-753) + + * PDF: The PDF parser now extracts paragraphs within each page + (TIKA-742) and can now optionally extract text from PDF + annotations (TIKA-738). There's also an option to enable (the + default) or disable auto-space insertion (TIKA-724). + + * Language detection: Tika can now detect Belarusian, Catalan, + Esperanto, Galician, Lithuanian (TIKA-582), Romanian, Slovak, + Slovenian, and Ukrainian (TIKA-681). + + * Java: Tika no longer ships retrotranslated Java 1.4 binaries along + with the normal ones that work with Java 5 and higher. (TIKA-744) + + * OpenOffice documents: header/footer text is now extracted for text, + presentation and spreadsheet documents (TIKA-736) + +Tika 1.0 relies on the following set of major dependencies (generated using +mvn dependency:tree from tika-parsers): + + org.apache.tika:tika-parsers:bundle:1.0 + +- org.apache.tika:tika-core:jar:1.0:compile + +- edu.ucar:netcdf:jar:4.2-min:compile + | \- org.slf4j:slf4j-api:jar:1.5.6:compile + +- org.apache.james:apache-mime4j-core:jar:0.7:compile + +- org.apache.james:apache-mime4j-dom:jar:0.7:compile + +- org.apache.commons:commons-compress:jar:1.3:compile + +- commons-codec:commons-codec:jar:1.5:compile + +- org.apache.pdfbox:pdfbox:jar:1.6.0:compile + | +- org.apache.pdfbox:fontbox:jar:1.6.0:compile + | +- org.apache.pdfbox:jempbox:jar:1.6.0:compile + | \- commons-logging:commons-logging:jar:1.1.1:compile + +- org.bouncycastle:bcmail-jdk15:jar:1.45:compile + +- org.bouncycastle:bcprov-jdk15:jar:1.45:compile + +- org.apache.poi:poi:jar:3.8-beta4:compile + +- org.apache.poi:poi-scratchpad:jar:3.8-beta4:compile + +- org.apache.poi:poi-ooxml:jar:3.8-beta4:compile + | +- org.apache.poi:poi-ooxml-schemas:jar:3.8-beta4:compile + | | \- org.apache.xmlbeans:xmlbeans:jar:2.3.0:compile + | \- dom4j:dom4j:jar:1.6.1:compile + +- org.apache.geronimo.specs:geronimo-stax-api_1.0_spec:jar:1.0.1:compile + +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2.1:compile + +- asm:asm:jar:3.1:compile + +- com.drewnoakes:metadata-extractor:jar:2.4.0-beta-1:compile + +- de.l3s.boilerpipe:boilerpipe:jar:1.1.0:compile + +- rome:rome:jar:0.9:compile + \- jdom:jdom:jar:1.0:compile + +The following people have contributed to Tika 1.0 by submitting or commenting +on the issues resolved in this release: + +Andrzej Bialecki +Antoni Mylka +Benson Margulies +Chris A. Mattmann +Cristian Vat +Dave Meikle +David Smiley +Dennis Adler +Erik Hetzner +Ingo Renner +Jeremias Maerki +Jeremy Anderson +Jeroen van Vianen +John Bartak +Jukka Zitting +Julien Nioche +Ken Krugler +Mark Butler +Maxim Valyanskiy +Michael Bryant +Michael McCandless +Nick Burch +Pablo Queixalos +Uwe Schindler +Žygimantas Medelis + + +See http://s.apache.org/Zk6 for more details on these contributions. + + +Release 0.10 - 09/25/2011 +------------------------- + +The most notable changes in Tika 0.10 over previous releases are: + + * A parser for CHM help files was added. (TIKA-245) + + * TIKA-698: Invalid characters are now replaced with the Unicode + replacement character (U+FFFD), whereas before such characters were + replaced with spaces, so you may need to change your processing of + Tika's output to now handle U+FFFD. + + * The RTF parser was rewritten to perform its own direct shallow + parse of the RTF content, instead of using RTFEditorKit from + javax.swing. This fixes several issues in the old parser, + including doubling of Unicode characters in certain cases + (TIKA-683), exceptions on mal-formed RTF docs (TIKA-666), and + missing text from some elements (header/footer, hyperlinks, + footnotes, text inside pictures). + + * Handling of temporary files within Tika was much improved + (TIKA-701, TIKA-654, TIKA-645, TIKA-153) + + * The Tika GUI got a facelift and some extra features (TIKA-635) + + * The apache-mime4j dependency of the email message parser was upgraded + from version 0.6 to 0.7 (TIKA-716). The parser also now accepts a + MimeConfig object in the ParseContext as configuration (TIKA-640). + +Tika 0.10 relies on the following set of major dependencies (generated using +mvn dependency:tree from tika-parsers): + + org.apache.tika:tika-parsers:bundle:0.10 + +- org.apache.tika:tika-core:jar:0.10:compile + +- edu.ucar:netcdf:jar:4.2-min:compile + | \- org.slf4j:slf4j-api:jar:1.5.6:compile + +- org.apache.james:apache-mime4j-core:jar:0.7:compile + +- org.apache.james:apache-mime4j-dom:jar:0.7:compile + +- org.apache.commons:commons-compress:jar:1.1:compile + +- commons-codec:commons-codec:jar:1.4:compile + +- org.apache.pdfbox:pdfbox:jar:1.6.0:compile + | +- org.apache.pdfbox:fontbox:jar:1.6.0:compile + | +- org.apache.pdfbox:jempbox:jar:1.6.0:compile + | \- commons-logging:commons-logging:jar:1.1.1:compile + +- org.bouncycastle:bcmail-jdk15:jar:1.45:compile + +- org.bouncycastle:bcprov-jdk15:jar:1.45:compile + +- org.apache.poi:poi:jar:3.8-beta4:compile + +- org.apache.poi:poi-scratchpad:jar:3.8-beta4:compile + +- org.apache.poi:poi-ooxml:jar:3.8-beta4:compile + | +- org.apache.poi:poi-ooxml-schemas:jar:3.8-beta4:compile + | | \- org.apache.xmlbeans:xmlbeans:jar:2.3.0:compile + | \- dom4j:dom4j:jar:1.6.1:compile + +- org.apache.geronimo.specs:geronimo-stax-api_1.0_spec:jar:1.0.1:compile + +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2.1:compile + +- asm:asm:jar:3.1:compile + +- com.drewnoakes:metadata-extractor:jar:2.4.0-beta-1:compile + +- de.l3s.boilerpipe:boilerpipe:jar:1.1.0:compile + +- rome:rome:jar:0.9:compile + \- jdom:jdom:jar:1.0:compile + +The following people have contributed to Tika 0.10 by submitting or commenting +on the issues resolved in this release: + + Alain Viret + Alex Ott + Alexander Chow + Andreas Kemkes + Andrew Khoury + Babak Farhang + Benjamin Douglas + Benson Margulies + Chris A. Mattmann + chris hudson + Chris Lott + Cristian Vat + Curt Arnold + Cynthia L Wong + Dave Brosius + David Benson + Enrico Donelli + Erik Hetzner + Erna de Groot + Gabriele Columbro + Gavin + Geoff Jarrad + Gregory Kanevsky + gunter rombauts + Henning Gross + Henri Bergius + Ingo Renner + Ingo Wiarda + Izaak Alpert + Jan H√∏ydahl + Jens Wilmer + Jeremy Anderson + Joseph Vychtrle + Joshua Turner + Jukka Zitting + Julien Nioche + Karl Heinz Marbaise + Ken Krugler + Kostya Gribov + Luciano Leggieri + Mads Hansen + Mark Butler + Matt Sheppard + Maxim Valyanskiy + Michael McCandless + Michael Pisula + Murad Shahid + Nick Burch + Oleg Tikhonov + Pablo Queixalos + Paul Jakubik + Raimund Merkert + Rajiv Kumar + Robert Trickey + Sami Siren + samraj + Selva Ganesan + Sjoerd Smeets + Stephen Duncan Jr + Tran Nam Quang + Uwe Schindler + Vitaliy Filippov + +See http://s.apache.org/vR for more details on these contributions. + + +Release 0.9 - 02/13/2011 +------------------------ + +The most notable changes in Tika 0.9 over previous releases are: + + * A critical bugfix preventing metadata from printing to the + command line when the underlying Parser didn't generate + XHTML output was fixed. (TIKA-596) + + * The 0.8 version of Tika included a NetCDF jar file that pulled + in tremendous amounts of redundant dependencies. This has + been addressed in Tika 0.9 by republishing a minimal NetCDF + jar and changing Tika to depend on that. (TIKA-556) + + * MIME detection for iWork, and OpenXML documents has been + improved. (TIKA-533, TIKA-562, TIKA-588) + + * A critical backwards incompatible bug in PDF parsing that + was introduced in Tika 0.8 has been fixed. (TIKA-548) + + * Support for forked parsing in separate processes was added. + (TIKA-416) + + * Tika's language identifier now supports the Lithuanian + language. (TIKA-582) + +Tika 0.9 relies on the following set of major dependencies (generated using +mvn dependency:tree from tika-parsers): + + org.apache.tika:tika-parsers:bundle:0.9 + +- org.apache.tika:tika-core:jar:0.9:compile + +- edu.ucar:netcdf:jar:4.2-min:compile + | \- org.slf4j:slf4j-api:jar:1.5.6:compile + +- commons-httpclient:commons-httpclient:jar:3.1:compile + | +- commons-logging:commons-logging:jar:1.1.1:compile (version managed from 1.0.4) + | \- commons-codec:commons-codec:jar:1.2:compile + +- org.apache.james:apache-mime4j:jar:0.6:compile + +- org.apache.commons:commons-compress:jar:1.1:compile + +- org.apache.pdfbox:pdfbox:jar:1.4.0:compile + | +- org.apache.pdfbox:fontbox:jar:1.4.0:compile + | \- org.apache.pdfbox:jempbox:jar:1.4.0:compile + +- org.bouncycastle:bcmail-jdk15:jar:1.45:compile + +- org.bouncycastle:bcprov-jdk15:jar:1.45:compile + +- org.apache.poi:poi:jar:3.7:compile + +- org.apache.poi:poi-scratchpad:jar:3.7:compile + +- org.apache.poi:poi-ooxml:jar:3.7:compile + | +- org.apache.poi:poi-ooxml-schemas:jar:3.7:compile + | | \- org.apache.xmlbeans:xmlbeans:jar:2.3.0:compile + | \- dom4j:dom4j:jar:1.6.1:compile + +- org.apache.geronimo.specs:geronimo-stax-api_1.0_spec:jar:1.0.1:compile + +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2:compile + +- asm:asm:jar:3.1:compile + +- com.drewnoakes:metadata-extractor:jar:2.4.0-beta-1:compile + +- de.l3s.boilerpipe:boilerpipe:jar:1.1.0:compile + +- rome:rome:jar:0.9:compile + \- jdom:jdom:jar:1.0:compile + +The following people have contributed to Tika 0.9 by submitting or commenting +on the issues resolved in this release: + + Alex Skochin + Alexander Chow + Antoine L. + Antoni Mylka + Benjamin Douglas + Benson Margulies + Chris A. Mattmann + Cristian Vat + Cyriel Vringer + David Benson + Erik Hetzner + Gabriel Miklos + Geoff Jarrad + Jukka Zitting + Ken Krugler + Kostya Gribov + Leszek Piotrowicz + Martijn van Groningen + Maxim Valyanskiy + Michel Tremblay + Nick Burch + paul + Paul Pearcy + Peter van Raamsdonk + Piotr Bartosiewicz + Reinhard Schwab + Scott Severtson + Shinsuke Sugaya + Staffan Olsson + Steve Kearns + Tom Klonikowski + ≈Ωygimantas Medelis + +See http://s.apache.org/qi for more details on these contributions. + + +Release 0.8 - 11/07/2010 +------------------------ + +The most notable changes in Tika 0.8 over previous releases are: + + * Language identification is now dynamically configurable, + managed via a config file loaded from the classpath. (TIKA-490) + + * Tika now supports parsing Feeds by wrapping the underlying + Rome library. (TIKA-466) + + * A quick-start guide for Tika parsing was contributed. (TIKA-464) + + * An approach for plumbing through XHTML attributes was added. (TIKA-379) + + * Media type hierarchy information is now taken into account when + selecting the best parser for a given input document. (TIKA-298) + + * Support for parsing common scientific data formats including netCDF + and HDF4/5 was added (TIKA-400 and TIKA-399). + + * Unit tests for Windows have been fixed, allowing TestParsers + to complete. (TIKA-398) + +Tika 0.8 relies on the following set of major dependencies (generated using +mvn dependency:tree from tika-parsers): + + org.apache.tika:tika-parsers:bundle:0.8 + +- org.apache.tika:tika-core:jar:0.8:compile + +- edu.ucar:netcdf:jar:4.2:compile + | \- org.slf4j:slf4j-api:jar:1.5.6:compile + +- commons-httpclient:commons-httpclient:jar:3.1:compile + | +- commons-logging:commons-logging:jar:1.1.1:compile (version managed from 1.0.4) + | \- commons-codec:commons-codec:jar:1.2:compile + +- org.apache.commons:commons-compress:jar:1.1:compile + +- org.apache.pdfbox:pdfbox:jar:1.3.1:compile + | +- org.apache.pdfbox:fontbox:jar:1.3.1:compile + | \- org.apache.pdfbox:jempbox:jar:1.3.1:compile + +- org.bouncycastle:bcmail-jdk15:jar:1.45:compile + +- org.bouncycastle:bcprov-jdk15:jar:1.45:compile + +- org.apache.poi:poi:jar:3.7:compile + +- org.apache.poi:poi-scratchpad:jar:3.7:compile + +- org.apache.poi:poi-ooxml:jar:3.7:compile + | +- org.apache.poi:poi-ooxml-schemas:jar:3.7:compile + | | \- org.apache.xmlbeans:xmlbeans:jar:2.3.0:compile + | \- dom4j:dom4j:jar:1.6.1:compile + +- org.apache.geronimo.specs:geronimo-stax-api_1.0_spec:jar:1.0.1:compile + +- org.ccil.cowan.tagsoup:tagsoup:jar:1.2:compile + +- asm:asm:jar:3.1:compile + +- com.drewnoakes:metadata-extractor:jar:2.4.0-beta-1:compile + +- de.l3s.boilerpipe:boilerpipe:jar:1.1.0:compile + +- rome:rome:jar:0.9:compile + \- jdom:jdom:jar:1.0:compile + +The following people have contributed to Tika 0.8 by submitting or commenting +on the issues resolved in this release: + + ≈Åukasz Wiktor + Adam Wilmer + Alex Baranau + Alex Ott + Andr√© Ricardo + Andrey Barhatov + Andrey Sidorenko + Antoni Mylka + Arturo Beltran + Attila Kir√°ly + Brad Greenlee + Bruno Dumon + Chris A. Mattmann + Chris Bamford + Christophe Gourmelon + Dave Meikle + David Weekly + Dmitry Kuzmenko + Erik Hetzner + Geoff Jarrad + Gerd Bremer + Grant Ingersoll + Jan H√∏ydahl + Jean-Philippe Ricard + Jeremias Maerki + Joao Garcia + Jukka Zitting + Julien Nioche + Ken Krugler + Liam O'Boyle + Mads Hansen + Marcel May + Markus Goldbach + Martijn van Groningen + Maxim Valyanskiy + Mike Hays + Miroslav Pokorny + Nick Burch + Otis Gospodnetic + Peter van Raamsdonk + Peter Wolanin + Peter_Lenahan@ibi.com + Piotr Bartosiewicz + Radek + Rajiv Kumar + Reinhard Schwab + rick cameron + Robert Muir + Sanjeev Rao + Simon Tyler + Sjoerd Smeets + Slavomir Varchula + Staffan Olsson + Tom De Leu + Uwe Schindler + Victor Kazakov + +See http://s.apache.org/ab0 for more details on these contributions. + + +Release 0.7 - 3/31/2010 +----------------------- + +The most notable changes in Tika 0.7 over previous releases are: + + * MP3 file parsing was improved, including Channel and SampleRate + extraction and ID3v2 support (TIKA-368, TIKA-372). Further, audio + parsing mime detection was also improved for the MIDI format. (TIKA-199) + + * Tika no longer relies on X11 for its RTF parsing functionality. (TIKA-386) + + * A Thread-safe bug in the AutoDetectParser was discovered and + addressed. (TIKA-374) + + * Upgrade to PDFBox 1.0.0. The new PDFBox version improves PDF parsing + performance and fixes a number of text extraction issues. (TIKA-380) + +The following people have contributed to Tika 0.7 by submitting or commenting +on the issues resolved in this release: + + Adam Rauch + Benson Margulies + Brett S. + Chris A. Mattmann + Daan de Wit + Dave Meikle + Durville + Ingo Renner + Jukka Zitting + Ken Krugler + Kenny Neal + Markus Goldbach + Maxim Valyanskiy + Nick Burch + Sami Siren + Uwe Schindler + +See http://tinyurl.com/yklopby for more details on these contributions. + + +Release 0.6 - 01/20/2010 +------------------------ + +The most notable changes in Tika 0.6 over the previous release are: + + * Mime-type detection for HTML (and all types) has been improved, allowing malformed + HTML files and those HTML files that require a bit more observed content + before the type is properly detected, are now correctly identified by + the AutoDetectParser. (TIKA-327, TIKA-357, TIKA-366, TIKA-367) + + * Tika now has an additional OSGi bundle packaging that includes all the + required parser libraries. This bundle package makes it easy to use all + Tika features in an OSGi environment. (TIKA-340, TIKA-342) + + * The Apache POI dependency used for parsing Microsoft Office file formats + has been upgraded to version 3.6. The most visible improvement in this + version is the notably reduced ooxml jar file size. The tika-app jar size + is now down to 15MB from the 25MB in Tika 0.5. (TIKA-353) + + * Handling of character encoding information in input metadata and HTML + tags has been improved. When no applicable encoding information is + available, the encoding is detected by looking at the input data. + (TIKA-332, TIKA-334, TIKA-335, TIKA-341) + + * Some document types like Excel spreadsheets contain content like + numbers or formulas whose exact text format depends on the current locale. + So far Tika has used the platform default locale in such cases, but + clients can now explicitly specify the locale by passing a Locale instance + in the parse context. (TIKA-125) + + * The default text output encoding of the tika-app jar is now UTF-8 + when running on Mac OS X. This is because the default encoding used + by Java is not compatible with the console application in Mac OS X. + On all other platforms the text output from tika-app still uses + the platform default encoding. (TIKA-324) + + * A flash video (video/x-flv) parser has been added. (TIKA-328) + + * The handling of Number and Date cell formatting within the Microsoft Excel + documents has been added. This include currencies, percentages and + scientific formats. (TIKA-103) + +The following people have contributed to Tika 0.6 by submitting or commenting +on the issues resolved in this release: + + Andrzej Bialecki + Bertrand Delacretaz + Chris A. Mattmann + Dave Meikle + Erik Hetzner + Felix Meschberger + Jukka Zitting + Julien Nioche + Ken Krugler + Luke Nezda + Maxim Valyanskiy + Niall Pemberton + Peter Wolanin + Piotr B. + Sami Siren + Yuan-Fang Li + +See http://tinyurl.com/yc3dk67 for more details on these contributions. + + +Release 0.5 - 11/14/2009 +------------------------ + +The most notable changes in Tika 0.5 over the previous release are: + + * Improved RDF/OWL mime detection using both MIME magic as well as + pattern matching (TIKA-309) + + * An org.apache.tika.Tika facade class has been added to simplify common + text extraction and type detection use cases. (TIKA-269) + + * A new parse context argument was added to the Parser.parse() method. + This context map can be used to pass things like a delegate parser or + other settings to the parsing process. The previous parse() method + signature has been deprecated and will be removed in Tika 1.0. (TIKA-275) + + * A simple ngram-based language detection mechanism has been added along + with predefined language profiles for 18 languages. (TIKA-209) + + * The media type registry in Tika was synchronized with the MIME type + configuration in the Apache HTTP Server. Tika now knows about 1274 + different media types and can detect 672 of those using 927 file + extension and 280 magic byte patterns. (TIKA-285) + + * Tika now uses the Apache PDFBox version 0.8.0-incubating for parsing PDF + documents. This version is notably better than the 0.7.3 release used + earlier. (TIKA-158) + +The following people have contributed to Tika 0.5 by submitting or commenting +on the issues resolved in this release: + + Alex Baranov + Bart Hanssens + Benson Margulies + Chris A. Mattmann + Daan de Wit + Erik Hetzner + Frank Hellwig + Jeff Cadow + Joachim Zittmayr + Jukka Zitting + Julien Nioche + Ken Krugler + Maxim Valyanskiy + MRIT64 + Paul Borgermans + Piotr B. + Robert Newson + Sascha Szott + Ted Dunning + Thilo Goetz + Uwe Schindler + Yuan-Fang Li + +See http://tinyurl.com/yl9prwp for more details on these contributions. + + +Release 0.4 - 07/14/2009 +------------------------ + +The most notable changes in Tika 0.4 over the previous release are: + + * Tika has been split to three different components for increased + modularity. The tika-core component contains the key interfaces and + core functionality of Tika, tika-parsers contains all the adapters + to external parser libraries, and tika-app bundles everything together + in a single executable jar file. (TIKA-219) + + * All the three Tika components are packaged as OSGi bundles. (TIKA-228) + + * Tika now uses the new Commons Compress library for improved support + of compression and packaging formats like gzip, bzip2, tar, cpio, + ar, zip and jar. (TIKA-204) + + * The memory use of parsing Excel sheets with lots of numbers + has been considerably reduced. (TIKA-211) + + * The AutoDetectParser now has basic protection against "zip bomb" + attacks, where a specially crafted input document can expand to + practically infinite amount of output text. (TIKA-216) + + * The ParsingReader class can now use a thread pool or a more complex + execution model (java.util.concurrent.Executor) for the background + parsing task. (TIKA-215) + + * Automatic type detection of text- and XML-based documents has been + improved. (TIKA-225) + + * Charset detection functionality from the ICU4J library was inlined + in Tika to avoid the dependency to the large ICU4J jar. (TIKA-229) + + * Composite parsers like the AutoDetectParser now make sure that any + RuntimeExceptions, IOExceptions or SAXExceptions unrelated to the given + document stream or content handler are converted to TikaExceptions + before being passed to the client. (TIKA-198, TIKA-237) + +The following people have contributed to Tika 0.4 by submitting or commenting +on the issues resolved in this release: + + Chris A. Mattmann + Daan de Wit + Dave Meikle + David Weekly + Jeremias Maerki + Jonathan Koren + Jukka Zitting + Karl Heinz Marbaise + Keith R. Bennett + Maxim Valyanskiy + Niall Pemberton + Robert Burrell Donkin + Sami Siren + Siddharth Gargate + Uwe Schindler + +See http://tinyurl.com/mgv9o3 for more details on these contributions. + + +Release 0.3 - 03/09/2009 +------------------------ + +The most notable changes in Tika 0.3 over the previous release are: + + * Tika now supports mime type glob patterns specified using + standard JDK 1.4 (and beyond) syntax via the isregex attribute + on the glob tag. See: + + http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html + + for more information. (TIKA-194) + + * Tika now supports the Office Open XML format used by + Microsoft Office 2007. (TIKA-152) + + * All the metadata keys for Microsoft Office document properties are now + included as constants in the MSOffice interface. Clients should use + these constants instead of the raw string values to refer to specific + metadata items. (TIKA-186) + + * Automatic detection of document types in Tika has been improved. + For example Tika can now detect plain text just by looking at the first + few bytes of the document. (TIKA-154) + + * Tika now disables the loading of all external entities in XML files + that it parses as input documents. This improves security and avoids + problems with potentially broken references. (TIKA-185) + + * Tika now replaces all invalid XML characters in the extracted text + content with spaces. This prevents problems when output from Tika + is processed with XML tools. (TIKA-180) + + * The Tika CLI now correctly flushes its buffers when invoked with the + --text argument. This prevents the end of the text output from being + lost. (TIKA-179) + + * Embedded text in MIDI files is now extracted. For example many karaoke + files contain song lyrics embedded as MIDI text. + + * The text content of Microsoft Outlook message files no longer appears as + multiple copies in the extracted text. (TIKA-197) + + * The ParsingReader class now makes most document metadata available + already before any of the extracted text is consumed. This makes it + easier for example to construct Lucene Document instances that contain + both extracted text and metadata. (TIKA-203) + +See http://tinyurl.com/tika-0-3-changes for a list of all changes in Tika 0.3. + +The following people have contributed to Tika 0.3 by submitting or commenting +on the issues resolved in this release: + + Andrzej Rusin + Chris A. Mattmann + Dave Meikle + Georger Ara√∫jo + Guillermo Arribas + Jonathan Koren + Jukka Zitting + Karl Heinz Marbaise + Kumar Raja Jana + Paul Borgermans + Peter Becker + S√©bastien Michel + Uwe Schindler + +See http://tinyurl.com/tika-0-3-contributions for more details on +these contributions. + + +Release 0.2 - 12/04/2008 +------------------------ + +1. TIKA-109 - WordParser fails on some Word files (Dave Meikle) + +2. TIKA-105 - Excel parser implementation based on POI's Event API + (Niall Pemberton) + +3. TIKA-116 - Streaming parser for OpenDocument files (Jukka Zitting) + +4. TIKA-117 - Drop JDOM and Jaxen dependencies (Jukka Zitting) + +5. TIKA-115 - Tika package with all the dependencies (Jukka Zitting) + +6. TIKA-97 - Tika GUI (Jukka Zitting) + +7. TIKA-96 - Tika CLI (Jukka Zitting) + +8. TIKA-112 - Use Commons IO 1.4 (Jukka Zitting) + +9. TIKA-127 - Add support for Visio files (Jukka Zitting) + +10. TIKA-129 - node() support for the streaming XPath utility (Jukka Zitting) + +11. TIKA-130 - self-or-descendant axis does not match self in streaming XPath + (Jukka Zitting) + +12. TIKA-131 - Lazy XHTML prefix generation (Jukka Zitting) + +13. TIKA-128 - HTML parser should produce XHTML SAX events (Jukka Zitting) + +14. TIKA-133 - TeeContentHandler constructor should use varargs (Jukka Zitting) + +15. TIKA-132 - Refactor Excel extractor to parse per sheet and add + hyperlink support (Niall Pemberton) + +16. TIKA-134 - mvn package does not produce packages for bin/src + (Karl Heinz Marbaise) + +17. TIKA-138 - Ignore HTML style and script content (Jukka Zitting) + +18. TIKA-113 - Metadata (such as title) should not be part of content + (Jukka Zitting) + +19. TIKA-139 - Add a composite parser (Jukka Zitting) + +20. TIKA-142 - Include application/xhtml+xml as valid mime type for XMLParser + (mattmann) + +21. TIKA-143 - Add ParsingReader (Jukka Zitting) + +22. TIKA-144 - Upgrade nekohtml dependency (Jukka Zitting) + +23. TIKA-145 - Separate NOTICEs and LICENSEs for binary and source packages + (Jukka Zitting) + +24. TIKA-146 - Upgrade to POI 3.1 (Jukka Zitting) + +25. TIKA-99 - Support external parser programs (Jukka Zitting) + +26. TIKA-149 - Parser for Zip files (Dave Meikle & Jukka Zitting) + +27. TIKA-150 - Parser for tar files (Jukka Zitting) + +28. TIKA-151 - Stream compression support (Jukka Zitting) + +29. TIKA-156 - Some MIME magic patterns are ignored by MimeTypes + (Jukka Zitting) + +30. TIKA-155 - Java class file parser (Dave Brosius & Jukka Zitting) + +31. TIKA-108 - New Tika logos (Yongqian Li & Jukka Zitting) + +32. TIKA-120 - Add support for retrieving ID3 tags from MP3 files + (Dave Meikle & Jukka Zitting) + +33. TIKA-54 - Outlook msg parser + (Rida Benjelloun, Dave Meikle & Jukka Zitting) + +34. TIKA-114 - PDFParser : Getting content of the document using + "writer.ToString ()" , some words are stuck together + (Dave Meikle) + +35. TIKA-161 - Enable PMD reports (Jukka Zitting) + +36. TIKA-159 - Add support for parsing basic audio types: wav, aiff, au, midi + (Sami Siren) + +37. TIKA-140 - HTML parser unable to extract text + (Julien Nioche & Jukka Zitting) + +38. TIKA-163 - GUI does not support drag and drop in Gnome or KDE (Dave Meikle) + +39. TIKA-166 - Update HTMLParser to parse contents of meta tags (Dave Meikle) + +40. TIKA-164 - Upgrade of the nekohtml dependency to 1.9.9 (Jukka Zitting) + +41. TIKA-165 - Upgrade of the ICU4J dependency to version 3.8 (Jukka Zitting) + +42. TIKA-172 - New Open Document Parser that emits structured XHTML content + (Uwe Schindler & Jukka Zitting) + +43. TIKA-175 - Retrotranslate Tika for use in Java 1.4 environments (Jukka Zitting) + +44. TIKA-177 - Improvements to build instruction in README (Chris Hostetter & Jukka Zitting) + +45. TIKA-171 - New ContentHandler for plain text output that has no problem with + missing white space after XHTML block tags (Uwe Schindler & Jukka Zitting) + + +Release 0.1-incubating - 12/27/2007 +----------------------------------- + +1. TIKA-5 - Port Metadata Framework from Nutch (mattmann) + +2. TIKA-11 - Consolidate test classes into a src/test/java directory tree (mattmann) + +3. TIKA-15 - Utils.print does not print a Content having no value (jukka) + +4. TIKA-19 - org.apache.tika.TestParsers fails (bdelacretaz) + +5. TIKA-16 - Issues with data files used for testing by TestParsers (bdelacretaz) + +6. TIKA-14 - MimeTypeUtils.getMimeType() returns the default mime type for + .odt (Open Office) file (bdelacretaz) + +7. TIKA-12 - Add URL capability to MimeTypesUtils (jukka) + +8. TIKA-13 - Fix obsolete package names in config.xml (siren) + +9. TIKA-10 - Remove MimeInfoException catch clauses and import from TestParsers (siren) + +10. TIKA-8 - Replaced the jmimeinfo dependency with a trivial mime type detector (jukka) + +11. TIKA-7 - Added the Lius Lite code. Added missing dependencies to POM (jukka) + +12. TIKA-18 - "Office" interface should be renamed "MSOffice" (mattmann) + +13. TIKA-23 - Decouple Parser from ParserConfig (jukka) + +14. TIKA-6 - Port Nutch (or better) MimeType detection system into Tika (J. Charron & mattmann) + +15. TIKA-25 - Removed hardcoded reference to C:\oo.xml in OpenOfficeParser (K. Bennett & jukka) + +16. TIKA-17 - Need to support URL's for input resources. (K. Bennett & mattmann) + +17. TIKA-22 - Remove @author tags from the java source (mattmann) + +18. TIKA-21 - Simplified configuration code (jukka) + +19. TIKA-17 - Rename all "Lius" classes to be "Tika" classes (jukka) + +20. TIKA-30 - Added utility constructors to TikaConfig (K. Bennett & jukka) + +21. TIKA-28 - Rename config.xml to tika-config.xml or similar (mattmann) + +22. TIKA-26 - Use Map instead of List (jukka) + +23. TIKA-31 - protected Parser.parse(InputStream stream, + Iterable contents) (jukka & K. Bennett) + +24. TIKA-36 - A convenience method for getting a document's content's text + would be helpful (K. Bennett & mattmann) + +25. TIKA-33 - Stateless parsers (jukka) + +26. TIKA-38 - TXTParser adds a space to the content it reads from a file (K. Bennett & ridabenjelloun) + +27. TIKA-35 - Extract MsOffice properties, use RereadableInputStream devloped by K. Bennett (ridabenjelloun & K. Bennett) + +28. TIKA-39 - Excel parsing improvements (siren & ridabenjelloun) + +29. TIKA-34 - Provide a method that will return a default configuration + (TikaConfig) (K. Bennett & mattmann) + +30. TIKA-42 - Content class needs (String, String, String) constructor (K. Bennett) + +31. TIKA-43 - Parser interface (jukka) + +32. TIKA-47 - Remove TikaLogger (jukka) + +33. TIKA-46 - Use Metadata in Parser (jukka & mattmann) + +34. TIKA-48 - Merge MS Extractors and Parsers (jukka) + +35. TIKA-45 - RereadableInputStream needs to be able to read to + the end of the original stream on first rewind. (K. Bennett) + +36. TIKA-41 - Resource files occur twice in jar file. (jukka) + +37. TIKA-49 - Some files have old-style license headers, fixed (Robert Burrell Donkin & bdelacretaz) + +38. TIKA-51 - Leftover temp files after running Tika tests, fixed (bdelacretaz) + +39. TIKA-40 - Tika needs to support diverse character encodings (jukka) + +40. TIKA-55 - ParseUtils.getParser() method variants should have consistent parameter orders + (K. Bennett) + +41. TIKA-52 - RereadableInputStream needs to support not closing the input stream it wraps. + (K. Bennett via bdelacretaz) + +42. TIKA-53 - XHTML SAX events from parsers (jukka) + +43. TIKA-57 - Rename org.apache.tika.ms to org.apache.tika.parser.ms (jukka) + +44. TIKA-62 - Use TikaConfig.getDefaultConfig() instead of a hardcoded + config path in TestParsers (jukka) + +45. TIKA-58 - Replace jtidy html parser with nekohtml based parser (siren) + +46. TIKA-60 - Rename Microsoft parser classes (jukka) + +47. TIKA-63 - Avoid multiple passes over the input stream in Microsoft parsers + (jukka) + +48. TIKA-66 - Use Java 5 features in org.apache.tika.mime (jukka) + +49. TIKA-56 - Mime type detection fails with upper case file extensions such as "PDF" + (mattmann) + +50. TIKA-65 - Add encode detection support for HTML parser (siren) + +51. TIKA-68 - Add dummy parser classes to be used as sentinels (jukka) + +52. TIKA-67 - Add an auto-detecting Parser implementation (jukka) + +53. TIKA-70 - Better MIME information for the Open Document formats (jukka) + +54. TIKA-71 - Remove ParserConfig and ParserFactory (jukka) + +55. TIKA-83 - Create a org.apache.tika.sax package for SAX utilities (jukka) + +56. TIKA-84 - Add MimeTypes.getMimeType(InputStream) (jukka) + +57. TIKA-85 - Add glob patterns from the ASF svn:eol-style documentation (jukka) + +58. TIKA-100 - Structured PDF parsing (jukka) + +59. TIKA-101 - Improve site and build (mattmann) + +60. TIKA-102 - Parser implementations loading a large amount of content + into a single String could be problematic (Niall Pemberton) + +61. TIKA-107 - Remove use of assertions for argument checking (Niall Pemberton) + +62. TIKA-104 - Add utility methods to throw IOException with the caused + intialized (jukka & Niall Pemberton) + +63. TIKA-106 - Remove dependency on Jakarta ORO - use JDK 1.4 Regex + (Niall Pemberton) + +64. TIKA-111 - Missing license headers (jukka) + +65. TIKA-112 - XMLParser improvement (ridabenjelloun) diff --git a/All/Genesis-OOB/Genesis#143/comMsg.txt b/All/Genesis-OOB/Genesis#143/comMsg.txt deleted file mode 100755 index 45d9c59..0000000 --- a/All/Genesis-OOB/Genesis#143/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -PDFBOX-1611: avoid IndexOutOfBoundsExcpetion if font matrix values are on separated on single lines diff --git a/All/Genesis-OOB/Genesis#143/diff.diff b/All/Genesis-OOB/Genesis#143/diff.diff deleted file mode 100755 index 0c8a300..0000000 --- a/All/Genesis-OOB/Genesis#143/diff.diff +++ /dev/null @@ -1,48 +0,0 @@ -diff --git a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDType1Font.java b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDType1Font.java -index 93da6c1..e597e63 100644 ---- a/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDType1Font.java -+++ b/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDType1Font.java -@@ -362 +362 @@ public class PDType1Font extends PDSimpleFont -- "Encoding defintion found without /Encoding line."); -+ "Encoding definition found without /Encoding line."); -@@ -383,0 +384,3 @@ public class PDType1Font extends PDSimpleFont -+ // most likely all matrix values are in the same line than the keyword -+ if (line.indexOf("[") > -1) -+ { -@@ -395,0 +399,5 @@ public class PDType1Font extends PDSimpleFont -+ } -+ catch (NumberFormatException exception) -+ { -+ LOG.error("Can't read the fontmatrix from embedded font file!"); -+ } -@@ -397,0 +406,20 @@ public class PDType1Font extends PDSimpleFont -+ } -+ else -+ { -+ // there are fonts where all values are on a separate line, see PDFBOX-1611 -+ COSArray array = new COSArray(); -+ while((line = in.readLine()) != null) -+ { -+ if (line.startsWith("[")) -+ { -+ continue; -+ } -+ if (line.endsWith("]")) -+ { -+ break; -+ } -+ try -+ { -+ COSFloat floatValue = new COSFloat(Float.parseFloat(line)); -+ array.add(floatValue); -+ } -@@ -402,0 +431,9 @@ public class PDType1Font extends PDSimpleFont -+ if (array.size() == 6) -+ { -+ fontMatrix = new PDMatrix(array); -+ } -+ else -+ { -+ LOG.error("Can't read the fontmatrix from embedded font file, not enough values!"); -+ } -+ } diff --git a/All/Genesis-OOB/Genesis#143/new/PDType1Font.java b/All/Genesis-OOB/Genesis#143/new/PDType1Font.java deleted file mode 100755 index e597e63..0000000 --- a/All/Genesis-OOB/Genesis#143/new/PDType1Font.java +++ /dev/null @@ -1,553 +0,0 @@ -/* - * 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.pdfbox.pdmodel.font; - -import java.awt.Font; -import java.awt.FontFormatException; -import java.awt.font.GlyphVector; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; -import java.util.StringTokenizer; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.fontbox.afm.FontMetric; -import org.apache.pdfbox.cos.COSArray; -import org.apache.pdfbox.cos.COSDictionary; -import org.apache.pdfbox.cos.COSFloat; -import org.apache.pdfbox.cos.COSName; -import org.apache.pdfbox.encoding.AFMEncoding; -import org.apache.pdfbox.encoding.Encoding; -import org.apache.pdfbox.encoding.EncodingManager; -import org.apache.pdfbox.encoding.Type1Encoding; -import org.apache.pdfbox.encoding.WinAnsiEncoding; -import org.apache.pdfbox.pdmodel.common.PDMatrix; -import org.apache.pdfbox.pdmodel.common.PDStream; - -/** - * This is implementation of the Type1 Font. - * - * @author Ben Litchfield - * @version $Revision: 1.11 $ - */ -public class PDType1Font extends PDSimpleFont -{ - - /** - * Log instance. - */ - private static final Log LOG = LogFactory.getLog(PDType1Font.class); - - private PDType1CFont type1CFont = null; - /** - * Standard Base 14 Font. - */ - public static final PDType1Font TIMES_ROMAN = new PDType1Font( "Times-Roman" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font TIMES_BOLD = new PDType1Font( "Times-Bold" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font TIMES_ITALIC = new PDType1Font( "Times-Italic" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font TIMES_BOLD_ITALIC = new PDType1Font( "Times-BoldItalic" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font HELVETICA = new PDType1Font( "Helvetica" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font HELVETICA_BOLD = new PDType1Font( "Helvetica-Bold" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font HELVETICA_OBLIQUE = new PDType1Font( "Helvetica-Oblique" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font HELVETICA_BOLD_OBLIQUE = new PDType1Font( "Helvetica-BoldOblique" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font COURIER = new PDType1Font( "Courier" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font COURIER_BOLD = new PDType1Font( "Courier-Bold" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font COURIER_OBLIQUE = new PDType1Font( "Courier-Oblique" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font COURIER_BOLD_OBLIQUE = new PDType1Font( "Courier-BoldOblique" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font SYMBOL = new PDType1Font( "Symbol" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font ZAPF_DINGBATS = new PDType1Font( "ZapfDingbats" ); - - private static final Map STANDARD_14 = new HashMap(); - static - { - STANDARD_14.put( TIMES_ROMAN.getBaseFont(), TIMES_ROMAN ); - STANDARD_14.put( TIMES_BOLD.getBaseFont(), TIMES_BOLD ); - STANDARD_14.put( TIMES_ITALIC.getBaseFont(), TIMES_ITALIC ); - STANDARD_14.put( TIMES_BOLD_ITALIC.getBaseFont(), TIMES_BOLD_ITALIC ); - STANDARD_14.put( HELVETICA.getBaseFont(), HELVETICA ); - STANDARD_14.put( HELVETICA_BOLD.getBaseFont(), HELVETICA_BOLD ); - STANDARD_14.put( HELVETICA_OBLIQUE.getBaseFont(), HELVETICA_OBLIQUE ); - STANDARD_14.put( HELVETICA_BOLD_OBLIQUE.getBaseFont(), HELVETICA_BOLD_OBLIQUE ); - STANDARD_14.put( COURIER.getBaseFont(), COURIER ); - STANDARD_14.put( COURIER_BOLD.getBaseFont(), COURIER_BOLD ); - STANDARD_14.put( COURIER_OBLIQUE.getBaseFont(), COURIER_OBLIQUE ); - STANDARD_14.put( COURIER_BOLD_OBLIQUE.getBaseFont(), COURIER_BOLD_OBLIQUE ); - STANDARD_14.put( SYMBOL.getBaseFont(), SYMBOL ); - STANDARD_14.put( ZAPF_DINGBATS.getBaseFont(), ZAPF_DINGBATS ); - } - - private Font awtFont = null; - - /** - * Constructor. - */ - public PDType1Font() - { - super(); - font.setItem( COSName.SUBTYPE, COSName.TYPE1 ); - } - - /** - * Constructor. - * - * @param fontDictionary The font dictionary according to the PDF specification. - */ - public PDType1Font( COSDictionary fontDictionary ) - { - super( fontDictionary ); - PDFontDescriptor fd = getFontDescriptor(); - if (fd != null && fd instanceof PDFontDescriptorDictionary) - { - // a Type1 font may contain a Type1C font - PDStream fontFile3 = ((PDFontDescriptorDictionary)fd).getFontFile3(); - if (fontFile3 != null) - { - try - { - type1CFont = new PDType1CFont( super.font ); - } - catch (IOException exception) - { - LOG.info("Can't read the embedded type1C font " + fd.getFontName() ); - } - } - } - } - - /** - * Constructor. - * - * @param baseFont The base font for this font. - */ - public PDType1Font( String baseFont ) - { - this(); - setBaseFont( baseFont ); - setFontEncoding(new WinAnsiEncoding()); - setEncoding(COSName.WIN_ANSI_ENCODING); - } - - /** - * A convenience method to get one of the standard 14 font from name. - * - * @param name The name of the font to get. - * - * @return The font that matches the name or null if it does not exist. - */ - public static PDType1Font getStandardFont( String name ) - { - return (PDType1Font)STANDARD_14.get( name ); - } - - /** - * This will get the names of the standard 14 fonts. - * - * @return An array of the names of the standard 14 fonts. - */ - public static String[] getStandard14Names() - { - return (String[])STANDARD_14.keySet().toArray( new String[14] ); - } - - /** - * {@inheritDoc} - */ - public Font getawtFont() throws IOException - { - if( awtFont == null ) - { - if (type1CFont != null) - { - awtFont = type1CFont.getawtFont(); - } - else - { - String baseFont = getBaseFont(); - PDFontDescriptor fd = getFontDescriptor(); - if (fd != null && fd instanceof PDFontDescriptorDictionary) - { - PDFontDescriptorDictionary fdDictionary = (PDFontDescriptorDictionary)fd; - if( fdDictionary.getFontFile() != null ) - { - try - { - // create a type1 font with the embedded data - awtFont = Font.createFont( Font.TYPE1_FONT, - fdDictionary.getFontFile().createInputStream() ); - } - catch (FontFormatException e) - { - LOG.info("Can't read the embedded type1 font " + fd.getFontName() ); - } - } - if (awtFont == null) - { - // check if the font is part of our environment - awtFont = FontManager.getAwtFont(fd.getFontName()); - if (awtFont == null) - { - LOG.info("Can't find the specified font " + fd.getFontName() ); - } - } - } - else - { - // check if the font is part of our environment - awtFont = FontManager.getAwtFont(baseFont); - if (awtFont == null) - { - LOG.info("Can't find the specified basefont " + baseFont ); - } - } - } - if (awtFont == null) - { - // we can't find anything, so we have to use the standard font - awtFont = FontManager.getStandardFont(); - LOG.info("Using font "+awtFont.getName()+ " instead"); - } - } - return awtFont; - } - - /** - * {@inheritDoc} - */ - @Override - protected void determineEncoding() - { - super.determineEncoding(); - Encoding fontEncoding = getFontEncoding(); - if(fontEncoding == null) - { - FontMetric metric = getAFM(); - if (metric != null) - { - fontEncoding = new AFMEncoding( metric ); - } - setFontEncoding(fontEncoding); - } - getEncodingFromFont(getFontEncoding() == null); - } - - /** - * Tries to get the encoding for the type1 font. - * - */ - private void getEncodingFromFont(boolean extractEncoding) - { - // This whole section of code needs to be replaced with an actual type1 font parser!! - // Get the font program from the embedded type font. - PDFontDescriptor fontDescriptor = getFontDescriptor(); - if( fontDescriptor != null && fontDescriptor instanceof PDFontDescriptorDictionary) - { - PDStream fontFile = ((PDFontDescriptorDictionary)fontDescriptor).getFontFile(); - if( fontFile != null ) - { - BufferedReader in = null; - try - { - in = new BufferedReader(new InputStreamReader(fontFile.createInputStream())); - - // this section parses the font program stream searching for a /Encoding entry - // if it contains an array of values a Type1Encoding will be returned - // if it encoding contains an encoding name the corresponding Encoding will be returned - String line = ""; - Type1Encoding encoding = null; - while( (line = in.readLine()) != null) - { - if (extractEncoding) - { - if (line.startsWith("currentdict end")) - { - if (encoding != null) - { - setFontEncoding(encoding); - } - break; - } - if (line.startsWith("/Encoding")) - { - if(line.contains("array")) - { - StringTokenizer st = new StringTokenizer(line); - // ignore the first token - st.nextElement(); - int arraySize = Integer.parseInt(st.nextToken()); - encoding = new Type1Encoding(arraySize); - } - // if there is already an encoding, we don't need to - // assign another one - else if (getFontEncoding() == null) - { - StringTokenizer st = new StringTokenizer(line); - // ignore the first token - st.nextElement(); - String type1Encoding = st.nextToken(); - setFontEncoding( - EncodingManager.INSTANCE.getEncoding( - COSName.getPDFName(type1Encoding))); - break; - } - } - else if (line.startsWith("dup")) - { - StringTokenizer st = new StringTokenizer(line.replaceAll("/"," /")); - // ignore the first token - st.nextElement(); - try - { - int index = Integer.parseInt(st.nextToken()); - String name = st.nextToken(); - if(encoding == null) - { - LOG.warn("Unable to get character encoding. " + - "Encoding definition found without /Encoding line."); - } - else - { - encoding.addCharacterEncoding(index, name.replace("/", "")); - } - } - catch(NumberFormatException exception) - { - // there are (tex?)-some fonts containing postscript code like the following, - // which has to be ignored, see PDFBOX-1481 - // dup dup 161 10 getinterval 0 exch putinterval .... - LOG.debug("Malformed encoding definition ignored (line="+line+")"); - } - continue; - } - } - // according to the pdf reference, all font matrices should be same, except for type 3 fonts. - // but obviously there are some type1 fonts with different matrix values, see pdf sample - // attached to PDFBOX-935 - if (line.startsWith("/FontMatrix")) - { - // most likely all matrix values are in the same line than the keyword - if (line.indexOf("[") > -1) - { - String matrixValues = line.substring(line.indexOf("[")+1,line.lastIndexOf("]")); - StringTokenizer st = new StringTokenizer(matrixValues); - COSArray array = new COSArray(); - if (st.countTokens() >= 6) - { - try - { - for (int i=0;i<6;i++) - { - COSFloat floatValue = new COSFloat(Float.parseFloat(st.nextToken())); - array.add(floatValue); - } - } - catch (NumberFormatException exception) - { - LOG.error("Can't read the fontmatrix from embedded font file!"); - } - fontMatrix = new PDMatrix(array); - } - } - else - { - // there are fonts where all values are on a separate line, see PDFBOX-1611 - COSArray array = new COSArray(); - while((line = in.readLine()) != null) - { - if (line.startsWith("[")) - { - continue; - } - if (line.endsWith("]")) - { - break; - } - try - { - COSFloat floatValue = new COSFloat(Float.parseFloat(line)); - array.add(floatValue); - } - catch (NumberFormatException exception) - { - LOG.error("Can't read the fontmatrix from embedded font file!"); - } - } - if (array.size() == 6) - { - fontMatrix = new PDMatrix(array); - } - else - { - LOG.error("Can't read the fontmatrix from embedded font file, not enough values!"); - } - } - } - } - } - catch(IOException exception) - { - LOG.error("Error: Could not extract the encoding from the embedded type1 font."); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch(IOException exception) - { - LOG.error("An error occurs while closing the stream used to read the embedded type1 font."); - } - } - } - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public String encode(byte[] c, int offset, int length) throws IOException - { - if (type1CFont != null) - { - return type1CFont.encode(c, offset, length); - } - else - { - return super.encode(c, offset, length); - } - } - - /** - * {@inheritDoc} - */ - @Override - public int encodeToCID( byte[] c, int offset, int length ) throws IOException - { - if (type1CFont != null && getFontEncoding() == null) - { - return type1CFont.encodeToCID(c, offset, length); - } - else - { - return super.encodeToCID(c, offset, length); - } - } - - /** - * {@inheritDoc} - */ - @Override - public PDMatrix getFontMatrix() - { - if (type1CFont != null) - { - return type1CFont.getFontMatrix(); - } - else - { - return super.getFontMatrix(); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected GlyphVector remapGlyphs(GlyphVector glyphVector, String string) - { - // this is used to fix an apparent bug with the sun jdk where the mapping of - // character code to glyph index done by native code is wrong; this does not happen with openjdk - try - { - Field fGlyphs = glyphVector.getClass().getDeclaredField("glyphs"); - fGlyphs.setAccessible(true); - int[] glyphs = (int[]) fGlyphs.get(glyphVector); - if (glyphs.length == 1 && glyphs[0] != 65535) - { - return glyphVector; - } - if (type1CFont != null) - { - Field fuserGlyphs = glyphVector.getClass().getDeclaredField("userGlyphs"); - fuserGlyphs.setAccessible(true); - int[] userGlyphs = (int[]) fuserGlyphs.get(glyphVector); - for (int j = 0; j < glyphs.length; j++) - { - if (glyphs[j] == 65535) - { - int c = (int) string.charAt(j); - glyphs[j] = type1CFont.getGlyphIndex(c); - userGlyphs[j] = type1CFont.getGlyphIndex(c); - } - } - } - } - catch (Exception e) - { - e.printStackTrace(); - } - return glyphVector; - } - -} diff --git a/All/Genesis-OOB/Genesis#143/old/PDType1Font.java b/All/Genesis-OOB/Genesis#143/old/PDType1Font.java deleted file mode 100755 index 93da6c1..0000000 --- a/All/Genesis-OOB/Genesis#143/old/PDType1Font.java +++ /dev/null @@ -1,516 +0,0 @@ -/* - * 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.pdfbox.pdmodel.font; - -import java.awt.Font; -import java.awt.FontFormatException; -import java.awt.font.GlyphVector; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.lang.reflect.Field; -import java.util.HashMap; -import java.util.Map; -import java.util.StringTokenizer; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.fontbox.afm.FontMetric; -import org.apache.pdfbox.cos.COSArray; -import org.apache.pdfbox.cos.COSDictionary; -import org.apache.pdfbox.cos.COSFloat; -import org.apache.pdfbox.cos.COSName; -import org.apache.pdfbox.encoding.AFMEncoding; -import org.apache.pdfbox.encoding.Encoding; -import org.apache.pdfbox.encoding.EncodingManager; -import org.apache.pdfbox.encoding.Type1Encoding; -import org.apache.pdfbox.encoding.WinAnsiEncoding; -import org.apache.pdfbox.pdmodel.common.PDMatrix; -import org.apache.pdfbox.pdmodel.common.PDStream; - -/** - * This is implementation of the Type1 Font. - * - * @author Ben Litchfield - * @version $Revision: 1.11 $ - */ -public class PDType1Font extends PDSimpleFont -{ - - /** - * Log instance. - */ - private static final Log LOG = LogFactory.getLog(PDType1Font.class); - - private PDType1CFont type1CFont = null; - /** - * Standard Base 14 Font. - */ - public static final PDType1Font TIMES_ROMAN = new PDType1Font( "Times-Roman" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font TIMES_BOLD = new PDType1Font( "Times-Bold" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font TIMES_ITALIC = new PDType1Font( "Times-Italic" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font TIMES_BOLD_ITALIC = new PDType1Font( "Times-BoldItalic" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font HELVETICA = new PDType1Font( "Helvetica" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font HELVETICA_BOLD = new PDType1Font( "Helvetica-Bold" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font HELVETICA_OBLIQUE = new PDType1Font( "Helvetica-Oblique" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font HELVETICA_BOLD_OBLIQUE = new PDType1Font( "Helvetica-BoldOblique" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font COURIER = new PDType1Font( "Courier" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font COURIER_BOLD = new PDType1Font( "Courier-Bold" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font COURIER_OBLIQUE = new PDType1Font( "Courier-Oblique" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font COURIER_BOLD_OBLIQUE = new PDType1Font( "Courier-BoldOblique" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font SYMBOL = new PDType1Font( "Symbol" ); - /** - * Standard Base 14 Font. - */ - public static final PDType1Font ZAPF_DINGBATS = new PDType1Font( "ZapfDingbats" ); - - private static final Map STANDARD_14 = new HashMap(); - static - { - STANDARD_14.put( TIMES_ROMAN.getBaseFont(), TIMES_ROMAN ); - STANDARD_14.put( TIMES_BOLD.getBaseFont(), TIMES_BOLD ); - STANDARD_14.put( TIMES_ITALIC.getBaseFont(), TIMES_ITALIC ); - STANDARD_14.put( TIMES_BOLD_ITALIC.getBaseFont(), TIMES_BOLD_ITALIC ); - STANDARD_14.put( HELVETICA.getBaseFont(), HELVETICA ); - STANDARD_14.put( HELVETICA_BOLD.getBaseFont(), HELVETICA_BOLD ); - STANDARD_14.put( HELVETICA_OBLIQUE.getBaseFont(), HELVETICA_OBLIQUE ); - STANDARD_14.put( HELVETICA_BOLD_OBLIQUE.getBaseFont(), HELVETICA_BOLD_OBLIQUE ); - STANDARD_14.put( COURIER.getBaseFont(), COURIER ); - STANDARD_14.put( COURIER_BOLD.getBaseFont(), COURIER_BOLD ); - STANDARD_14.put( COURIER_OBLIQUE.getBaseFont(), COURIER_OBLIQUE ); - STANDARD_14.put( COURIER_BOLD_OBLIQUE.getBaseFont(), COURIER_BOLD_OBLIQUE ); - STANDARD_14.put( SYMBOL.getBaseFont(), SYMBOL ); - STANDARD_14.put( ZAPF_DINGBATS.getBaseFont(), ZAPF_DINGBATS ); - } - - private Font awtFont = null; - - /** - * Constructor. - */ - public PDType1Font() - { - super(); - font.setItem( COSName.SUBTYPE, COSName.TYPE1 ); - } - - /** - * Constructor. - * - * @param fontDictionary The font dictionary according to the PDF specification. - */ - public PDType1Font( COSDictionary fontDictionary ) - { - super( fontDictionary ); - PDFontDescriptor fd = getFontDescriptor(); - if (fd != null && fd instanceof PDFontDescriptorDictionary) - { - // a Type1 font may contain a Type1C font - PDStream fontFile3 = ((PDFontDescriptorDictionary)fd).getFontFile3(); - if (fontFile3 != null) - { - try - { - type1CFont = new PDType1CFont( super.font ); - } - catch (IOException exception) - { - LOG.info("Can't read the embedded type1C font " + fd.getFontName() ); - } - } - } - } - - /** - * Constructor. - * - * @param baseFont The base font for this font. - */ - public PDType1Font( String baseFont ) - { - this(); - setBaseFont( baseFont ); - setFontEncoding(new WinAnsiEncoding()); - setEncoding(COSName.WIN_ANSI_ENCODING); - } - - /** - * A convenience method to get one of the standard 14 font from name. - * - * @param name The name of the font to get. - * - * @return The font that matches the name or null if it does not exist. - */ - public static PDType1Font getStandardFont( String name ) - { - return (PDType1Font)STANDARD_14.get( name ); - } - - /** - * This will get the names of the standard 14 fonts. - * - * @return An array of the names of the standard 14 fonts. - */ - public static String[] getStandard14Names() - { - return (String[])STANDARD_14.keySet().toArray( new String[14] ); - } - - /** - * {@inheritDoc} - */ - public Font getawtFont() throws IOException - { - if( awtFont == null ) - { - if (type1CFont != null) - { - awtFont = type1CFont.getawtFont(); - } - else - { - String baseFont = getBaseFont(); - PDFontDescriptor fd = getFontDescriptor(); - if (fd != null && fd instanceof PDFontDescriptorDictionary) - { - PDFontDescriptorDictionary fdDictionary = (PDFontDescriptorDictionary)fd; - if( fdDictionary.getFontFile() != null ) - { - try - { - // create a type1 font with the embedded data - awtFont = Font.createFont( Font.TYPE1_FONT, - fdDictionary.getFontFile().createInputStream() ); - } - catch (FontFormatException e) - { - LOG.info("Can't read the embedded type1 font " + fd.getFontName() ); - } - } - if (awtFont == null) - { - // check if the font is part of our environment - awtFont = FontManager.getAwtFont(fd.getFontName()); - if (awtFont == null) - { - LOG.info("Can't find the specified font " + fd.getFontName() ); - } - } - } - else - { - // check if the font is part of our environment - awtFont = FontManager.getAwtFont(baseFont); - if (awtFont == null) - { - LOG.info("Can't find the specified basefont " + baseFont ); - } - } - } - if (awtFont == null) - { - // we can't find anything, so we have to use the standard font - awtFont = FontManager.getStandardFont(); - LOG.info("Using font "+awtFont.getName()+ " instead"); - } - } - return awtFont; - } - - /** - * {@inheritDoc} - */ - @Override - protected void determineEncoding() - { - super.determineEncoding(); - Encoding fontEncoding = getFontEncoding(); - if(fontEncoding == null) - { - FontMetric metric = getAFM(); - if (metric != null) - { - fontEncoding = new AFMEncoding( metric ); - } - setFontEncoding(fontEncoding); - } - getEncodingFromFont(getFontEncoding() == null); - } - - /** - * Tries to get the encoding for the type1 font. - * - */ - private void getEncodingFromFont(boolean extractEncoding) - { - // This whole section of code needs to be replaced with an actual type1 font parser!! - // Get the font program from the embedded type font. - PDFontDescriptor fontDescriptor = getFontDescriptor(); - if( fontDescriptor != null && fontDescriptor instanceof PDFontDescriptorDictionary) - { - PDStream fontFile = ((PDFontDescriptorDictionary)fontDescriptor).getFontFile(); - if( fontFile != null ) - { - BufferedReader in = null; - try - { - in = new BufferedReader(new InputStreamReader(fontFile.createInputStream())); - - // this section parses the font program stream searching for a /Encoding entry - // if it contains an array of values a Type1Encoding will be returned - // if it encoding contains an encoding name the corresponding Encoding will be returned - String line = ""; - Type1Encoding encoding = null; - while( (line = in.readLine()) != null) - { - if (extractEncoding) - { - if (line.startsWith("currentdict end")) - { - if (encoding != null) - { - setFontEncoding(encoding); - } - break; - } - if (line.startsWith("/Encoding")) - { - if(line.contains("array")) - { - StringTokenizer st = new StringTokenizer(line); - // ignore the first token - st.nextElement(); - int arraySize = Integer.parseInt(st.nextToken()); - encoding = new Type1Encoding(arraySize); - } - // if there is already an encoding, we don't need to - // assign another one - else if (getFontEncoding() == null) - { - StringTokenizer st = new StringTokenizer(line); - // ignore the first token - st.nextElement(); - String type1Encoding = st.nextToken(); - setFontEncoding( - EncodingManager.INSTANCE.getEncoding( - COSName.getPDFName(type1Encoding))); - break; - } - } - else if (line.startsWith("dup")) - { - StringTokenizer st = new StringTokenizer(line.replaceAll("/"," /")); - // ignore the first token - st.nextElement(); - try - { - int index = Integer.parseInt(st.nextToken()); - String name = st.nextToken(); - if(encoding == null) - { - LOG.warn("Unable to get character encoding. " + - "Encoding defintion found without /Encoding line."); - } - else - { - encoding.addCharacterEncoding(index, name.replace("/", "")); - } - } - catch(NumberFormatException exception) - { - // there are (tex?)-some fonts containing postscript code like the following, - // which has to be ignored, see PDFBOX-1481 - // dup dup 161 10 getinterval 0 exch putinterval .... - LOG.debug("Malformed encoding definition ignored (line="+line+")"); - } - continue; - } - } - // according to the pdf reference, all font matrices should be same, except for type 3 fonts. - // but obviously there are some type1 fonts with different matrix values, see pdf sample - // attached to PDFBOX-935 - if (line.startsWith("/FontMatrix")) - { - String matrixValues = line.substring(line.indexOf("[")+1,line.lastIndexOf("]")); - StringTokenizer st = new StringTokenizer(matrixValues); - COSArray array = new COSArray(); - if (st.countTokens() >= 6) - { - try - { - for (int i=0;i<6;i++) - { - COSFloat floatValue = new COSFloat(Float.parseFloat(st.nextToken())); - array.add(floatValue); - } - fontMatrix = new PDMatrix(array); - } - catch (NumberFormatException exception) - { - LOG.error("Can't read the fontmatrix from embedded font file!"); - } - } - } - } - } - catch(IOException exception) - { - LOG.error("Error: Could not extract the encoding from the embedded type1 font."); - } - finally - { - if (in != null) - { - try - { - in.close(); - } - catch(IOException exception) - { - LOG.error("An error occurs while closing the stream used to read the embedded type1 font."); - } - } - } - } - } - } - - /** - * {@inheritDoc} - */ - @Override - public String encode(byte[] c, int offset, int length) throws IOException - { - if (type1CFont != null) - { - return type1CFont.encode(c, offset, length); - } - else - { - return super.encode(c, offset, length); - } - } - - /** - * {@inheritDoc} - */ - @Override - public int encodeToCID( byte[] c, int offset, int length ) throws IOException - { - if (type1CFont != null && getFontEncoding() == null) - { - return type1CFont.encodeToCID(c, offset, length); - } - else - { - return super.encodeToCID(c, offset, length); - } - } - - /** - * {@inheritDoc} - */ - @Override - public PDMatrix getFontMatrix() - { - if (type1CFont != null) - { - return type1CFont.getFontMatrix(); - } - else - { - return super.getFontMatrix(); - } - } - - /** - * {@inheritDoc} - */ - @Override - protected GlyphVector remapGlyphs(GlyphVector glyphVector, String string) - { - // this is used to fix an apparent bug with the sun jdk where the mapping of - // character code to glyph index done by native code is wrong; this does not happen with openjdk - try - { - Field fGlyphs = glyphVector.getClass().getDeclaredField("glyphs"); - fGlyphs.setAccessible(true); - int[] glyphs = (int[]) fGlyphs.get(glyphVector); - if (glyphs.length == 1 && glyphs[0] != 65535) - { - return glyphVector; - } - if (type1CFont != null) - { - Field fuserGlyphs = glyphVector.getClass().getDeclaredField("userGlyphs"); - fuserGlyphs.setAccessible(true); - int[] userGlyphs = (int[]) fuserGlyphs.get(glyphVector); - for (int j = 0; j < glyphs.length; j++) - { - if (glyphs[j] == 65535) - { - int c = (int) string.charAt(j); - glyphs[j] = type1CFont.getGlyphIndex(c); - userGlyphs[j] = type1CFont.getGlyphIndex(c); - } - } - } - } - catch (Exception e) - { - e.printStackTrace(); - } - return glyphVector; - } - -} diff --git a/All/Genesis-OOB/Genesis#143/pair.info b/All/Genesis-OOB/Genesis#143/pair.info deleted file mode 100755 index 279423a..0000000 --- a/All/Genesis-OOB/Genesis#143/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:143 -SATName:Genesis -modifiedFPath:pdfbox/src/main/java/org/apache/pdfbox/pdmodel/font/PDType1Font.java -comSha:fbad17c -parentComSha:fbad17c^1 -githubUrl:https://github.com/BrentDouglas/pdfbox -repoName:BrentDouglas#pdfbox \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#146/comMsg.txt b/All/Genesis-OOB/Genesis#146/comMsg.txt deleted file mode 100755 index 8dd8a5e..0000000 --- a/All/Genesis-OOB/Genesis#146/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix ArrayIndexOutOfBoundsException when cipher such as "RSA" are evaluate by CipherWithNoIntegrityDetector. #24 Tested with EcbModeDetectorTest diff --git a/All/Genesis-OOB/Genesis#146/diff.diff b/All/Genesis-OOB/Genesis#146/diff.diff deleted file mode 100755 index de7273c..0000000 --- a/All/Genesis-OOB/Genesis#146/diff.diff +++ /dev/null @@ -1,8 +0,0 @@ -diff --git a/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/CipherWithNoIntegrityDetector.java b/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/CipherWithNoIntegrityDetector.java -index cec7aca..fb9a7e0 100644 ---- a/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/CipherWithNoIntegrityDetector.java -+++ b/plugin/src/main/java/com/h3xstream/findsecbugs/crypto/CipherWithNoIntegrityDetector.java -@@ -93,0 +94 @@ public class CipherWithNoIntegrityDetector extends OpcodeStackDetector { -+ if(cipherDefinition.length > 1) { //Some cipher will not have mode specified (ie: "RSA" .. issue GitHub #24) -@@ -103,0 +105 @@ public class CipherWithNoIntegrityDetector extends OpcodeStackDetector { -+} diff --git a/All/Genesis-OOB/Genesis#146/new/CipherWithNoIntegrityDetector.java b/All/Genesis-OOB/Genesis#146/new/CipherWithNoIntegrityDetector.java deleted file mode 100755 index fb9a7e0..0000000 --- a/All/Genesis-OOB/Genesis#146/new/CipherWithNoIntegrityDetector.java +++ /dev/null @@ -1,105 +0,0 @@ -/** - * Find Security Bugs - * Copyright (c) 2014, Philippe Arteau, All rights reserved. - * - * 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 3.0 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. - */ -package com.h3xstream.findsecbugs.crypto; - -import com.h3xstream.findsecbugs.common.StringTracer; -import edu.umd.cs.findbugs.BugInstance; -import edu.umd.cs.findbugs.BugReporter; -import edu.umd.cs.findbugs.OpcodeStack; -import edu.umd.cs.findbugs.Priorities; -import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; -import org.apache.bcel.Constants; - -import java.util.Arrays; -import java.util.List; - -/** - *

- * This detector mark cipher usage that doesn't provide integrity. - * The identification will be made base on the mode use. - *

- *

- * Bad modes: - *

    - *
  • ECB
  • - *
  • CBC
  • - *
  • OFB
  • - *
  • ...
  • - *
- *

- *

- * Safe modes: - *

    - *
  • CCM
  • - *
  • CWC
  • - *
  • OCB
  • - *
  • EAX
  • - *
  • GCM
  • - *
- *

- * Ref: Wikipedia: Authenticated encryption - */ -public class CipherWithNoIntegrityDetector extends OpcodeStackDetector { - - private static final String ECB_MODE_TYPE = "ECB_MODE"; - private static final String PADDING_ORACLE_TYPE = "PADDING_ORACLE"; - private static final String CIPHER_INTEGRITY_TYPE = "CIPHER_INTEGRITY"; - - private static final boolean DEBUG = false; - private static final List SECURE_CIPHER_MODES = Arrays.asList("CCM","CWC","OCB","EAX","GCM"); - - private BugReporter bugReporter; - - public CipherWithNoIntegrityDetector(BugReporter bugReporter) { - this.bugReporter = bugReporter; - } - - @Override - public void sawOpcode(int seen) { - if (seen == Constants.INVOKESTATIC && getClassConstantOperand().equals("javax/crypto/Cipher") && - getNameConstantOperand().equals("getInstance")) { - OpcodeStack.Item item = stack.getStackItem(stack.getStackDepth() - 1); //The first argument is last - if (StringTracer.isConstantString(item)) { - String cipherValue = (String) item.getConstant(); - if (DEBUG) System.out.println(cipherValue); - - //Ref for the list of potential ciphers : http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#impl - //Note: Not all ECB mode are vulnerable. see RSA/ECB/* - if (cipherValue.contains("AES/ECB/") || cipherValue.contains("DES/ECB/") || cipherValue.contains("DESede/ECB/")) { - bugReporter.reportBug(new BugInstance(this, ECB_MODE_TYPE, Priorities.HIGH_PRIORITY) // - .addClass(this).addMethod(this).addSourceLine(this)); - } - - if (cipherValue.contains("/CBC/PKCS5Padding")) { - bugReporter.reportBug(new BugInstance(this, PADDING_ORACLE_TYPE, Priorities.HIGH_PRIORITY) // - .addClass(this).addMethod(this).addSourceLine(this)); - } - - String[] cipherDefinition = cipherValue.split("/"); - if(cipherDefinition.length > 1) { //Some cipher will not have mode specified (ie: "RSA" .. issue GitHub #24) - String cipherMode = cipherDefinition[1]; - - if (!SECURE_CIPHER_MODES.contains(cipherMode)) { //Not a secure mode! - bugReporter.reportBug(new BugInstance(this, CIPHER_INTEGRITY_TYPE, Priorities.HIGH_PRIORITY) // - .addClass(this).addMethod(this).addSourceLine(this)); - } - } - } - } - } -} diff --git a/All/Genesis-OOB/Genesis#146/old/CipherWithNoIntegrityDetector.java b/All/Genesis-OOB/Genesis#146/old/CipherWithNoIntegrityDetector.java deleted file mode 100755 index cec7aca..0000000 --- a/All/Genesis-OOB/Genesis#146/old/CipherWithNoIntegrityDetector.java +++ /dev/null @@ -1,103 +0,0 @@ -/** - * Find Security Bugs - * Copyright (c) 2014, Philippe Arteau, All rights reserved. - * - * 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 3.0 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. - */ -package com.h3xstream.findsecbugs.crypto; - -import com.h3xstream.findsecbugs.common.StringTracer; -import edu.umd.cs.findbugs.BugInstance; -import edu.umd.cs.findbugs.BugReporter; -import edu.umd.cs.findbugs.OpcodeStack; -import edu.umd.cs.findbugs.Priorities; -import edu.umd.cs.findbugs.bcel.OpcodeStackDetector; -import org.apache.bcel.Constants; - -import java.util.Arrays; -import java.util.List; - -/** - *

- * This detector mark cipher usage that doesn't provide integrity. - * The identification will be made base on the mode use. - *

- *

- * Bad modes: - *

    - *
  • ECB
  • - *
  • CBC
  • - *
  • OFB
  • - *
  • ...
  • - *
- *

- *

- * Safe modes: - *

    - *
  • CCM
  • - *
  • CWC
  • - *
  • OCB
  • - *
  • EAX
  • - *
  • GCM
  • - *
- *

- * Ref: Wikipedia: Authenticated encryption - */ -public class CipherWithNoIntegrityDetector extends OpcodeStackDetector { - - private static final String ECB_MODE_TYPE = "ECB_MODE"; - private static final String PADDING_ORACLE_TYPE = "PADDING_ORACLE"; - private static final String CIPHER_INTEGRITY_TYPE = "CIPHER_INTEGRITY"; - - private static final boolean DEBUG = false; - private static final List SECURE_CIPHER_MODES = Arrays.asList("CCM","CWC","OCB","EAX","GCM"); - - private BugReporter bugReporter; - - public CipherWithNoIntegrityDetector(BugReporter bugReporter) { - this.bugReporter = bugReporter; - } - - @Override - public void sawOpcode(int seen) { - if (seen == Constants.INVOKESTATIC && getClassConstantOperand().equals("javax/crypto/Cipher") && - getNameConstantOperand().equals("getInstance")) { - OpcodeStack.Item item = stack.getStackItem(stack.getStackDepth() - 1); //The first argument is last - if (StringTracer.isConstantString(item)) { - String cipherValue = (String) item.getConstant(); - if (DEBUG) System.out.println(cipherValue); - - //Ref for the list of potential ciphers : http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#impl - //Note: Not all ECB mode are vulnerable. see RSA/ECB/* - if (cipherValue.contains("AES/ECB/") || cipherValue.contains("DES/ECB/") || cipherValue.contains("DESede/ECB/")) { - bugReporter.reportBug(new BugInstance(this, ECB_MODE_TYPE, Priorities.HIGH_PRIORITY) // - .addClass(this).addMethod(this).addSourceLine(this)); - } - - if (cipherValue.contains("/CBC/PKCS5Padding")) { - bugReporter.reportBug(new BugInstance(this, PADDING_ORACLE_TYPE, Priorities.HIGH_PRIORITY) // - .addClass(this).addMethod(this).addSourceLine(this)); - } - - String[] cipherDefinition = cipherValue.split("/"); - String cipherMode = cipherDefinition[1]; - - if(!SECURE_CIPHER_MODES.contains(cipherMode)) { //Not a secure mode! - bugReporter.reportBug(new BugInstance(this, CIPHER_INTEGRITY_TYPE, Priorities.HIGH_PRIORITY) // - .addClass(this).addMethod(this).addSourceLine(this)); - } - } - } - } -} diff --git a/All/Genesis-OOB/Genesis#146/pair.info b/All/Genesis-OOB/Genesis#146/pair.info deleted file mode 100755 index f075053..0000000 --- a/All/Genesis-OOB/Genesis#146/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:146 -SATName:Genesis -modifiedFPath:plugin/src/main/java/com/h3xstream/findsecbugs/crypto/CipherWithNoIntegrityDetector.java -comSha:0572d7d -parentComSha:0572d7d^1 -githubUrl:https://github.com/h3xstream/find-sec-bugs -repoName:h3xstream#find-sec-bugs \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#147/comMsg.txt b/All/Genesis-OOB/Genesis#147/comMsg.txt deleted file mode 100755 index 38aa99f..0000000 --- a/All/Genesis-OOB/Genesis#147/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ - pools: fix parsing error in HsmRunSystem diff --git a/All/Genesis-OOB/Genesis#147/diff.diff b/All/Genesis-OOB/Genesis#147/diff.diff deleted file mode 100755 index cbfab89..0000000 --- a/All/Genesis-OOB/Genesis#147/diff.diff +++ /dev/null @@ -1,39 +0,0 @@ -diff --git a/modules/dcache/src/main/java/diskCacheV111/util/HsmRunSystem.java b/modules/dcache/src/main/java/diskCacheV111/util/HsmRunSystem.java -index 3569dad..027d5f1 100644 ---- a/modules/dcache/src/main/java/diskCacheV111/util/HsmRunSystem.java -+++ b/modules/dcache/src/main/java/diskCacheV111/util/HsmRunSystem.java -@@ -65,4 +65,17 @@ public class HsmRunSystem extends RunSystem -- int index = error.indexOf(PNFSID_TAG); -- if (index >= 0) { -- index += PNFSID_TAG.length(); -- ids.append(error.substring(index, error.indexOf("&", index))); -+ /* -+ * FIXME this method should not really be in this class, -+ * but in an enstore-specific script utility. -+ * The check for the end tag is a provisional work-around. -+ * -+ * NOTE: I am not sure whether the mere presence of the ampersand -+ * here denotes an enstore error string or not, so I've left -+ * each check as self-contained for the moment. -+ */ -+ int start = error.indexOf(PNFSID_TAG); -+ if (start >= 0) { -+ start += PNFSID_TAG.length(); -+ int end = error.indexOf("&", start); -+ if (end >= 0) { -+ ids.append(PNFSID_TAG) -+ .append(error.substring(start, end)); -+ } -@@ -71,4 +84,8 @@ public class HsmRunSystem extends RunSystem -- index = error.indexOf(BFID_TAG); -- if (index >= 0) { -- index += BFID_TAG.length(); -- ids.append(error.substring(index, error.indexOf("&", index))); -+ start = error.indexOf(BFID_TAG); -+ if (start >= 0) { -+ start += BFID_TAG.length(); -+ int end = error.indexOf("&", start); -+ if (end > 0) { -+ ids.append(BFID_TAG) -+ .append(error.substring(start, end)); -+ } diff --git a/All/Genesis-OOB/Genesis#147/new/HsmRunSystem.java b/All/Genesis-OOB/Genesis#147/new/HsmRunSystem.java deleted file mode 100755 index 027d5f1..0000000 --- a/All/Genesis-OOB/Genesis#147/new/HsmRunSystem.java +++ /dev/null @@ -1,104 +0,0 @@ -package diskCacheV111.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -import org.dcache.alarms.AlarmMarkerFactory; -import org.dcache.alarms.PredefinedAlarm; -import org.dcache.util.NetworkUtils; - -/** - * Utility class for invoking an HSM integration script. - */ -public class HsmRunSystem extends RunSystem -{ - private static final Logger LOGGER = LoggerFactory.getLogger(HsmRunSystem.class); - private static final String PNFSID_TAG = "pnfsid_file="; - private static final String BFID_TAG = "bfid="; - - private final String storageName; - - public HsmRunSystem(String storageName, String exec, int maxLines, long timeout) - { - super(exec, maxLines, timeout); - this.storageName = storageName; - } - - public String execute() throws IOException, CacheException - { - go(); - int returnCode = getExitValue(); - try { - switch (returnCode) { - case 0: - break; - case 71: - throw new CacheException(CacheException.HSM_DELAY_ERROR, - "HSM script failed (script reported 71: " - + getErrorString() + ")"); - case 143: - throw new TimeoutCacheException( - "HSM script was killed (script reported 143: " - + getErrorString() + ")"); - default: - throw new CacheException(returnCode, - "HSM script failed (script reported: " - + returnCode + ": " - + getErrorString()); - } - } catch (CacheException e) { - LOGGER.error(AlarmMarkerFactory.getMarker(PredefinedAlarm.HSM_SCRIPT_FAILURE, - NetworkUtils.getCanonicalHostName(), - storageName, - extractPossibleEnstoreIds(getErrorString())), - e.getMessage()); - throw e; - } - return getOutputString(); - } - - private String extractPossibleEnstoreIds(String error) { - StringBuilder ids = new StringBuilder(); - - /* - * FIXME this method should not really be in this class, - * but in an enstore-specific script utility. - * The check for the end tag is a provisional work-around. - * - * NOTE: I am not sure whether the mere presence of the ampersand - * here denotes an enstore error string or not, so I've left - * each check as self-contained for the moment. - */ - int start = error.indexOf(PNFSID_TAG); - if (start >= 0) { - start += PNFSID_TAG.length(); - int end = error.indexOf("&", start); - if (end >= 0) { - ids.append(PNFSID_TAG) - .append(error.substring(start, end)); - } - } - - start = error.indexOf(BFID_TAG); - if (start >= 0) { - start += BFID_TAG.length(); - int end = error.indexOf("&", start); - if (end > 0) { - ids.append(BFID_TAG) - .append(error.substring(start, end)); - } - } - - /* - * if the message does not contain data based on f_enstore2uri - * then just enforce a match on the error string. - */ - if (ids.length() == 0) { - ids.append(error); - } - - return ids.toString(); - } -} diff --git a/All/Genesis-OOB/Genesis#147/old/HsmRunSystem.java b/All/Genesis-OOB/Genesis#147/old/HsmRunSystem.java deleted file mode 100755 index 3569dad..0000000 --- a/All/Genesis-OOB/Genesis#147/old/HsmRunSystem.java +++ /dev/null @@ -1,87 +0,0 @@ -package diskCacheV111.util; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.IOException; - -import org.dcache.alarms.AlarmMarkerFactory; -import org.dcache.alarms.PredefinedAlarm; -import org.dcache.util.NetworkUtils; - -/** - * Utility class for invoking an HSM integration script. - */ -public class HsmRunSystem extends RunSystem -{ - private static final Logger LOGGER = LoggerFactory.getLogger(HsmRunSystem.class); - private static final String PNFSID_TAG = "pnfsid_file="; - private static final String BFID_TAG = "bfid="; - - private final String storageName; - - public HsmRunSystem(String storageName, String exec, int maxLines, long timeout) - { - super(exec, maxLines, timeout); - this.storageName = storageName; - } - - public String execute() throws IOException, CacheException - { - go(); - int returnCode = getExitValue(); - try { - switch (returnCode) { - case 0: - break; - case 71: - throw new CacheException(CacheException.HSM_DELAY_ERROR, - "HSM script failed (script reported 71: " - + getErrorString() + ")"); - case 143: - throw new TimeoutCacheException( - "HSM script was killed (script reported 143: " - + getErrorString() + ")"); - default: - throw new CacheException(returnCode, - "HSM script failed (script reported: " - + returnCode + ": " - + getErrorString()); - } - } catch (CacheException e) { - LOGGER.error(AlarmMarkerFactory.getMarker(PredefinedAlarm.HSM_SCRIPT_FAILURE, - NetworkUtils.getCanonicalHostName(), - storageName, - extractPossibleEnstoreIds(getErrorString())), - e.getMessage()); - throw e; - } - return getOutputString(); - } - - private String extractPossibleEnstoreIds(String error) { - StringBuilder ids = new StringBuilder(); - - int index = error.indexOf(PNFSID_TAG); - if (index >= 0) { - index += PNFSID_TAG.length(); - ids.append(error.substring(index, error.indexOf("&", index))); - } - - index = error.indexOf(BFID_TAG); - if (index >= 0) { - index += BFID_TAG.length(); - ids.append(error.substring(index, error.indexOf("&", index))); - } - - /* - * if the message does not contain data based on f_enstore2uri - * then just enforce a match on the error string. - */ - if (ids.length() == 0) { - ids.append(error); - } - - return ids.toString(); - } -} diff --git a/All/Genesis-OOB/Genesis#147/pair.info b/All/Genesis-OOB/Genesis#147/pair.info deleted file mode 100755 index 5915885..0000000 --- a/All/Genesis-OOB/Genesis#147/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:147 -SATName:Genesis -modifiedFPath:modules/dcache/src/main/java/diskCacheV111/util/HsmRunSystem.java -comSha:86e7494 -parentComSha:86e7494^1 -githubUrl:https://github.com/dCache/dcache -repoName:dCache#dcache \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#15/comMsg.txt b/All/Genesis-OOB/Genesis#15/comMsg.txt deleted file mode 100755 index 48f562c..0000000 --- a/All/Genesis-OOB/Genesis#15/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fix sharejoin bug-close connection,reason:program err:java.lang.IndexOutOfBoundsException diff --git a/All/Genesis-OOB/Genesis#15/diff.diff b/All/Genesis-OOB/Genesis#15/diff.diff deleted file mode 100755 index 00bf88c..0000000 --- a/All/Genesis-OOB/Genesis#15/diff.diff +++ /dev/null @@ -1,18 +0,0 @@ -diff --git a/src/main/java/io/mycat/sqlengine/sharejoin/TableFilter.java b/src/main/java/io/mycat/sqlengine/sharejoin/TableFilter.java -index 9be0911..1bb3829 100644 ---- a/src/main/java/io/mycat/sqlengine/sharejoin/TableFilter.java -+++ b/src/main/java/io/mycat/sqlengine/sharejoin/TableFilter.java -@@ -277 +277,9 @@ public class TableFilter { -- if (parent==null){ -+ if (parent==null){ // on/where -+ String parentJoinKey = getJoinKey(true); -+ // fix sharejoin bug -+ // (AbstractConnection.java:458) -close connection,reason:program err:java.lang.IndexOutOfBoundsException: -+ // select join -+ if(sql != null && parentJoinKey != null && -+ sql.toUpperCase().indexOf(parentJoinKey.trim().toUpperCase()) == -1){ -+ sql += ", " + parentJoinKey; -+ } -@@ -283 +291 @@ public class TableFilter { -- else { -+ else { // on/where diff --git a/All/Genesis-OOB/Genesis#15/new/TableFilter.java b/All/Genesis-OOB/Genesis#15/new/TableFilter.java deleted file mode 100755 index 1bb3829..0000000 --- a/All/Genesis-OOB/Genesis#15/new/TableFilter.java +++ /dev/null @@ -1,323 +0,0 @@ -package io.mycat.sqlengine.sharejoin; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -/** - * 功能详细描述:分片join,单独的语句 - * @author sohudo[http://blog.csdn.net/wind520] - * @create 2015年02月01日 - * @version 0.0.1 - */ - -public class TableFilter { - public static final Logger LOGGER = LoggerFactory - .getLogger(TableFilter.class); - - private LinkedHashMap fieldAliasMap = new LinkedHashMap(); - private String tName; - private String tAlia; - private String where=""; - private String order=""; - - private String parenTable="";//左连接的join的表 - private String joinParentkey="";//左连接的join字段 - private String joinKey=""; //join字段 - - private TableFilter join; - private TableFilter parent; - - private int offset=0; - private int rowCount=0; - - private boolean outJoin; - private boolean allField; - public TableFilter(String taName,String taAlia,boolean outJoin) { - this.tName=taName; - this.tAlia=taAlia; - this.outJoin=outJoin; - this.where=""; - } - - private String getTablefrom(String key){ - if (key==null){ - return ""; - } - else { - int i=key.indexOf('.'); - if (i==-1){ - return key; - } - else - return key.substring(0, i); - } - - } - private String getFieldfrom(String key){ - if (key==null){ - return ""; - } - else { - int i=key.indexOf('.'); - if (i==-1){ - return key; - } - else - return key.substring(i+1); - } - } - - public void addField(String fieldName,String fieldAlia){ - String atable=getTablefrom(fieldName); - String afield=getFieldfrom(fieldName); - boolean allfield=afield.equals("*")?true:false; - if (atable.equals("*")) { - fieldAliasMap.put(afield, null); - setAllField(allfield); - if (join!=null) { - join.addField(fieldName,null); - join.setAllField(allfield); - } - } - else { - if (atable.equals(tAlia)) { - fieldAliasMap.put(afield, fieldAlia); - setAllField(allfield); - } - else { - if (join!=null) { - join.addField(fieldName,fieldAlia); - join.setAllField(allfield); - } - } - } - } - - public void addWhere(String fieldName,String value,String Operator,String and){ - String atable=getTablefrom(fieldName); - String afield=getFieldfrom(fieldName); - if (atable.equals(tAlia)) { - where=unionsql(where,afield+Operator+value,and); - } - else { - if (join!=null) { - join.addWhere(fieldName,value,Operator,and); - } - } - } - - private String unionsql(String key,String value,String Operator){ - if (key.trim().equals("")){ - key=value; - } - else { - key+=" "+Operator+" "+value; - } - return key; - } - - public void addOrders(String fieldName,String des){ - String atable=getTablefrom(fieldName); - String afield=getFieldfrom(fieldName); - if (atable.equals(tAlia)) { - order=unionsql(order,afield+" "+des,","); - } - else { - if (join!=null) { - join.addOrders(fieldName,des); - } - } - } - public void addLimit(int offset,int rowCount){ - this.offset=offset; - this.rowCount=rowCount; - } - public void setJoinKey(String fieldName,String value){ - if (parent==null){ - if (join!=null) { - join.setJoinKey(fieldName,value); - } - } - else { - int i=joinLkey(fieldName,value); - if (i==1){ - joinParentkey=getFieldfrom(value); - parenTable =getTablefrom(value); - joinKey=getFieldfrom(fieldName); - } - else { - if (i==2){ - joinParentkey=getFieldfrom(fieldName); - parenTable =getTablefrom(fieldName); - joinKey=getFieldfrom(value); - } - else { - if (join!=null) { - join.setJoinKey(fieldName,value); - } - } - } - } - } - - private String getChildJoinKey(boolean left){ - if (join!=null){ - if (left) { - return join.joinParentkey; - } - else { - return join.joinKey; - } - } - else { - return ""; - } - } - public String getJoinKey(boolean left){ - return getChildJoinKey(left); - } - private int joinLkey(String fieldName,String value){ - String key1=getTablefrom(fieldName); - String key2=getTablefrom(value); - if (key1.equals(tAlia) ) { - return 1; - } - - if (key2.equals(tAlia) ) { - return 2; - } - /* - String bAlia=""; - if (join!=null){ - bAlia=join.getTableAlia(); - } - if (key1.equals(tAlia)&& key2.equals(bAlia) ) { - return 1; - } - - if (key2.equals(tAlia)&& key1.equals(bAlia) ) { - return 2; - } - */ - return 0; - } - - public String getTableName(){ - return tName; - } - public void setTableName(String value){ - tName=value; - } - - public String getTableAlia(){ - return tAlia; - } - public void setTableAlia(String value){ - tAlia=value; - } - - public boolean getOutJoin(){ - return outJoin; - } - public void setOutJoin(boolean value){ - outJoin=value; - } - - - public boolean getAllField(){ - return allField; - } - public void setAllField(boolean value){ - allField=value; - } - - public TableFilter getTableJoin(){ - return join; - } - public void setTableJoin(TableFilter value){ - join=value; - join.setParent(this); - } - public TableFilter getParent() { - return parent; - } - - public void setParent(TableFilter parent) { - this.parent = parent; - } - - private String unionField(String field,String key,String Operator){ - if (key.trim().equals("")){ - key=field; - } - else { - key=field+Operator+" "+key; - } - return key; - } - - public String getSQL(){ - String sql=""; - Iterator> iter = fieldAliasMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - String key = entry.getKey(); - String val = entry.getValue(); - if (val==null) { - sql=unionsql(sql,getFieldfrom(key),","); - } - else - sql=unionsql(sql,getFieldfrom(key)+" as "+val,","); - } - if (parent==null){ // on/where 等于号左边的表 - String parentJoinKey = getJoinKey(true); - // fix sharejoin bug: - // (AbstractConnection.java:458) -close connection,reason:program err:java.lang.IndexOutOfBoundsException: - // 原因是左表的select列没有包含 join 列,在获取结果时报上面的错误 - if(sql != null && parentJoinKey != null && - sql.toUpperCase().indexOf(parentJoinKey.trim().toUpperCase()) == -1){ - sql += ", " + parentJoinKey; - } - sql="select "+sql+" from "+tName; - if (!(where.trim().equals(""))){ - sql+=" where "+where.trim(); - } - } - else { // on/where 等于号右边边的表 - if (allField) { - sql="select "+sql+" from "+tName; - } - else { - sql=unionField("select "+joinKey,sql,","); - sql=sql+" from "+tName; - //sql="select "+joinKey+","+sql+" from "+tName; - } - if (!(where.trim().equals(""))){ - sql+=" where "+where.trim()+" and ("+joinKey+" in %s )"; - } - else { - sql+=" where "+joinKey+" in %s "; - } - } - - if (!(order.trim().equals(""))){ - sql+=" order by "+order.trim(); - } - if (parent==null){ - if ((rowCount>0)&& (offset>0)){ - sql+=" limit"+offset+","+rowCount; - } - else { - if (rowCount>0){ - sql+=" limit "+rowCount; - } - } - } - return sql; - } -} diff --git a/All/Genesis-OOB/Genesis#15/old/TableFilter.java b/All/Genesis-OOB/Genesis#15/old/TableFilter.java deleted file mode 100755 index 9be0911..0000000 --- a/All/Genesis-OOB/Genesis#15/old/TableFilter.java +++ /dev/null @@ -1,315 +0,0 @@ -package io.mycat.sqlengine.sharejoin; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -/** - * 功能详细描述:分片join,单独的语句 - * @author sohudo[http://blog.csdn.net/wind520] - * @create 2015年02月01日 - * @version 0.0.1 - */ - -public class TableFilter { - public static final Logger LOGGER = LoggerFactory - .getLogger(TableFilter.class); - - private LinkedHashMap fieldAliasMap = new LinkedHashMap(); - private String tName; - private String tAlia; - private String where=""; - private String order=""; - - private String parenTable="";//左连接的join的表 - private String joinParentkey="";//左连接的join字段 - private String joinKey=""; //join字段 - - private TableFilter join; - private TableFilter parent; - - private int offset=0; - private int rowCount=0; - - private boolean outJoin; - private boolean allField; - public TableFilter(String taName,String taAlia,boolean outJoin) { - this.tName=taName; - this.tAlia=taAlia; - this.outJoin=outJoin; - this.where=""; - } - - private String getTablefrom(String key){ - if (key==null){ - return ""; - } - else { - int i=key.indexOf('.'); - if (i==-1){ - return key; - } - else - return key.substring(0, i); - } - - } - private String getFieldfrom(String key){ - if (key==null){ - return ""; - } - else { - int i=key.indexOf('.'); - if (i==-1){ - return key; - } - else - return key.substring(i+1); - } - } - - public void addField(String fieldName,String fieldAlia){ - String atable=getTablefrom(fieldName); - String afield=getFieldfrom(fieldName); - boolean allfield=afield.equals("*")?true:false; - if (atable.equals("*")) { - fieldAliasMap.put(afield, null); - setAllField(allfield); - if (join!=null) { - join.addField(fieldName,null); - join.setAllField(allfield); - } - } - else { - if (atable.equals(tAlia)) { - fieldAliasMap.put(afield, fieldAlia); - setAllField(allfield); - } - else { - if (join!=null) { - join.addField(fieldName,fieldAlia); - join.setAllField(allfield); - } - } - } - } - - public void addWhere(String fieldName,String value,String Operator,String and){ - String atable=getTablefrom(fieldName); - String afield=getFieldfrom(fieldName); - if (atable.equals(tAlia)) { - where=unionsql(where,afield+Operator+value,and); - } - else { - if (join!=null) { - join.addWhere(fieldName,value,Operator,and); - } - } - } - - private String unionsql(String key,String value,String Operator){ - if (key.trim().equals("")){ - key=value; - } - else { - key+=" "+Operator+" "+value; - } - return key; - } - - public void addOrders(String fieldName,String des){ - String atable=getTablefrom(fieldName); - String afield=getFieldfrom(fieldName); - if (atable.equals(tAlia)) { - order=unionsql(order,afield+" "+des,","); - } - else { - if (join!=null) { - join.addOrders(fieldName,des); - } - } - } - public void addLimit(int offset,int rowCount){ - this.offset=offset; - this.rowCount=rowCount; - } - public void setJoinKey(String fieldName,String value){ - if (parent==null){ - if (join!=null) { - join.setJoinKey(fieldName,value); - } - } - else { - int i=joinLkey(fieldName,value); - if (i==1){ - joinParentkey=getFieldfrom(value); - parenTable =getTablefrom(value); - joinKey=getFieldfrom(fieldName); - } - else { - if (i==2){ - joinParentkey=getFieldfrom(fieldName); - parenTable =getTablefrom(fieldName); - joinKey=getFieldfrom(value); - } - else { - if (join!=null) { - join.setJoinKey(fieldName,value); - } - } - } - } - } - - private String getChildJoinKey(boolean left){ - if (join!=null){ - if (left) { - return join.joinParentkey; - } - else { - return join.joinKey; - } - } - else { - return ""; - } - } - public String getJoinKey(boolean left){ - return getChildJoinKey(left); - } - private int joinLkey(String fieldName,String value){ - String key1=getTablefrom(fieldName); - String key2=getTablefrom(value); - if (key1.equals(tAlia) ) { - return 1; - } - - if (key2.equals(tAlia) ) { - return 2; - } - /* - String bAlia=""; - if (join!=null){ - bAlia=join.getTableAlia(); - } - if (key1.equals(tAlia)&& key2.equals(bAlia) ) { - return 1; - } - - if (key2.equals(tAlia)&& key1.equals(bAlia) ) { - return 2; - } - */ - return 0; - } - - public String getTableName(){ - return tName; - } - public void setTableName(String value){ - tName=value; - } - - public String getTableAlia(){ - return tAlia; - } - public void setTableAlia(String value){ - tAlia=value; - } - - public boolean getOutJoin(){ - return outJoin; - } - public void setOutJoin(boolean value){ - outJoin=value; - } - - - public boolean getAllField(){ - return allField; - } - public void setAllField(boolean value){ - allField=value; - } - - public TableFilter getTableJoin(){ - return join; - } - public void setTableJoin(TableFilter value){ - join=value; - join.setParent(this); - } - public TableFilter getParent() { - return parent; - } - - public void setParent(TableFilter parent) { - this.parent = parent; - } - - private String unionField(String field,String key,String Operator){ - if (key.trim().equals("")){ - key=field; - } - else { - key=field+Operator+" "+key; - } - return key; - } - - public String getSQL(){ - String sql=""; - Iterator> iter = fieldAliasMap.entrySet().iterator(); - while (iter.hasNext()) { - Map.Entry entry = (Map.Entry) iter.next(); - String key = entry.getKey(); - String val = entry.getValue(); - if (val==null) { - sql=unionsql(sql,getFieldfrom(key),","); - } - else - sql=unionsql(sql,getFieldfrom(key)+" as "+val,","); - } - if (parent==null){ - sql="select "+sql+" from "+tName; - if (!(where.trim().equals(""))){ - sql+=" where "+where.trim(); - } - } - else { - if (allField) { - sql="select "+sql+" from "+tName; - } - else { - sql=unionField("select "+joinKey,sql,","); - sql=sql+" from "+tName; - //sql="select "+joinKey+","+sql+" from "+tName; - } - if (!(where.trim().equals(""))){ - sql+=" where "+where.trim()+" and ("+joinKey+" in %s )"; - } - else { - sql+=" where "+joinKey+" in %s "; - } - } - - if (!(order.trim().equals(""))){ - sql+=" order by "+order.trim(); - } - if (parent==null){ - if ((rowCount>0)&& (offset>0)){ - sql+=" limit"+offset+","+rowCount; - } - else { - if (rowCount>0){ - sql+=" limit "+rowCount; - } - } - } - return sql; - } -} diff --git a/All/Genesis-OOB/Genesis#15/pair.info b/All/Genesis-OOB/Genesis#15/pair.info deleted file mode 100755 index 47656b2..0000000 --- a/All/Genesis-OOB/Genesis#15/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:15 -SATName:Genesis -modifiedFPath:src/main/java/io/mycat/sqlengine/sharejoin/TableFilter.java -comSha:b10a0c9dc33e7568d8963a945d46123d5ab58377 -parentComSha:b10a0c9dc33e7568d8963a945d46123d5ab58377^1 -githubUrl:https://github.com/MyCATApache/Mycat-Server -repoName:MyCATApache#Mycat-Server \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#157/comMsg.txt b/All/Genesis-OOB/Genesis#157/comMsg.txt deleted file mode 100755 index cb9f406..0000000 --- a/All/Genesis-OOB/Genesis#157/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -IndexOutOfBoundsException fixed. #349 diff --git a/All/Genesis-OOB/Genesis#157/diff.diff b/All/Genesis-OOB/Genesis#157/diff.diff deleted file mode 100755 index 37cdf0f..0000000 --- a/All/Genesis-OOB/Genesis#157/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/com/corundumstudio/socketio/protocol/PacketDecoder.java b/src/main/java/com/corundumstudio/socketio/protocol/PacketDecoder.java -index 1be5e58..f6a0f89 100644 ---- a/src/main/java/com/corundumstudio/socketio/protocol/PacketDecoder.java -+++ b/src/main/java/com/corundumstudio/socketio/protocol/PacketDecoder.java -@@ -122 +122,2 @@ public class PacketDecoder { -- int headEndIndex = buffer.bytesBefore(10, (byte)-1); -+ int maxLength = Math.min(buffer.readableBytes(), 10); -+ int headEndIndex = buffer.bytesBefore(maxLength, (byte)-1); -@@ -124 +125 @@ public class PacketDecoder { -- headEndIndex = buffer.bytesBefore(10, (byte)0x3f); -+ headEndIndex = buffer.bytesBefore(maxLength, (byte)0x3f); diff --git a/All/Genesis-OOB/Genesis#157/new/PacketDecoder.java b/All/Genesis-OOB/Genesis#157/new/PacketDecoder.java deleted file mode 100755 index f6a0f89..0000000 --- a/All/Genesis-OOB/Genesis#157/new/PacketDecoder.java +++ /dev/null @@ -1,312 +0,0 @@ -/** - * Copyright 2012 Nikita Koksharov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.corundumstudio.socketio.protocol; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufInputStream; -import io.netty.buffer.Unpooled; -import io.netty.handler.codec.base64.Base64; -import io.netty.util.CharsetUtil; - -import java.io.IOException; -import java.net.URLDecoder; -import java.util.LinkedList; -import java.util.UUID; - -import com.corundumstudio.socketio.AckCallback; -import com.corundumstudio.socketio.ack.AckManager; -import com.corundumstudio.socketio.handler.ClientHead; - -public class PacketDecoder { - - private final UTF8CharsScanner utf8scanner = new UTF8CharsScanner(); - - private final ByteBuf QUOTES = Unpooled.copiedBuffer("\"", CharsetUtil.UTF_8); - - private final JsonSupport jsonSupport; - private final AckManager ackManager; - - public PacketDecoder(JsonSupport jsonSupport, AckManager ackManager) { - this.jsonSupport = jsonSupport; - this.ackManager = ackManager; - } - - private boolean isStringPacket(ByteBuf content) { - return content.getByte(content.readerIndex()) == 0x0; - } - - // TODO optimize - public ByteBuf preprocessJson(Integer jsonIndex, ByteBuf content) throws IOException { - String packet = URLDecoder.decode(content.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8.name()); - - if (jsonIndex != null) { - /** - * double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side - * (c) socket.io.js - * - * @see https://github.com/Automattic/socket.io-client/blob/1.3.3/socket.io.js#L2682 - */ - packet = packet.replace("\\\\n", "\\n"); - - // skip "d=" - packet = packet.substring(2); - } - packet = new String(packet.getBytes(CharsetUtil.ISO_8859_1), CharsetUtil.UTF_8); - - return Unpooled.wrappedBuffer(packet.getBytes(CharsetUtil.UTF_8)); - } - - // fastest way to parse chars to int - private long readLong(ByteBuf chars, int length) { - long result = 0; - for (int i = chars.readerIndex(); i < chars.readerIndex() + length; i++) { - int digit = ((int)chars.getByte(i) & 0xF); - for (int j = 0; j < chars.readerIndex() + length-1-i; j++) { - digit *= 10; - } - result += digit; - } - chars.readerIndex(chars.readerIndex() + length); - return result; - } - - private PacketType readType(ByteBuf buffer) { - int typeId = buffer.readByte() & 0xF; - return PacketType.valueOf(typeId); - } - - private PacketType readInnerType(ByteBuf buffer) { - int typeId = buffer.readByte() & 0xF; - return PacketType.valueOfInner(typeId); - } - - @Deprecated - public Packet decodePacket(String string, UUID uuid) throws IOException { - ByteBuf buf = Unpooled.copiedBuffer(string, CharsetUtil.UTF_8); - try { - return null; - } finally { - buf.release(); - } - } - - private boolean hasLengthHeader(ByteBuf buffer) { - for (int i = 0; i < Math.min(buffer.readableBytes(), 10); i++) { - byte b = buffer.getByte(buffer.readerIndex() + i); - if (b == (byte)':' && i > 0) { - return true; - } - if (b > 57 || b < 48) { - return false; - } - } - return false; - } - - public Packet decodePackets(ByteBuf buffer, ClientHead client) throws IOException { - if (isStringPacket(buffer)) { - // TODO refactor - int maxLength = Math.min(buffer.readableBytes(), 10); - int headEndIndex = buffer.bytesBefore(maxLength, (byte)-1); - if (headEndIndex == -1) { - headEndIndex = buffer.bytesBefore(maxLength, (byte)0x3f); - } - int len = (int) readLong(buffer, headEndIndex); - - ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len); - // skip this frame - buffer.readerIndex(buffer.readerIndex() + 1 + len); - return decode(client, frame); - } else if (hasLengthHeader(buffer)) { - // TODO refactor - int lengthEndIndex = buffer.bytesBefore((byte)':'); - int lenHeader = (int) readLong(buffer, lengthEndIndex); - int len = utf8scanner.getActualLength(buffer, lenHeader); - - ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len); - if (lenHeader != len) { - frame = Unpooled.wrappedBuffer(frame.toString(CharsetUtil.UTF_8).getBytes(CharsetUtil.ISO_8859_1)); - } - // skip this frame - buffer.readerIndex(buffer.readerIndex() + 1 + len); - return decode(client, frame); - } - return decode(client, buffer); - } - - private String readString(ByteBuf frame) { - return readString(frame, frame.readableBytes()); - } - - private String readString(ByteBuf frame, int size) { - byte[] bytes = new byte[size]; - frame.readBytes(bytes); - return new String(bytes, CharsetUtil.UTF_8); - } - - private Packet decode(ClientHead head, ByteBuf frame) throws IOException { - if ((frame.getByte(0) == 'b' && frame.getByte(1) == '4') - || frame.getByte(0) == 4 || frame.getByte(0) == 1) { - return parseBinary(head, frame); - } - PacketType type = readType(frame); - Packet packet = new Packet(type); - - if (type == PacketType.PING) { - packet.setData(readString(frame)); - return packet; - } - - if (!frame.isReadable()) { - return packet; - } - - PacketType innerType = readInnerType(frame); - packet.setSubType(innerType); - - parseHeader(frame, packet, innerType); - parseBody(head, frame, packet); - return packet; - } - - private void parseHeader(ByteBuf frame, Packet packet, PacketType innerType) { - int endIndex = frame.bytesBefore((byte)'['); - if (endIndex <= 0) { - return; - } - - int attachmentsDividerIndex = frame.bytesBefore(endIndex, (byte)'-'); - boolean hasAttachments = attachmentsDividerIndex != -1; - if (hasAttachments && PacketType.BINARY_EVENT.equals(innerType)) { - int attachments = (int) readLong(frame, attachmentsDividerIndex); - packet.initAttachments(attachments); - frame.readerIndex(frame.readerIndex() + 1); - - endIndex -= attachmentsDividerIndex + 1; - } - if (endIndex == 0) { - return; - } - - // TODO optimize - boolean hasNsp = frame.bytesBefore(endIndex, (byte)',') != -1; - if (hasNsp) { - String nspAckId = readString(frame, endIndex); - String[] parts = nspAckId.split(","); - String nsp = parts[0]; - packet.setNsp(nsp); - if (parts.length > 1) { - String ackId = parts[1]; - packet.setAckId(Long.valueOf(ackId)); - } - } else { - long ackId = readLong(frame, endIndex); - packet.setAckId(ackId); - } - } - - private Packet parseBinary(ClientHead head, ByteBuf frame) throws IOException { - if (frame.getByte(0) == 1) { - frame.readByte(); - int headEndIndex = frame.bytesBefore((byte)-1); - int len = (int) readLong(frame, headEndIndex); - ByteBuf oldFrame = frame; - frame = frame.slice(oldFrame.readerIndex() + 1, len); - oldFrame.readerIndex(oldFrame.readerIndex() + 1 + len); - } - - if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') { - frame.readShort(); - } else if (frame.getByte(0) == 4) { - frame.readByte(); - } - - Packet binaryPacket = head.getLastBinaryPacket(); - if (binaryPacket != null) { - ByteBuf attachBuf; - if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') { - attachBuf = frame; - } else { - attachBuf = Base64.encode(frame); - } - binaryPacket.addAttachment(Unpooled.copiedBuffer(attachBuf)); - frame.readerIndex(frame.readerIndex() + frame.readableBytes()); - - if (binaryPacket.isAttachmentsLoaded()) { - LinkedList slices = new LinkedList(); - ByteBuf source = binaryPacket.getDataSource(); - for (int i = 0; i < binaryPacket.getAttachments().size(); i++) { - ByteBuf attachment = binaryPacket.getAttachments().get(i); - ByteBuf scanValue = Unpooled.copiedBuffer("{\"_placeholder\":true,\"num\":" + i + "}", CharsetUtil.UTF_8); - int pos = PacketEncoder.find(source, scanValue); - if (pos == -1) { - scanValue = Unpooled.copiedBuffer("{\"num\":" + i + ",\"_placeholder\":true}", CharsetUtil.UTF_8); - pos = PacketEncoder.find(source, scanValue); - if (pos == -1) { - throw new IllegalStateException("Can't find attachment by index: " + i + " in packet source"); - } - } - - ByteBuf prefixBuf = source.slice(source.readerIndex(), pos - source.readerIndex()); - slices.add(prefixBuf); - slices.add(QUOTES); - slices.add(attachment); - slices.add(QUOTES); - - source.readerIndex(pos + scanValue.readableBytes()); - } - slices.add(source.slice()); - - ByteBuf compositeBuf = Unpooled.wrappedBuffer(slices.toArray(new ByteBuf[slices.size()])); - parseBody(head, compositeBuf, binaryPacket); - head.setLastBinaryPacket(null); - return binaryPacket; - } - } - return new Packet(PacketType.MESSAGE); - } - - private void parseBody(ClientHead head, ByteBuf frame, Packet packet) throws IOException { - if (packet.getType() == PacketType.MESSAGE) { - if (packet.getSubType() == PacketType.CONNECT - || packet.getSubType() == PacketType.DISCONNECT) { - packet.setNsp(readString(frame)); - } - - if (packet.getSubType() == PacketType.ACK) { - ByteBufInputStream in = new ByteBufInputStream(frame); - AckCallback callback = ackManager.getCallback(head.getSessionId(), packet.getAckId()); - AckArgs args = jsonSupport.readAckArgs(in, callback); - packet.setData(args.getArgs()); - } - - if (packet.getSubType() == PacketType.EVENT - || packet.getSubType() == PacketType.BINARY_EVENT) { - if (packet.hasAttachments() && !packet.isAttachmentsLoaded()) { - packet.setDataSource(Unpooled.copiedBuffer(frame)); - frame.readerIndex(frame.readableBytes()); - head.setLastBinaryPacket(packet); - } else { - ByteBufInputStream in = new ByteBufInputStream(frame); - Event event = jsonSupport.readValue(packet.getNsp(), in, Event.class); - packet.setName(event.getName()); - packet.setData(event.getArgs()); - } - } - } - } - -} diff --git a/All/Genesis-OOB/Genesis#157/old/PacketDecoder.java b/All/Genesis-OOB/Genesis#157/old/PacketDecoder.java deleted file mode 100755 index 1be5e58..0000000 --- a/All/Genesis-OOB/Genesis#157/old/PacketDecoder.java +++ /dev/null @@ -1,311 +0,0 @@ -/** - * Copyright 2012 Nikita Koksharov - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.corundumstudio.socketio.protocol; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufInputStream; -import io.netty.buffer.Unpooled; -import io.netty.handler.codec.base64.Base64; -import io.netty.util.CharsetUtil; - -import java.io.IOException; -import java.net.URLDecoder; -import java.util.LinkedList; -import java.util.UUID; - -import com.corundumstudio.socketio.AckCallback; -import com.corundumstudio.socketio.ack.AckManager; -import com.corundumstudio.socketio.handler.ClientHead; - -public class PacketDecoder { - - private final UTF8CharsScanner utf8scanner = new UTF8CharsScanner(); - - private final ByteBuf QUOTES = Unpooled.copiedBuffer("\"", CharsetUtil.UTF_8); - - private final JsonSupport jsonSupport; - private final AckManager ackManager; - - public PacketDecoder(JsonSupport jsonSupport, AckManager ackManager) { - this.jsonSupport = jsonSupport; - this.ackManager = ackManager; - } - - private boolean isStringPacket(ByteBuf content) { - return content.getByte(content.readerIndex()) == 0x0; - } - - // TODO optimize - public ByteBuf preprocessJson(Integer jsonIndex, ByteBuf content) throws IOException { - String packet = URLDecoder.decode(content.toString(CharsetUtil.UTF_8), CharsetUtil.UTF_8.name()); - - if (jsonIndex != null) { - /** - * double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side - * (c) socket.io.js - * - * @see https://github.com/Automattic/socket.io-client/blob/1.3.3/socket.io.js#L2682 - */ - packet = packet.replace("\\\\n", "\\n"); - - // skip "d=" - packet = packet.substring(2); - } - packet = new String(packet.getBytes(CharsetUtil.ISO_8859_1), CharsetUtil.UTF_8); - - return Unpooled.wrappedBuffer(packet.getBytes(CharsetUtil.UTF_8)); - } - - // fastest way to parse chars to int - private long readLong(ByteBuf chars, int length) { - long result = 0; - for (int i = chars.readerIndex(); i < chars.readerIndex() + length; i++) { - int digit = ((int)chars.getByte(i) & 0xF); - for (int j = 0; j < chars.readerIndex() + length-1-i; j++) { - digit *= 10; - } - result += digit; - } - chars.readerIndex(chars.readerIndex() + length); - return result; - } - - private PacketType readType(ByteBuf buffer) { - int typeId = buffer.readByte() & 0xF; - return PacketType.valueOf(typeId); - } - - private PacketType readInnerType(ByteBuf buffer) { - int typeId = buffer.readByte() & 0xF; - return PacketType.valueOfInner(typeId); - } - - @Deprecated - public Packet decodePacket(String string, UUID uuid) throws IOException { - ByteBuf buf = Unpooled.copiedBuffer(string, CharsetUtil.UTF_8); - try { - return null; - } finally { - buf.release(); - } - } - - private boolean hasLengthHeader(ByteBuf buffer) { - for (int i = 0; i < Math.min(buffer.readableBytes(), 10); i++) { - byte b = buffer.getByte(buffer.readerIndex() + i); - if (b == (byte)':' && i > 0) { - return true; - } - if (b > 57 || b < 48) { - return false; - } - } - return false; - } - - public Packet decodePackets(ByteBuf buffer, ClientHead client) throws IOException { - if (isStringPacket(buffer)) { - // TODO refactor - int headEndIndex = buffer.bytesBefore(10, (byte)-1); - if (headEndIndex == -1) { - headEndIndex = buffer.bytesBefore(10, (byte)0x3f); - } - int len = (int) readLong(buffer, headEndIndex); - - ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len); - // skip this frame - buffer.readerIndex(buffer.readerIndex() + 1 + len); - return decode(client, frame); - } else if (hasLengthHeader(buffer)) { - // TODO refactor - int lengthEndIndex = buffer.bytesBefore((byte)':'); - int lenHeader = (int) readLong(buffer, lengthEndIndex); - int len = utf8scanner.getActualLength(buffer, lenHeader); - - ByteBuf frame = buffer.slice(buffer.readerIndex() + 1, len); - if (lenHeader != len) { - frame = Unpooled.wrappedBuffer(frame.toString(CharsetUtil.UTF_8).getBytes(CharsetUtil.ISO_8859_1)); - } - // skip this frame - buffer.readerIndex(buffer.readerIndex() + 1 + len); - return decode(client, frame); - } - return decode(client, buffer); - } - - private String readString(ByteBuf frame) { - return readString(frame, frame.readableBytes()); - } - - private String readString(ByteBuf frame, int size) { - byte[] bytes = new byte[size]; - frame.readBytes(bytes); - return new String(bytes, CharsetUtil.UTF_8); - } - - private Packet decode(ClientHead head, ByteBuf frame) throws IOException { - if ((frame.getByte(0) == 'b' && frame.getByte(1) == '4') - || frame.getByte(0) == 4 || frame.getByte(0) == 1) { - return parseBinary(head, frame); - } - PacketType type = readType(frame); - Packet packet = new Packet(type); - - if (type == PacketType.PING) { - packet.setData(readString(frame)); - return packet; - } - - if (!frame.isReadable()) { - return packet; - } - - PacketType innerType = readInnerType(frame); - packet.setSubType(innerType); - - parseHeader(frame, packet, innerType); - parseBody(head, frame, packet); - return packet; - } - - private void parseHeader(ByteBuf frame, Packet packet, PacketType innerType) { - int endIndex = frame.bytesBefore((byte)'['); - if (endIndex <= 0) { - return; - } - - int attachmentsDividerIndex = frame.bytesBefore(endIndex, (byte)'-'); - boolean hasAttachments = attachmentsDividerIndex != -1; - if (hasAttachments && PacketType.BINARY_EVENT.equals(innerType)) { - int attachments = (int) readLong(frame, attachmentsDividerIndex); - packet.initAttachments(attachments); - frame.readerIndex(frame.readerIndex() + 1); - - endIndex -= attachmentsDividerIndex + 1; - } - if (endIndex == 0) { - return; - } - - // TODO optimize - boolean hasNsp = frame.bytesBefore(endIndex, (byte)',') != -1; - if (hasNsp) { - String nspAckId = readString(frame, endIndex); - String[] parts = nspAckId.split(","); - String nsp = parts[0]; - packet.setNsp(nsp); - if (parts.length > 1) { - String ackId = parts[1]; - packet.setAckId(Long.valueOf(ackId)); - } - } else { - long ackId = readLong(frame, endIndex); - packet.setAckId(ackId); - } - } - - private Packet parseBinary(ClientHead head, ByteBuf frame) throws IOException { - if (frame.getByte(0) == 1) { - frame.readByte(); - int headEndIndex = frame.bytesBefore((byte)-1); - int len = (int) readLong(frame, headEndIndex); - ByteBuf oldFrame = frame; - frame = frame.slice(oldFrame.readerIndex() + 1, len); - oldFrame.readerIndex(oldFrame.readerIndex() + 1 + len); - } - - if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') { - frame.readShort(); - } else if (frame.getByte(0) == 4) { - frame.readByte(); - } - - Packet binaryPacket = head.getLastBinaryPacket(); - if (binaryPacket != null) { - ByteBuf attachBuf; - if (frame.getByte(0) == 'b' && frame.getByte(1) == '4') { - attachBuf = frame; - } else { - attachBuf = Base64.encode(frame); - } - binaryPacket.addAttachment(Unpooled.copiedBuffer(attachBuf)); - frame.readerIndex(frame.readerIndex() + frame.readableBytes()); - - if (binaryPacket.isAttachmentsLoaded()) { - LinkedList slices = new LinkedList(); - ByteBuf source = binaryPacket.getDataSource(); - for (int i = 0; i < binaryPacket.getAttachments().size(); i++) { - ByteBuf attachment = binaryPacket.getAttachments().get(i); - ByteBuf scanValue = Unpooled.copiedBuffer("{\"_placeholder\":true,\"num\":" + i + "}", CharsetUtil.UTF_8); - int pos = PacketEncoder.find(source, scanValue); - if (pos == -1) { - scanValue = Unpooled.copiedBuffer("{\"num\":" + i + ",\"_placeholder\":true}", CharsetUtil.UTF_8); - pos = PacketEncoder.find(source, scanValue); - if (pos == -1) { - throw new IllegalStateException("Can't find attachment by index: " + i + " in packet source"); - } - } - - ByteBuf prefixBuf = source.slice(source.readerIndex(), pos - source.readerIndex()); - slices.add(prefixBuf); - slices.add(QUOTES); - slices.add(attachment); - slices.add(QUOTES); - - source.readerIndex(pos + scanValue.readableBytes()); - } - slices.add(source.slice()); - - ByteBuf compositeBuf = Unpooled.wrappedBuffer(slices.toArray(new ByteBuf[slices.size()])); - parseBody(head, compositeBuf, binaryPacket); - head.setLastBinaryPacket(null); - return binaryPacket; - } - } - return new Packet(PacketType.MESSAGE); - } - - private void parseBody(ClientHead head, ByteBuf frame, Packet packet) throws IOException { - if (packet.getType() == PacketType.MESSAGE) { - if (packet.getSubType() == PacketType.CONNECT - || packet.getSubType() == PacketType.DISCONNECT) { - packet.setNsp(readString(frame)); - } - - if (packet.getSubType() == PacketType.ACK) { - ByteBufInputStream in = new ByteBufInputStream(frame); - AckCallback callback = ackManager.getCallback(head.getSessionId(), packet.getAckId()); - AckArgs args = jsonSupport.readAckArgs(in, callback); - packet.setData(args.getArgs()); - } - - if (packet.getSubType() == PacketType.EVENT - || packet.getSubType() == PacketType.BINARY_EVENT) { - if (packet.hasAttachments() && !packet.isAttachmentsLoaded()) { - packet.setDataSource(Unpooled.copiedBuffer(frame)); - frame.readerIndex(frame.readableBytes()); - head.setLastBinaryPacket(packet); - } else { - ByteBufInputStream in = new ByteBufInputStream(frame); - Event event = jsonSupport.readValue(packet.getNsp(), in, Event.class); - packet.setName(event.getName()); - packet.setData(event.getArgs()); - } - } - } - } - -} diff --git a/All/Genesis-OOB/Genesis#157/pair.info b/All/Genesis-OOB/Genesis#157/pair.info deleted file mode 100755 index 83d6897..0000000 --- a/All/Genesis-OOB/Genesis#157/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:157 -SATName:Genesis -modifiedFPath:src/main/java/com/corundumstudio/socketio/protocol/PacketDecoder.java -comSha:8d63b89 -parentComSha:8d63b89^1 -githubUrl:https://github.com/mrniko/netty-socketio -repoName:mrniko#netty-socketio \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#176/comMsg.txt b/All/Genesis-OOB/Genesis#176/comMsg.txt deleted file mode 100755 index 1f13c20..0000000 --- a/All/Genesis-OOB/Genesis#176/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -HTTPCORE-263: Under rare circumstances incorrectly delineated or garbled HTTP message can cause an IndexOutOfBoundsException in AbstractSessionInputBuffer#readLine() Contributed by Michael Pujos diff --git a/All/Genesis-OOB/Genesis#176/diff.diff b/All/Genesis-OOB/Genesis#176/diff.diff deleted file mode 100755 index f0e7887..0000000 --- a/All/Genesis-OOB/Genesis#176/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/httpcore/src/main/java/org/apache/http/impl/io/AbstractSessionInputBuffer.java b/httpcore/src/main/java/org/apache/http/impl/io/AbstractSessionInputBuffer.java -index fe4d633..b160164 100644 ---- a/httpcore/src/main/java/org/apache/http/impl/io/AbstractSessionInputBuffer.java -+++ b/httpcore/src/main/java/org/apache/http/impl/io/AbstractSessionInputBuffer.java -@@ -340 +340 @@ private int lineFromReadBuffer(final CharArrayBuffer charbuffer, int pos) -- if (pos > 0 && this.buffer[pos - 1] == HTTP.CR) { -+ if (pos > off && this.buffer[pos - 1] == HTTP.CR) { diff --git a/All/Genesis-OOB/Genesis#176/new/AbstractSessionInputBuffer.java b/All/Genesis-OOB/Genesis#176/new/AbstractSessionInputBuffer.java deleted file mode 100755 index b160164..0000000 --- a/All/Genesis-OOB/Genesis#176/new/AbstractSessionInputBuffer.java +++ /dev/null @@ -1,409 +0,0 @@ -/* - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.BufferInfo; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.io.HttpTransportMetrics; -import org.apache.http.params.CoreConnectionPNames; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.ByteArrayBuffer; -import org.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for session input buffers that stream data from - * an arbitrary {@link InputStream}. This class buffers input data in - * an internal byte array for optimal input performance. - *

- * {@link #readLine(CharArrayBuffer)} and {@link #readLine()} methods of this - * class treat a lone LF as valid line delimiters in addition to CR-LF required - * by the HTTP specification. - * - *

- * The following parameters can be used to customize the behavior of this - * class: - *

    - *
  • {@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}
  • - *
  • {@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}
  • - *
  • {@link org.apache.http.params.CoreConnectionPNames#MIN_CHUNK_LIMIT}
  • - *
- * @since 4.0 - */ -@NotThreadSafe -public abstract class AbstractSessionInputBuffer implements SessionInputBuffer, BufferInfo { - - private static final Charset ASCII = Charset.forName("US-ASCII"); - - private InputStream instream; - private byte[] buffer; - private int bufferpos; - private int bufferlen; - - private ByteArrayBuffer linebuffer = null; - - private Charset charset; - private CharsetDecoder decoder; - private CharBuffer cbuf; - private boolean ascii = true; - private int maxLineLen = -1; - private int minChunkLimit = 512; - - private HttpTransportMetricsImpl metrics; - - private CodingErrorAction onMalformedInputAction; - private CodingErrorAction onUnMappableInputAction; - - /** - * Initializes this session input buffer. - * - * @param instream the source input stream. - * @param buffersize the size of the internal buffer. - * @param params HTTP parameters. - */ - protected void init(final InputStream instream, int buffersize, final HttpParams params) { - if (instream == null) { - throw new IllegalArgumentException("Input stream may not be null"); - } - if (buffersize <= 0) { - throw new IllegalArgumentException("Buffer size may not be negative or zero"); - } - if (params == null) { - throw new IllegalArgumentException("HTTP parameters may not be null"); - } - this.instream = instream; - this.buffer = new byte[buffersize]; - this.bufferpos = 0; - this.bufferlen = 0; - this.linebuffer = new ByteArrayBuffer(buffersize); - this.charset = Charset.forName(HttpProtocolParams.getHttpElementCharset(params)); - this.ascii = this.charset.equals(ASCII); - this.decoder = null; - this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1); - this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512); - this.metrics = createTransportMetrics(); - this.onMalformedInputAction = HttpProtocolParams.getMalformedInputAction(params); - this.onUnMappableInputAction = HttpProtocolParams.getUnmappableInputAction(params); - } - - /** - * @since 4.1 - */ - protected HttpTransportMetricsImpl createTransportMetrics() { - return new HttpTransportMetricsImpl(); - } - - /** - * @since 4.1 - */ - public int capacity() { - return this.buffer.length; - } - - /** - * @since 4.1 - */ - public int length() { - return this.bufferlen - this.bufferpos; - } - - /** - * @since 4.1 - */ - public int available() { - return capacity() - length(); - } - - protected int fillBuffer() throws IOException { - // compact the buffer if necessary - if (this.bufferpos > 0) { - int len = this.bufferlen - this.bufferpos; - if (len > 0) { - System.arraycopy(this.buffer, this.bufferpos, this.buffer, 0, len); - } - this.bufferpos = 0; - this.bufferlen = len; - } - int l; - int off = this.bufferlen; - int len = this.buffer.length - off; - l = this.instream.read(this.buffer, off, len); - if (l == -1) { - return -1; - } else { - this.bufferlen = off + l; - this.metrics.incrementBytesTransferred(l); - return l; - } - } - - protected boolean hasBufferedData() { - return this.bufferpos < this.bufferlen; - } - - public int read() throws IOException { - int noRead = 0; - while (!hasBufferedData()) { - noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - return this.buffer[this.bufferpos++] & 0xff; - } - - public int read(final byte[] b, int off, int len) throws IOException { - if (b == null) { - return 0; - } - if (hasBufferedData()) { - int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - // If the remaining capacity is big enough, read directly from the - // underlying input stream bypassing the buffer. - if (len > this.minChunkLimit) { - int read = this.instream.read(b, off, len); - if (read > 0) { - this.metrics.incrementBytesTransferred(read); - } - return read; - } else { - // otherwise read to the buffer first - while (!hasBufferedData()) { - int noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - } - - public int read(final byte[] b) throws IOException { - if (b == null) { - return 0; - } - return read(b, 0, b.length); - } - - private int locateLF() { - for (int i = this.bufferpos; i < this.bufferlen; i++) { - if (this.buffer[i] == HTTP.LF) { - return i; - } - } - return -1; - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer into the given line buffer. The number of chars actually - * read is returned as an integer. The line delimiter itself is discarded. - * If no char is available because the end of the stream has been reached, - * the value -1 is returned. This method blocks until input - * data is available, end of file is detected, or an exception is thrown. - *

- * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @param charbuffer the line buffer. - * @return one line of characters - * @exception IOException if an I/O error occurs. - */ - public int readLine(final CharArrayBuffer charbuffer) throws IOException { - if (charbuffer == null) { - throw new IllegalArgumentException("Char array buffer may not be null"); - } - int noRead = 0; - boolean retry = true; - while (retry) { - // attempt to find end of line (LF) - int i = locateLF(); - if (i != -1) { - // end of line found. - if (this.linebuffer.isEmpty()) { - // the entire line is preset in the read buffer - return lineFromReadBuffer(charbuffer, i); - } - retry = false; - int len = i + 1 - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = i + 1; - } else { - // end of line not found - if (hasBufferedData()) { - int len = this.bufferlen - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = this.bufferlen; - } - noRead = fillBuffer(); - if (noRead == -1) { - retry = false; - } - } - if (this.maxLineLen > 0 && this.linebuffer.length() >= this.maxLineLen) { - throw new IOException("Maximum line length limit exceeded"); - } - } - if (noRead == -1 && this.linebuffer.isEmpty()) { - // indicate the end of stream - return -1; - } - return lineFromLineBuffer(charbuffer); - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer. The line delimiter itself is discarded. If no char is - * available because the end of the stream has been reached, - * null is returned. This method blocks until input data is - * available, end of file is detected, or an exception is thrown. - *

- * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @return HTTP line as a string - * @exception IOException if an I/O error occurs. - */ - private int lineFromLineBuffer(final CharArrayBuffer charbuffer) - throws IOException { - // discard LF if found - int len = this.linebuffer.length(); - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.LF) { - len--; - } - // discard CR if found - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.CR) { - len--; - } - } - } - if (this.ascii) { - charbuffer.append(this.linebuffer, 0, len); - } else { - ByteBuffer bbuf = ByteBuffer.wrap(this.linebuffer.buffer(), 0, len); - len = appendDecoded(charbuffer, bbuf); - } - this.linebuffer.clear(); - return len; - } - - private int lineFromReadBuffer(final CharArrayBuffer charbuffer, int pos) - throws IOException { - int off = this.bufferpos; - int len; - this.bufferpos = pos + 1; - if (pos > off && this.buffer[pos - 1] == HTTP.CR) { - // skip CR if found - pos--; - } - len = pos - off; - if (this.ascii) { - charbuffer.append(this.buffer, off, len); - } else { - ByteBuffer bbuf = ByteBuffer.wrap(this.buffer, off, len); - len = appendDecoded(charbuffer, bbuf); - } - return len; - } - - private int appendDecoded( - final CharArrayBuffer charbuffer, final ByteBuffer bbuf) throws IOException { - if (!bbuf.hasRemaining()) { - return 0; - } - if (this.decoder == null) { - this.decoder = this.charset.newDecoder(); - this.decoder.onMalformedInput(this.onMalformedInputAction); - this.decoder.onUnmappableCharacter(this.onUnMappableInputAction); - } - if (this.cbuf == null) { - this.cbuf = CharBuffer.allocate(1024); - } - this.decoder.reset(); - int len = 0; - while (bbuf.hasRemaining()) { - CoderResult result = this.decoder.decode(bbuf, this.cbuf, true); - len += handleDecodingResult(result, charbuffer, bbuf); - } - CoderResult result = this.decoder.flush(this.cbuf); - len += handleDecodingResult(result, charbuffer, bbuf); - this.cbuf.clear(); - return len; - } - - private int handleDecodingResult( - final CoderResult result, - final CharArrayBuffer charbuffer, - final ByteBuffer bbuf) throws IOException { - if (result.isError()) { - result.throwException(); - } - this.cbuf.flip(); - int len = this.cbuf.remaining(); - while (this.cbuf.hasRemaining()) { - charbuffer.append(this.cbuf.get()); - } - this.cbuf.compact(); - return len; - } - - public String readLine() throws IOException { - CharArrayBuffer charbuffer = new CharArrayBuffer(64); - int l = readLine(charbuffer); - if (l != -1) { - return charbuffer.toString(); - } else { - return null; - } - } - - public HttpTransportMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/All/Genesis-OOB/Genesis#176/new/RELEASE_NOTES.txt b/All/Genesis-OOB/Genesis#176/new/RELEASE_NOTES.txt deleted file mode 100755 index 5117e4d..0000000 --- a/All/Genesis-OOB/Genesis#176/new/RELEASE_NOTES.txt +++ /dev/null @@ -1,939 +0,0 @@ -Changes since 4.2 -------------------- - -* [HTTPCORE-263] Under rare circumstances incorrectly delineated or garbled HTTP message - can cause an IndexOutOfBoundsException in AbstractSessionInputBuffer#readLine() - Contributed by Michael Pujos - -* Made connection pools use FIFO algorithm instead of LIFO when leasing / releasing persistent - connections. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-298] Fixed non-blocking SSLIOSession state can getting out of sync with the underlying - IOSession in case the I/O session is terminated by the I/O reactor rather than by the protocol - handler. - Contributed by Sandeep Tamhankar - -* Fixed NPE in StringEntity constructor thrown if ContentType#getCharset is null. - Contributed by Oleg Kalnichevski - -Release 4.2 -------------------- - -This is the first stable (GA) release of HttpCore 4.2. The most notable features included in this -release are connection pool components for blocking and non-blocking HTTP connections and new -asynchronous client and server side protocol handlers. - -New protocol handling API used in conjunction with connection pooling components is expected to -make development of asynchronous HTTP client agents and HTTP proxies easier and less error prone. - -Connection pool components are based on mature code migrated from HttpClient and HttpAsyncClient -modules but have a slightly different API that makes a better use of Java standard concurrent -primitives. - -Changelog -------------------- - -* Fixed HttpAsyncRequestExecutor incorrect execution of message exchanges that span across multiple - hosts (for instance, in case of a request redirect). - Contributed by Oleg Kalnichevski - -* AbstractHttpClientConnection#isResponseAvailable method now catches SocketTimeoutException - and returns false. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-296] Server side connections (both blocking and non-blocking) can now handle entity - enclosing requests without Content-Length and Transfer-Encoding headers. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-295] [HTTPCORE-288] Provided direct access to the underlying socket of non-blocking - HTTP connection to allow modification of socket level settings such as TCP_NODELAY, SO_KEEPALIVE, - TrafficClass, etc. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-289] HttpAsyncService fails to invoke Cancellable#cancel() when the ongoing HTTP - exchange is aborted by the client. - Contributed by Oleg Kalnichevski - -Incompatible changes --------------------- -[Compared to release version 4.1.4] - -The following methods have been deprecated for some time now and have been deleted: - -org.apache.http.impl.SocketHttpServerConnection#createHttpDataReceiver(Socket, int, HttpParams) -org.apache.http.impl.SocketHttpServerConnection#createHttpDataTransmitter(Socket, int, HttpParams) -org.apache.http.protocol.HttpRequestHandlerRegistry#matchUriRequestPattern(String, String) - -The following classes have been deprecated for some while now and have been deleted: - -org.apache.http.nio.entity.ByteArrayNIOEntity -org.apache.http.nio.entity.FileNIOEntity -org.apache.http.nio.entity.HttpNIOEntity -org.apache.http.nio.entity.StringNIOEntity -org.apache.http.nio.protocol.NHttpClientHandlerBase -org.apache.http.nio.protocol.NHttpServiceHandlerBase - -Release 4.2-BETA1 -------------------- - -This is the first BETA release of HttpCore 4.2. This release comes with completely redesigned -and rewritten asynchronous protocol handlers. New protocol handling API used in conjunction with -connection pooling components is expected to make development of asynchronous HTTP client agents -and HTTP proxies easier and less error prone. - -Sample application shipped with the release include an example of an HTTP file server capable of -direct channel (zero copy) data transfer and an example of a non-blocking, fully streaming reverse -proxy. - -This release also incorporates bug fixes from the stable 4.1.x branch and includes an updated -HttpCore tutorial. - - - -Release 4.1.4 -------------------- - -This is a maintenance release that fixes a number of bugs found since 4.1.3. It is also likely -to be the last release in the 4.1.x branch. - -Changelog -------------------- - -* [HTTPCORE-286] Canceled I/O session can cause an IllegalStateException in BaseIOReactor#validate - leading to an abnormal termination of the I/O reactor. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-257] Fixed incorrect results produced by DefaultConnectionReuseStrategy when handling - response messages whose content entity has been decoded or modified by a protocol interceptor. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-283] Workaround for a bug causing termination of the I/O reactor in case of exception - thrown by NHttpServiceHandler#requestReceived or NHttpClientHandler#responseReceived - methods. A more comprehensive fix for the bug applied to the 4.2 branch. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-281] ResponseConnControl protocol interceptor does not correctly populate connection - persistence control headers when sending a HTTP/1.1 response message in response to a HTTP/1.0 - request message. - Contributed by William R. Speirs - -* [HTTPCORE-282] The default value of the internal event mask of newly created non-blocking I/O - is not correctly initialized, which causes the READ interest bit to get cleared in the interest - op queuing mode unless the event mask is explicitly reset. - Contributed by Sadeep Jayasumana and Oleg Kalnichevski - -* [HTTPCORE-268] Handle runtime exceptions thrown by SSLEngine. - Contributed by Oleg Kalnichevski - - - -Release 4.2-ALPHA2 -------------------- - -This is the second ALPHA release of HttpCore 4.2. This release comes with completely redesigned -and rewritten asynchronous protocol handlers. New protocol handling API used in conjunction with -connection pooling components introduced in the previous ALPHA release is expected to make -development of asynchronous HTTP client agents and HTTP proxies easier and less error prone. - -Sample application shipped with the release include an example of an HTTP file server capable of -direct channel (zero copy) data transfer and an example of a non-blocking, fully streaming reverse -proxy. - -We are kindly asking existing and prospective users of HttpCore to review and try out the -new protocol handlers and give us feedback while the 4.2 API is still not final. If no major flaws -are discovered the 4.2 API is expected to be frozen with the next BETA release. - -Please note that new features included in this release are still considered experimental and -their API may change in the future ALPHA releases. This release also marks the end of support for -Java 1.3. As of this release HttpCore requires Java 1.5 for all its components. Several classes and -methods deprecated between versions 4.0-beta1 and 4.0 GA (more than two years ago) have been -removed in this release. - -Changelog -------------------- - -* [HTTPCORE-270] Fixed IllegalStateException in AbstractSessionOutputBuffer and - AbstractSessionInputBuffer. - Contributed by William R. Speirs - -* [HTTPCORE-269] Connection pools incorrectly handle lease requests when the max limit for the given - route has been exceeded and all connections in the route pool are stateful. - Contributed by Oleg Kalnichevski - - -Release 4.2-ALPHA1 -------------------- - -This is the first ALPHA release of 4.2. The most notable feature included in this release is -support for connection pools of blocking and non-blocking HTTP connections. Connection pool -components are based on mature code migrated from HttpClient and HttpAsyncClient modules but have -a slightly different API that makes a better use of Java standard concurrent primitives. - -Support for connection pools in HttpCore is expected to make development of client and proxy HTTP -services easier and less error prone. - -Please note that new features included in this release are still considered experimental and -their API may change in the future ALPHA releases. This release also marks the end of support for -Java 1.3. As of this release HttpCore requires Java 1.5 for all its components. Several classes and -methods deprecated between versions 4.0-beta1 and 4.0 GA (more than two years ago) have been -removed in this release. - -Changelog -------------------- - -* [HTTPCORE-268] Handle runtime exceptions thrown by SSLEngine. - Contributed by Oleg Kalnichevski - -Release 4.1.3 -------------------- - -This is an emergency release that fixes a severe regression in the non-blocking SSL I/O code -introduced in release 4.1.2. - -* [HTTPCORE-266] SSLIOSession does not correctly terminate if the opposite end shuts down connection - without sending a 'close notify' message causing an infinite loop in the I/O dispatch thread. - Contributed by Oleg Kalnichevski - -Release 4.1.2 -------------------- - -This is a patch release that fixes a number of bugs found in the previous version. - -Please note that several classes and methods deprecated between versions 4.0-beta1 and 4.0 GA -(more than two years ago) will also be removed in the 4.2 branch. - -Users of 4.0.x versions are advised to upgrade and replace deprecated API calls following -recommendations in javadocs. - -* [HTTPCORE-261] IOSession#setSocketTimeout() method does not reset the timeout count. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-260] Non-blocking SSL I/O session can terminate prematurely causing message body - truncation when message content is chunk coded and the connection is closed on the opposite end. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-257] Fixed incorrect results produced by DefaultConnectionReuseStrategy when handling - response messages whose content entity has been decoded or modified by a protocol interceptor. - Contributed by Oleg Kalnichevski - -Release 4.1.1 -------------------- - -This is a patch release that fixes a number of non-critical issues found since release 4.1. - -This release marks the end of support for Java 1.3. As of release 4.2 HttpCore will require -Java 1.5 for all its components. - -Please note that several classes and methods deprecated between versions 4.0-beta1 and 4.0 GA -(more than two years ago) will also be removed in the 4.2 branch. - -Users of 4.0.x versions are advised to upgrade and replace deprecated API calls following -recommendations in javadocs. - -* In case of an unexpected end of stream condition (the peer closed connection prematurely) - truncated Content-Length delimited message bodies will cause an I/O exception. Application - can still choose to catch and ignore ConnectionClosedException in order to accept partial - message content. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-255]: Fixed resource management in InputStreamEntity#writeTo() - Contributed by Oleg Kalnichevski - -* [HTTPCORE-254]: Erratic results from metrics (sebb) - -* [HTTPCORE-242]: Fixed NPE in AsyncNHttpClientHandler caused by an early response to an - entity enclosing request. - Contributed by Oleg Kalnichevski - - -Release 4.1 -------------------- - -This is the first stable (GA) release of HttpCore 4.1. This release provides a compatibility mode -with JREs that have a naive (broken) implementation of SelectionKey API and also improves -compatibility with the Google Android platform. There has also been a number of performance -related improvements and bug fixes in both blocking and non-blocking components. - -Changelog -------------------- - -* [HTTPCORE-240]: DefaultConnectingIOReactor leaks a socket descriptor if the session request fails. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-239]: The ChunkEncoder could request for a negative buffer limit causing an - IllegalArgumentException. - Contributed by Asankha Perera - -* [HTTPCORE-236]: SSLIOSession#isAppInputReady() does not check the status of the session input - buffer. - Contributed by Dmitry Lukyanov - -* [HTTPCORE-233]: EntityUtils#toString() and EntityUtils#toByteArray() to return null if - HttpEntity#getContent() is null - Contributed by Oleg Kalnichevski - -* [HTTPCORE-231] Fixed incorrect handling of HTTP entities by non-blocking LengthDelimitedDecoder - when the Content-Length value is larger than Integer.MAX_VALUE. - Contributed by Oleg Kalnichevski - -Release 4.1-BETA2 -------------------- - -This is the second BETA release of HttpCore 4.1. This is mainly a bug fix release that addresses -a number of non-critical bugs. - -The most significant change in this release is deprecation of the HttpEntity#consumeContent() -method and streamlining of connection management and resource deallocation by HTTP entities. -Please refer to the javadocs for details. - -* [HTTPCORE-229] AbstractSessionInputBuffer#readLine(CharArrayBuffer) returns incorrect - number of characters read by the method when using non-standard HTTP element charset. - Contributed by Oleg Kalnichevski - -* Non-blocking connections can trigger #responseReady / #requestReady events by mistake - when the underlying session is already closed. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-228] Fixed NPE in AsyncNHttpServiceHandler caused by entity enclosing requests - if no matching request handler can be found. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-227] Fixed incorrect request / response count by non-blocking connections. - Contributed by Harold Lee - -* [HTTPCORE-226] Improved compatibility of NIO components with Google Android. - Contributed by Oleg Kalnichevski - -* ByteArrayBuffer, CharArrayBuffer, BasicHeader, BufferedHeader, HeaderGroup, BasicRequestLine, - BasicStatusLine made Serializable. - Contributed by Oleg Kalnichevski - -Release 4.1-BETA1 -------------------- - -This is the first BETA release of HttpCore 4.1. This release finalizes the API introduced in the -4.1 development branch. It also fixes a number of bugs discovered since the previous release and -delivers a number of performance optimizations in the blocking HTTP transport components. -The blocking HTTP transport is expected to be 5% to 10% faster compared to previous releases. - -* [HTTPCORE-222] Fixed Import-Package in the OSGi META-INF - Contributed by Willem Jiang - -* [HTTPCORE-177] Reduce intermediate data buffering by reading large chunks of data directly from - the underlying socket stream. This results in improved performance of blocking read operations. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-220] IdentityDecoder fails to detect end of stream when using file channels. - Contributed by Asankha C. Perera - -* [HTTPCORE-218] ChunkEncoder#write method no longer returns incorrect value if - the data to write is greater than the size of the internal buffer used by the encoder. - Contributed by Richie Jefts - -* [HTTPCORE-209] Added parameter to set SO_REUSEADDR on sockets bound to a local address. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-207] SocketHttp*Connection classes can leak sockets if the connection is half-closed - Contributed by David Koski - -Release 4.1-ALPHA1 -------------------- - -This is the first public release from the 4.1 branch of HttpCore. This release adds a number of -new features, most notable being introduction of compatibility mode with IBM JREs and other JREs -with naive (broken) implementation of SelectionKey API. - -Please note new classes and methods added in the 4.1 branch are still considered API unstable. - -* Ensure that an attempt is made to close out all active sessions gracefully in case of an abnormal - shutdown of the I/O reactor. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-201] OSGi Export-Package to specify release version - Contributed by Oleg Kalnichevski - -* [HTTPCORE-183] Added Thread-safe implementations of HttpParams and HttpProcessor - - SyncBasicHttpParams and ImmutableHttpProcessor classes - Contributed by Oleg Kalnichevski - -* [HTTPCORE-199] ContentInputStream implements InputStream#available(). - Contributed by Oleg Kalnichevski - -* [HTTPCORE-195] Truncated chunk-coded streams can now be tolerated by catching and discarding - TruncatedChunkException. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-155] Compatibility mode with IBM JRE and other JREs with naive (broken) implementation - of SelectionKey. - Contributed by Marc Beyerle and Oleg Kalnichevski - -* [HTTPCORE-191] Blocking HTTP connections are now capable of correctly preserving their internal - state on SocketTimeoutExceptions, which makes it possible to continue reading from the connection - after a socket timeout. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-190] ChunkedInputStream is now capable of correctly preserving its internal state on - SocketTimeoutExceptions, which makes it possible to continue reading from the stream after a - socket timeout. - Contributed by Oleg Kalnichevski - -Release 4.0.1 -------------------- - -This is a patch release addressing a number of issues discovered since the 4.0 release. Users -of NIO module are advised to upgrade. - -* [HTTPCORE-198] CONNECT request includes Host header for HTTP 1.1 connections. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-196] SSLIOSession now unwraps encrypted data more aggressively eliminating long - pauses when receiving data over non-blocking connections. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-197] Fixed bug causing the non-blocking ChunkDecoder to report some data stream as - truncated under special conditions. - Contributed by Denis Rogov and Oleg Kalnichevski - -* SSLIOSession#isAppOutputReady and SSLIOSession#isAppInputReady no longer ignore the application - event mask causing I/O event notifications for unrequested type of events. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-193] Fixed problem with SSLIOSession incorrectly handling of end-of-stream condition. - Contributed by Asankha C. Perera and Oleg Kalnichevski - - -Release 4.0 -------------------- - -This is the first stable (GA) release of HttpCore 4.0. This release mainly improves the -documentation and fixes a few minor bugs reported since the previous release. HttpCore -now comes with a complete tutorial presenting an in-depth coverage of the API. - -HttpCore is a set of low level HTTP transport components that can be used to build custom -client and server side HTTP services with a minimal footprint. HttpCore supports two I/O -models: blocking I/O model based on the classic Java I/O and non-blocking, event driven I/O -model based on Java NIO. The blocking I/O model may be more appropriate for data intensive, -low latency scenarios, whereas the non-blocking model may be more appropriate for high latency -scenarios where raw data throughput is less important than the ability to handle thousands of -simultaneous HTTP connections in a resource efficient manner. - -* [HTTPCORE-180] Fixed NPE in standard I/O event dispatchers when - IOEventDispatch#disconnected fires before the session was fully initialized - (IOEventDispatch#connected was not called). - Contributed by Oleg Kalnichevski - -* [HTTPCORE-175] Chunk decoders no longer accept truncated chunks as valid input. - Contributed by Oleg Kalnichevski - - -Release 4.0 Beta 3 -------------------- - -The third BETA version of HttpComponents Core has been released. This is a -maintenance release, which addresses a number of issues discovered since the -previous release. - -The only significant new feature is an addition of an OSGi compliant bundle -combining HttpCore and HttpCore NIO jars. - -* [HTTPCORE-173] Tolerate missing closing chunk if the chunk coded content - is terminated by the end of stream (EOF) condition. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-174] Position is incremented twice in ContentLengthInputStream#skip(long) - Contributed by Ildar Safarov - -* [HTTPCORE-125] OSGi bundle containing HttpCore & HttpCore NIO jars. - Contributed by Oleg Kalnichevski - -* CancelledKeyException thrown in BaseIOReactor#validate() no longer causes - a premature I/O reactor shutdown. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-172] Added #close() method to SharedInputBuffer and - SharedOutputBuffer. The purpose of the new method is to close the buffer - in case of normal / orderly termination of the underlying HTTP connection. - Use #shutdown() method to force-close the buffer in case of abnormal / - exceptional termination of the underlying connection. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-170] Fixed race condition in SharedOutputBuffer. - Contributed by Jason Walton - -* [HTTPCORE-169] Fixed bug causing connecting I/O reactors to shut down due to - ClosedChannelException if a pending session request is cancelled before the new - channel has been registered with the selector. - Contributed by Anders Wallgren - -* [HTTPCORE-167] Fixed handling the end of stream (EOF) condition in the #isStale() - check of blocking HTTP connections. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-166] NIO reactors now maintain an audit log of fatal exceptions, - which can be used to examine the cause and problems experienced during - the shutdown process. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-165] Improved handling of CancelledKeyException in I/O reactors - Contributed by Oleg Kalnichevski - - -Release 4.0 Beta 2 -------------------- - -The second BETA version of HttpComponents Core has been released. This release -adds a number of improvements to the NIO components, most notable being improved -asynchronous client side and server side protocol handlers. - -There has been a number of important bug fixes in HttpCore NIO module, whereas -HttpCore base module has had very few changes. - -All upstream projects dependent on HttpCore NIO are strongly advised to upgrade. - -* [HTTPCORE-163] Fixed AbstractMultiworkerIOReactor#execute() to correctly - propagate the original I/O exception in case of an abnormal termination. - Contributed by Patrick Moore - -* Changed behavior of IdentityDecoder & LengthDelimitedDecoder to throw - an IOException if data is attempted to be written beyond the length - of a FileChannel. Previously would write nothing. - Contributed by Sam Berlin - -* Fixed bug in LengthDelimitedDecoder & IdentityDecoder that caused transfers - to a FileChannel to overwrite arbitrary parts of the file, if data was - buffered in SessionInputBuffer. - Contributed by Sam Berlin - -* Fixed concurrency bug in the ThrottlingHttpServerHandler protocol handler. - Contributed by Oleg Kalnichevski - -* Fixed bug in SharedInputBuffer that caused input events to be - incorrectly suspended. - Contributed by Asankha C. Perera - -* [HTTPCORE-150] Entity implementation that serializes a Java object - Contributed by Andrea Selva - -* [HTTPCORE-157] ChunkedOutputStream#flush() now behaves consistently with the - specification of OutputStream#flush(). - Contributed by Oleg Kalnichevski - -* [HTTPCORE-147] Fixed handling of requests with partially consumed content - in ThrottlingHttpServiceHandler. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-92] ChunkEncoder splits input data larger than available space - in the session output buffer into smaller chunks instead of expanding - the buffer. - Contributed by Andrea Selva and - Oleg Kalnichevski - -* [HTTPCORE-149] I/O reactors now count period of inactivity since the - time of the last read or write operation. Previously only read - operations resulted in timeout counter reset. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-148] Improved asynchronous server and client HTTP protocol - handler implementations. - Contributed by Sam Berlin - -* [HTTPCORE-143] Ensure the underlying channel is closed if the session - request is canceled or times out. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-140] Fixed timeout handling in ThrottlingHttpServiceHandler. - Contributed by Lorenzo Moretti and - Oleg Kalnichevski - - - -Release 4.0 Beta 1 -------------------- - -The first BETA version of HttpComponents Core has been released. This release -can be considered a major milestone, as it marks the end of API instability -in HttpCore. As of this release the API compatibility between minor releases -in 4.x codeline will be maintained. - -This release includes several major improvements such as enhanced HTTP message -parsing API and optimized parser implementations, Java 5.0 compatibility -for HttpCore NIO extensions. Upstream projects are strongly encouraged to -upgrade to the latest release. - -The focus of the development efforts will be gradually shifting towards -providing better test coverage, documentation and performance optimizations. - -Changelog: ----------- - -* [HTTPCORE-141] Session request timeout in DefaultConnectingIOReactor - invalidates the request. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-137] DefaultHttpRequestFactory extended to support all methods - specified in RFC 2616 (except CONNECT). - Contributed by Oleg Kalnichevski - -* Replaced HTTP parameter linking with a simple child/parent stack. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-134] all serialVersionUID attributes are private - Contributed by Roland Weber - -* [HTTPCORE-133] Clone support for basic HTTP message elements and - non-streaming entities. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-127] Improved API for lifecycle management of listening I/O - reactors. One can now suspend and resume listener endpoints. - Contributed by Asankha C. Perera - -* [HTTPCORE-112] DefaultConnectionReuseStrategy interprets token sequences - Contributed by Roland Weber - -* [HTTPCORE-122] new interface TokenIterator and basic implementation - Contributed by Roland Weber - -* HttpCore NIOSSL classes moved to HttpCore NIO. - Contributed by Oleg Kalnichevski - -* HttpCore NIO ported to Java 1.5. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-130] Fixed over-synchronization bug leading to a thread deadlock - condition in SSL IOEventDispatch implementations. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-37] HttpParams beans - Contributed by Stojce Dimski - -* [HTTPCORE-128] Simplified injection of custom NIO connection implementations. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-126] Improved HTTP message parsing API and optimized parser - implementations. - Contributed by Oleg Kalnichevski - -* Do not include "Connection: close" to 500 responses per default. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-121] new interface HeaderElementIterator - Contributed by Andrea Selva - -* [HTTPCORE-123] Fixed problem with SSLSession losing buffered data, if the - connection has been closed by the peer. - Contributed by Risto Reinpõld - - - -Release 4.0 Alpha 6 -------------------- - -The sixth ALPHA version of HttpComponents Core has been released. This release -sports an improved message parsing and formatting API in the base module and -lots of incremental improvements and bug fixes in the NIO and NIOSSL modules. -Based on the improved API, it is now possible to send and receive SIP messages -with HttpComponents Core. - -HttpCore is now feature complete and we are planning to freeze the public APIs -as of next release (BETA1). - -* [HTTPCORE-120] new interface HeaderIterator, available from HttpMessage - Contributed by Roland Weber - -* [HTTPCORE-118] Purge closed sessions prior to opening new ones. This should - reduce chances of running out of memory when opening and closing lots of - NIO connections in a tight loop. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-117] Fixed bug preventing protocol handlers from closing timed out - NIO connection when pending output (output session buffer is not empty). - Contributed by Oleg Kalnichevski - -* [HTTPCORE-86] Allow for optional handling of runtime exceptions - thrown by protocol handlers to ensure the I/O dispatch thread - remains running. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-116] moved parameter names to interfaces - Contributed by Roland Weber - -* [HTTPCORE-109] Improved shutdown process of the I/O reactors in NIO modules. - I/O reactors now attempt to terminate connections gracefully before shutting - down the underlying socket channels. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-107] allow sending and receiving of SIP messages - Contributed by Roland Weber - -* [HTTPCORE-114]: Fixed incorrect handling of the end-of-stream condition - in SSLIOSession. - Oleg Kalnichevski - -* [HTTPCORE-110] refactored message parsing and formatting logic - Contributed by Roland Weber - -* [HTTPCORE-113] Removed unnecessary target hostname resolution from - non-blocking client protocol handlers. - Oleg Kalnichevski - -* [HTTPCORE-108] Close all channels registered with the I/O reactor during - shutdown. Fixed the problem with DefaultListeningIOReactor not releasing - socket ports until JVM is restarted. - Oleg Kalnichevski - -* [HTTPCORE-106] Pluggable HTTP message parsers and message writers - Oleg Kalnichevski - -* [HTTPCORE-105] Consistent class names in base and NIO modules - Oleg Kalnichevski - -* [HTTPCORE-100] revised HttpContext hierarchy - Contributed by Roland Weber - -* [HTTPCORE-103] NIO connections now attempt to consume all available session - data while parsing HTTP messages. This can potentially improve performance - of non-blocking SSL connections. - Contributed by Steffen Pingel - -* [HTTPCORE-102] Exceeding of maximum line length limit detected late - Contributed by Steffen Pingel - -* [HTTPCORE-21] Transport and connection metrics - Contributed by Andrea Selva and - Oleg Kalnichevski - -* [HTTPCORE-91] new interceptor RequestDate, renamed constants in protocol.HTTP - Contributed by Roland Weber - -* [HTTPCORE-90] Version detection based on build-time properties - Contributed by Oleg Kalnichevski and - Roland Weber - -* [HTTPCORE-88] Added convenience methods to HttpRequestInterceptorList, - HttpResponseInterceptorList interfaces - Contributed by Andrea Selva - -* [HTTPCORE-89]: Fixed bug in DefaultConnectingIOReactor causing incorrect - handling of local (immediate) connections on some platforms (affects Sun - Solaris 2.9 / Sparc and likely other Solaris 2.x platforms) - Contributed by Sam Berlin - -Release 4.0 Alpha 5 -------------------- - -The fifth ALPHA version of HttpComponents Core has been released. This release -delivers a number of incremental improvements across the board in all modules -and adds several performance oriented features such as ability to transfer -data directly between a file and a socket channels. - -HttpCore is almost fully feature complete now and we are likely to freeze -the public APIs as of next release (BETA1). - -* [HTTPCORE-87] RuntimeExcpetions thrown in I/O worker threads are now correctly - propagated to the I/O reactor. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-84]: Removed DateUtils/DateParseException from core. - Contributed by Roland Weber - -* [HTTPCORE-63]: Made I/O select interval configurable for all default I/O - reactor implementations. - Contributed by Oleg Kalnichevski and - Anders Wallgren - -* [HTTPCORE-82]: Revised linking of HttpParams to reduce potential for misuse. - Method #setDefaults() removed from the HttpParams interface. - Contributed by Roland Weber - -* [HTTPCORE-81]: Maximum line length and maximum header counts parameters are now - correctly enforced in both base and NIO modules. Fixed maximum line length check - when parsing folded header lines. - Contributed by Steffen Pingel - -* Added HTTP client handler implementation that allocates fixed size content - buffers upon initialization and is capable of throttling the rate of I/O events - in order to make sure those content buffers do not get overflown. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-76]: Added IOSession#shutdown() method intended to force-close - I/O sessions (primarily needed to terminate hung SSL connections). - Contributed by Sandeep Tamhankar - -* [HTTPCORE-78]: Added ByteBufferAllocator interface that can be used to apply - different ByteArray allocation strategies to session and content buffers. - Use heap bound implementation for short-lived or variable in length (requiring - frequent content re-allocation) buffers. - Contributed by Steffen Pingel - -* [HTTPCORE-77]: The result of CharsetDecoder#decode() and CharsetEncoder#encode() - was not checked for errors resulting in an infinite loop in - SessionInputBuffer#readLine() and SessionOutputBuffer#writeLine() - when malformed characters were processed. - Contributed by Steffen Pingel - -* [HTTPCORE-71]: HttpParams can be copied. - Contributed by Roland Weber - -* [HTTPCORE-75]: DefaultNHttpServerConnection and DefaultNHttpClientConnection - now correctly terminate the underlying I/O session when closed. - BufferingHttpServiceHandler now correctly applies connection keep-alive - strategy when sending a response with no content body. - Contributed by Steffen Pingel - -* [HTTPCORE-73]: Fixed bug preventing NHttpServiceHandler#responseReady and - NHttpClientHandler#requestReady events from being fired if the HTTP message - has no content body. - Contributed by Steffen Pingel - -* [HTTPCORE-67]: Improved event listener interface - Contributed by Oleg Kalnichevski - -* [HTTPCORE-43]: Support for FileChannel#transferFrom() and - FileChannel#transferTo() methods. Direct coping from and to FileChannel is - expected to improve performance of file bound operations - Contributed by Andrea Selva - -* [HTTPCORE-66]: Fixed handling of HTTP HEAD methods - Contributed by Steffen Pingel and - Oleg Kalnichevski - -* [HTTPCORE-58]: NIO HTTP connections changed to throw checked - ConnectionClosedException instead of unchecked IllegalStateException when - an attempt is made to perform an I/O operation on a closed conection - Contributed by Oleg Kalnichevski - -* [HTTPCORE-56]: DefaultConnectingIOReactor no longer terminates due to a - CancelledKeyException, if a session request gets canceled before selection - key is fully initialized. - Contributed by Oleg Kalnichevski - -Release 4.0 Alpha 4 -------------------- - -The forth ALPHA version of HttpComponents Core has been released. -The ALPHA4 release fixes a number of bugs and adds a number of -improvements to HttpCore base and HttpCore NIO extensions. -HttpCore NIO can be used to build HTTP services intended to handle -thousands of simultaneous connections with a small number of I/O -threads. This release also introduces NIOSSL extensions that can be -used to extend HttpCore non-blocking transport components with -ability to transparently encrypt data in transit using SSL/TLS protocol. - -* [HTTPCORE-49]: DefaultConnectingIOReactor can now correctly handle - unresolved socket addresses. It no longer terminates with the - UnresolvedAddressException runtime exception. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-42]: Added server side API for the expectation verification. - Improved support for the 'expect: continue' handshake in HttpCore and - HttpCore NIO. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-26]: Added SSL support for HttpCore NIO. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-40]: API classes no longer reference impl classes in module-main. - Contributed by Roland Weber - -* [HTTPCORE-39]: Refactored HttpStatus, spun off [English]ReasonPhraseFactory. - Contributed by Roland Weber - -* [HTTPCORE-32]: HttpRequestInterceptorList, HttpResponseInterceptorList - Contributed by Roland Weber - -* [HTTPCORE-38]: Packages nio.impl.* are now impl.nio.*, same for examples. - Contributed by Roland Weber - -* [HTTPCORE-27]: I/O reactors can now accept a thread factory as an optional - parameter. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-36]: Fixed #setHandlers() method and matching of request URIs - with a query part in HttpRequestHandlerRegistry - Contributed by Oleg Kalnichevski - -* [HTTPCORE-28]: DefaultConnectingIOReactor now maintains a queue of connect - requests and registers new sessions with the selector on the I/O thread. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-29] DefaultConnectingIOReactor changed to ensure IOExceptions - are correctly propagated to the caller, if an exception is thrown while - initializing a newly connected socket. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-24] Fixed bug in non-blocking connection implementations, which - prevented the session buffer from being correctly flushed when the content - coding process has been completed. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-23] Fixed threading bug in DefaultConnectingIOReactor. - Contributed by Asankha C. Perera - -Release 4.0 Alpha 3 -------------------- - -The third ALPHA version of HttpCore has been released. The ALPHA3 release -includes a number of API optimizations and improvements and introduces a set -of NIO extensions to the HttpCore API. NIO extensions can be used to build -HTTP services intended to handle thousands of simultaneous connections with -a small number of I/O threads. - -* [HTTPCORE-15] Provided a interafce to access IP address of the local and - remote end points. - Contributed by Oleg Kalnichevski - -* [ HTTPCORE-14] Scheme, SocketFactory and SecureSocketFactory moved to - HttpClient. Decoupled HttpHost and Scheme. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-13] Refactored HttpProcessor interface and related impl classes - Contributed by Roland Weber - -* [HTTPCORE-11] Client connection interface no longer defines a specific - method to open a connection. HTTP connections can now represent any - abstract I/O transport such as those based on NIO API. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-10] Non-blocking (async) client side I/O transport based on NIO. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-9] Non-blocking (async) server side I/O transport based on NIO. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-7] ConnectionReuseStrategy interface changed to allow access - to the HTTP execution context. - Contributed by Roland Weber - -* [HTTPCORE-6] Header implementation allowing for performance short-cuts - when serializing and deserializing HTTP headers. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-5] Header, HeaderElement, NameValuePair, RequestLine, StatusLine, - HttpVersion changed to interfaces. API no longer contains any parsing and - formatting code and does not imply any specific physical representation of - HTTP messages and their elements. - Contributed by Oleg Kalnichevski - -Release 4.0 Alpha 2 -------------------- -This is a maintenance release that mostly fixes minor problems found since the -previous release. The upstream projects are strongly encouraged use this -release as a dependency while HttpCore undergoes another round of reviews -and optimization in the SVN trunk - -Changelog: ---------- -* [HTTPCORE-4] optional header and line length limits to contain OOME risks - Contributed by Oleg Kalnichevski - -Release 4.0 Alpha 1 -------------------- -This release represents a complete redesign of the Jakarta Commons HttpClient -3.x API and a significant rewrite of the core HTTP components derived from -HttpClient 3.0 code base. - -These components will form the foundation of the future releases of Jakarta -HttpClient and can also be used separately to build custom client- and -server-side HTTP services. diff --git a/All/Genesis-OOB/Genesis#176/old/AbstractSessionInputBuffer.java b/All/Genesis-OOB/Genesis#176/old/AbstractSessionInputBuffer.java deleted file mode 100755 index fe4d633..0000000 --- a/All/Genesis-OOB/Genesis#176/old/AbstractSessionInputBuffer.java +++ /dev/null @@ -1,409 +0,0 @@ -/* - * ==================================================================== - * 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. - * ==================================================================== - * - * This software consists of voluntary contributions made by many - * individuals on behalf of the Apache Software Foundation. For more - * information on the Apache Software Foundation, please see - * . - * - */ - -package org.apache.http.impl.io; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.ByteBuffer; -import java.nio.CharBuffer; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; -import java.nio.charset.CoderResult; -import java.nio.charset.CodingErrorAction; - -import org.apache.http.annotation.NotThreadSafe; -import org.apache.http.io.BufferInfo; -import org.apache.http.io.SessionInputBuffer; -import org.apache.http.io.HttpTransportMetrics; -import org.apache.http.params.CoreConnectionPNames; -import org.apache.http.params.HttpParams; -import org.apache.http.params.HttpProtocolParams; -import org.apache.http.protocol.HTTP; -import org.apache.http.util.ByteArrayBuffer; -import org.apache.http.util.CharArrayBuffer; - -/** - * Abstract base class for session input buffers that stream data from - * an arbitrary {@link InputStream}. This class buffers input data in - * an internal byte array for optimal input performance. - *

- * {@link #readLine(CharArrayBuffer)} and {@link #readLine()} methods of this - * class treat a lone LF as valid line delimiters in addition to CR-LF required - * by the HTTP specification. - * - *

- * The following parameters can be used to customize the behavior of this - * class: - *

    - *
  • {@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}
  • - *
  • {@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}
  • - *
  • {@link org.apache.http.params.CoreConnectionPNames#MIN_CHUNK_LIMIT}
  • - *
- * @since 4.0 - */ -@NotThreadSafe -public abstract class AbstractSessionInputBuffer implements SessionInputBuffer, BufferInfo { - - private static final Charset ASCII = Charset.forName("US-ASCII"); - - private InputStream instream; - private byte[] buffer; - private int bufferpos; - private int bufferlen; - - private ByteArrayBuffer linebuffer = null; - - private Charset charset; - private CharsetDecoder decoder; - private CharBuffer cbuf; - private boolean ascii = true; - private int maxLineLen = -1; - private int minChunkLimit = 512; - - private HttpTransportMetricsImpl metrics; - - private CodingErrorAction onMalformedInputAction; - private CodingErrorAction onUnMappableInputAction; - - /** - * Initializes this session input buffer. - * - * @param instream the source input stream. - * @param buffersize the size of the internal buffer. - * @param params HTTP parameters. - */ - protected void init(final InputStream instream, int buffersize, final HttpParams params) { - if (instream == null) { - throw new IllegalArgumentException("Input stream may not be null"); - } - if (buffersize <= 0) { - throw new IllegalArgumentException("Buffer size may not be negative or zero"); - } - if (params == null) { - throw new IllegalArgumentException("HTTP parameters may not be null"); - } - this.instream = instream; - this.buffer = new byte[buffersize]; - this.bufferpos = 0; - this.bufferlen = 0; - this.linebuffer = new ByteArrayBuffer(buffersize); - this.charset = Charset.forName(HttpProtocolParams.getHttpElementCharset(params)); - this.ascii = this.charset.equals(ASCII); - this.decoder = null; - this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1); - this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512); - this.metrics = createTransportMetrics(); - this.onMalformedInputAction = HttpProtocolParams.getMalformedInputAction(params); - this.onUnMappableInputAction = HttpProtocolParams.getUnmappableInputAction(params); - } - - /** - * @since 4.1 - */ - protected HttpTransportMetricsImpl createTransportMetrics() { - return new HttpTransportMetricsImpl(); - } - - /** - * @since 4.1 - */ - public int capacity() { - return this.buffer.length; - } - - /** - * @since 4.1 - */ - public int length() { - return this.bufferlen - this.bufferpos; - } - - /** - * @since 4.1 - */ - public int available() { - return capacity() - length(); - } - - protected int fillBuffer() throws IOException { - // compact the buffer if necessary - if (this.bufferpos > 0) { - int len = this.bufferlen - this.bufferpos; - if (len > 0) { - System.arraycopy(this.buffer, this.bufferpos, this.buffer, 0, len); - } - this.bufferpos = 0; - this.bufferlen = len; - } - int l; - int off = this.bufferlen; - int len = this.buffer.length - off; - l = this.instream.read(this.buffer, off, len); - if (l == -1) { - return -1; - } else { - this.bufferlen = off + l; - this.metrics.incrementBytesTransferred(l); - return l; - } - } - - protected boolean hasBufferedData() { - return this.bufferpos < this.bufferlen; - } - - public int read() throws IOException { - int noRead = 0; - while (!hasBufferedData()) { - noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - return this.buffer[this.bufferpos++] & 0xff; - } - - public int read(final byte[] b, int off, int len) throws IOException { - if (b == null) { - return 0; - } - if (hasBufferedData()) { - int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - // If the remaining capacity is big enough, read directly from the - // underlying input stream bypassing the buffer. - if (len > this.minChunkLimit) { - int read = this.instream.read(b, off, len); - if (read > 0) { - this.metrics.incrementBytesTransferred(read); - } - return read; - } else { - // otherwise read to the buffer first - while (!hasBufferedData()) { - int noRead = fillBuffer(); - if (noRead == -1) { - return -1; - } - } - int chunk = Math.min(len, this.bufferlen - this.bufferpos); - System.arraycopy(this.buffer, this.bufferpos, b, off, chunk); - this.bufferpos += chunk; - return chunk; - } - } - - public int read(final byte[] b) throws IOException { - if (b == null) { - return 0; - } - return read(b, 0, b.length); - } - - private int locateLF() { - for (int i = this.bufferpos; i < this.bufferlen; i++) { - if (this.buffer[i] == HTTP.LF) { - return i; - } - } - return -1; - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer into the given line buffer. The number of chars actually - * read is returned as an integer. The line delimiter itself is discarded. - * If no char is available because the end of the stream has been reached, - * the value -1 is returned. This method blocks until input - * data is available, end of file is detected, or an exception is thrown. - *

- * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @param charbuffer the line buffer. - * @return one line of characters - * @exception IOException if an I/O error occurs. - */ - public int readLine(final CharArrayBuffer charbuffer) throws IOException { - if (charbuffer == null) { - throw new IllegalArgumentException("Char array buffer may not be null"); - } - int noRead = 0; - boolean retry = true; - while (retry) { - // attempt to find end of line (LF) - int i = locateLF(); - if (i != -1) { - // end of line found. - if (this.linebuffer.isEmpty()) { - // the entire line is preset in the read buffer - return lineFromReadBuffer(charbuffer, i); - } - retry = false; - int len = i + 1 - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = i + 1; - } else { - // end of line not found - if (hasBufferedData()) { - int len = this.bufferlen - this.bufferpos; - this.linebuffer.append(this.buffer, this.bufferpos, len); - this.bufferpos = this.bufferlen; - } - noRead = fillBuffer(); - if (noRead == -1) { - retry = false; - } - } - if (this.maxLineLen > 0 && this.linebuffer.length() >= this.maxLineLen) { - throw new IOException("Maximum line length limit exceeded"); - } - } - if (noRead == -1 && this.linebuffer.isEmpty()) { - // indicate the end of stream - return -1; - } - return lineFromLineBuffer(charbuffer); - } - - /** - * Reads a complete line of characters up to a line delimiter from this - * session buffer. The line delimiter itself is discarded. If no char is - * available because the end of the stream has been reached, - * null is returned. This method blocks until input data is - * available, end of file is detected, or an exception is thrown. - *

- * This method treats a lone LF as a valid line delimiters in addition - * to CR-LF required by the HTTP specification. - * - * @return HTTP line as a string - * @exception IOException if an I/O error occurs. - */ - private int lineFromLineBuffer(final CharArrayBuffer charbuffer) - throws IOException { - // discard LF if found - int len = this.linebuffer.length(); - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.LF) { - len--; - } - // discard CR if found - if (len > 0) { - if (this.linebuffer.byteAt(len - 1) == HTTP.CR) { - len--; - } - } - } - if (this.ascii) { - charbuffer.append(this.linebuffer, 0, len); - } else { - ByteBuffer bbuf = ByteBuffer.wrap(this.linebuffer.buffer(), 0, len); - len = appendDecoded(charbuffer, bbuf); - } - this.linebuffer.clear(); - return len; - } - - private int lineFromReadBuffer(final CharArrayBuffer charbuffer, int pos) - throws IOException { - int off = this.bufferpos; - int len; - this.bufferpos = pos + 1; - if (pos > 0 && this.buffer[pos - 1] == HTTP.CR) { - // skip CR if found - pos--; - } - len = pos - off; - if (this.ascii) { - charbuffer.append(this.buffer, off, len); - } else { - ByteBuffer bbuf = ByteBuffer.wrap(this.buffer, off, len); - len = appendDecoded(charbuffer, bbuf); - } - return len; - } - - private int appendDecoded( - final CharArrayBuffer charbuffer, final ByteBuffer bbuf) throws IOException { - if (!bbuf.hasRemaining()) { - return 0; - } - if (this.decoder == null) { - this.decoder = this.charset.newDecoder(); - this.decoder.onMalformedInput(this.onMalformedInputAction); - this.decoder.onUnmappableCharacter(this.onUnMappableInputAction); - } - if (this.cbuf == null) { - this.cbuf = CharBuffer.allocate(1024); - } - this.decoder.reset(); - int len = 0; - while (bbuf.hasRemaining()) { - CoderResult result = this.decoder.decode(bbuf, this.cbuf, true); - len += handleDecodingResult(result, charbuffer, bbuf); - } - CoderResult result = this.decoder.flush(this.cbuf); - len += handleDecodingResult(result, charbuffer, bbuf); - this.cbuf.clear(); - return len; - } - - private int handleDecodingResult( - final CoderResult result, - final CharArrayBuffer charbuffer, - final ByteBuffer bbuf) throws IOException { - if (result.isError()) { - result.throwException(); - } - this.cbuf.flip(); - int len = this.cbuf.remaining(); - while (this.cbuf.hasRemaining()) { - charbuffer.append(this.cbuf.get()); - } - this.cbuf.compact(); - return len; - } - - public String readLine() throws IOException { - CharArrayBuffer charbuffer = new CharArrayBuffer(64); - int l = readLine(charbuffer); - if (l != -1) { - return charbuffer.toString(); - } else { - return null; - } - } - - public HttpTransportMetrics getMetrics() { - return this.metrics; - } - -} diff --git a/All/Genesis-OOB/Genesis#176/old/RELEASE_NOTES.txt b/All/Genesis-OOB/Genesis#176/old/RELEASE_NOTES.txt deleted file mode 100755 index ab55438..0000000 --- a/All/Genesis-OOB/Genesis#176/old/RELEASE_NOTES.txt +++ /dev/null @@ -1,935 +0,0 @@ -Changes since 4.2 -------------------- - -* Made connection pools use FIFO algorithm instead of LIFO when leasing / releasing persistent - connections. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-298] Fixed non-blocking SSLIOSession state can getting out of sync with the underlying - IOSession in case the I/O session is terminated by the I/O reactor rather than by the protocol - handler. - Contributed by Sandeep Tamhankar - -* Fixed NPE in StringEntity constructor thrown if ContentType#getCharset is null. - Contributed by Oleg Kalnichevski - -Release 4.2 -------------------- - -This is the first stable (GA) release of HttpCore 4.2. The most notable features included in this -release are connection pool components for blocking and non-blocking HTTP connections and new -asynchronous client and server side protocol handlers. - -New protocol handling API used in conjunction with connection pooling components is expected to -make development of asynchronous HTTP client agents and HTTP proxies easier and less error prone. - -Connection pool components are based on mature code migrated from HttpClient and HttpAsyncClient -modules but have a slightly different API that makes a better use of Java standard concurrent -primitives. - -Changelog -------------------- - -* Fixed HttpAsyncRequestExecutor incorrect execution of message exchanges that span across multiple - hosts (for instance, in case of a request redirect). - Contributed by Oleg Kalnichevski - -* AbstractHttpClientConnection#isResponseAvailable method now catches SocketTimeoutException - and returns false. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-296] Server side connections (both blocking and non-blocking) can now handle entity - enclosing requests without Content-Length and Transfer-Encoding headers. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-295] [HTTPCORE-288] Provided direct access to the underlying socket of non-blocking - HTTP connection to allow modification of socket level settings such as TCP_NODELAY, SO_KEEPALIVE, - TrafficClass, etc. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-289] HttpAsyncService fails to invoke Cancellable#cancel() when the ongoing HTTP - exchange is aborted by the client. - Contributed by Oleg Kalnichevski - -Incompatible changes --------------------- -[Compared to release version 4.1.4] - -The following methods have been deprecated for some time now and have been deleted: - -org.apache.http.impl.SocketHttpServerConnection#createHttpDataReceiver(Socket, int, HttpParams) -org.apache.http.impl.SocketHttpServerConnection#createHttpDataTransmitter(Socket, int, HttpParams) -org.apache.http.protocol.HttpRequestHandlerRegistry#matchUriRequestPattern(String, String) - -The following classes have been deprecated for some while now and have been deleted: - -org.apache.http.nio.entity.ByteArrayNIOEntity -org.apache.http.nio.entity.FileNIOEntity -org.apache.http.nio.entity.HttpNIOEntity -org.apache.http.nio.entity.StringNIOEntity -org.apache.http.nio.protocol.NHttpClientHandlerBase -org.apache.http.nio.protocol.NHttpServiceHandlerBase - -Release 4.2-BETA1 -------------------- - -This is the first BETA release of HttpCore 4.2. This release comes with completely redesigned -and rewritten asynchronous protocol handlers. New protocol handling API used in conjunction with -connection pooling components is expected to make development of asynchronous HTTP client agents -and HTTP proxies easier and less error prone. - -Sample application shipped with the release include an example of an HTTP file server capable of -direct channel (zero copy) data transfer and an example of a non-blocking, fully streaming reverse -proxy. - -This release also incorporates bug fixes from the stable 4.1.x branch and includes an updated -HttpCore tutorial. - - - -Release 4.1.4 -------------------- - -This is a maintenance release that fixes a number of bugs found since 4.1.3. It is also likely -to be the last release in the 4.1.x branch. - -Changelog -------------------- - -* [HTTPCORE-286] Canceled I/O session can cause an IllegalStateException in BaseIOReactor#validate - leading to an abnormal termination of the I/O reactor. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-257] Fixed incorrect results produced by DefaultConnectionReuseStrategy when handling - response messages whose content entity has been decoded or modified by a protocol interceptor. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-283] Workaround for a bug causing termination of the I/O reactor in case of exception - thrown by NHttpServiceHandler#requestReceived or NHttpClientHandler#responseReceived - methods. A more comprehensive fix for the bug applied to the 4.2 branch. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-281] ResponseConnControl protocol interceptor does not correctly populate connection - persistence control headers when sending a HTTP/1.1 response message in response to a HTTP/1.0 - request message. - Contributed by William R. Speirs - -* [HTTPCORE-282] The default value of the internal event mask of newly created non-blocking I/O - is not correctly initialized, which causes the READ interest bit to get cleared in the interest - op queuing mode unless the event mask is explicitly reset. - Contributed by Sadeep Jayasumana and Oleg Kalnichevski - -* [HTTPCORE-268] Handle runtime exceptions thrown by SSLEngine. - Contributed by Oleg Kalnichevski - - - -Release 4.2-ALPHA2 -------------------- - -This is the second ALPHA release of HttpCore 4.2. This release comes with completely redesigned -and rewritten asynchronous protocol handlers. New protocol handling API used in conjunction with -connection pooling components introduced in the previous ALPHA release is expected to make -development of asynchronous HTTP client agents and HTTP proxies easier and less error prone. - -Sample application shipped with the release include an example of an HTTP file server capable of -direct channel (zero copy) data transfer and an example of a non-blocking, fully streaming reverse -proxy. - -We are kindly asking existing and prospective users of HttpCore to review and try out the -new protocol handlers and give us feedback while the 4.2 API is still not final. If no major flaws -are discovered the 4.2 API is expected to be frozen with the next BETA release. - -Please note that new features included in this release are still considered experimental and -their API may change in the future ALPHA releases. This release also marks the end of support for -Java 1.3. As of this release HttpCore requires Java 1.5 for all its components. Several classes and -methods deprecated between versions 4.0-beta1 and 4.0 GA (more than two years ago) have been -removed in this release. - -Changelog -------------------- - -* [HTTPCORE-270] Fixed IllegalStateException in AbstractSessionOutputBuffer and - AbstractSessionInputBuffer. - Contributed by William R. Speirs - -* [HTTPCORE-269] Connection pools incorrectly handle lease requests when the max limit for the given - route has been exceeded and all connections in the route pool are stateful. - Contributed by Oleg Kalnichevski - - -Release 4.2-ALPHA1 -------------------- - -This is the first ALPHA release of 4.2. The most notable feature included in this release is -support for connection pools of blocking and non-blocking HTTP connections. Connection pool -components are based on mature code migrated from HttpClient and HttpAsyncClient modules but have -a slightly different API that makes a better use of Java standard concurrent primitives. - -Support for connection pools in HttpCore is expected to make development of client and proxy HTTP -services easier and less error prone. - -Please note that new features included in this release are still considered experimental and -their API may change in the future ALPHA releases. This release also marks the end of support for -Java 1.3. As of this release HttpCore requires Java 1.5 for all its components. Several classes and -methods deprecated between versions 4.0-beta1 and 4.0 GA (more than two years ago) have been -removed in this release. - -Changelog -------------------- - -* [HTTPCORE-268] Handle runtime exceptions thrown by SSLEngine. - Contributed by Oleg Kalnichevski - -Release 4.1.3 -------------------- - -This is an emergency release that fixes a severe regression in the non-blocking SSL I/O code -introduced in release 4.1.2. - -* [HTTPCORE-266] SSLIOSession does not correctly terminate if the opposite end shuts down connection - without sending a 'close notify' message causing an infinite loop in the I/O dispatch thread. - Contributed by Oleg Kalnichevski - -Release 4.1.2 -------------------- - -This is a patch release that fixes a number of bugs found in the previous version. - -Please note that several classes and methods deprecated between versions 4.0-beta1 and 4.0 GA -(more than two years ago) will also be removed in the 4.2 branch. - -Users of 4.0.x versions are advised to upgrade and replace deprecated API calls following -recommendations in javadocs. - -* [HTTPCORE-261] IOSession#setSocketTimeout() method does not reset the timeout count. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-260] Non-blocking SSL I/O session can terminate prematurely causing message body - truncation when message content is chunk coded and the connection is closed on the opposite end. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-257] Fixed incorrect results produced by DefaultConnectionReuseStrategy when handling - response messages whose content entity has been decoded or modified by a protocol interceptor. - Contributed by Oleg Kalnichevski - -Release 4.1.1 -------------------- - -This is a patch release that fixes a number of non-critical issues found since release 4.1. - -This release marks the end of support for Java 1.3. As of release 4.2 HttpCore will require -Java 1.5 for all its components. - -Please note that several classes and methods deprecated between versions 4.0-beta1 and 4.0 GA -(more than two years ago) will also be removed in the 4.2 branch. - -Users of 4.0.x versions are advised to upgrade and replace deprecated API calls following -recommendations in javadocs. - -* In case of an unexpected end of stream condition (the peer closed connection prematurely) - truncated Content-Length delimited message bodies will cause an I/O exception. Application - can still choose to catch and ignore ConnectionClosedException in order to accept partial - message content. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-255]: Fixed resource management in InputStreamEntity#writeTo() - Contributed by Oleg Kalnichevski - -* [HTTPCORE-254]: Erratic results from metrics (sebb) - -* [HTTPCORE-242]: Fixed NPE in AsyncNHttpClientHandler caused by an early response to an - entity enclosing request. - Contributed by Oleg Kalnichevski - - -Release 4.1 -------------------- - -This is the first stable (GA) release of HttpCore 4.1. This release provides a compatibility mode -with JREs that have a naive (broken) implementation of SelectionKey API and also improves -compatibility with the Google Android platform. There has also been a number of performance -related improvements and bug fixes in both blocking and non-blocking components. - -Changelog -------------------- - -* [HTTPCORE-240]: DefaultConnectingIOReactor leaks a socket descriptor if the session request fails. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-239]: The ChunkEncoder could request for a negative buffer limit causing an - IllegalArgumentException. - Contributed by Asankha Perera - -* [HTTPCORE-236]: SSLIOSession#isAppInputReady() does not check the status of the session input - buffer. - Contributed by Dmitry Lukyanov - -* [HTTPCORE-233]: EntityUtils#toString() and EntityUtils#toByteArray() to return null if - HttpEntity#getContent() is null - Contributed by Oleg Kalnichevski - -* [HTTPCORE-231] Fixed incorrect handling of HTTP entities by non-blocking LengthDelimitedDecoder - when the Content-Length value is larger than Integer.MAX_VALUE. - Contributed by Oleg Kalnichevski - -Release 4.1-BETA2 -------------------- - -This is the second BETA release of HttpCore 4.1. This is mainly a bug fix release that addresses -a number of non-critical bugs. - -The most significant change in this release is deprecation of the HttpEntity#consumeContent() -method and streamlining of connection management and resource deallocation by HTTP entities. -Please refer to the javadocs for details. - -* [HTTPCORE-229] AbstractSessionInputBuffer#readLine(CharArrayBuffer) returns incorrect - number of characters read by the method when using non-standard HTTP element charset. - Contributed by Oleg Kalnichevski - -* Non-blocking connections can trigger #responseReady / #requestReady events by mistake - when the underlying session is already closed. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-228] Fixed NPE in AsyncNHttpServiceHandler caused by entity enclosing requests - if no matching request handler can be found. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-227] Fixed incorrect request / response count by non-blocking connections. - Contributed by Harold Lee - -* [HTTPCORE-226] Improved compatibility of NIO components with Google Android. - Contributed by Oleg Kalnichevski - -* ByteArrayBuffer, CharArrayBuffer, BasicHeader, BufferedHeader, HeaderGroup, BasicRequestLine, - BasicStatusLine made Serializable. - Contributed by Oleg Kalnichevski - -Release 4.1-BETA1 -------------------- - -This is the first BETA release of HttpCore 4.1. This release finalizes the API introduced in the -4.1 development branch. It also fixes a number of bugs discovered since the previous release and -delivers a number of performance optimizations in the blocking HTTP transport components. -The blocking HTTP transport is expected to be 5% to 10% faster compared to previous releases. - -* [HTTPCORE-222] Fixed Import-Package in the OSGi META-INF - Contributed by Willem Jiang - -* [HTTPCORE-177] Reduce intermediate data buffering by reading large chunks of data directly from - the underlying socket stream. This results in improved performance of blocking read operations. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-220] IdentityDecoder fails to detect end of stream when using file channels. - Contributed by Asankha C. Perera - -* [HTTPCORE-218] ChunkEncoder#write method no longer returns incorrect value if - the data to write is greater than the size of the internal buffer used by the encoder. - Contributed by Richie Jefts - -* [HTTPCORE-209] Added parameter to set SO_REUSEADDR on sockets bound to a local address. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-207] SocketHttp*Connection classes can leak sockets if the connection is half-closed - Contributed by David Koski - -Release 4.1-ALPHA1 -------------------- - -This is the first public release from the 4.1 branch of HttpCore. This release adds a number of -new features, most notable being introduction of compatibility mode with IBM JREs and other JREs -with naive (broken) implementation of SelectionKey API. - -Please note new classes and methods added in the 4.1 branch are still considered API unstable. - -* Ensure that an attempt is made to close out all active sessions gracefully in case of an abnormal - shutdown of the I/O reactor. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-201] OSGi Export-Package to specify release version - Contributed by Oleg Kalnichevski - -* [HTTPCORE-183] Added Thread-safe implementations of HttpParams and HttpProcessor - - SyncBasicHttpParams and ImmutableHttpProcessor classes - Contributed by Oleg Kalnichevski - -* [HTTPCORE-199] ContentInputStream implements InputStream#available(). - Contributed by Oleg Kalnichevski - -* [HTTPCORE-195] Truncated chunk-coded streams can now be tolerated by catching and discarding - TruncatedChunkException. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-155] Compatibility mode with IBM JRE and other JREs with naive (broken) implementation - of SelectionKey. - Contributed by Marc Beyerle and Oleg Kalnichevski - -* [HTTPCORE-191] Blocking HTTP connections are now capable of correctly preserving their internal - state on SocketTimeoutExceptions, which makes it possible to continue reading from the connection - after a socket timeout. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-190] ChunkedInputStream is now capable of correctly preserving its internal state on - SocketTimeoutExceptions, which makes it possible to continue reading from the stream after a - socket timeout. - Contributed by Oleg Kalnichevski - -Release 4.0.1 -------------------- - -This is a patch release addressing a number of issues discovered since the 4.0 release. Users -of NIO module are advised to upgrade. - -* [HTTPCORE-198] CONNECT request includes Host header for HTTP 1.1 connections. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-196] SSLIOSession now unwraps encrypted data more aggressively eliminating long - pauses when receiving data over non-blocking connections. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-197] Fixed bug causing the non-blocking ChunkDecoder to report some data stream as - truncated under special conditions. - Contributed by Denis Rogov and Oleg Kalnichevski - -* SSLIOSession#isAppOutputReady and SSLIOSession#isAppInputReady no longer ignore the application - event mask causing I/O event notifications for unrequested type of events. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-193] Fixed problem with SSLIOSession incorrectly handling of end-of-stream condition. - Contributed by Asankha C. Perera and Oleg Kalnichevski - - -Release 4.0 -------------------- - -This is the first stable (GA) release of HttpCore 4.0. This release mainly improves the -documentation and fixes a few minor bugs reported since the previous release. HttpCore -now comes with a complete tutorial presenting an in-depth coverage of the API. - -HttpCore is a set of low level HTTP transport components that can be used to build custom -client and server side HTTP services with a minimal footprint. HttpCore supports two I/O -models: blocking I/O model based on the classic Java I/O and non-blocking, event driven I/O -model based on Java NIO. The blocking I/O model may be more appropriate for data intensive, -low latency scenarios, whereas the non-blocking model may be more appropriate for high latency -scenarios where raw data throughput is less important than the ability to handle thousands of -simultaneous HTTP connections in a resource efficient manner. - -* [HTTPCORE-180] Fixed NPE in standard I/O event dispatchers when - IOEventDispatch#disconnected fires before the session was fully initialized - (IOEventDispatch#connected was not called). - Contributed by Oleg Kalnichevski - -* [HTTPCORE-175] Chunk decoders no longer accept truncated chunks as valid input. - Contributed by Oleg Kalnichevski - - -Release 4.0 Beta 3 -------------------- - -The third BETA version of HttpComponents Core has been released. This is a -maintenance release, which addresses a number of issues discovered since the -previous release. - -The only significant new feature is an addition of an OSGi compliant bundle -combining HttpCore and HttpCore NIO jars. - -* [HTTPCORE-173] Tolerate missing closing chunk if the chunk coded content - is terminated by the end of stream (EOF) condition. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-174] Position is incremented twice in ContentLengthInputStream#skip(long) - Contributed by Ildar Safarov - -* [HTTPCORE-125] OSGi bundle containing HttpCore & HttpCore NIO jars. - Contributed by Oleg Kalnichevski - -* CancelledKeyException thrown in BaseIOReactor#validate() no longer causes - a premature I/O reactor shutdown. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-172] Added #close() method to SharedInputBuffer and - SharedOutputBuffer. The purpose of the new method is to close the buffer - in case of normal / orderly termination of the underlying HTTP connection. - Use #shutdown() method to force-close the buffer in case of abnormal / - exceptional termination of the underlying connection. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-170] Fixed race condition in SharedOutputBuffer. - Contributed by Jason Walton - -* [HTTPCORE-169] Fixed bug causing connecting I/O reactors to shut down due to - ClosedChannelException if a pending session request is cancelled before the new - channel has been registered with the selector. - Contributed by Anders Wallgren - -* [HTTPCORE-167] Fixed handling the end of stream (EOF) condition in the #isStale() - check of blocking HTTP connections. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-166] NIO reactors now maintain an audit log of fatal exceptions, - which can be used to examine the cause and problems experienced during - the shutdown process. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-165] Improved handling of CancelledKeyException in I/O reactors - Contributed by Oleg Kalnichevski - - -Release 4.0 Beta 2 -------------------- - -The second BETA version of HttpComponents Core has been released. This release -adds a number of improvements to the NIO components, most notable being improved -asynchronous client side and server side protocol handlers. - -There has been a number of important bug fixes in HttpCore NIO module, whereas -HttpCore base module has had very few changes. - -All upstream projects dependent on HttpCore NIO are strongly advised to upgrade. - -* [HTTPCORE-163] Fixed AbstractMultiworkerIOReactor#execute() to correctly - propagate the original I/O exception in case of an abnormal termination. - Contributed by Patrick Moore - -* Changed behavior of IdentityDecoder & LengthDelimitedDecoder to throw - an IOException if data is attempted to be written beyond the length - of a FileChannel. Previously would write nothing. - Contributed by Sam Berlin - -* Fixed bug in LengthDelimitedDecoder & IdentityDecoder that caused transfers - to a FileChannel to overwrite arbitrary parts of the file, if data was - buffered in SessionInputBuffer. - Contributed by Sam Berlin - -* Fixed concurrency bug in the ThrottlingHttpServerHandler protocol handler. - Contributed by Oleg Kalnichevski - -* Fixed bug in SharedInputBuffer that caused input events to be - incorrectly suspended. - Contributed by Asankha C. Perera - -* [HTTPCORE-150] Entity implementation that serializes a Java object - Contributed by Andrea Selva - -* [HTTPCORE-157] ChunkedOutputStream#flush() now behaves consistently with the - specification of OutputStream#flush(). - Contributed by Oleg Kalnichevski - -* [HTTPCORE-147] Fixed handling of requests with partially consumed content - in ThrottlingHttpServiceHandler. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-92] ChunkEncoder splits input data larger than available space - in the session output buffer into smaller chunks instead of expanding - the buffer. - Contributed by Andrea Selva and - Oleg Kalnichevski - -* [HTTPCORE-149] I/O reactors now count period of inactivity since the - time of the last read or write operation. Previously only read - operations resulted in timeout counter reset. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-148] Improved asynchronous server and client HTTP protocol - handler implementations. - Contributed by Sam Berlin - -* [HTTPCORE-143] Ensure the underlying channel is closed if the session - request is canceled or times out. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-140] Fixed timeout handling in ThrottlingHttpServiceHandler. - Contributed by Lorenzo Moretti and - Oleg Kalnichevski - - - -Release 4.0 Beta 1 -------------------- - -The first BETA version of HttpComponents Core has been released. This release -can be considered a major milestone, as it marks the end of API instability -in HttpCore. As of this release the API compatibility between minor releases -in 4.x codeline will be maintained. - -This release includes several major improvements such as enhanced HTTP message -parsing API and optimized parser implementations, Java 5.0 compatibility -for HttpCore NIO extensions. Upstream projects are strongly encouraged to -upgrade to the latest release. - -The focus of the development efforts will be gradually shifting towards -providing better test coverage, documentation and performance optimizations. - -Changelog: ----------- - -* [HTTPCORE-141] Session request timeout in DefaultConnectingIOReactor - invalidates the request. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-137] DefaultHttpRequestFactory extended to support all methods - specified in RFC 2616 (except CONNECT). - Contributed by Oleg Kalnichevski - -* Replaced HTTP parameter linking with a simple child/parent stack. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-134] all serialVersionUID attributes are private - Contributed by Roland Weber - -* [HTTPCORE-133] Clone support for basic HTTP message elements and - non-streaming entities. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-127] Improved API for lifecycle management of listening I/O - reactors. One can now suspend and resume listener endpoints. - Contributed by Asankha C. Perera - -* [HTTPCORE-112] DefaultConnectionReuseStrategy interprets token sequences - Contributed by Roland Weber - -* [HTTPCORE-122] new interface TokenIterator and basic implementation - Contributed by Roland Weber - -* HttpCore NIOSSL classes moved to HttpCore NIO. - Contributed by Oleg Kalnichevski - -* HttpCore NIO ported to Java 1.5. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-130] Fixed over-synchronization bug leading to a thread deadlock - condition in SSL IOEventDispatch implementations. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-37] HttpParams beans - Contributed by Stojce Dimski - -* [HTTPCORE-128] Simplified injection of custom NIO connection implementations. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-126] Improved HTTP message parsing API and optimized parser - implementations. - Contributed by Oleg Kalnichevski - -* Do not include "Connection: close" to 500 responses per default. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-121] new interface HeaderElementIterator - Contributed by Andrea Selva - -* [HTTPCORE-123] Fixed problem with SSLSession losing buffered data, if the - connection has been closed by the peer. - Contributed by Risto Reinpõld - - - -Release 4.0 Alpha 6 -------------------- - -The sixth ALPHA version of HttpComponents Core has been released. This release -sports an improved message parsing and formatting API in the base module and -lots of incremental improvements and bug fixes in the NIO and NIOSSL modules. -Based on the improved API, it is now possible to send and receive SIP messages -with HttpComponents Core. - -HttpCore is now feature complete and we are planning to freeze the public APIs -as of next release (BETA1). - -* [HTTPCORE-120] new interface HeaderIterator, available from HttpMessage - Contributed by Roland Weber - -* [HTTPCORE-118] Purge closed sessions prior to opening new ones. This should - reduce chances of running out of memory when opening and closing lots of - NIO connections in a tight loop. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-117] Fixed bug preventing protocol handlers from closing timed out - NIO connection when pending output (output session buffer is not empty). - Contributed by Oleg Kalnichevski - -* [HTTPCORE-86] Allow for optional handling of runtime exceptions - thrown by protocol handlers to ensure the I/O dispatch thread - remains running. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-116] moved parameter names to interfaces - Contributed by Roland Weber - -* [HTTPCORE-109] Improved shutdown process of the I/O reactors in NIO modules. - I/O reactors now attempt to terminate connections gracefully before shutting - down the underlying socket channels. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-107] allow sending and receiving of SIP messages - Contributed by Roland Weber - -* [HTTPCORE-114]: Fixed incorrect handling of the end-of-stream condition - in SSLIOSession. - Oleg Kalnichevski - -* [HTTPCORE-110] refactored message parsing and formatting logic - Contributed by Roland Weber - -* [HTTPCORE-113] Removed unnecessary target hostname resolution from - non-blocking client protocol handlers. - Oleg Kalnichevski - -* [HTTPCORE-108] Close all channels registered with the I/O reactor during - shutdown. Fixed the problem with DefaultListeningIOReactor not releasing - socket ports until JVM is restarted. - Oleg Kalnichevski - -* [HTTPCORE-106] Pluggable HTTP message parsers and message writers - Oleg Kalnichevski - -* [HTTPCORE-105] Consistent class names in base and NIO modules - Oleg Kalnichevski - -* [HTTPCORE-100] revised HttpContext hierarchy - Contributed by Roland Weber - -* [HTTPCORE-103] NIO connections now attempt to consume all available session - data while parsing HTTP messages. This can potentially improve performance - of non-blocking SSL connections. - Contributed by Steffen Pingel - -* [HTTPCORE-102] Exceeding of maximum line length limit detected late - Contributed by Steffen Pingel - -* [HTTPCORE-21] Transport and connection metrics - Contributed by Andrea Selva and - Oleg Kalnichevski - -* [HTTPCORE-91] new interceptor RequestDate, renamed constants in protocol.HTTP - Contributed by Roland Weber - -* [HTTPCORE-90] Version detection based on build-time properties - Contributed by Oleg Kalnichevski and - Roland Weber - -* [HTTPCORE-88] Added convenience methods to HttpRequestInterceptorList, - HttpResponseInterceptorList interfaces - Contributed by Andrea Selva - -* [HTTPCORE-89]: Fixed bug in DefaultConnectingIOReactor causing incorrect - handling of local (immediate) connections on some platforms (affects Sun - Solaris 2.9 / Sparc and likely other Solaris 2.x platforms) - Contributed by Sam Berlin - -Release 4.0 Alpha 5 -------------------- - -The fifth ALPHA version of HttpComponents Core has been released. This release -delivers a number of incremental improvements across the board in all modules -and adds several performance oriented features such as ability to transfer -data directly between a file and a socket channels. - -HttpCore is almost fully feature complete now and we are likely to freeze -the public APIs as of next release (BETA1). - -* [HTTPCORE-87] RuntimeExcpetions thrown in I/O worker threads are now correctly - propagated to the I/O reactor. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-84]: Removed DateUtils/DateParseException from core. - Contributed by Roland Weber - -* [HTTPCORE-63]: Made I/O select interval configurable for all default I/O - reactor implementations. - Contributed by Oleg Kalnichevski and - Anders Wallgren - -* [HTTPCORE-82]: Revised linking of HttpParams to reduce potential for misuse. - Method #setDefaults() removed from the HttpParams interface. - Contributed by Roland Weber - -* [HTTPCORE-81]: Maximum line length and maximum header counts parameters are now - correctly enforced in both base and NIO modules. Fixed maximum line length check - when parsing folded header lines. - Contributed by Steffen Pingel - -* Added HTTP client handler implementation that allocates fixed size content - buffers upon initialization and is capable of throttling the rate of I/O events - in order to make sure those content buffers do not get overflown. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-76]: Added IOSession#shutdown() method intended to force-close - I/O sessions (primarily needed to terminate hung SSL connections). - Contributed by Sandeep Tamhankar - -* [HTTPCORE-78]: Added ByteBufferAllocator interface that can be used to apply - different ByteArray allocation strategies to session and content buffers. - Use heap bound implementation for short-lived or variable in length (requiring - frequent content re-allocation) buffers. - Contributed by Steffen Pingel - -* [HTTPCORE-77]: The result of CharsetDecoder#decode() and CharsetEncoder#encode() - was not checked for errors resulting in an infinite loop in - SessionInputBuffer#readLine() and SessionOutputBuffer#writeLine() - when malformed characters were processed. - Contributed by Steffen Pingel - -* [HTTPCORE-71]: HttpParams can be copied. - Contributed by Roland Weber - -* [HTTPCORE-75]: DefaultNHttpServerConnection and DefaultNHttpClientConnection - now correctly terminate the underlying I/O session when closed. - BufferingHttpServiceHandler now correctly applies connection keep-alive - strategy when sending a response with no content body. - Contributed by Steffen Pingel - -* [HTTPCORE-73]: Fixed bug preventing NHttpServiceHandler#responseReady and - NHttpClientHandler#requestReady events from being fired if the HTTP message - has no content body. - Contributed by Steffen Pingel - -* [HTTPCORE-67]: Improved event listener interface - Contributed by Oleg Kalnichevski - -* [HTTPCORE-43]: Support for FileChannel#transferFrom() and - FileChannel#transferTo() methods. Direct coping from and to FileChannel is - expected to improve performance of file bound operations - Contributed by Andrea Selva - -* [HTTPCORE-66]: Fixed handling of HTTP HEAD methods - Contributed by Steffen Pingel and - Oleg Kalnichevski - -* [HTTPCORE-58]: NIO HTTP connections changed to throw checked - ConnectionClosedException instead of unchecked IllegalStateException when - an attempt is made to perform an I/O operation on a closed conection - Contributed by Oleg Kalnichevski - -* [HTTPCORE-56]: DefaultConnectingIOReactor no longer terminates due to a - CancelledKeyException, if a session request gets canceled before selection - key is fully initialized. - Contributed by Oleg Kalnichevski - -Release 4.0 Alpha 4 -------------------- - -The forth ALPHA version of HttpComponents Core has been released. -The ALPHA4 release fixes a number of bugs and adds a number of -improvements to HttpCore base and HttpCore NIO extensions. -HttpCore NIO can be used to build HTTP services intended to handle -thousands of simultaneous connections with a small number of I/O -threads. This release also introduces NIOSSL extensions that can be -used to extend HttpCore non-blocking transport components with -ability to transparently encrypt data in transit using SSL/TLS protocol. - -* [HTTPCORE-49]: DefaultConnectingIOReactor can now correctly handle - unresolved socket addresses. It no longer terminates with the - UnresolvedAddressException runtime exception. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-42]: Added server side API for the expectation verification. - Improved support for the 'expect: continue' handshake in HttpCore and - HttpCore NIO. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-26]: Added SSL support for HttpCore NIO. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-40]: API classes no longer reference impl classes in module-main. - Contributed by Roland Weber - -* [HTTPCORE-39]: Refactored HttpStatus, spun off [English]ReasonPhraseFactory. - Contributed by Roland Weber - -* [HTTPCORE-32]: HttpRequestInterceptorList, HttpResponseInterceptorList - Contributed by Roland Weber - -* [HTTPCORE-38]: Packages nio.impl.* are now impl.nio.*, same for examples. - Contributed by Roland Weber - -* [HTTPCORE-27]: I/O reactors can now accept a thread factory as an optional - parameter. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-36]: Fixed #setHandlers() method and matching of request URIs - with a query part in HttpRequestHandlerRegistry - Contributed by Oleg Kalnichevski - -* [HTTPCORE-28]: DefaultConnectingIOReactor now maintains a queue of connect - requests and registers new sessions with the selector on the I/O thread. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-29] DefaultConnectingIOReactor changed to ensure IOExceptions - are correctly propagated to the caller, if an exception is thrown while - initializing a newly connected socket. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-24] Fixed bug in non-blocking connection implementations, which - prevented the session buffer from being correctly flushed when the content - coding process has been completed. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-23] Fixed threading bug in DefaultConnectingIOReactor. - Contributed by Asankha C. Perera - -Release 4.0 Alpha 3 -------------------- - -The third ALPHA version of HttpCore has been released. The ALPHA3 release -includes a number of API optimizations and improvements and introduces a set -of NIO extensions to the HttpCore API. NIO extensions can be used to build -HTTP services intended to handle thousands of simultaneous connections with -a small number of I/O threads. - -* [HTTPCORE-15] Provided a interafce to access IP address of the local and - remote end points. - Contributed by Oleg Kalnichevski - -* [ HTTPCORE-14] Scheme, SocketFactory and SecureSocketFactory moved to - HttpClient. Decoupled HttpHost and Scheme. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-13] Refactored HttpProcessor interface and related impl classes - Contributed by Roland Weber - -* [HTTPCORE-11] Client connection interface no longer defines a specific - method to open a connection. HTTP connections can now represent any - abstract I/O transport such as those based on NIO API. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-10] Non-blocking (async) client side I/O transport based on NIO. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-9] Non-blocking (async) server side I/O transport based on NIO. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-7] ConnectionReuseStrategy interface changed to allow access - to the HTTP execution context. - Contributed by Roland Weber - -* [HTTPCORE-6] Header implementation allowing for performance short-cuts - when serializing and deserializing HTTP headers. - Contributed by Oleg Kalnichevski - -* [HTTPCORE-5] Header, HeaderElement, NameValuePair, RequestLine, StatusLine, - HttpVersion changed to interfaces. API no longer contains any parsing and - formatting code and does not imply any specific physical representation of - HTTP messages and their elements. - Contributed by Oleg Kalnichevski - -Release 4.0 Alpha 2 -------------------- -This is a maintenance release that mostly fixes minor problems found since the -previous release. The upstream projects are strongly encouraged use this -release as a dependency while HttpCore undergoes another round of reviews -and optimization in the SVN trunk - -Changelog: ---------- -* [HTTPCORE-4] optional header and line length limits to contain OOME risks - Contributed by Oleg Kalnichevski - -Release 4.0 Alpha 1 -------------------- -This release represents a complete redesign of the Jakarta Commons HttpClient -3.x API and a significant rewrite of the core HTTP components derived from -HttpClient 3.0 code base. - -These components will form the foundation of the future releases of Jakarta -HttpClient and can also be used separately to build custom client- and -server-side HTTP services. diff --git a/All/Genesis-OOB/Genesis#176/pair.info b/All/Genesis-OOB/Genesis#176/pair.info deleted file mode 100755 index d776b80..0000000 --- a/All/Genesis-OOB/Genesis#176/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:176 -SATName:Genesis -modifiedFPath:httpcore/src/main/java/org/apache/http/impl/io/AbstractSessionInputBuffer.java -comSha:dd00a9e -parentComSha:dd00a9e^1 -githubUrl:https://github.com/apache/httpcore -repoName:apache#httpcore \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#177/comMsg.txt b/All/Genesis-OOB/Genesis#177/comMsg.txt deleted file mode 100755 index cc6262f..0000000 --- a/All/Genesis-OOB/Genesis#177/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Method visitEndTag: Length check must be first as otherwise the 'tag' will cause a StringIndexOutOfBoundsException to be thrown. diff --git a/All/Genesis-OOB/Genesis#177/diff.diff b/All/Genesis-OOB/Genesis#177/diff.diff deleted file mode 100755 index 24289da..0000000 --- a/All/Genesis-OOB/Genesis#177/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/parser/src/main/java/org/htmlparser/beans/StringBean.java b/parser/src/main/java/org/htmlparser/beans/StringBean.java -index c07d765..3fc9659 100644 ---- a/parser/src/main/java/org/htmlparser/beans/StringBean.java -+++ b/parser/src/main/java/org/htmlparser/beans/StringBean.java -@@ -46 +46 @@ import org.htmlparser.visitors.NodeVisitor; -- *

The property Strings, which is the output property is null -+ *

The property Strings, which is the output property is null -@@ -695 +695,2 @@ public class StringBean extends NodeVisitor implements Serializable -- if ((name.charAt (0) == 'H') && (2 == name.length ()) && Character.isDigit (name.charAt (1))) -+ // Length check must be first as otherwise the 'tag' will cause a StringIndexOutOfBoundsException to be thrown. -+ if ((2 == name.length ()) && (name.charAt (0) == 'H') && (Character.isDigit (name.charAt (1)))) diff --git a/All/Genesis-OOB/Genesis#177/new/StringBean.java b/All/Genesis-OOB/Genesis#177/new/StringBean.java deleted file mode 100755 index 3fc9659..0000000 --- a/All/Genesis-OOB/Genesis#177/new/StringBean.java +++ /dev/null @@ -1,719 +0,0 @@ -// HTMLParser Library - A java-based parser for HTML -// http://htmlparser.org -// Copyright (C) 2006 Derrick Oswald -// -// Revision Control Information -// -// $URL$ -// $Author$ -// $Date$ -// $Revision$ -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the Common Public License; either -// version 1.0 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 -// Common Public License for more details. -// -// You should have received a copy of the Common Public License -// along with this library; if not, the license is available from -// the Open Source Initiative (OSI) website: -// http://opensource.org/licenses/cpl1.0.php - -package org.htmlparser.beans; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.net.URLConnection; - -import org.htmlparser.Parser; -import org.htmlparser.Text; -import org.htmlparser.tags.LinkTag; -import org.htmlparser.Tag; -import org.htmlparser.util.ParserException; -import org.htmlparser.util.EncodingChangeException; -import org.htmlparser.util.Translate; -import org.htmlparser.visitors.NodeVisitor; - -/** - * Extract strings from a URL. - *

Text within <SCRIPT></SCRIPT> tags is removed.

- *

The text within <PRE></PRE> tags is not altered.

- *

The property Strings, which is the output property is null - * until a URL is set. So a typical usage is:

- *
- *     StringBean sb = new StringBean ();
- *     sb.setLinks (false);
- *     sb.setReplaceNonBreakingSpaces (true);
- *     sb.setCollapse (true);
- *     sb.setURL ("http://www.netbeans.org"); // the HTTP is performed here
- *     String s = sb.getStrings ();
- * 
- * You can also use the StringBean as a NodeVisitor on your own parser, - * in which case you have to refetch your page if you change one of the - * properties because it resets the Strings property:

- *
- *     StringBean sb = new StringBean ();
- *     Parser parser = new Parser ("http://cbc.ca");
- *     parser.visitAllNodesWith (sb);
- *     String s = sb.getStrings ();
- *     sb.setLinks (true);
- *     parser.reset ();
- *     parser.visitAllNodesWith (sb);
- *     String sl = sb.getStrings ();
- * 
- * According to Nick Burch, who contributed the patch, this is handy if you - * don't want StringBean to wander off and get the content itself, either - * because you already have it, it's not on a website etc. - */ -public class StringBean extends NodeVisitor implements Serializable -{ - /** - * Property name in event where the URL contents changes. - */ - public static final String PROP_STRINGS_PROPERTY = "strings"; - - /** - * Property name in event where the 'embed links' state changes. - */ - public static final String PROP_LINKS_PROPERTY = "links"; - - /** - * Property name in event where the URL changes. - */ - public static final String PROP_URL_PROPERTY = "URL"; - - /** - * Property name in event where the 'replace non-breaking spaces' - * state changes. - */ - public static final String PROP_REPLACE_SPACE_PROPERTY = - "replaceNonBreakingSpaces"; - - /** - * Property name in event where the 'collapse whitespace' state changes. - */ - public static final String PROP_COLLAPSE_PROPERTY = "collapse"; - - /** - * Property name in event where the connection changes. - */ - public static final String PROP_CONNECTION_PROPERTY = "connection"; - - /** - * A newline. - */ - private static final String NEWLINE = System.getProperty ("line.separator"); - - /** - * The length of the NEWLINE. - */ - private static final int NEWLINE_SIZE = NEWLINE.length (); - - /** - * Bound property support. - */ - protected PropertyChangeSupport mPropertySupport; - - /** - * The parser used to extract strings. - */ - protected Parser mParser; - - /** - * The strings extracted from the URL. - */ - protected String mStrings; - - /** - * If true the link URLs are embedded in the text output. - */ - protected boolean mLinks; - - /** - * If true regular space characters are substituted for - * non-breaking spaces in the text output. - */ - protected boolean mReplaceSpace; - - /** - * If true sequences of whitespace characters are replaced - * with a single space character. - */ - protected boolean mCollapse; - - /** - * The state of the collapse processiung state machine. - */ - protected int mCollapseState; - - /** - * The buffer text is stored in while traversing the HTML. - */ - protected StringBuffer mBuffer; - - /** - * Set true when traversing a SCRIPT tag. - */ - protected boolean mIsScript; - - /** - * Set true when traversing a PRE tag. - */ - protected boolean mIsPre; - - /** - * Set true when traversing a STYLE tag. - */ - protected boolean mIsStyle; - - /** - * Create a StringBean object. - * Default property values are set to 'do the right thing': - *

Links is set false so text appears like a - * browser would display it, albeit without the colour or underline clues - * normally associated with a link.

- *

ReplaceNonBreakingSpaces is set true, so - * that printing the text works, but the extra information regarding these - * formatting marks is available if you set it false.

- *

Collapse is set true, so text appears - * compact like a browser would display it.

- */ - public StringBean () - { - super (true, true); - mPropertySupport = new PropertyChangeSupport (this); - mParser = new Parser (); - mStrings = null; - mLinks = false; - mReplaceSpace = true; - mCollapse = true; - mCollapseState = 0; - mBuffer = new StringBuffer (4096); - mIsScript = false; - mIsPre = false; - mIsStyle = false; - } - - // - // internals - // - - /** - * Appends a newline to the buffer if there isn't one there already. - * Except if the buffer is empty. - */ - protected void carriageReturn () - { - int length; - - length = mBuffer.length (); - if ((0 != length) // don't append newlines to the beginning of a buffer - && ((NEWLINE_SIZE <= length) // not enough chars to hold a NEWLINE - && (!mBuffer.substring ( - length - NEWLINE_SIZE, length).equals (NEWLINE)))) - mBuffer.append (NEWLINE); - mCollapseState = 0; - } - - /** - * Add the given text collapsing whitespace. - * Use a little finite state machine: - *
-     * state 0: whitepace was last emitted character
-     * state 1: in whitespace
-     * state 2: in word
-     * A whitespace character moves us to state 1 and any other character
-     * moves us to state 2, except that state 0 stays in state 0 until
-     * a non-whitespace and going from whitespace to word we emit a space
-     * before the character:
-     *    input:     whitespace   other-character
-     * state\next
-     *    0               0             2
-     *    1               1        space then 2
-     *    2               1             2
-     * 
- * @param buffer The buffer to append to. - * @param string The string to append. - */ - protected void collapse (StringBuffer buffer, String string) - { - int chars; - char character; - - chars = string.length (); - if (0 != chars) - { - for (int i = 0; i < chars; i++) - { - character = string.charAt (i); - switch (character) - { - // see HTML specification section 9.1 White space - // http://www.w3.org/TR/html4/struct/text.html#h-9.1 - case '\u0020': - case '\u0009': - case '\u000C': - case '\u200B': - case '\r': - case '\n': - if (0 != mCollapseState) - mCollapseState = 1; - break; - default: - if (1 == mCollapseState) - buffer.append (' '); - mCollapseState = 2; - buffer.append (character); - } - } - } - } - - /** - * Extract the text from a page. - * @return The textual contents of the page. - * @exception ParserException If a parse error occurs. - */ - protected String extractStrings () - throws - ParserException - { - String ret; - - mCollapseState = 0; - mParser.visitAllNodesWith (this); - ret = mBuffer.toString (); - mBuffer = new StringBuffer(4096); - - return (ret); - } - - /** - * Assign the Strings property, firing the property change. - * @param strings The new value of the Strings property. - */ - protected void updateStrings (String strings) - { - String oldValue; - - if ((null == mStrings) || !mStrings.equals (strings)) - { - oldValue = mStrings; - mStrings = strings; - mPropertySupport.firePropertyChange ( - PROP_STRINGS_PROPERTY, oldValue, strings); - } - } - - /** - * Fetch the URL contents. - * Only do work if there is a valid parser with it's URL set. - */ - protected void setStrings () - { - mCollapseState = 0; - if (null != getURL ()) - try - { - try - { - mParser.visitAllNodesWith (this); - updateStrings (mBuffer.toString ()); - } - finally - { - mBuffer = new StringBuffer (4096); - } - } - catch (EncodingChangeException ece) - { - mIsPre = false; - mIsScript = false; - mIsStyle = false; - try - { // try again with the encoding now in force - mParser.reset (); - mBuffer = new StringBuffer (4096); - mCollapseState = 0; - mParser.visitAllNodesWith (this); - updateStrings (mBuffer.toString ()); - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - finally - { - mBuffer = new StringBuffer (4096); - } - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - else - { - // reset in case this StringBean is used as a visitor - // on another parser, not it's own - mStrings = null; - mBuffer = new StringBuffer (4096); - } - } - - /** - * Refetch the URL contents. - * Only need to worry if there is already a valid parser and it's - * been spent fetching the string contents. - */ - private void resetStrings () - { - if (null != mStrings) - try - { - mParser.setURL (getURL ()); - setStrings (); - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - } - - // - // Property change support. - // - - /** - * Add a PropertyChangeListener to the listener list. - * The listener is registered for all properties. - * @param listener The PropertyChangeListener to be added. - */ - public void addPropertyChangeListener (PropertyChangeListener listener) - { - mPropertySupport.addPropertyChangeListener (listener); - } - - /** - * Remove a PropertyChangeListener from the listener list. - * This removes a registered PropertyChangeListener. - * @param listener The PropertyChangeListener to be removed. - */ - public void removePropertyChangeListener (PropertyChangeListener listener) - { - mPropertySupport.removePropertyChangeListener (listener); - } - - // - // Properties - // - - /** - * Return the textual contents of the URL. - * This is the primary output of the bean. - * @return The user visible (what would be seen in a browser) text. - */ - public String getStrings () - { - if (null == mStrings) - if (0 == mBuffer.length ()) - setStrings (); - else - updateStrings (mBuffer.toString ()); - - return (mStrings); - } - - /** - * Get the current 'include links' state. - * @return true if link text is included in the text extracted - * from the URL, false otherwise. - */ - public boolean getLinks () - { - return (mLinks); - } - - /** - * Set the 'include links' state. - * If the setting is changed after the URL has been set, the text from the - * URL will be reacquired, which is possibly expensive. - * @param links Use true if link text is to be included in the - * text extracted from the URL, false otherwise. - */ - public void setLinks (boolean links) - { - boolean oldValue = mLinks; - if (oldValue != links) - { - mLinks = links; - mPropertySupport.firePropertyChange ( - PROP_LINKS_PROPERTY, oldValue, links); - resetStrings (); - } - } - - /** - * Get the current URL. - * @return The URL from which text has been extracted, or null - * if this property has not been set yet. - */ - public String getURL () - { - return ((null != mParser) ? mParser.getURL () : null); - } - - /** - * Set the URL to extract strings from. - * The text from the URL will be fetched, which may be expensive, so this - * property should be set last. - * @param url The URL that text should be fetched from. - */ - public void setURL (String url) - { - String old; - URLConnection conn; - - old = getURL (); - conn = getConnection (); - if (((null == old) && (null != url)) || ((null != old) - && !old.equals (url))) - { - try - { - if (null == mParser) - mParser = new Parser (url); - else - mParser.setURL (url); - mPropertySupport.firePropertyChange ( - PROP_URL_PROPERTY, old, getURL ()); - mPropertySupport.firePropertyChange ( - PROP_CONNECTION_PROPERTY, conn, mParser.getConnection ()); - setStrings (); - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - } - } - - /** - * Get the current 'replace non breaking spaces' state. - * @return true if non-breaking spaces (character '\u00a0', - * numeric character reference &#160; or character entity - * reference &nbsp;) are to be replaced with normal - * spaces (character '\u0020'). - */ - public boolean getReplaceNonBreakingSpaces () - { - return (mReplaceSpace); - } - - /** - * Set the 'replace non breaking spaces' state. - * If the setting is changed after the URL has been set, the text from the - * URL will be reacquired, which is possibly expensive. - * @param replace true if non-breaking spaces - * (character '\u00a0', numeric character reference &#160; - * or character entity reference &nbsp;) are to be replaced with normal - * spaces (character '\u0020'). - */ - public void setReplaceNonBreakingSpaces (boolean replace) - { - boolean oldValue = mReplaceSpace; - if (oldValue != replace) - { - mReplaceSpace = replace; - mPropertySupport.firePropertyChange (PROP_REPLACE_SPACE_PROPERTY, - oldValue, replace); - resetStrings (); - } - } - - /** - * Get the current 'collapse whitespace' state. - * If set to true this emulates the operation of browsers - * in interpretting text where user agents should collapse input - * white space sequences when producing output inter-word space. - * See HTML specification section 9.1 White space - * - * http://www.w3.org/TR/html4/struct/text.html#h-9.1. - * @return true if sequences of whitespace (space '\u0020', - * tab '\u0009', form feed '\u000C', zero-width space '\u200B', - * carriage-return '\r' and NEWLINE '\n') are to be replaced with a single - * space. - */ - public boolean getCollapse () - { - return (mCollapse); - } - - /** - * Set the current 'collapse whitespace' state. - * If the setting is changed after the URL has been set, the text from the - * URL will be reacquired, which is possibly expensive. - * The internal state of the collapse state machine can be reset with - * code like this: - * setCollapse (getCollapse ()); - * @param collapse If true, sequences of whitespace - * will be reduced to a single space. - */ - public void setCollapse (boolean collapse) - { - mCollapseState = 0; - boolean oldValue = mCollapse; - if (oldValue != collapse) - { - mCollapse = collapse; - mPropertySupport.firePropertyChange ( - PROP_COLLAPSE_PROPERTY, oldValue, collapse); - resetStrings (); - } - } - - /** - * Get the current connection. - * @return The connection that the parser has or null if it - * hasn't been set or the parser hasn't been constructed yet. - */ - public URLConnection getConnection () - { - return ((null != mParser) ? mParser.getConnection () : null); - } - - /** - * Set the parser's connection. - * The text from the URL will be fetched, which may be expensive, so this - * property should be set last. - * @param connection New value of property Connection. - */ - public void setConnection (URLConnection connection) - { - String url; - URLConnection conn; - - url = getURL (); - conn = getConnection (); - if (((null == conn) && (null != connection)) - || ((null != conn) && !conn.equals (connection))) - { - try - { - if (null == mParser) - mParser = new Parser (connection); - else - mParser.setConnection (connection); - mPropertySupport.firePropertyChange ( - PROP_URL_PROPERTY, url, getURL ()); - mPropertySupport.firePropertyChange ( - PROP_CONNECTION_PROPERTY, conn, mParser.getConnection ()); - setStrings (); - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - } - } - - // - // NodeVisitor overrides - // - - /** - * Appends the text to the output. - * @param string The text node. - */ - public void visitStringNode (Text string) - { - if (!mIsScript && !mIsStyle) - { - String text = string.getText (); - if (!mIsPre) - { - text = Translate.decode (text); - if (getReplaceNonBreakingSpaces ()) - text = text.replace ('\u00a0', ' '); - if (getCollapse ()) - collapse (mBuffer, text); - else - mBuffer.append (text); - } - else - mBuffer.append (text); - } - } - - /** - * Appends a NEWLINE to the output if the tag breaks flow, and - * possibly sets the state of the PRE and SCRIPT flags. - * @param tag The tag to examine. - */ - public void visitTag (Tag tag) - { - String name; - - if (tag instanceof LinkTag) - if (getLinks ()) - { // appends the link as text between angle brackets to the output. - mBuffer.append ("<"); - mBuffer.append (((LinkTag)tag).getLink ()); - mBuffer.append (">"); - } - name = tag.getTagName (); - if (name.equalsIgnoreCase ("PRE")) - mIsPre = true; - else if (name.equalsIgnoreCase ("SCRIPT")) - mIsScript = true; - else if (name.equalsIgnoreCase ("STYLE")) - mIsStyle = true; - if (tag.breaksFlow ()) - carriageReturn (); - } - - /** - * Resets the state of the PRE and SCRIPT flags. - * @param tag The end tag to process. - */ - public void visitEndTag (Tag tag) - { - String name; - - name = tag.getTagName (); - if (name.equalsIgnoreCase ("PRE")) - mIsPre = false; - else if (name.equalsIgnoreCase ("SCRIPT")) - mIsScript = false; - else if (name.equalsIgnoreCase ("STYLE")) - mIsStyle = false; - // Bug # 1574684 text extracted merges words in some cases - // Length check must be first as otherwise the 'tag' will cause a StringIndexOutOfBoundsException to be thrown. - if ((2 == name.length ()) && (name.charAt (0) == 'H') && (Character.isDigit (name.charAt (1)))) - carriageReturn (); - } - - /** - * Unit test. - * @param args Pass arg[0] as the URL to process. - */ - public static void main (String[] args) - { - if (0 >= args.length) - System.out.println ("Usage: java -classpath htmlparser.jar" - + " org.htmlparser.beans.StringBean "); - else - { - StringBean sb = new StringBean (); - sb.setLinks (false); - sb.setReplaceNonBreakingSpaces (true); - sb.setCollapse (true); - sb.setURL (args[0]); - System.out.println (sb.getStrings ()); - } - } -} diff --git a/All/Genesis-OOB/Genesis#177/old/StringBean.java b/All/Genesis-OOB/Genesis#177/old/StringBean.java deleted file mode 100755 index c07d765..0000000 --- a/All/Genesis-OOB/Genesis#177/old/StringBean.java +++ /dev/null @@ -1,718 +0,0 @@ -// HTMLParser Library - A java-based parser for HTML -// http://htmlparser.org -// Copyright (C) 2006 Derrick Oswald -// -// Revision Control Information -// -// $URL$ -// $Author$ -// $Date$ -// $Revision$ -// -// This library is free software; you can redistribute it and/or -// modify it under the terms of the Common Public License; either -// version 1.0 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 -// Common Public License for more details. -// -// You should have received a copy of the Common Public License -// along with this library; if not, the license is available from -// the Open Source Initiative (OSI) website: -// http://opensource.org/licenses/cpl1.0.php - -package org.htmlparser.beans; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.net.URLConnection; - -import org.htmlparser.Parser; -import org.htmlparser.Text; -import org.htmlparser.tags.LinkTag; -import org.htmlparser.Tag; -import org.htmlparser.util.ParserException; -import org.htmlparser.util.EncodingChangeException; -import org.htmlparser.util.Translate; -import org.htmlparser.visitors.NodeVisitor; - -/** - * Extract strings from a URL. - *

Text within <SCRIPT></SCRIPT> tags is removed.

- *

The text within <PRE></PRE> tags is not altered.

- *

The property Strings, which is the output property is null - * until a URL is set. So a typical usage is:

- *
- *     StringBean sb = new StringBean ();
- *     sb.setLinks (false);
- *     sb.setReplaceNonBreakingSpaces (true);
- *     sb.setCollapse (true);
- *     sb.setURL ("http://www.netbeans.org"); // the HTTP is performed here
- *     String s = sb.getStrings ();
- * 
- * You can also use the StringBean as a NodeVisitor on your own parser, - * in which case you have to refetch your page if you change one of the - * properties because it resets the Strings property:

- *
- *     StringBean sb = new StringBean ();
- *     Parser parser = new Parser ("http://cbc.ca");
- *     parser.visitAllNodesWith (sb);
- *     String s = sb.getStrings ();
- *     sb.setLinks (true);
- *     parser.reset ();
- *     parser.visitAllNodesWith (sb);
- *     String sl = sb.getStrings ();
- * 
- * According to Nick Burch, who contributed the patch, this is handy if you - * don't want StringBean to wander off and get the content itself, either - * because you already have it, it's not on a website etc. - */ -public class StringBean extends NodeVisitor implements Serializable -{ - /** - * Property name in event where the URL contents changes. - */ - public static final String PROP_STRINGS_PROPERTY = "strings"; - - /** - * Property name in event where the 'embed links' state changes. - */ - public static final String PROP_LINKS_PROPERTY = "links"; - - /** - * Property name in event where the URL changes. - */ - public static final String PROP_URL_PROPERTY = "URL"; - - /** - * Property name in event where the 'replace non-breaking spaces' - * state changes. - */ - public static final String PROP_REPLACE_SPACE_PROPERTY = - "replaceNonBreakingSpaces"; - - /** - * Property name in event where the 'collapse whitespace' state changes. - */ - public static final String PROP_COLLAPSE_PROPERTY = "collapse"; - - /** - * Property name in event where the connection changes. - */ - public static final String PROP_CONNECTION_PROPERTY = "connection"; - - /** - * A newline. - */ - private static final String NEWLINE = System.getProperty ("line.separator"); - - /** - * The length of the NEWLINE. - */ - private static final int NEWLINE_SIZE = NEWLINE.length (); - - /** - * Bound property support. - */ - protected PropertyChangeSupport mPropertySupport; - - /** - * The parser used to extract strings. - */ - protected Parser mParser; - - /** - * The strings extracted from the URL. - */ - protected String mStrings; - - /** - * If true the link URLs are embedded in the text output. - */ - protected boolean mLinks; - - /** - * If true regular space characters are substituted for - * non-breaking spaces in the text output. - */ - protected boolean mReplaceSpace; - - /** - * If true sequences of whitespace characters are replaced - * with a single space character. - */ - protected boolean mCollapse; - - /** - * The state of the collapse processiung state machine. - */ - protected int mCollapseState; - - /** - * The buffer text is stored in while traversing the HTML. - */ - protected StringBuffer mBuffer; - - /** - * Set true when traversing a SCRIPT tag. - */ - protected boolean mIsScript; - - /** - * Set true when traversing a PRE tag. - */ - protected boolean mIsPre; - - /** - * Set true when traversing a STYLE tag. - */ - protected boolean mIsStyle; - - /** - * Create a StringBean object. - * Default property values are set to 'do the right thing': - *

Links is set false so text appears like a - * browser would display it, albeit without the colour or underline clues - * normally associated with a link.

- *

ReplaceNonBreakingSpaces is set true, so - * that printing the text works, but the extra information regarding these - * formatting marks is available if you set it false.

- *

Collapse is set true, so text appears - * compact like a browser would display it.

- */ - public StringBean () - { - super (true, true); - mPropertySupport = new PropertyChangeSupport (this); - mParser = new Parser (); - mStrings = null; - mLinks = false; - mReplaceSpace = true; - mCollapse = true; - mCollapseState = 0; - mBuffer = new StringBuffer (4096); - mIsScript = false; - mIsPre = false; - mIsStyle = false; - } - - // - // internals - // - - /** - * Appends a newline to the buffer if there isn't one there already. - * Except if the buffer is empty. - */ - protected void carriageReturn () - { - int length; - - length = mBuffer.length (); - if ((0 != length) // don't append newlines to the beginning of a buffer - && ((NEWLINE_SIZE <= length) // not enough chars to hold a NEWLINE - && (!mBuffer.substring ( - length - NEWLINE_SIZE, length).equals (NEWLINE)))) - mBuffer.append (NEWLINE); - mCollapseState = 0; - } - - /** - * Add the given text collapsing whitespace. - * Use a little finite state machine: - *
-     * state 0: whitepace was last emitted character
-     * state 1: in whitespace
-     * state 2: in word
-     * A whitespace character moves us to state 1 and any other character
-     * moves us to state 2, except that state 0 stays in state 0 until
-     * a non-whitespace and going from whitespace to word we emit a space
-     * before the character:
-     *    input:     whitespace   other-character
-     * state\next
-     *    0               0             2
-     *    1               1        space then 2
-     *    2               1             2
-     * 
- * @param buffer The buffer to append to. - * @param string The string to append. - */ - protected void collapse (StringBuffer buffer, String string) - { - int chars; - char character; - - chars = string.length (); - if (0 != chars) - { - for (int i = 0; i < chars; i++) - { - character = string.charAt (i); - switch (character) - { - // see HTML specification section 9.1 White space - // http://www.w3.org/TR/html4/struct/text.html#h-9.1 - case '\u0020': - case '\u0009': - case '\u000C': - case '\u200B': - case '\r': - case '\n': - if (0 != mCollapseState) - mCollapseState = 1; - break; - default: - if (1 == mCollapseState) - buffer.append (' '); - mCollapseState = 2; - buffer.append (character); - } - } - } - } - - /** - * Extract the text from a page. - * @return The textual contents of the page. - * @exception ParserException If a parse error occurs. - */ - protected String extractStrings () - throws - ParserException - { - String ret; - - mCollapseState = 0; - mParser.visitAllNodesWith (this); - ret = mBuffer.toString (); - mBuffer = new StringBuffer(4096); - - return (ret); - } - - /** - * Assign the Strings property, firing the property change. - * @param strings The new value of the Strings property. - */ - protected void updateStrings (String strings) - { - String oldValue; - - if ((null == mStrings) || !mStrings.equals (strings)) - { - oldValue = mStrings; - mStrings = strings; - mPropertySupport.firePropertyChange ( - PROP_STRINGS_PROPERTY, oldValue, strings); - } - } - - /** - * Fetch the URL contents. - * Only do work if there is a valid parser with it's URL set. - */ - protected void setStrings () - { - mCollapseState = 0; - if (null != getURL ()) - try - { - try - { - mParser.visitAllNodesWith (this); - updateStrings (mBuffer.toString ()); - } - finally - { - mBuffer = new StringBuffer (4096); - } - } - catch (EncodingChangeException ece) - { - mIsPre = false; - mIsScript = false; - mIsStyle = false; - try - { // try again with the encoding now in force - mParser.reset (); - mBuffer = new StringBuffer (4096); - mCollapseState = 0; - mParser.visitAllNodesWith (this); - updateStrings (mBuffer.toString ()); - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - finally - { - mBuffer = new StringBuffer (4096); - } - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - else - { - // reset in case this StringBean is used as a visitor - // on another parser, not it's own - mStrings = null; - mBuffer = new StringBuffer (4096); - } - } - - /** - * Refetch the URL contents. - * Only need to worry if there is already a valid parser and it's - * been spent fetching the string contents. - */ - private void resetStrings () - { - if (null != mStrings) - try - { - mParser.setURL (getURL ()); - setStrings (); - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - } - - // - // Property change support. - // - - /** - * Add a PropertyChangeListener to the listener list. - * The listener is registered for all properties. - * @param listener The PropertyChangeListener to be added. - */ - public void addPropertyChangeListener (PropertyChangeListener listener) - { - mPropertySupport.addPropertyChangeListener (listener); - } - - /** - * Remove a PropertyChangeListener from the listener list. - * This removes a registered PropertyChangeListener. - * @param listener The PropertyChangeListener to be removed. - */ - public void removePropertyChangeListener (PropertyChangeListener listener) - { - mPropertySupport.removePropertyChangeListener (listener); - } - - // - // Properties - // - - /** - * Return the textual contents of the URL. - * This is the primary output of the bean. - * @return The user visible (what would be seen in a browser) text. - */ - public String getStrings () - { - if (null == mStrings) - if (0 == mBuffer.length ()) - setStrings (); - else - updateStrings (mBuffer.toString ()); - - return (mStrings); - } - - /** - * Get the current 'include links' state. - * @return true if link text is included in the text extracted - * from the URL, false otherwise. - */ - public boolean getLinks () - { - return (mLinks); - } - - /** - * Set the 'include links' state. - * If the setting is changed after the URL has been set, the text from the - * URL will be reacquired, which is possibly expensive. - * @param links Use true if link text is to be included in the - * text extracted from the URL, false otherwise. - */ - public void setLinks (boolean links) - { - boolean oldValue = mLinks; - if (oldValue != links) - { - mLinks = links; - mPropertySupport.firePropertyChange ( - PROP_LINKS_PROPERTY, oldValue, links); - resetStrings (); - } - } - - /** - * Get the current URL. - * @return The URL from which text has been extracted, or null - * if this property has not been set yet. - */ - public String getURL () - { - return ((null != mParser) ? mParser.getURL () : null); - } - - /** - * Set the URL to extract strings from. - * The text from the URL will be fetched, which may be expensive, so this - * property should be set last. - * @param url The URL that text should be fetched from. - */ - public void setURL (String url) - { - String old; - URLConnection conn; - - old = getURL (); - conn = getConnection (); - if (((null == old) && (null != url)) || ((null != old) - && !old.equals (url))) - { - try - { - if (null == mParser) - mParser = new Parser (url); - else - mParser.setURL (url); - mPropertySupport.firePropertyChange ( - PROP_URL_PROPERTY, old, getURL ()); - mPropertySupport.firePropertyChange ( - PROP_CONNECTION_PROPERTY, conn, mParser.getConnection ()); - setStrings (); - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - } - } - - /** - * Get the current 'replace non breaking spaces' state. - * @return true if non-breaking spaces (character '\u00a0', - * numeric character reference &#160; or character entity - * reference &nbsp;) are to be replaced with normal - * spaces (character '\u0020'). - */ - public boolean getReplaceNonBreakingSpaces () - { - return (mReplaceSpace); - } - - /** - * Set the 'replace non breaking spaces' state. - * If the setting is changed after the URL has been set, the text from the - * URL will be reacquired, which is possibly expensive. - * @param replace true if non-breaking spaces - * (character '\u00a0', numeric character reference &#160; - * or character entity reference &nbsp;) are to be replaced with normal - * spaces (character '\u0020'). - */ - public void setReplaceNonBreakingSpaces (boolean replace) - { - boolean oldValue = mReplaceSpace; - if (oldValue != replace) - { - mReplaceSpace = replace; - mPropertySupport.firePropertyChange (PROP_REPLACE_SPACE_PROPERTY, - oldValue, replace); - resetStrings (); - } - } - - /** - * Get the current 'collapse whitespace' state. - * If set to true this emulates the operation of browsers - * in interpretting text where user agents should collapse input - * white space sequences when producing output inter-word space. - * See HTML specification section 9.1 White space - * - * http://www.w3.org/TR/html4/struct/text.html#h-9.1. - * @return true if sequences of whitespace (space '\u0020', - * tab '\u0009', form feed '\u000C', zero-width space '\u200B', - * carriage-return '\r' and NEWLINE '\n') are to be replaced with a single - * space. - */ - public boolean getCollapse () - { - return (mCollapse); - } - - /** - * Set the current 'collapse whitespace' state. - * If the setting is changed after the URL has been set, the text from the - * URL will be reacquired, which is possibly expensive. - * The internal state of the collapse state machine can be reset with - * code like this: - * setCollapse (getCollapse ()); - * @param collapse If true, sequences of whitespace - * will be reduced to a single space. - */ - public void setCollapse (boolean collapse) - { - mCollapseState = 0; - boolean oldValue = mCollapse; - if (oldValue != collapse) - { - mCollapse = collapse; - mPropertySupport.firePropertyChange ( - PROP_COLLAPSE_PROPERTY, oldValue, collapse); - resetStrings (); - } - } - - /** - * Get the current connection. - * @return The connection that the parser has or null if it - * hasn't been set or the parser hasn't been constructed yet. - */ - public URLConnection getConnection () - { - return ((null != mParser) ? mParser.getConnection () : null); - } - - /** - * Set the parser's connection. - * The text from the URL will be fetched, which may be expensive, so this - * property should be set last. - * @param connection New value of property Connection. - */ - public void setConnection (URLConnection connection) - { - String url; - URLConnection conn; - - url = getURL (); - conn = getConnection (); - if (((null == conn) && (null != connection)) - || ((null != conn) && !conn.equals (connection))) - { - try - { - if (null == mParser) - mParser = new Parser (connection); - else - mParser.setConnection (connection); - mPropertySupport.firePropertyChange ( - PROP_URL_PROPERTY, url, getURL ()); - mPropertySupport.firePropertyChange ( - PROP_CONNECTION_PROPERTY, conn, mParser.getConnection ()); - setStrings (); - } - catch (ParserException pe) - { - updateStrings (pe.toString ()); - } - } - } - - // - // NodeVisitor overrides - // - - /** - * Appends the text to the output. - * @param string The text node. - */ - public void visitStringNode (Text string) - { - if (!mIsScript && !mIsStyle) - { - String text = string.getText (); - if (!mIsPre) - { - text = Translate.decode (text); - if (getReplaceNonBreakingSpaces ()) - text = text.replace ('\u00a0', ' '); - if (getCollapse ()) - collapse (mBuffer, text); - else - mBuffer.append (text); - } - else - mBuffer.append (text); - } - } - - /** - * Appends a NEWLINE to the output if the tag breaks flow, and - * possibly sets the state of the PRE and SCRIPT flags. - * @param tag The tag to examine. - */ - public void visitTag (Tag tag) - { - String name; - - if (tag instanceof LinkTag) - if (getLinks ()) - { // appends the link as text between angle brackets to the output. - mBuffer.append ("<"); - mBuffer.append (((LinkTag)tag).getLink ()); - mBuffer.append (">"); - } - name = tag.getTagName (); - if (name.equalsIgnoreCase ("PRE")) - mIsPre = true; - else if (name.equalsIgnoreCase ("SCRIPT")) - mIsScript = true; - else if (name.equalsIgnoreCase ("STYLE")) - mIsStyle = true; - if (tag.breaksFlow ()) - carriageReturn (); - } - - /** - * Resets the state of the PRE and SCRIPT flags. - * @param tag The end tag to process. - */ - public void visitEndTag (Tag tag) - { - String name; - - name = tag.getTagName (); - if (name.equalsIgnoreCase ("PRE")) - mIsPre = false; - else if (name.equalsIgnoreCase ("SCRIPT")) - mIsScript = false; - else if (name.equalsIgnoreCase ("STYLE")) - mIsStyle = false; - // Bug # 1574684 text extracted merges words in some cases - if ((name.charAt (0) == 'H') && (2 == name.length ()) && Character.isDigit (name.charAt (1))) - carriageReturn (); - } - - /** - * Unit test. - * @param args Pass arg[0] as the URL to process. - */ - public static void main (String[] args) - { - if (0 >= args.length) - System.out.println ("Usage: java -classpath htmlparser.jar" - + " org.htmlparser.beans.StringBean "); - else - { - StringBean sb = new StringBean (); - sb.setLinks (false); - sb.setReplaceNonBreakingSpaces (true); - sb.setCollapse (true); - sb.setURL (args[0]); - System.out.println (sb.getStrings ()); - } - } -} diff --git a/All/Genesis-OOB/Genesis#177/pair.info b/All/Genesis-OOB/Genesis#177/pair.info deleted file mode 100755 index 18d2b65..0000000 --- a/All/Genesis-OOB/Genesis#177/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:177 -SATName:Genesis -modifiedFPath:parser/src/main/java/org/htmlparser/beans/StringBean.java -comSha:04d381a -parentComSha:04d381a^1 -githubUrl:https://github.com/subbuss/htmlparser -repoName:subbuss#htmlparser \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#18/comMsg.txt b/All/Genesis-OOB/Genesis#18/comMsg.txt deleted file mode 100755 index 187428b..0000000 --- a/All/Genesis-OOB/Genesis#18/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Added negative id check to Material.getMaterial(int). Fixes BUKKIT-3414 Negative id values would try to access the array out of bounds and throw an java.lang.ArrayIndexOutOfBoundsException. diff --git a/All/Genesis-OOB/Genesis#18/diff.diff b/All/Genesis-OOB/Genesis#18/diff.diff deleted file mode 100755 index 033396f..0000000 --- a/All/Genesis-OOB/Genesis#18/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/src/main/java/org/bukkit/Material.java b/src/main/java/org/bukkit/Material.java -index 1a72610..7d26f61 100644 ---- a/src/main/java/org/bukkit/Material.java -+++ b/src/main/java/org/bukkit/Material.java -@@ -531 +531 @@ public enum Material { -- if (byId.length > id) { -+ if (byId.length > id && id >= 0) { diff --git a/All/Genesis-OOB/Genesis#18/new/Material.java b/All/Genesis-OOB/Genesis#18/new/Material.java deleted file mode 100755 index 7d26f61..0000000 --- a/All/Genesis-OOB/Genesis#18/new/Material.java +++ /dev/null @@ -1,918 +0,0 @@ -package org.bukkit; - -import java.lang.reflect.Constructor; -import java.util.Map; - -import org.apache.commons.lang.Validate; -import org.bukkit.map.MapView; -import org.bukkit.material.Bed; -import org.bukkit.material.Button; -import org.bukkit.material.Cake; -import org.bukkit.material.Cauldron; -import org.bukkit.material.Chest; -import org.bukkit.material.Coal; -import org.bukkit.material.CocoaPlant; -import org.bukkit.material.Command; -import org.bukkit.material.Crops; -import org.bukkit.material.DetectorRail; -import org.bukkit.material.Diode; -import org.bukkit.material.Dispenser; -import org.bukkit.material.Door; -import org.bukkit.material.Dye; -import org.bukkit.material.EnderChest; -import org.bukkit.material.FlowerPot; -import org.bukkit.material.Furnace; -import org.bukkit.material.Gate; -import org.bukkit.material.Ladder; -import org.bukkit.material.Lever; -import org.bukkit.material.LongGrass; -import org.bukkit.material.MaterialData; -import org.bukkit.material.MonsterEggs; -import org.bukkit.material.Mushroom; -import org.bukkit.material.PistonBaseMaterial; -import org.bukkit.material.PistonExtensionMaterial; -import org.bukkit.material.PoweredRail; -import org.bukkit.material.PressurePlate; -import org.bukkit.material.Pumpkin; -import org.bukkit.material.Rails; -import org.bukkit.material.RedstoneTorch; -import org.bukkit.material.RedstoneWire; -import org.bukkit.material.Sandstone; -import org.bukkit.material.Sign; -import org.bukkit.material.Skull; -import org.bukkit.material.SmoothBrick; -import org.bukkit.material.SpawnEgg; -import org.bukkit.material.Stairs; -import org.bukkit.material.Step; -import org.bukkit.material.Torch; -import org.bukkit.material.TrapDoor; -import org.bukkit.material.Tree; -import org.bukkit.material.Tripwire; -import org.bukkit.material.TripwireHook; -import org.bukkit.material.Vine; -import org.bukkit.material.WoodenStep; -import org.bukkit.material.Wool; -import org.bukkit.potion.Potion; -import org.bukkit.util.Java15Compat; - -import com.google.common.collect.Maps; - -/** - * An enum of all material ids accepted by the official server + client - */ -public enum Material { - AIR(0, 0), - STONE(1), - GRASS(2), - DIRT(3), - COBBLESTONE(4), - WOOD(5, Tree.class), - SAPLING(6, Tree.class), - BEDROCK(7), - WATER(8, MaterialData.class), - STATIONARY_WATER(9, MaterialData.class), - LAVA(10, MaterialData.class), - STATIONARY_LAVA(11, MaterialData.class), - SAND(12), - GRAVEL(13), - GOLD_ORE(14), - IRON_ORE(15), - COAL_ORE(16), - LOG(17, Tree.class), - LEAVES(18, Tree.class), - SPONGE(19), - GLASS(20), - LAPIS_ORE(21), - LAPIS_BLOCK(22), - DISPENSER(23, Dispenser.class), - SANDSTONE(24, Sandstone.class), - NOTE_BLOCK(25), - BED_BLOCK(26, Bed.class), - POWERED_RAIL(27, PoweredRail.class), - DETECTOR_RAIL(28, DetectorRail.class), - PISTON_STICKY_BASE(29, PistonBaseMaterial.class), - WEB(30), - LONG_GRASS(31, LongGrass.class), - DEAD_BUSH(32), - PISTON_BASE(33, PistonBaseMaterial.class), - PISTON_EXTENSION(34, PistonExtensionMaterial.class), - WOOL(35, Wool.class), - PISTON_MOVING_PIECE(36), - YELLOW_FLOWER(37), - RED_ROSE(38), - BROWN_MUSHROOM(39), - RED_MUSHROOM(40), - GOLD_BLOCK(41), - IRON_BLOCK(42), - DOUBLE_STEP(43, Step.class), - STEP(44, Step.class), - BRICK(45), - TNT(46), - BOOKSHELF(47), - MOSSY_COBBLESTONE(48), - OBSIDIAN(49), - TORCH(50, Torch.class), - FIRE(51), - MOB_SPAWNER(52), - WOOD_STAIRS(53, Stairs.class), - CHEST(54, Chest.class), - REDSTONE_WIRE(55, RedstoneWire.class), - DIAMOND_ORE(56), - DIAMOND_BLOCK(57), - WORKBENCH(58), - CROPS(59, Crops.class), - SOIL(60, MaterialData.class), - FURNACE(61, Furnace.class), - BURNING_FURNACE(62, Furnace.class), - SIGN_POST(63, 64, Sign.class), - WOODEN_DOOR(64, Door.class), - LADDER(65, Ladder.class), - RAILS(66, Rails.class), - COBBLESTONE_STAIRS(67, Stairs.class), - WALL_SIGN(68, 64, Sign.class), - LEVER(69, Lever.class), - STONE_PLATE(70, PressurePlate.class), - IRON_DOOR_BLOCK(71, Door.class), - WOOD_PLATE(72, PressurePlate.class), - REDSTONE_ORE(73), - GLOWING_REDSTONE_ORE(74), - REDSTONE_TORCH_OFF(75, RedstoneTorch.class), - REDSTONE_TORCH_ON(76, RedstoneTorch.class), - STONE_BUTTON(77, Button.class), - SNOW(78), - ICE(79), - SNOW_BLOCK(80), - CACTUS(81, MaterialData.class), - CLAY(82), - SUGAR_CANE_BLOCK(83, MaterialData.class), - JUKEBOX(84), - FENCE(85), - PUMPKIN(86, Pumpkin.class), - NETHERRACK(87), - SOUL_SAND(88), - GLOWSTONE(89), - PORTAL(90), - JACK_O_LANTERN(91, Pumpkin.class), - CAKE_BLOCK(92, 64, Cake.class), - DIODE_BLOCK_OFF(93, Diode.class), - DIODE_BLOCK_ON(94, Diode.class), - LOCKED_CHEST(95), - TRAP_DOOR(96, TrapDoor.class), - MONSTER_EGGS(97, MonsterEggs.class), - SMOOTH_BRICK(98, SmoothBrick.class), - HUGE_MUSHROOM_1(99, Mushroom.class), - HUGE_MUSHROOM_2(100, Mushroom.class), - IRON_FENCE(101), - THIN_GLASS(102), - MELON_BLOCK(103), - PUMPKIN_STEM(104, MaterialData.class), - MELON_STEM(105, MaterialData.class), - VINE(106, Vine.class), - FENCE_GATE(107, Gate.class), - BRICK_STAIRS(108, Stairs.class), - SMOOTH_STAIRS(109, Stairs.class), - MYCEL(110), - WATER_LILY(111), - NETHER_BRICK(112), - NETHER_FENCE(113), - NETHER_BRICK_STAIRS(114, Stairs.class), - NETHER_WARTS(115, MaterialData.class), - ENCHANTMENT_TABLE(116), - BREWING_STAND(117, MaterialData.class), - CAULDRON(118, Cauldron.class), - ENDER_PORTAL(119), - ENDER_PORTAL_FRAME(120), - ENDER_STONE(121), - DRAGON_EGG(122), - REDSTONE_LAMP_OFF(123), - REDSTONE_LAMP_ON(124), - WOOD_DOUBLE_STEP(125, WoodenStep.class), - WOOD_STEP(126, WoodenStep.class), - COCOA(127, CocoaPlant.class), - SANDSTONE_STAIRS(128, Stairs.class), - EMERALD_ORE(129), - ENDER_CHEST(130, EnderChest.class), - TRIPWIRE_HOOK(131, TripwireHook.class), - TRIPWIRE(132, Tripwire.class), - EMERALD_BLOCK(133), - SPRUCE_WOOD_STAIRS(134, Stairs.class), - BIRCH_WOOD_STAIRS(135, Stairs.class), - JUNGLE_WOOD_STAIRS(136, Stairs.class), - COMMAND(137, Command.class), - BEACON(138), - COBBLE_WALL(139), - FLOWER_POT(140, FlowerPot.class), - CARROT(141), - POTATO(142), - WOOD_BUTTON(143, Button.class), - SKULL(144, Skull.class), - ANVIL(145), - // ----- Item Separator ----- - IRON_SPADE(256, 1, 250), - IRON_PICKAXE(257, 1, 250), - IRON_AXE(258, 1, 250), - FLINT_AND_STEEL(259, 1, 64), - APPLE(260), - BOW(261, 1, 384), - ARROW(262), - COAL(263, Coal.class), - DIAMOND(264), - IRON_INGOT(265), - GOLD_INGOT(266), - IRON_SWORD(267, 1, 250), - WOOD_SWORD(268, 1, 59), - WOOD_SPADE(269, 1, 59), - WOOD_PICKAXE(270, 1, 59), - WOOD_AXE(271, 1, 59), - STONE_SWORD(272, 1, 131), - STONE_SPADE(273, 1, 131), - STONE_PICKAXE(274, 1, 131), - STONE_AXE(275, 1, 131), - DIAMOND_SWORD(276, 1, 1561), - DIAMOND_SPADE(277, 1, 1561), - DIAMOND_PICKAXE(278, 1, 1561), - DIAMOND_AXE(279, 1, 1561), - STICK(280), - BOWL(281), - MUSHROOM_SOUP(282, 1), - GOLD_SWORD(283, 1, 32), - GOLD_SPADE(284, 1, 32), - GOLD_PICKAXE(285, 1, 32), - GOLD_AXE(286, 1, 32), - STRING(287), - FEATHER(288), - SULPHUR(289), - WOOD_HOE(290, 1, 59), - STONE_HOE(291, 1, 131), - IRON_HOE(292, 1, 250), - DIAMOND_HOE(293, 1, 1561), - GOLD_HOE(294, 1, 32), - SEEDS(295), - WHEAT(296), - BREAD(297), - LEATHER_HELMET(298, 1, 55), - LEATHER_CHESTPLATE(299, 1, 80), - LEATHER_LEGGINGS(300, 1, 75), - LEATHER_BOOTS(301, 1, 65), - CHAINMAIL_HELMET(302, 1, 165), - CHAINMAIL_CHESTPLATE(303, 1, 240), - CHAINMAIL_LEGGINGS(304, 1, 225), - CHAINMAIL_BOOTS(305, 1, 195), - IRON_HELMET(306, 1, 165), - IRON_CHESTPLATE(307, 1, 240), - IRON_LEGGINGS(308, 1, 225), - IRON_BOOTS(309, 1, 195), - DIAMOND_HELMET(310, 1, 363), - DIAMOND_CHESTPLATE(311, 1, 528), - DIAMOND_LEGGINGS(312, 1, 495), - DIAMOND_BOOTS(313, 1, 429), - GOLD_HELMET(314, 1, 77), - GOLD_CHESTPLATE(315, 1, 112), - GOLD_LEGGINGS(316, 1, 105), - GOLD_BOOTS(317, 1, 91), - FLINT(318), - PORK(319), - GRILLED_PORK(320), - PAINTING(321), - GOLDEN_APPLE(322), - SIGN(323, 16), - WOOD_DOOR(324, 1), - BUCKET(325, 16), - WATER_BUCKET(326, 1), - LAVA_BUCKET(327, 1), - MINECART(328, 1), - SADDLE(329, 1), - IRON_DOOR(330, 1), - REDSTONE(331), - SNOW_BALL(332, 16), - BOAT(333, 1), - LEATHER(334), - MILK_BUCKET(335, 1), - CLAY_BRICK(336), - CLAY_BALL(337), - SUGAR_CANE(338), - PAPER(339), - BOOK(340), - SLIME_BALL(341), - STORAGE_MINECART(342, 1), - POWERED_MINECART(343, 1), - EGG(344, 16), - COMPASS(345), - FISHING_ROD(346, 1, 64), - WATCH(347), - GLOWSTONE_DUST(348), - RAW_FISH(349), - COOKED_FISH(350), - INK_SACK(351, Dye.class), - BONE(352), - SUGAR(353), - CAKE(354, 1), - BED(355, 1), - DIODE(356), - COOKIE(357), - /** - * @see MapView - */ - MAP(358, MaterialData.class), - SHEARS(359, 1, 238), - MELON(360), - PUMPKIN_SEEDS(361), - MELON_SEEDS(362), - RAW_BEEF(363), - COOKED_BEEF(364), - RAW_CHICKEN(365), - COOKED_CHICKEN(366), - ROTTEN_FLESH(367), - ENDER_PEARL(368, 16), - BLAZE_ROD(369), - GHAST_TEAR(370), - GOLD_NUGGET(371), - NETHER_STALK(372), - /** - * @see Potion - */ - POTION(373, 1, MaterialData.class), - GLASS_BOTTLE(374), - SPIDER_EYE(375), - FERMENTED_SPIDER_EYE(376), - BLAZE_POWDER(377), - MAGMA_CREAM(378), - BREWING_STAND_ITEM(379), - CAULDRON_ITEM(380), - EYE_OF_ENDER(381), - SPECKLED_MELON(382), - MONSTER_EGG(383, 64, SpawnEgg.class), - EXP_BOTTLE(384, 64), - FIREBALL(385, 64), - BOOK_AND_QUILL(386, 1), - WRITTEN_BOOK(387, 1), - EMERALD(388, 64), - ITEM_FRAME(389), - FLOWER_POT_ITEM(390), - CARROT_ITEM(391), - POTATO_ITEM(392), - BAKED_POTATO(393), - POISONOUS_POTATO(394), - EMPTY_MAP(395), - GOLDEN_CARROT(396), - SKULL_ITEM(397), - CARROT_STICK(398, 1, 25), - NETHER_STAR(399), - PUMPKIN_PIE(400), - FIREWORK(401), - FIREWORK_CHARGE(402), - ENCHANTED_BOOK(403, 1), - GOLD_RECORD(2256, 1), - GREEN_RECORD(2257, 1), - RECORD_3(2258, 1), - RECORD_4(2259, 1), - RECORD_5(2260, 1), - RECORD_6(2261, 1), - RECORD_7(2262, 1), - RECORD_8(2263, 1), - RECORD_9(2264, 1), - RECORD_10(2265, 1), - RECORD_11(2266, 1), - RECORD_12(2267, 1), - ; - - private final int id; - private final Constructor ctor; - private static Material[] byId = new Material[383]; - private final static Map BY_NAME = Maps.newHashMap(); - private final int maxStack; - private final short durability; - - private Material(final int id) { - this(id, 64); - } - - private Material(final int id, final int stack) { - this(id, stack, MaterialData.class); - } - - private Material(final int id, final int stack, final int durability) { - this(id, stack, durability, MaterialData.class); - } - - private Material(final int id, final Class data) { - this(id, 64, data); - } - - private Material(final int id, final int stack, final Class data) { - this(id, stack, 0, data); - } - - private Material(final int id, final int stack, final int durability, final Class data) { - this.id = id; - this.durability = (short) durability; - this.maxStack = stack; - // try to cache the constructor for this material - try { - this.ctor = data.getConstructor(int.class, byte.class); - } catch (NoSuchMethodException ex) { - throw new AssertionError(ex); - } catch (SecurityException ex) { - throw new AssertionError(ex); - } - } - - /** - * Gets the item ID or block ID of this Material - * - * @return ID of this material - */ - public int getId() { - return id; - } - - /** - * Gets the maximum amount of this material that can be held in a stack - * - * @return Maximum stack size for this material - */ - public int getMaxStackSize() { - return maxStack; - } - - /** - * Gets the maximum durability of this material - * - * @return Maximum durability for this material - */ - public short getMaxDurability() { - return durability; - } - - /** - * Gets the MaterialData class associated with this Material - * - * @return MaterialData associated with this Material - */ - public Class getData() { - return ctor.getDeclaringClass(); - } - - /** - * Constructs a new MaterialData relevant for this Material, with the given - * initial data - * - * @param raw Initial data to construct the MaterialData with - * @return New MaterialData with the given data - */ - public MaterialData getNewData(final byte raw) { - try { - return ctor.newInstance(id, raw); - } catch (InstantiationException ex) { - final Throwable t = ex.getCause(); - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } - if (t instanceof Error) { - throw (Error) t; - } - throw new AssertionError(t); - } catch (Throwable t) { - throw new AssertionError(t); - } - } - - /** - * Checks if this Material is a placable block - * - * @return true if this material is a block - */ - public boolean isBlock() { - return id < 256; - } - - /** - * Checks if this Material is edible. - * - * @return true if this Material is edible. - */ - public boolean isEdible() { - switch (this) { - case BREAD: - case CARROT_ITEM: - case BAKED_POTATO: - case POTATO_ITEM: - case POISONOUS_POTATO: - case GOLDEN_CARROT: - case PUMPKIN_PIE: - case COOKIE: - case MELON: - case MUSHROOM_SOUP: - case RAW_CHICKEN: - case COOKED_CHICKEN: - case RAW_BEEF: - case COOKED_BEEF: - case RAW_FISH: - case COOKED_FISH: - case PORK: - case GRILLED_PORK: - case APPLE: - case GOLDEN_APPLE: - case ROTTEN_FLESH: - case SPIDER_EYE: - return true; - default: - return false; - } - } - - /** - * Attempts to get the Material with the given ID - * - * @param id ID of the material to get - * @return Material if found, or null - */ - public static Material getMaterial(final int id) { - if (byId.length > id && id >= 0) { - return byId[id]; - } else { - return null; - } - } - - /** - * Attempts to get the Material with the given name. - * This is a normal lookup, names must be the precise name they are given - * in the enum. - * - * @param name Name of the material to get - * @return Material if found, or null - */ - public static Material getMaterial(final String name) { - return BY_NAME.get(name); - } - - /** - * Attempts to match the Material with the given name. - * This is a match lookup; names will be converted to uppercase, then stripped - * of special characters in an attempt to format it like the enum - * - * @param name Name of the material to get - * @return Material if found, or null - */ - public static Material matchMaterial(final String name) { - Validate.notNull(name, "Name cannot be null"); - - Material result = null; - - try { - result = getMaterial(Integer.parseInt(name)); - } catch (NumberFormatException ex) {} - - if (result == null) { - String filtered = name.toUpperCase(); - - filtered = filtered.replaceAll("\\s+", "_").replaceAll("\\W", ""); - result = BY_NAME.get(filtered); - } - - return result; - } - - static { - for (Material material : values()) { - if (byId.length > material.id) { - byId[material.id] = material; - } else { - byId = Java15Compat.Arrays_copyOfRange(byId, 0, material.id + 2); - byId[material.id] = material; - } - BY_NAME.put(material.name(), material); - } - } - - /** - * @return True if this material represents a playable music disk. - */ - public boolean isRecord() { - return id >= GOLD_RECORD.id && id <= RECORD_12.id; - } - - /** - * Check if the material is a block and solid (cannot be passed through by a player) - * - * @return True if this material is a block and solid - */ - public boolean isSolid() { - if (!isBlock() || id == 0) { - return false; - } - switch (this) { - case STONE: - case GRASS: - case DIRT: - case COBBLESTONE: - case WOOD: - case BEDROCK: - case SAND: - case GRAVEL: - case GOLD_ORE: - case IRON_ORE: - case COAL_ORE: - case LOG: - case LEAVES: - case SPONGE: - case GLASS: - case LAPIS_ORE: - case LAPIS_BLOCK: - case DISPENSER: - case SANDSTONE: - case NOTE_BLOCK: - case BED_BLOCK: - case PISTON_STICKY_BASE: - case PISTON_BASE: - case PISTON_EXTENSION: - case WOOL: - case PISTON_MOVING_PIECE: - case GOLD_BLOCK: - case IRON_BLOCK: - case DOUBLE_STEP: - case STEP: - case BRICK: - case TNT: - case BOOKSHELF: - case MOSSY_COBBLESTONE: - case OBSIDIAN: - case MOB_SPAWNER: - case WOOD_STAIRS: - case CHEST: - case DIAMOND_ORE: - case DIAMOND_BLOCK: - case WORKBENCH: - case SOIL: - case FURNACE: - case BURNING_FURNACE: - case SIGN_POST: - case WOODEN_DOOR: - case COBBLESTONE_STAIRS: - case WALL_SIGN: - case STONE_PLATE: - case IRON_DOOR_BLOCK: - case WOOD_PLATE: - case REDSTONE_ORE: - case GLOWING_REDSTONE_ORE: - case ICE: - case SNOW_BLOCK: - case CACTUS: - case CLAY: - case JUKEBOX: - case FENCE: - case PUMPKIN: - case NETHERRACK: - case SOUL_SAND: - case GLOWSTONE: - case JACK_O_LANTERN: - case CAKE_BLOCK: - case LOCKED_CHEST: - case TRAP_DOOR: - case MONSTER_EGGS: - case SMOOTH_BRICK: - case HUGE_MUSHROOM_1: - case HUGE_MUSHROOM_2: - case IRON_FENCE: - case THIN_GLASS: - case MELON_BLOCK: - case FENCE_GATE: - case BRICK_STAIRS: - case SMOOTH_STAIRS: - case MYCEL: - case NETHER_BRICK: - case NETHER_FENCE: - case NETHER_BRICK_STAIRS: - case ENCHANTMENT_TABLE: - case BREWING_STAND: - case CAULDRON: - case ENDER_PORTAL_FRAME: - case ENDER_STONE: - case DRAGON_EGG: - case REDSTONE_LAMP_OFF: - case REDSTONE_LAMP_ON: - case WOOD_DOUBLE_STEP: - case WOOD_STEP: - case SANDSTONE_STAIRS: - case EMERALD_ORE: - case ENDER_CHEST: - case EMERALD_BLOCK: - case SPRUCE_WOOD_STAIRS: - case BIRCH_WOOD_STAIRS: - case JUNGLE_WOOD_STAIRS: - case COMMAND: - case BEACON: - case COBBLE_WALL: - case ANVIL: - return true; - default: - return false; - } - } - - /** - * Check if the material is a block and does not block any light - * - * @return True if this material is a block and does not block any light - */ - public boolean isTransparent() { - if (!isBlock()) { - return false; - } - switch (this) { - case AIR: - case SAPLING: - case POWERED_RAIL: - case DETECTOR_RAIL: - case LONG_GRASS: - case DEAD_BUSH: - case YELLOW_FLOWER: - case RED_ROSE: - case BROWN_MUSHROOM: - case RED_MUSHROOM: - case TORCH: - case FIRE: - case REDSTONE_WIRE: - case CROPS: - case LADDER: - case RAILS: - case LEVER: - case REDSTONE_TORCH_OFF: - case REDSTONE_TORCH_ON: - case STONE_BUTTON: - case SNOW: - case SUGAR_CANE_BLOCK: - case PORTAL: - case DIODE_BLOCK_OFF: - case DIODE_BLOCK_ON: - case PUMPKIN_STEM: - case MELON_STEM: - case VINE: - case WATER_LILY: - case NETHER_WARTS: - case ENDER_PORTAL: - case COCOA: - case TRIPWIRE_HOOK: - case TRIPWIRE: - case FLOWER_POT: - case CARROT: - case POTATO: - case WOOD_BUTTON: - case SKULL: - return true; - default: - return false; - } - } - - /** - * Check if the material is a block and can catch fire - * - * @return True if this material is a block and can catch fire - */ - public boolean isFlammable() { - if (!isBlock()) { - return false; - } - switch (this) { - case WOOD: - case LOG: - case LEAVES: - case NOTE_BLOCK: - case BED_BLOCK: - case LONG_GRASS: - case DEAD_BUSH: - case WOOL: - case TNT: - case BOOKSHELF: - case WOOD_STAIRS: - case CHEST: - case WORKBENCH: - case SIGN_POST: - case WOODEN_DOOR: - case WALL_SIGN: - case WOOD_PLATE: - case JUKEBOX: - case FENCE: - case LOCKED_CHEST: - case TRAP_DOOR: - case HUGE_MUSHROOM_1: - case HUGE_MUSHROOM_2: - case VINE: - case FENCE_GATE: - case WOOD_DOUBLE_STEP: - case WOOD_STEP: - case SPRUCE_WOOD_STAIRS: - case BIRCH_WOOD_STAIRS: - case JUNGLE_WOOD_STAIRS: - return true; - default: - return false; - } - } - - /** - * Check if the material is a block and can burn away - * - * @return True if this material is a block and can burn away - */ - public boolean isBurnable() { - if (!isBlock()) { - return false; - } - switch (this) { - case WOOD: - case LOG: - case LEAVES: - case LONG_GRASS: - case WOOL: - case TNT: - case BOOKSHELF: - case WOOD_STAIRS: - case FENCE: - case VINE: - case WOOD_DOUBLE_STEP: - case WOOD_STEP: - case SPRUCE_WOOD_STAIRS: - case BIRCH_WOOD_STAIRS: - case JUNGLE_WOOD_STAIRS: - return true; - default: - return false; - } - } - - /** - * Check if the material is a block and completely blocks vision - * - * @return True if this material is a block and completely blocks vision - */ - public boolean isOccluding() { - if (!isBlock()) { - return false; - } - switch (this) { - case STONE: - case GRASS: - case DIRT: - case COBBLESTONE: - case WOOD: - case BEDROCK: - case SAND: - case GRAVEL: - case GOLD_ORE: - case IRON_ORE: - case COAL_ORE: - case LOG: - case SPONGE: - case LAPIS_ORE: - case LAPIS_BLOCK: - case DISPENSER: - case SANDSTONE: - case NOTE_BLOCK: - case WOOL: - case GOLD_BLOCK: - case IRON_BLOCK: - case DOUBLE_STEP: - case BRICK: - case BOOKSHELF: - case MOSSY_COBBLESTONE: - case OBSIDIAN: - case MOB_SPAWNER: - case DIAMOND_ORE: - case DIAMOND_BLOCK: - case WORKBENCH: - case FURNACE: - case BURNING_FURNACE: - case REDSTONE_ORE: - case GLOWING_REDSTONE_ORE: - case SNOW_BLOCK: - case CLAY: - case JUKEBOX: - case PUMPKIN: - case NETHERRACK: - case SOUL_SAND: - case JACK_O_LANTERN: - case LOCKED_CHEST: - case MONSTER_EGGS: - case SMOOTH_BRICK: - case HUGE_MUSHROOM_1: - case HUGE_MUSHROOM_2: - case MELON_BLOCK: - case MYCEL: - case NETHER_BRICK: - case ENDER_PORTAL_FRAME: - case ENDER_STONE: - case REDSTONE_LAMP_OFF: - case REDSTONE_LAMP_ON: - case WOOD_DOUBLE_STEP: - case EMERALD_ORE: - case EMERALD_BLOCK: - case COMMAND: - return true; - default: - return false; - } - } -} diff --git a/All/Genesis-OOB/Genesis#18/old/Material.java b/All/Genesis-OOB/Genesis#18/old/Material.java deleted file mode 100755 index 1a72610..0000000 --- a/All/Genesis-OOB/Genesis#18/old/Material.java +++ /dev/null @@ -1,918 +0,0 @@ -package org.bukkit; - -import java.lang.reflect.Constructor; -import java.util.Map; - -import org.apache.commons.lang.Validate; -import org.bukkit.map.MapView; -import org.bukkit.material.Bed; -import org.bukkit.material.Button; -import org.bukkit.material.Cake; -import org.bukkit.material.Cauldron; -import org.bukkit.material.Chest; -import org.bukkit.material.Coal; -import org.bukkit.material.CocoaPlant; -import org.bukkit.material.Command; -import org.bukkit.material.Crops; -import org.bukkit.material.DetectorRail; -import org.bukkit.material.Diode; -import org.bukkit.material.Dispenser; -import org.bukkit.material.Door; -import org.bukkit.material.Dye; -import org.bukkit.material.EnderChest; -import org.bukkit.material.FlowerPot; -import org.bukkit.material.Furnace; -import org.bukkit.material.Gate; -import org.bukkit.material.Ladder; -import org.bukkit.material.Lever; -import org.bukkit.material.LongGrass; -import org.bukkit.material.MaterialData; -import org.bukkit.material.MonsterEggs; -import org.bukkit.material.Mushroom; -import org.bukkit.material.PistonBaseMaterial; -import org.bukkit.material.PistonExtensionMaterial; -import org.bukkit.material.PoweredRail; -import org.bukkit.material.PressurePlate; -import org.bukkit.material.Pumpkin; -import org.bukkit.material.Rails; -import org.bukkit.material.RedstoneTorch; -import org.bukkit.material.RedstoneWire; -import org.bukkit.material.Sandstone; -import org.bukkit.material.Sign; -import org.bukkit.material.Skull; -import org.bukkit.material.SmoothBrick; -import org.bukkit.material.SpawnEgg; -import org.bukkit.material.Stairs; -import org.bukkit.material.Step; -import org.bukkit.material.Torch; -import org.bukkit.material.TrapDoor; -import org.bukkit.material.Tree; -import org.bukkit.material.Tripwire; -import org.bukkit.material.TripwireHook; -import org.bukkit.material.Vine; -import org.bukkit.material.WoodenStep; -import org.bukkit.material.Wool; -import org.bukkit.potion.Potion; -import org.bukkit.util.Java15Compat; - -import com.google.common.collect.Maps; - -/** - * An enum of all material ids accepted by the official server + client - */ -public enum Material { - AIR(0, 0), - STONE(1), - GRASS(2), - DIRT(3), - COBBLESTONE(4), - WOOD(5, Tree.class), - SAPLING(6, Tree.class), - BEDROCK(7), - WATER(8, MaterialData.class), - STATIONARY_WATER(9, MaterialData.class), - LAVA(10, MaterialData.class), - STATIONARY_LAVA(11, MaterialData.class), - SAND(12), - GRAVEL(13), - GOLD_ORE(14), - IRON_ORE(15), - COAL_ORE(16), - LOG(17, Tree.class), - LEAVES(18, Tree.class), - SPONGE(19), - GLASS(20), - LAPIS_ORE(21), - LAPIS_BLOCK(22), - DISPENSER(23, Dispenser.class), - SANDSTONE(24, Sandstone.class), - NOTE_BLOCK(25), - BED_BLOCK(26, Bed.class), - POWERED_RAIL(27, PoweredRail.class), - DETECTOR_RAIL(28, DetectorRail.class), - PISTON_STICKY_BASE(29, PistonBaseMaterial.class), - WEB(30), - LONG_GRASS(31, LongGrass.class), - DEAD_BUSH(32), - PISTON_BASE(33, PistonBaseMaterial.class), - PISTON_EXTENSION(34, PistonExtensionMaterial.class), - WOOL(35, Wool.class), - PISTON_MOVING_PIECE(36), - YELLOW_FLOWER(37), - RED_ROSE(38), - BROWN_MUSHROOM(39), - RED_MUSHROOM(40), - GOLD_BLOCK(41), - IRON_BLOCK(42), - DOUBLE_STEP(43, Step.class), - STEP(44, Step.class), - BRICK(45), - TNT(46), - BOOKSHELF(47), - MOSSY_COBBLESTONE(48), - OBSIDIAN(49), - TORCH(50, Torch.class), - FIRE(51), - MOB_SPAWNER(52), - WOOD_STAIRS(53, Stairs.class), - CHEST(54, Chest.class), - REDSTONE_WIRE(55, RedstoneWire.class), - DIAMOND_ORE(56), - DIAMOND_BLOCK(57), - WORKBENCH(58), - CROPS(59, Crops.class), - SOIL(60, MaterialData.class), - FURNACE(61, Furnace.class), - BURNING_FURNACE(62, Furnace.class), - SIGN_POST(63, 64, Sign.class), - WOODEN_DOOR(64, Door.class), - LADDER(65, Ladder.class), - RAILS(66, Rails.class), - COBBLESTONE_STAIRS(67, Stairs.class), - WALL_SIGN(68, 64, Sign.class), - LEVER(69, Lever.class), - STONE_PLATE(70, PressurePlate.class), - IRON_DOOR_BLOCK(71, Door.class), - WOOD_PLATE(72, PressurePlate.class), - REDSTONE_ORE(73), - GLOWING_REDSTONE_ORE(74), - REDSTONE_TORCH_OFF(75, RedstoneTorch.class), - REDSTONE_TORCH_ON(76, RedstoneTorch.class), - STONE_BUTTON(77, Button.class), - SNOW(78), - ICE(79), - SNOW_BLOCK(80), - CACTUS(81, MaterialData.class), - CLAY(82), - SUGAR_CANE_BLOCK(83, MaterialData.class), - JUKEBOX(84), - FENCE(85), - PUMPKIN(86, Pumpkin.class), - NETHERRACK(87), - SOUL_SAND(88), - GLOWSTONE(89), - PORTAL(90), - JACK_O_LANTERN(91, Pumpkin.class), - CAKE_BLOCK(92, 64, Cake.class), - DIODE_BLOCK_OFF(93, Diode.class), - DIODE_BLOCK_ON(94, Diode.class), - LOCKED_CHEST(95), - TRAP_DOOR(96, TrapDoor.class), - MONSTER_EGGS(97, MonsterEggs.class), - SMOOTH_BRICK(98, SmoothBrick.class), - HUGE_MUSHROOM_1(99, Mushroom.class), - HUGE_MUSHROOM_2(100, Mushroom.class), - IRON_FENCE(101), - THIN_GLASS(102), - MELON_BLOCK(103), - PUMPKIN_STEM(104, MaterialData.class), - MELON_STEM(105, MaterialData.class), - VINE(106, Vine.class), - FENCE_GATE(107, Gate.class), - BRICK_STAIRS(108, Stairs.class), - SMOOTH_STAIRS(109, Stairs.class), - MYCEL(110), - WATER_LILY(111), - NETHER_BRICK(112), - NETHER_FENCE(113), - NETHER_BRICK_STAIRS(114, Stairs.class), - NETHER_WARTS(115, MaterialData.class), - ENCHANTMENT_TABLE(116), - BREWING_STAND(117, MaterialData.class), - CAULDRON(118, Cauldron.class), - ENDER_PORTAL(119), - ENDER_PORTAL_FRAME(120), - ENDER_STONE(121), - DRAGON_EGG(122), - REDSTONE_LAMP_OFF(123), - REDSTONE_LAMP_ON(124), - WOOD_DOUBLE_STEP(125, WoodenStep.class), - WOOD_STEP(126, WoodenStep.class), - COCOA(127, CocoaPlant.class), - SANDSTONE_STAIRS(128, Stairs.class), - EMERALD_ORE(129), - ENDER_CHEST(130, EnderChest.class), - TRIPWIRE_HOOK(131, TripwireHook.class), - TRIPWIRE(132, Tripwire.class), - EMERALD_BLOCK(133), - SPRUCE_WOOD_STAIRS(134, Stairs.class), - BIRCH_WOOD_STAIRS(135, Stairs.class), - JUNGLE_WOOD_STAIRS(136, Stairs.class), - COMMAND(137, Command.class), - BEACON(138), - COBBLE_WALL(139), - FLOWER_POT(140, FlowerPot.class), - CARROT(141), - POTATO(142), - WOOD_BUTTON(143, Button.class), - SKULL(144, Skull.class), - ANVIL(145), - // ----- Item Separator ----- - IRON_SPADE(256, 1, 250), - IRON_PICKAXE(257, 1, 250), - IRON_AXE(258, 1, 250), - FLINT_AND_STEEL(259, 1, 64), - APPLE(260), - BOW(261, 1, 384), - ARROW(262), - COAL(263, Coal.class), - DIAMOND(264), - IRON_INGOT(265), - GOLD_INGOT(266), - IRON_SWORD(267, 1, 250), - WOOD_SWORD(268, 1, 59), - WOOD_SPADE(269, 1, 59), - WOOD_PICKAXE(270, 1, 59), - WOOD_AXE(271, 1, 59), - STONE_SWORD(272, 1, 131), - STONE_SPADE(273, 1, 131), - STONE_PICKAXE(274, 1, 131), - STONE_AXE(275, 1, 131), - DIAMOND_SWORD(276, 1, 1561), - DIAMOND_SPADE(277, 1, 1561), - DIAMOND_PICKAXE(278, 1, 1561), - DIAMOND_AXE(279, 1, 1561), - STICK(280), - BOWL(281), - MUSHROOM_SOUP(282, 1), - GOLD_SWORD(283, 1, 32), - GOLD_SPADE(284, 1, 32), - GOLD_PICKAXE(285, 1, 32), - GOLD_AXE(286, 1, 32), - STRING(287), - FEATHER(288), - SULPHUR(289), - WOOD_HOE(290, 1, 59), - STONE_HOE(291, 1, 131), - IRON_HOE(292, 1, 250), - DIAMOND_HOE(293, 1, 1561), - GOLD_HOE(294, 1, 32), - SEEDS(295), - WHEAT(296), - BREAD(297), - LEATHER_HELMET(298, 1, 55), - LEATHER_CHESTPLATE(299, 1, 80), - LEATHER_LEGGINGS(300, 1, 75), - LEATHER_BOOTS(301, 1, 65), - CHAINMAIL_HELMET(302, 1, 165), - CHAINMAIL_CHESTPLATE(303, 1, 240), - CHAINMAIL_LEGGINGS(304, 1, 225), - CHAINMAIL_BOOTS(305, 1, 195), - IRON_HELMET(306, 1, 165), - IRON_CHESTPLATE(307, 1, 240), - IRON_LEGGINGS(308, 1, 225), - IRON_BOOTS(309, 1, 195), - DIAMOND_HELMET(310, 1, 363), - DIAMOND_CHESTPLATE(311, 1, 528), - DIAMOND_LEGGINGS(312, 1, 495), - DIAMOND_BOOTS(313, 1, 429), - GOLD_HELMET(314, 1, 77), - GOLD_CHESTPLATE(315, 1, 112), - GOLD_LEGGINGS(316, 1, 105), - GOLD_BOOTS(317, 1, 91), - FLINT(318), - PORK(319), - GRILLED_PORK(320), - PAINTING(321), - GOLDEN_APPLE(322), - SIGN(323, 16), - WOOD_DOOR(324, 1), - BUCKET(325, 16), - WATER_BUCKET(326, 1), - LAVA_BUCKET(327, 1), - MINECART(328, 1), - SADDLE(329, 1), - IRON_DOOR(330, 1), - REDSTONE(331), - SNOW_BALL(332, 16), - BOAT(333, 1), - LEATHER(334), - MILK_BUCKET(335, 1), - CLAY_BRICK(336), - CLAY_BALL(337), - SUGAR_CANE(338), - PAPER(339), - BOOK(340), - SLIME_BALL(341), - STORAGE_MINECART(342, 1), - POWERED_MINECART(343, 1), - EGG(344, 16), - COMPASS(345), - FISHING_ROD(346, 1, 64), - WATCH(347), - GLOWSTONE_DUST(348), - RAW_FISH(349), - COOKED_FISH(350), - INK_SACK(351, Dye.class), - BONE(352), - SUGAR(353), - CAKE(354, 1), - BED(355, 1), - DIODE(356), - COOKIE(357), - /** - * @see MapView - */ - MAP(358, MaterialData.class), - SHEARS(359, 1, 238), - MELON(360), - PUMPKIN_SEEDS(361), - MELON_SEEDS(362), - RAW_BEEF(363), - COOKED_BEEF(364), - RAW_CHICKEN(365), - COOKED_CHICKEN(366), - ROTTEN_FLESH(367), - ENDER_PEARL(368, 16), - BLAZE_ROD(369), - GHAST_TEAR(370), - GOLD_NUGGET(371), - NETHER_STALK(372), - /** - * @see Potion - */ - POTION(373, 1, MaterialData.class), - GLASS_BOTTLE(374), - SPIDER_EYE(375), - FERMENTED_SPIDER_EYE(376), - BLAZE_POWDER(377), - MAGMA_CREAM(378), - BREWING_STAND_ITEM(379), - CAULDRON_ITEM(380), - EYE_OF_ENDER(381), - SPECKLED_MELON(382), - MONSTER_EGG(383, 64, SpawnEgg.class), - EXP_BOTTLE(384, 64), - FIREBALL(385, 64), - BOOK_AND_QUILL(386, 1), - WRITTEN_BOOK(387, 1), - EMERALD(388, 64), - ITEM_FRAME(389), - FLOWER_POT_ITEM(390), - CARROT_ITEM(391), - POTATO_ITEM(392), - BAKED_POTATO(393), - POISONOUS_POTATO(394), - EMPTY_MAP(395), - GOLDEN_CARROT(396), - SKULL_ITEM(397), - CARROT_STICK(398, 1, 25), - NETHER_STAR(399), - PUMPKIN_PIE(400), - FIREWORK(401), - FIREWORK_CHARGE(402), - ENCHANTED_BOOK(403, 1), - GOLD_RECORD(2256, 1), - GREEN_RECORD(2257, 1), - RECORD_3(2258, 1), - RECORD_4(2259, 1), - RECORD_5(2260, 1), - RECORD_6(2261, 1), - RECORD_7(2262, 1), - RECORD_8(2263, 1), - RECORD_9(2264, 1), - RECORD_10(2265, 1), - RECORD_11(2266, 1), - RECORD_12(2267, 1), - ; - - private final int id; - private final Constructor ctor; - private static Material[] byId = new Material[383]; - private final static Map BY_NAME = Maps.newHashMap(); - private final int maxStack; - private final short durability; - - private Material(final int id) { - this(id, 64); - } - - private Material(final int id, final int stack) { - this(id, stack, MaterialData.class); - } - - private Material(final int id, final int stack, final int durability) { - this(id, stack, durability, MaterialData.class); - } - - private Material(final int id, final Class data) { - this(id, 64, data); - } - - private Material(final int id, final int stack, final Class data) { - this(id, stack, 0, data); - } - - private Material(final int id, final int stack, final int durability, final Class data) { - this.id = id; - this.durability = (short) durability; - this.maxStack = stack; - // try to cache the constructor for this material - try { - this.ctor = data.getConstructor(int.class, byte.class); - } catch (NoSuchMethodException ex) { - throw new AssertionError(ex); - } catch (SecurityException ex) { - throw new AssertionError(ex); - } - } - - /** - * Gets the item ID or block ID of this Material - * - * @return ID of this material - */ - public int getId() { - return id; - } - - /** - * Gets the maximum amount of this material that can be held in a stack - * - * @return Maximum stack size for this material - */ - public int getMaxStackSize() { - return maxStack; - } - - /** - * Gets the maximum durability of this material - * - * @return Maximum durability for this material - */ - public short getMaxDurability() { - return durability; - } - - /** - * Gets the MaterialData class associated with this Material - * - * @return MaterialData associated with this Material - */ - public Class getData() { - return ctor.getDeclaringClass(); - } - - /** - * Constructs a new MaterialData relevant for this Material, with the given - * initial data - * - * @param raw Initial data to construct the MaterialData with - * @return New MaterialData with the given data - */ - public MaterialData getNewData(final byte raw) { - try { - return ctor.newInstance(id, raw); - } catch (InstantiationException ex) { - final Throwable t = ex.getCause(); - if (t instanceof RuntimeException) { - throw (RuntimeException) t; - } - if (t instanceof Error) { - throw (Error) t; - } - throw new AssertionError(t); - } catch (Throwable t) { - throw new AssertionError(t); - } - } - - /** - * Checks if this Material is a placable block - * - * @return true if this material is a block - */ - public boolean isBlock() { - return id < 256; - } - - /** - * Checks if this Material is edible. - * - * @return true if this Material is edible. - */ - public boolean isEdible() { - switch (this) { - case BREAD: - case CARROT_ITEM: - case BAKED_POTATO: - case POTATO_ITEM: - case POISONOUS_POTATO: - case GOLDEN_CARROT: - case PUMPKIN_PIE: - case COOKIE: - case MELON: - case MUSHROOM_SOUP: - case RAW_CHICKEN: - case COOKED_CHICKEN: - case RAW_BEEF: - case COOKED_BEEF: - case RAW_FISH: - case COOKED_FISH: - case PORK: - case GRILLED_PORK: - case APPLE: - case GOLDEN_APPLE: - case ROTTEN_FLESH: - case SPIDER_EYE: - return true; - default: - return false; - } - } - - /** - * Attempts to get the Material with the given ID - * - * @param id ID of the material to get - * @return Material if found, or null - */ - public static Material getMaterial(final int id) { - if (byId.length > id) { - return byId[id]; - } else { - return null; - } - } - - /** - * Attempts to get the Material with the given name. - * This is a normal lookup, names must be the precise name they are given - * in the enum. - * - * @param name Name of the material to get - * @return Material if found, or null - */ - public static Material getMaterial(final String name) { - return BY_NAME.get(name); - } - - /** - * Attempts to match the Material with the given name. - * This is a match lookup; names will be converted to uppercase, then stripped - * of special characters in an attempt to format it like the enum - * - * @param name Name of the material to get - * @return Material if found, or null - */ - public static Material matchMaterial(final String name) { - Validate.notNull(name, "Name cannot be null"); - - Material result = null; - - try { - result = getMaterial(Integer.parseInt(name)); - } catch (NumberFormatException ex) {} - - if (result == null) { - String filtered = name.toUpperCase(); - - filtered = filtered.replaceAll("\\s+", "_").replaceAll("\\W", ""); - result = BY_NAME.get(filtered); - } - - return result; - } - - static { - for (Material material : values()) { - if (byId.length > material.id) { - byId[material.id] = material; - } else { - byId = Java15Compat.Arrays_copyOfRange(byId, 0, material.id + 2); - byId[material.id] = material; - } - BY_NAME.put(material.name(), material); - } - } - - /** - * @return True if this material represents a playable music disk. - */ - public boolean isRecord() { - return id >= GOLD_RECORD.id && id <= RECORD_12.id; - } - - /** - * Check if the material is a block and solid (cannot be passed through by a player) - * - * @return True if this material is a block and solid - */ - public boolean isSolid() { - if (!isBlock() || id == 0) { - return false; - } - switch (this) { - case STONE: - case GRASS: - case DIRT: - case COBBLESTONE: - case WOOD: - case BEDROCK: - case SAND: - case GRAVEL: - case GOLD_ORE: - case IRON_ORE: - case COAL_ORE: - case LOG: - case LEAVES: - case SPONGE: - case GLASS: - case LAPIS_ORE: - case LAPIS_BLOCK: - case DISPENSER: - case SANDSTONE: - case NOTE_BLOCK: - case BED_BLOCK: - case PISTON_STICKY_BASE: - case PISTON_BASE: - case PISTON_EXTENSION: - case WOOL: - case PISTON_MOVING_PIECE: - case GOLD_BLOCK: - case IRON_BLOCK: - case DOUBLE_STEP: - case STEP: - case BRICK: - case TNT: - case BOOKSHELF: - case MOSSY_COBBLESTONE: - case OBSIDIAN: - case MOB_SPAWNER: - case WOOD_STAIRS: - case CHEST: - case DIAMOND_ORE: - case DIAMOND_BLOCK: - case WORKBENCH: - case SOIL: - case FURNACE: - case BURNING_FURNACE: - case SIGN_POST: - case WOODEN_DOOR: - case COBBLESTONE_STAIRS: - case WALL_SIGN: - case STONE_PLATE: - case IRON_DOOR_BLOCK: - case WOOD_PLATE: - case REDSTONE_ORE: - case GLOWING_REDSTONE_ORE: - case ICE: - case SNOW_BLOCK: - case CACTUS: - case CLAY: - case JUKEBOX: - case FENCE: - case PUMPKIN: - case NETHERRACK: - case SOUL_SAND: - case GLOWSTONE: - case JACK_O_LANTERN: - case CAKE_BLOCK: - case LOCKED_CHEST: - case TRAP_DOOR: - case MONSTER_EGGS: - case SMOOTH_BRICK: - case HUGE_MUSHROOM_1: - case HUGE_MUSHROOM_2: - case IRON_FENCE: - case THIN_GLASS: - case MELON_BLOCK: - case FENCE_GATE: - case BRICK_STAIRS: - case SMOOTH_STAIRS: - case MYCEL: - case NETHER_BRICK: - case NETHER_FENCE: - case NETHER_BRICK_STAIRS: - case ENCHANTMENT_TABLE: - case BREWING_STAND: - case CAULDRON: - case ENDER_PORTAL_FRAME: - case ENDER_STONE: - case DRAGON_EGG: - case REDSTONE_LAMP_OFF: - case REDSTONE_LAMP_ON: - case WOOD_DOUBLE_STEP: - case WOOD_STEP: - case SANDSTONE_STAIRS: - case EMERALD_ORE: - case ENDER_CHEST: - case EMERALD_BLOCK: - case SPRUCE_WOOD_STAIRS: - case BIRCH_WOOD_STAIRS: - case JUNGLE_WOOD_STAIRS: - case COMMAND: - case BEACON: - case COBBLE_WALL: - case ANVIL: - return true; - default: - return false; - } - } - - /** - * Check if the material is a block and does not block any light - * - * @return True if this material is a block and does not block any light - */ - public boolean isTransparent() { - if (!isBlock()) { - return false; - } - switch (this) { - case AIR: - case SAPLING: - case POWERED_RAIL: - case DETECTOR_RAIL: - case LONG_GRASS: - case DEAD_BUSH: - case YELLOW_FLOWER: - case RED_ROSE: - case BROWN_MUSHROOM: - case RED_MUSHROOM: - case TORCH: - case FIRE: - case REDSTONE_WIRE: - case CROPS: - case LADDER: - case RAILS: - case LEVER: - case REDSTONE_TORCH_OFF: - case REDSTONE_TORCH_ON: - case STONE_BUTTON: - case SNOW: - case SUGAR_CANE_BLOCK: - case PORTAL: - case DIODE_BLOCK_OFF: - case DIODE_BLOCK_ON: - case PUMPKIN_STEM: - case MELON_STEM: - case VINE: - case WATER_LILY: - case NETHER_WARTS: - case ENDER_PORTAL: - case COCOA: - case TRIPWIRE_HOOK: - case TRIPWIRE: - case FLOWER_POT: - case CARROT: - case POTATO: - case WOOD_BUTTON: - case SKULL: - return true; - default: - return false; - } - } - - /** - * Check if the material is a block and can catch fire - * - * @return True if this material is a block and can catch fire - */ - public boolean isFlammable() { - if (!isBlock()) { - return false; - } - switch (this) { - case WOOD: - case LOG: - case LEAVES: - case NOTE_BLOCK: - case BED_BLOCK: - case LONG_GRASS: - case DEAD_BUSH: - case WOOL: - case TNT: - case BOOKSHELF: - case WOOD_STAIRS: - case CHEST: - case WORKBENCH: - case SIGN_POST: - case WOODEN_DOOR: - case WALL_SIGN: - case WOOD_PLATE: - case JUKEBOX: - case FENCE: - case LOCKED_CHEST: - case TRAP_DOOR: - case HUGE_MUSHROOM_1: - case HUGE_MUSHROOM_2: - case VINE: - case FENCE_GATE: - case WOOD_DOUBLE_STEP: - case WOOD_STEP: - case SPRUCE_WOOD_STAIRS: - case BIRCH_WOOD_STAIRS: - case JUNGLE_WOOD_STAIRS: - return true; - default: - return false; - } - } - - /** - * Check if the material is a block and can burn away - * - * @return True if this material is a block and can burn away - */ - public boolean isBurnable() { - if (!isBlock()) { - return false; - } - switch (this) { - case WOOD: - case LOG: - case LEAVES: - case LONG_GRASS: - case WOOL: - case TNT: - case BOOKSHELF: - case WOOD_STAIRS: - case FENCE: - case VINE: - case WOOD_DOUBLE_STEP: - case WOOD_STEP: - case SPRUCE_WOOD_STAIRS: - case BIRCH_WOOD_STAIRS: - case JUNGLE_WOOD_STAIRS: - return true; - default: - return false; - } - } - - /** - * Check if the material is a block and completely blocks vision - * - * @return True if this material is a block and completely blocks vision - */ - public boolean isOccluding() { - if (!isBlock()) { - return false; - } - switch (this) { - case STONE: - case GRASS: - case DIRT: - case COBBLESTONE: - case WOOD: - case BEDROCK: - case SAND: - case GRAVEL: - case GOLD_ORE: - case IRON_ORE: - case COAL_ORE: - case LOG: - case SPONGE: - case LAPIS_ORE: - case LAPIS_BLOCK: - case DISPENSER: - case SANDSTONE: - case NOTE_BLOCK: - case WOOL: - case GOLD_BLOCK: - case IRON_BLOCK: - case DOUBLE_STEP: - case BRICK: - case BOOKSHELF: - case MOSSY_COBBLESTONE: - case OBSIDIAN: - case MOB_SPAWNER: - case DIAMOND_ORE: - case DIAMOND_BLOCK: - case WORKBENCH: - case FURNACE: - case BURNING_FURNACE: - case REDSTONE_ORE: - case GLOWING_REDSTONE_ORE: - case SNOW_BLOCK: - case CLAY: - case JUKEBOX: - case PUMPKIN: - case NETHERRACK: - case SOUL_SAND: - case JACK_O_LANTERN: - case LOCKED_CHEST: - case MONSTER_EGGS: - case SMOOTH_BRICK: - case HUGE_MUSHROOM_1: - case HUGE_MUSHROOM_2: - case MELON_BLOCK: - case MYCEL: - case NETHER_BRICK: - case ENDER_PORTAL_FRAME: - case ENDER_STONE: - case REDSTONE_LAMP_OFF: - case REDSTONE_LAMP_ON: - case WOOD_DOUBLE_STEP: - case EMERALD_ORE: - case EMERALD_BLOCK: - case COMMAND: - return true; - default: - return false; - } - } -} diff --git a/All/Genesis-OOB/Genesis#18/pair.info b/All/Genesis-OOB/Genesis#18/pair.info deleted file mode 100755 index a17df8c..0000000 --- a/All/Genesis-OOB/Genesis#18/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:18 -SATName:Genesis -modifiedFPath:src/main/java/org/bukkit/Material.java -comSha:a91c4c6f38224b07ca874ae42999d3b3d7ed63ce -parentComSha:a91c4c6f38224b07ca874ae42999d3b3d7ed63ce^1 -githubUrl:https://github.com/Bukkit/Bukkit -repoName:Bukkit#Bukkit \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#185/comMsg.txt b/All/Genesis-OOB/Genesis#185/comMsg.txt deleted file mode 100755 index 4004c6e..0000000 --- a/All/Genesis-OOB/Genesis#185/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fixed ArrayOutOfBounds exception in getParameterValuesForConstructor() diff --git a/All/Genesis-OOB/Genesis#185/diff.diff b/All/Genesis-OOB/Genesis#185/diff.diff deleted file mode 100755 index 9e415f3..0000000 --- a/All/Genesis-OOB/Genesis#185/diff.diff +++ /dev/null @@ -1,22 +0,0 @@ -diff --git a/src/main/java/uk/co/jemos/podam/api/PodamFactoryImpl.java b/src/main/java/uk/co/jemos/podam/api/PodamFactoryImpl.java -index 81d9aa5..1bde4f5 100644 ---- a/src/main/java/uk/co/jemos/podam/api/PodamFactoryImpl.java -+++ b/src/main/java/uk/co/jemos/podam/api/PodamFactoryImpl.java -@@ -2838,0 +2839 @@ public class PodamFactoryImpl implements PodamFactory { -+ Type[] genericTypes = constructor.getGenericParameterTypes(); -@@ -2841,2 +2842 @@ public class PodamFactoryImpl implements PodamFactory { -- int idx = 0; -- for (Class parameterType : parameterTypes) { -+ for (int idx = 0; idx < parameterTypes.length; idx++) { -@@ -2846 +2845,0 @@ public class PodamFactoryImpl implements PodamFactory { -- Type genericType = constructor.getGenericParameterTypes()[idx]; -@@ -2847,0 +2847,2 @@ public class PodamFactoryImpl implements PodamFactory { -+ Type genericType = (idx < genericTypes.length) ? -+ genericTypes[idx] : parameterTypes[idx]; -@@ -2849 +2850 @@ public class PodamFactoryImpl implements PodamFactory { -- parameterValues[idx] = manufactureParameterValue(parameterType, -+ parameterValues[idx] = manufactureParameterValue(parameterTypes[idx], -@@ -2852,3 +2852,0 @@ public class PodamFactoryImpl implements PodamFactory { -- -- idx++; -- diff --git a/All/Genesis-OOB/Genesis#185/new/PodamFactoryImpl.java b/All/Genesis-OOB/Genesis#185/new/PodamFactoryImpl.java deleted file mode 100755 index 1bde4f5..0000000 --- a/All/Genesis-OOB/Genesis#185/new/PodamFactoryImpl.java +++ /dev/null @@ -1,3097 +0,0 @@ -/** - * - */ -package uk.co.jemos.podam.api; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicReference; - -import net.jcip.annotations.Immutable; -import net.jcip.annotations.ThreadSafe; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import uk.co.jemos.podam.common.AttributeStrategy; -import uk.co.jemos.podam.common.ConstructorAdaptiveComparator; -import uk.co.jemos.podam.common.PodamBooleanValue; -import uk.co.jemos.podam.common.PodamByteValue; -import uk.co.jemos.podam.common.PodamCharValue; -import uk.co.jemos.podam.common.PodamCollection; -import uk.co.jemos.podam.common.PodamConstants; -import uk.co.jemos.podam.common.PodamConstructor; -import uk.co.jemos.podam.common.PodamDoubleValue; -import uk.co.jemos.podam.common.PodamFloatValue; -import uk.co.jemos.podam.common.PodamIntValue; -import uk.co.jemos.podam.common.PodamLongValue; -import uk.co.jemos.podam.common.PodamShortValue; -import uk.co.jemos.podam.common.PodamStrategyValue; -import uk.co.jemos.podam.common.PodamStringValue; -import uk.co.jemos.podam.exceptions.PodamMockeryException; - -/** - * The PODAM factory implementation - * - * @author mtedone - * - * @since 1.0.0 - * - */ -@ThreadSafe -@Immutable -public class PodamFactoryImpl implements PodamFactory { - - // ------------------->> Constants - - private static final String RESOLVING_COLLECTION_EXCEPTION_STR = "An exception occurred while resolving the collection"; - - private static final String MAP_CREATION_EXCEPTION_STR = "An exception occurred while creating a Map object"; - - private static final String UNCHECKED_STR = "unchecked"; - - private static final String THE_ANNOTATION_VALUE_STR = "The annotation value: "; - - private static final Type[] NO_TYPES = new Type[0]; - - /** Application logger */ - private static final Logger LOG = LoggerFactory - .getLogger(PodamFactoryImpl.class.getName()); - - // ------------------->> Instance / variables - - /** - * External factory to delegate production this factory cannot handle - *

- * The default is {@link LoggingExternalFactory}. - *

- */ - private final PodamFactory externalFactory; - - /** - * The strategy to use to fill data. - *

- * The default is {@link RandomDataProviderStrategy}. - *

- */ - private final DataProviderStrategy strategy; - - /** - * A map to keep one object for each class. If memoization is enabled, the - * factory will use this table to avoid creating objects of the same class - * multiple times. - */ - private Map, Object> memoizationTable = new HashMap, Object>(); - - // ------------------->> Constructors - - /** - * Default constructor. - */ - public PodamFactoryImpl() { - this(LoggingExternalFactory.getInstance(), - RandomDataProviderStrategy.getInstance()); - } - - /** - * Constructor with non-default strategy - * - * @param strategy - * The strategy to use to fill data - */ - public PodamFactoryImpl(DataProviderStrategy strategy) { - this(LoggingExternalFactory.getInstance(), strategy); - } - - /** - * Constructor with non-default external factory - * - * @param externalFactory - * External factory to delegate production this factory cannot - * handle - */ - public PodamFactoryImpl(PodamFactory externalFactory) { - this(externalFactory, RandomDataProviderStrategy.getInstance()); - } - - /** - * Full constructor. - * - * @param externalFactory - * External factory to delegate production this factory cannot - * handle - * @param strategy - * The strategy to use to fill data - */ - public PodamFactoryImpl(PodamFactory externalFactory, - DataProviderStrategy strategy) { - this.externalFactory = externalFactory; - this.strategy = strategy; - } - - // ------------------->> Public methods - - /** - * {@inheritDoc} - */ - @Override - public T manufacturePojo(Class pojoClass) { - return this.manufacturePojo(pojoClass, NO_TYPES); - } - - /** - * {@inheritDoc} - */ - @Override - public T manufacturePojoWithFullData(Class pojoClass, Type... genericTypeArgs) { - AbstractRandomDataProviderStrategy sortingStrategy; - if (getStrategy() instanceof AbstractRandomDataProviderStrategy) { - sortingStrategy = (AbstractRandomDataProviderStrategy) getStrategy(); - } else { - throw new IllegalStateException("manufacturePojoWithFullData can" - + " only be used with strategies derived from" - + " AbstractRandomDataProviderStrategy"); - } - ConstructorAdaptiveComparator constructorComparator; - if (sortingStrategy.getConstructorComparator() - instanceof ConstructorAdaptiveComparator) { - constructorComparator = (ConstructorAdaptiveComparator) - sortingStrategy.getConstructorComparator(); - } else { - throw new IllegalStateException("manufacturePojoWithFullData can" - + " only be used with constructor comparators derived from" - + " ConstructorAdaptiveComparator"); - } - constructorComparator.addHeavyClass(pojoClass); - T retValue = this.manufacturePojo(pojoClass, genericTypeArgs); - constructorComparator.removeHeavyClass(pojoClass); - return retValue; - } - - /** - * {@inheritDoc} - */ - @Override - public T manufacturePojo(Class pojoClass, Type... genericTypeArgs) { - Map, Integer> pojos = new HashMap, Integer>(); - pojos.put(pojoClass, 0); - try { - return this.manufacturePojoInternal(pojoClass, pojos, - genericTypeArgs); - } catch (InstantiationException e) { - throw new PodamMockeryException(e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new PodamMockeryException(e.getMessage(), e); - } catch (InvocationTargetException e) { - throw new PodamMockeryException(e.getMessage(), e); - } catch (ClassNotFoundException e) { - throw new PodamMockeryException(e.getMessage(), e); - } - } - - // ------------------->> Getters / Setters - - /** - * {@inheritDoc} - */ - - @Override - public DataProviderStrategy getStrategy() { - return strategy; - } - - // ------------------->> Private methods - - /** - * Fills type agruments map - *

- * This method places required and provided types for object creation into a - * map, which will be used for type mapping. - *

- * - * @param typeArgsMap - * a map to fill - * @param pojoClass - * Typed class - * @param genericTypeArgs - * Type arguments provided for a generics object by caller - * @return Array of unused provided generic type arguments - * @throws IllegalStateException - * If number of typed parameters doesn't match number of - * provided generic types - */ - private Type[] fillTypeArgMap(final Map typeArgsMap, - final Class pojoClass, final Type[] genericTypeArgs) { - - TypeVariable[] array = pojoClass.getTypeParameters(); - List> typeParameters = new ArrayList>(Arrays.asList(array)); - Iterator> iterator = typeParameters.iterator(); - /* Removing types, which are already in typeArgsMap */ - while (iterator.hasNext()) { - if (typeArgsMap.containsKey(iterator.next().getName())) { - iterator.remove(); - } - } - - if (typeParameters.size() > genericTypeArgs.length) { - String msg = pojoClass.getCanonicalName() - + " is missing generic type arguments, expected " - + typeParameters + " found " - + Arrays.toString(genericTypeArgs); - throw new IllegalStateException(msg); - } - - int i; - for (i = 0; i < typeParameters.size(); i++) { - typeArgsMap.put(typeParameters.get(i).getName(), genericTypeArgs[i]); - } - Type[] genericTypeArgsExtra; - if (typeParameters.size() < genericTypeArgs.length) { - genericTypeArgsExtra = Arrays.copyOfRange(genericTypeArgs, i, - genericTypeArgs.length); - } else { - genericTypeArgsExtra = null; - } - - /* Adding types, which were specified during inheritance */ - Class clazz = pojoClass; - while (clazz != null) { - Type superType = clazz.getGenericSuperclass(); - clazz = clazz.getSuperclass(); - if (superType instanceof ParameterizedType) { - ParameterizedType paramType = (ParameterizedType) superType; - Type[] actualParamTypes = paramType.getActualTypeArguments(); - TypeVariable[] paramTypes = clazz.getTypeParameters(); - for (i = 0; i < actualParamTypes.length - && i < paramTypes.length; i++) { - if (actualParamTypes[i] instanceof Class) { - typeArgsMap.put(paramTypes[i].getName(), - actualParamTypes[i]); - } - } - } - } - - return genericTypeArgsExtra; - } - - /** - * It attempts to create an instance of the given class - *

- * This method attempts to create an instance of the given argument for - * classes without setters. These may be either immutable classes (e.g. with - * final attributes and no setters) or Java classes (e.g. belonging to the - * java / javax namespace). In case the class does not provide a public, - * no-arg constructor (e.g. Calendar), this method attempts to find a , - * no-args, factory method (e.g. getInstance()) and it invokes it - *

- * - * @param pojoClass - * The name of the class for which an instance filled with values - * is required - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * - * - * @return An instance of the given class - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - private Object instantiatePojoWithoutConstructors( - Class pojoClass, Map, Integer> pojos, - Type... genericTypeArgs) throws InstantiationException, - IllegalAccessException, InvocationTargetException, - ClassNotFoundException { - - Object retValue = null; - - final Map typeArgsMap = new HashMap(); - Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, - pojoClass, genericTypeArgs); - - // If no publicly accessible constructors are available, - // the best we can do is to find a constructor (e.g. - // getInstance()) - - Method[] declaredMethods = pojoClass.getDeclaredMethods(); - strategy.sort(declaredMethods); - - // A candidate factory method is a method which returns the - // Class type - - // The parameters to pass to the method invocation - Object[] parameterValues = null; - Object[] noParams = new Object[] {}; - - for (Method candidateConstructor : declaredMethods) { - - if (!Modifier.isStatic(candidateConstructor.getModifiers()) - || !candidateConstructor.getReturnType().equals(pojoClass) - || retValue != null) { - continue; - } - - parameterValues = new Object[candidateConstructor - .getParameterTypes().length]; - - Class[] parameterTypes = candidateConstructor.getParameterTypes(); - - if (parameterTypes.length == 0) { - - parameterValues = noParams; - - } else { - - // This is a factory method with arguments - - Annotation[][] parameterAnnotations = candidateConstructor - .getParameterAnnotations(); - - int idx = 0; - - for (Class parameterType : parameterTypes) { - - List annotations = Arrays - .asList(parameterAnnotations[idx]); - Type genericType = candidateConstructor.getGenericParameterTypes()[idx]; - - parameterValues[idx] = manufactureParameterValue(parameterType, - genericType, annotations, typeArgsMap, pojos, - genericTypeArgsExtra == null ? NO_TYPES : genericTypeArgsExtra); - - idx++; - - } - - } - - try { - - retValue = candidateConstructor.invoke(pojoClass, - parameterValues); - LOG.debug("Could create an instance using " - + candidateConstructor); - - } catch (Exception t) { - - LOG.debug( - "PODAM could not create an instance for constructor: " - + candidateConstructor - + ". Will try another one...", t); - - } - - } - - if (retValue == null) { - retValue = externalFactory.manufacturePojo(pojoClass, genericTypeArgs); - } - if (retValue == null) { - LOG.warn("For class {} PODAM could not possibly create" - + " a value. It will be returned as null.", - pojoClass); - } - - return retValue; - - } - - /** - * It resolves generic parameter type - * - * - * @param paramType - * The generic parameter type - * @param typeArgsMap - * A map of resolved types - * @param methodGenericTypeArgs - * Return value posible generic types of the generic parameter - * type - * @return value for class representing the generic parameter type - */ - private Class resolveGenericParameter(Type paramType, - Map typeArgsMap, - AtomicReference methodGenericTypeArgs) { - - Class parameterType = null; - methodGenericTypeArgs.set(NO_TYPES); - if (paramType instanceof TypeVariable) { - final TypeVariable typeVariable = (TypeVariable) paramType; - final Type type = typeArgsMap.get(typeVariable.getName()); - if (type != null) { - parameterType = resolveGenericParameter(type, typeArgsMap, - methodGenericTypeArgs); - } - } else if (paramType instanceof ParameterizedType) { - ParameterizedType pType = (ParameterizedType) paramType; - parameterType = (Class) pType.getRawType(); - methodGenericTypeArgs.set(pType.getActualTypeArguments()); - } else if (paramType instanceof WildcardType) { - WildcardType wType = (WildcardType) paramType; - Type[] bounds = wType.getLowerBounds(); - String msg; - if (bounds != null && bounds.length > 0) { - msg = "Lower bounds:"; - } else { - bounds = wType.getUpperBounds(); - msg = "Upper bounds:"; - } - if (bounds != null && bounds.length > 0) { - LOG.debug(msg + Arrays.toString(bounds)); - parameterType = resolveGenericParameter(bounds[0], typeArgsMap, - methodGenericTypeArgs); - } - } else if (paramType instanceof Class) { - parameterType = (Class) paramType; - } - - if (parameterType == null) { - LOG.warn("Unrecognized type {}. Will use Object instead", - paramType); - parameterType = Object.class; - } - return parameterType; - } - - /** - * It resolves and returns the primitive value depending on the type - * - * - * @param primitiveClass - * The primitive type class - * @param annotations - * The annotations to consider for this attribute - * @param attributeMetadata - * @return the primitive value depending on the type - * - * @throws IllegalArgumentException - * If a specific value was set in an annotation but it was not - * possible to convert such value in the desired type - */ - private Object resolvePrimitiveValue(Class primitiveClass, - List annotations, AttributeMetadata attributeMetadata) { - - Object retValue = null; - - if (primitiveClass.equals(int.class)) { - - if (!annotations.isEmpty()) { - - retValue = getIntegerValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getInteger(attributeMetadata); - } - - } else if (primitiveClass.equals(long.class)) { - - if (!annotations.isEmpty()) { - - retValue = getLongValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getLong(attributeMetadata); - } - - } else if (primitiveClass.equals(float.class)) { - - if (!annotations.isEmpty()) { - - retValue = getFloatValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getFloat(attributeMetadata); - } - - } else if (primitiveClass.equals(double.class)) { - - if (!annotations.isEmpty()) { - - retValue = getDoubleValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getDouble(attributeMetadata); - } - - } else if (primitiveClass.equals(boolean.class)) { - - if (!annotations.isEmpty()) { - - retValue = getBooleanValueForAnnotation(annotations); - - } - - if (retValue == null) { - retValue = strategy.getBoolean(attributeMetadata); - } - - } else if (primitiveClass.equals(byte.class)) { - - if (!annotations.isEmpty()) { - - retValue = getByteValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getByte(attributeMetadata); - } - - } else if (primitiveClass.equals(short.class)) { - - if (!annotations.isEmpty()) { - - retValue = getShortValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getShort(attributeMetadata); - } - - } else if (primitiveClass.equals(char.class)) { - - if (!annotations.isEmpty()) { - - retValue = getCharacterValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getCharacter(attributeMetadata); - } - - } else { - - throw new IllegalArgumentException( - String.format("%s is unsupported primitive type", - primitiveClass)); - } - - return retValue; - } - - /** - * It returns the boolean value indicated in the annotation. - * - * @param annotations - * The collection of annotations for the annotated attribute - * @return The boolean value indicated in the annotation - */ - private Boolean getBooleanValueForAnnotation(List annotations) { - - Boolean retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamBooleanValue.class.isAssignableFrom(annotation.getClass())) { - PodamBooleanValue localStrategy = (PodamBooleanValue) annotation; - retValue = localStrategy.boolValue(); - - break; - } - - } - - return retValue; - } - - /** - * It returns a random byte if the attribute was annotated with - * {@link PodamByteValue} or {@code null} otherwise - * - * @param annotations - * The list of annotations for this attribute - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return A random byte if the attribute was annotated with - * - * @throws IllegalArgumentException - * If the {@link PodamByteValue#numValue()} value has been set - * and it is not convertible to a byte type - */ - private Byte getByteValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - Byte retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamByteValue.class.isAssignableFrom(annotation.getClass())) { - PodamByteValue intStrategy = (PodamByteValue) annotation; - - String numValueStr = intStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - - retValue = Byte.valueOf(numValueStr); - - } catch (NumberFormatException nfe) { - String errMsg = "The precise value: " - + numValueStr - + " cannot be converted to a byte type. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - } else { - byte minValue = intStrategy.minValue(); - byte maxValue = intStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getByteInRange(minValue, maxValue, - attributeMetadata); - } - - break; - - } - - } - return retValue; - } - - /** - * It returns a random short if the attribute was annotated with - * {@link PodamShortValue} or {@code null} otherwise - * - * @param annotations - * The annotations with which the attribute was annotated - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return A random short if the attribute was annotated with - * {@link PodamShortValue} or {@code null} otherwise - * - * @throws IllegalArgumentException - * If {@link PodamShortValue#numValue()} was set and its value - * could not be converted to a Short type - */ - private Short getShortValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Short retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamShortValue.class.isAssignableFrom(annotation.getClass())) { - PodamShortValue shortStrategy = (PodamShortValue) annotation; - - String numValueStr = shortStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - retValue = Short.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = "The precise value: " - + numValueStr - + " cannot be converted to a short type. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - } else { - - short minValue = shortStrategy.minValue(); - short maxValue = shortStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getShortInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * It creates and returns a random {@link Character} value - * - * @param annotations - * The list of annotations which might customise the return value - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return A random {@link Character} value - */ - private Character getCharacterValueWithinRange( - List annotations, AttributeMetadata attributeMetadata) { - - Character retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamCharValue.class.isAssignableFrom(annotation.getClass())) { - PodamCharValue annotationStrategy = (PodamCharValue) annotation; - - char charValue = annotationStrategy.charValue(); - if (charValue != ' ') { - retValue = charValue; - - } else { - - char minValue = annotationStrategy.minValue(); - char maxValue = annotationStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getCharacterInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * Returns either a customised int value if a {@link PodamIntValue} - * annotation was provided or a random integer if this was not the case - * - * @param annotations - * The list of annotations for the int attribute - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return Either a customised int value if a {@link PodamIntValue} - * annotation was provided or a random integer if this was not the - * case - * - * @throws IllegalArgumentException - * If it was not possible to convert the - * {@link PodamIntValue#numValue()} to an Integer - */ - private Integer getIntegerValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Integer retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamIntValue.class.isAssignableFrom(annotation.getClass())) { - PodamIntValue intStrategy = (PodamIntValue) annotation; - - String numValueStr = intStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - retValue = Integer.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = THE_ANNOTATION_VALUE_STR - + numValueStr - + " could not be converted to an Integer. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - - } - - } else { - - int minValue = intStrategy.minValue(); - int maxValue = intStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getIntegerInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * Returns either a customised float value if a {@link PodamFloatValue} - * annotation was provided or a random float if this was not the case - * - * @param annotations - * The list of annotations for the int attribute - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * - * @return Either a customised float value if a {@link PodamFloatValue} - * annotation was provided or a random float if this was not the - * case - * - * @throws IllegalArgumentException - * If {@link PodamFloatValue#numValue()} contained a value not - * convertible to a Float type - */ - private Float getFloatValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Float retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamFloatValue.class.isAssignableFrom(annotation.getClass())) { - PodamFloatValue floatStrategy = (PodamFloatValue) annotation; - - String numValueStr = floatStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - retValue = Float.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = THE_ANNOTATION_VALUE_STR - + numValueStr - + " could not be converted to a Float. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - } else { - - float minValue = floatStrategy.minValue(); - float maxValue = floatStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getFloatInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * It creates and returns a random {@link Double} value - * - * @param annotations - * The list of annotations which might customise the return value - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation * - * - * @return a random {@link Double} value - */ - private Double getDoubleValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Double retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamDoubleValue.class.isAssignableFrom(annotation.getClass())) { - PodamDoubleValue doubleStrategy = (PodamDoubleValue) annotation; - - String numValueStr = doubleStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - - try { - retValue = Double.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = THE_ANNOTATION_VALUE_STR - + numValueStr - + " could not be converted to a Double. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - - } else { - - double minValue = doubleStrategy.minValue(); - double maxValue = doubleStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getDoubleInRange(minValue, maxValue, - attributeMetadata); - } - - break; - - } - - } - return retValue; - - } - - /** - * Returns either a customised long value if a {@link PodamLongValue} - * annotation was provided or a random long if this was not the case - * - * @param annotations - * The list of annotations for the int attribute - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return Either a customised long value if a {@link PodamLongValue} - * annotation was provided or a random long if this was not the case - * - * @throws IllegalArgumentException - * If it was not possible to convert - * {@link PodamLongValue#numValue()} to a Long - */ - private Long getLongValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Long retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamLongValue.class.isAssignableFrom(annotation.getClass())) { - PodamLongValue longStrategy = (PodamLongValue) annotation; - - String numValueStr = longStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - retValue = Long.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = THE_ANNOTATION_VALUE_STR - + numValueStr - + " could not be converted to a Long. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - } else { - - long minValue = longStrategy.minValue(); - long maxValue = longStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getLongInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * It attempts to resolve the given class as a wrapper class and if this is - * the case it assigns a random value - * - * - * @param candidateWrapperClass - * The class which might be a wrapper class - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * @return {@code null} if this is not a wrapper class, otherwise an Object - * with the value for the wrapper class - */ - private Object resolveWrapperValue(Class candidateWrapperClass, - List annotations, AttributeMetadata attributeMetadata) { - - Object retValue = null; - - if (candidateWrapperClass.equals(Integer.class)) { - - if (!annotations.isEmpty()) { - - retValue = getIntegerValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getInteger(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Long.class)) { - - if (!annotations.isEmpty()) { - - retValue = getLongValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getLong(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Float.class)) { - - if (!annotations.isEmpty()) { - - retValue = getFloatValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getFloat(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Double.class)) { - - if (!annotations.isEmpty()) { - - retValue = getDoubleValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getDouble(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Boolean.class)) { - - if (!annotations.isEmpty()) { - - retValue = getBooleanValueForAnnotation(annotations); - - } - - if (retValue == null) { - retValue = strategy.getBoolean(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Byte.class)) { - - if (!annotations.isEmpty()) { - - retValue = getByteValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getByte(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Short.class)) { - - if (!annotations.isEmpty()) { - - retValue = getShortValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getShort(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Character.class)) { - - if (!annotations.isEmpty()) { - - retValue = getCharacterValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getCharacter(attributeMetadata); - } - - } - - return retValue; - } - - /** - * It creates and returns an instance of the given class if at least one of - * its constructors has been annotated with {@link PodamConstructor} - * - * @param - * The type of the instance to return - * - * @param pojoClass - * The class of which an instance is required - * @param pojos - * How many instances of the same class have been created so far - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return an instance of the given class if at least one of its - * constructors has been annotated with {@link PodamConstructor} - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - @SuppressWarnings({ UNCHECKED_STR }) - private T instantiatePojo(Class pojoClass, - Map, Integer> pojos, Type... genericTypeArgs) - throws SecurityException { - - T retValue = null; - - Constructor[] constructors = pojoClass.getConstructors(); - if (constructors.length == 0 || Modifier.isAbstract(pojoClass.getModifiers())) { - /* No public constructors, we will try static factory methods */ - try { - retValue = (T) instantiatePojoWithoutConstructors( - pojoClass, pojos, genericTypeArgs); - } catch (Exception e) { - LOG.debug("We couldn't create an instance for pojo: " - + pojoClass + " with factory methods, will " - + " try non-public constructors.", e); - } - - /* Then non-public constructors */ - if (retValue == null) { - constructors = pojoClass.getDeclaredConstructors(); - } - } - - if (retValue == null && constructors.length > 0) { - - /* We want constructor with minumum number of parameters - * to speed up the creation */ - strategy.sort(constructors); - - for (Constructor constructor : constructors) { - - try { - Object[] parameterValues = getParameterValuesForConstructor( - constructor, pojoClass, pojos, genericTypeArgs); - - // Being a generic method we cannot be sure on the identity of - // T, therefore the mismatch between the newInstance() return - // value (Object) and T is acceptable, thus the SuppressWarning - // annotation - - // Security hack - if (!constructor.isAccessible()) { - constructor.setAccessible(true); - } - retValue = (T) constructor.newInstance(parameterValues); - if (retValue != null) { - LOG.debug("We could create an instance with constructor: " - + constructor); - break; - } - } catch (Exception e) { - LOG.debug("We couldn't create an instance for pojo: {} with" - + " constructor: {}. Will try with another one.", - pojoClass, constructor, e); - } - } - } - - if (retValue == null) { - retValue = externalFactory.manufacturePojo(pojoClass, genericTypeArgs); - } - return retValue; - } - - /** - * Generic method which returns an instance of the given class filled with - * values dictated by the strategy - * - * @param - * The type for which a filled instance is required - * - * @param pojoClass - * The name of the class for which an instance filled with values - * is required - * @param pojos - * How many times {@code pojoClass} has been found. This will be - * used for reentrant objects - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return An instance of filled with dummy values - * @throws ClassNotFoundException - * @throws InvocationTargetException - * @throws IllegalAccessException - * @throws InstantiationException - * - * @throws PodamMockeryException - * if a problem occurred while creating a POJO instance or while - * setting its state - */ - @SuppressWarnings(UNCHECKED_STR) - private T manufacturePojoInternal(Class pojoClass, - Map, Integer> pojos, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - LOG.debug("Manufacturing {} with parameters {}", - pojoClass, Arrays.toString(genericTypeArgs)); - - T retValue = null; - - // reuse object from memoization table - if (strategy.isMemoizationEnabled()) { - T objectToReuse = (T) memoizationTable.get(pojoClass); - if (objectToReuse != null) { - return objectToReuse; - } - } - - if (pojoClass.isPrimitive()) { - // For JDK POJOs we can't retrieve attribute name - List annotations = new ArrayList(); - String noName = null; - return (T) resolvePrimitiveValue(pojoClass, annotations, - new AttributeMetadata(noName, pojoClass, annotations, pojoClass)); - } - - if (pojoClass.isInterface() - || Modifier.isAbstract(pojoClass.getModifiers())) { - Class specificClass = (Class) strategy - .getSpecificClass(pojoClass); - if (!specificClass.equals(pojoClass)) { - return this.manufacturePojoInternal(specificClass, pojos, - genericTypeArgs); - } else { - if (specificClass.isInterface()) { - return externalFactory.manufacturePojo(pojoClass, - genericTypeArgs); - } - } - } - - try { - - retValue = instantiatePojo(pojoClass, pojos, genericTypeArgs); - } catch (SecurityException e) { - throw new PodamMockeryException( - "Security exception while applying introspection.", e); - } - - // update memoization table with new object - // the reference is stored before properties are set so that recursive - // properties can use it - if (strategy.isMemoizationEnabled()) { - memoizationTable.put(pojoClass, retValue); - } - - /* Construction failed, no point to continue */ - if (retValue == null) { - return null; - } - - if (retValue instanceof Collection && ((Collection)retValue).size() == 0) { - fillCollection((Collection)retValue, pojos, genericTypeArgs); - } else if (retValue instanceof Map && ((Map)retValue).size() == 0) { - fillMap((Map)retValue, pojos, genericTypeArgs); - } - - Class[] parameterTypes = null; - Class attributeType = null; - - ClassInfo classInfo = PodamUtils.getClassInfo(pojoClass, - strategy.getExcludedAnnotations()); - - // According to JavaBeans standards, setters should have only - // one argument - Object setterArg = null; - for (Method setter : classInfo.getClassSetters()) { - - List pojoAttributeAnnotations = retrieveFieldAnnotations( - pojoClass, setter); - - String attributeName = PodamUtils - .extractFieldNameFromSetterMethod(setter); - - parameterTypes = setter.getParameterTypes(); - if (parameterTypes.length != 1) { - LOG.warn("Skipping setter with non-single arguments {}", - setter); - continue; - } - - // A class which has got an attribute to itself (e.g. - // recursive hierarchies) - attributeType = parameterTypes[0]; - - // If an attribute has been annotated with - // PodamAttributeStrategy, it takes the precedence over any - // other strategy. Additionally we don't pass the attribute - // metadata for value customisation; if user went to the extent - // of specifying a PodamAttributeStrategy annotation for an - // attribute they are already customising the value assigned to - // that attribute. - - PodamStrategyValue attributeStrategyAnnotation = containsAttributeStrategyAnnotation(pojoAttributeAnnotations); - if (null != attributeStrategyAnnotation) { - - AttributeStrategy attributeStrategy = attributeStrategyAnnotation - .value().newInstance(); - - if (LOG.isDebugEnabled()) { - LOG.debug("The attribute: " + attributeName - + " will be filled using the following strategy: " - + attributeStrategy); - } - - setterArg = returnAttributeDataStrategyValue(attributeType, - attributeStrategy); - - } else { - - final Map typeArgsMap = new HashMap(); - - Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, - pojoClass, genericTypeArgs); - if (genericTypeArgsExtra != null) { - LOG.warn("Lost generic type arguments {}", - Arrays.toString(genericTypeArgsExtra)); - } - - Type[] typeArguments = NO_TYPES; - // If the parameter is a generic parameterized type resolve - // the actual type arguments - if (setter.getGenericParameterTypes()[0] instanceof ParameterizedType) { - final ParameterizedType attributeParameterizedType = (ParameterizedType) setter - .getGenericParameterTypes()[0]; - typeArguments = attributeParameterizedType - .getActualTypeArguments(); - } else if (setter.getGenericParameterTypes()[0] instanceof TypeVariable) { - final TypeVariable typeVariable = (TypeVariable) setter - .getGenericParameterTypes()[0]; - Type type = typeArgsMap.get(typeVariable.getName()); - if (type instanceof ParameterizedType) { - final ParameterizedType attributeParameterizedType = (ParameterizedType) type; - - typeArguments = attributeParameterizedType - .getActualTypeArguments(); - attributeType = (Class) attributeParameterizedType - .getRawType(); - } else { - attributeType = (Class) type; - } - } - AtomicReference typeGenericTypeArgs - = new AtomicReference(NO_TYPES); - for (int i = 0; i < typeArguments.length; i++) { - if (typeArguments[i] instanceof TypeVariable) { - Class resolvedType = resolveGenericParameter(typeArguments[i], - typeArgsMap, typeGenericTypeArgs); - if (!Collection.class.isAssignableFrom(resolvedType) && !Map.class.isAssignableFrom(resolvedType)) { - typeArguments[i] = resolvedType; - } - } - } - - setterArg = manufactureAttributeValue(retValue, pojos, - attributeType, setter.getGenericParameterTypes()[0], - pojoAttributeAnnotations, attributeName, - typeArgsMap, typeArguments); - if (null == setterArg) { - setterArg = externalFactory.manufacturePojo(attributeType); - } - } - - if (setterArg != null) { - try { - setter.invoke(retValue, setterArg); - } catch(IllegalAccessException e) { - LOG.warn("{} is not accessible. Setting it to accessible." - + " However this is a security hack and your code" - + " should really adhere to JavaBeans standards.", - setter.toString()); - setter.setAccessible(true); - setter.invoke(retValue, setterArg); - } - } else { - LOG.warn("Couldn't find a suitable value for attribute {}[{}]" - + ". It will be left to null.", - pojoClass, attributeType); - } - - } - - return retValue; - - } - - /** - * It manufactures and returns the value for a POJO method parameter. - * - * - * @param pojos - * Set of manufactured pojos' types - * @param parameterType - * The type of the attribute for which a value is being - * manufactured - * @param genericType - * The generic type of the attribute for which a value is being - * manufactured - * @param annotations - * The annotations for the attribute being considered - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return The value for a parameter - * - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * @throws IllegalArgumentException - *
    - *
  • If an illegal argument was passed
  • - *
  • If an invalid value was set for a precise value in an - * annotation and such value could not be converted to the - * desired type
  • - *
- * - */ - private Object manufactureParameterValue(Map, Integer> pojos, - Class parameterType, Type genericType, - List annotations, Map typeArgsMap, - Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - String attributeName = null; - - return manufactureAttributeValue(Object.class, pojos, parameterType, - genericType, annotations, attributeName, typeArgsMap, - genericTypeArgs); - } - - /** - * It manufactures and returns the value for a POJO attribute. - * - * - * @param pojo - * The POJO being filled with values - * @param pojos - * Set of manufactured pojos' types - * @param attributeType - * The type of the attribute for which a value is being - * manufactured - * @param genericAttributeType - * The generic type of the attribute for which a value is being - * manufactured - * @param annotations - * The annotations for the attribute being considered - * @param attributeName - * The attribute name - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return The value for an attribute - * - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * @throws IllegalArgumentException - *
    - *
  • If an illegal argument was passed
  • - *
  • If an invalid value was set for a precise value in an - * annotation and such value could not be converted to the - * desired type
  • - *
- * - */ - private Object manufactureAttributeValue(Object pojo, - Map, Integer> pojos, Class attributeType, - Type genericAttributeType, List annotations, - String attributeName, Map typeArgsMap, - Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - Object attributeValue = null; - - Class realAttributeType; - if (Object.class.equals(attributeType) && attributeType != genericAttributeType) { - AtomicReference elementGenericTypeArgs - = new AtomicReference(NO_TYPES); - realAttributeType = resolveGenericParameter(genericAttributeType, - typeArgsMap, elementGenericTypeArgs); - } else { - realAttributeType = attributeType; - } - AttributeMetadata attributeMetadata = new AttributeMetadata( - attributeName, realAttributeType, annotations, pojo.getClass()); - - // Primitive type - if (realAttributeType.isPrimitive()) { - - attributeValue = resolvePrimitiveValue(realAttributeType, - annotations, attributeMetadata); - - // Wrapper type - } else if (isWrapper(realAttributeType)) { - - attributeValue = resolveWrapperValue(realAttributeType, - annotations, attributeMetadata); - - // String type - } else if (realAttributeType.equals(String.class)) { - - attributeValue = resolveStringValue(annotations, attributeMetadata); - - } else if (realAttributeType.isArray()) { - - // Array type - - attributeValue = resolveArrayElementValue(realAttributeType, - genericAttributeType, pojos, annotations, pojo, - attributeName, typeArgsMap); - - // Otherwise it's a different type of Object (including - // the Object class) - } else if (Collection.class.isAssignableFrom(realAttributeType)) { - - attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute( - pojo, pojos, realAttributeType, attributeName, - annotations, typeArgsMap, genericTypeArgs); - - } else if (Map.class.isAssignableFrom(realAttributeType)) { - - attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojo, - pojos, realAttributeType, attributeName, annotations, - typeArgsMap, genericTypeArgs); - - } else if (realAttributeType.isEnum()) { - - // Enum type - int enumConstantsLength = realAttributeType.getEnumConstants().length; - - if (enumConstantsLength > 0) { - int enumIndex = strategy.getIntegerInRange(0, - enumConstantsLength, attributeMetadata) - % enumConstantsLength; - attributeValue = realAttributeType.getEnumConstants()[enumIndex]; - } - - } else if (Type.class.isAssignableFrom(realAttributeType)) { - - Type paremeterType = null; - if (genericAttributeType instanceof ParameterizedType) { - ParameterizedType parametrized = (ParameterizedType) genericAttributeType; - Type[] arguments = parametrized.getActualTypeArguments(); - if (arguments.length > 0) { - paremeterType = arguments[0]; - } - } else if (realAttributeType.getTypeParameters().length > 0) { - paremeterType = realAttributeType.getTypeParameters()[0]; - } - - if (paremeterType != null) { - AtomicReference elementGenericTypeArgs - = new AtomicReference(NO_TYPES); - attributeValue = resolveGenericParameter(paremeterType, - typeArgsMap, elementGenericTypeArgs); - } else { - LOG.error("{} is missing generic type argument, supplied {} {}", - genericAttributeType, typeArgsMap, - Arrays.toString(genericTypeArgs)); - } - - } - - // For any other type, we use the PODAM strategy - if (attributeValue == null) { - - TypeVariable[] typeParams = attributeType.getTypeParameters(); - Type[] genericTypeArgsAll = mergeActualAndSuppliedGenericTypes( - typeParams, genericTypeArgs, typeArgsMap); - - Integer depth = pojos.get(realAttributeType); - if (depth == null) { - depth = -1; - } - if (depth <= strategy.getMaxDepth(pojo.getClass())) { - - pojos.put(realAttributeType, depth + 1); - attributeValue = this.manufacturePojoInternal( - realAttributeType, pojos, genericTypeArgsAll); - pojos.put(realAttributeType, depth); - - } else { - - LOG.warn("Loop in {} production detected.", - realAttributeType); - attributeValue = externalFactory.manufacturePojo( - realAttributeType, genericTypeArgsAll); - - } - } - - return attributeValue; - } - - /** - * Utility to merge actual types with supplied array of generic type - * substitutions - * - * @param actualTypes - * an array of types used for field or POJO declaration - * @param suppliedTypes - * an array of supplied types for generic type substitution - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @return An array of merged actual and supplied types with generic types - * resolved - */ - private Type[] mergeActualAndSuppliedGenericTypes( - TypeVariable[] actualTypes, Type[] suppliedTypes, - Map typeArgsMap) { - - List resolvedTypes = new ArrayList(); - List substitutionTypes = new ArrayList(Arrays.asList(suppliedTypes)); - for (int i = 0; i < actualTypes.length; i++) { - Type type = typeArgsMap.get(actualTypes[i].getName()); - if (type != null) { - resolvedTypes.add(type); - if (!substitutionTypes.isEmpty() && substitutionTypes.get(0).equals(type)) { - substitutionTypes.remove(0); - } - } - } - Type[] resolved = resolvedTypes.toArray(new Type[resolvedTypes.size()]); - Type[] supplied = substitutionTypes.toArray(new Type[substitutionTypes.size()]); - return mergeTypeArrays(resolved, supplied); - } - - /** - * It creates and returns a String value, eventually customised by - * annotations - * - * @param annotations - * The list of annotations used to customise the String value, if - * any - * @param attributeMetadata - * @return a String value, eventually customised by annotations - * @throws IllegalAccessException - * If an exception occurred while creating an instance of the - * strategy - * @throws InstantiationException - * If an exception occurred while creating an instance of the - * strategy - * - * @throws IllegalArgumentException - * If {@link PodamStrategyValue} was specified but the type was - * not correct for the attribute being set - */ - private String resolveStringValue(List annotations, - AttributeMetadata attributeMetadata) throws InstantiationException, - IllegalAccessException { - - String retValue = null; - - if (annotations == null || annotations.isEmpty()) { - - retValue = strategy.getStringValue(attributeMetadata); - - } else { - - for (Annotation annotation : annotations) { - - if (!PodamStringValue.class.isAssignableFrom(annotation - .getClass())) { - continue; - } - - // A specific value takes precedence over the length - PodamStringValue podamAnnotation = (PodamStringValue) annotation; - - if (podamAnnotation.strValue() != null - && podamAnnotation.strValue().length() > 0) { - - retValue = podamAnnotation.strValue(); - - } else { - - retValue = strategy.getStringOfLength( - podamAnnotation.length(), attributeMetadata); - - } - - } - - if (retValue == null) { - retValue = strategy.getStringValue(attributeMetadata); - } - - } - - return retValue; - } - - /** - * It returns an default value for a {@link Field} matching the attribute - * name or null if a field was not found. - * - * @param pojoClass - * The class supposed to contain the field - * @param attributeName - * The field name - * - * @return an instance of {@link Field} matching the attribute name or - * null if a field was not found. - */ - private T getDefaultFieldValue(Object pojo, String attributeName) { - T retValue = null; - - try { - Field field = getField(pojo.getClass(), attributeName); - - if (field != null) { - - // It allows to invoke Field.get on private fields - field.setAccessible(true); - - @SuppressWarnings(UNCHECKED_STR) - T t = (T) field.get(pojo); - retValue = t; - } else { - - LOG.info("The field {}[{}] didn't exist.", pojo.getClass(), attributeName); - } - - } catch (Exception e) { - - LOG.warn("We couldn't get default value for {}[{}]", - pojo.getClass(), attributeName, e); - } - - return retValue; - } - - /** - * It returns a {@link Field} matching the attribute name or null if a field - * was not found. - * - * @param pojoClass - * The class supposed to contain the field - * @param attributeName - * The field name - * - * @return a {@link Field} matching the attribute name or null if a field - * was not found. - */ - private Field getField(Class pojoClass, String attributeName) { - - Field field = null; - - Class clazz = pojoClass; - - while (clazz != null) { - try { - field = clazz.getDeclaredField(attributeName); - break; - } catch (NoSuchFieldException e) { - clazz = clazz.getSuperclass(); - } - } - if (field == null) { - LOG.warn("A field could not be found for attribute '{}[{}]'", - pojoClass, attributeName); - } - return field; - } - - /** - * It returns a {@link PodamStrategyValue} if one was specified, or - * {@code null} otherwise. - * - * @param annotations - * The list of annotations - * @return {@code true} if the list of annotations contains at least one - * {@link PodamStrategyValue} annotation. - */ - private PodamStrategyValue containsAttributeStrategyAnnotation( - List annotations) { - PodamStrategyValue retValue = null; - - for (Annotation annotation : annotations) { - if (PodamStrategyValue.class - .isAssignableFrom(annotation.getClass())) { - retValue = (PodamStrategyValue) annotation; - break; - } - } - - return retValue; - } - - /** - * It returns {@code true} if this class is a wrapper class, {@code false} - * otherwise - * - * @param candidateWrapperClass - * The class to check - * @return {@code true} if this class is a wrapper class, {@code false} - * otherwise - */ - private boolean isWrapper(Class candidateWrapperClass) { - - return candidateWrapperClass.equals(Byte.class) ? true - : candidateWrapperClass.equals(Boolean.class) ? true - : candidateWrapperClass.equals(Character.class) ? true - : candidateWrapperClass.equals(Short.class) ? true - : candidateWrapperClass - .equals(Integer.class) ? true - : candidateWrapperClass - .equals(Long.class) ? true - : candidateWrapperClass - .equals(Float.class) ? true - : candidateWrapperClass - .equals(Double.class) ? true - : false; - } - - /** - * Given the original class and the setter method, it returns all - * annotations for the field or an empty collection if no custom annotations - * were found on the field - * - * @param clazz - * The class containing the annotated attribute - * @param setter - * The setter method - * @return all annotations for the field - * @throws NoSuchFieldException - * If the field could not be found - * @throws SecurityException - * if a security exception occurred - */ - private List retrieveFieldAnnotations(Class clazz, - Method setter) { - - List retValue = new ArrayList(); - - // Checks if the field has got any custom annotations - String attributeName = PodamUtils - .extractFieldNameFromSetterMethod(setter); - Field setterField = getField(clazz, attributeName); - - if (setterField != null) { - Annotation[] annotations = setterField.getAnnotations(); - - if (annotations != null && annotations.length != 0) { - retValue = Arrays.asList(annotations); - } - } - - return retValue; - - } - - /** - * It returns a collection of some sort with some data in it. - * - * - * @param pojoClass - * The POJO being analysed - * @param pojos - * Set of manufactured pojos' types - * @param collectionType - * The type of the attribute being evaluated - * @param annotations - * The set of annotations for the annotated attribute. It might - * be empty - * @param attributeName - * The name of the field being set - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return a collection of some sort with some data in it - * @throws PodamMockeryException - * An exception occurred while resolving the collection - * @throws IllegalArgumentException - * If the field name is null or empty - */ - private Collection resolveCollectionValueWhenCollectionIsPojoAttribute( - Object pojo, Map, Integer> pojos, - Class collectionType, String attributeName, - List annotations, Map typeArgsMap, - Type... genericTypeArgs) { - - // This needs to be generic because collections can be of any type - Collection retValue = null; - if (null != pojo && null != attributeName) { - - retValue = getDefaultFieldValue(pojo, attributeName); - } - - retValue = resolveCollectionType(collectionType, retValue); - - if (null == retValue) { - return null; - } - - try { - - Class typeClass = null; - - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericTypeArgs == null || genericTypeArgs.length == 0) { - - LOG.warn("The collection attribute: " - + attributeName - + " does not have a type. We will assume Object for you"); - // Support for non-generified collections - typeClass = Object.class; - - } else { - Type actualTypeArgument = genericTypeArgs[0]; - - typeClass = resolveGenericParameter(actualTypeArgument, - typeArgsMap, elementGenericTypeArgs); - } - - fillCollection(pojos, annotations, retValue, typeClass, - elementGenericTypeArgs.get()); - - } catch (SecurityException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (IllegalArgumentException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (InstantiationException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (IllegalAccessException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (ClassNotFoundException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (InvocationTargetException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } - - return retValue; - } - - /** - * It fills a collection with the required number of elements of the - * required type. - * - *

- * This method has a so-called side effect. It updates the collection passed - * as argument. - *

- * - * @param collection - * The Collection to be filled - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * - */ - private void fillCollection(Collection collection, - Map, Integer> pojos, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - final Map typeArgsMap = new HashMap(); - Class collectionClass = collection.getClass(); - Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, - collectionClass, genericTypeArgs); - - Annotation[] annotations = collection.getClass().getAnnotations(); - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - Type[] typeParams = collectionClass.getTypeParameters(); - while (typeParams.length < 1) { - Type type = collectionClass.getGenericSuperclass(); - collectionClass = resolveGenericParameter(type, typeArgsMap, - elementGenericTypeArgs); - typeParams = elementGenericTypeArgs.get(); - } - Class elementTypeClass = resolveGenericParameter(typeParams[0], - typeArgsMap, elementGenericTypeArgs); - Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), - genericTypeArgsExtra); - fillCollection(pojos, Arrays.asList(annotations), - collection, elementTypeClass, elementGenericArgs); - } - - /** - * It fills a collection with the required number of elements of the - * required type. - * - *

- * This method has a so-called side effect. It updates the collection passed - * as argument. - *

- * - * @param pojos - * Set of manufactured pojos' types - * @param annotations - * The annotations for this attribute - * @param collection - * The Collection to be filled - * @param collectionElementType - * The type of the collection element - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * - */ - private void fillCollection(Map, Integer> pojos, - List annotations, Collection collection, - Class collectionElementType, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - // If the user defined a strategy to fill the collection elements, - // we use it - PodamCollection collectionAnnotation = null; - AttributeStrategy elementStrategy = null; - for (Annotation annotation : annotations) { - if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { - collectionAnnotation = (PodamCollection) annotation; - break; - } - - } - - int nbrElements; - - if (null != collectionAnnotation) { - - nbrElements = collectionAnnotation.nbrElements(); - elementStrategy = collectionAnnotation.collectionElementStrategy() - .newInstance(); - } else { - - nbrElements = strategy - .getNumberOfCollectionElements(collectionElementType); - } - - try { - if (collection.size() > nbrElements) { - - collection.clear(); - } - - for (int i = collection.size(); i < nbrElements; i++) { - - // The default - Object element; - if (null != elementStrategy - && ObjectStrategy.class.isAssignableFrom(elementStrategy - .getClass()) - && Object.class.equals(collectionElementType)) { - LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy"); - element = elementStrategy.getValue(); - } else if (null != elementStrategy - && !ObjectStrategy.class.isAssignableFrom(elementStrategy - .getClass())) { - LOG.debug("Collection elements will be filled using the following strategy: " - + elementStrategy); - element = returnAttributeDataStrategyValue( - collectionElementType, elementStrategy); - } else { - Map nullTypeArgsMap = new HashMap(); - element = manufactureParameterValue(pojos, - collectionElementType, collectionElementType, - annotations, nullTypeArgsMap, genericTypeArgs); - } - collection.add(element); - } - } catch (UnsupportedOperationException e) { - - LOG.warn("Cannot fill immutable collection {}", collection.getClass()); - } - } - - /** - * It manufactures and returns a Map with at least one element in it - * - * @param pojoClass - * The POJO being initialised - * @param pojos - * Set of manufactured pojos' types - * @param attributeType - * The type of the POJO map attribute - * @param attributeName - * The POJO attribute name - * @param annotations - * The annotations specified for this attribute - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return Map with at least one element in it - * - * @throws IllegalArgumentException - *
    - *
  • If the attribute name is null or empty
  • - *
  • If the array of types of the Map has length different - * from 2
  • - *
- * - * @throws PodamMockeryException - * If an error occurred while creating the Map object - */ - private Map resolveMapValueWhenMapIsPojoAttribute( - Object pojo, Map, Integer> pojos, - Class attributeType, String attributeName, - List annotations, Map typeArgsMap, - Type... genericTypeArgs) { - - Map retValue = null; - if (null != pojo && null != attributeName) { - - retValue = getDefaultFieldValue(pojo, attributeName); - } - - retValue = resolveMapType(attributeType, retValue); - - if (null == retValue) { - return null; - } - - try { - - Class keyClass = null; - - Class elementClass = null; - - AtomicReference keyGenericTypeArgs = new AtomicReference( - NO_TYPES); - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericTypeArgs == null || genericTypeArgs.length == 0) { - - LOG.warn("Map attribute: " - + attributeName - + " is non-generic. We will assume a Map for you."); - - keyClass = Object.class; - - elementClass = Object.class; - - } else { - - // Expected only key, value type - if (genericTypeArgs.length != 2) { - throw new IllegalStateException( - "In a Map only key value generic type are expected."); - } - - Type[] actualTypeArguments = genericTypeArgs; - keyClass = resolveGenericParameter(actualTypeArguments[0], - typeArgsMap, keyGenericTypeArgs); - elementClass = resolveGenericParameter(actualTypeArguments[1], - typeArgsMap, elementGenericTypeArgs); - } - - MapArguments mapArguments = new MapArguments(); - mapArguments.setPojos(pojos); - mapArguments.setAnnotations(annotations); - mapArguments.setMapToBeFilled(retValue); - mapArguments.setKeyClass(keyClass); - mapArguments.setElementClass(elementClass); - mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); - mapArguments - .setElementGenericTypeArgs(elementGenericTypeArgs.get()); - - fillMap(mapArguments); - - } catch (InstantiationException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } catch (IllegalAccessException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } catch (SecurityException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } catch (ClassNotFoundException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } catch (InvocationTargetException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } - - return retValue; - } - - /** - * It fills a Map with the required number of elements of the required type. - * - *

- * This method has a so-called side-effect. It updates the Map given as - * argument. - *

- * - * @param pojoClass - * The POJO being initialised - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * - */ - private void fillMap(Map map, - Map, Integer> pojos, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - final Map typeArgsMap = new HashMap(); - Class pojoClass = map.getClass(); - Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, - pojoClass, genericTypeArgs); - - Class mapClass = pojoClass; - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - Type[] typeParams = mapClass.getTypeParameters(); - while (typeParams.length < 2) { - Type type = mapClass.getGenericSuperclass(); - mapClass = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); - typeParams = elementGenericTypeArgs.get(); - } - AtomicReference keyGenericTypeArgs = new AtomicReference( - NO_TYPES); - Class keyClass = resolveGenericParameter(typeParams[0], - typeArgsMap, keyGenericTypeArgs); - Class elementClass = resolveGenericParameter(typeParams[1], - typeArgsMap, elementGenericTypeArgs); - - Type[] keyGenericArgs = mergeTypeArrays(keyGenericTypeArgs.get(), - genericTypeArgsExtra); - Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), - genericTypeArgsExtra); - - MapArguments mapArguments = new MapArguments(); - mapArguments.setPojos(pojos); - mapArguments.setAnnotations(Arrays.asList(pojoClass.getAnnotations())); - mapArguments.setMapToBeFilled(map); - mapArguments.setKeyClass(keyClass); - mapArguments.setElementClass(elementClass); - mapArguments.setKeyGenericTypeArgs(keyGenericArgs); - mapArguments.setElementGenericTypeArgs(elementGenericArgs); - - fillMap(mapArguments); - } - - /** - * It fills a Map with the required number of elements of the required type. - * - *

- * This method has a so-called side-effect. It updates the Map given as - * argument. - *

- * - * @param mapArguments - * The arguments POJO - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * - */ - private void fillMap(MapArguments mapArguments) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - // If the user defined a strategy to fill the collection elements, - // we use it - PodamCollection collectionAnnotation = null; - AttributeStrategy keyStrategy = null; - AttributeStrategy elementStrategy = null; - for (Annotation annotation : mapArguments.getAnnotations()) { - if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { - collectionAnnotation = (PodamCollection) annotation; - break; - } - } - - int nbrElements; - - if (null != collectionAnnotation) { - - nbrElements = collectionAnnotation.nbrElements(); - keyStrategy = collectionAnnotation.mapKeyStrategy().newInstance(); - elementStrategy = collectionAnnotation.mapElementStrategy() - .newInstance(); - } else { - - nbrElements = strategy.getNumberOfCollectionElements(mapArguments - .getElementClass()); - } - - Map map = mapArguments.getMapToBeFilled(); - try { - if (map.size() > nbrElements) { - - map.clear(); - } - - for (int i = map.size(); i < nbrElements; i++) { - - Object keyValue = null; - - Object elementValue = null; - - @SuppressWarnings(UNCHECKED_STR) - Class> mapType = - (Class>) mapArguments.getMapToBeFilled().getClass(); - - MapKeyOrElementsArguments valueArguments = new MapKeyOrElementsArguments(); - valueArguments.setPojoClass(mapType); - valueArguments.setPojos(mapArguments.getPojos()); - valueArguments.setAnnotations(mapArguments.getAnnotations()); - valueArguments.setKeyOrValueType(mapArguments.getKeyClass()); - valueArguments.setElementStrategy(keyStrategy); - valueArguments.setGenericTypeArgs(mapArguments - .getKeyGenericTypeArgs()); - - keyValue = getMapKeyOrElementValue(valueArguments); - - valueArguments = new MapKeyOrElementsArguments(); - valueArguments.setPojoClass(mapType); - valueArguments.setPojos(mapArguments.getPojos()); - valueArguments.setAnnotations(mapArguments.getAnnotations()); - valueArguments.setKeyOrValueType(mapArguments.getElementClass()); - valueArguments.setElementStrategy(elementStrategy); - valueArguments.setGenericTypeArgs(mapArguments - .getElementGenericTypeArgs()); - - elementValue = getMapKeyOrElementValue(valueArguments); - - /* ConcurrentHashMap doesn't allow null values */ - if (elementValue != null || !(map instanceof ConcurrentHashMap)) { - map.put(keyValue, elementValue); - } - } - } catch (UnsupportedOperationException e) { - - LOG.warn("Cannot fill immutable map {}", map.getClass()); - } - } - - /** - * It fills a Map key or value with the appropriate value, considering - * attribute-level customisation. - * - * @param keyOrElementsArguments - * The arguments POJO - * @return A Map key or value - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws IllegalArgumentException - *
    - *
  • If an illegal argument was passed
  • - *
  • If an invalid value was set for a precise value in an - * annotation and such value could not be converted to the - * desired type
  • - *
- */ - private Object getMapKeyOrElementValue( - MapKeyOrElementsArguments keyOrElementsArguments) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - Object retValue = null; - - if (null != keyOrElementsArguments.getElementStrategy() - && ObjectStrategy.class.isAssignableFrom(keyOrElementsArguments - .getElementStrategy().getClass()) - && Object.class.equals(keyOrElementsArguments - .getKeyOrValueType())) { - LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy"); - retValue = keyOrElementsArguments.getElementStrategy().getValue(); - } else if (null != keyOrElementsArguments.getElementStrategy() - && !ObjectStrategy.class - .isAssignableFrom(keyOrElementsArguments - .getElementStrategy().getClass())) { - LOG.debug("Map key or value will be filled using the following strategy: " - + keyOrElementsArguments.getElementStrategy()); - retValue = returnAttributeDataStrategyValue( - keyOrElementsArguments.getKeyOrValueType(), - keyOrElementsArguments.getElementStrategy()); - - } else { - - Map nullTypeArgsMap = new HashMap(); - retValue = manufactureParameterValue( - keyOrElementsArguments.getPojos(), - keyOrElementsArguments.getKeyOrValueType(), - keyOrElementsArguments.getKeyOrValueType(), - keyOrElementsArguments.getAnnotations(), - nullTypeArgsMap, - keyOrElementsArguments.getGenericTypeArgs()); - } - return retValue; - } - - /** - * It returns an Array with the first element set - * - * - * @param attributeType - * The array type - * @param genericAttributeType - * The array generic type - * @param pojos - * Set of manufactured pojos' types - * @param annotations - * The annotations to be considered - * @param pojo - * POJO containing attribute - * @param attributeName - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @return Array with the first element set - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - private Object resolveArrayElementValue(Class attributeType, - Type genericType, Map, Integer> pojos, - List annotations, Object pojo, String attributeName, - Map typeArgsMap) throws InstantiationException, - IllegalAccessException, InvocationTargetException, - ClassNotFoundException { - - Class componentType = null; - AtomicReference genericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericType instanceof GenericArrayType) { - Type genericComponentType = ((GenericArrayType) genericType).getGenericComponentType(); - if (genericComponentType instanceof TypeVariable) { - TypeVariable componentTypeVariable - = (TypeVariable) genericComponentType; - final Type resolvedType - = typeArgsMap.get(componentTypeVariable.getName()); - componentType - = resolveGenericParameter(resolvedType, typeArgsMap, - genericTypeArgs); - } - } - if (componentType == null) { - componentType = attributeType.getComponentType(); - } - - // If the user defined a strategy to fill the collection elements, - // we use it - PodamCollection collectionAnnotation = null; - AttributeStrategy elementStrategy = null; - for (Annotation annotation : annotations) { - if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { - collectionAnnotation = (PodamCollection) annotation; - break; - } - - } - - int nbrElements; - if (null != collectionAnnotation) { - - nbrElements = collectionAnnotation.nbrElements(); - elementStrategy = collectionAnnotation.collectionElementStrategy() - .newInstance(); - } else { - - nbrElements = strategy.getNumberOfCollectionElements(attributeType); - } - - Object arrayElement = null; - Object array = Array.newInstance(componentType, nbrElements); - - for (int i = 0; i < nbrElements; i++) { - - // The default - if (null != elementStrategy - && ObjectStrategy.class - .isAssignableFrom(collectionAnnotation - .collectionElementStrategy()) - && Object.class.equals(componentType)) { - LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy"); - arrayElement = elementStrategy.getValue(); - } else if (null != elementStrategy - && !ObjectStrategy.class - .isAssignableFrom(collectionAnnotation - .collectionElementStrategy())) { - LOG.debug("Array elements will be filled using the following strategy: " - + elementStrategy); - arrayElement = returnAttributeDataStrategyValue(componentType, - elementStrategy); - - } else { - - arrayElement = manufactureAttributeValue(pojo, pojos, - componentType, genericType, annotations, attributeName, - typeArgsMap, genericTypeArgs.get()); - - } - - Array.set(array, i, arrayElement); - - } - - return array; - } - - /** - * Given a collection type it returns an instance - *

- *

    - *
  • The default type for a {@link List} is an {@link ArrayList}
  • - *
  • The default type for a {@link Queue} is a {@link LinkedList}
  • - *
  • The default type for a {@link Set} is a {@link HashSet}
  • - *
- * - *

- * - * @param collectionType - * The collection type * - * @param defaultValue - * Default value for the collection, can be null - * @return an instance of the collection type or null - */ - private Collection resolveCollectionType( - Class collectionType, Collection defaultValue) { - - Collection retValue = null; - - // Default list and set are ArrayList and HashSet. If users - // wants a particular collection flavour they have to initialise - // the collection - if (null != defaultValue && - (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { - /* Default collection, which is not immutable */ - retValue = defaultValue; - } else { - if (Queue.class.isAssignableFrom(collectionType)) { - if (collectionType.isAssignableFrom(LinkedList.class)) { - retValue = new LinkedList(); - } - } else if (Set.class.isAssignableFrom(collectionType)) { - if (collectionType.isAssignableFrom(HashSet.class)) { - retValue = new HashSet(); - } - } else { - if (collectionType.isAssignableFrom(ArrayList.class)) { - retValue = new ArrayList(); - } - } - if (null != retValue && null != defaultValue) { - retValue.addAll(defaultValue); - } - } - return retValue; - } - - /** - * It manufactures and returns a default instance for each map type - * - *

- * The default implementation for a {@link ConcurrentMap} is - * {@link ConcurrentHashMap} - *

- * - *

- * The default implementation for a {@link SortedMap} is a {@link TreeMap} - *

- * - *

- * The default Map is none of the above was recognised is a {@link HashMap} - *

- * - * @param mapType - * The attribute type implementing Map - * @param defaultValue - * Default value for map - * @return A default instance for each map type or null - * - */ - private Map resolveMapType( - Class mapType, Map defaultValue) { - - Map retValue = null; - - if (null != defaultValue && - (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { - /* Default map, which is not immutable */ - retValue = defaultValue; - } else { - if (SortedMap.class.isAssignableFrom(mapType)) { - if (mapType.isAssignableFrom(TreeMap.class)) { - retValue = new TreeMap(); - } - } else if (ConcurrentMap.class.isAssignableFrom(mapType)) { - if (mapType.isAssignableFrom(ConcurrentHashMap.class)) { - retValue = new ConcurrentHashMap(); - } - } else { - if (mapType.isAssignableFrom(HashMap.class)) { - retValue = new HashMap(); - } - } - } - - return retValue; - - } - - /** - * Given a constructor it manufactures and returns the parameter values - * required to invoke it - * - * @param constructor - * The constructor for which parameter values are required - * @param pojoClass - * The POJO class containing the constructor - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * - * @return The parameter values required to invoke the constructor - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - private Object[] getParameterValuesForConstructor( - Constructor constructor, Class pojoClass, - Map, Integer> pojos, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - final Map typeArgsMap = new HashMap(); - final Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, - genericTypeArgs); - - Annotation[][] parameterAnnotations = constructor - .getParameterAnnotations(); - - Class[] parameterTypes = constructor.getParameterTypes(); - Type[] genericTypes = constructor.getGenericParameterTypes(); - Object[] parameterValues = new Object[parameterTypes.length]; - - for (int idx = 0; idx < parameterTypes.length; idx++) { - - List annotations = Arrays - .asList(parameterAnnotations[idx]); - - Type genericType = (idx < genericTypes.length) ? - genericTypes[idx] : parameterTypes[idx]; - - parameterValues[idx] = manufactureParameterValue(parameterTypes[idx], - genericType, annotations, typeArgsMap, pojos, - genericTypeArgsExtra == null ? NO_TYPES : genericTypeArgsExtra); - } - - return parameterValues; - - } - - /** - * Manufactures and returns the parameter value for method required to - * invoke it - * - * @param parameterType type of parameter - * @param genericType generic type of parameter - * @param annotations parameter annotations - * @param typeArgsMap map for resolving generic types - * @param genericTypeArgsExtra extra generic types for chaining - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * - * @return The parameter values required to invoke the constructor - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - private Object manufactureParameterValue(Class parameterType, - Type genericType, List annotations, - final Map typeArgsMap, Map, Integer> pojos, - Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - Object parameterValue = null; - - if (Collection.class.isAssignableFrom(parameterType)) { - - Collection defaultValue = null; - Collection collection = resolveCollectionType( - parameterType, defaultValue); - - if (collection != null) { - Class collectionElementType; - AtomicReference collectionGenericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericType instanceof ParameterizedType) { - ParameterizedType pType = (ParameterizedType) genericType; - Type actualTypeArgument = pType.getActualTypeArguments()[0]; - - collectionElementType = resolveGenericParameter( - actualTypeArgument, typeArgsMap, - collectionGenericTypeArgs); - } else { - LOG.warn("Collection parameter {} type is non-generic." - + "We will assume a Collection for you.", - genericType); - collectionElementType = Object.class; - } - - Type[] genericTypeArgsAll = mergeTypeArrays( - collectionGenericTypeArgs.get(), genericTypeArgs); - fillCollection(pojos, annotations, - collection, collectionElementType, genericTypeArgsAll); - - parameterValue = collection; - } - - } else if (Map.class.isAssignableFrom(parameterType)) { - - Map defaultValue = null; - Map map = resolveMapType(parameterType, defaultValue); - - if (map != null) { - Class keyClass; - Class elementClass; - AtomicReference keyGenericTypeArgs = new AtomicReference( - NO_TYPES); - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericType instanceof ParameterizedType) { - ParameterizedType pType = (ParameterizedType) genericType; - Type[] actualTypeArguments = pType.getActualTypeArguments(); - - keyClass = resolveGenericParameter(actualTypeArguments[0], - typeArgsMap, keyGenericTypeArgs); - elementClass = resolveGenericParameter( - actualTypeArguments[1], typeArgsMap, - elementGenericTypeArgs); - } else { - LOG.warn("Map parameter {} type is non-generic." - + "We will assume a Map for you.", - genericType); - keyClass = Object.class; - elementClass = Object.class; - } - - Type[] genericTypeArgsAll = mergeTypeArrays( - elementGenericTypeArgs.get(), genericTypeArgs); - - MapArguments mapArguments = new MapArguments(); - mapArguments.setPojos(pojos); - mapArguments.setAnnotations(annotations); - mapArguments.setMapToBeFilled(map); - mapArguments.setKeyClass(keyClass); - mapArguments.setElementClass(elementClass); - mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); - mapArguments.setElementGenericTypeArgs(genericTypeArgsAll); - - fillMap(mapArguments); - - parameterValue = map; - } - } - - if (parameterValue == null) { - - Map typeArgsMapForParam; - if (genericType instanceof ParameterizedType) { - typeArgsMapForParam = new HashMap(typeArgsMap); - ParameterizedType parametrizedType = - (ParameterizedType) genericType; - - TypeVariable[] argumentTypes = parameterType.getTypeParameters(); - Type[] argumentGenericTypes = parametrizedType.getActualTypeArguments(); - - for (int k = 0; k < argumentTypes.length; k++) { - if (argumentGenericTypes[k] instanceof Class) { - Class genericParam = (Class) argumentGenericTypes[k]; - typeArgsMapForParam.put(argumentTypes[k].getName(), genericParam); - } - } - } else { - typeArgsMapForParam = typeArgsMap; - } - - parameterValue = manufactureParameterValue(pojos, parameterType, - genericType, annotations, typeArgsMapForParam, - genericTypeArgs); - } - - return parameterValue; - } - - /** - * Utility method to merge two arrays - * - * @param original - * The main array - * @param extra - * The additional array, optionally may be null - * @return A merged array of original and extra arrays - */ - private Type[] mergeTypeArrays(Type[] original, Type[] extra) { - - Type[] merged; - - if (extra != null) { - merged = new Type[original.length + extra.length]; - System.arraycopy(original, 0, merged, 0, original.length); - System.arraycopy(extra, 0, merged, original.length, extra.length); - } else { - merged = original; - } - - return merged; - } - - /** - * It retrieves the value for the {@link PodamStrategyValue} annotation with - * which the attribute was annotated - * - * @param attributeType - * The attribute type, used for type checking - * @param attributeStrategy - * The {@link AttributeStrategy} to use - * @return The value for the {@link PodamStrategyValue} annotation with - * which the attribute was annotated - * @throws InstantiationException - * If an exception occurred while creating an instance of the - * strategy contained within the {@link PodamStrategyValue} - * annotation - * @throws IllegalAccessException - * If an exception occurred while creating an instance of the - * strategy contained within the {@link PodamStrategyValue} - * annotation - * - * @throws IllegalArgumentException - * If the type of the data strategy defined for the - * {@link PodamStrategyValue} annotation is not assignable to - * the annotated attribute. This de facto guarantees type - * safety. - */ - private Object returnAttributeDataStrategyValue(Class attributeType, - AttributeStrategy attributeStrategy) - throws InstantiationException, IllegalAccessException { - - Object retValue = null; - - Method attributeStrategyMethod = null; - - try { - attributeStrategyMethod = attributeStrategy.getClass().getMethod( - PodamConstants.PODAM_ATTRIBUTE_STRATEGY_METHOD_NAME, - new Class[] {}); - - if (!attributeType.isAssignableFrom(attributeStrategyMethod - .getReturnType())) { - String errMsg = "The type of the Podam Attribute Strategy is not " - + attributeType.getName() - + " but " - + attributeStrategyMethod.getReturnType().getName() - + ". An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg); - } - - retValue = attributeStrategy.getValue(); - - } catch (SecurityException e) { - throw new IllegalStateException( - "A security issue occurred while retrieving the Podam Attribute Strategy details", - e); - } catch (NoSuchMethodException e) { - throw new IllegalStateException( - "It seems the Podam Attribute Annotation is of the wrong type", - e); - } - - return retValue; - - } - - // ------------------->> equals() / hashcode() / toString() - - // ------------------->> Inner classes - -} diff --git a/All/Genesis-OOB/Genesis#185/old/PodamFactoryImpl.java b/All/Genesis-OOB/Genesis#185/old/PodamFactoryImpl.java deleted file mode 100755 index 81d9aa5..0000000 --- a/All/Genesis-OOB/Genesis#185/old/PodamFactoryImpl.java +++ /dev/null @@ -1,3099 +0,0 @@ -/** - * - */ -package uk.co.jemos.podam.api; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Array; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; -import java.lang.reflect.WildcardType; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Queue; -import java.util.Set; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicReference; - -import net.jcip.annotations.Immutable; -import net.jcip.annotations.ThreadSafe; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import uk.co.jemos.podam.common.AttributeStrategy; -import uk.co.jemos.podam.common.ConstructorAdaptiveComparator; -import uk.co.jemos.podam.common.PodamBooleanValue; -import uk.co.jemos.podam.common.PodamByteValue; -import uk.co.jemos.podam.common.PodamCharValue; -import uk.co.jemos.podam.common.PodamCollection; -import uk.co.jemos.podam.common.PodamConstants; -import uk.co.jemos.podam.common.PodamConstructor; -import uk.co.jemos.podam.common.PodamDoubleValue; -import uk.co.jemos.podam.common.PodamFloatValue; -import uk.co.jemos.podam.common.PodamIntValue; -import uk.co.jemos.podam.common.PodamLongValue; -import uk.co.jemos.podam.common.PodamShortValue; -import uk.co.jemos.podam.common.PodamStrategyValue; -import uk.co.jemos.podam.common.PodamStringValue; -import uk.co.jemos.podam.exceptions.PodamMockeryException; - -/** - * The PODAM factory implementation - * - * @author mtedone - * - * @since 1.0.0 - * - */ -@ThreadSafe -@Immutable -public class PodamFactoryImpl implements PodamFactory { - - // ------------------->> Constants - - private static final String RESOLVING_COLLECTION_EXCEPTION_STR = "An exception occurred while resolving the collection"; - - private static final String MAP_CREATION_EXCEPTION_STR = "An exception occurred while creating a Map object"; - - private static final String UNCHECKED_STR = "unchecked"; - - private static final String THE_ANNOTATION_VALUE_STR = "The annotation value: "; - - private static final Type[] NO_TYPES = new Type[0]; - - /** Application logger */ - private static final Logger LOG = LoggerFactory - .getLogger(PodamFactoryImpl.class.getName()); - - // ------------------->> Instance / variables - - /** - * External factory to delegate production this factory cannot handle - *

- * The default is {@link LoggingExternalFactory}. - *

- */ - private final PodamFactory externalFactory; - - /** - * The strategy to use to fill data. - *

- * The default is {@link RandomDataProviderStrategy}. - *

- */ - private final DataProviderStrategy strategy; - - /** - * A map to keep one object for each class. If memoization is enabled, the - * factory will use this table to avoid creating objects of the same class - * multiple times. - */ - private Map, Object> memoizationTable = new HashMap, Object>(); - - // ------------------->> Constructors - - /** - * Default constructor. - */ - public PodamFactoryImpl() { - this(LoggingExternalFactory.getInstance(), - RandomDataProviderStrategy.getInstance()); - } - - /** - * Constructor with non-default strategy - * - * @param strategy - * The strategy to use to fill data - */ - public PodamFactoryImpl(DataProviderStrategy strategy) { - this(LoggingExternalFactory.getInstance(), strategy); - } - - /** - * Constructor with non-default external factory - * - * @param externalFactory - * External factory to delegate production this factory cannot - * handle - */ - public PodamFactoryImpl(PodamFactory externalFactory) { - this(externalFactory, RandomDataProviderStrategy.getInstance()); - } - - /** - * Full constructor. - * - * @param externalFactory - * External factory to delegate production this factory cannot - * handle - * @param strategy - * The strategy to use to fill data - */ - public PodamFactoryImpl(PodamFactory externalFactory, - DataProviderStrategy strategy) { - this.externalFactory = externalFactory; - this.strategy = strategy; - } - - // ------------------->> Public methods - - /** - * {@inheritDoc} - */ - @Override - public T manufacturePojo(Class pojoClass) { - return this.manufacturePojo(pojoClass, NO_TYPES); - } - - /** - * {@inheritDoc} - */ - @Override - public T manufacturePojoWithFullData(Class pojoClass, Type... genericTypeArgs) { - AbstractRandomDataProviderStrategy sortingStrategy; - if (getStrategy() instanceof AbstractRandomDataProviderStrategy) { - sortingStrategy = (AbstractRandomDataProviderStrategy) getStrategy(); - } else { - throw new IllegalStateException("manufacturePojoWithFullData can" - + " only be used with strategies derived from" - + " AbstractRandomDataProviderStrategy"); - } - ConstructorAdaptiveComparator constructorComparator; - if (sortingStrategy.getConstructorComparator() - instanceof ConstructorAdaptiveComparator) { - constructorComparator = (ConstructorAdaptiveComparator) - sortingStrategy.getConstructorComparator(); - } else { - throw new IllegalStateException("manufacturePojoWithFullData can" - + " only be used with constructor comparators derived from" - + " ConstructorAdaptiveComparator"); - } - constructorComparator.addHeavyClass(pojoClass); - T retValue = this.manufacturePojo(pojoClass, genericTypeArgs); - constructorComparator.removeHeavyClass(pojoClass); - return retValue; - } - - /** - * {@inheritDoc} - */ - @Override - public T manufacturePojo(Class pojoClass, Type... genericTypeArgs) { - Map, Integer> pojos = new HashMap, Integer>(); - pojos.put(pojoClass, 0); - try { - return this.manufacturePojoInternal(pojoClass, pojos, - genericTypeArgs); - } catch (InstantiationException e) { - throw new PodamMockeryException(e.getMessage(), e); - } catch (IllegalAccessException e) { - throw new PodamMockeryException(e.getMessage(), e); - } catch (InvocationTargetException e) { - throw new PodamMockeryException(e.getMessage(), e); - } catch (ClassNotFoundException e) { - throw new PodamMockeryException(e.getMessage(), e); - } - } - - // ------------------->> Getters / Setters - - /** - * {@inheritDoc} - */ - - @Override - public DataProviderStrategy getStrategy() { - return strategy; - } - - // ------------------->> Private methods - - /** - * Fills type agruments map - *

- * This method places required and provided types for object creation into a - * map, which will be used for type mapping. - *

- * - * @param typeArgsMap - * a map to fill - * @param pojoClass - * Typed class - * @param genericTypeArgs - * Type arguments provided for a generics object by caller - * @return Array of unused provided generic type arguments - * @throws IllegalStateException - * If number of typed parameters doesn't match number of - * provided generic types - */ - private Type[] fillTypeArgMap(final Map typeArgsMap, - final Class pojoClass, final Type[] genericTypeArgs) { - - TypeVariable[] array = pojoClass.getTypeParameters(); - List> typeParameters = new ArrayList>(Arrays.asList(array)); - Iterator> iterator = typeParameters.iterator(); - /* Removing types, which are already in typeArgsMap */ - while (iterator.hasNext()) { - if (typeArgsMap.containsKey(iterator.next().getName())) { - iterator.remove(); - } - } - - if (typeParameters.size() > genericTypeArgs.length) { - String msg = pojoClass.getCanonicalName() - + " is missing generic type arguments, expected " - + typeParameters + " found " - + Arrays.toString(genericTypeArgs); - throw new IllegalStateException(msg); - } - - int i; - for (i = 0; i < typeParameters.size(); i++) { - typeArgsMap.put(typeParameters.get(i).getName(), genericTypeArgs[i]); - } - Type[] genericTypeArgsExtra; - if (typeParameters.size() < genericTypeArgs.length) { - genericTypeArgsExtra = Arrays.copyOfRange(genericTypeArgs, i, - genericTypeArgs.length); - } else { - genericTypeArgsExtra = null; - } - - /* Adding types, which were specified during inheritance */ - Class clazz = pojoClass; - while (clazz != null) { - Type superType = clazz.getGenericSuperclass(); - clazz = clazz.getSuperclass(); - if (superType instanceof ParameterizedType) { - ParameterizedType paramType = (ParameterizedType) superType; - Type[] actualParamTypes = paramType.getActualTypeArguments(); - TypeVariable[] paramTypes = clazz.getTypeParameters(); - for (i = 0; i < actualParamTypes.length - && i < paramTypes.length; i++) { - if (actualParamTypes[i] instanceof Class) { - typeArgsMap.put(paramTypes[i].getName(), - actualParamTypes[i]); - } - } - } - } - - return genericTypeArgsExtra; - } - - /** - * It attempts to create an instance of the given class - *

- * This method attempts to create an instance of the given argument for - * classes without setters. These may be either immutable classes (e.g. with - * final attributes and no setters) or Java classes (e.g. belonging to the - * java / javax namespace). In case the class does not provide a public, - * no-arg constructor (e.g. Calendar), this method attempts to find a , - * no-args, factory method (e.g. getInstance()) and it invokes it - *

- * - * @param pojoClass - * The name of the class for which an instance filled with values - * is required - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * - * - * @return An instance of the given class - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - private Object instantiatePojoWithoutConstructors( - Class pojoClass, Map, Integer> pojos, - Type... genericTypeArgs) throws InstantiationException, - IllegalAccessException, InvocationTargetException, - ClassNotFoundException { - - Object retValue = null; - - final Map typeArgsMap = new HashMap(); - Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, - pojoClass, genericTypeArgs); - - // If no publicly accessible constructors are available, - // the best we can do is to find a constructor (e.g. - // getInstance()) - - Method[] declaredMethods = pojoClass.getDeclaredMethods(); - strategy.sort(declaredMethods); - - // A candidate factory method is a method which returns the - // Class type - - // The parameters to pass to the method invocation - Object[] parameterValues = null; - Object[] noParams = new Object[] {}; - - for (Method candidateConstructor : declaredMethods) { - - if (!Modifier.isStatic(candidateConstructor.getModifiers()) - || !candidateConstructor.getReturnType().equals(pojoClass) - || retValue != null) { - continue; - } - - parameterValues = new Object[candidateConstructor - .getParameterTypes().length]; - - Class[] parameterTypes = candidateConstructor.getParameterTypes(); - - if (parameterTypes.length == 0) { - - parameterValues = noParams; - - } else { - - // This is a factory method with arguments - - Annotation[][] parameterAnnotations = candidateConstructor - .getParameterAnnotations(); - - int idx = 0; - - for (Class parameterType : parameterTypes) { - - List annotations = Arrays - .asList(parameterAnnotations[idx]); - Type genericType = candidateConstructor.getGenericParameterTypes()[idx]; - - parameterValues[idx] = manufactureParameterValue(parameterType, - genericType, annotations, typeArgsMap, pojos, - genericTypeArgsExtra == null ? NO_TYPES : genericTypeArgsExtra); - - idx++; - - } - - } - - try { - - retValue = candidateConstructor.invoke(pojoClass, - parameterValues); - LOG.debug("Could create an instance using " - + candidateConstructor); - - } catch (Exception t) { - - LOG.debug( - "PODAM could not create an instance for constructor: " - + candidateConstructor - + ". Will try another one...", t); - - } - - } - - if (retValue == null) { - retValue = externalFactory.manufacturePojo(pojoClass, genericTypeArgs); - } - if (retValue == null) { - LOG.warn("For class {} PODAM could not possibly create" - + " a value. It will be returned as null.", - pojoClass); - } - - return retValue; - - } - - /** - * It resolves generic parameter type - * - * - * @param paramType - * The generic parameter type - * @param typeArgsMap - * A map of resolved types - * @param methodGenericTypeArgs - * Return value posible generic types of the generic parameter - * type - * @return value for class representing the generic parameter type - */ - private Class resolveGenericParameter(Type paramType, - Map typeArgsMap, - AtomicReference methodGenericTypeArgs) { - - Class parameterType = null; - methodGenericTypeArgs.set(NO_TYPES); - if (paramType instanceof TypeVariable) { - final TypeVariable typeVariable = (TypeVariable) paramType; - final Type type = typeArgsMap.get(typeVariable.getName()); - if (type != null) { - parameterType = resolveGenericParameter(type, typeArgsMap, - methodGenericTypeArgs); - } - } else if (paramType instanceof ParameterizedType) { - ParameterizedType pType = (ParameterizedType) paramType; - parameterType = (Class) pType.getRawType(); - methodGenericTypeArgs.set(pType.getActualTypeArguments()); - } else if (paramType instanceof WildcardType) { - WildcardType wType = (WildcardType) paramType; - Type[] bounds = wType.getLowerBounds(); - String msg; - if (bounds != null && bounds.length > 0) { - msg = "Lower bounds:"; - } else { - bounds = wType.getUpperBounds(); - msg = "Upper bounds:"; - } - if (bounds != null && bounds.length > 0) { - LOG.debug(msg + Arrays.toString(bounds)); - parameterType = resolveGenericParameter(bounds[0], typeArgsMap, - methodGenericTypeArgs); - } - } else if (paramType instanceof Class) { - parameterType = (Class) paramType; - } - - if (parameterType == null) { - LOG.warn("Unrecognized type {}. Will use Object instead", - paramType); - parameterType = Object.class; - } - return parameterType; - } - - /** - * It resolves and returns the primitive value depending on the type - * - * - * @param primitiveClass - * The primitive type class - * @param annotations - * The annotations to consider for this attribute - * @param attributeMetadata - * @return the primitive value depending on the type - * - * @throws IllegalArgumentException - * If a specific value was set in an annotation but it was not - * possible to convert such value in the desired type - */ - private Object resolvePrimitiveValue(Class primitiveClass, - List annotations, AttributeMetadata attributeMetadata) { - - Object retValue = null; - - if (primitiveClass.equals(int.class)) { - - if (!annotations.isEmpty()) { - - retValue = getIntegerValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getInteger(attributeMetadata); - } - - } else if (primitiveClass.equals(long.class)) { - - if (!annotations.isEmpty()) { - - retValue = getLongValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getLong(attributeMetadata); - } - - } else if (primitiveClass.equals(float.class)) { - - if (!annotations.isEmpty()) { - - retValue = getFloatValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getFloat(attributeMetadata); - } - - } else if (primitiveClass.equals(double.class)) { - - if (!annotations.isEmpty()) { - - retValue = getDoubleValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getDouble(attributeMetadata); - } - - } else if (primitiveClass.equals(boolean.class)) { - - if (!annotations.isEmpty()) { - - retValue = getBooleanValueForAnnotation(annotations); - - } - - if (retValue == null) { - retValue = strategy.getBoolean(attributeMetadata); - } - - } else if (primitiveClass.equals(byte.class)) { - - if (!annotations.isEmpty()) { - - retValue = getByteValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getByte(attributeMetadata); - } - - } else if (primitiveClass.equals(short.class)) { - - if (!annotations.isEmpty()) { - - retValue = getShortValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getShort(attributeMetadata); - } - - } else if (primitiveClass.equals(char.class)) { - - if (!annotations.isEmpty()) { - - retValue = getCharacterValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getCharacter(attributeMetadata); - } - - } else { - - throw new IllegalArgumentException( - String.format("%s is unsupported primitive type", - primitiveClass)); - } - - return retValue; - } - - /** - * It returns the boolean value indicated in the annotation. - * - * @param annotations - * The collection of annotations for the annotated attribute - * @return The boolean value indicated in the annotation - */ - private Boolean getBooleanValueForAnnotation(List annotations) { - - Boolean retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamBooleanValue.class.isAssignableFrom(annotation.getClass())) { - PodamBooleanValue localStrategy = (PodamBooleanValue) annotation; - retValue = localStrategy.boolValue(); - - break; - } - - } - - return retValue; - } - - /** - * It returns a random byte if the attribute was annotated with - * {@link PodamByteValue} or {@code null} otherwise - * - * @param annotations - * The list of annotations for this attribute - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return A random byte if the attribute was annotated with - * - * @throws IllegalArgumentException - * If the {@link PodamByteValue#numValue()} value has been set - * and it is not convertible to a byte type - */ - private Byte getByteValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - Byte retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamByteValue.class.isAssignableFrom(annotation.getClass())) { - PodamByteValue intStrategy = (PodamByteValue) annotation; - - String numValueStr = intStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - - retValue = Byte.valueOf(numValueStr); - - } catch (NumberFormatException nfe) { - String errMsg = "The precise value: " - + numValueStr - + " cannot be converted to a byte type. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - } else { - byte minValue = intStrategy.minValue(); - byte maxValue = intStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getByteInRange(minValue, maxValue, - attributeMetadata); - } - - break; - - } - - } - return retValue; - } - - /** - * It returns a random short if the attribute was annotated with - * {@link PodamShortValue} or {@code null} otherwise - * - * @param annotations - * The annotations with which the attribute was annotated - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return A random short if the attribute was annotated with - * {@link PodamShortValue} or {@code null} otherwise - * - * @throws IllegalArgumentException - * If {@link PodamShortValue#numValue()} was set and its value - * could not be converted to a Short type - */ - private Short getShortValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Short retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamShortValue.class.isAssignableFrom(annotation.getClass())) { - PodamShortValue shortStrategy = (PodamShortValue) annotation; - - String numValueStr = shortStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - retValue = Short.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = "The precise value: " - + numValueStr - + " cannot be converted to a short type. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - } else { - - short minValue = shortStrategy.minValue(); - short maxValue = shortStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getShortInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * It creates and returns a random {@link Character} value - * - * @param annotations - * The list of annotations which might customise the return value - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return A random {@link Character} value - */ - private Character getCharacterValueWithinRange( - List annotations, AttributeMetadata attributeMetadata) { - - Character retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamCharValue.class.isAssignableFrom(annotation.getClass())) { - PodamCharValue annotationStrategy = (PodamCharValue) annotation; - - char charValue = annotationStrategy.charValue(); - if (charValue != ' ') { - retValue = charValue; - - } else { - - char minValue = annotationStrategy.minValue(); - char maxValue = annotationStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getCharacterInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * Returns either a customised int value if a {@link PodamIntValue} - * annotation was provided or a random integer if this was not the case - * - * @param annotations - * The list of annotations for the int attribute - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return Either a customised int value if a {@link PodamIntValue} - * annotation was provided or a random integer if this was not the - * case - * - * @throws IllegalArgumentException - * If it was not possible to convert the - * {@link PodamIntValue#numValue()} to an Integer - */ - private Integer getIntegerValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Integer retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamIntValue.class.isAssignableFrom(annotation.getClass())) { - PodamIntValue intStrategy = (PodamIntValue) annotation; - - String numValueStr = intStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - retValue = Integer.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = THE_ANNOTATION_VALUE_STR - + numValueStr - + " could not be converted to an Integer. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - - } - - } else { - - int minValue = intStrategy.minValue(); - int maxValue = intStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getIntegerInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * Returns either a customised float value if a {@link PodamFloatValue} - * annotation was provided or a random float if this was not the case - * - * @param annotations - * The list of annotations for the int attribute - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * - * @return Either a customised float value if a {@link PodamFloatValue} - * annotation was provided or a random float if this was not the - * case - * - * @throws IllegalArgumentException - * If {@link PodamFloatValue#numValue()} contained a value not - * convertible to a Float type - */ - private Float getFloatValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Float retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamFloatValue.class.isAssignableFrom(annotation.getClass())) { - PodamFloatValue floatStrategy = (PodamFloatValue) annotation; - - String numValueStr = floatStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - retValue = Float.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = THE_ANNOTATION_VALUE_STR - + numValueStr - + " could not be converted to a Float. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - } else { - - float minValue = floatStrategy.minValue(); - float maxValue = floatStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getFloatInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * It creates and returns a random {@link Double} value - * - * @param annotations - * The list of annotations which might customise the return value - * - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation * - * - * @return a random {@link Double} value - */ - private Double getDoubleValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Double retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamDoubleValue.class.isAssignableFrom(annotation.getClass())) { - PodamDoubleValue doubleStrategy = (PodamDoubleValue) annotation; - - String numValueStr = doubleStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - - try { - retValue = Double.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = THE_ANNOTATION_VALUE_STR - + numValueStr - + " could not be converted to a Double. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - - } else { - - double minValue = doubleStrategy.minValue(); - double maxValue = doubleStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getDoubleInRange(minValue, maxValue, - attributeMetadata); - } - - break; - - } - - } - return retValue; - - } - - /** - * Returns either a customised long value if a {@link PodamLongValue} - * annotation was provided or a random long if this was not the case - * - * @param annotations - * The list of annotations for the int attribute - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * - * @return Either a customised long value if a {@link PodamLongValue} - * annotation was provided or a random long if this was not the case - * - * @throws IllegalArgumentException - * If it was not possible to convert - * {@link PodamLongValue#numValue()} to a Long - */ - private Long getLongValueWithinRange(List annotations, - AttributeMetadata attributeMetadata) { - - Long retValue = null; - - for (Annotation annotation : annotations) { - - if (PodamLongValue.class.isAssignableFrom(annotation.getClass())) { - PodamLongValue longStrategy = (PodamLongValue) annotation; - - String numValueStr = longStrategy.numValue(); - if (null != numValueStr && !"".equals(numValueStr)) { - try { - retValue = Long.valueOf(numValueStr); - } catch (NumberFormatException nfe) { - String errMsg = THE_ANNOTATION_VALUE_STR - + numValueStr - + " could not be converted to a Long. An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg, nfe); - } - } else { - - long minValue = longStrategy.minValue(); - long maxValue = longStrategy.maxValue(); - - // Sanity check - if (minValue > maxValue) { - maxValue = minValue; - } - - retValue = strategy.getLongInRange(minValue, maxValue, - attributeMetadata); - - } - - break; - - } - - } - return retValue; - } - - /** - * It attempts to resolve the given class as a wrapper class and if this is - * the case it assigns a random value - * - * - * @param candidateWrapperClass - * The class which might be a wrapper class - * @param attributeMetadata - * The attribute's metadata, if any, used for customisation - * @return {@code null} if this is not a wrapper class, otherwise an Object - * with the value for the wrapper class - */ - private Object resolveWrapperValue(Class candidateWrapperClass, - List annotations, AttributeMetadata attributeMetadata) { - - Object retValue = null; - - if (candidateWrapperClass.equals(Integer.class)) { - - if (!annotations.isEmpty()) { - - retValue = getIntegerValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getInteger(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Long.class)) { - - if (!annotations.isEmpty()) { - - retValue = getLongValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getLong(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Float.class)) { - - if (!annotations.isEmpty()) { - - retValue = getFloatValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getFloat(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Double.class)) { - - if (!annotations.isEmpty()) { - - retValue = getDoubleValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getDouble(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Boolean.class)) { - - if (!annotations.isEmpty()) { - - retValue = getBooleanValueForAnnotation(annotations); - - } - - if (retValue == null) { - retValue = strategy.getBoolean(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Byte.class)) { - - if (!annotations.isEmpty()) { - - retValue = getByteValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getByte(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Short.class)) { - - if (!annotations.isEmpty()) { - - retValue = getShortValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getShort(attributeMetadata); - } - - } else if (candidateWrapperClass.equals(Character.class)) { - - if (!annotations.isEmpty()) { - - retValue = getCharacterValueWithinRange(annotations, - attributeMetadata); - - } - - if (retValue == null) { - retValue = strategy.getCharacter(attributeMetadata); - } - - } - - return retValue; - } - - /** - * It creates and returns an instance of the given class if at least one of - * its constructors has been annotated with {@link PodamConstructor} - * - * @param - * The type of the instance to return - * - * @param pojoClass - * The class of which an instance is required - * @param pojos - * How many instances of the same class have been created so far - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return an instance of the given class if at least one of its - * constructors has been annotated with {@link PodamConstructor} - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - @SuppressWarnings({ UNCHECKED_STR }) - private T instantiatePojo(Class pojoClass, - Map, Integer> pojos, Type... genericTypeArgs) - throws SecurityException { - - T retValue = null; - - Constructor[] constructors = pojoClass.getConstructors(); - if (constructors.length == 0 || Modifier.isAbstract(pojoClass.getModifiers())) { - /* No public constructors, we will try static factory methods */ - try { - retValue = (T) instantiatePojoWithoutConstructors( - pojoClass, pojos, genericTypeArgs); - } catch (Exception e) { - LOG.debug("We couldn't create an instance for pojo: " - + pojoClass + " with factory methods, will " - + " try non-public constructors.", e); - } - - /* Then non-public constructors */ - if (retValue == null) { - constructors = pojoClass.getDeclaredConstructors(); - } - } - - if (retValue == null && constructors.length > 0) { - - /* We want constructor with minumum number of parameters - * to speed up the creation */ - strategy.sort(constructors); - - for (Constructor constructor : constructors) { - - try { - Object[] parameterValues = getParameterValuesForConstructor( - constructor, pojoClass, pojos, genericTypeArgs); - - // Being a generic method we cannot be sure on the identity of - // T, therefore the mismatch between the newInstance() return - // value (Object) and T is acceptable, thus the SuppressWarning - // annotation - - // Security hack - if (!constructor.isAccessible()) { - constructor.setAccessible(true); - } - retValue = (T) constructor.newInstance(parameterValues); - if (retValue != null) { - LOG.debug("We could create an instance with constructor: " - + constructor); - break; - } - } catch (Exception e) { - LOG.debug("We couldn't create an instance for pojo: {} with" - + " constructor: {}. Will try with another one.", - pojoClass, constructor, e); - } - } - } - - if (retValue == null) { - retValue = externalFactory.manufacturePojo(pojoClass, genericTypeArgs); - } - return retValue; - } - - /** - * Generic method which returns an instance of the given class filled with - * values dictated by the strategy - * - * @param - * The type for which a filled instance is required - * - * @param pojoClass - * The name of the class for which an instance filled with values - * is required - * @param pojos - * How many times {@code pojoClass} has been found. This will be - * used for reentrant objects - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return An instance of filled with dummy values - * @throws ClassNotFoundException - * @throws InvocationTargetException - * @throws IllegalAccessException - * @throws InstantiationException - * - * @throws PodamMockeryException - * if a problem occurred while creating a POJO instance or while - * setting its state - */ - @SuppressWarnings(UNCHECKED_STR) - private T manufacturePojoInternal(Class pojoClass, - Map, Integer> pojos, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - LOG.debug("Manufacturing {} with parameters {}", - pojoClass, Arrays.toString(genericTypeArgs)); - - T retValue = null; - - // reuse object from memoization table - if (strategy.isMemoizationEnabled()) { - T objectToReuse = (T) memoizationTable.get(pojoClass); - if (objectToReuse != null) { - return objectToReuse; - } - } - - if (pojoClass.isPrimitive()) { - // For JDK POJOs we can't retrieve attribute name - List annotations = new ArrayList(); - String noName = null; - return (T) resolvePrimitiveValue(pojoClass, annotations, - new AttributeMetadata(noName, pojoClass, annotations, pojoClass)); - } - - if (pojoClass.isInterface() - || Modifier.isAbstract(pojoClass.getModifiers())) { - Class specificClass = (Class) strategy - .getSpecificClass(pojoClass); - if (!specificClass.equals(pojoClass)) { - return this.manufacturePojoInternal(specificClass, pojos, - genericTypeArgs); - } else { - if (specificClass.isInterface()) { - return externalFactory.manufacturePojo(pojoClass, - genericTypeArgs); - } - } - } - - try { - - retValue = instantiatePojo(pojoClass, pojos, genericTypeArgs); - } catch (SecurityException e) { - throw new PodamMockeryException( - "Security exception while applying introspection.", e); - } - - // update memoization table with new object - // the reference is stored before properties are set so that recursive - // properties can use it - if (strategy.isMemoizationEnabled()) { - memoizationTable.put(pojoClass, retValue); - } - - /* Construction failed, no point to continue */ - if (retValue == null) { - return null; - } - - if (retValue instanceof Collection && ((Collection)retValue).size() == 0) { - fillCollection((Collection)retValue, pojos, genericTypeArgs); - } else if (retValue instanceof Map && ((Map)retValue).size() == 0) { - fillMap((Map)retValue, pojos, genericTypeArgs); - } - - Class[] parameterTypes = null; - Class attributeType = null; - - ClassInfo classInfo = PodamUtils.getClassInfo(pojoClass, - strategy.getExcludedAnnotations()); - - // According to JavaBeans standards, setters should have only - // one argument - Object setterArg = null; - for (Method setter : classInfo.getClassSetters()) { - - List pojoAttributeAnnotations = retrieveFieldAnnotations( - pojoClass, setter); - - String attributeName = PodamUtils - .extractFieldNameFromSetterMethod(setter); - - parameterTypes = setter.getParameterTypes(); - if (parameterTypes.length != 1) { - LOG.warn("Skipping setter with non-single arguments {}", - setter); - continue; - } - - // A class which has got an attribute to itself (e.g. - // recursive hierarchies) - attributeType = parameterTypes[0]; - - // If an attribute has been annotated with - // PodamAttributeStrategy, it takes the precedence over any - // other strategy. Additionally we don't pass the attribute - // metadata for value customisation; if user went to the extent - // of specifying a PodamAttributeStrategy annotation for an - // attribute they are already customising the value assigned to - // that attribute. - - PodamStrategyValue attributeStrategyAnnotation = containsAttributeStrategyAnnotation(pojoAttributeAnnotations); - if (null != attributeStrategyAnnotation) { - - AttributeStrategy attributeStrategy = attributeStrategyAnnotation - .value().newInstance(); - - if (LOG.isDebugEnabled()) { - LOG.debug("The attribute: " + attributeName - + " will be filled using the following strategy: " - + attributeStrategy); - } - - setterArg = returnAttributeDataStrategyValue(attributeType, - attributeStrategy); - - } else { - - final Map typeArgsMap = new HashMap(); - - Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, - pojoClass, genericTypeArgs); - if (genericTypeArgsExtra != null) { - LOG.warn("Lost generic type arguments {}", - Arrays.toString(genericTypeArgsExtra)); - } - - Type[] typeArguments = NO_TYPES; - // If the parameter is a generic parameterized type resolve - // the actual type arguments - if (setter.getGenericParameterTypes()[0] instanceof ParameterizedType) { - final ParameterizedType attributeParameterizedType = (ParameterizedType) setter - .getGenericParameterTypes()[0]; - typeArguments = attributeParameterizedType - .getActualTypeArguments(); - } else if (setter.getGenericParameterTypes()[0] instanceof TypeVariable) { - final TypeVariable typeVariable = (TypeVariable) setter - .getGenericParameterTypes()[0]; - Type type = typeArgsMap.get(typeVariable.getName()); - if (type instanceof ParameterizedType) { - final ParameterizedType attributeParameterizedType = (ParameterizedType) type; - - typeArguments = attributeParameterizedType - .getActualTypeArguments(); - attributeType = (Class) attributeParameterizedType - .getRawType(); - } else { - attributeType = (Class) type; - } - } - AtomicReference typeGenericTypeArgs - = new AtomicReference(NO_TYPES); - for (int i = 0; i < typeArguments.length; i++) { - if (typeArguments[i] instanceof TypeVariable) { - Class resolvedType = resolveGenericParameter(typeArguments[i], - typeArgsMap, typeGenericTypeArgs); - if (!Collection.class.isAssignableFrom(resolvedType) && !Map.class.isAssignableFrom(resolvedType)) { - typeArguments[i] = resolvedType; - } - } - } - - setterArg = manufactureAttributeValue(retValue, pojos, - attributeType, setter.getGenericParameterTypes()[0], - pojoAttributeAnnotations, attributeName, - typeArgsMap, typeArguments); - if (null == setterArg) { - setterArg = externalFactory.manufacturePojo(attributeType); - } - } - - if (setterArg != null) { - try { - setter.invoke(retValue, setterArg); - } catch(IllegalAccessException e) { - LOG.warn("{} is not accessible. Setting it to accessible." - + " However this is a security hack and your code" - + " should really adhere to JavaBeans standards.", - setter.toString()); - setter.setAccessible(true); - setter.invoke(retValue, setterArg); - } - } else { - LOG.warn("Couldn't find a suitable value for attribute {}[{}]" - + ". It will be left to null.", - pojoClass, attributeType); - } - - } - - return retValue; - - } - - /** - * It manufactures and returns the value for a POJO method parameter. - * - * - * @param pojos - * Set of manufactured pojos' types - * @param parameterType - * The type of the attribute for which a value is being - * manufactured - * @param genericType - * The generic type of the attribute for which a value is being - * manufactured - * @param annotations - * The annotations for the attribute being considered - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return The value for a parameter - * - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * @throws IllegalArgumentException - *
    - *
  • If an illegal argument was passed
  • - *
  • If an invalid value was set for a precise value in an - * annotation and such value could not be converted to the - * desired type
  • - *
- * - */ - private Object manufactureParameterValue(Map, Integer> pojos, - Class parameterType, Type genericType, - List annotations, Map typeArgsMap, - Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - String attributeName = null; - - return manufactureAttributeValue(Object.class, pojos, parameterType, - genericType, annotations, attributeName, typeArgsMap, - genericTypeArgs); - } - - /** - * It manufactures and returns the value for a POJO attribute. - * - * - * @param pojo - * The POJO being filled with values - * @param pojos - * Set of manufactured pojos' types - * @param attributeType - * The type of the attribute for which a value is being - * manufactured - * @param genericAttributeType - * The generic type of the attribute for which a value is being - * manufactured - * @param annotations - * The annotations for the attribute being considered - * @param attributeName - * The attribute name - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return The value for an attribute - * - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * @throws IllegalArgumentException - *
    - *
  • If an illegal argument was passed
  • - *
  • If an invalid value was set for a precise value in an - * annotation and such value could not be converted to the - * desired type
  • - *
- * - */ - private Object manufactureAttributeValue(Object pojo, - Map, Integer> pojos, Class attributeType, - Type genericAttributeType, List annotations, - String attributeName, Map typeArgsMap, - Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - Object attributeValue = null; - - Class realAttributeType; - if (Object.class.equals(attributeType) && attributeType != genericAttributeType) { - AtomicReference elementGenericTypeArgs - = new AtomicReference(NO_TYPES); - realAttributeType = resolveGenericParameter(genericAttributeType, - typeArgsMap, elementGenericTypeArgs); - } else { - realAttributeType = attributeType; - } - AttributeMetadata attributeMetadata = new AttributeMetadata( - attributeName, realAttributeType, annotations, pojo.getClass()); - - // Primitive type - if (realAttributeType.isPrimitive()) { - - attributeValue = resolvePrimitiveValue(realAttributeType, - annotations, attributeMetadata); - - // Wrapper type - } else if (isWrapper(realAttributeType)) { - - attributeValue = resolveWrapperValue(realAttributeType, - annotations, attributeMetadata); - - // String type - } else if (realAttributeType.equals(String.class)) { - - attributeValue = resolveStringValue(annotations, attributeMetadata); - - } else if (realAttributeType.isArray()) { - - // Array type - - attributeValue = resolveArrayElementValue(realAttributeType, - genericAttributeType, pojos, annotations, pojo, - attributeName, typeArgsMap); - - // Otherwise it's a different type of Object (including - // the Object class) - } else if (Collection.class.isAssignableFrom(realAttributeType)) { - - attributeValue = resolveCollectionValueWhenCollectionIsPojoAttribute( - pojo, pojos, realAttributeType, attributeName, - annotations, typeArgsMap, genericTypeArgs); - - } else if (Map.class.isAssignableFrom(realAttributeType)) { - - attributeValue = resolveMapValueWhenMapIsPojoAttribute(pojo, - pojos, realAttributeType, attributeName, annotations, - typeArgsMap, genericTypeArgs); - - } else if (realAttributeType.isEnum()) { - - // Enum type - int enumConstantsLength = realAttributeType.getEnumConstants().length; - - if (enumConstantsLength > 0) { - int enumIndex = strategy.getIntegerInRange(0, - enumConstantsLength, attributeMetadata) - % enumConstantsLength; - attributeValue = realAttributeType.getEnumConstants()[enumIndex]; - } - - } else if (Type.class.isAssignableFrom(realAttributeType)) { - - Type paremeterType = null; - if (genericAttributeType instanceof ParameterizedType) { - ParameterizedType parametrized = (ParameterizedType) genericAttributeType; - Type[] arguments = parametrized.getActualTypeArguments(); - if (arguments.length > 0) { - paremeterType = arguments[0]; - } - } else if (realAttributeType.getTypeParameters().length > 0) { - paremeterType = realAttributeType.getTypeParameters()[0]; - } - - if (paremeterType != null) { - AtomicReference elementGenericTypeArgs - = new AtomicReference(NO_TYPES); - attributeValue = resolveGenericParameter(paremeterType, - typeArgsMap, elementGenericTypeArgs); - } else { - LOG.error("{} is missing generic type argument, supplied {} {}", - genericAttributeType, typeArgsMap, - Arrays.toString(genericTypeArgs)); - } - - } - - // For any other type, we use the PODAM strategy - if (attributeValue == null) { - - TypeVariable[] typeParams = attributeType.getTypeParameters(); - Type[] genericTypeArgsAll = mergeActualAndSuppliedGenericTypes( - typeParams, genericTypeArgs, typeArgsMap); - - Integer depth = pojos.get(realAttributeType); - if (depth == null) { - depth = -1; - } - if (depth <= strategy.getMaxDepth(pojo.getClass())) { - - pojos.put(realAttributeType, depth + 1); - attributeValue = this.manufacturePojoInternal( - realAttributeType, pojos, genericTypeArgsAll); - pojos.put(realAttributeType, depth); - - } else { - - LOG.warn("Loop in {} production detected.", - realAttributeType); - attributeValue = externalFactory.manufacturePojo( - realAttributeType, genericTypeArgsAll); - - } - } - - return attributeValue; - } - - /** - * Utility to merge actual types with supplied array of generic type - * substitutions - * - * @param actualTypes - * an array of types used for field or POJO declaration - * @param suppliedTypes - * an array of supplied types for generic type substitution - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @return An array of merged actual and supplied types with generic types - * resolved - */ - private Type[] mergeActualAndSuppliedGenericTypes( - TypeVariable[] actualTypes, Type[] suppliedTypes, - Map typeArgsMap) { - - List resolvedTypes = new ArrayList(); - List substitutionTypes = new ArrayList(Arrays.asList(suppliedTypes)); - for (int i = 0; i < actualTypes.length; i++) { - Type type = typeArgsMap.get(actualTypes[i].getName()); - if (type != null) { - resolvedTypes.add(type); - if (!substitutionTypes.isEmpty() && substitutionTypes.get(0).equals(type)) { - substitutionTypes.remove(0); - } - } - } - Type[] resolved = resolvedTypes.toArray(new Type[resolvedTypes.size()]); - Type[] supplied = substitutionTypes.toArray(new Type[substitutionTypes.size()]); - return mergeTypeArrays(resolved, supplied); - } - - /** - * It creates and returns a String value, eventually customised by - * annotations - * - * @param annotations - * The list of annotations used to customise the String value, if - * any - * @param attributeMetadata - * @return a String value, eventually customised by annotations - * @throws IllegalAccessException - * If an exception occurred while creating an instance of the - * strategy - * @throws InstantiationException - * If an exception occurred while creating an instance of the - * strategy - * - * @throws IllegalArgumentException - * If {@link PodamStrategyValue} was specified but the type was - * not correct for the attribute being set - */ - private String resolveStringValue(List annotations, - AttributeMetadata attributeMetadata) throws InstantiationException, - IllegalAccessException { - - String retValue = null; - - if (annotations == null || annotations.isEmpty()) { - - retValue = strategy.getStringValue(attributeMetadata); - - } else { - - for (Annotation annotation : annotations) { - - if (!PodamStringValue.class.isAssignableFrom(annotation - .getClass())) { - continue; - } - - // A specific value takes precedence over the length - PodamStringValue podamAnnotation = (PodamStringValue) annotation; - - if (podamAnnotation.strValue() != null - && podamAnnotation.strValue().length() > 0) { - - retValue = podamAnnotation.strValue(); - - } else { - - retValue = strategy.getStringOfLength( - podamAnnotation.length(), attributeMetadata); - - } - - } - - if (retValue == null) { - retValue = strategy.getStringValue(attributeMetadata); - } - - } - - return retValue; - } - - /** - * It returns an default value for a {@link Field} matching the attribute - * name or null if a field was not found. - * - * @param pojoClass - * The class supposed to contain the field - * @param attributeName - * The field name - * - * @return an instance of {@link Field} matching the attribute name or - * null if a field was not found. - */ - private T getDefaultFieldValue(Object pojo, String attributeName) { - T retValue = null; - - try { - Field field = getField(pojo.getClass(), attributeName); - - if (field != null) { - - // It allows to invoke Field.get on private fields - field.setAccessible(true); - - @SuppressWarnings(UNCHECKED_STR) - T t = (T) field.get(pojo); - retValue = t; - } else { - - LOG.info("The field {}[{}] didn't exist.", pojo.getClass(), attributeName); - } - - } catch (Exception e) { - - LOG.warn("We couldn't get default value for {}[{}]", - pojo.getClass(), attributeName, e); - } - - return retValue; - } - - /** - * It returns a {@link Field} matching the attribute name or null if a field - * was not found. - * - * @param pojoClass - * The class supposed to contain the field - * @param attributeName - * The field name - * - * @return a {@link Field} matching the attribute name or null if a field - * was not found. - */ - private Field getField(Class pojoClass, String attributeName) { - - Field field = null; - - Class clazz = pojoClass; - - while (clazz != null) { - try { - field = clazz.getDeclaredField(attributeName); - break; - } catch (NoSuchFieldException e) { - clazz = clazz.getSuperclass(); - } - } - if (field == null) { - LOG.warn("A field could not be found for attribute '{}[{}]'", - pojoClass, attributeName); - } - return field; - } - - /** - * It returns a {@link PodamStrategyValue} if one was specified, or - * {@code null} otherwise. - * - * @param annotations - * The list of annotations - * @return {@code true} if the list of annotations contains at least one - * {@link PodamStrategyValue} annotation. - */ - private PodamStrategyValue containsAttributeStrategyAnnotation( - List annotations) { - PodamStrategyValue retValue = null; - - for (Annotation annotation : annotations) { - if (PodamStrategyValue.class - .isAssignableFrom(annotation.getClass())) { - retValue = (PodamStrategyValue) annotation; - break; - } - } - - return retValue; - } - - /** - * It returns {@code true} if this class is a wrapper class, {@code false} - * otherwise - * - * @param candidateWrapperClass - * The class to check - * @return {@code true} if this class is a wrapper class, {@code false} - * otherwise - */ - private boolean isWrapper(Class candidateWrapperClass) { - - return candidateWrapperClass.equals(Byte.class) ? true - : candidateWrapperClass.equals(Boolean.class) ? true - : candidateWrapperClass.equals(Character.class) ? true - : candidateWrapperClass.equals(Short.class) ? true - : candidateWrapperClass - .equals(Integer.class) ? true - : candidateWrapperClass - .equals(Long.class) ? true - : candidateWrapperClass - .equals(Float.class) ? true - : candidateWrapperClass - .equals(Double.class) ? true - : false; - } - - /** - * Given the original class and the setter method, it returns all - * annotations for the field or an empty collection if no custom annotations - * were found on the field - * - * @param clazz - * The class containing the annotated attribute - * @param setter - * The setter method - * @return all annotations for the field - * @throws NoSuchFieldException - * If the field could not be found - * @throws SecurityException - * if a security exception occurred - */ - private List retrieveFieldAnnotations(Class clazz, - Method setter) { - - List retValue = new ArrayList(); - - // Checks if the field has got any custom annotations - String attributeName = PodamUtils - .extractFieldNameFromSetterMethod(setter); - Field setterField = getField(clazz, attributeName); - - if (setterField != null) { - Annotation[] annotations = setterField.getAnnotations(); - - if (annotations != null && annotations.length != 0) { - retValue = Arrays.asList(annotations); - } - } - - return retValue; - - } - - /** - * It returns a collection of some sort with some data in it. - * - * - * @param pojoClass - * The POJO being analysed - * @param pojos - * Set of manufactured pojos' types - * @param collectionType - * The type of the attribute being evaluated - * @param annotations - * The set of annotations for the annotated attribute. It might - * be empty - * @param attributeName - * The name of the field being set - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return a collection of some sort with some data in it - * @throws PodamMockeryException - * An exception occurred while resolving the collection - * @throws IllegalArgumentException - * If the field name is null or empty - */ - private Collection resolveCollectionValueWhenCollectionIsPojoAttribute( - Object pojo, Map, Integer> pojos, - Class collectionType, String attributeName, - List annotations, Map typeArgsMap, - Type... genericTypeArgs) { - - // This needs to be generic because collections can be of any type - Collection retValue = null; - if (null != pojo && null != attributeName) { - - retValue = getDefaultFieldValue(pojo, attributeName); - } - - retValue = resolveCollectionType(collectionType, retValue); - - if (null == retValue) { - return null; - } - - try { - - Class typeClass = null; - - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericTypeArgs == null || genericTypeArgs.length == 0) { - - LOG.warn("The collection attribute: " - + attributeName - + " does not have a type. We will assume Object for you"); - // Support for non-generified collections - typeClass = Object.class; - - } else { - Type actualTypeArgument = genericTypeArgs[0]; - - typeClass = resolveGenericParameter(actualTypeArgument, - typeArgsMap, elementGenericTypeArgs); - } - - fillCollection(pojos, annotations, retValue, typeClass, - elementGenericTypeArgs.get()); - - } catch (SecurityException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (IllegalArgumentException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (InstantiationException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (IllegalAccessException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (ClassNotFoundException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } catch (InvocationTargetException e) { - throw new PodamMockeryException(RESOLVING_COLLECTION_EXCEPTION_STR, - e); - } - - return retValue; - } - - /** - * It fills a collection with the required number of elements of the - * required type. - * - *

- * This method has a so-called side effect. It updates the collection passed - * as argument. - *

- * - * @param collection - * The Collection to be filled - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * - */ - private void fillCollection(Collection collection, - Map, Integer> pojos, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - final Map typeArgsMap = new HashMap(); - Class collectionClass = collection.getClass(); - Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, - collectionClass, genericTypeArgs); - - Annotation[] annotations = collection.getClass().getAnnotations(); - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - Type[] typeParams = collectionClass.getTypeParameters(); - while (typeParams.length < 1) { - Type type = collectionClass.getGenericSuperclass(); - collectionClass = resolveGenericParameter(type, typeArgsMap, - elementGenericTypeArgs); - typeParams = elementGenericTypeArgs.get(); - } - Class elementTypeClass = resolveGenericParameter(typeParams[0], - typeArgsMap, elementGenericTypeArgs); - Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), - genericTypeArgsExtra); - fillCollection(pojos, Arrays.asList(annotations), - collection, elementTypeClass, elementGenericArgs); - } - - /** - * It fills a collection with the required number of elements of the - * required type. - * - *

- * This method has a so-called side effect. It updates the collection passed - * as argument. - *

- * - * @param pojos - * Set of manufactured pojos' types - * @param annotations - * The annotations for this attribute - * @param collection - * The Collection to be filled - * @param collectionElementType - * The type of the collection element - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * - */ - private void fillCollection(Map, Integer> pojos, - List annotations, Collection collection, - Class collectionElementType, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - // If the user defined a strategy to fill the collection elements, - // we use it - PodamCollection collectionAnnotation = null; - AttributeStrategy elementStrategy = null; - for (Annotation annotation : annotations) { - if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { - collectionAnnotation = (PodamCollection) annotation; - break; - } - - } - - int nbrElements; - - if (null != collectionAnnotation) { - - nbrElements = collectionAnnotation.nbrElements(); - elementStrategy = collectionAnnotation.collectionElementStrategy() - .newInstance(); - } else { - - nbrElements = strategy - .getNumberOfCollectionElements(collectionElementType); - } - - try { - if (collection.size() > nbrElements) { - - collection.clear(); - } - - for (int i = collection.size(); i < nbrElements; i++) { - - // The default - Object element; - if (null != elementStrategy - && ObjectStrategy.class.isAssignableFrom(elementStrategy - .getClass()) - && Object.class.equals(collectionElementType)) { - LOG.debug("Element strategy is ObjectStrategy and collection element is of type Object: using the ObjectStrategy strategy"); - element = elementStrategy.getValue(); - } else if (null != elementStrategy - && !ObjectStrategy.class.isAssignableFrom(elementStrategy - .getClass())) { - LOG.debug("Collection elements will be filled using the following strategy: " - + elementStrategy); - element = returnAttributeDataStrategyValue( - collectionElementType, elementStrategy); - } else { - Map nullTypeArgsMap = new HashMap(); - element = manufactureParameterValue(pojos, - collectionElementType, collectionElementType, - annotations, nullTypeArgsMap, genericTypeArgs); - } - collection.add(element); - } - } catch (UnsupportedOperationException e) { - - LOG.warn("Cannot fill immutable collection {}", collection.getClass()); - } - } - - /** - * It manufactures and returns a Map with at least one element in it - * - * @param pojoClass - * The POJO being initialised - * @param pojos - * Set of manufactured pojos' types - * @param attributeType - * The type of the POJO map attribute - * @param attributeName - * The POJO attribute name - * @param annotations - * The annotations specified for this attribute - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @return Map with at least one element in it - * - * @throws IllegalArgumentException - *
    - *
  • If the attribute name is null or empty
  • - *
  • If the array of types of the Map has length different - * from 2
  • - *
- * - * @throws PodamMockeryException - * If an error occurred while creating the Map object - */ - private Map resolveMapValueWhenMapIsPojoAttribute( - Object pojo, Map, Integer> pojos, - Class attributeType, String attributeName, - List annotations, Map typeArgsMap, - Type... genericTypeArgs) { - - Map retValue = null; - if (null != pojo && null != attributeName) { - - retValue = getDefaultFieldValue(pojo, attributeName); - } - - retValue = resolveMapType(attributeType, retValue); - - if (null == retValue) { - return null; - } - - try { - - Class keyClass = null; - - Class elementClass = null; - - AtomicReference keyGenericTypeArgs = new AtomicReference( - NO_TYPES); - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericTypeArgs == null || genericTypeArgs.length == 0) { - - LOG.warn("Map attribute: " - + attributeName - + " is non-generic. We will assume a Map for you."); - - keyClass = Object.class; - - elementClass = Object.class; - - } else { - - // Expected only key, value type - if (genericTypeArgs.length != 2) { - throw new IllegalStateException( - "In a Map only key value generic type are expected."); - } - - Type[] actualTypeArguments = genericTypeArgs; - keyClass = resolveGenericParameter(actualTypeArguments[0], - typeArgsMap, keyGenericTypeArgs); - elementClass = resolveGenericParameter(actualTypeArguments[1], - typeArgsMap, elementGenericTypeArgs); - } - - MapArguments mapArguments = new MapArguments(); - mapArguments.setPojos(pojos); - mapArguments.setAnnotations(annotations); - mapArguments.setMapToBeFilled(retValue); - mapArguments.setKeyClass(keyClass); - mapArguments.setElementClass(elementClass); - mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); - mapArguments - .setElementGenericTypeArgs(elementGenericTypeArgs.get()); - - fillMap(mapArguments); - - } catch (InstantiationException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } catch (IllegalAccessException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } catch (SecurityException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } catch (ClassNotFoundException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } catch (InvocationTargetException e) { - throw new PodamMockeryException(MAP_CREATION_EXCEPTION_STR, e); - } - - return retValue; - } - - /** - * It fills a Map with the required number of elements of the required type. - * - *

- * This method has a so-called side-effect. It updates the Map given as - * argument. - *

- * - * @param pojoClass - * The POJO being initialised - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * - */ - private void fillMap(Map map, - Map, Integer> pojos, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - final Map typeArgsMap = new HashMap(); - Class pojoClass = map.getClass(); - Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, - pojoClass, genericTypeArgs); - - Class mapClass = pojoClass; - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - Type[] typeParams = mapClass.getTypeParameters(); - while (typeParams.length < 2) { - Type type = mapClass.getGenericSuperclass(); - mapClass = resolveGenericParameter(type, typeArgsMap, elementGenericTypeArgs); - typeParams = elementGenericTypeArgs.get(); - } - AtomicReference keyGenericTypeArgs = new AtomicReference( - NO_TYPES); - Class keyClass = resolveGenericParameter(typeParams[0], - typeArgsMap, keyGenericTypeArgs); - Class elementClass = resolveGenericParameter(typeParams[1], - typeArgsMap, elementGenericTypeArgs); - - Type[] keyGenericArgs = mergeTypeArrays(keyGenericTypeArgs.get(), - genericTypeArgsExtra); - Type[] elementGenericArgs = mergeTypeArrays(elementGenericTypeArgs.get(), - genericTypeArgsExtra); - - MapArguments mapArguments = new MapArguments(); - mapArguments.setPojos(pojos); - mapArguments.setAnnotations(Arrays.asList(pojoClass.getAnnotations())); - mapArguments.setMapToBeFilled(map); - mapArguments.setKeyClass(keyClass); - mapArguments.setElementClass(elementClass); - mapArguments.setKeyGenericTypeArgs(keyGenericArgs); - mapArguments.setElementGenericTypeArgs(elementGenericArgs); - - fillMap(mapArguments); - } - - /** - * It fills a Map with the required number of elements of the required type. - * - *

- * This method has a so-called side-effect. It updates the Map given as - * argument. - *

- * - * @param mapArguments - * The arguments POJO - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - * - */ - private void fillMap(MapArguments mapArguments) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - // If the user defined a strategy to fill the collection elements, - // we use it - PodamCollection collectionAnnotation = null; - AttributeStrategy keyStrategy = null; - AttributeStrategy elementStrategy = null; - for (Annotation annotation : mapArguments.getAnnotations()) { - if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { - collectionAnnotation = (PodamCollection) annotation; - break; - } - } - - int nbrElements; - - if (null != collectionAnnotation) { - - nbrElements = collectionAnnotation.nbrElements(); - keyStrategy = collectionAnnotation.mapKeyStrategy().newInstance(); - elementStrategy = collectionAnnotation.mapElementStrategy() - .newInstance(); - } else { - - nbrElements = strategy.getNumberOfCollectionElements(mapArguments - .getElementClass()); - } - - Map map = mapArguments.getMapToBeFilled(); - try { - if (map.size() > nbrElements) { - - map.clear(); - } - - for (int i = map.size(); i < nbrElements; i++) { - - Object keyValue = null; - - Object elementValue = null; - - @SuppressWarnings(UNCHECKED_STR) - Class> mapType = - (Class>) mapArguments.getMapToBeFilled().getClass(); - - MapKeyOrElementsArguments valueArguments = new MapKeyOrElementsArguments(); - valueArguments.setPojoClass(mapType); - valueArguments.setPojos(mapArguments.getPojos()); - valueArguments.setAnnotations(mapArguments.getAnnotations()); - valueArguments.setKeyOrValueType(mapArguments.getKeyClass()); - valueArguments.setElementStrategy(keyStrategy); - valueArguments.setGenericTypeArgs(mapArguments - .getKeyGenericTypeArgs()); - - keyValue = getMapKeyOrElementValue(valueArguments); - - valueArguments = new MapKeyOrElementsArguments(); - valueArguments.setPojoClass(mapType); - valueArguments.setPojos(mapArguments.getPojos()); - valueArguments.setAnnotations(mapArguments.getAnnotations()); - valueArguments.setKeyOrValueType(mapArguments.getElementClass()); - valueArguments.setElementStrategy(elementStrategy); - valueArguments.setGenericTypeArgs(mapArguments - .getElementGenericTypeArgs()); - - elementValue = getMapKeyOrElementValue(valueArguments); - - /* ConcurrentHashMap doesn't allow null values */ - if (elementValue != null || !(map instanceof ConcurrentHashMap)) { - map.put(keyValue, elementValue); - } - } - } catch (UnsupportedOperationException e) { - - LOG.warn("Cannot fill immutable map {}", map.getClass()); - } - } - - /** - * It fills a Map key or value with the appropriate value, considering - * attribute-level customisation. - * - * @param keyOrElementsArguments - * The arguments POJO - * @return A Map key or value - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws IllegalArgumentException - *
    - *
  • If an illegal argument was passed
  • - *
  • If an invalid value was set for a precise value in an - * annotation and such value could not be converted to the - * desired type
  • - *
- */ - private Object getMapKeyOrElementValue( - MapKeyOrElementsArguments keyOrElementsArguments) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - Object retValue = null; - - if (null != keyOrElementsArguments.getElementStrategy() - && ObjectStrategy.class.isAssignableFrom(keyOrElementsArguments - .getElementStrategy().getClass()) - && Object.class.equals(keyOrElementsArguments - .getKeyOrValueType())) { - LOG.debug("Element strategy is ObjectStrategy and Map key or value type is of type Object: using the ObjectStrategy strategy"); - retValue = keyOrElementsArguments.getElementStrategy().getValue(); - } else if (null != keyOrElementsArguments.getElementStrategy() - && !ObjectStrategy.class - .isAssignableFrom(keyOrElementsArguments - .getElementStrategy().getClass())) { - LOG.debug("Map key or value will be filled using the following strategy: " - + keyOrElementsArguments.getElementStrategy()); - retValue = returnAttributeDataStrategyValue( - keyOrElementsArguments.getKeyOrValueType(), - keyOrElementsArguments.getElementStrategy()); - - } else { - - Map nullTypeArgsMap = new HashMap(); - retValue = manufactureParameterValue( - keyOrElementsArguments.getPojos(), - keyOrElementsArguments.getKeyOrValueType(), - keyOrElementsArguments.getKeyOrValueType(), - keyOrElementsArguments.getAnnotations(), - nullTypeArgsMap, - keyOrElementsArguments.getGenericTypeArgs()); - } - return retValue; - } - - /** - * It returns an Array with the first element set - * - * - * @param attributeType - * The array type - * @param genericAttributeType - * The array generic type - * @param pojos - * Set of manufactured pojos' types - * @param annotations - * The annotations to be considered - * @param pojo - * POJO containing attribute - * @param attributeName - * @param typeArgsMap - * a map relating the generic class arguments ("" for - * example) with their actual types - * @return Array with the first element set - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - private Object resolveArrayElementValue(Class attributeType, - Type genericType, Map, Integer> pojos, - List annotations, Object pojo, String attributeName, - Map typeArgsMap) throws InstantiationException, - IllegalAccessException, InvocationTargetException, - ClassNotFoundException { - - Class componentType = null; - AtomicReference genericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericType instanceof GenericArrayType) { - Type genericComponentType = ((GenericArrayType) genericType).getGenericComponentType(); - if (genericComponentType instanceof TypeVariable) { - TypeVariable componentTypeVariable - = (TypeVariable) genericComponentType; - final Type resolvedType - = typeArgsMap.get(componentTypeVariable.getName()); - componentType - = resolveGenericParameter(resolvedType, typeArgsMap, - genericTypeArgs); - } - } - if (componentType == null) { - componentType = attributeType.getComponentType(); - } - - // If the user defined a strategy to fill the collection elements, - // we use it - PodamCollection collectionAnnotation = null; - AttributeStrategy elementStrategy = null; - for (Annotation annotation : annotations) { - if (PodamCollection.class.isAssignableFrom(annotation.getClass())) { - collectionAnnotation = (PodamCollection) annotation; - break; - } - - } - - int nbrElements; - if (null != collectionAnnotation) { - - nbrElements = collectionAnnotation.nbrElements(); - elementStrategy = collectionAnnotation.collectionElementStrategy() - .newInstance(); - } else { - - nbrElements = strategy.getNumberOfCollectionElements(attributeType); - } - - Object arrayElement = null; - Object array = Array.newInstance(componentType, nbrElements); - - for (int i = 0; i < nbrElements; i++) { - - // The default - if (null != elementStrategy - && ObjectStrategy.class - .isAssignableFrom(collectionAnnotation - .collectionElementStrategy()) - && Object.class.equals(componentType)) { - LOG.debug("Element strategy is ObjectStrategy and array element is of type Object: using the ObjectStrategy strategy"); - arrayElement = elementStrategy.getValue(); - } else if (null != elementStrategy - && !ObjectStrategy.class - .isAssignableFrom(collectionAnnotation - .collectionElementStrategy())) { - LOG.debug("Array elements will be filled using the following strategy: " - + elementStrategy); - arrayElement = returnAttributeDataStrategyValue(componentType, - elementStrategy); - - } else { - - arrayElement = manufactureAttributeValue(pojo, pojos, - componentType, genericType, annotations, attributeName, - typeArgsMap, genericTypeArgs.get()); - - } - - Array.set(array, i, arrayElement); - - } - - return array; - } - - /** - * Given a collection type it returns an instance - *

- *

    - *
  • The default type for a {@link List} is an {@link ArrayList}
  • - *
  • The default type for a {@link Queue} is a {@link LinkedList}
  • - *
  • The default type for a {@link Set} is a {@link HashSet}
  • - *
- * - *

- * - * @param collectionType - * The collection type * - * @param defaultValue - * Default value for the collection, can be null - * @return an instance of the collection type or null - */ - private Collection resolveCollectionType( - Class collectionType, Collection defaultValue) { - - Collection retValue = null; - - // Default list and set are ArrayList and HashSet. If users - // wants a particular collection flavour they have to initialise - // the collection - if (null != defaultValue && - (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { - /* Default collection, which is not immutable */ - retValue = defaultValue; - } else { - if (Queue.class.isAssignableFrom(collectionType)) { - if (collectionType.isAssignableFrom(LinkedList.class)) { - retValue = new LinkedList(); - } - } else if (Set.class.isAssignableFrom(collectionType)) { - if (collectionType.isAssignableFrom(HashSet.class)) { - retValue = new HashSet(); - } - } else { - if (collectionType.isAssignableFrom(ArrayList.class)) { - retValue = new ArrayList(); - } - } - if (null != retValue && null != defaultValue) { - retValue.addAll(defaultValue); - } - } - return retValue; - } - - /** - * It manufactures and returns a default instance for each map type - * - *

- * The default implementation for a {@link ConcurrentMap} is - * {@link ConcurrentHashMap} - *

- * - *

- * The default implementation for a {@link SortedMap} is a {@link TreeMap} - *

- * - *

- * The default Map is none of the above was recognised is a {@link HashMap} - *

- * - * @param mapType - * The attribute type implementing Map - * @param defaultValue - * Default value for map - * @return A default instance for each map type or null - * - */ - private Map resolveMapType( - Class mapType, Map defaultValue) { - - Map retValue = null; - - if (null != defaultValue && - (defaultValue.getClass().getModifiers() & Modifier.PRIVATE) == 0) { - /* Default map, which is not immutable */ - retValue = defaultValue; - } else { - if (SortedMap.class.isAssignableFrom(mapType)) { - if (mapType.isAssignableFrom(TreeMap.class)) { - retValue = new TreeMap(); - } - } else if (ConcurrentMap.class.isAssignableFrom(mapType)) { - if (mapType.isAssignableFrom(ConcurrentHashMap.class)) { - retValue = new ConcurrentHashMap(); - } - } else { - if (mapType.isAssignableFrom(HashMap.class)) { - retValue = new HashMap(); - } - } - } - - return retValue; - - } - - /** - * Given a constructor it manufactures and returns the parameter values - * required to invoke it - * - * @param constructor - * The constructor for which parameter values are required - * @param pojoClass - * The POJO class containing the constructor - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * - * @return The parameter values required to invoke the constructor - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - private Object[] getParameterValuesForConstructor( - Constructor constructor, Class pojoClass, - Map, Integer> pojos, Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - final Map typeArgsMap = new HashMap(); - final Type[] genericTypeArgsExtra = fillTypeArgMap(typeArgsMap, pojoClass, - genericTypeArgs); - - Annotation[][] parameterAnnotations = constructor - .getParameterAnnotations(); - - Class[] parameterTypes = constructor.getParameterTypes(); - Object[] parameterValues = new Object[parameterTypes.length]; - - int idx = 0; - for (Class parameterType : parameterTypes) { - - List annotations = Arrays - .asList(parameterAnnotations[idx]); - Type genericType = constructor.getGenericParameterTypes()[idx]; - - - parameterValues[idx] = manufactureParameterValue(parameterType, - genericType, annotations, typeArgsMap, pojos, - genericTypeArgsExtra == null ? NO_TYPES : genericTypeArgsExtra); - - idx++; - - } - - return parameterValues; - - } - - /** - * Manufactures and returns the parameter value for method required to - * invoke it - * - * @param parameterType type of parameter - * @param genericType generic type of parameter - * @param annotations parameter annotations - * @param typeArgsMap map for resolving generic types - * @param genericTypeArgsExtra extra generic types for chaining - * @param pojos - * Set of manufactured pojos' types - * @param genericTypeArgs - * The generic type arguments for the current generic class - * instance - * - * @return The parameter values required to invoke the constructor - * @throws IllegalArgumentException - * If an illegal argument was passed to the constructor - * @throws InstantiationException - * If an exception occurred during instantiation - * @throws IllegalAccessException - * If security was violated while creating the object - * @throws InvocationTargetException - * If an exception occurred while invoking the constructor or - * factory method - * @throws ClassNotFoundException - * If it was not possible to create a class from a string - */ - private Object manufactureParameterValue(Class parameterType, - Type genericType, List annotations, - final Map typeArgsMap, Map, Integer> pojos, - Type... genericTypeArgs) - throws InstantiationException, IllegalAccessException, - InvocationTargetException, ClassNotFoundException { - - Object parameterValue = null; - - if (Collection.class.isAssignableFrom(parameterType)) { - - Collection defaultValue = null; - Collection collection = resolveCollectionType( - parameterType, defaultValue); - - if (collection != null) { - Class collectionElementType; - AtomicReference collectionGenericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericType instanceof ParameterizedType) { - ParameterizedType pType = (ParameterizedType) genericType; - Type actualTypeArgument = pType.getActualTypeArguments()[0]; - - collectionElementType = resolveGenericParameter( - actualTypeArgument, typeArgsMap, - collectionGenericTypeArgs); - } else { - LOG.warn("Collection parameter {} type is non-generic." - + "We will assume a Collection for you.", - genericType); - collectionElementType = Object.class; - } - - Type[] genericTypeArgsAll = mergeTypeArrays( - collectionGenericTypeArgs.get(), genericTypeArgs); - fillCollection(pojos, annotations, - collection, collectionElementType, genericTypeArgsAll); - - parameterValue = collection; - } - - } else if (Map.class.isAssignableFrom(parameterType)) { - - Map defaultValue = null; - Map map = resolveMapType(parameterType, defaultValue); - - if (map != null) { - Class keyClass; - Class elementClass; - AtomicReference keyGenericTypeArgs = new AtomicReference( - NO_TYPES); - AtomicReference elementGenericTypeArgs = new AtomicReference( - NO_TYPES); - if (genericType instanceof ParameterizedType) { - ParameterizedType pType = (ParameterizedType) genericType; - Type[] actualTypeArguments = pType.getActualTypeArguments(); - - keyClass = resolveGenericParameter(actualTypeArguments[0], - typeArgsMap, keyGenericTypeArgs); - elementClass = resolveGenericParameter( - actualTypeArguments[1], typeArgsMap, - elementGenericTypeArgs); - } else { - LOG.warn("Map parameter {} type is non-generic." - + "We will assume a Map for you.", - genericType); - keyClass = Object.class; - elementClass = Object.class; - } - - Type[] genericTypeArgsAll = mergeTypeArrays( - elementGenericTypeArgs.get(), genericTypeArgs); - - MapArguments mapArguments = new MapArguments(); - mapArguments.setPojos(pojos); - mapArguments.setAnnotations(annotations); - mapArguments.setMapToBeFilled(map); - mapArguments.setKeyClass(keyClass); - mapArguments.setElementClass(elementClass); - mapArguments.setKeyGenericTypeArgs(keyGenericTypeArgs.get()); - mapArguments.setElementGenericTypeArgs(genericTypeArgsAll); - - fillMap(mapArguments); - - parameterValue = map; - } - } - - if (parameterValue == null) { - - Map typeArgsMapForParam; - if (genericType instanceof ParameterizedType) { - typeArgsMapForParam = new HashMap(typeArgsMap); - ParameterizedType parametrizedType = - (ParameterizedType) genericType; - - TypeVariable[] argumentTypes = parameterType.getTypeParameters(); - Type[] argumentGenericTypes = parametrizedType.getActualTypeArguments(); - - for (int k = 0; k < argumentTypes.length; k++) { - if (argumentGenericTypes[k] instanceof Class) { - Class genericParam = (Class) argumentGenericTypes[k]; - typeArgsMapForParam.put(argumentTypes[k].getName(), genericParam); - } - } - } else { - typeArgsMapForParam = typeArgsMap; - } - - parameterValue = manufactureParameterValue(pojos, parameterType, - genericType, annotations, typeArgsMapForParam, - genericTypeArgs); - } - - return parameterValue; - } - - /** - * Utility method to merge two arrays - * - * @param original - * The main array - * @param extra - * The additional array, optionally may be null - * @return A merged array of original and extra arrays - */ - private Type[] mergeTypeArrays(Type[] original, Type[] extra) { - - Type[] merged; - - if (extra != null) { - merged = new Type[original.length + extra.length]; - System.arraycopy(original, 0, merged, 0, original.length); - System.arraycopy(extra, 0, merged, original.length, extra.length); - } else { - merged = original; - } - - return merged; - } - - /** - * It retrieves the value for the {@link PodamStrategyValue} annotation with - * which the attribute was annotated - * - * @param attributeType - * The attribute type, used for type checking - * @param attributeStrategy - * The {@link AttributeStrategy} to use - * @return The value for the {@link PodamStrategyValue} annotation with - * which the attribute was annotated - * @throws InstantiationException - * If an exception occurred while creating an instance of the - * strategy contained within the {@link PodamStrategyValue} - * annotation - * @throws IllegalAccessException - * If an exception occurred while creating an instance of the - * strategy contained within the {@link PodamStrategyValue} - * annotation - * - * @throws IllegalArgumentException - * If the type of the data strategy defined for the - * {@link PodamStrategyValue} annotation is not assignable to - * the annotated attribute. This de facto guarantees type - * safety. - */ - private Object returnAttributeDataStrategyValue(Class attributeType, - AttributeStrategy attributeStrategy) - throws InstantiationException, IllegalAccessException { - - Object retValue = null; - - Method attributeStrategyMethod = null; - - try { - attributeStrategyMethod = attributeStrategy.getClass().getMethod( - PodamConstants.PODAM_ATTRIBUTE_STRATEGY_METHOD_NAME, - new Class[] {}); - - if (!attributeType.isAssignableFrom(attributeStrategyMethod - .getReturnType())) { - String errMsg = "The type of the Podam Attribute Strategy is not " - + attributeType.getName() - + " but " - + attributeStrategyMethod.getReturnType().getName() - + ". An exception will be thrown."; - LOG.error(errMsg); - throw new IllegalArgumentException(errMsg); - } - - retValue = attributeStrategy.getValue(); - - } catch (SecurityException e) { - throw new IllegalStateException( - "A security issue occurred while retrieving the Podam Attribute Strategy details", - e); - } catch (NoSuchMethodException e) { - throw new IllegalStateException( - "It seems the Podam Attribute Annotation is of the wrong type", - e); - } - - return retValue; - - } - - // ------------------->> equals() / hashcode() / toString() - - // ------------------->> Inner classes - -} diff --git a/All/Genesis-OOB/Genesis#185/pair.info b/All/Genesis-OOB/Genesis#185/pair.info deleted file mode 100755 index 65197c1..0000000 --- a/All/Genesis-OOB/Genesis#185/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:185 -SATName:Genesis -modifiedFPath:src/main/java/uk/co/jemos/podam/api/PodamFactoryImpl.java -comSha:c6145d6 -parentComSha:c6145d6^1 -githubUrl:https://github.com/mtedone/podam -repoName:mtedone#podam \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#19/comMsg.txt b/All/Genesis-OOB/Genesis#19/comMsg.txt deleted file mode 100755 index 50bfd3f..0000000 --- a/All/Genesis-OOB/Genesis#19/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Fix pageSize assumptions in Page.split(). diff --git a/All/Genesis-OOB/Genesis#19/diff.diff b/All/Genesis-OOB/Genesis#19/diff.diff deleted file mode 100755 index f294d1e..0000000 --- a/All/Genesis-OOB/Genesis#19/diff.diff +++ /dev/null @@ -1,26 +0,0 @@ -diff --git a/src/main/java/com/tdunning/math/stats/ArrayDigest.java b/src/main/java/com/tdunning/math/stats/ArrayDigest.java -index 9591332..3bcc2b7 100644 ---- a/src/main/java/com/tdunning/math/stats/ArrayDigest.java -+++ b/src/main/java/com/tdunning/math/stats/ArrayDigest.java -@@ -824,0 +825,2 @@ public class ArrayDigest extends AbstractTDigest { -+ assert active == pageSize; -+ final int half = pageSize / 2; -@@ -826,2 +828,2 @@ public class ArrayDigest extends AbstractTDigest { -- System.arraycopy(centroids, 16, newPage.centroids, 0, pageSize / 2); -- System.arraycopy(counts, 16, newPage.counts, 0, pageSize / 2); -+ System.arraycopy(centroids, half, newPage.centroids, 0, pageSize - half); -+ System.arraycopy(counts, half, newPage.counts, 0, pageSize - half); -@@ -830 +832 @@ public class ArrayDigest extends AbstractTDigest { -- newPage.history.addAll(history.subList(pageSize / 2, pageSize)); -+ newPage.history.addAll(history.subList(half, pageSize)); -@@ -833 +835 @@ public class ArrayDigest extends AbstractTDigest { -- tmp.addAll(history.subList(0, pageSize / 2)); -+ tmp.addAll(history.subList(0, half)); -@@ -836,2 +838,2 @@ public class ArrayDigest extends AbstractTDigest { -- active = 16; -- newPage.active = 16; -+ active = half; -+ newPage.active = pageSize - half; -@@ -841 +843 @@ public class ArrayDigest extends AbstractTDigest { -- for (int i = 0; i < 16; i++) { -+ for (int i = 0; i < half; i++) { diff --git a/All/Genesis-OOB/Genesis#19/new/ArrayDigest.java b/All/Genesis-OOB/Genesis#19/new/ArrayDigest.java deleted file mode 100755 index 3bcc2b7..0000000 --- a/All/Genesis-OOB/Genesis#19/new/ArrayDigest.java +++ /dev/null @@ -1,864 +0,0 @@ -/* - * 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 com.tdunning.math.stats; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * Array based implementation of a TDigest. - *

- * This implementation is essentially a one-level b-tree in which nodes are collected into - * pages typically with 32 values per page. Commonly, an ArrayDigest contains 500-3000 - * centroids. With 32 values per page, we have about 32 values per page and about 30 pages - * which seems to give a nice balance for speed. Sizes from 4 to 100 are plausible, however. - */ -public class ArrayDigest extends AbstractTDigest { - private final int pageSize; - - private List data = new ArrayList(); - private int totalWeight = 0; - private int centroidCount = 0; - private double compression = 100; - - public ArrayDigest(int pageSize, double compression) { - if (pageSize > 3) { - this.pageSize = pageSize; - this.compression = compression; - } else { - throw new IllegalArgumentException("Must have page size of 4 or more"); - } - } - - @Override - public void add(double x, int w) { - Index start = floor(x); - if (start == null) { - start = ceiling(x); - } - - if (start == null) { - addRaw(x, w); - } else { - Iterable neighbors = inclusiveTail(start); - double minDistance = Double.MAX_VALUE; - int lastNeighbor = 0; - int i = headCount(start); - for (Index neighbor : neighbors) { - double z = Math.abs(mean(neighbor) - x); - if (z <= minDistance) { - minDistance = z; - lastNeighbor = i; - } else { - // as soon as z exceeds the minimum, we have passed the nearest neighbor and can quit - break; - } - i++; - } - - Index closest = null; - int sum = headSum(start); - i = headCount(start); - double n = 0; - for (Index neighbor : neighbors) { - if (i > lastNeighbor) { - break; - } - double z = Math.abs(mean(neighbor) - x); - double q = (sum + count(neighbor) / 2.0) / totalWeight; - double k = 4 * totalWeight * q * (1 - q) / compression; - - // this slightly clever selection method improves accuracy with lots of repeated points - if (z == minDistance && count(neighbor) + w <= k) { - n++; - if (gen.nextDouble() < 1 / n) { - closest = neighbor; - } - } - sum += count(neighbor); - i++; - } - - if (closest == null) { - addRaw(x, w); - } else { - if (n == 1) { - // if the nearest point was unique, centroid ordering cannot change - Page p = data.get(closest.page); - p.counts[closest.subPage] += w; - p.totalCount += w; - p.centroids[closest.subPage] += (x - p.centroids[closest.subPage]) / p.counts[closest.subPage]; - if (p.history != null && p.history.get(closest.subPage) != null) { - p.history.get(closest.subPage).add(x); - } - totalWeight += w; - } else { - // if the nearest point was not unique, then we may not be modifying the first copy - // which means that ordering can change - int weight = count(closest) + w; - double center = mean(closest); - center = center + (x - center) / weight; - - if (mean(increment(closest, -1)) <= center && mean(increment(closest, 1)) >= center) { - // if order doesn't change, we can short-cut the process - Page p = data.get(closest.page); - p.counts[closest.subPage] = weight; - p.centroids[closest.subPage] = center; - - p.totalCount += w; - totalWeight += w; - if (p.history != null && p.history.get(closest.subPage) != null) { - p.history.get(closest.subPage).add(x); - } - } else { - delete(closest); - - List history = history(closest); - if (history != null) { - history.add(x); - } - - addRaw(center, weight, history); - } - - } - } - - if (centroidCount > 100 * compression) { - // something such as sequential ordering of data points - // has caused a pathological expansion of our summary. - // To fight this, we simply replay the current centroids - // in random order. - - // this causes us to forget the diagnostic recording of data points - compress(); - } - } - } - - public int headSum(Index limit) { - int r = 0; - - for (int i = 0; limit != null && i < limit.page; i++) { - r += data.get(i).totalCount; - } - - if (limit != null && limit.page < data.size()) { - for (int j = 0; j < limit.subPage; j++) { - r += data.get(limit.page).counts[j]; - } - } - - return r; - } - - /** - * Returns the number of centroids strictly before the limit. - */ - private int headCount(Index limit) { - int r = 0; - - for (int i = 0; i < limit.page; i++) { - r += data.get(i).active; - } - - if (limit.page < data.size()) { - for (int j = 0; j < limit.subPage; j++) { - r++; - } - } - - return r; - } - - public double mean(Index index) { - return data.get(index.page).centroids[index.subPage]; - } - - public int count(Index index) { - return data.get(index.page).counts[index.subPage]; - } - - @Override - public void compress() { - ArrayDigest reduced = new ArrayDigest(pageSize, compression); - if (recordAllData) { - reduced.recordAllData(); - } - List tmp = new ArrayList(); - Iterator ix = this.iterator(0, 0); - while (ix.hasNext()) { - tmp.add(ix.next()); - } - - Collections.shuffle(tmp, gen); - for (Index index : tmp) { - reduced.add(mean(index), count(index)); - } - - data = reduced.data; - centroidCount = reduced.centroidCount; - } - - @Override - public void compress(GroupTree other) { - throw new UnsupportedOperationException("Default operation"); - } - - @Override - public int size() { - return totalWeight; - } - - @Override - public double cdf(double x) { - if (size() == 0) { - return Double.NaN; - } else if (size() == 1) { - return x < data.get(0).centroids[0] ? 0 : 1; - } else { - double r = 0; - - // we scan a across the centroids - Iterator it = iterator(0, 0); - Index a = it.next(); - - // b is the look-ahead to the next centroid - Index b = it.next(); - - // initially, we set left width equal to right width - double left = (b.mean() - a.mean()) / 2; - double right = left; - - // scan to next to last element - while (it.hasNext()) { - if (x < a.mean() + right) { - return (r + a.count() * AbstractTDigest.interpolate(x, a.mean() - left, a.mean() + right)) / totalWeight; - } - r += a.count(); - - a = b; - b = it.next(); - - left = right; - right = (b.mean() - a.mean()) / 2; - } - - // for the last element, assume right width is same as left - left = right; - a = b; - if (x < a.mean() + right) { - return (r + a.count() * AbstractTDigest.interpolate(x, a.mean() - left, a.mean() + right)) / totalWeight; - } else { - return 1; - } - } - } - - @Override - public double quantile(double q) { - if (q < 0 || q > 1) { - throw new IllegalArgumentException("q should be in [0,1], got " + q); - } - - if (centroidCount() == 0) { - return Double.NaN; - } else if (centroidCount() == 1) { - return data.get(0).centroids[0]; - } - - // if values were stored in a sorted array, index would be the offset we are interested in - final double index = q * (size() - 1); - - double previousMean = Double.NaN, previousIndex = 0; - long total = 0; - Index next; - Iterator it = iterator(0, 0); - while (true) { - next = it.next(); - final double nextIndex = total + (next.count() - 1.0) / 2; - if (nextIndex >= index) { - if (Double.isNaN(previousMean)) { - // special case 1: the index we are interested in is before the 1st centroid - if (nextIndex == previousIndex) { - return next.mean(); - } - // assume values grow linearly between index previousIndex=0 and nextIndex2 - Index next2 = it.next(); - final double nextIndex2 = total + next.count() + (next2.count() - 1.0) / 2; - previousMean = (nextIndex2 * next.mean() - nextIndex * next2.mean()) / (nextIndex2 - nextIndex); - } - // common case: we found two centroids previous and next so that the desired quantile is - // after 'previous' but before 'next' - return quantile(previousIndex, index, nextIndex, previousMean, next.mean()); - } else if (!it.hasNext()) { - // special case 2: the index we are interested in is beyond the last centroid - // again, assume values grow linearly between index previousIndex and (count - 1) - // which is the highest possible index - final double nextIndex2 = size() - 1; - final double nextMean2 = (next.mean() * (nextIndex2 - previousIndex) - previousMean * (nextIndex2 - nextIndex)) / (nextIndex - previousIndex); - return quantile(nextIndex, index, nextIndex2, next.mean(), nextMean2); - } - total += next.count(); - previousMean = next.mean(); - previousIndex = nextIndex; - } - } - - @Override - public int centroidCount() { - return centroidCount; - } - - @Override - public Iterable centroids() { - List r = new ArrayList(); - Iterator ix = iterator(0, 0); - while (ix.hasNext()) { - Index index = ix.next(); - Page current = data.get(index.page); - Centroid centroid = new Centroid(current.centroids[index.subPage], current.counts[index.subPage]); - if (current.history != null) { - for (double x : current.history.get(index.subPage)) { - centroid.insertData(x); - } - } - r.add(centroid); - } - return r; - } - - public Iterator allAfter(double x) { - if (data.size() == 0) { - return iterator(0, 0); - } else { - - for (int i = 1; i < data.size(); i++) { - if (data.get(i).centroids[0] >= x) { - Page previous = data.get(i - 1); - for (int j = 0; j < previous.active; j++) { - if (previous.centroids[j] > x) { - return iterator(i - 1, j); - } - } - return iterator(i, 0); - } - } - - Page last = data.get(data.size() - 1); - for (int j = 0; j < last.active; j++) { - if (last.centroids[j] > x) { - return iterator(data.size() - 1, j); - } - } - return iterator(data.size(), 0); - } - } - - /** - * Returns a cursor pointing to the first element <= x. Exposed only for testing. - * @param x The value used to find the cursor. - * @return The cursor. - */ - public Index floor(double x) { - Iterator rx = allBefore(x); - if (!rx.hasNext()) { - return null; - } - Index r = rx.next(); - Index z = r; - while (rx.hasNext() && mean(z) == x) { - r = z; - z = rx.next(); - } - return r; - } - - public Index ceiling(double x) { - Iterator r = allAfter(x); - return r.hasNext() ? r.next() : null; - } - - /** - * Returns an iterator which will give each element <= to x in non-increasing order. - * - * @param x The upper bound of all returned elements - * @return An iterator that returns elements in non-increasing order. - */ - public Iterator allBefore(double x) { - if (data.size() == 0) { - return iterator(0, 0); - } else { - for (int i = 1; i < data.size(); i++) { - if (data.get(i).centroids[0] > x) { - Page previous = data.get(i - 1); - for (int j = 0; j < previous.active; j++) { - if (previous.centroids[j] > x) { - return reverse(i - 1, j - 1); - } - } - return reverse(i, -1); - } - } - Page last = data.get(data.size() - 1); - for (int j = 0; j < last.active; j++) { - if (last.centroids[j] > x) { - return reverse(data.size() - 1, j - 1); - } - } - return reverse(data.size(), -1); - } - } - - public Index increment(Index x, int delta) { - int i = x.page; - int j = x.subPage + delta; - - while (i < data.size() && j >= data.get(i).active) { - j -= data.get(i).active; - i++; - } - - while (i > 0 && j < 0) { - i--; - j += data.get(i).active; - } - return new Index(i, j); - } - - @Override - public double compression() { - return compression; - } - - /** - * Returns an upper bound on the number bytes that will be required to represent this histogram. - */ - @Override - public int byteSize() { - return 4 + 8 + 8 + centroidCount * 12; - } - - /** - * Returns an upper bound on the number of bytes that will be required to represent this histogram in - * the tighter representation. - */ - @Override - public int smallByteSize() { - int bound = byteSize(); - ByteBuffer buf = ByteBuffer.allocate(bound); - asSmallBytes(buf); - return buf.position(); - } - - /** - * Outputs a histogram as bytes using a particularly cheesy encoding. - */ - @Override - public void asBytes(ByteBuffer buf) { - buf.putInt(VERBOSE_ARRAY_DIGEST); - buf.putDouble(compression()); - buf.putInt(pageSize); - buf.putInt(centroidCount); - for (Page page : data) { - for (int i = 0; i < page.active; i++) { - buf.putDouble(page.centroids[i]); - } - } - for (Page page : data) { - for (int i = 0; i < page.active; i++) { - buf.putInt(page.counts[i]); - } - } - } - - @Override - public void asSmallBytes(ByteBuffer buf) { - buf.putInt(SMALL_ARRAY_DIGEST); - buf.putDouble(compression()); - buf.putInt(pageSize); - buf.putInt(centroidCount); - - double x = 0; - for (Page page : data) { - for (int i = 0; i < page.active; i++) { - double mean = page.centroids[i]; - double delta = mean - x; - x = mean; - buf.putFloat((float) delta); - } - } - for (Page page : data) { - for (int i = 0; i < page.active; i++) { - int n = page.counts[i]; - encode(buf, n); - } - } - } - - /** - * Reads a histogram from a byte buffer - * - * @return The new histogram structure - */ - public static ArrayDigest fromBytes(ByteBuffer buf) { - int encoding = buf.getInt(); - if (encoding == VERBOSE_ENCODING || encoding == VERBOSE_ARRAY_DIGEST) { - double compression = buf.getDouble(); - int pageSize = 32; - if (encoding == VERBOSE_ARRAY_DIGEST) { - pageSize = buf.getInt(); - } - ArrayDigest r = new ArrayDigest(pageSize, compression); - int n = buf.getInt(); - double[] means = new double[n]; - for (int i = 0; i < n; i++) { - means[i] = buf.getDouble(); - } - for (int i = 0; i < n; i++) { - r.add(means[i], buf.getInt()); - } - return r; - } else if (encoding == SMALL_ENCODING || encoding == SMALL_ARRAY_DIGEST) { - double compression = buf.getDouble(); - int pageSize = 32; - if (encoding == SMALL_ARRAY_DIGEST) { - pageSize = buf.getInt(); - } - ArrayDigest r = new ArrayDigest(pageSize, compression); - int n = buf.getInt(); - double[] means = new double[n]; - double x = 0; - for (int i = 0; i < n; i++) { - double delta = buf.getFloat(); - x += delta; - means[i] = x; - } - - for (int i = 0; i < n; i++) { - int z = decode(buf); - r.add(means[i], z); - } - return r; - } else { - throw new IllegalStateException("Invalid format for serialized histogram"); - } - } - - private List history(Index index) { - List> h = data.get(index.page).history; - return h == null ? null : h.get(index.subPage); - } - - private void delete(Index index) { - // don't want to delete empty pages here because other indexes would be screwed up. - // this should almost never happen anyway since deletes only cause small ordering - // changes - totalWeight -= count(index); - centroidCount--; - data.get(index.page).delete(index.subPage); - } - - private Iterable inclusiveTail(final Index start) { - return new Iterable() { - @Override - public Iterator iterator() { - return ArrayDigest.this.iterator(start.page, start.subPage); - } - }; - } - - void addRaw(double x, int w) { - List tmp = new ArrayList(); - tmp.add(x); - addRaw(x, w, recordAllData ? tmp : null); - } - - void addRaw(double x, int w, List history) { - if (centroidCount == 0) { - Page page = new Page(pageSize, recordAllData); - page.add(x, w, history); - totalWeight += w; - centroidCount++; - data.add(page); - } else { - for (int i = 1; i < data.size(); i++) { - if (data.get(i).centroids[0] > x) { - Page newPage = data.get(i - 1).add(x, w, history); - totalWeight += w; - centroidCount++; - if (newPage != null) { - data.add(i, newPage); - } - return; - } - } - Page newPage = data.get(data.size() - 1).add(x, w, history); - totalWeight += w; - centroidCount++; - if (newPage != null) { - data.add(data.size(), newPage); - } - } - } - - @Override - void add(double x, int w, Centroid base) { - addRaw(x, w, base.data()); - } - - private Iterator iterator(final int startPage, final int startSubPage) { - return new Iterator() { - int page = startPage; - int subPage = startSubPage; - Index end = new Index(-1, -1); - Index next = null; - - @Override - public boolean hasNext() { - if (next == null) { - next = computeNext(); - } - return next != end; - } - - @Override - public Index next() { - if (hasNext()) { - Index r = next; - next = null; - return r; - } else { - throw new NoSuchElementException("Can't iterate past end of data"); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Default operation"); - } - - protected Index computeNext() { - if (page >= data.size()) { - return end; - } else { - Page current = data.get(page); - if (subPage >= current.active) { - subPage = 0; - page++; - return computeNext(); - } else { - Index r = new Index(page, subPage); - subPage++; - return r; - } - } - } - }; - } - - private Iterator reverse(final int startPage, final int startSubPage) { - return new Iterator() { - int page = startPage; - int subPage = startSubPage; - - Index end = new Index(-1, -1); - Index next = null; - - @Override - public boolean hasNext() { - if (next == null) { - next = computeNext(); - } - return next != end; - } - - @Override - public Index next() { - if (hasNext()) { - Index r = next; - next = null; - return r; - } else { - throw new NoSuchElementException("Can't reverse iterate before beginning of data"); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Default operation"); - } - - protected Index computeNext() { - if (page < 0) { - return end; - } else { - if (subPage < 0) { - page--; - if (page >= 0) { - subPage = data.get(page).active - 1; - } - return computeNext(); - } else { - Index r = new Index(page, subPage); - subPage--; - return r; - } - } - } - }; - } - - public final static int VERBOSE_ENCODING = 1; - public final static int SMALL_ENCODING = 2; - public final static int VERBOSE_ARRAY_DIGEST = 3; - public final static int SMALL_ARRAY_DIGEST = 4; - - class Index { - final int page, subPage; - - private Index(int page, int subPage) { - this.page = page; - this.subPage = subPage; - } - - double mean() { - return data.get(page).centroids[subPage]; - } - - int count() { - return data.get(page).counts[subPage]; - } - } - - private static class Page { - private final boolean recordAllData; - private final int pageSize; - - int totalCount; - int active; - double[] centroids; - int[] counts; - List> history; - - private Page(int pageSize, boolean recordAllData) { - this.pageSize = pageSize; - this.recordAllData = recordAllData; - centroids = new double[this.pageSize]; - counts = new int[this.pageSize]; - history = this.recordAllData ? new ArrayList>() : null; - } - - public Page add(double x, int w, List history) { - for (int i = 0; i < active; i++) { - if (centroids[i] >= x) { - // insert at i - if (active >= pageSize) { - // split page - Page newPage = split(); - if (i < pageSize / 2) { - addAt(i, x, w, history); - } else { - newPage.addAt(i - pageSize / 2, x, w, history); - } - return newPage; - } else { - addAt(i, x, w, history); - return null; - } - } - } - - // insert at end - if (active >= pageSize) { - // split page - Page newPage = split(); - newPage.addAt(pageSize / 2, x, w, history); - return newPage; - } else { - addAt(active, x, w, history); - return null; - } - } - - private void addAt(int i, double x, int w, List history) { - if (i < active) { - // shift data to make room - System.arraycopy(centroids, i, centroids, i + 1, active - i); - System.arraycopy(counts, i, counts, i + 1, active - i); - if (this.history != null) { - this.history.add(i, history); - } - centroids[i] = x; - counts[i] = w; - } else { - centroids[active] = x; - counts[active] = w; - if (this.history != null) { - this.history.add(history); - } - } - active++; - totalCount += w; - } - - private Page split() { - assert active == pageSize; - final int half = pageSize / 2; - Page newPage = new Page(pageSize, recordAllData); - System.arraycopy(centroids, half, newPage.centroids, 0, pageSize - half); - System.arraycopy(counts, half, newPage.counts, 0, pageSize - half); - if (history != null) { - newPage.history = new ArrayList>(); - newPage.history.addAll(history.subList(half, pageSize)); - - List> tmp = new ArrayList>(); - tmp.addAll(history.subList(0, half)); - history = tmp; - } - active = half; - newPage.active = pageSize - half; - - newPage.totalCount = totalCount; - totalCount = 0; - for (int i = 0; i < half; i++) { - totalCount += counts[i]; - newPage.totalCount -= counts[i]; - } - - return newPage; - } - - public void delete(int i) { - int w = counts[i]; - if (i != active - 1) { - System.arraycopy(centroids, i + 1, centroids, i, active - i - 1); - System.arraycopy(counts, i + 1, counts, i, active - i - 1); - if (history != null) { - history.remove(i); - } - } - active--; - totalCount -= w; - } - } -} diff --git a/All/Genesis-OOB/Genesis#19/old/ArrayDigest.java b/All/Genesis-OOB/Genesis#19/old/ArrayDigest.java deleted file mode 100755 index 9591332..0000000 --- a/All/Genesis-OOB/Genesis#19/old/ArrayDigest.java +++ /dev/null @@ -1,862 +0,0 @@ -/* - * 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 com.tdunning.math.stats; - -import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.NoSuchElementException; - -/** - * Array based implementation of a TDigest. - *

- * This implementation is essentially a one-level b-tree in which nodes are collected into - * pages typically with 32 values per page. Commonly, an ArrayDigest contains 500-3000 - * centroids. With 32 values per page, we have about 32 values per page and about 30 pages - * which seems to give a nice balance for speed. Sizes from 4 to 100 are plausible, however. - */ -public class ArrayDigest extends AbstractTDigest { - private final int pageSize; - - private List data = new ArrayList(); - private int totalWeight = 0; - private int centroidCount = 0; - private double compression = 100; - - public ArrayDigest(int pageSize, double compression) { - if (pageSize > 3) { - this.pageSize = pageSize; - this.compression = compression; - } else { - throw new IllegalArgumentException("Must have page size of 4 or more"); - } - } - - @Override - public void add(double x, int w) { - Index start = floor(x); - if (start == null) { - start = ceiling(x); - } - - if (start == null) { - addRaw(x, w); - } else { - Iterable neighbors = inclusiveTail(start); - double minDistance = Double.MAX_VALUE; - int lastNeighbor = 0; - int i = headCount(start); - for (Index neighbor : neighbors) { - double z = Math.abs(mean(neighbor) - x); - if (z <= minDistance) { - minDistance = z; - lastNeighbor = i; - } else { - // as soon as z exceeds the minimum, we have passed the nearest neighbor and can quit - break; - } - i++; - } - - Index closest = null; - int sum = headSum(start); - i = headCount(start); - double n = 0; - for (Index neighbor : neighbors) { - if (i > lastNeighbor) { - break; - } - double z = Math.abs(mean(neighbor) - x); - double q = (sum + count(neighbor) / 2.0) / totalWeight; - double k = 4 * totalWeight * q * (1 - q) / compression; - - // this slightly clever selection method improves accuracy with lots of repeated points - if (z == minDistance && count(neighbor) + w <= k) { - n++; - if (gen.nextDouble() < 1 / n) { - closest = neighbor; - } - } - sum += count(neighbor); - i++; - } - - if (closest == null) { - addRaw(x, w); - } else { - if (n == 1) { - // if the nearest point was unique, centroid ordering cannot change - Page p = data.get(closest.page); - p.counts[closest.subPage] += w; - p.totalCount += w; - p.centroids[closest.subPage] += (x - p.centroids[closest.subPage]) / p.counts[closest.subPage]; - if (p.history != null && p.history.get(closest.subPage) != null) { - p.history.get(closest.subPage).add(x); - } - totalWeight += w; - } else { - // if the nearest point was not unique, then we may not be modifying the first copy - // which means that ordering can change - int weight = count(closest) + w; - double center = mean(closest); - center = center + (x - center) / weight; - - if (mean(increment(closest, -1)) <= center && mean(increment(closest, 1)) >= center) { - // if order doesn't change, we can short-cut the process - Page p = data.get(closest.page); - p.counts[closest.subPage] = weight; - p.centroids[closest.subPage] = center; - - p.totalCount += w; - totalWeight += w; - if (p.history != null && p.history.get(closest.subPage) != null) { - p.history.get(closest.subPage).add(x); - } - } else { - delete(closest); - - List history = history(closest); - if (history != null) { - history.add(x); - } - - addRaw(center, weight, history); - } - - } - } - - if (centroidCount > 100 * compression) { - // something such as sequential ordering of data points - // has caused a pathological expansion of our summary. - // To fight this, we simply replay the current centroids - // in random order. - - // this causes us to forget the diagnostic recording of data points - compress(); - } - } - } - - public int headSum(Index limit) { - int r = 0; - - for (int i = 0; limit != null && i < limit.page; i++) { - r += data.get(i).totalCount; - } - - if (limit != null && limit.page < data.size()) { - for (int j = 0; j < limit.subPage; j++) { - r += data.get(limit.page).counts[j]; - } - } - - return r; - } - - /** - * Returns the number of centroids strictly before the limit. - */ - private int headCount(Index limit) { - int r = 0; - - for (int i = 0; i < limit.page; i++) { - r += data.get(i).active; - } - - if (limit.page < data.size()) { - for (int j = 0; j < limit.subPage; j++) { - r++; - } - } - - return r; - } - - public double mean(Index index) { - return data.get(index.page).centroids[index.subPage]; - } - - public int count(Index index) { - return data.get(index.page).counts[index.subPage]; - } - - @Override - public void compress() { - ArrayDigest reduced = new ArrayDigest(pageSize, compression); - if (recordAllData) { - reduced.recordAllData(); - } - List tmp = new ArrayList(); - Iterator ix = this.iterator(0, 0); - while (ix.hasNext()) { - tmp.add(ix.next()); - } - - Collections.shuffle(tmp, gen); - for (Index index : tmp) { - reduced.add(mean(index), count(index)); - } - - data = reduced.data; - centroidCount = reduced.centroidCount; - } - - @Override - public void compress(GroupTree other) { - throw new UnsupportedOperationException("Default operation"); - } - - @Override - public int size() { - return totalWeight; - } - - @Override - public double cdf(double x) { - if (size() == 0) { - return Double.NaN; - } else if (size() == 1) { - return x < data.get(0).centroids[0] ? 0 : 1; - } else { - double r = 0; - - // we scan a across the centroids - Iterator it = iterator(0, 0); - Index a = it.next(); - - // b is the look-ahead to the next centroid - Index b = it.next(); - - // initially, we set left width equal to right width - double left = (b.mean() - a.mean()) / 2; - double right = left; - - // scan to next to last element - while (it.hasNext()) { - if (x < a.mean() + right) { - return (r + a.count() * AbstractTDigest.interpolate(x, a.mean() - left, a.mean() + right)) / totalWeight; - } - r += a.count(); - - a = b; - b = it.next(); - - left = right; - right = (b.mean() - a.mean()) / 2; - } - - // for the last element, assume right width is same as left - left = right; - a = b; - if (x < a.mean() + right) { - return (r + a.count() * AbstractTDigest.interpolate(x, a.mean() - left, a.mean() + right)) / totalWeight; - } else { - return 1; - } - } - } - - @Override - public double quantile(double q) { - if (q < 0 || q > 1) { - throw new IllegalArgumentException("q should be in [0,1], got " + q); - } - - if (centroidCount() == 0) { - return Double.NaN; - } else if (centroidCount() == 1) { - return data.get(0).centroids[0]; - } - - // if values were stored in a sorted array, index would be the offset we are interested in - final double index = q * (size() - 1); - - double previousMean = Double.NaN, previousIndex = 0; - long total = 0; - Index next; - Iterator it = iterator(0, 0); - while (true) { - next = it.next(); - final double nextIndex = total + (next.count() - 1.0) / 2; - if (nextIndex >= index) { - if (Double.isNaN(previousMean)) { - // special case 1: the index we are interested in is before the 1st centroid - if (nextIndex == previousIndex) { - return next.mean(); - } - // assume values grow linearly between index previousIndex=0 and nextIndex2 - Index next2 = it.next(); - final double nextIndex2 = total + next.count() + (next2.count() - 1.0) / 2; - previousMean = (nextIndex2 * next.mean() - nextIndex * next2.mean()) / (nextIndex2 - nextIndex); - } - // common case: we found two centroids previous and next so that the desired quantile is - // after 'previous' but before 'next' - return quantile(previousIndex, index, nextIndex, previousMean, next.mean()); - } else if (!it.hasNext()) { - // special case 2: the index we are interested in is beyond the last centroid - // again, assume values grow linearly between index previousIndex and (count - 1) - // which is the highest possible index - final double nextIndex2 = size() - 1; - final double nextMean2 = (next.mean() * (nextIndex2 - previousIndex) - previousMean * (nextIndex2 - nextIndex)) / (nextIndex - previousIndex); - return quantile(nextIndex, index, nextIndex2, next.mean(), nextMean2); - } - total += next.count(); - previousMean = next.mean(); - previousIndex = nextIndex; - } - } - - @Override - public int centroidCount() { - return centroidCount; - } - - @Override - public Iterable centroids() { - List r = new ArrayList(); - Iterator ix = iterator(0, 0); - while (ix.hasNext()) { - Index index = ix.next(); - Page current = data.get(index.page); - Centroid centroid = new Centroid(current.centroids[index.subPage], current.counts[index.subPage]); - if (current.history != null) { - for (double x : current.history.get(index.subPage)) { - centroid.insertData(x); - } - } - r.add(centroid); - } - return r; - } - - public Iterator allAfter(double x) { - if (data.size() == 0) { - return iterator(0, 0); - } else { - - for (int i = 1; i < data.size(); i++) { - if (data.get(i).centroids[0] >= x) { - Page previous = data.get(i - 1); - for (int j = 0; j < previous.active; j++) { - if (previous.centroids[j] > x) { - return iterator(i - 1, j); - } - } - return iterator(i, 0); - } - } - - Page last = data.get(data.size() - 1); - for (int j = 0; j < last.active; j++) { - if (last.centroids[j] > x) { - return iterator(data.size() - 1, j); - } - } - return iterator(data.size(), 0); - } - } - - /** - * Returns a cursor pointing to the first element <= x. Exposed only for testing. - * @param x The value used to find the cursor. - * @return The cursor. - */ - public Index floor(double x) { - Iterator rx = allBefore(x); - if (!rx.hasNext()) { - return null; - } - Index r = rx.next(); - Index z = r; - while (rx.hasNext() && mean(z) == x) { - r = z; - z = rx.next(); - } - return r; - } - - public Index ceiling(double x) { - Iterator r = allAfter(x); - return r.hasNext() ? r.next() : null; - } - - /** - * Returns an iterator which will give each element <= to x in non-increasing order. - * - * @param x The upper bound of all returned elements - * @return An iterator that returns elements in non-increasing order. - */ - public Iterator allBefore(double x) { - if (data.size() == 0) { - return iterator(0, 0); - } else { - for (int i = 1; i < data.size(); i++) { - if (data.get(i).centroids[0] > x) { - Page previous = data.get(i - 1); - for (int j = 0; j < previous.active; j++) { - if (previous.centroids[j] > x) { - return reverse(i - 1, j - 1); - } - } - return reverse(i, -1); - } - } - Page last = data.get(data.size() - 1); - for (int j = 0; j < last.active; j++) { - if (last.centroids[j] > x) { - return reverse(data.size() - 1, j - 1); - } - } - return reverse(data.size(), -1); - } - } - - public Index increment(Index x, int delta) { - int i = x.page; - int j = x.subPage + delta; - - while (i < data.size() && j >= data.get(i).active) { - j -= data.get(i).active; - i++; - } - - while (i > 0 && j < 0) { - i--; - j += data.get(i).active; - } - return new Index(i, j); - } - - @Override - public double compression() { - return compression; - } - - /** - * Returns an upper bound on the number bytes that will be required to represent this histogram. - */ - @Override - public int byteSize() { - return 4 + 8 + 8 + centroidCount * 12; - } - - /** - * Returns an upper bound on the number of bytes that will be required to represent this histogram in - * the tighter representation. - */ - @Override - public int smallByteSize() { - int bound = byteSize(); - ByteBuffer buf = ByteBuffer.allocate(bound); - asSmallBytes(buf); - return buf.position(); - } - - /** - * Outputs a histogram as bytes using a particularly cheesy encoding. - */ - @Override - public void asBytes(ByteBuffer buf) { - buf.putInt(VERBOSE_ARRAY_DIGEST); - buf.putDouble(compression()); - buf.putInt(pageSize); - buf.putInt(centroidCount); - for (Page page : data) { - for (int i = 0; i < page.active; i++) { - buf.putDouble(page.centroids[i]); - } - } - for (Page page : data) { - for (int i = 0; i < page.active; i++) { - buf.putInt(page.counts[i]); - } - } - } - - @Override - public void asSmallBytes(ByteBuffer buf) { - buf.putInt(SMALL_ARRAY_DIGEST); - buf.putDouble(compression()); - buf.putInt(pageSize); - buf.putInt(centroidCount); - - double x = 0; - for (Page page : data) { - for (int i = 0; i < page.active; i++) { - double mean = page.centroids[i]; - double delta = mean - x; - x = mean; - buf.putFloat((float) delta); - } - } - for (Page page : data) { - for (int i = 0; i < page.active; i++) { - int n = page.counts[i]; - encode(buf, n); - } - } - } - - /** - * Reads a histogram from a byte buffer - * - * @return The new histogram structure - */ - public static ArrayDigest fromBytes(ByteBuffer buf) { - int encoding = buf.getInt(); - if (encoding == VERBOSE_ENCODING || encoding == VERBOSE_ARRAY_DIGEST) { - double compression = buf.getDouble(); - int pageSize = 32; - if (encoding == VERBOSE_ARRAY_DIGEST) { - pageSize = buf.getInt(); - } - ArrayDigest r = new ArrayDigest(pageSize, compression); - int n = buf.getInt(); - double[] means = new double[n]; - for (int i = 0; i < n; i++) { - means[i] = buf.getDouble(); - } - for (int i = 0; i < n; i++) { - r.add(means[i], buf.getInt()); - } - return r; - } else if (encoding == SMALL_ENCODING || encoding == SMALL_ARRAY_DIGEST) { - double compression = buf.getDouble(); - int pageSize = 32; - if (encoding == SMALL_ARRAY_DIGEST) { - pageSize = buf.getInt(); - } - ArrayDigest r = new ArrayDigest(pageSize, compression); - int n = buf.getInt(); - double[] means = new double[n]; - double x = 0; - for (int i = 0; i < n; i++) { - double delta = buf.getFloat(); - x += delta; - means[i] = x; - } - - for (int i = 0; i < n; i++) { - int z = decode(buf); - r.add(means[i], z); - } - return r; - } else { - throw new IllegalStateException("Invalid format for serialized histogram"); - } - } - - private List history(Index index) { - List> h = data.get(index.page).history; - return h == null ? null : h.get(index.subPage); - } - - private void delete(Index index) { - // don't want to delete empty pages here because other indexes would be screwed up. - // this should almost never happen anyway since deletes only cause small ordering - // changes - totalWeight -= count(index); - centroidCount--; - data.get(index.page).delete(index.subPage); - } - - private Iterable inclusiveTail(final Index start) { - return new Iterable() { - @Override - public Iterator iterator() { - return ArrayDigest.this.iterator(start.page, start.subPage); - } - }; - } - - void addRaw(double x, int w) { - List tmp = new ArrayList(); - tmp.add(x); - addRaw(x, w, recordAllData ? tmp : null); - } - - void addRaw(double x, int w, List history) { - if (centroidCount == 0) { - Page page = new Page(pageSize, recordAllData); - page.add(x, w, history); - totalWeight += w; - centroidCount++; - data.add(page); - } else { - for (int i = 1; i < data.size(); i++) { - if (data.get(i).centroids[0] > x) { - Page newPage = data.get(i - 1).add(x, w, history); - totalWeight += w; - centroidCount++; - if (newPage != null) { - data.add(i, newPage); - } - return; - } - } - Page newPage = data.get(data.size() - 1).add(x, w, history); - totalWeight += w; - centroidCount++; - if (newPage != null) { - data.add(data.size(), newPage); - } - } - } - - @Override - void add(double x, int w, Centroid base) { - addRaw(x, w, base.data()); - } - - private Iterator iterator(final int startPage, final int startSubPage) { - return new Iterator() { - int page = startPage; - int subPage = startSubPage; - Index end = new Index(-1, -1); - Index next = null; - - @Override - public boolean hasNext() { - if (next == null) { - next = computeNext(); - } - return next != end; - } - - @Override - public Index next() { - if (hasNext()) { - Index r = next; - next = null; - return r; - } else { - throw new NoSuchElementException("Can't iterate past end of data"); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Default operation"); - } - - protected Index computeNext() { - if (page >= data.size()) { - return end; - } else { - Page current = data.get(page); - if (subPage >= current.active) { - subPage = 0; - page++; - return computeNext(); - } else { - Index r = new Index(page, subPage); - subPage++; - return r; - } - } - } - }; - } - - private Iterator reverse(final int startPage, final int startSubPage) { - return new Iterator() { - int page = startPage; - int subPage = startSubPage; - - Index end = new Index(-1, -1); - Index next = null; - - @Override - public boolean hasNext() { - if (next == null) { - next = computeNext(); - } - return next != end; - } - - @Override - public Index next() { - if (hasNext()) { - Index r = next; - next = null; - return r; - } else { - throw new NoSuchElementException("Can't reverse iterate before beginning of data"); - } - } - - @Override - public void remove() { - throw new UnsupportedOperationException("Default operation"); - } - - protected Index computeNext() { - if (page < 0) { - return end; - } else { - if (subPage < 0) { - page--; - if (page >= 0) { - subPage = data.get(page).active - 1; - } - return computeNext(); - } else { - Index r = new Index(page, subPage); - subPage--; - return r; - } - } - } - }; - } - - public final static int VERBOSE_ENCODING = 1; - public final static int SMALL_ENCODING = 2; - public final static int VERBOSE_ARRAY_DIGEST = 3; - public final static int SMALL_ARRAY_DIGEST = 4; - - class Index { - final int page, subPage; - - private Index(int page, int subPage) { - this.page = page; - this.subPage = subPage; - } - - double mean() { - return data.get(page).centroids[subPage]; - } - - int count() { - return data.get(page).counts[subPage]; - } - } - - private static class Page { - private final boolean recordAllData; - private final int pageSize; - - int totalCount; - int active; - double[] centroids; - int[] counts; - List> history; - - private Page(int pageSize, boolean recordAllData) { - this.pageSize = pageSize; - this.recordAllData = recordAllData; - centroids = new double[this.pageSize]; - counts = new int[this.pageSize]; - history = this.recordAllData ? new ArrayList>() : null; - } - - public Page add(double x, int w, List history) { - for (int i = 0; i < active; i++) { - if (centroids[i] >= x) { - // insert at i - if (active >= pageSize) { - // split page - Page newPage = split(); - if (i < pageSize / 2) { - addAt(i, x, w, history); - } else { - newPage.addAt(i - pageSize / 2, x, w, history); - } - return newPage; - } else { - addAt(i, x, w, history); - return null; - } - } - } - - // insert at end - if (active >= pageSize) { - // split page - Page newPage = split(); - newPage.addAt(pageSize / 2, x, w, history); - return newPage; - } else { - addAt(active, x, w, history); - return null; - } - } - - private void addAt(int i, double x, int w, List history) { - if (i < active) { - // shift data to make room - System.arraycopy(centroids, i, centroids, i + 1, active - i); - System.arraycopy(counts, i, counts, i + 1, active - i); - if (this.history != null) { - this.history.add(i, history); - } - centroids[i] = x; - counts[i] = w; - } else { - centroids[active] = x; - counts[active] = w; - if (this.history != null) { - this.history.add(history); - } - } - active++; - totalCount += w; - } - - private Page split() { - Page newPage = new Page(pageSize, recordAllData); - System.arraycopy(centroids, 16, newPage.centroids, 0, pageSize / 2); - System.arraycopy(counts, 16, newPage.counts, 0, pageSize / 2); - if (history != null) { - newPage.history = new ArrayList>(); - newPage.history.addAll(history.subList(pageSize / 2, pageSize)); - - List> tmp = new ArrayList>(); - tmp.addAll(history.subList(0, pageSize / 2)); - history = tmp; - } - active = 16; - newPage.active = 16; - - newPage.totalCount = totalCount; - totalCount = 0; - for (int i = 0; i < 16; i++) { - totalCount += counts[i]; - newPage.totalCount -= counts[i]; - } - - return newPage; - } - - public void delete(int i) { - int w = counts[i]; - if (i != active - 1) { - System.arraycopy(centroids, i + 1, centroids, i, active - i - 1); - System.arraycopy(counts, i + 1, counts, i, active - i - 1); - if (history != null) { - history.remove(i); - } - } - active--; - totalCount -= w; - } - } -} diff --git a/All/Genesis-OOB/Genesis#19/pair.info b/All/Genesis-OOB/Genesis#19/pair.info deleted file mode 100755 index 721a709..0000000 --- a/All/Genesis-OOB/Genesis#19/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:19 -SATName:Genesis -modifiedFPath:src/main/java/com/tdunning/math/stats/ArrayDigest.java -comSha:b3f0a26d4e23af01bfdf9f9572a699db160095fa -parentComSha:b3f0a26d4e23af01bfdf9f9572a699db160095fa^1 -githubUrl:https://github.com/tdunning/t-digest -repoName:tdunning#t-digest \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#206/comMsg.txt b/All/Genesis-OOB/Genesis#206/comMsg.txt deleted file mode 100755 index b3c659f..0000000 --- a/All/Genesis-OOB/Genesis#206/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixed StringIndexOutOfBoundsException caused by bad DOCTYPE node handling of multi-byte UTF-8 characters diff --git a/All/Genesis-OOB/Genesis#206/diff.diff b/All/Genesis-OOB/Genesis#206/diff.diff deleted file mode 100755 index 913646d..0000000 --- a/All/Genesis-OOB/Genesis#206/diff.diff +++ /dev/null @@ -1,16 +0,0 @@ -diff --git a/src/main/java/org/w3c/tidy/Lexer.java b/src/main/java/org/w3c/tidy/Lexer.java -index 1a9de61..4f95a93 100644 ---- a/src/main/java/org/w3c/tidy/Lexer.java -+++ b/src/main/java/org/w3c/tidy/Lexer.java -@@ -1033,4 +1033,5 @@ public class Lexer -- return !(TidyUtils.findBadSubString("SYSTEM", s, len) -- || TidyUtils.findBadSubString("PUBLIC", s, len) -- || TidyUtils.findBadSubString("//DTD", s, len) -- || TidyUtils.findBadSubString("//W3C", s, len) || TidyUtils.findBadSubString("//EN", s, len)); -+ return !(TidyUtils.findBadSubString("SYSTEM", s, s.length()) -+ || TidyUtils.findBadSubString("PUBLIC", s, s.length()) -+ || TidyUtils.findBadSubString("//DTD", s, s.length()) -+ || TidyUtils.findBadSubString("//W3C", s, s.length()) -+ || TidyUtils.findBadSubString("//EN", s, s.length())); -@@ -4062,0 +4064 @@ public class Lexer -+ diff --git a/All/Genesis-OOB/Genesis#206/new/Lexer.java b/All/Genesis-OOB/Genesis#206/new/Lexer.java deleted file mode 100755 index 4f95a93..0000000 --- a/All/Genesis-OOB/Genesis#206/new/Lexer.java +++ /dev/null @@ -1,4064 +0,0 @@ -/* - * Java HTML Tidy - JTidy - * HTML parser and pretty printer - * - * Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts - * Institute of Technology, Institut National de Recherche en - * Informatique et en Automatique, Keio University). All Rights - * Reserved. - * - * Contributing Author(s): - * - * Dave Raggett - * Andy Quick (translation to Java) - * Gary L Peskin (Java development) - * Sami Lempinen (release management) - * Fabrizio Giustina - * - * The contributing author(s) would like to thank all those who - * helped with testing, bug fixes, and patience. This wouldn't - * have been possible without all of you. - * - * COPYRIGHT NOTICE: - * - * This software and documentation is provided "as is," and - * the copyright holders and contributing author(s) make no - * representations or warranties, express or implied, including - * but not limited to, warranties of merchantability or fitness - * for any particular purpose or that the use of the software or - * documentation will not infringe any third party patents, - * copyrights, trademarks or other rights. - * - * The copyright holders and contributing author(s) will not be - * liable for any direct, indirect, special or consequential damages - * arising out of any use of the software or documentation, even if - * advised of the possibility of such damage. - * - * Permission is hereby granted to use, copy, modify, and distribute - * this source code, or portions hereof, documentation and executables, - * for any purpose, without fee, subject to the following restrictions: - * - * 1. The origin of this source code must not be misrepresented. - * 2. Altered versions must be plainly marked as such and must - * not be misrepresented as being the original source. - * 3. This Copyright notice may not be removed or altered from any - * source or altered source distribution. - * - * The copyright holders and contributing author(s) specifically - * permit, without fee, and encourage the use of this source code - * as a component for supporting the Hypertext Markup Language in - * commercial products. If you use this source code in a product, - * acknowledgment is not required but would be appreciated. - * - */ -package org.w3c.tidy; - -import java.io.PrintWriter; -import java.util.List; -import java.util.Stack; -import java.util.Vector; - - -/** - * Lexer for html parser. - *

- * Given a file stream fp it returns a sequence of tokens. GetToken(fp) gets the next token UngetToken(fp) provides one - * level undo The tags include an attribute list: - linked list of attribute/value nodes - each node has 2 - * null-terminated strings. - entities are replaced in attribute values white space is compacted if not in preformatted - * mode If not in preformatted mode then leading white space is discarded and subsequent white space sequences compacted - * to single space chars. If XmlTags is no then Tag names are folded to upper case and attribute names to lower case. - * Not yet done: - Doctype subset and marked sections - *

- * @author Dave Raggett dsr@w3.org - * @author Andy Quick ac.quick@sympatico.ca (translation to Java) - * @author Fabrizio Giustina - * @version $Revision$ ($Author$) - */ -public class Lexer -{ - - /** - * state: ignore whitespace. - */ - public static final short IGNORE_WHITESPACE = 0; - - /** - * state: mixed content. - */ - public static final short MIXED_CONTENT = 1; - - /** - * state: preformatted. - */ - public static final short PREFORMATTED = 2; - - /** - * state: ignore markup. - */ - public static final short IGNORE_MARKUP = 3; - - /** - * URI for XHTML 1.0 transitional DTD. - */ - private static final String VOYAGER_LOOSE = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"; - - /** - * URI for XHTML 1.0 strict DTD. - */ - private static final String VOYAGER_STRICT = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"; - - /** - * URI for XHTML 1.0 frameset DTD. - */ - private static final String VOYAGER_FRAMESET = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"; - - /** - * URI for XHTML 1.1. - */ - private static final String VOYAGER_11 = "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"; - - /** - * URI for XHTML Basic 1.0. - */ - // private static final String VOYAGER_BASIC = "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd"; - /** - * xhtml namespace. - */ - private static final String XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; - - /** - * lists all the known versions. - */ - private static final Lexer.W3CVersionInfo[] W3CVERSION = { - new W3CVersionInfo("HTML 4.01", "XHTML 1.0 Strict", VOYAGER_STRICT, Dict.VERS_HTML40_STRICT), - new W3CVersionInfo("HTML 4.01 Transitional", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML40_LOOSE), - new W3CVersionInfo("HTML 4.01 Frameset", "XHTML 1.0 Frameset", VOYAGER_FRAMESET, Dict.VERS_FRAMESET), - new W3CVersionInfo("HTML 4.0", "XHTML 1.0 Strict", VOYAGER_STRICT, Dict.VERS_HTML40_STRICT), - new W3CVersionInfo("HTML 4.0 Transitional", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML40_LOOSE), - new W3CVersionInfo("HTML 4.0 Frameset", "XHTML 1.0 Frameset", VOYAGER_FRAMESET, Dict.VERS_FRAMESET), - new W3CVersionInfo("HTML 3.2", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML32), - new W3CVersionInfo("HTML 3.2 Final", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML32), - new W3CVersionInfo("HTML 3.2 Draft", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML32), - new W3CVersionInfo("HTML 2.0", "XHTML 1.0 Strict", VOYAGER_STRICT, Dict.VERS_HTML20), - new W3CVersionInfo("HTML 4.01", "XHTML 1.1", VOYAGER_STRICT, Dict.VERS_XHTML11)}; - - /** - * getToken state: content. - */ - private static final short LEX_CONTENT = 0; - - /** - * getToken state: gt. - */ - private static final short LEX_GT = 1; - - /** - * getToken state: endtag. - */ - private static final short LEX_ENDTAG = 2; - - /** - * getToken state: start tag. - */ - private static final short LEX_STARTTAG = 3; - - /** - * getToken state: comment. - */ - private static final short LEX_COMMENT = 4; - - /** - * getToken state: doctype. - */ - private static final short LEX_DOCTYPE = 5; - - /** - * getToken state: procinstr. - */ - private static final short LEX_PROCINSTR = 6; - - /** - * getToken state: cdata. - */ - private static final short LEX_CDATA = 8; - - /** - * getToken state: section. - */ - private static final short LEX_SECTION = 9; - - /** - * getToken state: asp. - */ - private static final short LEX_ASP = 10; - - /** - * getToken state: jste. - */ - private static final short LEX_JSTE = 11; - - /** - * getToken state: php. - */ - private static final short LEX_PHP = 12; - - /** - * getToken state: xml declaration. - */ - private static final short LEX_XMLDECL = 13; - - /** - * file stream. - */ - protected StreamIn in; - - /** - * error output stream. - */ - protected PrintWriter errout; - - /** - * for accessibility errors. - */ - protected short badAccess; - - /** - * for bad style errors. - */ - protected short badLayout; - - /** - * for bad char encodings. - */ - protected short badChars; - - /** - * for mismatched/mispositioned form tags. - */ - protected short badForm; - - /** - * count of warnings in this document. - */ - protected short warnings; - - /** - * count of errors. - */ - protected short errors; - - /** - * lines seen. - */ - protected int lines; - - /** - * at start of current token. - */ - protected int columns; - - /** - * used to collapse contiguous white space. - */ - protected boolean waswhite; - - /** - * true after token has been pushed back. - */ - protected boolean pushed; - - /** - * when space is moved after end tag. - */ - protected boolean insertspace; - - /** - * Netscape compatibility. - */ - protected boolean excludeBlocks; - - /** - * true if moved out of table. - */ - protected boolean exiled; - - /** - * true if xmlns attribute on html element. - */ - protected boolean isvoyager; - - /** - * bit vector of HTML versions. - */ - protected short versions; - - /** - * version as given by doctype (if any). - */ - protected int doctype; - - /** - * set if html or PUBLIC is missing. - */ - protected boolean badDoctype; - - /** - * start of current node. - */ - protected int txtstart; - - /** - * end of current node. - */ - protected int txtend; - - /** - * state of lexer's finite state machine. - */ - protected short state; - - /** - * current node. - */ - protected Node token; - - /** - * Lexer character buffer parse tree nodes span onto this buffer which contains the concatenated text contents of - * all of the elements. Lexsize must be reset for each file. Byte buffer of UTF-8 chars. - */ - protected byte[] lexbuf; - - /** - * allocated. - */ - protected int lexlength; - - /** - * used. - */ - protected int lexsize; - - /** - * Inline stack for compatibility with Mosaic. For deferring text node. - */ - protected Node inode; - - /** - * for inferring inline tags. - */ - protected int insert; - - /** - * stack. - */ - protected Stack istack; - - /** - * start of frame. - */ - protected int istackbase; - - /** - * used for cleaning up presentation markup. - */ - protected Style styles; - - /** - * configuration. - */ - protected Configuration configuration; - - /** - * already seen end body tag? - */ - protected boolean seenEndBody; - - /** - * already seen end html tag? - */ - protected boolean seenEndHtml; - - /** - * report. - */ - protected Report report; - - /** - * Root node is saved here. - */ - protected Node root; - - /** - * node list. - */ - private List nodeList; - - /** - * Instantiates a new Lexer. - * @param in StreamIn - * @param configuration configuation instance - * @param report report instance, for reporting errors - */ - public Lexer(StreamIn in, Configuration configuration, Report report) - { - this.report = report; - this.in = in; - this.lines = 1; - this.columns = 1; - this.state = LEX_CONTENT; - this.versions = (Dict.VERS_ALL | Dict.VERS_PROPRIETARY); - this.doctype = Dict.VERS_UNKNOWN; - this.insert = -1; - this.istack = new Stack(); - this.configuration = configuration; - this.nodeList = new Vector(); - } - - /** - * Creates a new node and add it to nodelist. - * @return Node - */ - public Node newNode() - { - Node node = new Node(); - this.nodeList.add(node); - return node; - } - - /** - * Creates a new node and add it to nodelist. - * @param type node type: Node.ROOT_NODE | Node.DOCTYPE_TAG | Node.COMMENT_TAG | Node.PROC_INS_TAG | Node.TEXT_NODE | - * Node.START_TAG | Node.END_TAG | Node.START_END_TAG | Node.CDATA_TAG | Node.SECTION_TAG | Node. ASP_TAG | - * Node.JSTE_TAG | Node.PHP_TAG | Node.XML_DECL - * @param textarray array of bytes contained in the Node - * @param start start position - * @param end end position - * @return Node - */ - public Node newNode(short type, byte[] textarray, int start, int end) - { - Node node = new Node(type, textarray, start, end); - this.nodeList.add(node); - return node; - } - - /** - * Creates a new node and add it to nodelist. - * @param type node type: Node.ROOT_NODE | Node.DOCTYPE_TAG | Node.COMMENT_TAG | Node.PROC_INS_TAG | Node.TEXT_NODE | - * Node.START_TAG | Node.END_TAG | Node.START_END_TAG | Node.CDATA_TAG | Node.SECTION_TAG | Node. ASP_TAG | - * Node.JSTE_TAG | Node.PHP_TAG | Node.XML_DECL - * @param textarray array of bytes contained in the Node - * @param start start position - * @param end end position - * @param element tag name - * @return Node - */ - public Node newNode(short type, byte[] textarray, int start, int end, String element) - { - Node node = new Node(type, textarray, start, end, element, this.configuration.tt); - this.nodeList.add(node); - return node; - } - - /** - * Clones a node and add it to node list. - * @param node Node - * @return cloned Node - */ - public Node cloneNode(Node node) - { - Node cnode = (Node) node.clone(); - this.nodeList.add(cnode); - for (AttVal att = cnode.attributes; att != null; att = att.next) - { - if (att.asp != null) - { - this.nodeList.add(att.asp); - } - if (att.php != null) - { - this.nodeList.add(att.php); - } - } - return cnode; - } - - /** - * Clones an attribute value and add eventual asp or php node to node list. - * @param attrs original AttVal - * @return cloned AttVal - */ - public AttVal cloneAttributes(AttVal attrs) - { - AttVal cattrs = (AttVal) attrs.clone(); - for (AttVal att = cattrs; att != null; att = att.next) - { - if (att.asp != null) - { - this.nodeList.add(att.asp); - } - if (att.php != null) - { - this.nodeList.add(att.php); - } - } - return cattrs; - } - - /** - * Update oldtextarray in the current nodes. - * @param oldtextarray previous text array - * @param newtextarray new text array - */ - protected void updateNodeTextArrays(byte[] oldtextarray, byte[] newtextarray) - { - Node node; - for (int i = 0; i < this.nodeList.size(); i++) - { - node = (Node) (this.nodeList.get(i)); - if (node.textarray == oldtextarray) - { - node.textarray = newtextarray; - } - } - } - - /** - * Adds a new line node. Used for creating preformatted text from Word2000. - * @return new line node - */ - public Node newLineNode() - { - Node node = newNode(); - - node.textarray = this.lexbuf; - node.start = this.lexsize; - addCharToLexer('\n'); - node.end = this.lexsize; - return node; - } - - /** - * Has end of input stream been reached? - * @return true if end of input stream been reached - */ - public boolean endOfInput() - { - return this.in.isEndOfStream(); - } - - /** - * Adds a byte to lexer buffer. - * @param c byte to add - */ - public void addByte(int c) - { - if (this.lexsize + 1 >= this.lexlength) - { - while (this.lexsize + 1 >= this.lexlength) - { - if (this.lexlength == 0) - { - this.lexlength = 8192; - } - else - { - this.lexlength = this.lexlength * 2; - } - } - - byte[] temp = this.lexbuf; - this.lexbuf = new byte[this.lexlength]; - if (temp != null) - { - System.arraycopy(temp, 0, this.lexbuf, 0, temp.length); - updateNodeTextArrays(temp, this.lexbuf); - } - } - - this.lexbuf[this.lexsize++] = (byte) c; - this.lexbuf[this.lexsize] = (byte) '\0'; // debug - } - - /** - * Substitute the last char in buffer. - * @param c new char - */ - public void changeChar(byte c) - { - if (this.lexsize > 0) - { - this.lexbuf[this.lexsize - 1] = c; - } - } - - /** - * Store char c as UTF-8 encoded byte stream. - * @param c char to store - */ - public void addCharToLexer(int c) - { - // Allow only valid XML characters. See: http://www.w3.org/TR/2004/REC-xml-20040204/#NT-Char - // Fix by Pablo Mayrgundter 17-08-2004 - - if ((this.configuration.xmlOut || this.configuration.xHTML) // only for xml output - && !((c >= 0x20 && c <= 0xD7FF) // Check the common-case first. - || c == 0x9 - || c == 0xA - || c == 0xD // Then white-space. - || (c >= 0xE000 && c <= 0xFFFD) // Then high-range unicode. - || (c >= 0x10000 && c <= 0x10FFFF))) - { - return; - } - - int i = 0; - int[] count = new int[]{0}; - byte[] buf = new byte[10]; // unsigned char - - boolean err = EncodingUtils.encodeCharToUTF8Bytes(c, buf, null, count); - if (err) - { - // replacement char 0xFFFD encoded as UTF-8 - buf[0] = (byte) 0xEF; - buf[1] = (byte) 0xBF; - buf[2] = (byte) 0xBD; - count[0] = 3; - } - - for (i = 0; i < count[0]; i++) - { - addByte(buf[i]); // uint - } - - } - - /** - * Adds a string to lexer buffer. - * @param str String to add - */ - public void addStringToLexer(String str) - { - for (int i = 0; i < str.length(); i++) - { - addCharToLexer(str.charAt(i)); - } - } - - /** - * Parse an html entity. - * @param mode mode - */ - public void parseEntity(short mode) - { - // No longer attempts to insert missing ';' for unknown - // entities unless one was present already, since this - // gives unexpected results. - // - // For example: - // was tidied to: - // rather than: - // - // My thanks for Maurice Buxton for spotting this. - // - // Also Randy Waki pointed out the following case for the - // 04 Aug 00 version (bug #433012): - // - // For example: - // was tidied to: - // rather than: - // - // where "lang" is a known entity (#9001), but browsers would - // misinterpret "⟨" because it had a value > 256. - // - // So the case of an apparently known entity with a value > 256 and - // missing a semicolon is handled specially. - // - // "ParseEntity" is also a bit of a misnomer - it handles entities and - // numeric character references. Invalid NCR's are now reported. - - int start; - boolean first = true; - boolean semicolon = false; - int c, ch, startcol; - String str; - - start = this.lexsize - 1; // to start at "&" - startcol = this.in.getCurcol() - 1; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - if (c == ';') - { - semicolon = true; - break; - } - - if (first && c == '#') - { - // #431953 - start RJ - if (!this.configuration.ncr - || "BIG5".equals(this.configuration.getInCharEncodingName()) - || "SHIFTJIS".equals(this.configuration.getInCharEncodingName())) - { - this.in.ungetChar(c); - return; - } - // #431953 - end RJ - - addCharToLexer(c); - first = false; - continue; - } - - first = false; - - if (TidyUtils.isNamechar((char) c)) - { - addCharToLexer(c); - continue; - } - - // otherwise put it back - this.in.ungetChar(c); - break; - } - - str = TidyUtils.getString(this.lexbuf, start, this.lexsize - start); - - if ("&apos".equals(str) && !configuration.xmlOut && !this.isvoyager && !configuration.xHTML) - { - report.entityError(this, Report.APOS_UNDEFINED, str, 39); - } - - ch = EntityTable.getDefaultEntityTable().entityCode(str); - - // drops invalid numeric entities from XML mode. Fix by Pablo Mayrgundter 17-08-2004 - // if ((this.configuration.xmlOut || this.configuration.xHTML) // only for xml output - // && !((ch >= 0x20 && ch <= 0xD7FF) // Check the common-case first. - // || ch == 0x9 || ch == 0xA || ch == 0xD // Then white-space. - // || (ch >= 0xE000 && ch <= 0xFFFD))) - // { - // this.lexsize = start; - // return; - // } - - // deal with unrecognized or invalid entities - // #433012 - fix by Randy Waki 17 Feb 01 - // report invalid NCR's - Terry Teague 01 Sep 01 - if (ch <= 0 || (ch >= 256 && c != ';')) - { - // set error position just before offending character - this.lines = this.in.getCurline(); - this.columns = startcol; - - if (this.lexsize > start + 1) - { - if (ch >= 128 && ch <= 159) - { - // invalid numeric character reference - int c1 = 0; - - if ("WIN1252".equals(configuration.replacementCharEncoding)) - { - c1 = EncodingUtils.decodeWin1252(ch); - } - else if ("MACROMAN".equals(configuration.replacementCharEncoding)) - { - c1 = EncodingUtils.decodeMacRoman(ch); - } - - // "or" DISCARDED_CHAR with the other errors if discarding char; otherwise default is replacing - - int replaceMode = c1 != 0 ? Report.REPLACED_CHAR : Report.DISCARDED_CHAR; - - if (c != ';') /* issue warning if not terminated by ';' */ - { - report.entityError(this, Report.MISSING_SEMICOLON_NCR, str, c); - } - - report.encodingError(this, (short) (Report.INVALID_NCR | replaceMode), ch); - - if (c1 != 0) - { - // make the replacement - this.lexsize = start; - addCharToLexer(c1); - semicolon = false; - } - else - { - /* discard */ - this.lexsize = start; - semicolon = false; - } - - } - else - { - report.entityError(this, Report.UNKNOWN_ENTITY, str, ch); - } - - if (semicolon) - { - addCharToLexer(';'); - } - } - else - { - // naked & - report.entityError(this, Report.UNESCAPED_AMPERSAND, str, ch); - } - } - else - { - // issue warning if not terminated by ';' - if (c != ';') - { - // set error position just before offending character - this.lines = this.in.getCurline(); - this.columns = startcol; - report.entityError(this, Report.MISSING_SEMICOLON, str, c); - } - - this.lexsize = start; - - if (ch == 160 && TidyUtils.toBoolean(mode & PREFORMATTED)) - { - ch = ' '; - } - - addCharToLexer(ch); - - if (ch == '&' && !this.configuration.quoteAmpersand) - { - addCharToLexer('a'); - addCharToLexer('m'); - addCharToLexer('p'); - addCharToLexer(';'); - } - } - } - - /** - * Parses a tag name. - * @return first char after the tag name - */ - public char parseTagName() - { - int c; - - // fold case of first char in buffer - c = this.lexbuf[this.txtstart]; - - if (!this.configuration.xmlTags && TidyUtils.isUpper((char) c)) - { - c = TidyUtils.toLower((char) c); - this.lexbuf[this.txtstart] = (byte) c; - } - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - if (!TidyUtils.isNamechar((char) c)) - { - break; - } - - // fold case of subsequent chars - if (!this.configuration.xmlTags && TidyUtils.isUpper((char) c)) - { - c = TidyUtils.toLower((char) c); - } - - addCharToLexer(c); - } - - this.txtend = this.lexsize; - return (char) c; - } - - /** - * calls addCharToLexer for any char in the string. - * @param str input String - */ - public void addStringLiteral(String str) - { - int len = str.length(); - for (int i = 0; i < len; i++) - { - addCharToLexer(str.charAt(i)); - } - } - - /** - * calls addCharToLexer for any char in the string till len is reached. - * @param str input String - * @param len length of the substring to be added - */ - void addStringLiteralLen(String str, int len) - { - int strlen = str.length(); - if (strlen < len) - { - len = strlen; - } - for (int i = 0; i < len; i++) - { - addCharToLexer(str.charAt(i)); - } - } - - /** - * Choose what version to use for new doctype. - * @return html version constant - */ - public short htmlVersion() - { - if (TidyUtils.toBoolean(versions & Dict.VERS_HTML20)) - { - return Dict.VERS_HTML20; - } - - if (!(this.configuration.xmlOut | this.configuration.xmlTags | this.isvoyager) - && TidyUtils.toBoolean(versions & Dict.VERS_HTML32)) - { - return Dict.VERS_HTML32; - } - if (TidyUtils.toBoolean(versions & Dict.VERS_XHTML11)) - { - return Dict.VERS_XHTML11; - } - if (TidyUtils.toBoolean(versions & Dict.VERS_HTML40_STRICT)) - { - return Dict.VERS_HTML40_STRICT; - } - - if (TidyUtils.toBoolean(versions & Dict.VERS_HTML40_LOOSE)) - { - return Dict.VERS_HTML40_LOOSE; - } - - if (TidyUtils.toBoolean(versions & Dict.VERS_FRAMESET)) - { - return Dict.VERS_FRAMESET; - } - - return Dict.VERS_UNKNOWN; - } - - /** - * Choose what version to use for new doctype. - * @return html version name - */ - public String htmlVersionName() - { - short guessed; - int j; - - guessed = apparentVersion(); - - for (j = 0; j < W3CVERSION.length; ++j) - { - if (guessed == W3CVERSION[j].code) - { - if (this.isvoyager) - { - return W3CVERSION[j].voyagerName; - } - - return W3CVERSION[j].name; - } - } - - return null; - } - - /** - * Add meta element for Tidy. If the meta tag is already present, update release date. - * @param root root node - * @return true if the tag has been added - */ - public boolean addGenerator(Node root) - { - AttVal attval; - Node node; - Node head = root.findHEAD(this.configuration.tt); - - if (head != null) - { - String meta = "HTML Tidy for Java (vers. " + Report.RELEASE_DATE_STRING + "), see www.w3.org"; - - for (node = head.content; node != null; node = node.next) - { - if (node.tag == this.configuration.tt.tagMeta) - { - attval = node.getAttrByName("name"); - - if (attval != null && attval.value != null && "generator".equalsIgnoreCase(attval.value)) - { - attval = node.getAttrByName("content"); - - if (attval != null - && attval.value != null - && attval.value.length() >= 9 - && "HTML Tidy".equalsIgnoreCase(attval.value.substring(0, 9))) - { - attval.value = meta; - return false; - } - } - } - } - - node = this.inferredTag("meta"); - node.addAttribute("content", meta); - node.addAttribute("name", "generator"); - head.insertNodeAtStart(node); - return true; - } - - return false; - } - - /** - * Check system keywords (keywords should be uppercase). - * @param doctype doctype node - * @return true if doctype keywords are all uppercase - */ - public boolean checkDocTypeKeyWords(Node doctype) - { - int len = doctype.end - doctype.start; - String s = TidyUtils.getString(this.lexbuf, doctype.start, len); - - return !(TidyUtils.findBadSubString("SYSTEM", s, s.length()) - || TidyUtils.findBadSubString("PUBLIC", s, s.length()) - || TidyUtils.findBadSubString("//DTD", s, s.length()) - || TidyUtils.findBadSubString("//W3C", s, s.length()) - || TidyUtils.findBadSubString("//EN", s, s.length())); - } - - /** - * Examine DOCTYPE to identify version. - * @param doctype doctype node - * @return version code - */ - public short findGivenVersion(Node doctype) - { - String p, s; - int i, j; - int len; - String str1; - String str2; - - // if root tag for doctype isn't html give up now - str1 = TidyUtils.getString(this.lexbuf, doctype.start, 5); - if (!"html ".equalsIgnoreCase(str1)) - { - return 0; - } - - if (!checkDocTypeKeyWords(doctype)) - { - report.warning(this, doctype, null, Report.DTYPE_NOT_UPPER_CASE); - } - - // give up if all we are given is the system id for the doctype - str1 = TidyUtils.getString(this.lexbuf, doctype.start + 5, 7); - if ("SYSTEM ".equalsIgnoreCase(str1)) - { - // but at least ensure the case is correct - if (!str1.substring(0, 6).equals("SYSTEM")) - { - System.arraycopy(TidyUtils.getBytes("SYSTEM"), 0, this.lexbuf, doctype.start + 5, 6); - } - return 0; // unrecognized - } - - if ("PUBLIC ".equalsIgnoreCase(str1)) - { - if (!str1.substring(0, 6).equals("PUBLIC")) - { - System.arraycopy(TidyUtils.getBytes("PUBLIC "), 0, this.lexbuf, doctype.start + 5, 6); - } - } - else - { - this.badDoctype = true; - } - - for (i = doctype.start; i < doctype.end; ++i) - { - if (this.lexbuf[i] == (byte) '"') - { - str1 = TidyUtils.getString(this.lexbuf, i + 1, 12); - str2 = TidyUtils.getString(this.lexbuf, i + 1, 13); - if (str1.equals("-//W3C//DTD ")) - { - // compute length of identifier e.g. "HTML 4.0 Transitional" - for (j = i + 13; j < doctype.end && this.lexbuf[j] != (byte) '/'; ++j) - { - // - } - len = j - i - 13; - p = TidyUtils.getString(this.lexbuf, i + 13, len); - - for (j = 1; j < W3CVERSION.length; ++j) - { - s = W3CVERSION[j].name; - if (len == s.length() && s.equals(p)) - { - return W3CVERSION[j].code; - } - } - - // else unrecognized version - } - else if (str2.equals("-//IETF//DTD ")) - { - // compute length of identifier e.g. "HTML 2.0" - for (j = i + 14; j < doctype.end && this.lexbuf[j] != (byte) '/'; ++j) - { - // - } - len = j - i - 14; - - p = TidyUtils.getString(this.lexbuf, i + 14, len); - s = W3CVERSION[0].name; - if (len == s.length() && s.equals(p)) - { - return W3CVERSION[0].code; - } - - // else unrecognized version - } - break; - } - } - - return 0; - } - - /** - * Fix xhtml namespace. - * @param root root Node - * @param profile current profile - */ - public void fixHTMLNameSpace(Node root, String profile) - { - Node node; - AttVal attr; - - node = root.content; - while (node != null && node.tag != this.configuration.tt.tagHtml) - { - node = node.next; - } - - if (node != null) - { - - for (attr = node.attributes; attr != null; attr = attr.next) - { - if (attr.attribute.equals("xmlns")) - { - break; - } - - } - - if (attr != null) - { - if (!attr.value.equals(profile)) - { - report.warning(this, node, null, Report.INCONSISTENT_NAMESPACE); - attr.value = profile; - } - } - else - { - attr = new AttVal(node.attributes, null, '"', "xmlns", profile); - attr.dict = AttributeTable.getDefaultAttributeTable().findAttribute(attr); - node.attributes = attr; - } - } - } - - /** - * Put DOCTYPE declaration between the <:?xml version "1.0" ... ?> declaration, if any, and the - * html tag. Should also work for any comments, etc. that may precede the html tag. - * @param root root node - * @return new doctype node - */ - Node newXhtmlDocTypeNode(Node root) - { - Node html = root.findHTML(this.configuration.tt); - if (html == null) - { - return null; - } - - Node newdoctype = newNode(); - newdoctype.setType(Node.DOCTYPE_TAG); - newdoctype.next = html; - newdoctype.parent = root; - newdoctype.prev = null; - - if (html == root.content) - { - // No declaration. - root.content.prev = newdoctype; - root.content = newdoctype; - newdoctype.prev = null; - } - else - { - // we have an declaration. - newdoctype.prev = html.prev; - newdoctype.prev.next = newdoctype; - } - html.prev = newdoctype; - return newdoctype; - } - - /** - * Adds a new xhtml doctype to the document. - * @param root root node - * @return true if a doctype has been added - */ - public boolean setXHTMLDocType(Node root) - { - String fpi = " "; - String sysid = ""; - String namespace = XHTML_NAMESPACE; - String dtdsub = null; - Node doctype; - int dtdlen = 0; - - doctype = root.findDocType(); - - fixHTMLNameSpace(root, namespace); // #427839 - fix by Evan Lenz 05 Sep 00 - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_OMIT) - { - if (doctype != null) - { - Node.discardElement(doctype); - } - return true; - } - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_AUTO) - { - // see what flavor of XHTML this document matches - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_STRICT)) - { - // use XHTML strict - fpi = "-//W3C//DTD XHTML 1.0 Strict//EN"; - sysid = VOYAGER_STRICT; - } - else if (TidyUtils.toBoolean(this.versions & Dict.VERS_FRAMESET)) - { - // use XHTML frames - fpi = "-//W3C//DTD XHTML 1.0 Frameset//EN"; - sysid = VOYAGER_FRAMESET; - } - else if (TidyUtils.toBoolean(this.versions & Dict.VERS_LOOSE)) - { - fpi = "-//W3C//DTD XHTML 1.0 Transitional//EN"; - sysid = VOYAGER_LOOSE; - } - else if (TidyUtils.toBoolean(this.versions & Dict.VERS_XHTML11)) - { - // use XHTML 1.1 - fpi = "-//W3C//DTD XHTML 1.1//EN"; - sysid = VOYAGER_11; - } - else - { - // proprietary - fpi = null; - sysid = ""; - if (doctype != null)// #473490 - fix by Bjšrn Hšhrmann 10 Oct 01 - { - Node.discardElement(doctype); - } - } - } - else if (this.configuration.docTypeMode == Configuration.DOCTYPE_STRICT) - { - fpi = "-//W3C//DTD XHTML 1.0 Strict//EN"; - sysid = VOYAGER_STRICT; - } - else if (this.configuration.docTypeMode == Configuration.DOCTYPE_LOOSE) - { - fpi = "-//W3C//DTD XHTML 1.0 Transitional//EN"; - sysid = VOYAGER_LOOSE; - } - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_USER && this.configuration.docTypeStr != null) - { - fpi = this.configuration.docTypeStr; - sysid = ""; - } - - if (fpi == null) - { - return false; - } - - if (doctype != null) - { - // Look for internal DTD subset - if (configuration.xHTML || configuration.xmlOut) - { - - int len = doctype.end - doctype.start + 1; - String start = TidyUtils.getString(this.lexbuf, doctype.start, len); - - int dtdbeg = start.indexOf('['); - if (dtdbeg >= 0) - { - int dtdend = start.substring(dtdbeg).indexOf(']'); - if (dtdend >= 0) - { - dtdlen = dtdend + 1; - dtdsub = start.substring(dtdbeg); - } - } - } - } - else - { - if ((doctype = newXhtmlDocTypeNode(root)) == null) - { - return false; - } - } - - this.txtstart = this.lexsize; - this.txtend = this.lexsize; - - // add public identifier - addStringLiteral("html PUBLIC "); - - // check if the fpi is quoted or not - if (fpi.charAt(0) == '"') - { - addStringLiteral(fpi); - } - else - { - addStringLiteral("\""); - addStringLiteral(fpi); - addStringLiteral("\""); - } - - if (this.configuration.wraplen != 0 && sysid.length() + 6 >= this.configuration.wraplen) - { - addStringLiteral("\n\""); - } - else - { - // FG: don't wrap - addStringLiteral(" \""); - } - - // add system identifier - addStringLiteral(sysid); - addStringLiteral("\""); - - if (dtdlen > 0 && dtdsub != null) - { - addCharToLexer(' '); - addStringLiteralLen(dtdsub, dtdlen); - } - - this.txtend = this.lexsize; - - int length = this.txtend - this.txtstart; - doctype.textarray = new byte[length]; - - System.arraycopy(this.lexbuf, this.txtstart, doctype.textarray, 0, length); - doctype.start = 0; - doctype.end = length; - - return false; - } - - /** - * Return the html version used in document. - * @return version code - */ - public short apparentVersion() - { - switch (this.doctype) - { - case Dict.VERS_UNKNOWN : - return htmlVersion(); - - case Dict.VERS_HTML20 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML20)) - { - return Dict.VERS_HTML20; - } - - break; - - case Dict.VERS_HTML32 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML32)) - { - return Dict.VERS_HTML32; - } - - break; // to replace old version by new - - case Dict.VERS_HTML40_STRICT : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_STRICT)) - { - return Dict.VERS_HTML40_STRICT; - } - - break; - - case Dict.VERS_HTML40_LOOSE : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_LOOSE)) - { - return Dict.VERS_HTML40_LOOSE; - } - - break; // to replace old version by new - - case Dict.VERS_FRAMESET : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_FRAMESET)) - { - return Dict.VERS_FRAMESET; - } - - break; - - case Dict.VERS_XHTML11 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_XHTML11)) - { - return Dict.VERS_XHTML11; - } - - break; - default : - // should never reach here - break; - } - - // kludge to avoid error appearing at end of file - // it would be better to note the actual position - // when first encountering the doctype declaration - - this.lines = 1; - this.columns = 1; - - report.warning(this, null, null, Report.INCONSISTENT_VERSION); - return this.htmlVersion(); - } - - /** - * Fixup doctype if missing. - * @param root root node - * @return false if current version has not been identified - */ - public boolean fixDocType(Node root) - { - Node doctype; - int guessed = Dict.VERS_HTML40_STRICT, i; - - if (this.badDoctype) - { - report.warning(this, null, null, Report.MALFORMED_DOCTYPE); - } - - doctype = root.findDocType(); - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_OMIT) - { - if (doctype != null) - { - Node.discardElement(doctype); - } - return true; - } - - if (this.configuration.xmlOut) - { - return true; - } - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_STRICT) - { - Node.discardElement(doctype); - doctype = null; - guessed = Dict.VERS_HTML40_STRICT; - } - else if (this.configuration.docTypeMode == Configuration.DOCTYPE_LOOSE) - { - Node.discardElement(doctype); - doctype = null; - guessed = Dict.VERS_HTML40_LOOSE; - } - else if (this.configuration.docTypeMode == Configuration.DOCTYPE_AUTO) - { - if (doctype != null) - { - if (this.doctype == Dict.VERS_UNKNOWN) - { - return false; - } - - switch (this.doctype) - { - case Dict.VERS_UNKNOWN : - return false; - - case Dict.VERS_HTML20 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML20)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_HTML32 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML32)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_HTML40_STRICT : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_STRICT)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_HTML40_LOOSE : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_LOOSE)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_FRAMESET : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_FRAMESET)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_XHTML11 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_XHTML11)) - { - return true; - } - - break; // to replace old version by new - default : - // should never reach here - break; - } - - // INCONSISTENT_VERSION warning is now issued by ApparentVersion() - } - - // choose new doctype - guessed = htmlVersion(); - } - - if (guessed == Dict.VERS_UNKNOWN) - { - return false; - } - - // for XML use the Voyager system identifier - if (this.configuration.xmlOut || this.configuration.xmlTags || this.isvoyager) - { - if (doctype != null) - { - Node.discardElement(doctype); - } - - fixHTMLNameSpace(root, XHTML_NAMESPACE); - - // Namespace is the same for all XHTML variants - // Also, don't return yet. Still need to add DOCTYPE declaration. - // - // for (i = 0; i < W3CVersion.length; ++i) - // { - // if (guessed == W3CVersion[i].code) - // { - // fixHTMLNameSpace(root, W3CVersion[i].profile); - // break; - // } - // } - // return true; - } - - if (doctype == null) - { - if ((doctype = newXhtmlDocTypeNode(root)) == null) - { - return false; - } - } - - this.txtstart = this.lexsize; - this.txtend = this.lexsize; - - // use the appropriate public identifier - addStringLiteral("html PUBLIC "); - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_USER - && this.configuration.docTypeStr != null - && this.configuration.docTypeStr.length() > 0) - { - // check if the fpi is quoted or not - if (this.configuration.docTypeStr.charAt(0) == '"') - { - addStringLiteral(this.configuration.docTypeStr); - } - else - { - addStringLiteral("\""); // #431889 - fix by Dave Bryan 04 Jan 2001 - addStringLiteral(this.configuration.docTypeStr); - addStringLiteral("\""); // #431889 - fix by Dave Bryan 04 Jan 2001 - } - } - else if (guessed == Dict.VERS_HTML20) - { - addStringLiteral("\"-//IETF//DTD HTML 2.0//EN\""); - } - else - { - addStringLiteral("\"-//W3C//DTD "); - - for (i = 0; i < W3CVERSION.length; ++i) - { - if (guessed == W3CVERSION[i].code) - { - addStringLiteral(W3CVERSION[i].name); - break; - } - } - - addStringLiteral("//EN\""); - } - - this.txtend = this.lexsize; - - int length = this.txtend - this.txtstart; - doctype.textarray = new byte[length]; - - System.arraycopy(this.lexbuf, this.txtstart, doctype.textarray, 0, length); - doctype.start = 0; - doctype.end = length; - - return true; - } - - /** - * Ensure XML document starts with <?XML version="1.0"?>. Add encoding attribute if not using - * ASCII or UTF-8 output. - * @param root root node - * @return always true - */ - public boolean fixXmlDecl(Node root) - { - Node xml; - AttVal version; - AttVal encoding; - - if (root.content != null && root.content.type == Node.XML_DECL) - { - xml = root.content; - } - else - { - xml = newNode(Node.XML_DECL, this.lexbuf, 0, 0); - xml.next = root.content; - - if (root.content != null) - { - root.content.prev = xml; - xml.next = root.content; - } - - root.content = xml; - } - - version = xml.getAttrByName("version"); - encoding = xml.getAttrByName("encoding"); - - // We need to insert a check if declared encoding and output encoding mismatch - // and fix the Xml declaration accordingly!!! - if (encoding == null && !"UTF8".equals(this.configuration.getOutCharEncodingName())) - { - if ("ISO8859_1".equals(this.configuration.getOutCharEncodingName())) - { - xml.addAttribute("encoding", "iso-8859-1"); - } - if ("ISO2022".equals(this.configuration.getOutCharEncodingName())) - { - xml.addAttribute("encoding", "iso-2022"); - } - } - - if (version == null) - { - xml.addAttribute("version", "1.0"); - } - - return true; - } - - /** - * Generates and inserts a new node. - * @param name tag name - * @return generated node - */ - public Node inferredTag(String name) - { - Node node; - - node = newNode(Node.START_TAG, this.lexbuf, this.txtstart, this.txtend, name); - node.implicit = true; - return node; - } - - /** - * Create a text node for the contents of a CDATA element like style or script which ends with </foo> for some - * foo. - * @param container container node - * @return cdata node - */ - public Node getCDATA(Node container) - { - int c, lastc, start, len, i; - int qt = 0; - int esc = 0; - String str; - boolean endtag = false; - boolean begtag = false; - - if (container.isJavaScript()) - { - esc = '\\'; - } - - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - this.waswhite = false; - this.txtstart = this.lexsize; - this.txtend = this.lexsize; - - lastc = '\0'; - start = -1; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - // treat \r\n as \n and \r as \n - if (qt > 0) - { - // #598860 script parsing fails with quote chars - // A quoted string is ended by the quotation character, or end of line - if ((c == '\r' || c == '\n' || c == qt) && (!TidyUtils.toBoolean(esc) || lastc != esc)) - { - qt = 0; - } - else if (c == '/' && lastc == '<') - { - start = this.lexsize + 1; // to first letter - } - - else if (c == '>' && start >= 0) - { - len = this.lexsize - start; - - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol() - 3; - - report.warning(this, null, null, Report.BAD_CDATA_CONTENT); - - // if javascript insert backslash before / - if (TidyUtils.toBoolean(esc)) - { - for (i = this.lexsize; i > start - 1; --i) - { - this.lexbuf[i] = this.lexbuf[i - 1]; - } - - this.lexbuf[start - 1] = (byte) esc; - this.lexsize++; - } - - start = -1; - } - } - else if (TidyUtils.isQuote(c) && (!TidyUtils.toBoolean(esc) || lastc != esc)) - { - qt = c; - } - else if (c == '<') - { - start = this.lexsize + 1; // to first letter - endtag = false; - begtag = true; - } - else if (c == '!' && lastc == '<') // Cancel start tag - { - start = -1; - endtag = false; - begtag = false; - } - else if (c == '/' && lastc == '<') - { - start = this.lexsize + 1; // to first letter - endtag = true; - begtag = false; - } - else if (c == '>' && start >= 0) // End of begin or end tag - { - int decr = 2; - - if (endtag && ((len = this.lexsize - start) == container.element.length())) - { - - str = TidyUtils.getString(this.lexbuf, start, len); - if (container.element.equalsIgnoreCase(str)) - { - this.txtend = start - decr; - this.lexsize = start - decr; // #433857 - fix by Huajun Zeng 26 Apr 01 - break; - } - } - - // Unquoted markup will end SCRIPT or STYLE elements - - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol() - 3; - - report.warning(this, null, null, Report.BAD_CDATA_CONTENT); - if (begtag) - { - decr = 1; - } - this.txtend = start - decr; - this.lexsize = start - decr; - break; - } - // #427844 - fix by Markus Hoenicka 21 Oct 00 - else if (c == '\r') - { - if (begtag || endtag) - { - continue; // discard whitespace in endtag - } - - c = this.in.readChar(); - - if (c != '\n') - { - this.in.ungetChar(c); - } - - c = '\n'; - - } - else if ((c == '\n' || c == '\t' || c == ' ') && (begtag || endtag)) - { - continue; // discard whitespace in endtag - } - - addCharToLexer(c); - this.txtend = this.lexsize; - lastc = c; - } - - if (c == StreamIn.END_OF_STREAM) - { - report.warning(this, container, null, Report.MISSING_ENDTAG_FOR); - } - - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - return null; - } - - /** - * - * - */ - public void ungetToken() - { - this.pushed = true; - } - - /** - * Gets a token. - * @param mode one of the following: - *
    - *
  • MixedContent-- for elements which don't accept PCDATA
  • - *
  • Preformatted-- white spacepreserved as is
  • - *
  • IgnoreMarkup-- for CDATA elements such as script, style
  • - *
- * @return next Node - */ - public Node getToken(short mode) - { - int c = 0; - int badcomment = 0; - // pass by reference - boolean[] isempty = new boolean[1]; - boolean inDTDSubset = false; - AttVal attributes = null; - - if (this.pushed) - { - // duplicate inlines in preference to pushed text nodes when appropriate - if (this.token.type != Node.TEXT_NODE || (this.insert == -1 && this.inode == null)) - { - this.pushed = false; - return this.token; - } - } - - // at start of block elements, unclosed inline - if (this.insert != -1 || this.inode != null) - { - return insertedToken(); - } - - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - this.waswhite = false; - - this.txtstart = this.lexsize; - this.txtend = this.lexsize; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - // FG fix for [427846] different from tidy - // if (this.insertspace && (!TidyUtils.toBoolean(mode & IGNORE_WHITESPACE))) - if (this.insertspace && mode != IGNORE_WHITESPACE) - { - addCharToLexer(' '); - } - if (this.insertspace && (!TidyUtils.toBoolean(mode & IGNORE_WHITESPACE))) - { - this.waswhite = true; - this.insertspace = false; - } - - // treat \r\n as \n and \r as \n - if (c == '\r') - { - c = this.in.readChar(); - - if (c != '\n') - { - this.in.ungetChar(c); - } - - c = '\n'; - } - - addCharToLexer(c); - - switch (this.state) - { - case LEX_CONTENT : - // element content - - // Discard white space if appropriate. - // Its cheaper to do this here rather than in parser methods for elements that - // don't have mixed content. - if (TidyUtils.isWhite((char) c) && (mode == IGNORE_WHITESPACE) && this.lexsize == this.txtstart + 1) - { - --this.lexsize; - this.waswhite = false; - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - continue; - } - - if (c == '<') - { - this.state = LEX_GT; - continue; - } - - if (TidyUtils.isWhite((char) c)) - { - // was previous char white? - if (this.waswhite) - { - if (mode != PREFORMATTED && mode != IGNORE_MARKUP) - { - --this.lexsize; - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - } - } - else - { - // prev char wasn't white - this.waswhite = true; - - if (mode != PREFORMATTED && mode != IGNORE_MARKUP && c != ' ') - { - changeChar((byte) ' '); - } - } - - continue; - } - else if (c == '&' && mode != IGNORE_MARKUP) - { - parseEntity(mode); - } - - // this is needed to avoid trimming trailing whitespace - if (mode == IGNORE_WHITESPACE) - { - mode = MIXED_CONTENT; - } - - this.waswhite = false; - continue; - - case LEX_GT : - // < - - // check for endtag - if (c == '/') - { - c = this.in.readChar(); - if (c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - continue; - } - - addCharToLexer(c); - - if (TidyUtils.isLetter((char) c)) - { - this.lexsize -= 3; - this.txtend = this.lexsize; - this.in.ungetChar(c); - this.state = LEX_ENDTAG; - this.lexbuf[this.lexsize] = (byte) '\0'; // debug - - // changed from - // this.in.curcol -= 2; - this.columns -= 2; - - // if some text before the this.txtstart) - { - // trim space char before end tag - if (mode == IGNORE_WHITESPACE && this.lexbuf[this.lexsize - 1] == (byte) ' ') - { - this.lexsize -= 1; - this.txtend = this.lexsize; - } - - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - continue; // no text so keep going - } - - // otherwise treat as CDATA - this.waswhite = false; - this.state = LEX_CONTENT; - continue; - } - - if (mode == IGNORE_MARKUP) - { - // otherwise treat as CDATA - this.waswhite = false; - this.state = LEX_CONTENT; - continue; - } - - // look out for comments, doctype or marked sections this isn't quite right, but its getting there - if (c == '!') - { - c = this.in.readChar(); - - if (c == '-') - { - c = this.in.readChar(); - - if (c == '-') - { - this.state = LEX_COMMENT; // comment - this.lexsize -= 2; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - report.warning(this, null, null, Report.MALFORMED_COMMENT); - } - else if (c == 'd' || c == 'D') - { - this.state = LEX_DOCTYPE; // doctype - this.lexsize -= 2; - this.txtend = this.lexsize; - mode = IGNORE_WHITESPACE; - - // skip until white space or '>' - - for (;;) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM || c == '>') - { - this.in.ungetChar(c); - break; - } - - if (!TidyUtils.isWhite((char) c)) - { - continue; - } - - // and skip to end of whitespace - - for (;;) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM || c == '>') - { - this.in.ungetChar(c); - break; - } - - if (TidyUtils.isWhite((char) c)) - { - continue; - } - - this.in.ungetChar(c); - break; - } - - break; - } - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - else if (c == '[') - { - // Word 2000 embeds ... sequences - this.lexsize -= 2; - this.state = LEX_SECTION; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - // otherwise swallow chars up to and including next '>' - while (true) - { - c = this.in.readChar(); - if (c == '>') - { - break; - } - if (c == -1) - { - this.in.ungetChar(c); - break; - } - } - - this.lexsize -= 2; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - continue; - } - - // processing instructions - - if (c == '?') - { - this.lexsize -= 2; - this.state = LEX_PROCINSTR; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - // Microsoft ASP's e.g. <% ... server-code ... %> - if (c == '%') - { - this.lexsize -= 2; - this.state = LEX_ASP; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - // Netscapes JSTE e.g. <# ... server-code ... #> - if (c == '#') - { - this.lexsize -= 2; - this.state = LEX_JSTE; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - // check for start tag - if (TidyUtils.isLetter((char) c)) - { - this.in.ungetChar(c); // push back letter - this.lexsize -= 2; // discard " <" + letter - this.txtend = this.lexsize; - this.state = LEX_STARTTAG; // ready to read tag name - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - continue; // no text so keep going - } - - // otherwise treat as CDATA - this.state = LEX_CONTENT; - this.waswhite = false; - continue; - - case LEX_ENDTAG : - // ' - while (c != '>') - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - break; - } - } - - if (c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - continue; - } - - this.state = LEX_CONTENT; - this.waswhite = false; - return this.token; // the endtag token - - case LEX_STARTTAG : - // first letter of tagname - this.txtstart = this.lexsize - 1; // set txtstart to first letter - c = parseTagName(); - isempty[0] = false; - attributes = null; - this.token = newNode( - (isempty[0] ? Node.START_END_TAG : Node.START_TAG), - this.lexbuf, - this.txtstart, - this.txtend, - TidyUtils.getString(this.lexbuf, this.txtstart, this.txtend - this.txtstart)); - - // parse attributes, consuming closing ">" - if (c != '>') - { - if (c == '/') - { - this.in.ungetChar(c); - } - - attributes = parseAttrs(isempty); - } - - if (isempty[0]) - { - this.token.type = Node.START_END_TAG; - } - - this.token.attributes = attributes; - this.lexsize = this.txtstart; - this.txtend = this.txtstart; - - // swallow newline following start tag - // special check needed for CRLF sequence - // this doesn't apply to empty elements - // nor to preformatted content that needs escaping - - if ( - - (mode != PREFORMATTED || preContent(this.token)) - && (this.token.expectsContent() || this.token.tag == this.configuration.tt.tagBr)) - { - - c = this.in.readChar(); - - if (c == '\r') - { - c = this.in.readChar(); - - if (c != '\n') - { - this.in.ungetChar(c); - } - } - else if (c != '\n' && c != '\f') - { - this.in.ungetChar(c); - } - - this.waswhite = true; // to swallow leading whitespace - } - else - { - this.waswhite = false; - } - - this.state = LEX_CONTENT; - - if (this.token.tag == null) - { - report.error(this, null, this.token, Report.UNKNOWN_ELEMENT); - } - else if (!this.configuration.xmlTags) - { - constrainVersion(this.token.tag.versions); - - if (TidyUtils.toBoolean(this.token.tag.versions & Dict.VERS_PROPRIETARY)) - { - // #427810 - fix by Gary Deschaines 24 May 00 - if (this.configuration.makeClean && (this.token.tag != this.configuration.tt.tagNobr && // - this.token.tag != this.configuration.tt.tagWbr)) - { - report.warning(this, null, this.token, Report.PROPRIETARY_ELEMENT); - } - // #427810 - fix by Terry Teague 2 Jul 01 - else if (!this.configuration.makeClean) - { - report.warning(this, null, this.token, Report.PROPRIETARY_ELEMENT); - } - } - - if (this.token.tag.getChkattrs() != null) - { - this.token.tag.getChkattrs().check(this, this.token); - } - else - { - this.token.checkAttributes(this); - } - - // should this be called before attribute checks? - this.token.repairDuplicateAttributes(this); - - } - - return this.token; // return start tag - - case LEX_COMMENT : - // seen - - if (c != '-') - { - continue; - } - - c = this.in.readChar(); - addCharToLexer(c); - - if (c != '-') - { - continue; - } - - end_comment : while (true) - { - c = this.in.readChar(); - - if (c == '>') - { - if (badcomment != 0) - { - report.warning(this, null, null, Report.MALFORMED_COMMENT); - } - - this.txtend = this.lexsize - 2; // AQ 8Jul2000 - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.COMMENT_TAG, this.lexbuf, this.txtstart, this.txtend); - - // now look for a line break - - c = this.in.readChar(); - - if (c == '\r') - { - c = this.in.readChar(); - - if (c != '\n') - { - this.token.linebreak = true; - } - } - - if (c == '\n') - { - this.token.linebreak = true; - } - else - { - this.in.ungetChar(c); - } - - return this.token; - } - - // note position of first such error in the comment - if (badcomment == 0) - { - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol() - 3; - } - - badcomment++; - if (this.configuration.fixComments) - { - this.lexbuf[this.lexsize - 2] = (byte) '='; - } - - addCharToLexer(c); - - // if '-' then look for '>' to end the comment - if (c != '-') - { - break end_comment; - } - - } - // otherwise continue to look for --> - this.lexbuf[this.lexsize - 2] = (byte) '='; - continue; - - case LEX_DOCTYPE : - // seen ' munging whitespace - - if (TidyUtils.isWhite((char) c)) - { - if (this.waswhite) - { - this.lexsize -= 1; - } - - this.waswhite = true; - } - else - { - this.waswhite = false; - } - - if (inDTDSubset) - { - if (c == ']') - { - inDTDSubset = false; - } - } - else if (c == '[') - { - inDTDSubset = true; - } - if (inDTDSubset || c != '>') - { - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.DOCTYPE_TAG, this.lexbuf, this.txtstart, this.txtend); - // make a note of the version named by the doctype - this.doctype = findGivenVersion(this.token); - return this.token; - - case LEX_PROCINSTR : - // seen ' - // check for PHP preprocessor instructions - - if (this.lexsize - this.txtstart == 3) - { - if ((TidyUtils.getString(this.lexbuf, this.txtstart, 3)).equals("php")) - { - this.state = LEX_PHP; - continue; - } - } - - if (this.lexsize - this.txtstart == 4) - { - if ((TidyUtils.getString(this.lexbuf, this.txtstart, 3)).equals("xml") - && TidyUtils.isWhite((char) this.lexbuf[this.txtstart + 3])) - { - this.state = LEX_XMLDECL; - attributes = null; - continue; - } - } - - if (this.configuration.xmlPIs) // insist on ?> as terminator - { - if (c != '?') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - report.warning(this, null, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - continue; - } - - addCharToLexer(c); - } - - if (c != '>') - { - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.PROC_INS_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_ASP : - // seen <% so look for "%> " - if (c != '%') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.ASP_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_JSTE : - // seen <# so look for "#> " - if (c != '#') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.JSTE_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_PHP : - // seen " " - if (c != '?') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.PHP_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_XMLDECL : // seen "" - - if (TidyUtils.isWhite((char) c) && c != '?') - { - continue; - } - - // get pseudo-attribute - if (c != '?') - { - String name; - Node[] asp = new Node[1]; - Node[] php = new Node[1]; - AttVal av = new AttVal(); - int[] pdelim = new int[1]; - isempty[0] = false; - - this.in.ungetChar(c); - - name = this.parseAttribute(isempty, asp, php); - av.attribute = name; - - av.value = this.parseValue(name, true, isempty, pdelim); - av.delim = pdelim[0]; - av.next = attributes; - - attributes = av; - // continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - this.lexsize -= 1; - this.txtend = this.txtstart; - this.lexbuf[this.txtend] = '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.XML_DECL, this.lexbuf, this.txtstart, this.txtend); - this.token.attributes = attributes; - return this.token; - - case LEX_SECTION : - // seen " " - if (c == '[') - { - if (this.lexsize == (this.txtstart + 6) - && (TidyUtils.getString(this.lexbuf, this.txtstart, 6)).equals("CDATA[")) - { - this.state = LEX_CDATA; - this.lexsize -= 6; - continue; - } - } - - if (c != ']') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.SECTION_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_CDATA : - // seen " " - if (c != ']') - { - continue; - } - - // now look for ']' - c = this.in.readChar(); - - if (c != ']') - { - this.in.ungetChar(c); - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.CDATA_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - default : - // should never reach here - break; - } - } - - if (this.state == LEX_CONTENT) // text string - { - this.txtend = this.lexsize; - - if (this.txtend > this.txtstart) - { - this.in.ungetChar(c); - - if (this.lexbuf[this.lexsize - 1] == (byte) ' ') - { - this.lexsize -= 1; - this.txtend = this.lexsize; - } - - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - } - else if (this.state == LEX_COMMENT) // comment - { - if (c == StreamIn.END_OF_STREAM) - { - report.warning(this, null, null, Report.MALFORMED_COMMENT); - } - - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.COMMENT_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - return null; - } - - /** - * parser for ASP within start tags Some people use ASP for to customize attributes Tidy isn't really well suited to - * dealing with ASP This is a workaround for attributes, but won't deal with the case where the ASP is used to - * tailor the attribute value. Here is an example of a work around for using ASP in attribute values: - * href='<%=rsSchool.Fields("ID").Value%>' where the ASP that generates the attribute value is - * masked from Tidy by the quotemarks. - * @return parsed Node - */ - public Node parseAsp() - { - int c; - Node asp = null; - - this.txtstart = this.lexsize; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - - addCharToLexer(c); - - if (c != '%') - { - continue; - } - - if ((c = this.in.readChar()) == StreamIn.END_OF_STREAM) - { - break; - } - addCharToLexer(c); - - if (c == '>') - { - break; - } - } - - this.lexsize -= 2; - this.txtend = this.lexsize; - - if (this.txtend > this.txtstart) - { - asp = newNode(Node.ASP_TAG, this.lexbuf, this.txtstart, this.txtend); - } - - this.txtstart = this.txtend; - return asp; - } - - /** - * PHP is like ASP but is based upon XML processing instructions, e.g. <?php ... ?>. - * @return parsed Node - */ - public Node parsePhp() - { - int c; - Node php = null; - - this.txtstart = this.lexsize; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - addCharToLexer(c); - - if (c != '?') - { - continue; - } - - if ((c = this.in.readChar()) == StreamIn.END_OF_STREAM) - { - break; - } - addCharToLexer(c); - - if (c == '>') - { - break; - } - } - - this.lexsize -= 2; - this.txtend = this.lexsize; - - if (this.txtend > this.txtstart) - { - php = newNode(Node.PHP_TAG, this.lexbuf, this.txtstart, this.txtend); - } - - this.txtstart = this.txtend; - return php; - } - - /** - * consumes the '>' terminating start tags. - * @param isempty flag is passed as array so it can be modified - * @param asp asp Node, passed as array so it can be modified - * @param php php Node, passed as array so it can be modified - * @return parsed attribute - */ - public String parseAttribute(boolean[] isempty, Node[] asp, Node[] php) - { - int start = 0; - String attr; - int c = 0; - int lastc = 0; - - asp[0] = null; // clear asp pointer - php[0] = null; // clear php pointer - // skip white space before the attribute - - for (;;) - { - c = this.in.readChar(); - - if (c == '/') - { - c = this.in.readChar(); - - if (c == '>') - { - isempty[0] = true; - return null; - } - - this.in.ungetChar(c); - c = '/'; - break; - } - - if (c == '>') - { - return null; - } - - if (c == '<') - { - c = this.in.readChar(); - - if (c == '%') - { - asp[0] = parseAsp(); - return null; - } - else if (c == '?') - { - php[0] = parsePhp(); - return null; - } - - this.in.ungetChar(c); - if (this.state != LEX_XMLDECL) // FG fix for 532535 - { - this.in.ungetChar('<'); // fix for 433360 - } - report.attrError(this, this.token, null, Report.UNEXPECTED_GT); - return null; - } - - if (c == '=') - { - report.attrError(this, this.token, null, Report.UNEXPECTED_EQUALSIGN); - continue; - } - - if (c == '"' || c == '\'') - { - report.attrError(this, this.token, null, Report.UNEXPECTED_QUOTEMARK); - continue; - } - - if (c == StreamIn.END_OF_STREAM) - { - report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - return null; - } - - if (!TidyUtils.isWhite((char) c)) - { - break; - } - } - - start = this.lexsize; - lastc = c; - - for (;;) - { - // but push back '=' for parseValue() - if (c == '=' || c == '>') - { - this.in.ungetChar(c); - break; - } - - if (c == '<' || c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - break; - } - if (lastc == '-' && (c == '"' || c == '\'')) - { - this.lexsize--; - this.in.ungetChar(c); - break; - } - if (TidyUtils.isWhite((char) c)) - { - break; - } - - // what should be done about non-namechar characters? - // currently these are incorporated into the attr name - - if (!this.configuration.xmlTags && TidyUtils.isUpper((char) c)) - { - c = TidyUtils.toLower((char) c); - } - - // ++len; #427672 - handle attribute names with multibyte chars - fix by Randy Waki - 10 Aug 00 - addCharToLexer(c); - - lastc = c; - c = this.in.readChar(); - } - - // #427672 - handle attribute names with multibyte chars - fix by Randy Waki - 10 Aug 00 - int len = this.lexsize - start; - attr = (len > 0 ? TidyUtils.getString(this.lexbuf, start, len) : null); - this.lexsize = start; - - return attr; - } - - /** - * Invoked when < is seen in place of attribute value but terminates on whitespace if not ASP, PHP or Tango this - * routine recognizes ' and " quoted strings. - * @return delimiter - */ - public int parseServerInstruction() - { - int c, delim = '"'; - boolean isrule = false; - - c = this.in.readChar(); - addCharToLexer(c); - - // check for ASP, PHP or Tango - if (c == '%' || c == '?' || c == '@') - { - isrule = true; - } - - for (;;) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - break; - } - - if (c == '>') - { - if (isrule) - { - addCharToLexer(c); - } - else - { - this.in.ungetChar(c); - } - - break; - } - - // if not recognized as ASP, PHP or Tango - // then also finish value on whitespace - if (!isrule) - { - if (TidyUtils.isWhite((char) c)) - { - break; - } - } - - addCharToLexer(c); - - if (c == '"') - { - do - { - c = this.in.readChar(); - - if (endOfInput()) // #427840 - fix by Terry Teague 30 Jun 01 - { - report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - return 0; - } - if (c == '>') // #427840 - fix by Terry Teague 30 Jun 01 - { - this.in.ungetChar(c); - report.attrError(this, this.token, null, Report.UNEXPECTED_GT); - return 0; - } - - addCharToLexer(c); - } - while (c != '"'); - delim = '\''; - continue; - } - - if (c == '\'') - { - do - { - c = this.in.readChar(); - - if (endOfInput()) // #427840 - fix by Terry Teague 30 Jun 01 - { - report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - return 0; - } - if (c == '>') // #427840 - fix by Terry Teague 30 Jun 01 - { - this.in.ungetChar(c); - report.attrError(this, this.token, null, Report.UNEXPECTED_GT); - return 0; - } - - addCharToLexer(c); - } - while (c != '\''); - } - } - - return delim; - } - - /** - * Parse an attribute value. - * @param name attribute name - * @param foldCase fold case? - * @param isempty is attribute empty? Passed as an array reference to allow modification - * @param pdelim delimiter, passed as an array reference to allow modification - * @return parsed value - */ - public String parseValue(String name, boolean foldCase, boolean[] isempty, int[] pdelim) - { - // values start with "=" or " = " etc. - // doesn't consume the ">" at end of start tag - - int len = 0; - int start; - boolean seenGt = false; - boolean munge = true; - int c = 0; - int lastc, delim, quotewarning; - String value; - - delim = 0; - pdelim[0] = '"'; - - // Henry Zrepa reports that some folk are using the embed element with script attributes where newlines are - // significant and must be preserved - - if (this.configuration.literalAttribs) - { - munge = false; - } - - // skip white space before the '=' - while (true) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - break; - } - - if (!TidyUtils.isWhite((char) c)) - { - break; - } - } - - // c should be '=' if there is a value other legal possibilities are white space, '/' and '>' - - if (c != '=' && c != '"' && c != '\'') - { - this.in.ungetChar(c); - return null; - } - - // skip white space after '=' - - while (true) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - break; - } - - if (!TidyUtils.isWhite((char) c)) - { - break; - } - } - - // check for quote marks - - if (c == '"' || c == '\'') - { - delim = c; - } - else if (c == '<') - { - start = this.lexsize; - addCharToLexer(c); - pdelim[0] = parseServerInstruction(); - len = this.lexsize - start; - this.lexsize = start; - return (len > 0 ? TidyUtils.getString(this.lexbuf, start, len) : null); - } - else - { - this.in.ungetChar(c); - } - - // and read the value string check for quote mark if needed - - quotewarning = 0; - start = this.lexsize; - c = '\0'; - - while (true) - { - lastc = c; // track last character - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - break; - } - - if (delim == (char) 0) - { - if (c == '>') - { - this.in.ungetChar(c); - break; - } - - if (c == '"' || c == '\'') - { - report.attrError(this, this.token, null, Report.UNEXPECTED_QUOTEMARK); - break; - } - - if (c == '<') - { - this.in.ungetChar(c); // fix for 433360 - c = '>'; - this.in.ungetChar(c); - report.attrError(this, this.token, null, Report.UNEXPECTED_GT); - break; - } - - // For cases like
need to avoid treating /> as part of the attribute value, however - // care is needed to avoid so treating
in this way, which would map the - // tag to - - if (c == '/') - { - // peek ahead in case of /> - c = this.in.readChar(); - - if (c == '>' && !AttributeTable.getDefaultAttributeTable().isUrl(name)) - { - isempty[0] = true; - this.in.ungetChar(c); - break; - } - - // unget peeked char - this.in.ungetChar(c); - c = '/'; - } - } - else - { - // delim is '\'' or '"' - if (c == delim) - { - break; - } - - // treat CRLF, CR and LF as single line break - - if (c == '\r') - { - c = this.in.readChar(); - if (c != '\n') - { - this.in.ungetChar(c); - } - - c = '\n'; - } - - if (c == '\n' || c == '<' || c == '>') - { - ++quotewarning; - } - - if (c == '>') - { - seenGt = true; - } - } - - if (c == '&') - { - // no entities in ID attributes - if ("id".equalsIgnoreCase(name)) - { - report.attrError(this, null, null, Report.ENTITY_IN_ID); - continue; - } - - addCharToLexer(c); - parseEntity((short) 0); - continue; - - } - - // kludge for JavaScript attribute values with line continuations in string literals - - if (c == '\\') - { - c = this.in.readChar(); - - if (c != '\n') - { - this.in.ungetChar(c); - c = '\\'; - } - } - - if (TidyUtils.isWhite((char) c)) - { - if (delim == (char) 0) - { - break; - } - - if (munge) - { - // discard line breaks in quoted URLs - // #438650 - fix by Randy Waki - if (c == '\n' && AttributeTable.getDefaultAttributeTable().isUrl(name)) - { - // warn that we discard this newline - report.attrError(this, this.token, null, Report.NEWLINE_IN_URI); - continue; - } - - c = ' '; - - if (lastc == ' ') - { - continue; - } - } - } - else if (foldCase && TidyUtils.isUpper((char) c)) - { - c = TidyUtils.toLower((char) c); - } - - addCharToLexer(c); - } - - if (quotewarning > 10 && seenGt && munge) - { - // there is almost certainly a missing trailing quote mark as we have see too many newlines, < or > - // characters. an exception is made for Javascript attributes and the javascript URL scheme which may - // legitimately include < and >, and for attributes starting with " 0 || delim != 0) - { - // ignore leading and trailing white space for all but title, alt, value and prompts attributes unless - // --literal-attributes is set to yes - // #994841 - Whitespace is removed from value attributes - - if (munge && !TidyUtils.isInValuesIgnoreCase(new String[]{"alt", "title", "value", "prompt"}, name)) - { - while (TidyUtils.isWhite((char) this.lexbuf[start + len - 1])) - { - --len; - } - - while (TidyUtils.isWhite((char) this.lexbuf[start]) && start < len) - { - ++start; - --len; - } - } - - value = TidyUtils.getString(this.lexbuf, start, len); - } - else - { - value = null; - } - - // note delimiter if given - if (delim != 0) - { - pdelim[0] = delim; - } - else - { - pdelim[0] = '"'; - } - - return value; - } - - /** - * Check if attr is a valid name. - * @param attr String to check, must be non-null - * @return true if attr is a valid name. - */ - public static boolean isValidAttrName(String attr) - { - char c; - int i; - - // first character should be a letter - c = attr.charAt(0); - - if (!TidyUtils.isLetter(c)) - { - return false; - } - - // remaining characters should be namechars - for (i = 1; i < attr.length(); i++) - { - c = attr.charAt(i); - - if (TidyUtils.isNamechar(c)) - { - continue; - } - - return false; - } - - return true; - } - - /** - * In CSS1, selectors can contain only the characters A-Z, 0-9, and Unicode characters 161-255, plus dash (-); they - * cannot start with a dash or a digit; they can also contain escaped characters and any Unicode character as a - * numeric code (see next item). The backslash followed by at most four hexadecimal digits (0..9A..F) stands for the - * Unicode character with that number. Any character except a hexadecimal digit can be escaped to remove its special - * meaning, by putting a backslash in front. - * @param buf css selector name - * @return true if the given string is a valid css1 selector name - */ - public static boolean isCSS1Selector(String buf) - { - if (buf == null) - { - return false; - } - - // #508936 - CSS class naming for -clean option - boolean valid = true; - int esclen = 0; - char c; - int pos; - - for (pos = 0; valid && pos < buf.length(); ++pos) - { - c = buf.charAt(pos); - if (c == '\\') - { - esclen = 1; // ab\555\444 is 4 chars {'a', 'b', \555, \444} - } - else if (Character.isDigit(c)) - { - // Digit not 1st, unless escaped (Max length "\112F") - if (esclen > 0) - { - valid = (++esclen < 6); - } - if (valid) - { - valid = (pos > 0 || esclen > 0); - } - } - else - { - valid = (esclen > 0 // Escaped? Anything goes. - || (pos > 0 && c == '-') // Dash cannot be 1st char - || Character.isLetter(c) // a-z, A-Z anywhere - || (c >= 161 && c <= 255)); // Unicode 161-255 anywhere - esclen = 0; - } - } - return valid; - } - - /** - * Parse tag attributes. - * @param isempty is tag empty? - * @return parsed attribute/value list - */ - public AttVal parseAttrs(boolean[] isempty) - { - AttVal av, list; - String attribute, value; - int[] delim = new int[1]; - Node[] asp = new Node[1]; - Node[] php = new Node[1]; - - list = null; - - while (!endOfInput()) - { - attribute = parseAttribute(isempty, asp, php); - - if (attribute == null) - { - // check if attributes are created by ASP markup - if (asp[0] != null) - { - av = new AttVal(list, null, asp[0], null, '\0', null, null); - list = av; - continue; - } - - // check if attributes are created by PHP markup - if (php[0] != null) - { - av = new AttVal(list, null, null, php[0], '\0', null, null); - list = av; - continue; - } - - break; - } - - value = parseValue(attribute, false, isempty, delim); - - if (attribute != null && isValidAttrName(attribute)) - { - av = new AttVal(list, null, null, null, delim[0], attribute, value); - av.dict = AttributeTable.getDefaultAttributeTable().findAttribute(av); - list = av; - } - else - { - av = new AttVal(null, null, null, null, 0, attribute, value); - - // #427664 - fix by Gary Peskin 04 Aug 00; other fixes by Dave Raggett - if (value != null) - { - report.attrError(this, this.token, av, Report.BAD_ATTRIBUTE_VALUE); - } - else if (TidyUtils.lastChar(attribute) == '"') - { - report.attrError(this, this.token, av, Report.MISSING_QUOTEMARK); - } - else - { - report.attrError(this, this.token, av, Report.UNKNOWN_ATTRIBUTE); - } - } - } - - return list; - } - - /** - * Push a copy of an inline node onto stack but don't push if implicit or OBJECT or APPLET (implicit tags are ones - * generated from the istack) One issue arises with pushing inlines when the tag is already pushed. For instance: - * <p><em> text <p><em> more text Shouldn't be mapped to - * <p><em> text </em></p><p><em><em> more text </em></em> - * @param node Node to be pushed - */ - public void pushInline(Node node) - { - IStack is; - - if (node.implicit) - { - return; - } - - if (node.tag == null) - { - return; - } - - if (!TidyUtils.toBoolean(node.tag.model & Dict.CM_INLINE)) - { - return; - } - - if (TidyUtils.toBoolean(node.tag.model & Dict.CM_OBJECT)) - { - return; - } - - if (node.tag != this.configuration.tt.tagFont && isPushed(node)) - { - return; - } - - // make sure there is enough space for the stack - is = new IStack(); - is.tag = node.tag; - is.element = node.element; - if (node.attributes != null) - { - is.attributes = cloneAttributes(node.attributes); - } - this.istack.push(is); - } - - /** - * Pop a copy of an inline node from the stack. - * @param node Node to be popped - */ - public void popInline(Node node) - { - IStack is; - - if (node != null) - { - - if (node.tag == null) - { - return; - } - - if (!TidyUtils.toBoolean(node.tag.model & Dict.CM_INLINE)) - { - return; - } - - if (TidyUtils.toBoolean(node.tag.model & Dict.CM_OBJECT)) - { - return; - } - - // if node is then pop until we find an - if (node.tag == this.configuration.tt.tagA) - { - - while (this.istack.size() > 0) - { - is = (IStack) this.istack.pop(); - if (is.tag == this.configuration.tt.tagA) - { - break; - } - } - - if (this.insert >= this.istack.size()) - { - this.insert = -1; - } - return; - } - } - - if (this.istack.size() > 0) - { - is = (IStack) this.istack.pop(); - if (this.insert >= this.istack.size()) - { - this.insert = -1; - } - } - } - - /** - * Is the node in the stack? - * @param node Node - * @return true is the node is found in the stack - */ - public boolean isPushed(Node node) - { - int i; - IStack is; - - for (i = this.istack.size() - 1; i >= 0; --i) - { - is = (IStack) this.istack.elementAt(i); - if (is.tag == node.tag) - { - return true; - } - } - - return false; - } - - /** - * This has the effect of inserting "missing" inline elements around the contents of blocklevel elements such as P, - * TD, TH, DIV, PRE etc. This procedure is called at the start of ParseBlock. When the inline stack is not empty, as - * will be the case in: <i><h1>italic heading</h1></i> which is then treated as - * equivalent to <h1><i>italic heading</i></h1> This is implemented by setting the lexer - * into a mode where it gets tokens from the inline stack rather than from the input stream. - * @param node original node - * @return stack size - */ - public int inlineDup(Node node) - { - int n; - - n = this.istack.size() - this.istackbase; - if (n > 0) - { - this.insert = this.istackbase; - this.inode = node; - } - - return n; - } - - /** - * @return - */ - public Node insertedToken() - { - Node node; - IStack is; - int n; - - // this will only be null if inode != null - if (this.insert == -1) - { - node = this.inode; - this.inode = null; - return node; - } - - // is this is the "latest" node then update the position, otherwise use current values - if (this.inode == null) - { - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - } - - node = newNode(Node.START_TAG, this.lexbuf, this.txtstart, this.txtend); - - // GLP: Bugfix 126261. Remove when this change is fixed in istack.c in the original Tidy - node.implicit = true; - is = (IStack) this.istack.elementAt(this.insert); - node.element = is.element; - node.tag = is.tag; - if (is.attributes != null) - { - node.attributes = cloneAttributes(is.attributes); - } - - // advance lexer to next item on the stack - n = this.insert; - - // and recover state if we have reached the end - if (++n < this.istack.size()) - { - this.insert = n; - } - else - { - this.insert = -1; - } - - return node; - } - - /** - * Can the given element be removed? - * @param element node - * @return true if he element can be removed - */ - public boolean canPrune(Node element) - { - if (element.type == Node.TEXT_NODE) - { - return true; - } - - if (element.content != null) - { - return false; - } - - if (element.tag == this.configuration.tt.tagA && element.attributes != null) - { - return false; - } - - if (element.tag == this.configuration.tt.tagP && !this.configuration.dropEmptyParas) - { - return false; - } - - if (element.tag == null) - { - return false; - } - - if (TidyUtils.toBoolean(element.tag.model & Dict.CM_ROW)) - { - return false; - } - - if (TidyUtils.toBoolean(element.tag.model & Dict.CM_EMPTY)) - { - return false; - } - - if (element.tag == this.configuration.tt.tagApplet) - { - return false; - } - - if (element.tag == this.configuration.tt.tagObject) - { - return false; - } - - if (element.tag == this.configuration.tt.tagScript && element.getAttrByName("src") != null) - { - return false; - } - - // #540555 Empty title tag is trimmed - if (element.tag == this.configuration.tt.tagTitle) - { - return false; - } - - // #433359 - fix by Randy Waki 12 Mar 01 - Empty iframe is trimmed - if (element.tag == this.configuration.tt.tagIframe) - { - return false; - } - - if (element.getAttrByName("id") != null || element.getAttrByName("name") != null) - { - return false; - } - - return true; - } - - /** - * duplicate name attribute as an id and check if id and name match. - * @param node Node to check for name/it attributes - */ - public void fixId(Node node) - { - AttVal name = node.getAttrByName("name"); - AttVal id = node.getAttrByName("id"); - - if (name != null) - { - if (id != null) - { - if (id.value != null && !id.value.equals(name.value)) - { - report.attrError(this, node, name, Report.ID_NAME_MISMATCH); - } - } - else if (this.configuration.xmlOut) - { - node.addAttribute("id", name.value); - } - } - } - - /** - * Defer duplicates when entering a table or other element where the inlines shouldn't be duplicated. - */ - public void deferDup() - { - this.insert = -1; - this.inode = null; - } - - /** - * Constraint the html version in the document to the given one. Everything is allowed in proprietary version of - * HTML this is handled here rather than in the tag/attr dicts. - * @param vers html version code - */ - void constrainVersion(int vers) - { - this.versions &= (vers | Dict.VERS_PROPRIETARY); - } - - /** - * Is content acceptable for pre elements? - * @param node content - * @return true if node is acceptable in pre elements - */ - protected boolean preContent(Node node) - { - // p is coerced to br's - if (node.tag == this.configuration.tt.tagP) - { - return true; - } - - if (node.tag == null - || node.tag == this.configuration.tt.tagP - || !TidyUtils.toBoolean(node.tag.model & (Dict.CM_INLINE | Dict.CM_NEW))) - { - return false; - } - return true; - } - - /** - * document type. - */ - private static class W3CVersionInfo - { - - /** - * name. - */ - String name; - - /** - * voyager name. - */ - String voyagerName; - - /** - * profile. - */ - String profile; - - /** - * code. - */ - short code; - - /** - * Instantiates a new W3CVersionInfo. - * @param name version name - * @param voyagerName voyager (xhtml) name - * @param profile VOYAGER_STRICT | VOYAGER_LOOSE | VOYAGER_FRAMESET - * @param code unique code for this version info - */ - public W3CVersionInfo(String name, String voyagerName, String profile, short code) - { - this.name = name; - this.voyagerName = voyagerName; - this.profile = profile; - this.code = code; - } - } - -} - diff --git a/All/Genesis-OOB/Genesis#206/old/Lexer.java b/All/Genesis-OOB/Genesis#206/old/Lexer.java deleted file mode 100755 index 1a9de61..0000000 --- a/All/Genesis-OOB/Genesis#206/old/Lexer.java +++ /dev/null @@ -1,4062 +0,0 @@ -/* - * Java HTML Tidy - JTidy - * HTML parser and pretty printer - * - * Copyright (c) 1998-2000 World Wide Web Consortium (Massachusetts - * Institute of Technology, Institut National de Recherche en - * Informatique et en Automatique, Keio University). All Rights - * Reserved. - * - * Contributing Author(s): - * - * Dave Raggett - * Andy Quick (translation to Java) - * Gary L Peskin (Java development) - * Sami Lempinen (release management) - * Fabrizio Giustina - * - * The contributing author(s) would like to thank all those who - * helped with testing, bug fixes, and patience. This wouldn't - * have been possible without all of you. - * - * COPYRIGHT NOTICE: - * - * This software and documentation is provided "as is," and - * the copyright holders and contributing author(s) make no - * representations or warranties, express or implied, including - * but not limited to, warranties of merchantability or fitness - * for any particular purpose or that the use of the software or - * documentation will not infringe any third party patents, - * copyrights, trademarks or other rights. - * - * The copyright holders and contributing author(s) will not be - * liable for any direct, indirect, special or consequential damages - * arising out of any use of the software or documentation, even if - * advised of the possibility of such damage. - * - * Permission is hereby granted to use, copy, modify, and distribute - * this source code, or portions hereof, documentation and executables, - * for any purpose, without fee, subject to the following restrictions: - * - * 1. The origin of this source code must not be misrepresented. - * 2. Altered versions must be plainly marked as such and must - * not be misrepresented as being the original source. - * 3. This Copyright notice may not be removed or altered from any - * source or altered source distribution. - * - * The copyright holders and contributing author(s) specifically - * permit, without fee, and encourage the use of this source code - * as a component for supporting the Hypertext Markup Language in - * commercial products. If you use this source code in a product, - * acknowledgment is not required but would be appreciated. - * - */ -package org.w3c.tidy; - -import java.io.PrintWriter; -import java.util.List; -import java.util.Stack; -import java.util.Vector; - - -/** - * Lexer for html parser. - *

- * Given a file stream fp it returns a sequence of tokens. GetToken(fp) gets the next token UngetToken(fp) provides one - * level undo The tags include an attribute list: - linked list of attribute/value nodes - each node has 2 - * null-terminated strings. - entities are replaced in attribute values white space is compacted if not in preformatted - * mode If not in preformatted mode then leading white space is discarded and subsequent white space sequences compacted - * to single space chars. If XmlTags is no then Tag names are folded to upper case and attribute names to lower case. - * Not yet done: - Doctype subset and marked sections - *

- * @author Dave Raggett
dsr@w3.org - * @author Andy Quick ac.quick@sympatico.ca (translation to Java) - * @author Fabrizio Giustina - * @version $Revision$ ($Author$) - */ -public class Lexer -{ - - /** - * state: ignore whitespace. - */ - public static final short IGNORE_WHITESPACE = 0; - - /** - * state: mixed content. - */ - public static final short MIXED_CONTENT = 1; - - /** - * state: preformatted. - */ - public static final short PREFORMATTED = 2; - - /** - * state: ignore markup. - */ - public static final short IGNORE_MARKUP = 3; - - /** - * URI for XHTML 1.0 transitional DTD. - */ - private static final String VOYAGER_LOOSE = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"; - - /** - * URI for XHTML 1.0 strict DTD. - */ - private static final String VOYAGER_STRICT = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"; - - /** - * URI for XHTML 1.0 frameset DTD. - */ - private static final String VOYAGER_FRAMESET = "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"; - - /** - * URI for XHTML 1.1. - */ - private static final String VOYAGER_11 = "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"; - - /** - * URI for XHTML Basic 1.0. - */ - // private static final String VOYAGER_BASIC = "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd"; - /** - * xhtml namespace. - */ - private static final String XHTML_NAMESPACE = "http://www.w3.org/1999/xhtml"; - - /** - * lists all the known versions. - */ - private static final Lexer.W3CVersionInfo[] W3CVERSION = { - new W3CVersionInfo("HTML 4.01", "XHTML 1.0 Strict", VOYAGER_STRICT, Dict.VERS_HTML40_STRICT), - new W3CVersionInfo("HTML 4.01 Transitional", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML40_LOOSE), - new W3CVersionInfo("HTML 4.01 Frameset", "XHTML 1.0 Frameset", VOYAGER_FRAMESET, Dict.VERS_FRAMESET), - new W3CVersionInfo("HTML 4.0", "XHTML 1.0 Strict", VOYAGER_STRICT, Dict.VERS_HTML40_STRICT), - new W3CVersionInfo("HTML 4.0 Transitional", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML40_LOOSE), - new W3CVersionInfo("HTML 4.0 Frameset", "XHTML 1.0 Frameset", VOYAGER_FRAMESET, Dict.VERS_FRAMESET), - new W3CVersionInfo("HTML 3.2", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML32), - new W3CVersionInfo("HTML 3.2 Final", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML32), - new W3CVersionInfo("HTML 3.2 Draft", "XHTML 1.0 Transitional", VOYAGER_LOOSE, Dict.VERS_HTML32), - new W3CVersionInfo("HTML 2.0", "XHTML 1.0 Strict", VOYAGER_STRICT, Dict.VERS_HTML20), - new W3CVersionInfo("HTML 4.01", "XHTML 1.1", VOYAGER_STRICT, Dict.VERS_XHTML11)}; - - /** - * getToken state: content. - */ - private static final short LEX_CONTENT = 0; - - /** - * getToken state: gt. - */ - private static final short LEX_GT = 1; - - /** - * getToken state: endtag. - */ - private static final short LEX_ENDTAG = 2; - - /** - * getToken state: start tag. - */ - private static final short LEX_STARTTAG = 3; - - /** - * getToken state: comment. - */ - private static final short LEX_COMMENT = 4; - - /** - * getToken state: doctype. - */ - private static final short LEX_DOCTYPE = 5; - - /** - * getToken state: procinstr. - */ - private static final short LEX_PROCINSTR = 6; - - /** - * getToken state: cdata. - */ - private static final short LEX_CDATA = 8; - - /** - * getToken state: section. - */ - private static final short LEX_SECTION = 9; - - /** - * getToken state: asp. - */ - private static final short LEX_ASP = 10; - - /** - * getToken state: jste. - */ - private static final short LEX_JSTE = 11; - - /** - * getToken state: php. - */ - private static final short LEX_PHP = 12; - - /** - * getToken state: xml declaration. - */ - private static final short LEX_XMLDECL = 13; - - /** - * file stream. - */ - protected StreamIn in; - - /** - * error output stream. - */ - protected PrintWriter errout; - - /** - * for accessibility errors. - */ - protected short badAccess; - - /** - * for bad style errors. - */ - protected short badLayout; - - /** - * for bad char encodings. - */ - protected short badChars; - - /** - * for mismatched/mispositioned form tags. - */ - protected short badForm; - - /** - * count of warnings in this document. - */ - protected short warnings; - - /** - * count of errors. - */ - protected short errors; - - /** - * lines seen. - */ - protected int lines; - - /** - * at start of current token. - */ - protected int columns; - - /** - * used to collapse contiguous white space. - */ - protected boolean waswhite; - - /** - * true after token has been pushed back. - */ - protected boolean pushed; - - /** - * when space is moved after end tag. - */ - protected boolean insertspace; - - /** - * Netscape compatibility. - */ - protected boolean excludeBlocks; - - /** - * true if moved out of table. - */ - protected boolean exiled; - - /** - * true if xmlns attribute on html element. - */ - protected boolean isvoyager; - - /** - * bit vector of HTML versions. - */ - protected short versions; - - /** - * version as given by doctype (if any). - */ - protected int doctype; - - /** - * set if html or PUBLIC is missing. - */ - protected boolean badDoctype; - - /** - * start of current node. - */ - protected int txtstart; - - /** - * end of current node. - */ - protected int txtend; - - /** - * state of lexer's finite state machine. - */ - protected short state; - - /** - * current node. - */ - protected Node token; - - /** - * Lexer character buffer parse tree nodes span onto this buffer which contains the concatenated text contents of - * all of the elements. Lexsize must be reset for each file. Byte buffer of UTF-8 chars. - */ - protected byte[] lexbuf; - - /** - * allocated. - */ - protected int lexlength; - - /** - * used. - */ - protected int lexsize; - - /** - * Inline stack for compatibility with Mosaic. For deferring text node. - */ - protected Node inode; - - /** - * for inferring inline tags. - */ - protected int insert; - - /** - * stack. - */ - protected Stack istack; - - /** - * start of frame. - */ - protected int istackbase; - - /** - * used for cleaning up presentation markup. - */ - protected Style styles; - - /** - * configuration. - */ - protected Configuration configuration; - - /** - * already seen end body tag? - */ - protected boolean seenEndBody; - - /** - * already seen end html tag? - */ - protected boolean seenEndHtml; - - /** - * report. - */ - protected Report report; - - /** - * Root node is saved here. - */ - protected Node root; - - /** - * node list. - */ - private List nodeList; - - /** - * Instantiates a new Lexer. - * @param in StreamIn - * @param configuration configuation instance - * @param report report instance, for reporting errors - */ - public Lexer(StreamIn in, Configuration configuration, Report report) - { - this.report = report; - this.in = in; - this.lines = 1; - this.columns = 1; - this.state = LEX_CONTENT; - this.versions = (Dict.VERS_ALL | Dict.VERS_PROPRIETARY); - this.doctype = Dict.VERS_UNKNOWN; - this.insert = -1; - this.istack = new Stack(); - this.configuration = configuration; - this.nodeList = new Vector(); - } - - /** - * Creates a new node and add it to nodelist. - * @return Node - */ - public Node newNode() - { - Node node = new Node(); - this.nodeList.add(node); - return node; - } - - /** - * Creates a new node and add it to nodelist. - * @param type node type: Node.ROOT_NODE | Node.DOCTYPE_TAG | Node.COMMENT_TAG | Node.PROC_INS_TAG | Node.TEXT_NODE | - * Node.START_TAG | Node.END_TAG | Node.START_END_TAG | Node.CDATA_TAG | Node.SECTION_TAG | Node. ASP_TAG | - * Node.JSTE_TAG | Node.PHP_TAG | Node.XML_DECL - * @param textarray array of bytes contained in the Node - * @param start start position - * @param end end position - * @return Node - */ - public Node newNode(short type, byte[] textarray, int start, int end) - { - Node node = new Node(type, textarray, start, end); - this.nodeList.add(node); - return node; - } - - /** - * Creates a new node and add it to nodelist. - * @param type node type: Node.ROOT_NODE | Node.DOCTYPE_TAG | Node.COMMENT_TAG | Node.PROC_INS_TAG | Node.TEXT_NODE | - * Node.START_TAG | Node.END_TAG | Node.START_END_TAG | Node.CDATA_TAG | Node.SECTION_TAG | Node. ASP_TAG | - * Node.JSTE_TAG | Node.PHP_TAG | Node.XML_DECL - * @param textarray array of bytes contained in the Node - * @param start start position - * @param end end position - * @param element tag name - * @return Node - */ - public Node newNode(short type, byte[] textarray, int start, int end, String element) - { - Node node = new Node(type, textarray, start, end, element, this.configuration.tt); - this.nodeList.add(node); - return node; - } - - /** - * Clones a node and add it to node list. - * @param node Node - * @return cloned Node - */ - public Node cloneNode(Node node) - { - Node cnode = (Node) node.clone(); - this.nodeList.add(cnode); - for (AttVal att = cnode.attributes; att != null; att = att.next) - { - if (att.asp != null) - { - this.nodeList.add(att.asp); - } - if (att.php != null) - { - this.nodeList.add(att.php); - } - } - return cnode; - } - - /** - * Clones an attribute value and add eventual asp or php node to node list. - * @param attrs original AttVal - * @return cloned AttVal - */ - public AttVal cloneAttributes(AttVal attrs) - { - AttVal cattrs = (AttVal) attrs.clone(); - for (AttVal att = cattrs; att != null; att = att.next) - { - if (att.asp != null) - { - this.nodeList.add(att.asp); - } - if (att.php != null) - { - this.nodeList.add(att.php); - } - } - return cattrs; - } - - /** - * Update oldtextarray in the current nodes. - * @param oldtextarray previous text array - * @param newtextarray new text array - */ - protected void updateNodeTextArrays(byte[] oldtextarray, byte[] newtextarray) - { - Node node; - for (int i = 0; i < this.nodeList.size(); i++) - { - node = (Node) (this.nodeList.get(i)); - if (node.textarray == oldtextarray) - { - node.textarray = newtextarray; - } - } - } - - /** - * Adds a new line node. Used for creating preformatted text from Word2000. - * @return new line node - */ - public Node newLineNode() - { - Node node = newNode(); - - node.textarray = this.lexbuf; - node.start = this.lexsize; - addCharToLexer('\n'); - node.end = this.lexsize; - return node; - } - - /** - * Has end of input stream been reached? - * @return true if end of input stream been reached - */ - public boolean endOfInput() - { - return this.in.isEndOfStream(); - } - - /** - * Adds a byte to lexer buffer. - * @param c byte to add - */ - public void addByte(int c) - { - if (this.lexsize + 1 >= this.lexlength) - { - while (this.lexsize + 1 >= this.lexlength) - { - if (this.lexlength == 0) - { - this.lexlength = 8192; - } - else - { - this.lexlength = this.lexlength * 2; - } - } - - byte[] temp = this.lexbuf; - this.lexbuf = new byte[this.lexlength]; - if (temp != null) - { - System.arraycopy(temp, 0, this.lexbuf, 0, temp.length); - updateNodeTextArrays(temp, this.lexbuf); - } - } - - this.lexbuf[this.lexsize++] = (byte) c; - this.lexbuf[this.lexsize] = (byte) '\0'; // debug - } - - /** - * Substitute the last char in buffer. - * @param c new char - */ - public void changeChar(byte c) - { - if (this.lexsize > 0) - { - this.lexbuf[this.lexsize - 1] = c; - } - } - - /** - * Store char c as UTF-8 encoded byte stream. - * @param c char to store - */ - public void addCharToLexer(int c) - { - // Allow only valid XML characters. See: http://www.w3.org/TR/2004/REC-xml-20040204/#NT-Char - // Fix by Pablo Mayrgundter 17-08-2004 - - if ((this.configuration.xmlOut || this.configuration.xHTML) // only for xml output - && !((c >= 0x20 && c <= 0xD7FF) // Check the common-case first. - || c == 0x9 - || c == 0xA - || c == 0xD // Then white-space. - || (c >= 0xE000 && c <= 0xFFFD) // Then high-range unicode. - || (c >= 0x10000 && c <= 0x10FFFF))) - { - return; - } - - int i = 0; - int[] count = new int[]{0}; - byte[] buf = new byte[10]; // unsigned char - - boolean err = EncodingUtils.encodeCharToUTF8Bytes(c, buf, null, count); - if (err) - { - // replacement char 0xFFFD encoded as UTF-8 - buf[0] = (byte) 0xEF; - buf[1] = (byte) 0xBF; - buf[2] = (byte) 0xBD; - count[0] = 3; - } - - for (i = 0; i < count[0]; i++) - { - addByte(buf[i]); // uint - } - - } - - /** - * Adds a string to lexer buffer. - * @param str String to add - */ - public void addStringToLexer(String str) - { - for (int i = 0; i < str.length(); i++) - { - addCharToLexer(str.charAt(i)); - } - } - - /** - * Parse an html entity. - * @param mode mode - */ - public void parseEntity(short mode) - { - // No longer attempts to insert missing ';' for unknown - // entities unless one was present already, since this - // gives unexpected results. - // - // For example: - // was tidied to: - // rather than: - // - // My thanks for Maurice Buxton for spotting this. - // - // Also Randy Waki pointed out the following case for the - // 04 Aug 00 version (bug #433012): - // - // For example: - // was tidied to: - // rather than: - // - // where "lang" is a known entity (#9001), but browsers would - // misinterpret "⟨" because it had a value > 256. - // - // So the case of an apparently known entity with a value > 256 and - // missing a semicolon is handled specially. - // - // "ParseEntity" is also a bit of a misnomer - it handles entities and - // numeric character references. Invalid NCR's are now reported. - - int start; - boolean first = true; - boolean semicolon = false; - int c, ch, startcol; - String str; - - start = this.lexsize - 1; // to start at "&" - startcol = this.in.getCurcol() - 1; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - if (c == ';') - { - semicolon = true; - break; - } - - if (first && c == '#') - { - // #431953 - start RJ - if (!this.configuration.ncr - || "BIG5".equals(this.configuration.getInCharEncodingName()) - || "SHIFTJIS".equals(this.configuration.getInCharEncodingName())) - { - this.in.ungetChar(c); - return; - } - // #431953 - end RJ - - addCharToLexer(c); - first = false; - continue; - } - - first = false; - - if (TidyUtils.isNamechar((char) c)) - { - addCharToLexer(c); - continue; - } - - // otherwise put it back - this.in.ungetChar(c); - break; - } - - str = TidyUtils.getString(this.lexbuf, start, this.lexsize - start); - - if ("&apos".equals(str) && !configuration.xmlOut && !this.isvoyager && !configuration.xHTML) - { - report.entityError(this, Report.APOS_UNDEFINED, str, 39); - } - - ch = EntityTable.getDefaultEntityTable().entityCode(str); - - // drops invalid numeric entities from XML mode. Fix by Pablo Mayrgundter 17-08-2004 - // if ((this.configuration.xmlOut || this.configuration.xHTML) // only for xml output - // && !((ch >= 0x20 && ch <= 0xD7FF) // Check the common-case first. - // || ch == 0x9 || ch == 0xA || ch == 0xD // Then white-space. - // || (ch >= 0xE000 && ch <= 0xFFFD))) - // { - // this.lexsize = start; - // return; - // } - - // deal with unrecognized or invalid entities - // #433012 - fix by Randy Waki 17 Feb 01 - // report invalid NCR's - Terry Teague 01 Sep 01 - if (ch <= 0 || (ch >= 256 && c != ';')) - { - // set error position just before offending character - this.lines = this.in.getCurline(); - this.columns = startcol; - - if (this.lexsize > start + 1) - { - if (ch >= 128 && ch <= 159) - { - // invalid numeric character reference - int c1 = 0; - - if ("WIN1252".equals(configuration.replacementCharEncoding)) - { - c1 = EncodingUtils.decodeWin1252(ch); - } - else if ("MACROMAN".equals(configuration.replacementCharEncoding)) - { - c1 = EncodingUtils.decodeMacRoman(ch); - } - - // "or" DISCARDED_CHAR with the other errors if discarding char; otherwise default is replacing - - int replaceMode = c1 != 0 ? Report.REPLACED_CHAR : Report.DISCARDED_CHAR; - - if (c != ';') /* issue warning if not terminated by ';' */ - { - report.entityError(this, Report.MISSING_SEMICOLON_NCR, str, c); - } - - report.encodingError(this, (short) (Report.INVALID_NCR | replaceMode), ch); - - if (c1 != 0) - { - // make the replacement - this.lexsize = start; - addCharToLexer(c1); - semicolon = false; - } - else - { - /* discard */ - this.lexsize = start; - semicolon = false; - } - - } - else - { - report.entityError(this, Report.UNKNOWN_ENTITY, str, ch); - } - - if (semicolon) - { - addCharToLexer(';'); - } - } - else - { - // naked & - report.entityError(this, Report.UNESCAPED_AMPERSAND, str, ch); - } - } - else - { - // issue warning if not terminated by ';' - if (c != ';') - { - // set error position just before offending character - this.lines = this.in.getCurline(); - this.columns = startcol; - report.entityError(this, Report.MISSING_SEMICOLON, str, c); - } - - this.lexsize = start; - - if (ch == 160 && TidyUtils.toBoolean(mode & PREFORMATTED)) - { - ch = ' '; - } - - addCharToLexer(ch); - - if (ch == '&' && !this.configuration.quoteAmpersand) - { - addCharToLexer('a'); - addCharToLexer('m'); - addCharToLexer('p'); - addCharToLexer(';'); - } - } - } - - /** - * Parses a tag name. - * @return first char after the tag name - */ - public char parseTagName() - { - int c; - - // fold case of first char in buffer - c = this.lexbuf[this.txtstart]; - - if (!this.configuration.xmlTags && TidyUtils.isUpper((char) c)) - { - c = TidyUtils.toLower((char) c); - this.lexbuf[this.txtstart] = (byte) c; - } - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - if (!TidyUtils.isNamechar((char) c)) - { - break; - } - - // fold case of subsequent chars - if (!this.configuration.xmlTags && TidyUtils.isUpper((char) c)) - { - c = TidyUtils.toLower((char) c); - } - - addCharToLexer(c); - } - - this.txtend = this.lexsize; - return (char) c; - } - - /** - * calls addCharToLexer for any char in the string. - * @param str input String - */ - public void addStringLiteral(String str) - { - int len = str.length(); - for (int i = 0; i < len; i++) - { - addCharToLexer(str.charAt(i)); - } - } - - /** - * calls addCharToLexer for any char in the string till len is reached. - * @param str input String - * @param len length of the substring to be added - */ - void addStringLiteralLen(String str, int len) - { - int strlen = str.length(); - if (strlen < len) - { - len = strlen; - } - for (int i = 0; i < len; i++) - { - addCharToLexer(str.charAt(i)); - } - } - - /** - * Choose what version to use for new doctype. - * @return html version constant - */ - public short htmlVersion() - { - if (TidyUtils.toBoolean(versions & Dict.VERS_HTML20)) - { - return Dict.VERS_HTML20; - } - - if (!(this.configuration.xmlOut | this.configuration.xmlTags | this.isvoyager) - && TidyUtils.toBoolean(versions & Dict.VERS_HTML32)) - { - return Dict.VERS_HTML32; - } - if (TidyUtils.toBoolean(versions & Dict.VERS_XHTML11)) - { - return Dict.VERS_XHTML11; - } - if (TidyUtils.toBoolean(versions & Dict.VERS_HTML40_STRICT)) - { - return Dict.VERS_HTML40_STRICT; - } - - if (TidyUtils.toBoolean(versions & Dict.VERS_HTML40_LOOSE)) - { - return Dict.VERS_HTML40_LOOSE; - } - - if (TidyUtils.toBoolean(versions & Dict.VERS_FRAMESET)) - { - return Dict.VERS_FRAMESET; - } - - return Dict.VERS_UNKNOWN; - } - - /** - * Choose what version to use for new doctype. - * @return html version name - */ - public String htmlVersionName() - { - short guessed; - int j; - - guessed = apparentVersion(); - - for (j = 0; j < W3CVERSION.length; ++j) - { - if (guessed == W3CVERSION[j].code) - { - if (this.isvoyager) - { - return W3CVERSION[j].voyagerName; - } - - return W3CVERSION[j].name; - } - } - - return null; - } - - /** - * Add meta element for Tidy. If the meta tag is already present, update release date. - * @param root root node - * @return true if the tag has been added - */ - public boolean addGenerator(Node root) - { - AttVal attval; - Node node; - Node head = root.findHEAD(this.configuration.tt); - - if (head != null) - { - String meta = "HTML Tidy for Java (vers. " + Report.RELEASE_DATE_STRING + "), see www.w3.org"; - - for (node = head.content; node != null; node = node.next) - { - if (node.tag == this.configuration.tt.tagMeta) - { - attval = node.getAttrByName("name"); - - if (attval != null && attval.value != null && "generator".equalsIgnoreCase(attval.value)) - { - attval = node.getAttrByName("content"); - - if (attval != null - && attval.value != null - && attval.value.length() >= 9 - && "HTML Tidy".equalsIgnoreCase(attval.value.substring(0, 9))) - { - attval.value = meta; - return false; - } - } - } - } - - node = this.inferredTag("meta"); - node.addAttribute("content", meta); - node.addAttribute("name", "generator"); - head.insertNodeAtStart(node); - return true; - } - - return false; - } - - /** - * Check system keywords (keywords should be uppercase). - * @param doctype doctype node - * @return true if doctype keywords are all uppercase - */ - public boolean checkDocTypeKeyWords(Node doctype) - { - int len = doctype.end - doctype.start; - String s = TidyUtils.getString(this.lexbuf, doctype.start, len); - - return !(TidyUtils.findBadSubString("SYSTEM", s, len) - || TidyUtils.findBadSubString("PUBLIC", s, len) - || TidyUtils.findBadSubString("//DTD", s, len) - || TidyUtils.findBadSubString("//W3C", s, len) || TidyUtils.findBadSubString("//EN", s, len)); - } - - /** - * Examine DOCTYPE to identify version. - * @param doctype doctype node - * @return version code - */ - public short findGivenVersion(Node doctype) - { - String p, s; - int i, j; - int len; - String str1; - String str2; - - // if root tag for doctype isn't html give up now - str1 = TidyUtils.getString(this.lexbuf, doctype.start, 5); - if (!"html ".equalsIgnoreCase(str1)) - { - return 0; - } - - if (!checkDocTypeKeyWords(doctype)) - { - report.warning(this, doctype, null, Report.DTYPE_NOT_UPPER_CASE); - } - - // give up if all we are given is the system id for the doctype - str1 = TidyUtils.getString(this.lexbuf, doctype.start + 5, 7); - if ("SYSTEM ".equalsIgnoreCase(str1)) - { - // but at least ensure the case is correct - if (!str1.substring(0, 6).equals("SYSTEM")) - { - System.arraycopy(TidyUtils.getBytes("SYSTEM"), 0, this.lexbuf, doctype.start + 5, 6); - } - return 0; // unrecognized - } - - if ("PUBLIC ".equalsIgnoreCase(str1)) - { - if (!str1.substring(0, 6).equals("PUBLIC")) - { - System.arraycopy(TidyUtils.getBytes("PUBLIC "), 0, this.lexbuf, doctype.start + 5, 6); - } - } - else - { - this.badDoctype = true; - } - - for (i = doctype.start; i < doctype.end; ++i) - { - if (this.lexbuf[i] == (byte) '"') - { - str1 = TidyUtils.getString(this.lexbuf, i + 1, 12); - str2 = TidyUtils.getString(this.lexbuf, i + 1, 13); - if (str1.equals("-//W3C//DTD ")) - { - // compute length of identifier e.g. "HTML 4.0 Transitional" - for (j = i + 13; j < doctype.end && this.lexbuf[j] != (byte) '/'; ++j) - { - // - } - len = j - i - 13; - p = TidyUtils.getString(this.lexbuf, i + 13, len); - - for (j = 1; j < W3CVERSION.length; ++j) - { - s = W3CVERSION[j].name; - if (len == s.length() && s.equals(p)) - { - return W3CVERSION[j].code; - } - } - - // else unrecognized version - } - else if (str2.equals("-//IETF//DTD ")) - { - // compute length of identifier e.g. "HTML 2.0" - for (j = i + 14; j < doctype.end && this.lexbuf[j] != (byte) '/'; ++j) - { - // - } - len = j - i - 14; - - p = TidyUtils.getString(this.lexbuf, i + 14, len); - s = W3CVERSION[0].name; - if (len == s.length() && s.equals(p)) - { - return W3CVERSION[0].code; - } - - // else unrecognized version - } - break; - } - } - - return 0; - } - - /** - * Fix xhtml namespace. - * @param root root Node - * @param profile current profile - */ - public void fixHTMLNameSpace(Node root, String profile) - { - Node node; - AttVal attr; - - node = root.content; - while (node != null && node.tag != this.configuration.tt.tagHtml) - { - node = node.next; - } - - if (node != null) - { - - for (attr = node.attributes; attr != null; attr = attr.next) - { - if (attr.attribute.equals("xmlns")) - { - break; - } - - } - - if (attr != null) - { - if (!attr.value.equals(profile)) - { - report.warning(this, node, null, Report.INCONSISTENT_NAMESPACE); - attr.value = profile; - } - } - else - { - attr = new AttVal(node.attributes, null, '"', "xmlns", profile); - attr.dict = AttributeTable.getDefaultAttributeTable().findAttribute(attr); - node.attributes = attr; - } - } - } - - /** - * Put DOCTYPE declaration between the <:?xml version "1.0" ... ?> declaration, if any, and the - * html tag. Should also work for any comments, etc. that may precede the html tag. - * @param root root node - * @return new doctype node - */ - Node newXhtmlDocTypeNode(Node root) - { - Node html = root.findHTML(this.configuration.tt); - if (html == null) - { - return null; - } - - Node newdoctype = newNode(); - newdoctype.setType(Node.DOCTYPE_TAG); - newdoctype.next = html; - newdoctype.parent = root; - newdoctype.prev = null; - - if (html == root.content) - { - // No declaration. - root.content.prev = newdoctype; - root.content = newdoctype; - newdoctype.prev = null; - } - else - { - // we have an declaration. - newdoctype.prev = html.prev; - newdoctype.prev.next = newdoctype; - } - html.prev = newdoctype; - return newdoctype; - } - - /** - * Adds a new xhtml doctype to the document. - * @param root root node - * @return true if a doctype has been added - */ - public boolean setXHTMLDocType(Node root) - { - String fpi = " "; - String sysid = ""; - String namespace = XHTML_NAMESPACE; - String dtdsub = null; - Node doctype; - int dtdlen = 0; - - doctype = root.findDocType(); - - fixHTMLNameSpace(root, namespace); // #427839 - fix by Evan Lenz 05 Sep 00 - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_OMIT) - { - if (doctype != null) - { - Node.discardElement(doctype); - } - return true; - } - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_AUTO) - { - // see what flavor of XHTML this document matches - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_STRICT)) - { - // use XHTML strict - fpi = "-//W3C//DTD XHTML 1.0 Strict//EN"; - sysid = VOYAGER_STRICT; - } - else if (TidyUtils.toBoolean(this.versions & Dict.VERS_FRAMESET)) - { - // use XHTML frames - fpi = "-//W3C//DTD XHTML 1.0 Frameset//EN"; - sysid = VOYAGER_FRAMESET; - } - else if (TidyUtils.toBoolean(this.versions & Dict.VERS_LOOSE)) - { - fpi = "-//W3C//DTD XHTML 1.0 Transitional//EN"; - sysid = VOYAGER_LOOSE; - } - else if (TidyUtils.toBoolean(this.versions & Dict.VERS_XHTML11)) - { - // use XHTML 1.1 - fpi = "-//W3C//DTD XHTML 1.1//EN"; - sysid = VOYAGER_11; - } - else - { - // proprietary - fpi = null; - sysid = ""; - if (doctype != null)// #473490 - fix by Bjšrn Hšhrmann 10 Oct 01 - { - Node.discardElement(doctype); - } - } - } - else if (this.configuration.docTypeMode == Configuration.DOCTYPE_STRICT) - { - fpi = "-//W3C//DTD XHTML 1.0 Strict//EN"; - sysid = VOYAGER_STRICT; - } - else if (this.configuration.docTypeMode == Configuration.DOCTYPE_LOOSE) - { - fpi = "-//W3C//DTD XHTML 1.0 Transitional//EN"; - sysid = VOYAGER_LOOSE; - } - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_USER && this.configuration.docTypeStr != null) - { - fpi = this.configuration.docTypeStr; - sysid = ""; - } - - if (fpi == null) - { - return false; - } - - if (doctype != null) - { - // Look for internal DTD subset - if (configuration.xHTML || configuration.xmlOut) - { - - int len = doctype.end - doctype.start + 1; - String start = TidyUtils.getString(this.lexbuf, doctype.start, len); - - int dtdbeg = start.indexOf('['); - if (dtdbeg >= 0) - { - int dtdend = start.substring(dtdbeg).indexOf(']'); - if (dtdend >= 0) - { - dtdlen = dtdend + 1; - dtdsub = start.substring(dtdbeg); - } - } - } - } - else - { - if ((doctype = newXhtmlDocTypeNode(root)) == null) - { - return false; - } - } - - this.txtstart = this.lexsize; - this.txtend = this.lexsize; - - // add public identifier - addStringLiteral("html PUBLIC "); - - // check if the fpi is quoted or not - if (fpi.charAt(0) == '"') - { - addStringLiteral(fpi); - } - else - { - addStringLiteral("\""); - addStringLiteral(fpi); - addStringLiteral("\""); - } - - if (this.configuration.wraplen != 0 && sysid.length() + 6 >= this.configuration.wraplen) - { - addStringLiteral("\n\""); - } - else - { - // FG: don't wrap - addStringLiteral(" \""); - } - - // add system identifier - addStringLiteral(sysid); - addStringLiteral("\""); - - if (dtdlen > 0 && dtdsub != null) - { - addCharToLexer(' '); - addStringLiteralLen(dtdsub, dtdlen); - } - - this.txtend = this.lexsize; - - int length = this.txtend - this.txtstart; - doctype.textarray = new byte[length]; - - System.arraycopy(this.lexbuf, this.txtstart, doctype.textarray, 0, length); - doctype.start = 0; - doctype.end = length; - - return false; - } - - /** - * Return the html version used in document. - * @return version code - */ - public short apparentVersion() - { - switch (this.doctype) - { - case Dict.VERS_UNKNOWN : - return htmlVersion(); - - case Dict.VERS_HTML20 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML20)) - { - return Dict.VERS_HTML20; - } - - break; - - case Dict.VERS_HTML32 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML32)) - { - return Dict.VERS_HTML32; - } - - break; // to replace old version by new - - case Dict.VERS_HTML40_STRICT : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_STRICT)) - { - return Dict.VERS_HTML40_STRICT; - } - - break; - - case Dict.VERS_HTML40_LOOSE : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_LOOSE)) - { - return Dict.VERS_HTML40_LOOSE; - } - - break; // to replace old version by new - - case Dict.VERS_FRAMESET : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_FRAMESET)) - { - return Dict.VERS_FRAMESET; - } - - break; - - case Dict.VERS_XHTML11 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_XHTML11)) - { - return Dict.VERS_XHTML11; - } - - break; - default : - // should never reach here - break; - } - - // kludge to avoid error appearing at end of file - // it would be better to note the actual position - // when first encountering the doctype declaration - - this.lines = 1; - this.columns = 1; - - report.warning(this, null, null, Report.INCONSISTENT_VERSION); - return this.htmlVersion(); - } - - /** - * Fixup doctype if missing. - * @param root root node - * @return false if current version has not been identified - */ - public boolean fixDocType(Node root) - { - Node doctype; - int guessed = Dict.VERS_HTML40_STRICT, i; - - if (this.badDoctype) - { - report.warning(this, null, null, Report.MALFORMED_DOCTYPE); - } - - doctype = root.findDocType(); - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_OMIT) - { - if (doctype != null) - { - Node.discardElement(doctype); - } - return true; - } - - if (this.configuration.xmlOut) - { - return true; - } - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_STRICT) - { - Node.discardElement(doctype); - doctype = null; - guessed = Dict.VERS_HTML40_STRICT; - } - else if (this.configuration.docTypeMode == Configuration.DOCTYPE_LOOSE) - { - Node.discardElement(doctype); - doctype = null; - guessed = Dict.VERS_HTML40_LOOSE; - } - else if (this.configuration.docTypeMode == Configuration.DOCTYPE_AUTO) - { - if (doctype != null) - { - if (this.doctype == Dict.VERS_UNKNOWN) - { - return false; - } - - switch (this.doctype) - { - case Dict.VERS_UNKNOWN : - return false; - - case Dict.VERS_HTML20 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML20)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_HTML32 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML32)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_HTML40_STRICT : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_STRICT)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_HTML40_LOOSE : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_HTML40_LOOSE)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_FRAMESET : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_FRAMESET)) - { - return true; - } - - break; // to replace old version by new - - case Dict.VERS_XHTML11 : - if (TidyUtils.toBoolean(this.versions & Dict.VERS_XHTML11)) - { - return true; - } - - break; // to replace old version by new - default : - // should never reach here - break; - } - - // INCONSISTENT_VERSION warning is now issued by ApparentVersion() - } - - // choose new doctype - guessed = htmlVersion(); - } - - if (guessed == Dict.VERS_UNKNOWN) - { - return false; - } - - // for XML use the Voyager system identifier - if (this.configuration.xmlOut || this.configuration.xmlTags || this.isvoyager) - { - if (doctype != null) - { - Node.discardElement(doctype); - } - - fixHTMLNameSpace(root, XHTML_NAMESPACE); - - // Namespace is the same for all XHTML variants - // Also, don't return yet. Still need to add DOCTYPE declaration. - // - // for (i = 0; i < W3CVersion.length; ++i) - // { - // if (guessed == W3CVersion[i].code) - // { - // fixHTMLNameSpace(root, W3CVersion[i].profile); - // break; - // } - // } - // return true; - } - - if (doctype == null) - { - if ((doctype = newXhtmlDocTypeNode(root)) == null) - { - return false; - } - } - - this.txtstart = this.lexsize; - this.txtend = this.lexsize; - - // use the appropriate public identifier - addStringLiteral("html PUBLIC "); - - if (this.configuration.docTypeMode == Configuration.DOCTYPE_USER - && this.configuration.docTypeStr != null - && this.configuration.docTypeStr.length() > 0) - { - // check if the fpi is quoted or not - if (this.configuration.docTypeStr.charAt(0) == '"') - { - addStringLiteral(this.configuration.docTypeStr); - } - else - { - addStringLiteral("\""); // #431889 - fix by Dave Bryan 04 Jan 2001 - addStringLiteral(this.configuration.docTypeStr); - addStringLiteral("\""); // #431889 - fix by Dave Bryan 04 Jan 2001 - } - } - else if (guessed == Dict.VERS_HTML20) - { - addStringLiteral("\"-//IETF//DTD HTML 2.0//EN\""); - } - else - { - addStringLiteral("\"-//W3C//DTD "); - - for (i = 0; i < W3CVERSION.length; ++i) - { - if (guessed == W3CVERSION[i].code) - { - addStringLiteral(W3CVERSION[i].name); - break; - } - } - - addStringLiteral("//EN\""); - } - - this.txtend = this.lexsize; - - int length = this.txtend - this.txtstart; - doctype.textarray = new byte[length]; - - System.arraycopy(this.lexbuf, this.txtstart, doctype.textarray, 0, length); - doctype.start = 0; - doctype.end = length; - - return true; - } - - /** - * Ensure XML document starts with <?XML version="1.0"?>. Add encoding attribute if not using - * ASCII or UTF-8 output. - * @param root root node - * @return always true - */ - public boolean fixXmlDecl(Node root) - { - Node xml; - AttVal version; - AttVal encoding; - - if (root.content != null && root.content.type == Node.XML_DECL) - { - xml = root.content; - } - else - { - xml = newNode(Node.XML_DECL, this.lexbuf, 0, 0); - xml.next = root.content; - - if (root.content != null) - { - root.content.prev = xml; - xml.next = root.content; - } - - root.content = xml; - } - - version = xml.getAttrByName("version"); - encoding = xml.getAttrByName("encoding"); - - // We need to insert a check if declared encoding and output encoding mismatch - // and fix the Xml declaration accordingly!!! - if (encoding == null && !"UTF8".equals(this.configuration.getOutCharEncodingName())) - { - if ("ISO8859_1".equals(this.configuration.getOutCharEncodingName())) - { - xml.addAttribute("encoding", "iso-8859-1"); - } - if ("ISO2022".equals(this.configuration.getOutCharEncodingName())) - { - xml.addAttribute("encoding", "iso-2022"); - } - } - - if (version == null) - { - xml.addAttribute("version", "1.0"); - } - - return true; - } - - /** - * Generates and inserts a new node. - * @param name tag name - * @return generated node - */ - public Node inferredTag(String name) - { - Node node; - - node = newNode(Node.START_TAG, this.lexbuf, this.txtstart, this.txtend, name); - node.implicit = true; - return node; - } - - /** - * Create a text node for the contents of a CDATA element like style or script which ends with </foo> for some - * foo. - * @param container container node - * @return cdata node - */ - public Node getCDATA(Node container) - { - int c, lastc, start, len, i; - int qt = 0; - int esc = 0; - String str; - boolean endtag = false; - boolean begtag = false; - - if (container.isJavaScript()) - { - esc = '\\'; - } - - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - this.waswhite = false; - this.txtstart = this.lexsize; - this.txtend = this.lexsize; - - lastc = '\0'; - start = -1; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - // treat \r\n as \n and \r as \n - if (qt > 0) - { - // #598860 script parsing fails with quote chars - // A quoted string is ended by the quotation character, or end of line - if ((c == '\r' || c == '\n' || c == qt) && (!TidyUtils.toBoolean(esc) || lastc != esc)) - { - qt = 0; - } - else if (c == '/' && lastc == '<') - { - start = this.lexsize + 1; // to first letter - } - - else if (c == '>' && start >= 0) - { - len = this.lexsize - start; - - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol() - 3; - - report.warning(this, null, null, Report.BAD_CDATA_CONTENT); - - // if javascript insert backslash before / - if (TidyUtils.toBoolean(esc)) - { - for (i = this.lexsize; i > start - 1; --i) - { - this.lexbuf[i] = this.lexbuf[i - 1]; - } - - this.lexbuf[start - 1] = (byte) esc; - this.lexsize++; - } - - start = -1; - } - } - else if (TidyUtils.isQuote(c) && (!TidyUtils.toBoolean(esc) || lastc != esc)) - { - qt = c; - } - else if (c == '<') - { - start = this.lexsize + 1; // to first letter - endtag = false; - begtag = true; - } - else if (c == '!' && lastc == '<') // Cancel start tag - { - start = -1; - endtag = false; - begtag = false; - } - else if (c == '/' && lastc == '<') - { - start = this.lexsize + 1; // to first letter - endtag = true; - begtag = false; - } - else if (c == '>' && start >= 0) // End of begin or end tag - { - int decr = 2; - - if (endtag && ((len = this.lexsize - start) == container.element.length())) - { - - str = TidyUtils.getString(this.lexbuf, start, len); - if (container.element.equalsIgnoreCase(str)) - { - this.txtend = start - decr; - this.lexsize = start - decr; // #433857 - fix by Huajun Zeng 26 Apr 01 - break; - } - } - - // Unquoted markup will end SCRIPT or STYLE elements - - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol() - 3; - - report.warning(this, null, null, Report.BAD_CDATA_CONTENT); - if (begtag) - { - decr = 1; - } - this.txtend = start - decr; - this.lexsize = start - decr; - break; - } - // #427844 - fix by Markus Hoenicka 21 Oct 00 - else if (c == '\r') - { - if (begtag || endtag) - { - continue; // discard whitespace in endtag - } - - c = this.in.readChar(); - - if (c != '\n') - { - this.in.ungetChar(c); - } - - c = '\n'; - - } - else if ((c == '\n' || c == '\t' || c == ' ') && (begtag || endtag)) - { - continue; // discard whitespace in endtag - } - - addCharToLexer(c); - this.txtend = this.lexsize; - lastc = c; - } - - if (c == StreamIn.END_OF_STREAM) - { - report.warning(this, container, null, Report.MISSING_ENDTAG_FOR); - } - - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - return null; - } - - /** - * - * - */ - public void ungetToken() - { - this.pushed = true; - } - - /** - * Gets a token. - * @param mode one of the following: - *
    - *
  • MixedContent-- for elements which don't accept PCDATA
  • - *
  • Preformatted-- white spacepreserved as is
  • - *
  • IgnoreMarkup-- for CDATA elements such as script, style
  • - *
- * @return next Node - */ - public Node getToken(short mode) - { - int c = 0; - int badcomment = 0; - // pass by reference - boolean[] isempty = new boolean[1]; - boolean inDTDSubset = false; - AttVal attributes = null; - - if (this.pushed) - { - // duplicate inlines in preference to pushed text nodes when appropriate - if (this.token.type != Node.TEXT_NODE || (this.insert == -1 && this.inode == null)) - { - this.pushed = false; - return this.token; - } - } - - // at start of block elements, unclosed inline - if (this.insert != -1 || this.inode != null) - { - return insertedToken(); - } - - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - this.waswhite = false; - - this.txtstart = this.lexsize; - this.txtend = this.lexsize; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - // FG fix for [427846] different from tidy - // if (this.insertspace && (!TidyUtils.toBoolean(mode & IGNORE_WHITESPACE))) - if (this.insertspace && mode != IGNORE_WHITESPACE) - { - addCharToLexer(' '); - } - if (this.insertspace && (!TidyUtils.toBoolean(mode & IGNORE_WHITESPACE))) - { - this.waswhite = true; - this.insertspace = false; - } - - // treat \r\n as \n and \r as \n - if (c == '\r') - { - c = this.in.readChar(); - - if (c != '\n') - { - this.in.ungetChar(c); - } - - c = '\n'; - } - - addCharToLexer(c); - - switch (this.state) - { - case LEX_CONTENT : - // element content - - // Discard white space if appropriate. - // Its cheaper to do this here rather than in parser methods for elements that - // don't have mixed content. - if (TidyUtils.isWhite((char) c) && (mode == IGNORE_WHITESPACE) && this.lexsize == this.txtstart + 1) - { - --this.lexsize; - this.waswhite = false; - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - continue; - } - - if (c == '<') - { - this.state = LEX_GT; - continue; - } - - if (TidyUtils.isWhite((char) c)) - { - // was previous char white? - if (this.waswhite) - { - if (mode != PREFORMATTED && mode != IGNORE_MARKUP) - { - --this.lexsize; - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - } - } - else - { - // prev char wasn't white - this.waswhite = true; - - if (mode != PREFORMATTED && mode != IGNORE_MARKUP && c != ' ') - { - changeChar((byte) ' '); - } - } - - continue; - } - else if (c == '&' && mode != IGNORE_MARKUP) - { - parseEntity(mode); - } - - // this is needed to avoid trimming trailing whitespace - if (mode == IGNORE_WHITESPACE) - { - mode = MIXED_CONTENT; - } - - this.waswhite = false; - continue; - - case LEX_GT : - // < - - // check for endtag - if (c == '/') - { - c = this.in.readChar(); - if (c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - continue; - } - - addCharToLexer(c); - - if (TidyUtils.isLetter((char) c)) - { - this.lexsize -= 3; - this.txtend = this.lexsize; - this.in.ungetChar(c); - this.state = LEX_ENDTAG; - this.lexbuf[this.lexsize] = (byte) '\0'; // debug - - // changed from - // this.in.curcol -= 2; - this.columns -= 2; - - // if some text before the this.txtstart) - { - // trim space char before end tag - if (mode == IGNORE_WHITESPACE && this.lexbuf[this.lexsize - 1] == (byte) ' ') - { - this.lexsize -= 1; - this.txtend = this.lexsize; - } - - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - continue; // no text so keep going - } - - // otherwise treat as CDATA - this.waswhite = false; - this.state = LEX_CONTENT; - continue; - } - - if (mode == IGNORE_MARKUP) - { - // otherwise treat as CDATA - this.waswhite = false; - this.state = LEX_CONTENT; - continue; - } - - // look out for comments, doctype or marked sections this isn't quite right, but its getting there - if (c == '!') - { - c = this.in.readChar(); - - if (c == '-') - { - c = this.in.readChar(); - - if (c == '-') - { - this.state = LEX_COMMENT; // comment - this.lexsize -= 2; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - report.warning(this, null, null, Report.MALFORMED_COMMENT); - } - else if (c == 'd' || c == 'D') - { - this.state = LEX_DOCTYPE; // doctype - this.lexsize -= 2; - this.txtend = this.lexsize; - mode = IGNORE_WHITESPACE; - - // skip until white space or '>' - - for (;;) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM || c == '>') - { - this.in.ungetChar(c); - break; - } - - if (!TidyUtils.isWhite((char) c)) - { - continue; - } - - // and skip to end of whitespace - - for (;;) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM || c == '>') - { - this.in.ungetChar(c); - break; - } - - if (TidyUtils.isWhite((char) c)) - { - continue; - } - - this.in.ungetChar(c); - break; - } - - break; - } - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - else if (c == '[') - { - // Word 2000 embeds ... sequences - this.lexsize -= 2; - this.state = LEX_SECTION; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - // otherwise swallow chars up to and including next '>' - while (true) - { - c = this.in.readChar(); - if (c == '>') - { - break; - } - if (c == -1) - { - this.in.ungetChar(c); - break; - } - } - - this.lexsize -= 2; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - continue; - } - - // processing instructions - - if (c == '?') - { - this.lexsize -= 2; - this.state = LEX_PROCINSTR; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - // Microsoft ASP's e.g. <% ... server-code ... %> - if (c == '%') - { - this.lexsize -= 2; - this.state = LEX_ASP; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - // Netscapes JSTE e.g. <# ... server-code ... #> - if (c == '#') - { - this.lexsize -= 2; - this.state = LEX_JSTE; - this.txtend = this.lexsize; - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - this.txtstart = this.lexsize; - continue; - } - - // check for start tag - if (TidyUtils.isLetter((char) c)) - { - this.in.ungetChar(c); // push back letter - this.lexsize -= 2; // discard " <" + letter - this.txtend = this.lexsize; - this.state = LEX_STARTTAG; // ready to read tag name - - // if some text before < return it now - if (this.txtend > this.txtstart) - { - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - continue; // no text so keep going - } - - // otherwise treat as CDATA - this.state = LEX_CONTENT; - this.waswhite = false; - continue; - - case LEX_ENDTAG : - // ' - while (c != '>') - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - break; - } - } - - if (c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - continue; - } - - this.state = LEX_CONTENT; - this.waswhite = false; - return this.token; // the endtag token - - case LEX_STARTTAG : - // first letter of tagname - this.txtstart = this.lexsize - 1; // set txtstart to first letter - c = parseTagName(); - isempty[0] = false; - attributes = null; - this.token = newNode( - (isempty[0] ? Node.START_END_TAG : Node.START_TAG), - this.lexbuf, - this.txtstart, - this.txtend, - TidyUtils.getString(this.lexbuf, this.txtstart, this.txtend - this.txtstart)); - - // parse attributes, consuming closing ">" - if (c != '>') - { - if (c == '/') - { - this.in.ungetChar(c); - } - - attributes = parseAttrs(isempty); - } - - if (isempty[0]) - { - this.token.type = Node.START_END_TAG; - } - - this.token.attributes = attributes; - this.lexsize = this.txtstart; - this.txtend = this.txtstart; - - // swallow newline following start tag - // special check needed for CRLF sequence - // this doesn't apply to empty elements - // nor to preformatted content that needs escaping - - if ( - - (mode != PREFORMATTED || preContent(this.token)) - && (this.token.expectsContent() || this.token.tag == this.configuration.tt.tagBr)) - { - - c = this.in.readChar(); - - if (c == '\r') - { - c = this.in.readChar(); - - if (c != '\n') - { - this.in.ungetChar(c); - } - } - else if (c != '\n' && c != '\f') - { - this.in.ungetChar(c); - } - - this.waswhite = true; // to swallow leading whitespace - } - else - { - this.waswhite = false; - } - - this.state = LEX_CONTENT; - - if (this.token.tag == null) - { - report.error(this, null, this.token, Report.UNKNOWN_ELEMENT); - } - else if (!this.configuration.xmlTags) - { - constrainVersion(this.token.tag.versions); - - if (TidyUtils.toBoolean(this.token.tag.versions & Dict.VERS_PROPRIETARY)) - { - // #427810 - fix by Gary Deschaines 24 May 00 - if (this.configuration.makeClean && (this.token.tag != this.configuration.tt.tagNobr && // - this.token.tag != this.configuration.tt.tagWbr)) - { - report.warning(this, null, this.token, Report.PROPRIETARY_ELEMENT); - } - // #427810 - fix by Terry Teague 2 Jul 01 - else if (!this.configuration.makeClean) - { - report.warning(this, null, this.token, Report.PROPRIETARY_ELEMENT); - } - } - - if (this.token.tag.getChkattrs() != null) - { - this.token.tag.getChkattrs().check(this, this.token); - } - else - { - this.token.checkAttributes(this); - } - - // should this be called before attribute checks? - this.token.repairDuplicateAttributes(this); - - } - - return this.token; // return start tag - - case LEX_COMMENT : - // seen - - if (c != '-') - { - continue; - } - - c = this.in.readChar(); - addCharToLexer(c); - - if (c != '-') - { - continue; - } - - end_comment : while (true) - { - c = this.in.readChar(); - - if (c == '>') - { - if (badcomment != 0) - { - report.warning(this, null, null, Report.MALFORMED_COMMENT); - } - - this.txtend = this.lexsize - 2; // AQ 8Jul2000 - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.COMMENT_TAG, this.lexbuf, this.txtstart, this.txtend); - - // now look for a line break - - c = this.in.readChar(); - - if (c == '\r') - { - c = this.in.readChar(); - - if (c != '\n') - { - this.token.linebreak = true; - } - } - - if (c == '\n') - { - this.token.linebreak = true; - } - else - { - this.in.ungetChar(c); - } - - return this.token; - } - - // note position of first such error in the comment - if (badcomment == 0) - { - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol() - 3; - } - - badcomment++; - if (this.configuration.fixComments) - { - this.lexbuf[this.lexsize - 2] = (byte) '='; - } - - addCharToLexer(c); - - // if '-' then look for '>' to end the comment - if (c != '-') - { - break end_comment; - } - - } - // otherwise continue to look for --> - this.lexbuf[this.lexsize - 2] = (byte) '='; - continue; - - case LEX_DOCTYPE : - // seen ' munging whitespace - - if (TidyUtils.isWhite((char) c)) - { - if (this.waswhite) - { - this.lexsize -= 1; - } - - this.waswhite = true; - } - else - { - this.waswhite = false; - } - - if (inDTDSubset) - { - if (c == ']') - { - inDTDSubset = false; - } - } - else if (c == '[') - { - inDTDSubset = true; - } - if (inDTDSubset || c != '>') - { - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.DOCTYPE_TAG, this.lexbuf, this.txtstart, this.txtend); - // make a note of the version named by the doctype - this.doctype = findGivenVersion(this.token); - return this.token; - - case LEX_PROCINSTR : - // seen ' - // check for PHP preprocessor instructions - - if (this.lexsize - this.txtstart == 3) - { - if ((TidyUtils.getString(this.lexbuf, this.txtstart, 3)).equals("php")) - { - this.state = LEX_PHP; - continue; - } - } - - if (this.lexsize - this.txtstart == 4) - { - if ((TidyUtils.getString(this.lexbuf, this.txtstart, 3)).equals("xml") - && TidyUtils.isWhite((char) this.lexbuf[this.txtstart + 3])) - { - this.state = LEX_XMLDECL; - attributes = null; - continue; - } - } - - if (this.configuration.xmlPIs) // insist on ?> as terminator - { - if (c != '?') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - report.warning(this, null, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - continue; - } - - addCharToLexer(c); - } - - if (c != '>') - { - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.PROC_INS_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_ASP : - // seen <% so look for "%> " - if (c != '%') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.ASP_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_JSTE : - // seen <# so look for "#> " - if (c != '#') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.JSTE_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_PHP : - // seen " " - if (c != '?') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.PHP_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_XMLDECL : // seen "" - - if (TidyUtils.isWhite((char) c) && c != '?') - { - continue; - } - - // get pseudo-attribute - if (c != '?') - { - String name; - Node[] asp = new Node[1]; - Node[] php = new Node[1]; - AttVal av = new AttVal(); - int[] pdelim = new int[1]; - isempty[0] = false; - - this.in.ungetChar(c); - - name = this.parseAttribute(isempty, asp, php); - av.attribute = name; - - av.value = this.parseValue(name, true, isempty, pdelim); - av.delim = pdelim[0]; - av.next = attributes; - - attributes = av; - // continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - this.lexsize -= 1; - this.txtend = this.txtstart; - this.lexbuf[this.txtend] = '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.XML_DECL, this.lexbuf, this.txtstart, this.txtend); - this.token.attributes = attributes; - return this.token; - - case LEX_SECTION : - // seen " " - if (c == '[') - { - if (this.lexsize == (this.txtstart + 6) - && (TidyUtils.getString(this.lexbuf, this.txtstart, 6)).equals("CDATA[")) - { - this.state = LEX_CDATA; - this.lexsize -= 6; - continue; - } - } - - if (c != ']') - { - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.SECTION_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - case LEX_CDATA : - // seen " " - if (c != ']') - { - continue; - } - - // now look for ']' - c = this.in.readChar(); - - if (c != ']') - { - this.in.ungetChar(c); - continue; - } - - // now look for '>' - c = this.in.readChar(); - - if (c != '>') - { - this.in.ungetChar(c); - continue; - } - - this.lexsize -= 1; - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.CDATA_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - - default : - // should never reach here - break; - } - } - - if (this.state == LEX_CONTENT) // text string - { - this.txtend = this.lexsize; - - if (this.txtend > this.txtstart) - { - this.in.ungetChar(c); - - if (this.lexbuf[this.lexsize - 1] == (byte) ' ') - { - this.lexsize -= 1; - this.txtend = this.lexsize; - } - - this.token = newNode(Node.TEXT_NODE, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - } - else if (this.state == LEX_COMMENT) // comment - { - if (c == StreamIn.END_OF_STREAM) - { - report.warning(this, null, null, Report.MALFORMED_COMMENT); - } - - this.txtend = this.lexsize; - this.lexbuf[this.lexsize] = (byte) '\0'; - this.state = LEX_CONTENT; - this.waswhite = false; - this.token = newNode(Node.COMMENT_TAG, this.lexbuf, this.txtstart, this.txtend); - return this.token; - } - - return null; - } - - /** - * parser for ASP within start tags Some people use ASP for to customize attributes Tidy isn't really well suited to - * dealing with ASP This is a workaround for attributes, but won't deal with the case where the ASP is used to - * tailor the attribute value. Here is an example of a work around for using ASP in attribute values: - * href='<%=rsSchool.Fields("ID").Value%>' where the ASP that generates the attribute value is - * masked from Tidy by the quotemarks. - * @return parsed Node - */ - public Node parseAsp() - { - int c; - Node asp = null; - - this.txtstart = this.lexsize; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - - addCharToLexer(c); - - if (c != '%') - { - continue; - } - - if ((c = this.in.readChar()) == StreamIn.END_OF_STREAM) - { - break; - } - addCharToLexer(c); - - if (c == '>') - { - break; - } - } - - this.lexsize -= 2; - this.txtend = this.lexsize; - - if (this.txtend > this.txtstart) - { - asp = newNode(Node.ASP_TAG, this.lexbuf, this.txtstart, this.txtend); - } - - this.txtstart = this.txtend; - return asp; - } - - /** - * PHP is like ASP but is based upon XML processing instructions, e.g. <?php ... ?>. - * @return parsed Node - */ - public Node parsePhp() - { - int c; - Node php = null; - - this.txtstart = this.lexsize; - - while ((c = this.in.readChar()) != StreamIn.END_OF_STREAM) - { - addCharToLexer(c); - - if (c != '?') - { - continue; - } - - if ((c = this.in.readChar()) == StreamIn.END_OF_STREAM) - { - break; - } - addCharToLexer(c); - - if (c == '>') - { - break; - } - } - - this.lexsize -= 2; - this.txtend = this.lexsize; - - if (this.txtend > this.txtstart) - { - php = newNode(Node.PHP_TAG, this.lexbuf, this.txtstart, this.txtend); - } - - this.txtstart = this.txtend; - return php; - } - - /** - * consumes the '>' terminating start tags. - * @param isempty flag is passed as array so it can be modified - * @param asp asp Node, passed as array so it can be modified - * @param php php Node, passed as array so it can be modified - * @return parsed attribute - */ - public String parseAttribute(boolean[] isempty, Node[] asp, Node[] php) - { - int start = 0; - String attr; - int c = 0; - int lastc = 0; - - asp[0] = null; // clear asp pointer - php[0] = null; // clear php pointer - // skip white space before the attribute - - for (;;) - { - c = this.in.readChar(); - - if (c == '/') - { - c = this.in.readChar(); - - if (c == '>') - { - isempty[0] = true; - return null; - } - - this.in.ungetChar(c); - c = '/'; - break; - } - - if (c == '>') - { - return null; - } - - if (c == '<') - { - c = this.in.readChar(); - - if (c == '%') - { - asp[0] = parseAsp(); - return null; - } - else if (c == '?') - { - php[0] = parsePhp(); - return null; - } - - this.in.ungetChar(c); - if (this.state != LEX_XMLDECL) // FG fix for 532535 - { - this.in.ungetChar('<'); // fix for 433360 - } - report.attrError(this, this.token, null, Report.UNEXPECTED_GT); - return null; - } - - if (c == '=') - { - report.attrError(this, this.token, null, Report.UNEXPECTED_EQUALSIGN); - continue; - } - - if (c == '"' || c == '\'') - { - report.attrError(this, this.token, null, Report.UNEXPECTED_QUOTEMARK); - continue; - } - - if (c == StreamIn.END_OF_STREAM) - { - report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - return null; - } - - if (!TidyUtils.isWhite((char) c)) - { - break; - } - } - - start = this.lexsize; - lastc = c; - - for (;;) - { - // but push back '=' for parseValue() - if (c == '=' || c == '>') - { - this.in.ungetChar(c); - break; - } - - if (c == '<' || c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - break; - } - if (lastc == '-' && (c == '"' || c == '\'')) - { - this.lexsize--; - this.in.ungetChar(c); - break; - } - if (TidyUtils.isWhite((char) c)) - { - break; - } - - // what should be done about non-namechar characters? - // currently these are incorporated into the attr name - - if (!this.configuration.xmlTags && TidyUtils.isUpper((char) c)) - { - c = TidyUtils.toLower((char) c); - } - - // ++len; #427672 - handle attribute names with multibyte chars - fix by Randy Waki - 10 Aug 00 - addCharToLexer(c); - - lastc = c; - c = this.in.readChar(); - } - - // #427672 - handle attribute names with multibyte chars - fix by Randy Waki - 10 Aug 00 - int len = this.lexsize - start; - attr = (len > 0 ? TidyUtils.getString(this.lexbuf, start, len) : null); - this.lexsize = start; - - return attr; - } - - /** - * Invoked when < is seen in place of attribute value but terminates on whitespace if not ASP, PHP or Tango this - * routine recognizes ' and " quoted strings. - * @return delimiter - */ - public int parseServerInstruction() - { - int c, delim = '"'; - boolean isrule = false; - - c = this.in.readChar(); - addCharToLexer(c); - - // check for ASP, PHP or Tango - if (c == '%' || c == '?' || c == '@') - { - isrule = true; - } - - for (;;) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - break; - } - - if (c == '>') - { - if (isrule) - { - addCharToLexer(c); - } - else - { - this.in.ungetChar(c); - } - - break; - } - - // if not recognized as ASP, PHP or Tango - // then also finish value on whitespace - if (!isrule) - { - if (TidyUtils.isWhite((char) c)) - { - break; - } - } - - addCharToLexer(c); - - if (c == '"') - { - do - { - c = this.in.readChar(); - - if (endOfInput()) // #427840 - fix by Terry Teague 30 Jun 01 - { - report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - return 0; - } - if (c == '>') // #427840 - fix by Terry Teague 30 Jun 01 - { - this.in.ungetChar(c); - report.attrError(this, this.token, null, Report.UNEXPECTED_GT); - return 0; - } - - addCharToLexer(c); - } - while (c != '"'); - delim = '\''; - continue; - } - - if (c == '\'') - { - do - { - c = this.in.readChar(); - - if (endOfInput()) // #427840 - fix by Terry Teague 30 Jun 01 - { - report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - return 0; - } - if (c == '>') // #427840 - fix by Terry Teague 30 Jun 01 - { - this.in.ungetChar(c); - report.attrError(this, this.token, null, Report.UNEXPECTED_GT); - return 0; - } - - addCharToLexer(c); - } - while (c != '\''); - } - } - - return delim; - } - - /** - * Parse an attribute value. - * @param name attribute name - * @param foldCase fold case? - * @param isempty is attribute empty? Passed as an array reference to allow modification - * @param pdelim delimiter, passed as an array reference to allow modification - * @return parsed value - */ - public String parseValue(String name, boolean foldCase, boolean[] isempty, int[] pdelim) - { - // values start with "=" or " = " etc. - // doesn't consume the ">" at end of start tag - - int len = 0; - int start; - boolean seenGt = false; - boolean munge = true; - int c = 0; - int lastc, delim, quotewarning; - String value; - - delim = 0; - pdelim[0] = '"'; - - // Henry Zrepa reports that some folk are using the embed element with script attributes where newlines are - // significant and must be preserved - - if (this.configuration.literalAttribs) - { - munge = false; - } - - // skip white space before the '=' - while (true) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - break; - } - - if (!TidyUtils.isWhite((char) c)) - { - break; - } - } - - // c should be '=' if there is a value other legal possibilities are white space, '/' and '>' - - if (c != '=' && c != '"' && c != '\'') - { - this.in.ungetChar(c); - return null; - } - - // skip white space after '=' - - while (true) - { - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - this.in.ungetChar(c); - break; - } - - if (!TidyUtils.isWhite((char) c)) - { - break; - } - } - - // check for quote marks - - if (c == '"' || c == '\'') - { - delim = c; - } - else if (c == '<') - { - start = this.lexsize; - addCharToLexer(c); - pdelim[0] = parseServerInstruction(); - len = this.lexsize - start; - this.lexsize = start; - return (len > 0 ? TidyUtils.getString(this.lexbuf, start, len) : null); - } - else - { - this.in.ungetChar(c); - } - - // and read the value string check for quote mark if needed - - quotewarning = 0; - start = this.lexsize; - c = '\0'; - - while (true) - { - lastc = c; // track last character - c = this.in.readChar(); - - if (c == StreamIn.END_OF_STREAM) - { - report.attrError(this, this.token, null, Report.UNEXPECTED_END_OF_FILE); - this.in.ungetChar(c); - break; - } - - if (delim == (char) 0) - { - if (c == '>') - { - this.in.ungetChar(c); - break; - } - - if (c == '"' || c == '\'') - { - report.attrError(this, this.token, null, Report.UNEXPECTED_QUOTEMARK); - break; - } - - if (c == '<') - { - this.in.ungetChar(c); // fix for 433360 - c = '>'; - this.in.ungetChar(c); - report.attrError(this, this.token, null, Report.UNEXPECTED_GT); - break; - } - - // For cases like
need to avoid treating /> as part of the attribute value, however - // care is needed to avoid so treating
in this way, which would map the - // tag to - - if (c == '/') - { - // peek ahead in case of /> - c = this.in.readChar(); - - if (c == '>' && !AttributeTable.getDefaultAttributeTable().isUrl(name)) - { - isempty[0] = true; - this.in.ungetChar(c); - break; - } - - // unget peeked char - this.in.ungetChar(c); - c = '/'; - } - } - else - { - // delim is '\'' or '"' - if (c == delim) - { - break; - } - - // treat CRLF, CR and LF as single line break - - if (c == '\r') - { - c = this.in.readChar(); - if (c != '\n') - { - this.in.ungetChar(c); - } - - c = '\n'; - } - - if (c == '\n' || c == '<' || c == '>') - { - ++quotewarning; - } - - if (c == '>') - { - seenGt = true; - } - } - - if (c == '&') - { - // no entities in ID attributes - if ("id".equalsIgnoreCase(name)) - { - report.attrError(this, null, null, Report.ENTITY_IN_ID); - continue; - } - - addCharToLexer(c); - parseEntity((short) 0); - continue; - - } - - // kludge for JavaScript attribute values with line continuations in string literals - - if (c == '\\') - { - c = this.in.readChar(); - - if (c != '\n') - { - this.in.ungetChar(c); - c = '\\'; - } - } - - if (TidyUtils.isWhite((char) c)) - { - if (delim == (char) 0) - { - break; - } - - if (munge) - { - // discard line breaks in quoted URLs - // #438650 - fix by Randy Waki - if (c == '\n' && AttributeTable.getDefaultAttributeTable().isUrl(name)) - { - // warn that we discard this newline - report.attrError(this, this.token, null, Report.NEWLINE_IN_URI); - continue; - } - - c = ' '; - - if (lastc == ' ') - { - continue; - } - } - } - else if (foldCase && TidyUtils.isUpper((char) c)) - { - c = TidyUtils.toLower((char) c); - } - - addCharToLexer(c); - } - - if (quotewarning > 10 && seenGt && munge) - { - // there is almost certainly a missing trailing quote mark as we have see too many newlines, < or > - // characters. an exception is made for Javascript attributes and the javascript URL scheme which may - // legitimately include < and >, and for attributes starting with " 0 || delim != 0) - { - // ignore leading and trailing white space for all but title, alt, value and prompts attributes unless - // --literal-attributes is set to yes - // #994841 - Whitespace is removed from value attributes - - if (munge && !TidyUtils.isInValuesIgnoreCase(new String[]{"alt", "title", "value", "prompt"}, name)) - { - while (TidyUtils.isWhite((char) this.lexbuf[start + len - 1])) - { - --len; - } - - while (TidyUtils.isWhite((char) this.lexbuf[start]) && start < len) - { - ++start; - --len; - } - } - - value = TidyUtils.getString(this.lexbuf, start, len); - } - else - { - value = null; - } - - // note delimiter if given - if (delim != 0) - { - pdelim[0] = delim; - } - else - { - pdelim[0] = '"'; - } - - return value; - } - - /** - * Check if attr is a valid name. - * @param attr String to check, must be non-null - * @return true if attr is a valid name. - */ - public static boolean isValidAttrName(String attr) - { - char c; - int i; - - // first character should be a letter - c = attr.charAt(0); - - if (!TidyUtils.isLetter(c)) - { - return false; - } - - // remaining characters should be namechars - for (i = 1; i < attr.length(); i++) - { - c = attr.charAt(i); - - if (TidyUtils.isNamechar(c)) - { - continue; - } - - return false; - } - - return true; - } - - /** - * In CSS1, selectors can contain only the characters A-Z, 0-9, and Unicode characters 161-255, plus dash (-); they - * cannot start with a dash or a digit; they can also contain escaped characters and any Unicode character as a - * numeric code (see next item). The backslash followed by at most four hexadecimal digits (0..9A..F) stands for the - * Unicode character with that number. Any character except a hexadecimal digit can be escaped to remove its special - * meaning, by putting a backslash in front. - * @param buf css selector name - * @return true if the given string is a valid css1 selector name - */ - public static boolean isCSS1Selector(String buf) - { - if (buf == null) - { - return false; - } - - // #508936 - CSS class naming for -clean option - boolean valid = true; - int esclen = 0; - char c; - int pos; - - for (pos = 0; valid && pos < buf.length(); ++pos) - { - c = buf.charAt(pos); - if (c == '\\') - { - esclen = 1; // ab\555\444 is 4 chars {'a', 'b', \555, \444} - } - else if (Character.isDigit(c)) - { - // Digit not 1st, unless escaped (Max length "\112F") - if (esclen > 0) - { - valid = (++esclen < 6); - } - if (valid) - { - valid = (pos > 0 || esclen > 0); - } - } - else - { - valid = (esclen > 0 // Escaped? Anything goes. - || (pos > 0 && c == '-') // Dash cannot be 1st char - || Character.isLetter(c) // a-z, A-Z anywhere - || (c >= 161 && c <= 255)); // Unicode 161-255 anywhere - esclen = 0; - } - } - return valid; - } - - /** - * Parse tag attributes. - * @param isempty is tag empty? - * @return parsed attribute/value list - */ - public AttVal parseAttrs(boolean[] isempty) - { - AttVal av, list; - String attribute, value; - int[] delim = new int[1]; - Node[] asp = new Node[1]; - Node[] php = new Node[1]; - - list = null; - - while (!endOfInput()) - { - attribute = parseAttribute(isempty, asp, php); - - if (attribute == null) - { - // check if attributes are created by ASP markup - if (asp[0] != null) - { - av = new AttVal(list, null, asp[0], null, '\0', null, null); - list = av; - continue; - } - - // check if attributes are created by PHP markup - if (php[0] != null) - { - av = new AttVal(list, null, null, php[0], '\0', null, null); - list = av; - continue; - } - - break; - } - - value = parseValue(attribute, false, isempty, delim); - - if (attribute != null && isValidAttrName(attribute)) - { - av = new AttVal(list, null, null, null, delim[0], attribute, value); - av.dict = AttributeTable.getDefaultAttributeTable().findAttribute(av); - list = av; - } - else - { - av = new AttVal(null, null, null, null, 0, attribute, value); - - // #427664 - fix by Gary Peskin 04 Aug 00; other fixes by Dave Raggett - if (value != null) - { - report.attrError(this, this.token, av, Report.BAD_ATTRIBUTE_VALUE); - } - else if (TidyUtils.lastChar(attribute) == '"') - { - report.attrError(this, this.token, av, Report.MISSING_QUOTEMARK); - } - else - { - report.attrError(this, this.token, av, Report.UNKNOWN_ATTRIBUTE); - } - } - } - - return list; - } - - /** - * Push a copy of an inline node onto stack but don't push if implicit or OBJECT or APPLET (implicit tags are ones - * generated from the istack) One issue arises with pushing inlines when the tag is already pushed. For instance: - * <p><em> text <p><em> more text Shouldn't be mapped to - * <p><em> text </em></p><p><em><em> more text </em></em> - * @param node Node to be pushed - */ - public void pushInline(Node node) - { - IStack is; - - if (node.implicit) - { - return; - } - - if (node.tag == null) - { - return; - } - - if (!TidyUtils.toBoolean(node.tag.model & Dict.CM_INLINE)) - { - return; - } - - if (TidyUtils.toBoolean(node.tag.model & Dict.CM_OBJECT)) - { - return; - } - - if (node.tag != this.configuration.tt.tagFont && isPushed(node)) - { - return; - } - - // make sure there is enough space for the stack - is = new IStack(); - is.tag = node.tag; - is.element = node.element; - if (node.attributes != null) - { - is.attributes = cloneAttributes(node.attributes); - } - this.istack.push(is); - } - - /** - * Pop a copy of an inline node from the stack. - * @param node Node to be popped - */ - public void popInline(Node node) - { - IStack is; - - if (node != null) - { - - if (node.tag == null) - { - return; - } - - if (!TidyUtils.toBoolean(node.tag.model & Dict.CM_INLINE)) - { - return; - } - - if (TidyUtils.toBoolean(node.tag.model & Dict.CM_OBJECT)) - { - return; - } - - // if node is then pop until we find an - if (node.tag == this.configuration.tt.tagA) - { - - while (this.istack.size() > 0) - { - is = (IStack) this.istack.pop(); - if (is.tag == this.configuration.tt.tagA) - { - break; - } - } - - if (this.insert >= this.istack.size()) - { - this.insert = -1; - } - return; - } - } - - if (this.istack.size() > 0) - { - is = (IStack) this.istack.pop(); - if (this.insert >= this.istack.size()) - { - this.insert = -1; - } - } - } - - /** - * Is the node in the stack? - * @param node Node - * @return true is the node is found in the stack - */ - public boolean isPushed(Node node) - { - int i; - IStack is; - - for (i = this.istack.size() - 1; i >= 0; --i) - { - is = (IStack) this.istack.elementAt(i); - if (is.tag == node.tag) - { - return true; - } - } - - return false; - } - - /** - * This has the effect of inserting "missing" inline elements around the contents of blocklevel elements such as P, - * TD, TH, DIV, PRE etc. This procedure is called at the start of ParseBlock. When the inline stack is not empty, as - * will be the case in: <i><h1>italic heading</h1></i> which is then treated as - * equivalent to <h1><i>italic heading</i></h1> This is implemented by setting the lexer - * into a mode where it gets tokens from the inline stack rather than from the input stream. - * @param node original node - * @return stack size - */ - public int inlineDup(Node node) - { - int n; - - n = this.istack.size() - this.istackbase; - if (n > 0) - { - this.insert = this.istackbase; - this.inode = node; - } - - return n; - } - - /** - * @return - */ - public Node insertedToken() - { - Node node; - IStack is; - int n; - - // this will only be null if inode != null - if (this.insert == -1) - { - node = this.inode; - this.inode = null; - return node; - } - - // is this is the "latest" node then update the position, otherwise use current values - if (this.inode == null) - { - this.lines = this.in.getCurline(); - this.columns = this.in.getCurcol(); - } - - node = newNode(Node.START_TAG, this.lexbuf, this.txtstart, this.txtend); - - // GLP: Bugfix 126261. Remove when this change is fixed in istack.c in the original Tidy - node.implicit = true; - is = (IStack) this.istack.elementAt(this.insert); - node.element = is.element; - node.tag = is.tag; - if (is.attributes != null) - { - node.attributes = cloneAttributes(is.attributes); - } - - // advance lexer to next item on the stack - n = this.insert; - - // and recover state if we have reached the end - if (++n < this.istack.size()) - { - this.insert = n; - } - else - { - this.insert = -1; - } - - return node; - } - - /** - * Can the given element be removed? - * @param element node - * @return true if he element can be removed - */ - public boolean canPrune(Node element) - { - if (element.type == Node.TEXT_NODE) - { - return true; - } - - if (element.content != null) - { - return false; - } - - if (element.tag == this.configuration.tt.tagA && element.attributes != null) - { - return false; - } - - if (element.tag == this.configuration.tt.tagP && !this.configuration.dropEmptyParas) - { - return false; - } - - if (element.tag == null) - { - return false; - } - - if (TidyUtils.toBoolean(element.tag.model & Dict.CM_ROW)) - { - return false; - } - - if (TidyUtils.toBoolean(element.tag.model & Dict.CM_EMPTY)) - { - return false; - } - - if (element.tag == this.configuration.tt.tagApplet) - { - return false; - } - - if (element.tag == this.configuration.tt.tagObject) - { - return false; - } - - if (element.tag == this.configuration.tt.tagScript && element.getAttrByName("src") != null) - { - return false; - } - - // #540555 Empty title tag is trimmed - if (element.tag == this.configuration.tt.tagTitle) - { - return false; - } - - // #433359 - fix by Randy Waki 12 Mar 01 - Empty iframe is trimmed - if (element.tag == this.configuration.tt.tagIframe) - { - return false; - } - - if (element.getAttrByName("id") != null || element.getAttrByName("name") != null) - { - return false; - } - - return true; - } - - /** - * duplicate name attribute as an id and check if id and name match. - * @param node Node to check for name/it attributes - */ - public void fixId(Node node) - { - AttVal name = node.getAttrByName("name"); - AttVal id = node.getAttrByName("id"); - - if (name != null) - { - if (id != null) - { - if (id.value != null && !id.value.equals(name.value)) - { - report.attrError(this, node, name, Report.ID_NAME_MISMATCH); - } - } - else if (this.configuration.xmlOut) - { - node.addAttribute("id", name.value); - } - } - } - - /** - * Defer duplicates when entering a table or other element where the inlines shouldn't be duplicated. - */ - public void deferDup() - { - this.insert = -1; - this.inode = null; - } - - /** - * Constraint the html version in the document to the given one. Everything is allowed in proprietary version of - * HTML this is handled here rather than in the tag/attr dicts. - * @param vers html version code - */ - void constrainVersion(int vers) - { - this.versions &= (vers | Dict.VERS_PROPRIETARY); - } - - /** - * Is content acceptable for pre elements? - * @param node content - * @return true if node is acceptable in pre elements - */ - protected boolean preContent(Node node) - { - // p is coerced to br's - if (node.tag == this.configuration.tt.tagP) - { - return true; - } - - if (node.tag == null - || node.tag == this.configuration.tt.tagP - || !TidyUtils.toBoolean(node.tag.model & (Dict.CM_INLINE | Dict.CM_NEW))) - { - return false; - } - return true; - } - - /** - * document type. - */ - private static class W3CVersionInfo - { - - /** - * name. - */ - String name; - - /** - * voyager name. - */ - String voyagerName; - - /** - * profile. - */ - String profile; - - /** - * code. - */ - short code; - - /** - * Instantiates a new W3CVersionInfo. - * @param name version name - * @param voyagerName voyager (xhtml) name - * @param profile VOYAGER_STRICT | VOYAGER_LOOSE | VOYAGER_FRAMESET - * @param code unique code for this version info - */ - public W3CVersionInfo(String name, String voyagerName, String profile, short code) - { - this.name = name; - this.voyagerName = voyagerName; - this.profile = profile; - this.code = code; - } - } - -} \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#206/pair.info b/All/Genesis-OOB/Genesis#206/pair.info deleted file mode 100755 index 5d1dbc9..0000000 --- a/All/Genesis-OOB/Genesis#206/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:206 -SATName:Genesis -modifiedFPath:src/main/java/org/w3c/tidy/Lexer.java -comSha:f6bb30c -parentComSha:f6bb30c^1 -githubUrl:https://github.com/spullara/jtidy -repoName:spullara#jtidy \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#208/comMsg.txt b/All/Genesis-OOB/Genesis#208/comMsg.txt deleted file mode 100755 index 56bd562..0000000 --- a/All/Genesis-OOB/Genesis#208/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Updated Guice version and fixed a bounds bug in TemplateCompileException.tostring() diff --git a/All/Genesis-OOB/Genesis#208/diff.diff b/All/Genesis-OOB/Genesis#208/diff.diff deleted file mode 100755 index 1f58c05..0000000 --- a/All/Genesis-OOB/Genesis#208/diff.diff +++ /dev/null @@ -1,12 +0,0 @@ -diff --git a/sitebricks/src/main/java/com/google/sitebricks/compiler/TemplateCompileException.java b/sitebricks/src/main/java/com/google/sitebricks/compiler/TemplateCompileException.java -index b4d79dc..92f6a26 100644 ---- a/sitebricks/src/main/java/com/google/sitebricks/compiler/TemplateCompileException.java -+++ b/sitebricks/src/main/java/com/google/sitebricks/compiler/TemplateCompileException.java -@@ -7 +6,0 @@ import java.io.StringReader; --import java.util.List; -@@ -8,0 +8 @@ import java.util.Arrays; -+import java.util.List; -@@ -85,0 +86,3 @@ public final class TemplateCompileException extends RuntimeException { -+ if (lineNumber > templateLines.size() - 1) { -+ continue; -+ } diff --git a/All/Genesis-OOB/Genesis#208/new/TemplateCompileException.java b/All/Genesis-OOB/Genesis#208/new/TemplateCompileException.java deleted file mode 100755 index 92f6a26..0000000 --- a/All/Genesis-OOB/Genesis#208/new/TemplateCompileException.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.google.sitebricks.compiler; - -import org.apache.commons.io.IOUtils; - -import java.io.IOException; -import java.io.StringReader; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @author Dhanji R. Prasanna (dhanji@gmail.com) - */ -public final class TemplateCompileException extends RuntimeException { - private final List errors; - private final List templateLines; - private final String template; - private final Class page; - private final List warnings; - - public TemplateCompileException(Class page, String template, - List errors, List warnings) { - - this.page = page; - this.warnings = warnings; - try { - //noinspection unchecked - this.templateLines = IOUtils.readLines(new StringReader(template)); - } catch (IOException e) { - throw new IllegalStateException("Fatal error, could not read template after compile", e); - } - this.template = template; - - this.errors = errors; - } - - - @Override - public String getMessage() { - if (null == errors) - return super.getMessage(); - - StringBuilder builder = new StringBuilder("Compilation errors in template for "); - builder.append(page.getName()); - builder.append("\n\n"); - - AtomicInteger i = new AtomicInteger(0); - - if (!errors.isEmpty()) { - toString(builder, i, errors); - builder.append("\nTotal errors: "); - builder.append(errors.size()); - builder.append("\n\n"); - } - - if (!warnings.isEmpty()) { - toString(builder, i, warnings); - builder.append("\nTotal warnings: "); - builder.append(warnings.size()); - builder.append("\n\n"); - } - - return builder.toString(); - } - - private void toString(StringBuilder builder, AtomicInteger i, List errors) { - for (CompileError error : errors) { - EvaluatorCompiler.CompileErrorDetail cause = error.getCause(); - - builder.append(i.incrementAndGet()); - builder.append(") "); - - if (cause == null) { - builder.append("Unknown cause"); - builder.append("\n\n"); - } - else { - builder.append(cause.getError().getMessage()); - builder.append("\n\n"); - } - - // Context (source code) of the error. - int lineNumber = error.getLine(); - builder.append(lineNumber - 1); - builder.append(": "); - if (lineNumber > templateLines.size() - 1) { - continue; - } - builder.append(templateLines.get(lineNumber - 1)); - builder.append('\n'); - builder.append(lineNumber); - builder.append(": "); - builder.append(templateLines.get(lineNumber)); - builder.append('\n'); - - // Actual error line... - int contextLineNumber = lineNumber + 1; - builder.append(contextLineNumber); - builder.append(": "); - String fragment = templateLines.get(contextLineNumber); - builder.append(fragment); - builder.append('\n'); - - // Compute offset (line number width + expression offset). - int columnPad = Integer.toString(contextLineNumber).length() + 4; - int offset; - if (cause != null) - offset = fragment.indexOf(cause.getExpression()) + columnPad; - else - offset = 0; - - // Code pointer (caret). - // TODO fix this. It should appear directly beneath the line in question. - char[] spaces = new char[offset]; - Arrays.fill(spaces, ' '); - builder.append(spaces); - builder.append("^"); - - builder.append('\n'); - } - } - - public List getErrors() { - return errors; - } - - public List getWarnings() { - return warnings; - } -} diff --git a/All/Genesis-OOB/Genesis#208/new/acceptance-test.iml b/All/Genesis-OOB/Genesis#208/new/acceptance-test.iml deleted file mode 100755 index d35cf90..0000000 --- a/All/Genesis-OOB/Genesis#208/new/acceptance-test.iml +++ /dev/null @@ -1,481 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/All/Genesis-OOB/Genesis#208/old/TemplateCompileException.java b/All/Genesis-OOB/Genesis#208/old/TemplateCompileException.java deleted file mode 100755 index b4d79dc..0000000 --- a/All/Genesis-OOB/Genesis#208/old/TemplateCompileException.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.google.sitebricks.compiler; - -import org.apache.commons.io.IOUtils; - -import java.io.IOException; -import java.io.StringReader; -import java.util.List; -import java.util.Arrays; -import java.util.concurrent.atomic.AtomicInteger; - -/** - * @author Dhanji R. Prasanna (dhanji@gmail.com) - */ -public final class TemplateCompileException extends RuntimeException { - private final List errors; - private final List templateLines; - private final String template; - private final Class page; - private final List warnings; - - public TemplateCompileException(Class page, String template, - List errors, List warnings) { - - this.page = page; - this.warnings = warnings; - try { - //noinspection unchecked - this.templateLines = IOUtils.readLines(new StringReader(template)); - } catch (IOException e) { - throw new IllegalStateException("Fatal error, could not read template after compile", e); - } - this.template = template; - - this.errors = errors; - } - - - @Override - public String getMessage() { - if (null == errors) - return super.getMessage(); - - StringBuilder builder = new StringBuilder("Compilation errors in template for "); - builder.append(page.getName()); - builder.append("\n\n"); - - AtomicInteger i = new AtomicInteger(0); - - if (!errors.isEmpty()) { - toString(builder, i, errors); - builder.append("\nTotal errors: "); - builder.append(errors.size()); - builder.append("\n\n"); - } - - if (!warnings.isEmpty()) { - toString(builder, i, warnings); - builder.append("\nTotal warnings: "); - builder.append(warnings.size()); - builder.append("\n\n"); - } - - return builder.toString(); - } - - private void toString(StringBuilder builder, AtomicInteger i, List errors) { - for (CompileError error : errors) { - EvaluatorCompiler.CompileErrorDetail cause = error.getCause(); - - builder.append(i.incrementAndGet()); - builder.append(") "); - - if (cause == null) { - builder.append("Unknown cause"); - builder.append("\n\n"); - } - else { - builder.append(cause.getError().getMessage()); - builder.append("\n\n"); - } - - // Context (source code) of the error. - int lineNumber = error.getLine(); - builder.append(lineNumber - 1); - builder.append(": "); - builder.append(templateLines.get(lineNumber - 1)); - builder.append('\n'); - builder.append(lineNumber); - builder.append(": "); - builder.append(templateLines.get(lineNumber)); - builder.append('\n'); - - // Actual error line... - int contextLineNumber = lineNumber + 1; - builder.append(contextLineNumber); - builder.append(": "); - String fragment = templateLines.get(contextLineNumber); - builder.append(fragment); - builder.append('\n'); - - // Compute offset (line number width + expression offset). - int columnPad = Integer.toString(contextLineNumber).length() + 4; - int offset; - if (cause != null) - offset = fragment.indexOf(cause.getExpression()) + columnPad; - else - offset = 0; - - // Code pointer (caret). - // TODO fix this. It should appear directly beneath the line in question. - char[] spaces = new char[offset]; - Arrays.fill(spaces, ' '); - builder.append(spaces); - builder.append("^"); - - builder.append('\n'); - } - } - - public List getErrors() { - return errors; - } - - public List getWarnings() { - return warnings; - } -} diff --git a/All/Genesis-OOB/Genesis#208/old/acceptance-test.iml b/All/Genesis-OOB/Genesis#208/old/acceptance-test.iml deleted file mode 100755 index 29bb35a..0000000 --- a/All/Genesis-OOB/Genesis#208/old/acceptance-test.iml +++ /dev/null @@ -1,482 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/All/Genesis-OOB/Genesis#208/pair.info b/All/Genesis-OOB/Genesis#208/pair.info deleted file mode 100755 index 4857fbc..0000000 --- a/All/Genesis-OOB/Genesis#208/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:208 -SATName:Genesis -modifiedFPath:sitebricks/src/main/java/com/google/sitebricks/compiler/TemplateCompileException.java -comSha:2605a7a -parentComSha:2605a7a^1 -githubUrl:https://github.com/bakotaco/sitebricks -repoName:bakotaco#sitebricks \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#24/comMsg.txt b/All/Genesis-OOB/Genesis#24/comMsg.txt deleted file mode 100755 index fb2d546..0000000 --- a/All/Genesis-OOB/Genesis#24/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -fixed an issue (ArrayOutOfBoundException) with long log lines diff --git a/All/Genesis-OOB/Genesis#24/diff.diff b/All/Genesis-OOB/Genesis#24/diff.diff deleted file mode 100755 index 07c0ea7..0000000 --- a/All/Genesis-OOB/Genesis#24/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/src/main/java/org/jolokia/docker/maven/access/log/LogRequestor.java b/src/main/java/org/jolokia/docker/maven/access/log/LogRequestor.java -index ad865d4..7aecd26 100644 ---- a/src/main/java/org/jolokia/docker/maven/access/log/LogRequestor.java -+++ b/src/main/java/org/jolokia/docker/maven/access/log/LogRequestor.java -@@ -31,0 +32 @@ import org.jolokia.docker.maven.util.Timestamp; -+import static java.lang.Math.min; -@@ -106 +106,0 @@ public class LogRequestor extends Thread implements LogGetHandle { -- byte[] buf = new byte[8129]; -@@ -109,0 +110 @@ public class LogRequestor extends Thread implements LogGetHandle { -+ byte[] buf = new byte[declaredLength]; diff --git a/All/Genesis-OOB/Genesis#24/new/LogRequestor.java b/All/Genesis-OOB/Genesis#24/new/LogRequestor.java deleted file mode 100755 index 7aecd26..0000000 --- a/All/Genesis-OOB/Genesis#24/new/LogRequestor.java +++ /dev/null @@ -1,173 +0,0 @@ -package org.jolokia.docker.maven.access.log;/* - * - * Copyright 2014 Roland Huss - * - * 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. - */ - -import java.io.IOException; -import java.io.InputStream; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpUriRequest; -import org.jolokia.docker.maven.access.DockerAccessException; -import org.jolokia.docker.maven.access.UrlBuilder; -import org.jolokia.docker.maven.util.Timestamp; - -import static java.lang.Math.min; -import static org.jolokia.docker.maven.access.util.RequestUtil.newGet; - -/** - * Extractor for parsing the response of a log request - * - * @author roland - * @since 28/11/14 - */ -public class LogRequestor extends Thread implements LogGetHandle { - - // Patter for matching log entries - private static final Pattern LOG_LINE = Pattern.compile("^\\[?([^\\s\\]]*)]?\\s+(.*)\\s*$"); - private final HttpClient client; - - private final String containerId; - - // callback called for each line extracted - private LogCallback callback; - - private DockerAccessException exception; - - // Remember for asynchronous handling - private HttpUriRequest request; - - private final UrlBuilder urlBuilder; - - /** - * Create a helper object for requesting log entries synchronously ({@link #fetchLogs()}) or asynchronously ({@link #start()}. - * - * @param client HTTP client to use for requesting the docker host - * @param urlBuilder builder that creates docker urls - * @param containerId container for which to fetch the host - * @param callback callback to call for each line received - */ - public LogRequestor(HttpClient client, UrlBuilder urlBuilder, String containerId, LogCallback callback) { - this.client = client; - this.containerId = containerId; - - this.urlBuilder = urlBuilder; - - - this.callback = callback; - this.exception = null; - this.setDaemon(true); - } - - /** - * Get logs and feed a callback with the content - */ - public void fetchLogs() { - try { - HttpResponse resp = client.execute(getLogRequest(false)); - parseResponse(resp); - } catch (IOException exp) { - callback.error(exp.getMessage()); - } - } - - // Fetch log asynchronously as stream and follow stream - public void run() { - // Response to extract from - - try { - request = getLogRequest(true); - HttpResponse response = client.execute(request); - parseResponse(response); - } catch (IOException exp) { - callback.error("IO Error while requesting logs: " + exp); - } - } - - private void parseResponse(HttpResponse response) { - try (InputStream is = response.getEntity().getContent()) { - byte[] headBuf = new byte[8]; - while (IOUtils.read(is, headBuf, 0, 8) > 0) { - int type = headBuf[0]; - int declaredLength = extractLength(headBuf); - byte[] buf = new byte[declaredLength]; - int len = IOUtils.read(is, buf, 0, declaredLength); - if (len < 1) { - callback.error("Invalid log format: Couldn't read " + declaredLength + " bytes from stream"); - finish(); - return; - } - String txt = new String(buf, 0, len, "UTF-8"); - - callLogCallback(type, txt); - } - StatusLine status = response.getStatusLine(); - if (status.getStatusCode() != 200) { - exception = new DockerAccessException("Error while reading logs (" + status + ")"); - } - } catch (IOException e) { - callback.error("Cannot process chunk response: " + e); - finish(); - } catch (LogCallback.DoneException e) { - // Can be thrown by a log callback which indicates that we are done. - finish(); - } - } - - private void callLogCallback(int type, String txt) throws LogCallback.DoneException { - Matcher matcher = LOG_LINE.matcher(txt); - if (!matcher.matches()) { - callback.error("Invalid log format for '" + txt + "' (expected: \" \")"); - throw new LogCallback.DoneException(); - } - Timestamp ts = new Timestamp(matcher.group(1)); - String logTxt = matcher.group(2); - callback.log(type, ts, logTxt); - } - - private int extractLength(byte[] b) { - return b[7] & 0xFF | - (b[6] & 0xFF) << 8 | - (b[5] & 0xFF) << 16 | - (b[4] & 0xFF) << 24; - } - - - private HttpUriRequest getLogRequest(boolean follow) { - return newGet(urlBuilder.containerLogs(containerId, follow)); - } - - @Override - public void finish() { - if (request != null) { - request.abort(); - } - } - - @Override - public boolean isError() { - return exception != null; - } - - @Override - public DockerAccessException getException() { - return exception; - } -} diff --git a/All/Genesis-OOB/Genesis#24/old/LogRequestor.java b/All/Genesis-OOB/Genesis#24/old/LogRequestor.java deleted file mode 100755 index ad865d4..0000000 --- a/All/Genesis-OOB/Genesis#24/old/LogRequestor.java +++ /dev/null @@ -1,172 +0,0 @@ -package org.jolokia.docker.maven.access.log;/* - * - * Copyright 2014 Roland Huss - * - * 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. - */ - -import java.io.IOException; -import java.io.InputStream; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.io.IOUtils; -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.client.HttpClient; -import org.apache.http.client.methods.HttpUriRequest; -import org.jolokia.docker.maven.access.DockerAccessException; -import org.jolokia.docker.maven.access.UrlBuilder; -import org.jolokia.docker.maven.util.Timestamp; - -import static org.jolokia.docker.maven.access.util.RequestUtil.newGet; - -/** - * Extractor for parsing the response of a log request - * - * @author roland - * @since 28/11/14 - */ -public class LogRequestor extends Thread implements LogGetHandle { - - // Patter for matching log entries - private static final Pattern LOG_LINE = Pattern.compile("^\\[?([^\\s\\]]*)]?\\s+(.*)\\s*$"); - private final HttpClient client; - - private final String containerId; - - // callback called for each line extracted - private LogCallback callback; - - private DockerAccessException exception; - - // Remember for asynchronous handling - private HttpUriRequest request; - - private final UrlBuilder urlBuilder; - - /** - * Create a helper object for requesting log entries synchronously ({@link #fetchLogs()}) or asynchronously ({@link #start()}. - * - * @param client HTTP client to use for requesting the docker host - * @param urlBuilder builder that creates docker urls - * @param containerId container for which to fetch the host - * @param callback callback to call for each line received - */ - public LogRequestor(HttpClient client, UrlBuilder urlBuilder, String containerId, LogCallback callback) { - this.client = client; - this.containerId = containerId; - - this.urlBuilder = urlBuilder; - - - this.callback = callback; - this.exception = null; - this.setDaemon(true); - } - - /** - * Get logs and feed a callback with the content - */ - public void fetchLogs() { - try { - HttpResponse resp = client.execute(getLogRequest(false)); - parseResponse(resp); - } catch (IOException exp) { - callback.error(exp.getMessage()); - } - } - - // Fetch log asynchronously as stream and follow stream - public void run() { - // Response to extract from - - try { - request = getLogRequest(true); - HttpResponse response = client.execute(request); - parseResponse(response); - } catch (IOException exp) { - callback.error("IO Error while requesting logs: " + exp); - } - } - - private void parseResponse(HttpResponse response) { - try (InputStream is = response.getEntity().getContent()) { - byte[] headBuf = new byte[8]; - byte[] buf = new byte[8129]; - while (IOUtils.read(is, headBuf, 0, 8) > 0) { - int type = headBuf[0]; - int declaredLength = extractLength(headBuf); - int len = IOUtils.read(is, buf, 0, declaredLength); - if (len < 1) { - callback.error("Invalid log format: Couldn't read " + declaredLength + " bytes from stream"); - finish(); - return; - } - String txt = new String(buf, 0, len, "UTF-8"); - - callLogCallback(type, txt); - } - StatusLine status = response.getStatusLine(); - if (status.getStatusCode() != 200) { - exception = new DockerAccessException("Error while reading logs (" + status + ")"); - } - } catch (IOException e) { - callback.error("Cannot process chunk response: " + e); - finish(); - } catch (LogCallback.DoneException e) { - // Can be thrown by a log callback which indicates that we are done. - finish(); - } - } - - private void callLogCallback(int type, String txt) throws LogCallback.DoneException { - Matcher matcher = LOG_LINE.matcher(txt); - if (!matcher.matches()) { - callback.error("Invalid log format for '" + txt + "' (expected: \" \")"); - throw new LogCallback.DoneException(); - } - Timestamp ts = new Timestamp(matcher.group(1)); - String logTxt = matcher.group(2); - callback.log(type, ts, logTxt); - } - - private int extractLength(byte[] b) { - return b[7] & 0xFF | - (b[6] & 0xFF) << 8 | - (b[5] & 0xFF) << 16 | - (b[4] & 0xFF) << 24; - } - - - private HttpUriRequest getLogRequest(boolean follow) { - return newGet(urlBuilder.containerLogs(containerId, follow)); - } - - @Override - public void finish() { - if (request != null) { - request.abort(); - } - } - - @Override - public boolean isError() { - return exception != null; - } - - @Override - public DockerAccessException getException() { - return exception; - } -} diff --git a/All/Genesis-OOB/Genesis#24/pair.info b/All/Genesis-OOB/Genesis#24/pair.info deleted file mode 100755 index 0b23610..0000000 --- a/All/Genesis-OOB/Genesis#24/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:24 -SATName:Genesis -modifiedFPath:src/main/java/org/jolokia/docker/maven/access/log/LogRequestor.java -comSha:944f2d98d913bf639fff3ad9773342a39ce904f8 -parentComSha:944f2d98d913bf639fff3ad9773342a39ce904f8^1 -githubUrl:https://github.com/rhuss/docker-maven-plugin -repoName:rhuss#docker-maven-plugin \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#33/comMsg.txt b/All/Genesis-OOB/Genesis#33/comMsg.txt deleted file mode 100755 index bcc5fef..0000000 --- a/All/Genesis-OOB/Genesis#33/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -LANG-1162 StringUtils#equals fails with Index OOBE on non-Strings with identical leading prefix diff --git a/All/Genesis-OOB/Genesis#33/diff.diff b/All/Genesis-OOB/Genesis#33/diff.diff deleted file mode 100755 index a32174a..0000000 --- a/All/Genesis-OOB/Genesis#33/diff.diff +++ /dev/null @@ -1,11 +0,0 @@ -diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java -index 5f167b9..3f0314f 100644 ---- a/src/main/java/org/apache/commons/lang3/StringUtils.java -+++ b/src/main/java/org/apache/commons/lang3/StringUtils.java -@@ -790,0 +791,3 @@ public static boolean equals(final CharSequence cs1, final CharSequence cs2) { -+ if (cs1.length() != cs2.length()) { -+ return false; -+ } -@@ -794 +797 @@ public static boolean equals(final CharSequence cs1, final CharSequence cs2) { -- return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length())); -+ return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length()); diff --git a/All/Genesis-OOB/Genesis#33/new/StringUtils.java b/All/Genesis-OOB/Genesis#33/new/StringUtils.java deleted file mode 100755 index 3f0314f..0000000 --- a/All/Genesis-OOB/Genesis#33/new/StringUtils.java +++ /dev/null @@ -1,7976 +0,0 @@ -/* - * 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.commons.lang3; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.regex.Pattern; - -/** - *

Operations on {@link java.lang.String} that are - * {@code null} safe.

- * - *
    - *
  • IsEmpty/IsBlank - * - checks if a String contains text
  • - *
  • Trim/Strip - * - removes leading and trailing whitespace
  • - *
  • Equals - * - compares two strings null-safe
  • - *
  • startsWith - * - check if a String starts with a prefix null-safe
  • - *
  • endsWith - * - check if a String ends with a suffix null-safe
  • - *
  • IndexOf/LastIndexOf/Contains - * - null-safe index-of checks - *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - * - index-of any of a set of Strings
  • - *
  • ContainsOnly/ContainsNone/ContainsAny - * - does String contains only/none/any of these characters
  • - *
  • Substring/Left/Right/Mid - * - null-safe substring extractions
  • - *
  • SubstringBefore/SubstringAfter/SubstringBetween - * - substring extraction relative to other strings
  • - *
  • Split/Join - * - splits a String into an array of substrings and vice versa
  • - *
  • Remove/Delete - * - removes part of a String
  • - *
  • Replace/Overlay - * - Searches a String and replaces one String with another
  • - *
  • Chomp/Chop - * - removes the last part of a String
  • - *
  • AppendIfMissing - * - appends a suffix to the end of the String if not present
  • - *
  • PrependIfMissing - * - prepends a prefix to the start of the String if not present
  • - *
  • LeftPad/RightPad/Center/Repeat - * - pads a String
  • - *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - * - changes the case of a String
  • - *
  • CountMatches - * - counts the number of occurrences of one String in another
  • - *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - * - checks the characters in a String
  • - *
  • DefaultString - * - protects against a null input String
  • - *
  • Rotate - * - rotate (circular shift) a String
  • - *
  • Reverse/ReverseDelimited - * - reverses a String
  • - *
  • Abbreviate - * - abbreviates a string using ellipsis
  • - *
  • Difference - * - compares Strings and reports on their differences
  • - *
  • LevenshteinDistance - * - the number of changes needed to change one String into another
  • - *
- * - *

The {@code StringUtils} class defines certain words related to - * String handling.

- * - *
    - *
  • null - {@code null}
  • - *
  • empty - a zero-length string ({@code ""})
  • - *
  • space - the space character ({@code ' '}, char 32)
  • - *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • - *
  • trim - the characters <= 32 as in {@link String#trim()}
  • - *
- * - *

{@code StringUtils} handles {@code null} input Strings quietly. - * That is to say that a {@code null} input will return {@code null}. - * Where a {@code boolean} or {@code int} is being returned - * details vary by method.

- * - *

A side effect of the {@code null} handling is that a - * {@code NullPointerException} should be considered a bug in - * {@code StringUtils}.

- * - *

Methods in this class give sample code to explain their operation. - * The symbol {@code *} is used to indicate any input including {@code null}.

- * - *

#ThreadSafe#

- * @see java.lang.String - * @since 1.0 - */ -//@Immutable -public class StringUtils { - // Performance testing notes (JDK 1.4, Jul03, scolebourne) - // Whitespace: - // Character.isWhitespace() is faster than WHITESPACE.indexOf() - // where WHITESPACE is a string of all whitespace characters - // - // Character access: - // String.charAt(n) versus toCharArray(), then array[n] - // String.charAt(n) is about 15% worse for a 10K string - // They are about equal for a length 50 string - // String.charAt(n) is about 4 times better for a length 3 string - // String.charAt(n) is best bet overall - // - // Append: - // String.concat about twice as fast as StringBuffer.append - // (not sure who tested this) - - /** - * A String for a space character. - * - * @since 3.2 - */ - public static final String SPACE = " "; - - /** - * The empty String {@code ""}. - * @since 2.0 - */ - public static final String EMPTY = ""; - - /** - * A String for linefeed LF ("\n"). - * - * @see
JLF: Escape Sequences - * for Character and String Literals - * @since 3.2 - */ - public static final String LF = "\n"; - - /** - * A String for carriage return CR ("\r"). - * - * @see JLF: Escape Sequences - * for Character and String Literals - * @since 3.2 - */ - public static final String CR = "\r"; - - /** - * Represents a failed index search. - * @since 2.1 - */ - public static final int INDEX_NOT_FOUND = -1; - - /** - *

The maximum size to which the padding constant(s) can expand.

- */ - private static final int PAD_LIMIT = 8192; - - /** - *

{@code StringUtils} instances should NOT be constructed in - * standard programming. Instead, the class should be used as - * {@code StringUtils.trim(" foo ");}.

- * - *

This constructor is public to permit tools that require a JavaBean - * instance to operate.

- */ - public StringUtils() { - super(); - } - - // Empty checks - //----------------------------------------------------------------------- - /** - *

Checks if a CharSequence is empty ("") or null.

- * - *
-     * StringUtils.isEmpty(null)      = true
-     * StringUtils.isEmpty("")        = true
-     * StringUtils.isEmpty(" ")       = false
-     * StringUtils.isEmpty("bob")     = false
-     * StringUtils.isEmpty("  bob  ") = false
-     * 
- * - *

NOTE: This method changed in Lang version 2.0. - * It no longer trims the CharSequence. - * That functionality is available in isBlank().

- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if the CharSequence is empty or null - * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) - */ - public static boolean isEmpty(final CharSequence cs) { - return cs == null || cs.length() == 0; - } - - /** - *

Checks if a CharSequence is not empty ("") and not null.

- * - *
-     * StringUtils.isNotEmpty(null)      = false
-     * StringUtils.isNotEmpty("")        = false
-     * StringUtils.isNotEmpty(" ")       = true
-     * StringUtils.isNotEmpty("bob")     = true
-     * StringUtils.isNotEmpty("  bob  ") = true
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if the CharSequence is not empty and not null - * @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence) - */ - public static boolean isNotEmpty(final CharSequence cs) { - return !isEmpty(cs); - } - - /** - *

Checks if any one of the CharSequences are empty ("") or null.

- * - *
-     * StringUtils.isAnyEmpty(null)             = true
-     * StringUtils.isAnyEmpty(null, "foo")      = true
-     * StringUtils.isAnyEmpty("", "bar")        = true
-     * StringUtils.isAnyEmpty("bob", "")        = true
-     * StringUtils.isAnyEmpty("  bob  ", null)  = true
-     * StringUtils.isAnyEmpty(" ", "bar")       = false
-     * StringUtils.isAnyEmpty("foo", "bar")     = false
-     * 
- * - * @param css the CharSequences to check, may be null or empty - * @return {@code true} if any of the CharSequences are empty or null - * @since 3.2 - */ - public static boolean isAnyEmpty(final CharSequence... css) { - if (ArrayUtils.isEmpty(css)) { - return true; - } - for (final CharSequence cs : css){ - if (isEmpty(cs)) { - return true; - } - } - return false; - } - - /** - *

Checks if none of the CharSequences are empty ("") or null.

- * - *
-     * StringUtils.isNoneEmpty(null)             = false
-     * StringUtils.isNoneEmpty(null, "foo")      = false
-     * StringUtils.isNoneEmpty("", "bar")        = false
-     * StringUtils.isNoneEmpty("bob", "")        = false
-     * StringUtils.isNoneEmpty("  bob  ", null)  = false
-     * StringUtils.isNoneEmpty(" ", "bar")       = true
-     * StringUtils.isNoneEmpty("foo", "bar")     = true
-     * 
- * - * @param css the CharSequences to check, may be null or empty - * @return {@code true} if none of the CharSequences are empty or null - * @since 3.2 - */ - public static boolean isNoneEmpty(final CharSequence... css) { - return !isAnyEmpty(css); - } - /** - *

Checks if a CharSequence is whitespace, empty ("") or null.

- * - *
-     * StringUtils.isBlank(null)      = true
-     * StringUtils.isBlank("")        = true
-     * StringUtils.isBlank(" ")       = true
-     * StringUtils.isBlank("bob")     = false
-     * StringUtils.isBlank("  bob  ") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if the CharSequence is null, empty or whitespace - * @since 2.0 - * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence) - */ - public static boolean isBlank(final CharSequence cs) { - int strLen; - if (cs == null || (strLen = cs.length()) == 0) { - return true; - } - for (int i = 0; i < strLen; i++) { - if (Character.isWhitespace(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if a CharSequence is not empty (""), not null and not whitespace only.

- * - *
-     * StringUtils.isNotBlank(null)      = false
-     * StringUtils.isNotBlank("")        = false
-     * StringUtils.isNotBlank(" ")       = false
-     * StringUtils.isNotBlank("bob")     = true
-     * StringUtils.isNotBlank("  bob  ") = true
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if the CharSequence is - * not empty and not null and not whitespace - * @since 2.0 - * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) - */ - public static boolean isNotBlank(final CharSequence cs) { - return !isBlank(cs); - } - - /** - *

Checks if any one of the CharSequences are blank ("") or null and not whitespace only..

- * - *
-     * StringUtils.isAnyBlank(null)             = true
-     * StringUtils.isAnyBlank(null, "foo")      = true
-     * StringUtils.isAnyBlank(null, null)       = true
-     * StringUtils.isAnyBlank("", "bar")        = true
-     * StringUtils.isAnyBlank("bob", "")        = true
-     * StringUtils.isAnyBlank("  bob  ", null)  = true
-     * StringUtils.isAnyBlank(" ", "bar")       = true
-     * StringUtils.isAnyBlank("foo", "bar")     = false
-     * 
- * - * @param css the CharSequences to check, may be null or empty - * @return {@code true} if any of the CharSequences are blank or null or whitespace only - * @since 3.2 - */ - public static boolean isAnyBlank(final CharSequence... css) { - if (ArrayUtils.isEmpty(css)) { - return true; - } - for (final CharSequence cs : css){ - if (isBlank(cs)) { - return true; - } - } - return false; - } - - /** - *

Checks if none of the CharSequences are blank ("") or null and whitespace only..

- * - *
-     * StringUtils.isNoneBlank(null)             = false
-     * StringUtils.isNoneBlank(null, "foo")      = false
-     * StringUtils.isNoneBlank(null, null)       = false
-     * StringUtils.isNoneBlank("", "bar")        = false
-     * StringUtils.isNoneBlank("bob", "")        = false
-     * StringUtils.isNoneBlank("  bob  ", null)  = false
-     * StringUtils.isNoneBlank(" ", "bar")       = false
-     * StringUtils.isNoneBlank("foo", "bar")     = true
-     * 
- * - * @param css the CharSequences to check, may be null or empty - * @return {@code true} if none of the CharSequences are blank or null or whitespace only - * @since 3.2 - */ - public static boolean isNoneBlank(final CharSequence... css) { - return !isAnyBlank(css); - } - - // Trim - //----------------------------------------------------------------------- - /** - *

Removes control characters (char <= 32) from both - * ends of this String, handling {@code null} by returning - * {@code null}.

- * - *

The String is trimmed using {@link String#trim()}. - * Trim removes start and end characters <= 32. - * To strip whitespace use {@link #strip(String)}.

- * - *

To trim your choice of characters, use the - * {@link #strip(String, String)} methods.

- * - *
-     * StringUtils.trim(null)          = null
-     * StringUtils.trim("")            = ""
-     * StringUtils.trim("     ")       = ""
-     * StringUtils.trim("abc")         = "abc"
-     * StringUtils.trim("    abc    ") = "abc"
-     * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed string, {@code null} if null String input - */ - public static String trim(final String str) { - return str == null ? null : str.trim(); - } - - /** - *

Removes control characters (char <= 32) from both - * ends of this String returning {@code null} if the String is - * empty ("") after the trim or if it is {@code null}. - * - *

The String is trimmed using {@link String#trim()}. - * Trim removes start and end characters <= 32. - * To strip whitespace use {@link #stripToNull(String)}.

- * - *
-     * StringUtils.trimToNull(null)          = null
-     * StringUtils.trimToNull("")            = null
-     * StringUtils.trimToNull("     ")       = null
-     * StringUtils.trimToNull("abc")         = "abc"
-     * StringUtils.trimToNull("    abc    ") = "abc"
-     * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed String, - * {@code null} if only chars <= 32, empty or null String input - * @since 2.0 - */ - public static String trimToNull(final String str) { - final String ts = trim(str); - return isEmpty(ts) ? null : ts; - } - - /** - *

Removes control characters (char <= 32) from both - * ends of this String returning an empty String ("") if the String - * is empty ("") after the trim or if it is {@code null}. - * - *

The String is trimmed using {@link String#trim()}. - * Trim removes start and end characters <= 32. - * To strip whitespace use {@link #stripToEmpty(String)}.

- * - *
-     * StringUtils.trimToEmpty(null)          = ""
-     * StringUtils.trimToEmpty("")            = ""
-     * StringUtils.trimToEmpty("     ")       = ""
-     * StringUtils.trimToEmpty("abc")         = "abc"
-     * StringUtils.trimToEmpty("    abc    ") = "abc"
-     * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed String, or an empty String if {@code null} input - * @since 2.0 - */ - public static String trimToEmpty(final String str) { - return str == null ? EMPTY : str.trim(); - } - - // Stripping - //----------------------------------------------------------------------- - /** - *

Strips whitespace from the start and end of a String.

- * - *

This is similar to {@link #trim(String)} but removes whitespace. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.strip(null)     = null
-     * StringUtils.strip("")       = ""
-     * StringUtils.strip("   ")    = ""
-     * StringUtils.strip("abc")    = "abc"
-     * StringUtils.strip("  abc")  = "abc"
-     * StringUtils.strip("abc  ")  = "abc"
-     * StringUtils.strip(" abc ")  = "abc"
-     * StringUtils.strip(" ab c ") = "ab c"
-     * 
- * - * @param str the String to remove whitespace from, may be null - * @return the stripped String, {@code null} if null String input - */ - public static String strip(final String str) { - return strip(str, null); - } - - /** - *

Strips whitespace from the start and end of a String returning - * {@code null} if the String is empty ("") after the strip.

- * - *

This is similar to {@link #trimToNull(String)} but removes whitespace. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripToNull(null)     = null
-     * StringUtils.stripToNull("")       = null
-     * StringUtils.stripToNull("   ")    = null
-     * StringUtils.stripToNull("abc")    = "abc"
-     * StringUtils.stripToNull("  abc")  = "abc"
-     * StringUtils.stripToNull("abc  ")  = "abc"
-     * StringUtils.stripToNull(" abc ")  = "abc"
-     * StringUtils.stripToNull(" ab c ") = "ab c"
-     * 
- * - * @param str the String to be stripped, may be null - * @return the stripped String, - * {@code null} if whitespace, empty or null String input - * @since 2.0 - */ - public static String stripToNull(String str) { - if (str == null) { - return null; - } - str = strip(str, null); - return str.isEmpty() ? null : str; - } - - /** - *

Strips whitespace from the start and end of a String returning - * an empty String if {@code null} input.

- * - *

This is similar to {@link #trimToEmpty(String)} but removes whitespace. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripToEmpty(null)     = ""
-     * StringUtils.stripToEmpty("")       = ""
-     * StringUtils.stripToEmpty("   ")    = ""
-     * StringUtils.stripToEmpty("abc")    = "abc"
-     * StringUtils.stripToEmpty("  abc")  = "abc"
-     * StringUtils.stripToEmpty("abc  ")  = "abc"
-     * StringUtils.stripToEmpty(" abc ")  = "abc"
-     * StringUtils.stripToEmpty(" ab c ") = "ab c"
-     * 
- * - * @param str the String to be stripped, may be null - * @return the trimmed String, or an empty String if {@code null} input - * @since 2.0 - */ - public static String stripToEmpty(final String str) { - return str == null ? EMPTY : strip(str, null); - } - - /** - *

Strips any of a set of characters from the start and end of a String. - * This is similar to {@link String#trim()} but allows the characters - * to be stripped to be controlled.

- * - *

A {@code null} input String returns {@code null}. - * An empty string ("") input returns the empty string.

- * - *

If the stripChars String is {@code null}, whitespace is - * stripped as defined by {@link Character#isWhitespace(char)}. - * Alternatively use {@link #strip(String)}.

- * - *
-     * StringUtils.strip(null, *)          = null
-     * StringUtils.strip("", *)            = ""
-     * StringUtils.strip("abc", null)      = "abc"
-     * StringUtils.strip("  abc", null)    = "abc"
-     * StringUtils.strip("abc  ", null)    = "abc"
-     * StringUtils.strip(" abc ", null)    = "abc"
-     * StringUtils.strip("  abcyx", "xyz") = "  abc"
-     * 
- * - * @param str the String to remove characters from, may be null - * @param stripChars the characters to remove, null treated as whitespace - * @return the stripped String, {@code null} if null String input - */ - public static String strip(String str, final String stripChars) { - if (isEmpty(str)) { - return str; - } - str = stripStart(str, stripChars); - return stripEnd(str, stripChars); - } - - /** - *

Strips any of a set of characters from the start of a String.

- * - *

A {@code null} input String returns {@code null}. - * An empty string ("") input returns the empty string.

- * - *

If the stripChars String is {@code null}, whitespace is - * stripped as defined by {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripStart(null, *)          = null
-     * StringUtils.stripStart("", *)            = ""
-     * StringUtils.stripStart("abc", "")        = "abc"
-     * StringUtils.stripStart("abc", null)      = "abc"
-     * StringUtils.stripStart("  abc", null)    = "abc"
-     * StringUtils.stripStart("abc  ", null)    = "abc  "
-     * StringUtils.stripStart(" abc ", null)    = "abc "
-     * StringUtils.stripStart("yxabc  ", "xyz") = "abc  "
-     * 
- * - * @param str the String to remove characters from, may be null - * @param stripChars the characters to remove, null treated as whitespace - * @return the stripped String, {@code null} if null String input - */ - public static String stripStart(final String str, final String stripChars) { - int strLen; - if (str == null || (strLen = str.length()) == 0) { - return str; - } - int start = 0; - if (stripChars == null) { - while (start != strLen && Character.isWhitespace(str.charAt(start))) { - start++; - } - } else if (stripChars.isEmpty()) { - return str; - } else { - while (start != strLen && stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND) { - start++; - } - } - return str.substring(start); - } - - /** - *

Strips any of a set of characters from the end of a String.

- * - *

A {@code null} input String returns {@code null}. - * An empty string ("") input returns the empty string.

- * - *

If the stripChars String is {@code null}, whitespace is - * stripped as defined by {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripEnd(null, *)          = null
-     * StringUtils.stripEnd("", *)            = ""
-     * StringUtils.stripEnd("abc", "")        = "abc"
-     * StringUtils.stripEnd("abc", null)      = "abc"
-     * StringUtils.stripEnd("  abc", null)    = "  abc"
-     * StringUtils.stripEnd("abc  ", null)    = "abc"
-     * StringUtils.stripEnd(" abc ", null)    = " abc"
-     * StringUtils.stripEnd("  abcyx", "xyz") = "  abc"
-     * StringUtils.stripEnd("120.00", ".0")   = "12"
-     * 
- * - * @param str the String to remove characters from, may be null - * @param stripChars the set of characters to remove, null treated as whitespace - * @return the stripped String, {@code null} if null String input - */ - public static String stripEnd(final String str, final String stripChars) { - int end; - if (str == null || (end = str.length()) == 0) { - return str; - } - - if (stripChars == null) { - while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) { - end--; - } - } else if (stripChars.isEmpty()) { - return str; - } else { - while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) { - end--; - } - } - return str.substring(0, end); - } - - // StripAll - //----------------------------------------------------------------------- - /** - *

Strips whitespace from the start and end of every String in an array. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

A new array is returned each time, except for length zero. - * A {@code null} array will return {@code null}. - * An empty array will return itself. - * A {@code null} array entry will be ignored.

- * - *
-     * StringUtils.stripAll(null)             = null
-     * StringUtils.stripAll([])               = []
-     * StringUtils.stripAll(["abc", "  abc"]) = ["abc", "abc"]
-     * StringUtils.stripAll(["abc  ", null])  = ["abc", null]
-     * 
- * - * @param strs the array to remove whitespace from, may be null - * @return the stripped Strings, {@code null} if null array input - */ - public static String[] stripAll(final String... strs) { - return stripAll(strs, null); - } - - /** - *

Strips any of a set of characters from the start and end of every - * String in an array.

- *

Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

A new array is returned each time, except for length zero. - * A {@code null} array will return {@code null}. - * An empty array will return itself. - * A {@code null} array entry will be ignored. - * A {@code null} stripChars will strip whitespace as defined by - * {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripAll(null, *)                = null
-     * StringUtils.stripAll([], *)                  = []
-     * StringUtils.stripAll(["abc", "  abc"], null) = ["abc", "abc"]
-     * StringUtils.stripAll(["abc  ", null], null)  = ["abc", null]
-     * StringUtils.stripAll(["abc  ", null], "yz")  = ["abc  ", null]
-     * StringUtils.stripAll(["yabcz", null], "yz")  = ["abc", null]
-     * 
- * - * @param strs the array to remove characters from, may be null - * @param stripChars the characters to remove, null treated as whitespace - * @return the stripped Strings, {@code null} if null array input - */ - public static String[] stripAll(final String[] strs, final String stripChars) { - int strsLen; - if (strs == null || (strsLen = strs.length) == 0) { - return strs; - } - final String[] newArr = new String[strsLen]; - for (int i = 0; i < strsLen; i++) { - newArr[i] = strip(strs[i], stripChars); - } - return newArr; - } - - /** - *

Removes diacritics (~= accents) from a string. The case will not be altered.

- *

For instance, 'à' will be replaced by 'a'.

- *

Note that ligatures will be left as is.

- * - *
-     * StringUtils.stripAccents(null)                = null
-     * StringUtils.stripAccents("")                  = ""
-     * StringUtils.stripAccents("control")           = "control"
-     * StringUtils.stripAccents("éclair")     = "eclair"
-     * 
- * - * @param input String to be stripped - * @return input text with diacritics removed - * - * @since 3.0 - */ - // See also Lucene's ASCIIFoldingFilter (Lucene 2.9) that replaces accented characters by their unaccented equivalent (and uncommitted bug fix: https://issues.apache.org/jira/browse/LUCENE-1343?focusedCommentId=12858907&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12858907). - public static String stripAccents(final String input) { - if(input == null) { - return null; - } - final Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");//$NON-NLS-1$ - final String decomposed = Normalizer.normalize(input, Normalizer.Form.NFD); - // Note that this doesn't correctly remove ligatures... - return pattern.matcher(decomposed).replaceAll("");//$NON-NLS-1$ - } - - // Equals - //----------------------------------------------------------------------- - /** - *

Compares two CharSequences, returning {@code true} if they represent - * equal sequences of characters.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case sensitive.

- * - *
-     * StringUtils.equals(null, null)   = true
-     * StringUtils.equals(null, "abc")  = false
-     * StringUtils.equals("abc", null)  = false
-     * StringUtils.equals("abc", "abc") = true
-     * StringUtils.equals("abc", "ABC") = false
-     * 
- * - * @see Object#equals(Object) - * @param cs1 the first CharSequence, may be {@code null} - * @param cs2 the second CharSequence, may be {@code null} - * @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null} - * @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence) - */ - public static boolean equals(final CharSequence cs1, final CharSequence cs2) { - if (cs1 == cs2) { - return true; - } - if (cs1 == null || cs2 == null) { - return false; - } - if (cs1.length() != cs2.length()) { - return false; - } - if (cs1 instanceof String && cs2 instanceof String) { - return cs1.equals(cs2); - } - return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, cs1.length()); - } - - /** - *

Compares two CharSequences, returning {@code true} if they represent - * equal sequences of characters, ignoring case.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered equal. Comparison is case insensitive.

- * - *
-     * StringUtils.equalsIgnoreCase(null, null)   = true
-     * StringUtils.equalsIgnoreCase(null, "abc")  = false
-     * StringUtils.equalsIgnoreCase("abc", null)  = false
-     * StringUtils.equalsIgnoreCase("abc", "abc") = true
-     * StringUtils.equalsIgnoreCase("abc", "ABC") = true
-     * 
- * - * @param str1 the first CharSequence, may be null - * @param str2 the second CharSequence, may be null - * @return {@code true} if the CharSequence are equal, case insensitive, or - * both {@code null} - * @since 3.0 Changed signature from equalsIgnoreCase(String, String) to equalsIgnoreCase(CharSequence, CharSequence) - */ - public static boolean equalsIgnoreCase(final CharSequence str1, final CharSequence str2) { - if (str1 == null || str2 == null) { - return str1 == str2; - } else if (str1 == str2) { - return true; - } else if (str1.length() != str2.length()) { - return false; - } else { - return CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, str1.length()); - } - } - - // IndexOf - //----------------------------------------------------------------------- - /** - *

Finds the first index within a CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(int, int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code INDEX_NOT_FOUND (-1)}.

- * - *
-     * StringUtils.indexOf(null, *)         = -1
-     * StringUtils.indexOf("", *)           = -1
-     * StringUtils.indexOf("aabaabaa", 'a') = 0
-     * StringUtils.indexOf("aabaabaa", 'b') = 2
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @return the first index of the search character, - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from indexOf(String, int) to indexOf(CharSequence, int) - */ - public static int indexOf(final CharSequence seq, final int searchChar) { - if (isEmpty(seq)) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.indexOf(seq, searchChar, 0); - } - - /** - *

Finds the first index within a CharSequence from a start position, - * handling {@code null}. - * This method uses {@link String#indexOf(int, int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code (INDEX_NOT_FOUND) -1}. - * A negative start position is treated as zero. - * A start position greater than the string length returns {@code -1}.

- * - *
-     * StringUtils.indexOf(null, *, *)          = -1
-     * StringUtils.indexOf("", *, *)            = -1
-     * StringUtils.indexOf("aabaabaa", 'b', 0)  = 2
-     * StringUtils.indexOf("aabaabaa", 'b', 3)  = 5
-     * StringUtils.indexOf("aabaabaa", 'b', 9)  = -1
-     * StringUtils.indexOf("aabaabaa", 'b', -1) = 2
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @param startPos the start position, negative treated as zero - * @return the first index of the search character (always ≥ startPos), - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from indexOf(String, int, int) to indexOf(CharSequence, int, int) - */ - public static int indexOf(final CharSequence seq, final int searchChar, final int startPos) { - if (isEmpty(seq)) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.indexOf(seq, searchChar, startPos); - } - - /** - *

Finds the first index within a CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(String, int)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}.

- * - *
-     * StringUtils.indexOf(null, *)          = -1
-     * StringUtils.indexOf(*, null)          = -1
-     * StringUtils.indexOf("", "")           = 0
-     * StringUtils.indexOf("", *)            = -1 (except when * = "")
-     * StringUtils.indexOf("aabaabaa", "a")  = 0
-     * StringUtils.indexOf("aabaabaa", "b")  = 2
-     * StringUtils.indexOf("aabaabaa", "ab") = 1
-     * StringUtils.indexOf("aabaabaa", "")   = 0
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @return the first index of the search CharSequence, - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence) - */ - public static int indexOf(final CharSequence seq, final CharSequence searchSeq) { - if (seq == null || searchSeq == null) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.indexOf(seq, searchSeq, 0); - } - - /** - *

Finds the first index within a CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(String, int)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position is treated as zero. - * An empty ("") search CharSequence always matches. - * A start position greater than the string length only matches - * an empty search CharSequence.

- * - *
-     * StringUtils.indexOf(null, *, *)          = -1
-     * StringUtils.indexOf(*, null, *)          = -1
-     * StringUtils.indexOf("", "", 0)           = 0
-     * StringUtils.indexOf("", *, 0)            = -1 (except when * = "")
-     * StringUtils.indexOf("aabaabaa", "a", 0)  = 0
-     * StringUtils.indexOf("aabaabaa", "b", 0)  = 2
-     * StringUtils.indexOf("aabaabaa", "ab", 0) = 1
-     * StringUtils.indexOf("aabaabaa", "b", 3)  = 5
-     * StringUtils.indexOf("aabaabaa", "b", 9)  = -1
-     * StringUtils.indexOf("aabaabaa", "b", -1) = 2
-     * StringUtils.indexOf("aabaabaa", "", 2)   = 2
-     * StringUtils.indexOf("abc", "", 9)        = 3
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @param startPos the start position, negative treated as zero - * @return the first index of the search CharSequence (always ≥ startPos), - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from indexOf(String, String, int) to indexOf(CharSequence, CharSequence, int) - */ - public static int indexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) { - if (seq == null || searchSeq == null) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.indexOf(seq, searchSeq, startPos); - } - - /** - *

Finds the n-th index within a CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(String)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}.

- * - *
-     * StringUtils.ordinalIndexOf(null, *, *)          = -1
-     * StringUtils.ordinalIndexOf(*, null, *)          = -1
-     * StringUtils.ordinalIndexOf("", "", *)           = 0
-     * StringUtils.ordinalIndexOf("aabaabaa", "a", 1)  = 0
-     * StringUtils.ordinalIndexOf("aabaabaa", "a", 2)  = 1
-     * StringUtils.ordinalIndexOf("aabaabaa", "b", 1)  = 2
-     * StringUtils.ordinalIndexOf("aabaabaa", "b", 2)  = 5
-     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
-     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
-     * StringUtils.ordinalIndexOf("aabaabaa", "", 1)   = 0
-     * StringUtils.ordinalIndexOf("aabaabaa", "", 2)   = 0
-     * 
- * - *

Note that 'head(CharSequence str, int n)' may be implemented as:

- * - *
-     *   str.substring(0, lastOrdinalIndexOf(str, "\n", n))
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param ordinal the n-th {@code searchStr} to find - * @return the n-th index of the search CharSequence, - * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input - * @since 2.1 - * @since 3.0 Changed signature from ordinalIndexOf(String, String, int) to ordinalIndexOf(CharSequence, CharSequence, int) - */ - public static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) { - return ordinalIndexOf(str, searchStr, ordinal, false); - } - - /** - *

Finds the n-th index within a String, handling {@code null}. - * This method uses {@link String#indexOf(String)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}.

- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param ordinal the n-th {@code searchStr} to find - * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf() - * @return the n-th index of the search CharSequence, - * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input - */ - // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int) - private static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal, final boolean lastIndex) { - if (str == null || searchStr == null || ordinal <= 0) { - return INDEX_NOT_FOUND; - } - if (searchStr.length() == 0) { - return lastIndex ? str.length() : 0; - } - int found = 0; - int index = lastIndex ? str.length() : INDEX_NOT_FOUND; - do { - if (lastIndex) { - index = CharSequenceUtils.lastIndexOf(str, searchStr, index - searchStr.length()); - } else { - index = CharSequenceUtils.indexOf(str, searchStr, index + searchStr.length()); - } - if (index < 0) { - return index; - } - found++; - } while (found < ordinal); - return index; - } - - /** - *

Case in-sensitive find of the first index within a CharSequence.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position is treated as zero. - * An empty ("") search CharSequence always matches. - * A start position greater than the string length only matches - * an empty search CharSequence.

- * - *
-     * StringUtils.indexOfIgnoreCase(null, *)          = -1
-     * StringUtils.indexOfIgnoreCase(*, null)          = -1
-     * StringUtils.indexOfIgnoreCase("", "")           = 0
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "a")  = 0
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "b")  = 2
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @return the first index of the search CharSequence, - * -1 if no match or {@code null} string input - * @since 2.5 - * @since 3.0 Changed signature from indexOfIgnoreCase(String, String) to indexOfIgnoreCase(CharSequence, CharSequence) - */ - public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { - return indexOfIgnoreCase(str, searchStr, 0); - } - - /** - *

Case in-sensitive find of the first index within a CharSequence - * from the specified position.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position is treated as zero. - * An empty ("") search CharSequence always matches. - * A start position greater than the string length only matches - * an empty search CharSequence.

- * - *
-     * StringUtils.indexOfIgnoreCase(null, *, *)          = -1
-     * StringUtils.indexOfIgnoreCase(*, null, *)          = -1
-     * StringUtils.indexOfIgnoreCase("", "", 0)           = 0
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0)  = 0
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0)  = 2
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3)  = 5
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9)  = -1
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "", 2)   = 2
-     * StringUtils.indexOfIgnoreCase("abc", "", 9)        = 3
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param startPos the start position, negative treated as zero - * @return the first index of the search CharSequence (always ≥ startPos), - * -1 if no match or {@code null} string input - * @since 2.5 - * @since 3.0 Changed signature from indexOfIgnoreCase(String, String, int) to indexOfIgnoreCase(CharSequence, CharSequence, int) - */ - public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) { - if (str == null || searchStr == null) { - return INDEX_NOT_FOUND; - } - if (startPos < 0) { - startPos = 0; - } - final int endLimit = str.length() - searchStr.length() + 1; - if (startPos > endLimit) { - return INDEX_NOT_FOUND; - } - if (searchStr.length() == 0) { - return startPos; - } - for (int i = startPos; i < endLimit; i++) { - if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - // LastIndexOf - //----------------------------------------------------------------------- - /** - *

Finds the last index within a CharSequence, handling {@code null}. - * This method uses {@link String#lastIndexOf(int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code -1}.

- * - *
-     * StringUtils.lastIndexOf(null, *)         = -1
-     * StringUtils.lastIndexOf("", *)           = -1
-     * StringUtils.lastIndexOf("aabaabaa", 'a') = 7
-     * StringUtils.lastIndexOf("aabaabaa", 'b') = 5
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @return the last index of the search character, - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from lastIndexOf(String, int) to lastIndexOf(CharSequence, int) - */ - public static int lastIndexOf(final CharSequence seq, final int searchChar) { - if (isEmpty(seq)) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.lastIndexOf(seq, searchChar, seq.length()); - } - - /** - *

Finds the last index within a CharSequence from a start position, - * handling {@code null}. - * This method uses {@link String#lastIndexOf(int, int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code -1}. - * A negative start position returns {@code -1}. - * A start position greater than the string length searches the whole string. - * The search starts at the startPos and works backwards; matches starting after the start - * position are ignored. - *

- * - *
-     * StringUtils.lastIndexOf(null, *, *)          = -1
-     * StringUtils.lastIndexOf("", *,  *)           = -1
-     * StringUtils.lastIndexOf("aabaabaa", 'b', 8)  = 5
-     * StringUtils.lastIndexOf("aabaabaa", 'b', 4)  = 2
-     * StringUtils.lastIndexOf("aabaabaa", 'b', 0)  = -1
-     * StringUtils.lastIndexOf("aabaabaa", 'b', 9)  = 5
-     * StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
-     * StringUtils.lastIndexOf("aabaabaa", 'a', 0)  = 0
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @param startPos the start position - * @return the last index of the search character (always ≤ startPos), - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from lastIndexOf(String, int, int) to lastIndexOf(CharSequence, int, int) - */ - public static int lastIndexOf(final CharSequence seq, final int searchChar, final int startPos) { - if (isEmpty(seq)) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.lastIndexOf(seq, searchChar, startPos); - } - - /** - *

Finds the last index within a CharSequence, handling {@code null}. - * This method uses {@link String#lastIndexOf(String)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}.

- * - *
-     * StringUtils.lastIndexOf(null, *)          = -1
-     * StringUtils.lastIndexOf(*, null)          = -1
-     * StringUtils.lastIndexOf("", "")           = 0
-     * StringUtils.lastIndexOf("aabaabaa", "a")  = 7
-     * StringUtils.lastIndexOf("aabaabaa", "b")  = 5
-     * StringUtils.lastIndexOf("aabaabaa", "ab") = 4
-     * StringUtils.lastIndexOf("aabaabaa", "")   = 8
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @return the last index of the search String, - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from lastIndexOf(String, String) to lastIndexOf(CharSequence, CharSequence) - */ - public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) { - if (seq == null || searchSeq == null) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.lastIndexOf(seq, searchSeq, seq.length()); - } - - /** - *

Finds the n-th last index within a String, handling {@code null}. - * This method uses {@link String#lastIndexOf(String)}.

- * - *

A {@code null} String will return {@code -1}.

- * - *
-     * StringUtils.lastOrdinalIndexOf(null, *, *)          = -1
-     * StringUtils.lastOrdinalIndexOf(*, null, *)          = -1
-     * StringUtils.lastOrdinalIndexOf("", "", *)           = 0
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1)  = 7
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2)  = 6
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1)  = 5
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2)  = 2
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1)   = 8
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2)   = 8
-     * 
- * - *

Note that 'tail(CharSequence str, int n)' may be implemented as:

- * - *
-     *   str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param ordinal the n-th last {@code searchStr} to find - * @return the n-th last index of the search CharSequence, - * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input - * @since 2.5 - * @since 3.0 Changed signature from lastOrdinalIndexOf(String, String, int) to lastOrdinalIndexOf(CharSequence, CharSequence, int) - */ - public static int lastOrdinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) { - return ordinalIndexOf(str, searchStr, ordinal, true); - } - - /** - *

Finds the last index within a CharSequence, handling {@code null}. - * This method uses {@link String#lastIndexOf(String, int)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position returns {@code -1}. - * An empty ("") search CharSequence always matches unless the start position is negative. - * A start position greater than the string length searches the whole string. - * The search starts at the startPos and works backwards; matches starting after the start - * position are ignored. - *

- * - *
-     * StringUtils.lastIndexOf(null, *, *)          = -1
-     * StringUtils.lastIndexOf(*, null, *)          = -1
-     * StringUtils.lastIndexOf("aabaabaa", "a", 8)  = 7
-     * StringUtils.lastIndexOf("aabaabaa", "b", 8)  = 5
-     * StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
-     * StringUtils.lastIndexOf("aabaabaa", "b", 9)  = 5
-     * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
-     * StringUtils.lastIndexOf("aabaabaa", "a", 0)  = 0
-     * StringUtils.lastIndexOf("aabaabaa", "b", 0)  = -1
-     * StringUtils.lastIndexOf("aabaabaa", "b", 1)  = -1
-     * StringUtils.lastIndexOf("aabaabaa", "b", 2)  = 2
-     * StringUtils.lastIndexOf("aabaabaa", "ba", 2)  = -1
-     * StringUtils.lastIndexOf("aabaabaa", "ba", 2)  = 2
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @param startPos the start position, negative treated as zero - * @return the last index of the search CharSequence (always ≤ startPos), - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from lastIndexOf(String, String, int) to lastIndexOf(CharSequence, CharSequence, int) - */ - public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) { - if (seq == null || searchSeq == null) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.lastIndexOf(seq, searchSeq, startPos); - } - - /** - *

Case in-sensitive find of the last index within a CharSequence.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position returns {@code -1}. - * An empty ("") search CharSequence always matches unless the start position is negative. - * A start position greater than the string length searches the whole string.

- * - *
-     * StringUtils.lastIndexOfIgnoreCase(null, *)          = -1
-     * StringUtils.lastIndexOfIgnoreCase(*, null)          = -1
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A")  = 7
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B")  = 5
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @return the first index of the search CharSequence, - * -1 if no match or {@code null} string input - * @since 2.5 - * @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String) to lastIndexOfIgnoreCase(CharSequence, CharSequence) - */ - public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { - if (str == null || searchStr == null) { - return INDEX_NOT_FOUND; - } - return lastIndexOfIgnoreCase(str, searchStr, str.length()); - } - - /** - *

Case in-sensitive find of the last index within a CharSequence - * from the specified position.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position returns {@code -1}. - * An empty ("") search CharSequence always matches unless the start position is negative. - * A start position greater than the string length searches the whole string. - * The search starts at the startPos and works backwards; matches starting after the start - * position are ignored. - *

- * - *
-     * StringUtils.lastIndexOfIgnoreCase(null, *, *)          = -1
-     * StringUtils.lastIndexOfIgnoreCase(*, null, *)          = -1
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8)  = 7
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8)  = 5
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9)  = 5
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0)  = 0
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0)  = -1
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param startPos the start position - * @return the last index of the search CharSequence (always ≤ startPos), - * -1 if no match or {@code null} input - * @since 2.5 - * @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String, int) to lastIndexOfIgnoreCase(CharSequence, CharSequence, int) - */ - public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) { - if (str == null || searchStr == null) { - return INDEX_NOT_FOUND; - } - if (startPos > str.length() - searchStr.length()) { - startPos = str.length() - searchStr.length(); - } - if (startPos < 0) { - return INDEX_NOT_FOUND; - } - if (searchStr.length() == 0) { - return startPos; - } - - for (int i = startPos; i >= 0; i--) { - if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - // Contains - //----------------------------------------------------------------------- - /** - *

Checks if CharSequence contains a search character, handling {@code null}. - * This method uses {@link String#indexOf(int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code false}.

- * - *
-     * StringUtils.contains(null, *)    = false
-     * StringUtils.contains("", *)      = false
-     * StringUtils.contains("abc", 'a') = true
-     * StringUtils.contains("abc", 'z') = false
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @return true if the CharSequence contains the search character, - * false if not or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from contains(String, int) to contains(CharSequence, int) - */ - public static boolean contains(final CharSequence seq, final int searchChar) { - if (isEmpty(seq)) { - return false; - } - return CharSequenceUtils.indexOf(seq, searchChar, 0) >= 0; - } - - /** - *

Checks if CharSequence contains a search CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(String)} if possible.

- * - *

A {@code null} CharSequence will return {@code false}.

- * - *
-     * StringUtils.contains(null, *)     = false
-     * StringUtils.contains(*, null)     = false
-     * StringUtils.contains("", "")      = true
-     * StringUtils.contains("abc", "")   = true
-     * StringUtils.contains("abc", "a")  = true
-     * StringUtils.contains("abc", "z")  = false
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @return true if the CharSequence contains the search CharSequence, - * false if not or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence) - */ - public static boolean contains(final CharSequence seq, final CharSequence searchSeq) { - if (seq == null || searchSeq == null) { - return false; - } - return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0; - } - - /** - *

Checks if CharSequence contains a search CharSequence irrespective of case, - * handling {@code null}. Case-insensitivity is defined as by - * {@link String#equalsIgnoreCase(String)}. - * - *

A {@code null} CharSequence will return {@code false}.

- * - *
-     * StringUtils.contains(null, *) = false
-     * StringUtils.contains(*, null) = false
-     * StringUtils.contains("", "") = true
-     * StringUtils.contains("abc", "") = true
-     * StringUtils.contains("abc", "a") = true
-     * StringUtils.contains("abc", "z") = false
-     * StringUtils.contains("abc", "A") = true
-     * StringUtils.contains("abc", "Z") = false
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @return true if the CharSequence contains the search CharSequence irrespective of - * case or false if not or {@code null} string input - * @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence) - */ - public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) { - if (str == null || searchStr == null) { - return false; - } - final int len = searchStr.length(); - final int max = str.length() - len; - for (int i = 0; i <= max; i++) { - if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) { - return true; - } - } - return false; - } - - /** - * Check whether the given CharSequence contains any whitespace characters. - * @param seq the CharSequence to check (may be {@code null}) - * @return {@code true} if the CharSequence is not empty and - * contains at least 1 whitespace character - * @see java.lang.Character#isWhitespace - * @since 3.0 - */ - // From org.springframework.util.StringUtils, under Apache License 2.0 - public static boolean containsWhitespace(final CharSequence seq) { - if (isEmpty(seq)) { - return false; - } - final int strLen = seq.length(); - for (int i = 0; i < strLen; i++) { - if (Character.isWhitespace(seq.charAt(i))) { - return true; - } - } - return false; - } - - // IndexOfAny chars - //----------------------------------------------------------------------- - /** - *

Search a CharSequence to find the first index of any - * character in the given set of characters.

- * - *

A {@code null} String will return {@code -1}. - * A {@code null} or zero length search array will return {@code -1}.

- * - *
-     * StringUtils.indexOfAny(null, *)                = -1
-     * StringUtils.indexOfAny("", *)                  = -1
-     * StringUtils.indexOfAny(*, null)                = -1
-     * StringUtils.indexOfAny(*, [])                  = -1
-     * StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
-     * StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
-     * StringUtils.indexOfAny("aba", ['z'])           = -1
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the index of any of the chars, -1 if no match or null input - * @since 2.0 - * @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char...) - */ - public static int indexOfAny(final CharSequence cs, final char... searchChars) { - if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { - return INDEX_NOT_FOUND; - } - final int csLen = cs.length(); - final int csLast = csLen - 1; - final int searchLen = searchChars.length; - final int searchLast = searchLen - 1; - for (int i = 0; i < csLen; i++) { - final char ch = cs.charAt(i); - for (int j = 0; j < searchLen; j++) { - if (searchChars[j] == ch) { - if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) { - // ch is a supplementary character - if (searchChars[j + 1] == cs.charAt(i + 1)) { - return i; - } - } else { - return i; - } - } - } - } - return INDEX_NOT_FOUND; - } - - /** - *

Search a CharSequence to find the first index of any - * character in the given set of characters.

- * - *

A {@code null} String will return {@code -1}. - * A {@code null} search string will return {@code -1}.

- * - *
-     * StringUtils.indexOfAny(null, *)            = -1
-     * StringUtils.indexOfAny("", *)              = -1
-     * StringUtils.indexOfAny(*, null)            = -1
-     * StringUtils.indexOfAny(*, "")              = -1
-     * StringUtils.indexOfAny("zzabyycdxx", "za") = 0
-     * StringUtils.indexOfAny("zzabyycdxx", "by") = 3
-     * StringUtils.indexOfAny("aba","z")          = -1
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the index of any of the chars, -1 if no match or null input - * @since 2.0 - * @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String) - */ - public static int indexOfAny(final CharSequence cs, final String searchChars) { - if (isEmpty(cs) || isEmpty(searchChars)) { - return INDEX_NOT_FOUND; - } - return indexOfAny(cs, searchChars.toCharArray()); - } - - // ContainsAny - //----------------------------------------------------------------------- - /** - *

Checks if the CharSequence contains any character in the given - * set of characters.

- * - *

A {@code null} CharSequence will return {@code false}. - * A {@code null} or zero length search array will return {@code false}.

- * - *
-     * StringUtils.containsAny(null, *)                = false
-     * StringUtils.containsAny("", *)                  = false
-     * StringUtils.containsAny(*, null)                = false
-     * StringUtils.containsAny(*, [])                  = false
-     * StringUtils.containsAny("zzabyycdxx",['z','a']) = true
-     * StringUtils.containsAny("zzabyycdxx",['b','y']) = true
-     * StringUtils.containsAny("zzabyycdxx",['z','y']) = true
-     * StringUtils.containsAny("aba", ['z'])           = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the {@code true} if any of the chars are found, - * {@code false} if no match or null input - * @since 2.4 - * @since 3.0 Changed signature from containsAny(String, char[]) to containsAny(CharSequence, char...) - */ - public static boolean containsAny(final CharSequence cs, final char... searchChars) { - if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { - return false; - } - final int csLength = cs.length(); - final int searchLength = searchChars.length; - final int csLast = csLength - 1; - final int searchLast = searchLength - 1; - for (int i = 0; i < csLength; i++) { - final char ch = cs.charAt(i); - for (int j = 0; j < searchLength; j++) { - if (searchChars[j] == ch) { - if (Character.isHighSurrogate(ch)) { - if (j == searchLast) { - // missing low surrogate, fine, like String.indexOf(String) - return true; - } - if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) { - return true; - } - } else { - // ch is in the Basic Multilingual Plane - return true; - } - } - } - } - return false; - } - - /** - *

- * Checks if the CharSequence contains any character in the given set of characters. - *

- * - *

- * A {@code null} CharSequence will return {@code false}. A {@code null} search CharSequence will return - * {@code false}. - *

- * - *
-     * StringUtils.containsAny(null, *)            = false
-     * StringUtils.containsAny("", *)              = false
-     * StringUtils.containsAny(*, null)            = false
-     * StringUtils.containsAny(*, "")              = false
-     * StringUtils.containsAny("zzabyycdxx", "za") = true
-     * StringUtils.containsAny("zzabyycdxx", "by") = true
-     * StringUtils.containsAny("zzabyycdxx", "zy") = true
-     * StringUtils.containsAny("aba","z")          = false
-     * 
- * - * @param cs - * the CharSequence to check, may be null - * @param searchChars - * the chars to search for, may be null - * @return the {@code true} if any of the chars are found, {@code false} if no match or null input - * @since 2.4 - * @since 3.0 Changed signature from containsAny(String, String) to containsAny(CharSequence, CharSequence) - */ - public static boolean containsAny(final CharSequence cs, final CharSequence searchChars) { - if (searchChars == null) { - return false; - } - return containsAny(cs, CharSequenceUtils.toCharArray(searchChars)); - } - - /** - *

Checks if the CharSequence contains any of the CharSequences in the given array.

- * - *

- * A {@code null} CharSequence will return {@code false}. A {@code null} or zero - * length search array will return {@code false}. - *

- * - *
-     * StringUtils.containsAny(null, *)            = false
-     * StringUtils.containsAny("", *)              = false
-     * StringUtils.containsAny(*, null)            = false
-     * StringUtils.containsAny(*, [])              = false
-     * StringUtils.containsAny("abcd", "ab", null) = false
-     * StringUtils.containsAny("abcd", "ab", "cd") = true
-     * StringUtils.containsAny("abc", "d", "abc")  = true
-     * 
- * - * - * @param cs The CharSequence to check, may be null - * @param searchCharSequences The array of CharSequences to search for, may be null - * @return {@code true} if any of the search CharSequences are found, {@code false} otherwise - * @since 3.4 - */ - public static boolean containsAny(CharSequence cs, CharSequence... searchCharSequences) { - if (isEmpty(cs) || ArrayUtils.isEmpty(searchCharSequences)) { - return false; - } - for (CharSequence searchCharSequence : searchCharSequences) { - if (contains(cs, searchCharSequence)) { - return true; - } - } - return false; - } - - // IndexOfAnyBut chars - //----------------------------------------------------------------------- - /** - *

Searches a CharSequence to find the first index of any - * character not in the given set of characters.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A {@code null} or zero length search array will return {@code -1}.

- * - *
-     * StringUtils.indexOfAnyBut(null, *)                              = -1
-     * StringUtils.indexOfAnyBut("", *)                                = -1
-     * StringUtils.indexOfAnyBut(*, null)                              = -1
-     * StringUtils.indexOfAnyBut(*, [])                                = -1
-     * StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z', 'a'} ) = 3
-     * StringUtils.indexOfAnyBut("aba", new char[] {'z'} )             = 0
-     * StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'} )        = -1
-
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the index of any of the chars, -1 if no match or null input - * @since 2.0 - * @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char...) - */ - public static int indexOfAnyBut(final CharSequence cs, final char... searchChars) { - if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { - return INDEX_NOT_FOUND; - } - final int csLen = cs.length(); - final int csLast = csLen - 1; - final int searchLen = searchChars.length; - final int searchLast = searchLen - 1; - outer: - for (int i = 0; i < csLen; i++) { - final char ch = cs.charAt(i); - for (int j = 0; j < searchLen; j++) { - if (searchChars[j] == ch) { - if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) { - if (searchChars[j + 1] == cs.charAt(i + 1)) { - continue outer; - } - } else { - continue outer; - } - } - } - return i; - } - return INDEX_NOT_FOUND; - } - - /** - *

Search a CharSequence to find the first index of any - * character not in the given set of characters.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A {@code null} or empty search string will return {@code -1}.

- * - *
-     * StringUtils.indexOfAnyBut(null, *)            = -1
-     * StringUtils.indexOfAnyBut("", *)              = -1
-     * StringUtils.indexOfAnyBut(*, null)            = -1
-     * StringUtils.indexOfAnyBut(*, "")              = -1
-     * StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
-     * StringUtils.indexOfAnyBut("zzabyycdxx", "")   = -1
-     * StringUtils.indexOfAnyBut("aba","ab")         = -1
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the index of any of the chars, -1 if no match or null input - * @since 2.0 - * @since 3.0 Changed signature from indexOfAnyBut(String, String) to indexOfAnyBut(CharSequence, CharSequence) - */ - public static int indexOfAnyBut(final CharSequence seq, final CharSequence searchChars) { - if (isEmpty(seq) || isEmpty(searchChars)) { - return INDEX_NOT_FOUND; - } - final int strLen = seq.length(); - for (int i = 0; i < strLen; i++) { - final char ch = seq.charAt(i); - final boolean chFound = CharSequenceUtils.indexOf(searchChars, ch, 0) >= 0; - if (i + 1 < strLen && Character.isHighSurrogate(ch)) { - final char ch2 = seq.charAt(i + 1); - if (chFound && CharSequenceUtils.indexOf(searchChars, ch2, 0) < 0) { - return i; - } - } else { - if (!chFound) { - return i; - } - } - } - return INDEX_NOT_FOUND; - } - - // ContainsOnly - //----------------------------------------------------------------------- - /** - *

Checks if the CharSequence contains only certain characters.

- * - *

A {@code null} CharSequence will return {@code false}. - * A {@code null} valid character array will return {@code false}. - * An empty CharSequence (length()=0) always returns {@code true}.

- * - *
-     * StringUtils.containsOnly(null, *)       = false
-     * StringUtils.containsOnly(*, null)       = false
-     * StringUtils.containsOnly("", *)         = true
-     * StringUtils.containsOnly("ab", '')      = false
-     * StringUtils.containsOnly("abab", 'abc') = true
-     * StringUtils.containsOnly("ab1", 'abc')  = false
-     * StringUtils.containsOnly("abz", 'abc')  = false
-     * 
- * - * @param cs the String to check, may be null - * @param valid an array of valid chars, may be null - * @return true if it only contains valid chars and is non-null - * @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...) - */ - public static boolean containsOnly(final CharSequence cs, final char... valid) { - // All these pre-checks are to maintain API with an older version - if (valid == null || cs == null) { - return false; - } - if (cs.length() == 0) { - return true; - } - if (valid.length == 0) { - return false; - } - return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND; - } - - /** - *

Checks if the CharSequence contains only certain characters.

- * - *

A {@code null} CharSequence will return {@code false}. - * A {@code null} valid character String will return {@code false}. - * An empty String (length()=0) always returns {@code true}.

- * - *
-     * StringUtils.containsOnly(null, *)       = false
-     * StringUtils.containsOnly(*, null)       = false
-     * StringUtils.containsOnly("", *)         = true
-     * StringUtils.containsOnly("ab", "")      = false
-     * StringUtils.containsOnly("abab", "abc") = true
-     * StringUtils.containsOnly("ab1", "abc")  = false
-     * StringUtils.containsOnly("abz", "abc")  = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param validChars a String of valid chars, may be null - * @return true if it only contains valid chars and is non-null - * @since 2.0 - * @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String) - */ - public static boolean containsOnly(final CharSequence cs, final String validChars) { - if (cs == null || validChars == null) { - return false; - } - return containsOnly(cs, validChars.toCharArray()); - } - - // ContainsNone - //----------------------------------------------------------------------- - /** - *

Checks that the CharSequence does not contain certain characters.

- * - *

A {@code null} CharSequence will return {@code true}. - * A {@code null} invalid character array will return {@code true}. - * An empty CharSequence (length()=0) always returns true.

- * - *
-     * StringUtils.containsNone(null, *)       = true
-     * StringUtils.containsNone(*, null)       = true
-     * StringUtils.containsNone("", *)         = true
-     * StringUtils.containsNone("ab", '')      = true
-     * StringUtils.containsNone("abab", 'xyz') = true
-     * StringUtils.containsNone("ab1", 'xyz')  = true
-     * StringUtils.containsNone("abz", 'xyz')  = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars an array of invalid chars, may be null - * @return true if it contains none of the invalid chars, or is null - * @since 2.0 - * @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char...) - */ - public static boolean containsNone(final CharSequence cs, final char... searchChars) { - if (cs == null || searchChars == null) { - return true; - } - final int csLen = cs.length(); - final int csLast = csLen - 1; - final int searchLen = searchChars.length; - final int searchLast = searchLen - 1; - for (int i = 0; i < csLen; i++) { - final char ch = cs.charAt(i); - for (int j = 0; j < searchLen; j++) { - if (searchChars[j] == ch) { - if (Character.isHighSurrogate(ch)) { - if (j == searchLast) { - // missing low surrogate, fine, like String.indexOf(String) - return false; - } - if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) { - return false; - } - } else { - // ch is in the Basic Multilingual Plane - return false; - } - } - } - } - return true; - } - - /** - *

Checks that the CharSequence does not contain certain characters.

- * - *

A {@code null} CharSequence will return {@code true}. - * A {@code null} invalid character array will return {@code true}. - * An empty String ("") always returns true.

- * - *
-     * StringUtils.containsNone(null, *)       = true
-     * StringUtils.containsNone(*, null)       = true
-     * StringUtils.containsNone("", *)         = true
-     * StringUtils.containsNone("ab", "")      = true
-     * StringUtils.containsNone("abab", "xyz") = true
-     * StringUtils.containsNone("ab1", "xyz")  = true
-     * StringUtils.containsNone("abz", "xyz")  = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param invalidChars a String of invalid chars, may be null - * @return true if it contains none of the invalid chars, or is null - * @since 2.0 - * @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String) - */ - public static boolean containsNone(final CharSequence cs, final String invalidChars) { - if (cs == null || invalidChars == null) { - return true; - } - return containsNone(cs, invalidChars.toCharArray()); - } - - // IndexOfAny strings - //----------------------------------------------------------------------- - /** - *

Find the first index of any of a set of potential substrings.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A {@code null} or zero length search array will return {@code -1}. - * A {@code null} search array entry will be ignored, but a search - * array containing "" will return {@code 0} if {@code str} is not - * null. This method uses {@link String#indexOf(String)} if possible.

- * - *
-     * StringUtils.indexOfAny(null, *)                     = -1
-     * StringUtils.indexOfAny(*, null)                     = -1
-     * StringUtils.indexOfAny(*, [])                       = -1
-     * StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"])   = 2
-     * StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"])   = 2
-     * StringUtils.indexOfAny("zzabyycdxx", ["mn","op"])   = -1
-     * StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
-     * StringUtils.indexOfAny("zzabyycdxx", [""])          = 0
-     * StringUtils.indexOfAny("", [""])                    = 0
-     * StringUtils.indexOfAny("", ["a"])                   = -1
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStrs the CharSequences to search for, may be null - * @return the first index of any of the searchStrs in str, -1 if no match - * @since 3.0 Changed signature from indexOfAny(String, String[]) to indexOfAny(CharSequence, CharSequence...) - */ - public static int indexOfAny(final CharSequence str, final CharSequence... searchStrs) { - if (str == null || searchStrs == null) { - return INDEX_NOT_FOUND; - } - final int sz = searchStrs.length; - - // String's can't have a MAX_VALUEth index. - int ret = Integer.MAX_VALUE; - - int tmp = 0; - for (int i = 0; i < sz; i++) { - final CharSequence search = searchStrs[i]; - if (search == null) { - continue; - } - tmp = CharSequenceUtils.indexOf(str, search, 0); - if (tmp == INDEX_NOT_FOUND) { - continue; - } - - if (tmp < ret) { - ret = tmp; - } - } - - return ret == Integer.MAX_VALUE ? INDEX_NOT_FOUND : ret; - } - - /** - *

Find the latest index of any of a set of potential substrings.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A {@code null} search array will return {@code -1}. - * A {@code null} or zero length search array entry will be ignored, - * but a search array containing "" will return the length of {@code str} - * if {@code str} is not null. This method uses {@link String#indexOf(String)} if possible

- * - *
-     * StringUtils.lastIndexOfAny(null, *)                   = -1
-     * StringUtils.lastIndexOfAny(*, null)                   = -1
-     * StringUtils.lastIndexOfAny(*, [])                     = -1
-     * StringUtils.lastIndexOfAny(*, [null])                 = -1
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""])   = 10
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStrs the CharSequences to search for, may be null - * @return the last index of any of the CharSequences, -1 if no match - * @since 3.0 Changed signature from lastIndexOfAny(String, String[]) to lastIndexOfAny(CharSequence, CharSequence) - */ - public static int lastIndexOfAny(final CharSequence str, final CharSequence... searchStrs) { - if (str == null || searchStrs == null) { - return INDEX_NOT_FOUND; - } - final int sz = searchStrs.length; - int ret = INDEX_NOT_FOUND; - int tmp = 0; - for (int i = 0; i < sz; i++) { - final CharSequence search = searchStrs[i]; - if (search == null) { - continue; - } - tmp = CharSequenceUtils.lastIndexOf(str, search, str.length()); - if (tmp > ret) { - ret = tmp; - } - } - return ret; - } - - // Substring - //----------------------------------------------------------------------- - /** - *

Gets a substring from the specified String avoiding exceptions.

- * - *

A negative start position can be used to start {@code n} - * characters from the end of the String.

- * - *

A {@code null} String will return {@code null}. - * An empty ("") String will return "".

- * - *
-     * StringUtils.substring(null, *)   = null
-     * StringUtils.substring("", *)     = ""
-     * StringUtils.substring("abc", 0)  = "abc"
-     * StringUtils.substring("abc", 2)  = "c"
-     * StringUtils.substring("abc", 4)  = ""
-     * StringUtils.substring("abc", -2) = "bc"
-     * StringUtils.substring("abc", -4) = "abc"
-     * 
- * - * @param str the String to get the substring from, may be null - * @param start the position to start from, negative means - * count back from the end of the String by this many characters - * @return substring from start position, {@code null} if null String input - */ - public static String substring(final String str, int start) { - if (str == null) { - return null; - } - - // handle negatives, which means last n characters - if (start < 0) { - start = str.length() + start; // remember start is negative - } - - if (start < 0) { - start = 0; - } - if (start > str.length()) { - return EMPTY; - } - - return str.substring(start); - } - - /** - *

Gets a substring from the specified String avoiding exceptions.

- * - *

A negative start position can be used to start/end {@code n} - * characters from the end of the String.

- * - *

The returned substring starts with the character in the {@code start} - * position and ends before the {@code end} position. All position counting is - * zero-based -- i.e., to start at the beginning of the string use - * {@code start = 0}. Negative start and end positions can be used to - * specify offsets relative to the end of the String.

- * - *

If {@code start} is not strictly to the left of {@code end}, "" - * is returned.

- * - *
-     * StringUtils.substring(null, *, *)    = null
-     * StringUtils.substring("", * ,  *)    = "";
-     * StringUtils.substring("abc", 0, 2)   = "ab"
-     * StringUtils.substring("abc", 2, 0)   = ""
-     * StringUtils.substring("abc", 2, 4)   = "c"
-     * StringUtils.substring("abc", 4, 6)   = ""
-     * StringUtils.substring("abc", 2, 2)   = ""
-     * StringUtils.substring("abc", -2, -1) = "b"
-     * StringUtils.substring("abc", -4, 2)  = "ab"
-     * 
- * - * @param str the String to get the substring from, may be null - * @param start the position to start from, negative means - * count back from the end of the String by this many characters - * @param end the position to end at (exclusive), negative means - * count back from the end of the String by this many characters - * @return substring from start position to end position, - * {@code null} if null String input - */ - public static String substring(final String str, int start, int end) { - if (str == null) { - return null; - } - - // handle negatives - if (end < 0) { - end = str.length() + end; // remember end is negative - } - if (start < 0) { - start = str.length() + start; // remember start is negative - } - - // check length next - if (end > str.length()) { - end = str.length(); - } - - // if start is greater than end, return "" - if (start > end) { - return EMPTY; - } - - if (start < 0) { - start = 0; - } - if (end < 0) { - end = 0; - } - - return str.substring(start, end); - } - - // Left/Right/Mid - //----------------------------------------------------------------------- - /** - *

Gets the leftmost {@code len} characters of a String.

- * - *

If {@code len} characters are not available, or the - * String is {@code null}, the String will be returned without - * an exception. An empty String is returned if len is negative.

- * - *
-     * StringUtils.left(null, *)    = null
-     * StringUtils.left(*, -ve)     = ""
-     * StringUtils.left("", *)      = ""
-     * StringUtils.left("abc", 0)   = ""
-     * StringUtils.left("abc", 2)   = "ab"
-     * StringUtils.left("abc", 4)   = "abc"
-     * 
- * - * @param str the String to get the leftmost characters from, may be null - * @param len the length of the required String - * @return the leftmost characters, {@code null} if null String input - */ - public static String left(final String str, final int len) { - if (str == null) { - return null; - } - if (len < 0) { - return EMPTY; - } - if (str.length() <= len) { - return str; - } - return str.substring(0, len); - } - - /** - *

Gets the rightmost {@code len} characters of a String.

- * - *

If {@code len} characters are not available, or the String - * is {@code null}, the String will be returned without an - * an exception. An empty String is returned if len is negative.

- * - *
-     * StringUtils.right(null, *)    = null
-     * StringUtils.right(*, -ve)     = ""
-     * StringUtils.right("", *)      = ""
-     * StringUtils.right("abc", 0)   = ""
-     * StringUtils.right("abc", 2)   = "bc"
-     * StringUtils.right("abc", 4)   = "abc"
-     * 
- * - * @param str the String to get the rightmost characters from, may be null - * @param len the length of the required String - * @return the rightmost characters, {@code null} if null String input - */ - public static String right(final String str, final int len) { - if (str == null) { - return null; - } - if (len < 0) { - return EMPTY; - } - if (str.length() <= len) { - return str; - } - return str.substring(str.length() - len); - } - - /** - *

Gets {@code len} characters from the middle of a String.

- * - *

If {@code len} characters are not available, the remainder - * of the String will be returned without an exception. If the - * String is {@code null}, {@code null} will be returned. - * An empty String is returned if len is negative or exceeds the - * length of {@code str}.

- * - *
-     * StringUtils.mid(null, *, *)    = null
-     * StringUtils.mid(*, *, -ve)     = ""
-     * StringUtils.mid("", 0, *)      = ""
-     * StringUtils.mid("abc", 0, 2)   = "ab"
-     * StringUtils.mid("abc", 0, 4)   = "abc"
-     * StringUtils.mid("abc", 2, 4)   = "c"
-     * StringUtils.mid("abc", 4, 2)   = ""
-     * StringUtils.mid("abc", -2, 2)  = "ab"
-     * 
- * - * @param str the String to get the characters from, may be null - * @param pos the position to start from, negative treated as zero - * @param len the length of the required String - * @return the middle characters, {@code null} if null String input - */ - public static String mid(final String str, int pos, final int len) { - if (str == null) { - return null; - } - if (len < 0 || pos > str.length()) { - return EMPTY; - } - if (pos < 0) { - pos = 0; - } - if (str.length() <= pos + len) { - return str.substring(pos); - } - return str.substring(pos, pos + len); - } - - // SubStringAfter/SubStringBefore - //----------------------------------------------------------------------- - /** - *

Gets the substring before the first occurrence of a separator. - * The separator is not returned.

- * - *

A {@code null} string input will return {@code null}. - * An empty ("") string input will return the empty string. - * A {@code null} separator will return the input string.

- * - *

If nothing is found, the string input is returned.

- * - *
-     * StringUtils.substringBefore(null, *)      = null
-     * StringUtils.substringBefore("", *)        = ""
-     * StringUtils.substringBefore("abc", "a")   = ""
-     * StringUtils.substringBefore("abcba", "b") = "a"
-     * StringUtils.substringBefore("abc", "c")   = "ab"
-     * StringUtils.substringBefore("abc", "d")   = "abc"
-     * StringUtils.substringBefore("abc", "")    = ""
-     * StringUtils.substringBefore("abc", null)  = "abc"
-     * 
- * - * @param str the String to get a substring from, may be null - * @param separator the String to search for, may be null - * @return the substring before the first occurrence of the separator, - * {@code null} if null String input - * @since 2.0 - */ - public static String substringBefore(final String str, final String separator) { - if (isEmpty(str) || separator == null) { - return str; - } - if (separator.isEmpty()) { - return EMPTY; - } - final int pos = str.indexOf(separator); - if (pos == INDEX_NOT_FOUND) { - return str; - } - return str.substring(0, pos); - } - - /** - *

Gets the substring after the first occurrence of a separator. - * The separator is not returned.

- * - *

A {@code null} string input will return {@code null}. - * An empty ("") string input will return the empty string. - * A {@code null} separator will return the empty string if the - * input string is not {@code null}.

- * - *

If nothing is found, the empty string is returned.

- * - *
-     * StringUtils.substringAfter(null, *)      = null
-     * StringUtils.substringAfter("", *)        = ""
-     * StringUtils.substringAfter(*, null)      = ""
-     * StringUtils.substringAfter("abc", "a")   = "bc"
-     * StringUtils.substringAfter("abcba", "b") = "cba"
-     * StringUtils.substringAfter("abc", "c")   = ""
-     * StringUtils.substringAfter("abc", "d")   = ""
-     * StringUtils.substringAfter("abc", "")    = "abc"
-     * 
- * - * @param str the String to get a substring from, may be null - * @param separator the String to search for, may be null - * @return the substring after the first occurrence of the separator, - * {@code null} if null String input - * @since 2.0 - */ - public static String substringAfter(final String str, final String separator) { - if (isEmpty(str)) { - return str; - } - if (separator == null) { - return EMPTY; - } - final int pos = str.indexOf(separator); - if (pos == INDEX_NOT_FOUND) { - return EMPTY; - } - return str.substring(pos + separator.length()); - } - - /** - *

Gets the substring before the last occurrence of a separator. - * The separator is not returned.

- * - *

A {@code null} string input will return {@code null}. - * An empty ("") string input will return the empty string. - * An empty or {@code null} separator will return the input string.

- * - *

If nothing is found, the string input is returned.

- * - *
-     * StringUtils.substringBeforeLast(null, *)      = null
-     * StringUtils.substringBeforeLast("", *)        = ""
-     * StringUtils.substringBeforeLast("abcba", "b") = "abc"
-     * StringUtils.substringBeforeLast("abc", "c")   = "ab"
-     * StringUtils.substringBeforeLast("a", "a")     = ""
-     * StringUtils.substringBeforeLast("a", "z")     = "a"
-     * StringUtils.substringBeforeLast("a", null)    = "a"
-     * StringUtils.substringBeforeLast("a", "")      = "a"
-     * 
- * - * @param str the String to get a substring from, may be null - * @param separator the String to search for, may be null - * @return the substring before the last occurrence of the separator, - * {@code null} if null String input - * @since 2.0 - */ - public static String substringBeforeLast(final String str, final String separator) { - if (isEmpty(str) || isEmpty(separator)) { - return str; - } - final int pos = str.lastIndexOf(separator); - if (pos == INDEX_NOT_FOUND) { - return str; - } - return str.substring(0, pos); - } - - /** - *

Gets the substring after the last occurrence of a separator. - * The separator is not returned.

- * - *

A {@code null} string input will return {@code null}. - * An empty ("") string input will return the empty string. - * An empty or {@code null} separator will return the empty string if - * the input string is not {@code null}.

- * - *

If nothing is found, the empty string is returned.

- * - *
-     * StringUtils.substringAfterLast(null, *)      = null
-     * StringUtils.substringAfterLast("", *)        = ""
-     * StringUtils.substringAfterLast(*, "")        = ""
-     * StringUtils.substringAfterLast(*, null)      = ""
-     * StringUtils.substringAfterLast("abc", "a")   = "bc"
-     * StringUtils.substringAfterLast("abcba", "b") = "a"
-     * StringUtils.substringAfterLast("abc", "c")   = ""
-     * StringUtils.substringAfterLast("a", "a")     = ""
-     * StringUtils.substringAfterLast("a", "z")     = ""
-     * 
- * - * @param str the String to get a substring from, may be null - * @param separator the String to search for, may be null - * @return the substring after the last occurrence of the separator, - * {@code null} if null String input - * @since 2.0 - */ - public static String substringAfterLast(final String str, final String separator) { - if (isEmpty(str)) { - return str; - } - if (isEmpty(separator)) { - return EMPTY; - } - final int pos = str.lastIndexOf(separator); - if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) { - return EMPTY; - } - return str.substring(pos + separator.length()); - } - - // Substring between - //----------------------------------------------------------------------- - /** - *

Gets the String that is nested in between two instances of the - * same String.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} tag returns {@code null}.

- * - *
-     * StringUtils.substringBetween(null, *)            = null
-     * StringUtils.substringBetween("", "")             = ""
-     * StringUtils.substringBetween("", "tag")          = null
-     * StringUtils.substringBetween("tagabctag", null)  = null
-     * StringUtils.substringBetween("tagabctag", "")    = ""
-     * StringUtils.substringBetween("tagabctag", "tag") = "abc"
-     * 
- * - * @param str the String containing the substring, may be null - * @param tag the String before and after the substring, may be null - * @return the substring, {@code null} if no match - * @since 2.0 - */ - public static String substringBetween(final String str, final String tag) { - return substringBetween(str, tag, tag); - } - - /** - *

Gets the String that is nested in between two Strings. - * Only the first match is returned.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} open/close returns {@code null} (no match). - * An empty ("") open and close returns an empty string.

- * - *
-     * StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
-     * StringUtils.substringBetween(null, *, *)          = null
-     * StringUtils.substringBetween(*, null, *)          = null
-     * StringUtils.substringBetween(*, *, null)          = null
-     * StringUtils.substringBetween("", "", "")          = ""
-     * StringUtils.substringBetween("", "", "]")         = null
-     * StringUtils.substringBetween("", "[", "]")        = null
-     * StringUtils.substringBetween("yabcz", "", "")     = ""
-     * StringUtils.substringBetween("yabcz", "y", "z")   = "abc"
-     * StringUtils.substringBetween("yabczyabcz", "y", "z")   = "abc"
-     * 
- * - * @param str the String containing the substring, may be null - * @param open the String before the substring, may be null - * @param close the String after the substring, may be null - * @return the substring, {@code null} if no match - * @since 2.0 - */ - public static String substringBetween(final String str, final String open, final String close) { - if (str == null || open == null || close == null) { - return null; - } - final int start = str.indexOf(open); - if (start != INDEX_NOT_FOUND) { - final int end = str.indexOf(close, start + open.length()); - if (end != INDEX_NOT_FOUND) { - return str.substring(start + open.length(), end); - } - } - return null; - } - - /** - *

Searches a String for substrings delimited by a start and end tag, - * returning all matching substrings in an array.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} open/close returns {@code null} (no match). - * An empty ("") open/close returns {@code null} (no match).

- * - *
-     * StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
-     * StringUtils.substringsBetween(null, *, *)            = null
-     * StringUtils.substringsBetween(*, null, *)            = null
-     * StringUtils.substringsBetween(*, *, null)            = null
-     * StringUtils.substringsBetween("", "[", "]")          = []
-     * 
- * - * @param str the String containing the substrings, null returns null, empty returns empty - * @param open the String identifying the start of the substring, empty returns null - * @param close the String identifying the end of the substring, empty returns null - * @return a String Array of substrings, or {@code null} if no match - * @since 2.3 - */ - public static String[] substringsBetween(final String str, final String open, final String close) { - if (str == null || isEmpty(open) || isEmpty(close)) { - return null; - } - final int strLen = str.length(); - if (strLen == 0) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - final int closeLen = close.length(); - final int openLen = open.length(); - final List list = new ArrayList(); - int pos = 0; - while (pos < strLen - closeLen) { - int start = str.indexOf(open, pos); - if (start < 0) { - break; - } - start += openLen; - final int end = str.indexOf(close, start); - if (end < 0) { - break; - } - list.add(str.substring(start, end)); - pos = end + closeLen; - } - if (list.isEmpty()) { - return null; - } - return list.toArray(new String [list.size()]); - } - - // Nested extraction - //----------------------------------------------------------------------- - - // Splitting - //----------------------------------------------------------------------- - /** - *

Splits the provided text into an array, using whitespace as the - * separator. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as one separator. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.split(null)       = null
-     * StringUtils.split("")         = []
-     * StringUtils.split("abc def")  = ["abc", "def"]
-     * StringUtils.split("abc  def") = ["abc", "def"]
-     * StringUtils.split(" abc ")    = ["abc"]
-     * 
- * - * @param str the String to parse, may be null - * @return an array of parsed Strings, {@code null} if null String input - */ - public static String[] split(final String str) { - return split(str, null, -1); - } - - /** - *

Splits the provided text into an array, separator specified. - * This is an alternative to using StringTokenizer.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as one separator. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.split(null, *)         = null
-     * StringUtils.split("", *)           = []
-     * StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
-     * StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
-     * StringUtils.split("a:b:c", '.')    = ["a:b:c"]
-     * StringUtils.split("a b c", ' ')    = ["a", "b", "c"]
-     * 
- * - * @param str the String to parse, may be null - * @param separatorChar the character used as the delimiter - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.0 - */ - public static String[] split(final String str, final char separatorChar) { - return splitWorker(str, separatorChar, false); - } - - /** - *

Splits the provided text into an array, separators specified. - * This is an alternative to using StringTokenizer.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as one separator. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separatorChars splits on whitespace.

- * - *
-     * StringUtils.split(null, *)         = null
-     * StringUtils.split("", *)           = []
-     * StringUtils.split("abc def", null) = ["abc", "def"]
-     * StringUtils.split("abc def", " ")  = ["abc", "def"]
-     * StringUtils.split("abc  def", " ") = ["abc", "def"]
-     * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separatorChars the characters used as the delimiters, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String input - */ - public static String[] split(final String str, final String separatorChars) { - return splitWorker(str, separatorChars, -1, false); - } - - /** - *

Splits the provided text into an array with a maximum length, - * separators specified.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as one separator.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separatorChars splits on whitespace.

- * - *

If more than {@code max} delimited substrings are found, the last - * returned string includes all characters after the first {@code max - 1} - * returned strings (including separator characters).

- * - *
-     * StringUtils.split(null, *, *)            = null
-     * StringUtils.split("", *, *)              = []
-     * StringUtils.split("ab cd ef", null, 0)   = ["ab", "cd", "ef"]
-     * StringUtils.split("ab   cd ef", null, 0) = ["ab", "cd", "ef"]
-     * StringUtils.split("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
-     * StringUtils.split("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separatorChars the characters used as the delimiters, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the - * array. A zero or negative value implies no limit - * @return an array of parsed Strings, {@code null} if null String input - */ - public static String[] split(final String str, final String separatorChars, final int max) { - return splitWorker(str, separatorChars, max, false); - } - - /** - *

Splits the provided text into an array, separator string specified.

- * - *

The separator(s) will not be included in the returned String array. - * Adjacent separators are treated as one separator.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separator splits on whitespace.

- * - *
-     * StringUtils.splitByWholeSeparator(null, *)               = null
-     * StringUtils.splitByWholeSeparator("", *)                 = []
-     * StringUtils.splitByWholeSeparator("ab de fg", null)      = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparator("ab   de fg", null)    = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparator("ab:cd:ef", ":")       = ["ab", "cd", "ef"]
-     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String was input - */ - public static String[] splitByWholeSeparator(final String str, final String separator) { - return splitByWholeSeparatorWorker( str, separator, -1, false ) ; - } - - /** - *

Splits the provided text into an array, separator string specified. - * Returns a maximum of {@code max} substrings.

- * - *

The separator(s) will not be included in the returned String array. - * Adjacent separators are treated as one separator.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separator splits on whitespace.

- * - *
-     * StringUtils.splitByWholeSeparator(null, *, *)               = null
-     * StringUtils.splitByWholeSeparator("", *, *)                 = []
-     * StringUtils.splitByWholeSeparator("ab de fg", null, 0)      = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparator("ab   de fg", null, 0)    = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2)       = ["ab", "cd:ef"]
-     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
-     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the returned - * array. A zero or negative value implies no limit. - * @return an array of parsed Strings, {@code null} if null String was input - */ - public static String[] splitByWholeSeparator( final String str, final String separator, final int max ) { - return splitByWholeSeparatorWorker(str, separator, max, false); - } - - /** - *

Splits the provided text into an array, separator string specified.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separator splits on whitespace.

- * - *
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *)               = null
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *)                 = []
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null)      = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab   de fg", null)    = ["ab", "", "", "de", "fg"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":")       = ["ab", "cd", "ef"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String was input - * @since 2.4 - */ - public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) { - return splitByWholeSeparatorWorker(str, separator, -1, true); - } - - /** - *

Splits the provided text into an array, separator string specified. - * Returns a maximum of {@code max} substrings.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separator splits on whitespace.

- * - *
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *)               = null
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *)                 = []
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0)      = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab   de fg", null, 0)    = ["ab", "", "", "de", "fg"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2)       = ["ab", "cd:ef"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the returned - * array. A zero or negative value implies no limit. - * @return an array of parsed Strings, {@code null} if null String was input - * @since 2.4 - */ - public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) { - return splitByWholeSeparatorWorker(str, separator, max, true); - } - - /** - * Performs the logic for the {@code splitByWholeSeparatorPreserveAllTokens} methods. - * - * @param str the String to parse, may be {@code null} - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the returned - * array. A zero or negative value implies no limit. - * @param preserveAllTokens if {@code true}, adjacent separators are - * treated as empty token separators; if {@code false}, adjacent - * separators are treated as one separator. - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.4 - */ - private static String[] splitByWholeSeparatorWorker( - final String str, final String separator, final int max, final boolean preserveAllTokens) { - if (str == null) { - return null; - } - - final int len = str.length(); - - if (len == 0) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - - if (separator == null || EMPTY.equals(separator)) { - // Split on whitespace. - return splitWorker(str, null, max, preserveAllTokens); - } - - final int separatorLength = separator.length(); - - final ArrayList substrings = new ArrayList(); - int numberOfSubstrings = 0; - int beg = 0; - int end = 0; - while (end < len) { - end = str.indexOf(separator, beg); - - if (end > -1) { - if (end > beg) { - numberOfSubstrings += 1; - - if (numberOfSubstrings == max) { - end = len; - substrings.add(str.substring(beg)); - } else { - // The following is OK, because String.substring( beg, end ) excludes - // the character at the position 'end'. - substrings.add(str.substring(beg, end)); - - // Set the starting point for the next search. - // The following is equivalent to beg = end + (separatorLength - 1) + 1, - // which is the right calculation: - beg = end + separatorLength; - } - } else { - // We found a consecutive occurrence of the separator, so skip it. - if (preserveAllTokens) { - numberOfSubstrings += 1; - if (numberOfSubstrings == max) { - end = len; - substrings.add(str.substring(beg)); - } else { - substrings.add(EMPTY); - } - } - beg = end + separatorLength; - } - } else { - // String.substring( beg ) goes from 'beg' to the end of the String. - substrings.add(str.substring(beg)); - end = len; - } - } - - return substrings.toArray(new String[substrings.size()]); - } - - // ----------------------------------------------------------------------- - /** - *

Splits the provided text into an array, using whitespace as the - * separator, preserving all tokens, including empty tokens created by - * adjacent separators. This is an alternative to using StringTokenizer. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.splitPreserveAllTokens(null)       = null
-     * StringUtils.splitPreserveAllTokens("")         = []
-     * StringUtils.splitPreserveAllTokens("abc def")  = ["abc", "def"]
-     * StringUtils.splitPreserveAllTokens("abc  def") = ["abc", "", "def"]
-     * StringUtils.splitPreserveAllTokens(" abc ")    = ["", "abc", ""]
-     * 
- * - * @param str the String to parse, may be {@code null} - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.1 - */ - public static String[] splitPreserveAllTokens(final String str) { - return splitWorker(str, null, -1, true); - } - - /** - *

Splits the provided text into an array, separator specified, - * preserving all tokens, including empty tokens created by adjacent - * separators. This is an alternative to using StringTokenizer.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.splitPreserveAllTokens(null, *)         = null
-     * StringUtils.splitPreserveAllTokens("", *)           = []
-     * StringUtils.splitPreserveAllTokens("a.b.c", '.')    = ["a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("a..b.c", '.')   = ["a", "", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("a:b:c", '.')    = ["a:b:c"]
-     * StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("a b c", ' ')    = ["a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("a b c ", ' ')   = ["a", "b", "c", ""]
-     * StringUtils.splitPreserveAllTokens("a b c  ", ' ')   = ["a", "b", "c", "", ""]
-     * StringUtils.splitPreserveAllTokens(" a b c", ' ')   = ["", a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("  a b c", ' ')  = ["", "", a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens(" a b c ", ' ')  = ["", a", "b", "c", ""]
-     * 
- * - * @param str the String to parse, may be {@code null} - * @param separatorChar the character used as the delimiter, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.1 - */ - public static String[] splitPreserveAllTokens(final String str, final char separatorChar) { - return splitWorker(str, separatorChar, true); - } - - /** - * Performs the logic for the {@code split} and - * {@code splitPreserveAllTokens} methods that do not return a - * maximum array length. - * - * @param str the String to parse, may be {@code null} - * @param separatorChar the separate character - * @param preserveAllTokens if {@code true}, adjacent separators are - * treated as empty token separators; if {@code false}, adjacent - * separators are treated as one separator. - * @return an array of parsed Strings, {@code null} if null String input - */ - private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) { - // Performance tuned for 2.0 (JDK1.4) - - if (str == null) { - return null; - } - final int len = str.length(); - if (len == 0) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - final List list = new ArrayList(); - int i = 0, start = 0; - boolean match = false; - boolean lastMatch = false; - while (i < len) { - if (str.charAt(i) == separatorChar) { - if (match || preserveAllTokens) { - list.add(str.substring(start, i)); - match = false; - lastMatch = true; - } - start = ++i; - continue; - } - lastMatch = false; - match = true; - i++; - } - if (match || preserveAllTokens && lastMatch) { - list.add(str.substring(start, i)); - } - return list.toArray(new String[list.size()]); - } - - /** - *

Splits the provided text into an array, separators specified, - * preserving all tokens, including empty tokens created by adjacent - * separators. This is an alternative to using StringTokenizer.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separatorChars splits on whitespace.

- * - *
-     * StringUtils.splitPreserveAllTokens(null, *)           = null
-     * StringUtils.splitPreserveAllTokens("", *)             = []
-     * StringUtils.splitPreserveAllTokens("abc def", null)   = ["abc", "def"]
-     * StringUtils.splitPreserveAllTokens("abc def", " ")    = ["abc", "def"]
-     * StringUtils.splitPreserveAllTokens("abc  def", " ")   = ["abc", "", def"]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":")   = ["ab", "cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":")  = ["ab", "cd", "ef", ""]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
-     * StringUtils.splitPreserveAllTokens("ab::cd:ef", ":")  = ["ab", "", cd", "ef"]
-     * StringUtils.splitPreserveAllTokens(":cd:ef", ":")     = ["", cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("::cd:ef", ":")    = ["", "", cd", "ef"]
-     * StringUtils.splitPreserveAllTokens(":cd:ef:", ":")    = ["", cd", "ef", ""]
-     * 
- * - * @param str the String to parse, may be {@code null} - * @param separatorChars the characters used as the delimiters, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.1 - */ - public static String[] splitPreserveAllTokens(final String str, final String separatorChars) { - return splitWorker(str, separatorChars, -1, true); - } - - /** - *

Splits the provided text into an array with a maximum length, - * separators specified, preserving all tokens, including empty tokens - * created by adjacent separators.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * Adjacent separators are treated as one separator.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separatorChars splits on whitespace.

- * - *

If more than {@code max} delimited substrings are found, the last - * returned string includes all characters after the first {@code max - 1} - * returned strings (including separator characters).

- * - *
-     * StringUtils.splitPreserveAllTokens(null, *, *)            = null
-     * StringUtils.splitPreserveAllTokens("", *, *)              = []
-     * StringUtils.splitPreserveAllTokens("ab de fg", null, 0)   = ["ab", "cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 0) = ["ab", "cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
-     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 2) = ["ab", "  de fg"]
-     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 3) = ["ab", "", " de fg"]
-     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 4) = ["ab", "", "", "de fg"]
-     * 
- * - * @param str the String to parse, may be {@code null} - * @param separatorChars the characters used as the delimiters, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the - * array. A zero or negative value implies no limit - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.1 - */ - public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) { - return splitWorker(str, separatorChars, max, true); - } - - /** - * Performs the logic for the {@code split} and - * {@code splitPreserveAllTokens} methods that return a maximum array - * length. - * - * @param str the String to parse, may be {@code null} - * @param separatorChars the separate character - * @param max the maximum number of elements to include in the - * array. A zero or negative value implies no limit. - * @param preserveAllTokens if {@code true}, adjacent separators are - * treated as empty token separators; if {@code false}, adjacent - * separators are treated as one separator. - * @return an array of parsed Strings, {@code null} if null String input - */ - private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) { - // Performance tuned for 2.0 (JDK1.4) - // Direct code is quicker than StringTokenizer. - // Also, StringTokenizer uses isSpace() not isWhitespace() - - if (str == null) { - return null; - } - final int len = str.length(); - if (len == 0) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - final List list = new ArrayList(); - int sizePlus1 = 1; - int i = 0, start = 0; - boolean match = false; - boolean lastMatch = false; - if (separatorChars == null) { - // Null separator means use whitespace - while (i < len) { - if (Character.isWhitespace(str.charAt(i))) { - if (match || preserveAllTokens) { - lastMatch = true; - if (sizePlus1++ == max) { - i = len; - lastMatch = false; - } - list.add(str.substring(start, i)); - match = false; - } - start = ++i; - continue; - } - lastMatch = false; - match = true; - i++; - } - } else if (separatorChars.length() == 1) { - // Optimise 1 character case - final char sep = separatorChars.charAt(0); - while (i < len) { - if (str.charAt(i) == sep) { - if (match || preserveAllTokens) { - lastMatch = true; - if (sizePlus1++ == max) { - i = len; - lastMatch = false; - } - list.add(str.substring(start, i)); - match = false; - } - start = ++i; - continue; - } - lastMatch = false; - match = true; - i++; - } - } else { - // standard case - while (i < len) { - if (separatorChars.indexOf(str.charAt(i)) >= 0) { - if (match || preserveAllTokens) { - lastMatch = true; - if (sizePlus1++ == max) { - i = len; - lastMatch = false; - } - list.add(str.substring(start, i)); - match = false; - } - start = ++i; - continue; - } - lastMatch = false; - match = true; - i++; - } - } - if (match || preserveAllTokens && lastMatch) { - list.add(str.substring(start, i)); - } - return list.toArray(new String[list.size()]); - } - - /** - *

Splits a String by Character type as returned by - * {@code java.lang.Character.getType(char)}. Groups of contiguous - * characters of the same type are returned as complete tokens. - *

-     * StringUtils.splitByCharacterType(null)         = null
-     * StringUtils.splitByCharacterType("")           = []
-     * StringUtils.splitByCharacterType("ab de fg")   = ["ab", " ", "de", " ", "fg"]
-     * StringUtils.splitByCharacterType("ab   de fg") = ["ab", "   ", "de", " ", "fg"]
-     * StringUtils.splitByCharacterType("ab:cd:ef")   = ["ab", ":", "cd", ":", "ef"]
-     * StringUtils.splitByCharacterType("number5")    = ["number", "5"]
-     * StringUtils.splitByCharacterType("fooBar")     = ["foo", "B", "ar"]
-     * StringUtils.splitByCharacterType("foo200Bar")  = ["foo", "200", "B", "ar"]
-     * StringUtils.splitByCharacterType("ASFRules")   = ["ASFR", "ules"]
-     * 
- * @param str the String to split, may be {@code null} - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.4 - */ - public static String[] splitByCharacterType(final String str) { - return splitByCharacterType(str, false); - } - - /** - *

Splits a String by Character type as returned by - * {@code java.lang.Character.getType(char)}. Groups of contiguous - * characters of the same type are returned as complete tokens, with the - * following exception: the character of type - * {@code Character.UPPERCASE_LETTER}, if any, immediately - * preceding a token of type {@code Character.LOWERCASE_LETTER} - * will belong to the following token rather than to the preceding, if any, - * {@code Character.UPPERCASE_LETTER} token. - *

-     * StringUtils.splitByCharacterTypeCamelCase(null)         = null
-     * StringUtils.splitByCharacterTypeCamelCase("")           = []
-     * StringUtils.splitByCharacterTypeCamelCase("ab de fg")   = ["ab", " ", "de", " ", "fg"]
-     * StringUtils.splitByCharacterTypeCamelCase("ab   de fg") = ["ab", "   ", "de", " ", "fg"]
-     * StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef")   = ["ab", ":", "cd", ":", "ef"]
-     * StringUtils.splitByCharacterTypeCamelCase("number5")    = ["number", "5"]
-     * StringUtils.splitByCharacterTypeCamelCase("fooBar")     = ["foo", "Bar"]
-     * StringUtils.splitByCharacterTypeCamelCase("foo200Bar")  = ["foo", "200", "Bar"]
-     * StringUtils.splitByCharacterTypeCamelCase("ASFRules")   = ["ASF", "Rules"]
-     * 
- * @param str the String to split, may be {@code null} - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.4 - */ - public static String[] splitByCharacterTypeCamelCase(final String str) { - return splitByCharacterType(str, true); - } - - /** - *

Splits a String by Character type as returned by - * {@code java.lang.Character.getType(char)}. Groups of contiguous - * characters of the same type are returned as complete tokens, with the - * following exception: if {@code camelCase} is {@code true}, - * the character of type {@code Character.UPPERCASE_LETTER}, if any, - * immediately preceding a token of type {@code Character.LOWERCASE_LETTER} - * will belong to the following token rather than to the preceding, if any, - * {@code Character.UPPERCASE_LETTER} token. - * @param str the String to split, may be {@code null} - * @param camelCase whether to use so-called "camel-case" for letter types - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.4 - */ - private static String[] splitByCharacterType(final String str, final boolean camelCase) { - if (str == null) { - return null; - } - if (str.isEmpty()) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - final char[] c = str.toCharArray(); - final List list = new ArrayList(); - int tokenStart = 0; - int currentType = Character.getType(c[tokenStart]); - for (int pos = tokenStart + 1; pos < c.length; pos++) { - final int type = Character.getType(c[pos]); - if (type == currentType) { - continue; - } - if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) { - final int newTokenStart = pos - 1; - if (newTokenStart != tokenStart) { - list.add(new String(c, tokenStart, newTokenStart - tokenStart)); - tokenStart = newTokenStart; - } - } else { - list.add(new String(c, tokenStart, pos - tokenStart)); - tokenStart = pos; - } - currentType = type; - } - list.add(new String(c, tokenStart, c.length - tokenStart)); - return list.toArray(new String[list.size()]); - } - - // Joining - //----------------------------------------------------------------------- - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No separator is added to the joined String. - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null)            = null
-     * StringUtils.join([])              = ""
-     * StringUtils.join([null])          = ""
-     * StringUtils.join(["a", "b", "c"]) = "abc"
-     * StringUtils.join([null, "", "a"]) = "a"
-     * 
- * - * @param the specific type of values to join together - * @param elements the values to join together, may be null - * @return the joined String, {@code null} if null array input - * @since 2.0 - * @since 3.0 Changed signature to use varargs - */ - public static String join(final T... elements) { - return join(elements, null); - } - - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No delimiter is added before or after the list. - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
-     * StringUtils.join(["a", "b", "c"], null) = "abc"
-     * StringUtils.join([null, "", "a"], ';')  = ";;a"
-     * 
- * - * @param array the array of values to join together, may be null - * @param separator the separator character to use - * @return the joined String, {@code null} if null array input - * @since 2.0 - */ - public static String join(final Object[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final long[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final int[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final short[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final byte[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final char[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final float[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final double[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No delimiter is added before or after the list. - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
-     * StringUtils.join(["a", "b", "c"], null) = "abc"
-     * StringUtils.join([null, "", "a"], ';')  = ";;a"
-     * 
- * - * @param array the array of values to join together, may be null - * @param separator the separator character to use - * @param startIndex the first index to start joining from. It is - * an error to pass in an end index past the end of the array - * @param endIndex the index to stop joining from (exclusive). It is - * an error to pass in an end index past the end of the array - * @return the joined String, {@code null} if null array input - * @since 2.0 - */ - public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - if (array[i] != null) { - buf.append(array[i]); - } - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final long[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final int[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final byte[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final short[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final char[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final double[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final float[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No delimiter is added before or after the list. - * A {@code null} separator is the same as an empty String (""). - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null, *)                = null
-     * StringUtils.join([], *)                  = ""
-     * StringUtils.join([null], *)              = ""
-     * StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
-     * StringUtils.join(["a", "b", "c"], null)  = "abc"
-     * StringUtils.join(["a", "b", "c"], "")    = "abc"
-     * StringUtils.join([null, "", "a"], ',')   = ",,a"
-     * 
- * - * @param array the array of values to join together, may be null - * @param separator the separator character to use, null treated as "" - * @return the joined String, {@code null} if null array input - */ - public static String join(final Object[] array, final String separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No delimiter is added before or after the list. - * A {@code null} separator is the same as an empty String (""). - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null, *, *, *)                = null
-     * StringUtils.join([], *, *, *)                  = ""
-     * StringUtils.join([null], *, *, *)              = ""
-     * StringUtils.join(["a", "b", "c"], "--", 0, 3)  = "a--b--c"
-     * StringUtils.join(["a", "b", "c"], "--", 1, 3)  = "b--c"
-     * StringUtils.join(["a", "b", "c"], "--", 2, 3)  = "c"
-     * StringUtils.join(["a", "b", "c"], "--", 2, 2)  = ""
-     * StringUtils.join(["a", "b", "c"], null, 0, 3)  = "abc"
-     * StringUtils.join(["a", "b", "c"], "", 0, 3)    = "abc"
-     * StringUtils.join([null, "", "a"], ',', 0, 3)   = ",,a"
-     * 
- * - * @param array the array of values to join together, may be null - * @param separator the separator character to use, null treated as "" - * @param startIndex the first index to start joining from. - * @param endIndex the index to stop joining from (exclusive). - * @return the joined String, {@code null} if null array input; or the empty string - * if {@code endIndex - startIndex <= 0}. The number of joined entries is given by - * {@code endIndex - startIndex} - * @throws ArrayIndexOutOfBoundsException ife
- * {@code startIndex < 0} or
- * {@code startIndex >= array.length()} or
- * {@code endIndex < 0} or
- * {@code endIndex > array.length()} - */ - public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - if (separator == null) { - separator = EMPTY; - } - - // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator)) - // (Assuming that all Strings are roughly equally long) - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - - final StringBuilder buf = new StringBuilder(noOfItems * 16); - - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - if (array[i] != null) { - buf.append(array[i]); - } - } - return buf.toString(); - } - - /** - *

Joins the elements of the provided {@code Iterator} into - * a single String containing the provided elements.

- * - *

No delimiter is added before or after the list. Null objects or empty - * strings within the iteration are represented by empty strings.

- * - *

See the examples here: {@link #join(Object[],char)}.

- * - * @param iterator the {@code Iterator} of values to join together, may be null - * @param separator the separator character to use - * @return the joined String, {@code null} if null iterator input - * @since 2.0 - */ - public static String join(final Iterator iterator, final char separator) { - - // handle null, zero and one elements before building a buffer - if (iterator == null) { - return null; - } - if (!iterator.hasNext()) { - return EMPTY; - } - final Object first = iterator.next(); - if (!iterator.hasNext()) { - @SuppressWarnings( "deprecation" ) // ObjectUtils.toString(Object) has been deprecated in 3.2 - final - String result = ObjectUtils.toString(first); - return result; - } - - // two or more elements - final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small - if (first != null) { - buf.append(first); - } - - while (iterator.hasNext()) { - buf.append(separator); - final Object obj = iterator.next(); - if (obj != null) { - buf.append(obj); - } - } - - return buf.toString(); - } - - /** - *

Joins the elements of the provided {@code Iterator} into - * a single String containing the provided elements.

- * - *

No delimiter is added before or after the list. - * A {@code null} separator is the same as an empty String ("").

- * - *

See the examples here: {@link #join(Object[],String)}.

- * - * @param iterator the {@code Iterator} of values to join together, may be null - * @param separator the separator character to use, null treated as "" - * @return the joined String, {@code null} if null iterator input - */ - public static String join(final Iterator iterator, final String separator) { - - // handle null, zero and one elements before building a buffer - if (iterator == null) { - return null; - } - if (!iterator.hasNext()) { - return EMPTY; - } - final Object first = iterator.next(); - if (!iterator.hasNext()) { - @SuppressWarnings( "deprecation" ) // ObjectUtils.toString(Object) has been deprecated in 3.2 - final String result = ObjectUtils.toString(first); - return result; - } - - // two or more elements - final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small - if (first != null) { - buf.append(first); - } - - while (iterator.hasNext()) { - if (separator != null) { - buf.append(separator); - } - final Object obj = iterator.next(); - if (obj != null) { - buf.append(obj); - } - } - return buf.toString(); - } - - /** - *

Joins the elements of the provided {@code Iterable} into - * a single String containing the provided elements.

- * - *

No delimiter is added before or after the list. Null objects or empty - * strings within the iteration are represented by empty strings.

- * - *

See the examples here: {@link #join(Object[],char)}.

- * - * @param iterable the {@code Iterable} providing the values to join together, may be null - * @param separator the separator character to use - * @return the joined String, {@code null} if null iterator input - * @since 2.3 - */ - public static String join(final Iterable iterable, final char separator) { - if (iterable == null) { - return null; - } - return join(iterable.iterator(), separator); - } - - /** - *

Joins the elements of the provided {@code Iterable} into - * a single String containing the provided elements.

- * - *

No delimiter is added before or after the list. - * A {@code null} separator is the same as an empty String ("").

- * - *

See the examples here: {@link #join(Object[],String)}.

- * - * @param iterable the {@code Iterable} providing the values to join together, may be null - * @param separator the separator character to use, null treated as "" - * @return the joined String, {@code null} if null iterator input - * @since 2.3 - */ - public static String join(final Iterable iterable, final String separator) { - if (iterable == null) { - return null; - } - return join(iterable.iterator(), separator); - } - - /** - *

Joins the elements of the provided varargs into a - * single String containing the provided elements.

- * - *

No delimiter is added before or after the list. - * {@code null} elements and separator are treated as empty Strings ("").

- * - *
-     * StringUtils.joinWith(",", {"a", "b"})        = "a,b"
-     * StringUtils.joinWith(",", {"a", "b",""})     = "a,b,"
-     * StringUtils.joinWith(",", {"a", null, "b"})  = "a,,b"
-     * StringUtils.joinWith(null, {"a", "b"})       = "ab"
-     * 
- * - * @param separator the separator character to use, null treated as "" - * @param objects the varargs providing the values to join together. {@code null} elements are treated as "" - * @return the joined String. - * @throws java.lang.IllegalArgumentException if a null varargs is provided - */ - public static String joinWith(final String separator, final Object... objects) { - if (objects == null) { - throw new IllegalArgumentException("Object varargs must not be null"); - } - - final String sanitizedSeparator = defaultString(separator, StringUtils.EMPTY); - - final StringBuilder result = new StringBuilder(); - - final Iterator iterator = Arrays.asList(objects).iterator(); - while (iterator.hasNext()) { - @SuppressWarnings("deprecation") // o.k. to use as long as we do not require java 7 or greater - final String value = ObjectUtils.toString(iterator.next()); - result.append(value); - - if (iterator.hasNext()) { - result.append(sanitizedSeparator); - } - } - - return result.toString(); - } - - // Delete - //----------------------------------------------------------------------- - /** - *

Deletes all whitespaces from a String as defined by - * {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.deleteWhitespace(null)         = null
-     * StringUtils.deleteWhitespace("")           = ""
-     * StringUtils.deleteWhitespace("abc")        = "abc"
-     * StringUtils.deleteWhitespace("   ab  c  ") = "abc"
-     * 
- * - * @param str the String to delete whitespace from, may be null - * @return the String without whitespaces, {@code null} if null String input - */ - public static String deleteWhitespace(final String str) { - if (isEmpty(str)) { - return str; - } - final int sz = str.length(); - final char[] chs = new char[sz]; - int count = 0; - for (int i = 0; i < sz; i++) { - if (!Character.isWhitespace(str.charAt(i))) { - chs[count++] = str.charAt(i); - } - } - if (count == sz) { - return str; - } - return new String(chs, 0, count); - } - - // Remove - //----------------------------------------------------------------------- - /** - *

Removes a substring only if it is at the beginning of a source string, - * otherwise returns the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} search string will return the source string.

- * - *
-     * StringUtils.removeStart(null, *)      = null
-     * StringUtils.removeStart("", *)        = ""
-     * StringUtils.removeStart(*, null)      = *
-     * StringUtils.removeStart("www.domain.com", "www.")   = "domain.com"
-     * StringUtils.removeStart("domain.com", "www.")       = "domain.com"
-     * StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeStart("abc", "")    = "abc"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.1 - */ - public static String removeStart(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (str.startsWith(remove)){ - return str.substring(remove.length()); - } - return str; - } - - /** - *

Case insensitive removal of a substring if it is at the beginning of a source string, - * otherwise returns the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} search string will return the source string.

- * - *
-     * StringUtils.removeStartIgnoreCase(null, *)      = null
-     * StringUtils.removeStartIgnoreCase("", *)        = ""
-     * StringUtils.removeStartIgnoreCase(*, null)      = *
-     * StringUtils.removeStartIgnoreCase("www.domain.com", "www.")   = "domain.com"
-     * StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.")   = "domain.com"
-     * StringUtils.removeStartIgnoreCase("domain.com", "www.")       = "domain.com"
-     * StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeStartIgnoreCase("abc", "")    = "abc"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for (case insensitive) and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.4 - */ - public static String removeStartIgnoreCase(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (startsWithIgnoreCase(str, remove)) { - return str.substring(remove.length()); - } - return str; - } - - /** - *

Removes a substring only if it is at the end of a source string, - * otherwise returns the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} search string will return the source string.

- * - *
-     * StringUtils.removeEnd(null, *)      = null
-     * StringUtils.removeEnd("", *)        = ""
-     * StringUtils.removeEnd(*, null)      = *
-     * StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
-     * StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
-     * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeEnd("abc", "")    = "abc"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.1 - */ - public static String removeEnd(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (str.endsWith(remove)) { - return str.substring(0, str.length() - remove.length()); - } - return str; - } - - /** - *

Case insensitive removal of a substring if it is at the end of a source string, - * otherwise returns the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} search string will return the source string.

- * - *
-     * StringUtils.removeEndIgnoreCase(null, *)      = null
-     * StringUtils.removeEndIgnoreCase("", *)        = ""
-     * StringUtils.removeEndIgnoreCase(*, null)      = *
-     * StringUtils.removeEndIgnoreCase("www.domain.com", ".com.")  = "www.domain.com"
-     * StringUtils.removeEndIgnoreCase("www.domain.com", ".com")   = "www.domain"
-     * StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeEndIgnoreCase("abc", "")    = "abc"
-     * StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
-     * StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for (case insensitive) and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.4 - */ - public static String removeEndIgnoreCase(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (endsWithIgnoreCase(str, remove)) { - return str.substring(0, str.length() - remove.length()); - } - return str; - } - - /** - *

Removes all occurrences of a substring from within the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} remove string will return the source string. - * An empty ("") remove string will return the source string.

- * - *
-     * StringUtils.remove(null, *)        = null
-     * StringUtils.remove("", *)          = ""
-     * StringUtils.remove(*, null)        = *
-     * StringUtils.remove(*, "")          = *
-     * StringUtils.remove("queued", "ue") = "qd"
-     * StringUtils.remove("queued", "zz") = "queued"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.1 - */ - public static String remove(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - return replace(str, remove, EMPTY, -1); - } - - /** - *

Removes all occurrences of a character from within the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string.

- * - *
-     * StringUtils.remove(null, *)       = null
-     * StringUtils.remove("", *)         = ""
-     * StringUtils.remove("queued", 'u') = "qeed"
-     * StringUtils.remove("queued", 'z') = "queued"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the char to search for and remove, may be null - * @return the substring with the char removed if found, - * {@code null} if null String input - * @since 2.1 - */ - public static String remove(final String str, final char remove) { - if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) { - return str; - } - final char[] chars = str.toCharArray(); - int pos = 0; - for (int i = 0; i < chars.length; i++) { - if (chars[i] != remove) { - chars[pos++] = chars[i]; - } - } - return new String(chars, 0, pos); - } - - // Replacing - //----------------------------------------------------------------------- - /** - *

Replaces a String with another String inside a larger String, once.

- * - *

A {@code null} reference passed to this method is a no-op.

- * - *
-     * StringUtils.replaceOnce(null, *, *)        = null
-     * StringUtils.replaceOnce("", *, *)          = ""
-     * StringUtils.replaceOnce("any", null, *)    = "any"
-     * StringUtils.replaceOnce("any", *, null)    = "any"
-     * StringUtils.replaceOnce("any", "", *)      = "any"
-     * StringUtils.replaceOnce("aba", "a", null)  = "aba"
-     * StringUtils.replaceOnce("aba", "a", "")    = "ba"
-     * StringUtils.replaceOnce("aba", "a", "z")   = "zba"
-     * 
- * - * @see #replace(String text, String searchString, String replacement, int max) - * @param text text to search and replace in, may be null - * @param searchString the String to search for, may be null - * @param replacement the String to replace with, may be null - * @return the text with any replacements processed, - * {@code null} if null String input - */ - public static String replaceOnce(final String text, final String searchString, final String replacement) { - return replace(text, searchString, replacement, 1); - } - - /** - * Replaces each substring of the source String that matches the given regular expression with the given - * replacement using the {@link Pattern#DOTALL} option. DOTALL is also know as single-line mode in Perl. This call - * is also equivalent to: - *
    - *
  • {@code source.replaceAll("(?s)" + regex, replacement)}
  • - *
  • {@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement)}
  • - *
- * - * @param source - * the source string - * @param regex - * the regular expression to which this string is to be matched - * @param replacement - * the string to be substituted for each match - * @return The resulting {@code String} - * @see String#replaceAll(String, String) - * @see Pattern#DOTALL - * @since 3.2 - */ - public static String replacePattern(final String source, final String regex, final String replacement) { - return Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement); - } - - /** - * Removes each substring of the source String that matches the given regular expression using the DOTALL option. - * - * @param source - * the source string - * @param regex - * the regular expression to which this string is to be matched - * @return The resulting {@code String} - * @see String#replaceAll(String, String) - * @see Pattern#DOTALL - * @since 3.2 - */ - public static String removePattern(final String source, final String regex) { - return replacePattern(source, regex, StringUtils.EMPTY); - } - - /** - *

Replaces all occurrences of a String within another String.

- * - *

A {@code null} reference passed to this method is a no-op.

- * - *
-     * StringUtils.replace(null, *, *)        = null
-     * StringUtils.replace("", *, *)          = ""
-     * StringUtils.replace("any", null, *)    = "any"
-     * StringUtils.replace("any", *, null)    = "any"
-     * StringUtils.replace("any", "", *)      = "any"
-     * StringUtils.replace("aba", "a", null)  = "aba"
-     * StringUtils.replace("aba", "a", "")    = "b"
-     * StringUtils.replace("aba", "a", "z")   = "zbz"
-     * 
- * - * @see #replace(String text, String searchString, String replacement, int max) - * @param text text to search and replace in, may be null - * @param searchString the String to search for, may be null - * @param replacement the String to replace it with, may be null - * @return the text with any replacements processed, - * {@code null} if null String input - */ - public static String replace(final String text, final String searchString, final String replacement) { - return replace(text, searchString, replacement, -1); - } - - /** - *

Replaces a String with another String inside a larger String, - * for the first {@code max} values of the search String.

- * - *

A {@code null} reference passed to this method is a no-op.

- * - *
-     * StringUtils.replace(null, *, *, *)         = null
-     * StringUtils.replace("", *, *, *)           = ""
-     * StringUtils.replace("any", null, *, *)     = "any"
-     * StringUtils.replace("any", *, null, *)     = "any"
-     * StringUtils.replace("any", "", *, *)       = "any"
-     * StringUtils.replace("any", *, *, 0)        = "any"
-     * StringUtils.replace("abaa", "a", null, -1) = "abaa"
-     * StringUtils.replace("abaa", "a", "", -1)   = "b"
-     * StringUtils.replace("abaa", "a", "z", 0)   = "abaa"
-     * StringUtils.replace("abaa", "a", "z", 1)   = "zbaa"
-     * StringUtils.replace("abaa", "a", "z", 2)   = "zbza"
-     * StringUtils.replace("abaa", "a", "z", -1)  = "zbzz"
-     * 
- * - * @param text text to search and replace in, may be null - * @param searchString the String to search for, may be null - * @param replacement the String to replace it with, may be null - * @param max maximum number of values to replace, or {@code -1} if no maximum - * @return the text with any replacements processed, - * {@code null} if null String input - */ - public static String replace(final String text, final String searchString, final String replacement, int max) { - if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { - return text; - } - int start = 0; - int end = text.indexOf(searchString, start); - if (end == INDEX_NOT_FOUND) { - return text; - } - final int replLength = searchString.length(); - int increase = replacement.length() - replLength; - increase = increase < 0 ? 0 : increase; - increase *= max < 0 ? 16 : max > 64 ? 64 : max; - final StringBuilder buf = new StringBuilder(text.length() + increase); - while (end != INDEX_NOT_FOUND) { - buf.append(text.substring(start, end)).append(replacement); - start = end + replLength; - if (--max == 0) { - break; - } - end = text.indexOf(searchString, start); - } - buf.append(text.substring(start)); - return buf.toString(); - } - - /** - *

- * Replaces all occurrences of Strings within another String. - *

- * - *

- * A {@code null} reference passed to this method is a no-op, or if - * any "search string" or "string to replace" is null, that replace will be - * ignored. This will not repeat. For repeating replaces, call the - * overloaded method. - *

- * - *
-     *  StringUtils.replaceEach(null, *, *)        = null
-     *  StringUtils.replaceEach("", *, *)          = ""
-     *  StringUtils.replaceEach("aba", null, null) = "aba"
-     *  StringUtils.replaceEach("aba", new String[0], null) = "aba"
-     *  StringUtils.replaceEach("aba", null, new String[0]) = "aba"
-     *  StringUtils.replaceEach("aba", new String[]{"a"}, null)  = "aba"
-     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""})  = "b"
-     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"})  = "aba"
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"})  = "wcte"
-     *  (example of how it does not repeat)
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"})  = "dcte"
-     * 
- * - * @param text - * text to search and replace in, no-op if null - * @param searchList - * the Strings to search for, no-op if null - * @param replacementList - * the Strings to replace them with, no-op if null - * @return the text with any replacements processed, {@code null} if - * null String input - * @throws IllegalArgumentException - * if the lengths of the arrays are not the same (null is ok, - * and/or size 0) - * @since 2.4 - */ - public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) { - return replaceEach(text, searchList, replacementList, false, 0); - } - - /** - *

- * Replaces all occurrences of Strings within another String. - *

- * - *

- * A {@code null} reference passed to this method is a no-op, or if - * any "search string" or "string to replace" is null, that replace will be - * ignored. - *

- * - *
-     *  StringUtils.replaceEachRepeatedly(null, *, *) = null
-     *  StringUtils.replaceEachRepeatedly("", *, *) = ""
-     *  StringUtils.replaceEachRepeatedly("aba", null, null) = "aba"
-     *  StringUtils.replaceEachRepeatedly("aba", new String[0], null) = "aba"
-     *  StringUtils.replaceEachRepeatedly("aba", null, new String[0]) = "aba"
-     *  StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, null) = "aba"
-     *  StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}) = "b"
-     *  StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}) = "aba"
-     *  StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
-     *  (example of how it repeats)
-     *  StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "tcte"
-     *  StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}) = IllegalStateException
-     * 
- * - * @param text - * text to search and replace in, no-op if null - * @param searchList - * the Strings to search for, no-op if null - * @param replacementList - * the Strings to replace them with, no-op if null - * @return the text with any replacements processed, {@code null} if - * null String input - * @throws IllegalStateException - * if the search is repeating and there is an endless loop due - * to outputs of one being inputs to another - * @throws IllegalArgumentException - * if the lengths of the arrays are not the same (null is ok, - * and/or size 0) - * @since 2.4 - */ - public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) { - // timeToLive should be 0 if not used or nothing to replace, else it's - // the length of the replace array - final int timeToLive = searchList == null ? 0 : searchList.length; - return replaceEach(text, searchList, replacementList, true, timeToLive); - } - - /** - *

- * Replace all occurrences of Strings within another String. - * This is a private recursive helper method for {@link #replaceEachRepeatedly(String, String[], String[])} and - * {@link #replaceEach(String, String[], String[])} - *

- * - *

- * A {@code null} reference passed to this method is a no-op, or if - * any "search string" or "string to replace" is null, that replace will be - * ignored. - *

- * - *
-     *  StringUtils.replaceEach(null, *, *, *, *) = null
-     *  StringUtils.replaceEach("", *, *, *, *) = ""
-     *  StringUtils.replaceEach("aba", null, null, *, *) = "aba"
-     *  StringUtils.replaceEach("aba", new String[0], null, *, *) = "aba"
-     *  StringUtils.replaceEach("aba", null, new String[0], *, *) = "aba"
-     *  StringUtils.replaceEach("aba", new String[]{"a"}, null, *, *) = "aba"
-     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *, >=0) = "b"
-     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *, >=0) = "aba"
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *, >=0) = "wcte"
-     *  (example of how it repeats)
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false, >=0) = "dcte"
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true, >=2) = "tcte"
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *, *) = IllegalStateException
-     * 
- * - * @param text - * text to search and replace in, no-op if null - * @param searchList - * the Strings to search for, no-op if null - * @param replacementList - * the Strings to replace them with, no-op if null - * @param repeat if true, then replace repeatedly - * until there are no more possible replacements or timeToLive < 0 - * @param timeToLive - * if less than 0 then there is a circular reference and endless - * loop - * @return the text with any replacements processed, {@code null} if - * null String input - * @throws IllegalStateException - * if the search is repeating and there is an endless loop due - * to outputs of one being inputs to another - * @throws IllegalArgumentException - * if the lengths of the arrays are not the same (null is ok, - * and/or size 0) - * @since 2.4 - */ - private static String replaceEach( - final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) { - - // mchyzer Performance note: This creates very few new objects (one major goal) - // let me know if there are performance requests, we can create a harness to measure - - if (text == null || text.isEmpty() || searchList == null || - searchList.length == 0 || replacementList == null || replacementList.length == 0) { - return text; - } - - // if recursing, this shouldn't be less than 0 - if (timeToLive < 0) { - throw new IllegalStateException("Aborting to protect against StackOverflowError - " + - "output of one loop is the input of another"); - } - - final int searchLength = searchList.length; - final int replacementLength = replacementList.length; - - // make sure lengths are ok, these need to be equal - if (searchLength != replacementLength) { - throw new IllegalArgumentException("Search and Replace array lengths don't match: " - + searchLength - + " vs " - + replacementLength); - } - - // keep track of which still have matches - final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; - - // index on index that the match was found - int textIndex = -1; - int replaceIndex = -1; - int tempIndex = -1; - - // index of replace array that will replace the search string found - // NOTE: logic duplicated below START - for (int i = 0; i < searchLength; i++) { - if (noMoreMatchesForReplIndex[i] || searchList[i] == null || - searchList[i].isEmpty() || replacementList[i] == null) { - continue; - } - tempIndex = text.indexOf(searchList[i]); - - // see if we need to keep searching for this - if (tempIndex == -1) { - noMoreMatchesForReplIndex[i] = true; - } else { - if (textIndex == -1 || tempIndex < textIndex) { - textIndex = tempIndex; - replaceIndex = i; - } - } - } - // NOTE: logic mostly below END - - // no search strings found, we are done - if (textIndex == -1) { - return text; - } - - int start = 0; - - // get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit - int increase = 0; - - // count the replacement text elements that are larger than their corresponding text being replaced - for (int i = 0; i < searchList.length; i++) { - if (searchList[i] == null || replacementList[i] == null) { - continue; - } - final int greater = replacementList[i].length() - searchList[i].length(); - if (greater > 0) { - increase += 3 * greater; // assume 3 matches - } - } - // have upper-bound at 20% increase, then let Java take over - increase = Math.min(increase, text.length() / 5); - - final StringBuilder buf = new StringBuilder(text.length() + increase); - - while (textIndex != -1) { - - for (int i = start; i < textIndex; i++) { - buf.append(text.charAt(i)); - } - buf.append(replacementList[replaceIndex]); - - start = textIndex + searchList[replaceIndex].length(); - - textIndex = -1; - replaceIndex = -1; - tempIndex = -1; - // find the next earliest match - // NOTE: logic mostly duplicated above START - for (int i = 0; i < searchLength; i++) { - if (noMoreMatchesForReplIndex[i] || searchList[i] == null || - searchList[i].isEmpty() || replacementList[i] == null) { - continue; - } - tempIndex = text.indexOf(searchList[i], start); - - // see if we need to keep searching for this - if (tempIndex == -1) { - noMoreMatchesForReplIndex[i] = true; - } else { - if (textIndex == -1 || tempIndex < textIndex) { - textIndex = tempIndex; - replaceIndex = i; - } - } - } - // NOTE: logic duplicated above END - - } - final int textLength = text.length(); - for (int i = start; i < textLength; i++) { - buf.append(text.charAt(i)); - } - final String result = buf.toString(); - if (!repeat) { - return result; - } - - return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1); - } - - // Replace, character based - //----------------------------------------------------------------------- - /** - *

Replaces all occurrences of a character in a String with another. - * This is a null-safe version of {@link String#replace(char, char)}.

- * - *

A {@code null} string input returns {@code null}. - * An empty ("") string input returns an empty string.

- * - *
-     * StringUtils.replaceChars(null, *, *)        = null
-     * StringUtils.replaceChars("", *, *)          = ""
-     * StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
-     * StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
-     * 
- * - * @param str String to replace characters in, may be null - * @param searchChar the character to search for, may be null - * @param replaceChar the character to replace, may be null - * @return modified String, {@code null} if null string input - * @since 2.0 - */ - public static String replaceChars(final String str, final char searchChar, final char replaceChar) { - if (str == null) { - return null; - } - return str.replace(searchChar, replaceChar); - } - - /** - *

Replaces multiple characters in a String in one go. - * This method can also be used to delete characters.

- * - *

For example:
- * replaceChars("hello", "ho", "jy") = jelly.

- * - *

A {@code null} string input returns {@code null}. - * An empty ("") string input returns an empty string. - * A null or empty set of search characters returns the input string.

- * - *

The length of the search characters should normally equal the length - * of the replace characters. - * If the search characters is longer, then the extra search characters - * are deleted. - * If the search characters is shorter, then the extra replace characters - * are ignored.

- * - *
-     * StringUtils.replaceChars(null, *, *)           = null
-     * StringUtils.replaceChars("", *, *)             = ""
-     * StringUtils.replaceChars("abc", null, *)       = "abc"
-     * StringUtils.replaceChars("abc", "", *)         = "abc"
-     * StringUtils.replaceChars("abc", "b", null)     = "ac"
-     * StringUtils.replaceChars("abc", "b", "")       = "ac"
-     * StringUtils.replaceChars("abcba", "bc", "yz")  = "ayzya"
-     * StringUtils.replaceChars("abcba", "bc", "y")   = "ayya"
-     * StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
-     * 
- * - * @param str String to replace characters in, may be null - * @param searchChars a set of characters to search for, may be null - * @param replaceChars a set of characters to replace, may be null - * @return modified String, {@code null} if null string input - * @since 2.0 - */ - public static String replaceChars(final String str, final String searchChars, String replaceChars) { - if (isEmpty(str) || isEmpty(searchChars)) { - return str; - } - if (replaceChars == null) { - replaceChars = EMPTY; - } - boolean modified = false; - final int replaceCharsLength = replaceChars.length(); - final int strLength = str.length(); - final StringBuilder buf = new StringBuilder(strLength); - for (int i = 0; i < strLength; i++) { - final char ch = str.charAt(i); - final int index = searchChars.indexOf(ch); - if (index >= 0) { - modified = true; - if (index < replaceCharsLength) { - buf.append(replaceChars.charAt(index)); - } - } else { - buf.append(ch); - } - } - if (modified) { - return buf.toString(); - } - return str; - } - - // Overlay - //----------------------------------------------------------------------- - /** - *

Overlays part of a String with another String.

- * - *

A {@code null} string input returns {@code null}. - * A negative index is treated as zero. - * An index greater than the string length is treated as the string length. - * The start index is always the smaller of the two indices.

- * - *
-     * StringUtils.overlay(null, *, *, *)            = null
-     * StringUtils.overlay("", "abc", 0, 0)          = "abc"
-     * StringUtils.overlay("abcdef", null, 2, 4)     = "abef"
-     * StringUtils.overlay("abcdef", "", 2, 4)       = "abef"
-     * StringUtils.overlay("abcdef", "", 4, 2)       = "abef"
-     * StringUtils.overlay("abcdef", "zzzz", 2, 4)   = "abzzzzef"
-     * StringUtils.overlay("abcdef", "zzzz", 4, 2)   = "abzzzzef"
-     * StringUtils.overlay("abcdef", "zzzz", -1, 4)  = "zzzzef"
-     * StringUtils.overlay("abcdef", "zzzz", 2, 8)   = "abzzzz"
-     * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
-     * StringUtils.overlay("abcdef", "zzzz", 8, 10)  = "abcdefzzzz"
-     * 
- * - * @param str the String to do overlaying in, may be null - * @param overlay the String to overlay, may be null - * @param start the position to start overlaying at - * @param end the position to stop overlaying before - * @return overlayed String, {@code null} if null String input - * @since 2.0 - */ - public static String overlay(final String str, String overlay, int start, int end) { - if (str == null) { - return null; - } - if (overlay == null) { - overlay = EMPTY; - } - final int len = str.length(); - if (start < 0) { - start = 0; - } - if (start > len) { - start = len; - } - if (end < 0) { - end = 0; - } - if (end > len) { - end = len; - } - if (start > end) { - final int temp = start; - start = end; - end = temp; - } - return new StringBuilder(len + start - end + overlay.length() + 1) - .append(str.substring(0, start)) - .append(overlay) - .append(str.substring(end)) - .toString(); - } - - // Chomping - //----------------------------------------------------------------------- - /** - *

Removes one newline from end of a String if it's there, - * otherwise leave it alone. A newline is "{@code \n}", - * "{@code \r}", or "{@code \r\n}".

- * - *

NOTE: This method changed in 2.0. - * It now more closely matches Perl chomp.

- * - *
-     * StringUtils.chomp(null)          = null
-     * StringUtils.chomp("")            = ""
-     * StringUtils.chomp("abc \r")      = "abc "
-     * StringUtils.chomp("abc\n")       = "abc"
-     * StringUtils.chomp("abc\r\n")     = "abc"
-     * StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
-     * StringUtils.chomp("abc\n\r")     = "abc\n"
-     * StringUtils.chomp("abc\n\rabc")  = "abc\n\rabc"
-     * StringUtils.chomp("\r")          = ""
-     * StringUtils.chomp("\n")          = ""
-     * StringUtils.chomp("\r\n")        = ""
-     * 
- * - * @param str the String to chomp a newline from, may be null - * @return String without newline, {@code null} if null String input - */ - public static String chomp(final String str) { - if (isEmpty(str)) { - return str; - } - - if (str.length() == 1) { - final char ch = str.charAt(0); - if (ch == CharUtils.CR || ch == CharUtils.LF) { - return EMPTY; - } - return str; - } - - int lastIdx = str.length() - 1; - final char last = str.charAt(lastIdx); - - if (last == CharUtils.LF) { - if (str.charAt(lastIdx - 1) == CharUtils.CR) { - lastIdx--; - } - } else if (last != CharUtils.CR) { - lastIdx++; - } - return str.substring(0, lastIdx); - } - - /** - *

Removes {@code separator} from the end of - * {@code str} if it's there, otherwise leave it alone.

- * - *

NOTE: This method changed in version 2.0. - * It now more closely matches Perl chomp. - * For the previous behavior, use {@link #substringBeforeLast(String, String)}. - * This method uses {@link String#endsWith(String)}.

- * - *
-     * StringUtils.chomp(null, *)         = null
-     * StringUtils.chomp("", *)           = ""
-     * StringUtils.chomp("foobar", "bar") = "foo"
-     * StringUtils.chomp("foobar", "baz") = "foobar"
-     * StringUtils.chomp("foo", "foo")    = ""
-     * StringUtils.chomp("foo ", "foo")   = "foo "
-     * StringUtils.chomp(" foo", "foo")   = " "
-     * StringUtils.chomp("foo", "foooo")  = "foo"
-     * StringUtils.chomp("foo", "")       = "foo"
-     * StringUtils.chomp("foo", null)     = "foo"
-     * 
- * - * @param str the String to chomp from, may be null - * @param separator separator String, may be null - * @return String without trailing separator, {@code null} if null String input - * @deprecated This feature will be removed in Lang 4.0, use {@link StringUtils#removeEnd(String, String)} instead - */ - @Deprecated - public static String chomp(final String str, final String separator) { - return removeEnd(str,separator); - } - - // Chopping - //----------------------------------------------------------------------- - /** - *

Remove the last character from a String.

- * - *

If the String ends in {@code \r\n}, then remove both - * of them.

- * - *
-     * StringUtils.chop(null)          = null
-     * StringUtils.chop("")            = ""
-     * StringUtils.chop("abc \r")      = "abc "
-     * StringUtils.chop("abc\n")       = "abc"
-     * StringUtils.chop("abc\r\n")     = "abc"
-     * StringUtils.chop("abc")         = "ab"
-     * StringUtils.chop("abc\nabc")    = "abc\nab"
-     * StringUtils.chop("a")           = ""
-     * StringUtils.chop("\r")          = ""
-     * StringUtils.chop("\n")          = ""
-     * StringUtils.chop("\r\n")        = ""
-     * 
- * - * @param str the String to chop last character from, may be null - * @return String without last character, {@code null} if null String input - */ - public static String chop(final String str) { - if (str == null) { - return null; - } - final int strLen = str.length(); - if (strLen < 2) { - return EMPTY; - } - final int lastIdx = strLen - 1; - final String ret = str.substring(0, lastIdx); - final char last = str.charAt(lastIdx); - if (last == CharUtils.LF && ret.charAt(lastIdx - 1) == CharUtils.CR) { - return ret.substring(0, lastIdx - 1); - } - return ret; - } - - // Conversion - //----------------------------------------------------------------------- - - // Padding - //----------------------------------------------------------------------- - /** - *

Repeat a String {@code repeat} times to form a - * new String.

- * - *
-     * StringUtils.repeat(null, 2) = null
-     * StringUtils.repeat("", 0)   = ""
-     * StringUtils.repeat("", 2)   = ""
-     * StringUtils.repeat("a", 3)  = "aaa"
-     * StringUtils.repeat("ab", 2) = "abab"
-     * StringUtils.repeat("a", -2) = ""
-     * 
- * - * @param str the String to repeat, may be null - * @param repeat number of times to repeat str, negative treated as zero - * @return a new String consisting of the original String repeated, - * {@code null} if null String input - */ - public static String repeat(final String str, final int repeat) { - // Performance tuned for 2.0 (JDK1.4) - - if (str == null) { - return null; - } - if (repeat <= 0) { - return EMPTY; - } - final int inputLength = str.length(); - if (repeat == 1 || inputLength == 0) { - return str; - } - if (inputLength == 1 && repeat <= PAD_LIMIT) { - return repeat(str.charAt(0), repeat); - } - - final int outputLength = inputLength * repeat; - switch (inputLength) { - case 1 : - return repeat(str.charAt(0), repeat); - case 2 : - final char ch0 = str.charAt(0); - final char ch1 = str.charAt(1); - final char[] output2 = new char[outputLength]; - for (int i = repeat * 2 - 2; i >= 0; i--, i--) { - output2[i] = ch0; - output2[i + 1] = ch1; - } - return new String(output2); - default : - final StringBuilder buf = new StringBuilder(outputLength); - for (int i = 0; i < repeat; i++) { - buf.append(str); - } - return buf.toString(); - } - } - - /** - *

Repeat a String {@code repeat} times to form a - * new String, with a String separator injected each time.

- * - *
-     * StringUtils.repeat(null, null, 2) = null
-     * StringUtils.repeat(null, "x", 2)  = null
-     * StringUtils.repeat("", null, 0)   = ""
-     * StringUtils.repeat("", "", 2)     = ""
-     * StringUtils.repeat("", "x", 3)    = "xxx"
-     * StringUtils.repeat("?", ", ", 3)  = "?, ?, ?"
-     * 
- * - * @param str the String to repeat, may be null - * @param separator the String to inject, may be null - * @param repeat number of times to repeat str, negative treated as zero - * @return a new String consisting of the original String repeated, - * {@code null} if null String input - * @since 2.5 - */ - public static String repeat(final String str, final String separator, final int repeat) { - if(str == null || separator == null) { - return repeat(str, repeat); - } - // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it - final String result = repeat(str + separator, repeat); - return removeEnd(result, separator); - } - - /** - *

Returns padding using the specified delimiter repeated - * to a given length.

- * - *
-     * StringUtils.repeat('e', 0)  = ""
-     * StringUtils.repeat('e', 3)  = "eee"
-     * StringUtils.repeat('e', -2) = ""
-     * 
- * - *

Note: this method doesn't not support padding with - * Unicode Supplementary Characters - * as they require a pair of {@code char}s to be represented. - * If you are needing to support full I18N of your applications - * consider using {@link #repeat(String, int)} instead. - *

- * - * @param ch character to repeat - * @param repeat number of times to repeat char, negative treated as zero - * @return String with repeated character - * @see #repeat(String, int) - */ - public static String repeat(final char ch, final int repeat) { - if (repeat <= 0) { - return EMPTY; - } - final char[] buf = new char[repeat]; - for (int i = repeat - 1; i >= 0; i--) { - buf[i] = ch; - } - return new String(buf); - } - - /** - *

Right pad a String with spaces (' ').

- * - *

The String is padded to the size of {@code size}.

- * - *
-     * StringUtils.rightPad(null, *)   = null
-     * StringUtils.rightPad("", 3)     = "   "
-     * StringUtils.rightPad("bat", 3)  = "bat"
-     * StringUtils.rightPad("bat", 5)  = "bat  "
-     * StringUtils.rightPad("bat", 1)  = "bat"
-     * StringUtils.rightPad("bat", -1) = "bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @return right padded String or original String if no padding is necessary, - * {@code null} if null String input - */ - public static String rightPad(final String str, final int size) { - return rightPad(str, size, ' '); - } - - /** - *

Right pad a String with a specified character.

- * - *

The String is padded to the size of {@code size}.

- * - *
-     * StringUtils.rightPad(null, *, *)     = null
-     * StringUtils.rightPad("", 3, 'z')     = "zzz"
-     * StringUtils.rightPad("bat", 3, 'z')  = "bat"
-     * StringUtils.rightPad("bat", 5, 'z')  = "batzz"
-     * StringUtils.rightPad("bat", 1, 'z')  = "bat"
-     * StringUtils.rightPad("bat", -1, 'z') = "bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @param padChar the character to pad with - * @return right padded String or original String if no padding is necessary, - * {@code null} if null String input - * @since 2.0 - */ - public static String rightPad(final String str, final int size, final char padChar) { - if (str == null) { - return null; - } - final int pads = size - str.length(); - if (pads <= 0) { - return str; // returns original String when possible - } - if (pads > PAD_LIMIT) { - return rightPad(str, size, String.valueOf(padChar)); - } - return str.concat(repeat(padChar, pads)); - } - - /** - *

Right pad a String with a specified String.

- * - *

The String is padded to the size of {@code size}.

- * - *
-     * StringUtils.rightPad(null, *, *)      = null
-     * StringUtils.rightPad("", 3, "z")      = "zzz"
-     * StringUtils.rightPad("bat", 3, "yz")  = "bat"
-     * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
-     * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
-     * StringUtils.rightPad("bat", 1, "yz")  = "bat"
-     * StringUtils.rightPad("bat", -1, "yz") = "bat"
-     * StringUtils.rightPad("bat", 5, null)  = "bat  "
-     * StringUtils.rightPad("bat", 5, "")    = "bat  "
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @param padStr the String to pad with, null or empty treated as single space - * @return right padded String or original String if no padding is necessary, - * {@code null} if null String input - */ - public static String rightPad(final String str, final int size, String padStr) { - if (str == null) { - return null; - } - if (isEmpty(padStr)) { - padStr = SPACE; - } - final int padLen = padStr.length(); - final int strLen = str.length(); - final int pads = size - strLen; - if (pads <= 0) { - return str; // returns original String when possible - } - if (padLen == 1 && pads <= PAD_LIMIT) { - return rightPad(str, size, padStr.charAt(0)); - } - - if (pads == padLen) { - return str.concat(padStr); - } else if (pads < padLen) { - return str.concat(padStr.substring(0, pads)); - } else { - final char[] padding = new char[pads]; - final char[] padChars = padStr.toCharArray(); - for (int i = 0; i < pads; i++) { - padding[i] = padChars[i % padLen]; - } - return str.concat(new String(padding)); - } - } - - /** - *

Left pad a String with spaces (' ').

- * - *

The String is padded to the size of {@code size}.

- * - *
-     * StringUtils.leftPad(null, *)   = null
-     * StringUtils.leftPad("", 3)     = "   "
-     * StringUtils.leftPad("bat", 3)  = "bat"
-     * StringUtils.leftPad("bat", 5)  = "  bat"
-     * StringUtils.leftPad("bat", 1)  = "bat"
-     * StringUtils.leftPad("bat", -1) = "bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @return left padded String or original String if no padding is necessary, - * {@code null} if null String input - */ - public static String leftPad(final String str, final int size) { - return leftPad(str, size, ' '); - } - - /** - *

Left pad a String with a specified character.

- * - *

Pad to a size of {@code size}.

- * - *
-     * StringUtils.leftPad(null, *, *)     = null
-     * StringUtils.leftPad("", 3, 'z')     = "zzz"
-     * StringUtils.leftPad("bat", 3, 'z')  = "bat"
-     * StringUtils.leftPad("bat", 5, 'z')  = "zzbat"
-     * StringUtils.leftPad("bat", 1, 'z')  = "bat"
-     * StringUtils.leftPad("bat", -1, 'z') = "bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @param padChar the character to pad with - * @return left padded String or original String if no padding is necessary, - * {@code null} if null String input - * @since 2.0 - */ - public static String leftPad(final String str, final int size, final char padChar) { - if (str == null) { - return null; - } - final int pads = size - str.length(); - if (pads <= 0) { - return str; // returns original String when possible - } - if (pads > PAD_LIMIT) { - return leftPad(str, size, String.valueOf(padChar)); - } - return repeat(padChar, pads).concat(str); - } - - /** - *

Left pad a String with a specified String.

- * - *

Pad to a size of {@code size}.

- * - *
-     * StringUtils.leftPad(null, *, *)      = null
-     * StringUtils.leftPad("", 3, "z")      = "zzz"
-     * StringUtils.leftPad("bat", 3, "yz")  = "bat"
-     * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
-     * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
-     * StringUtils.leftPad("bat", 1, "yz")  = "bat"
-     * StringUtils.leftPad("bat", -1, "yz") = "bat"
-     * StringUtils.leftPad("bat", 5, null)  = "  bat"
-     * StringUtils.leftPad("bat", 5, "")    = "  bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @param padStr the String to pad with, null or empty treated as single space - * @return left padded String or original String if no padding is necessary, - * {@code null} if null String input - */ - public static String leftPad(final String str, final int size, String padStr) { - if (str == null) { - return null; - } - if (isEmpty(padStr)) { - padStr = SPACE; - } - final int padLen = padStr.length(); - final int strLen = str.length(); - final int pads = size - strLen; - if (pads <= 0) { - return str; // returns original String when possible - } - if (padLen == 1 && pads <= PAD_LIMIT) { - return leftPad(str, size, padStr.charAt(0)); - } - - if (pads == padLen) { - return padStr.concat(str); - } else if (pads < padLen) { - return padStr.substring(0, pads).concat(str); - } else { - final char[] padding = new char[pads]; - final char[] padChars = padStr.toCharArray(); - for (int i = 0; i < pads; i++) { - padding[i] = padChars[i % padLen]; - } - return new String(padding).concat(str); - } - } - - /** - * Gets a CharSequence length or {@code 0} if the CharSequence is - * {@code null}. - * - * @param cs - * a CharSequence or {@code null} - * @return CharSequence length or {@code 0} if the CharSequence is - * {@code null}. - * @since 2.4 - * @since 3.0 Changed signature from length(String) to length(CharSequence) - */ - public static int length(final CharSequence cs) { - return cs == null ? 0 : cs.length(); - } - - // Centering - //----------------------------------------------------------------------- - /** - *

Centers a String in a larger String of size {@code size} - * using the space character (' ').

- * - *

If the size is less than the String length, the String is returned. - * A {@code null} String returns {@code null}. - * A negative size is treated as zero.

- * - *

Equivalent to {@code center(str, size, " ")}.

- * - *
-     * StringUtils.center(null, *)   = null
-     * StringUtils.center("", 4)     = "    "
-     * StringUtils.center("ab", -1)  = "ab"
-     * StringUtils.center("ab", 4)   = " ab "
-     * StringUtils.center("abcd", 2) = "abcd"
-     * StringUtils.center("a", 4)    = " a  "
-     * 
- * - * @param str the String to center, may be null - * @param size the int size of new String, negative treated as zero - * @return centered String, {@code null} if null String input - */ - public static String center(final String str, final int size) { - return center(str, size, ' '); - } - - /** - *

Centers a String in a larger String of size {@code size}. - * Uses a supplied character as the value to pad the String with.

- * - *

If the size is less than the String length, the String is returned. - * A {@code null} String returns {@code null}. - * A negative size is treated as zero.

- * - *
-     * StringUtils.center(null, *, *)     = null
-     * StringUtils.center("", 4, ' ')     = "    "
-     * StringUtils.center("ab", -1, ' ')  = "ab"
-     * StringUtils.center("ab", 4, ' ')   = " ab "
-     * StringUtils.center("abcd", 2, ' ') = "abcd"
-     * StringUtils.center("a", 4, ' ')    = " a  "
-     * StringUtils.center("a", 4, 'y')    = "yayy"
-     * 
- * - * @param str the String to center, may be null - * @param size the int size of new String, negative treated as zero - * @param padChar the character to pad the new String with - * @return centered String, {@code null} if null String input - * @since 2.0 - */ - public static String center(String str, final int size, final char padChar) { - if (str == null || size <= 0) { - return str; - } - final int strLen = str.length(); - final int pads = size - strLen; - if (pads <= 0) { - return str; - } - str = leftPad(str, strLen + pads / 2, padChar); - str = rightPad(str, size, padChar); - return str; - } - - /** - *

Centers a String in a larger String of size {@code size}. - * Uses a supplied String as the value to pad the String with.

- * - *

If the size is less than the String length, the String is returned. - * A {@code null} String returns {@code null}. - * A negative size is treated as zero.

- * - *
-     * StringUtils.center(null, *, *)     = null
-     * StringUtils.center("", 4, " ")     = "    "
-     * StringUtils.center("ab", -1, " ")  = "ab"
-     * StringUtils.center("ab", 4, " ")   = " ab "
-     * StringUtils.center("abcd", 2, " ") = "abcd"
-     * StringUtils.center("a", 4, " ")    = " a  "
-     * StringUtils.center("a", 4, "yz")   = "yayz"
-     * StringUtils.center("abc", 7, null) = "  abc  "
-     * StringUtils.center("abc", 7, "")   = "  abc  "
-     * 
- * - * @param str the String to center, may be null - * @param size the int size of new String, negative treated as zero - * @param padStr the String to pad the new String with, must not be null or empty - * @return centered String, {@code null} if null String input - * @throws IllegalArgumentException if padStr is {@code null} or empty - */ - public static String center(String str, final int size, String padStr) { - if (str == null || size <= 0) { - return str; - } - if (isEmpty(padStr)) { - padStr = SPACE; - } - final int strLen = str.length(); - final int pads = size - strLen; - if (pads <= 0) { - return str; - } - str = leftPad(str, strLen + pads / 2, padStr); - str = rightPad(str, size, padStr); - return str; - } - - // Case conversion - //----------------------------------------------------------------------- - /** - *

Converts a String to upper case as per {@link String#toUpperCase()}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.upperCase(null)  = null
-     * StringUtils.upperCase("")    = ""
-     * StringUtils.upperCase("aBc") = "ABC"
-     * 
- * - *

Note: As described in the documentation for {@link String#toUpperCase()}, - * the result of this method is affected by the current locale. - * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)} - * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

- * - * @param str the String to upper case, may be null - * @return the upper cased String, {@code null} if null String input - */ - public static String upperCase(final String str) { - if (str == null) { - return null; - } - return str.toUpperCase(); - } - - /** - *

Converts a String to upper case as per {@link String#toUpperCase(Locale)}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.upperCase(null, Locale.ENGLISH)  = null
-     * StringUtils.upperCase("", Locale.ENGLISH)    = ""
-     * StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
-     * 
- * - * @param str the String to upper case, may be null - * @param locale the locale that defines the case transformation rules, must not be null - * @return the upper cased String, {@code null} if null String input - * @since 2.5 - */ - public static String upperCase(final String str, final Locale locale) { - if (str == null) { - return null; - } - return str.toUpperCase(locale); - } - - /** - *

Converts a String to lower case as per {@link String#toLowerCase()}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.lowerCase(null)  = null
-     * StringUtils.lowerCase("")    = ""
-     * StringUtils.lowerCase("aBc") = "abc"
-     * 
- * - *

Note: As described in the documentation for {@link String#toLowerCase()}, - * the result of this method is affected by the current locale. - * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)} - * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

- * - * @param str the String to lower case, may be null - * @return the lower cased String, {@code null} if null String input - */ - public static String lowerCase(final String str) { - if (str == null) { - return null; - } - return str.toLowerCase(); - } - - /** - *

Converts a String to lower case as per {@link String#toLowerCase(Locale)}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.lowerCase(null, Locale.ENGLISH)  = null
-     * StringUtils.lowerCase("", Locale.ENGLISH)    = ""
-     * StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
-     * 
- * - * @param str the String to lower case, may be null - * @param locale the locale that defines the case transformation rules, must not be null - * @return the lower cased String, {@code null} if null String input - * @since 2.5 - */ - public static String lowerCase(final String str, final Locale locale) { - if (str == null) { - return null; - } - return str.toLowerCase(locale); - } - - /** - *

Capitalizes a String changing the first character to title case as - * per {@link Character#toTitleCase(char)}. No other characters are changed.

- * - *

For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#capitalize(String)}. - * A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.capitalize(null)  = null
-     * StringUtils.capitalize("")    = ""
-     * StringUtils.capitalize("cat") = "Cat"
-     * StringUtils.capitalize("cAt") = "CAt"
-     * StringUtils.capitalize("'cat'") = "'cat'"
-     * 
- * - * @param str the String to capitalize, may be null - * @return the capitalized String, {@code null} if null String input - * @see org.apache.commons.lang3.text.WordUtils#capitalize(String) - * @see #uncapitalize(String) - * @since 2.0 - */ - public static String capitalize(final String str) { - int strLen; - if (str == null || (strLen = str.length()) == 0) { - return str; - } - - final char firstChar = str.charAt(0); - final char newChar = Character.toTitleCase(firstChar); - if (firstChar == newChar) { - // already capitalized - return str; - } - - char[] newChars = new char[strLen]; - newChars[0] = newChar; - str.getChars(1,strLen, newChars, 1); - return String.valueOf(newChars); - } - - /** - *

Uncapitalizes a String, changing the first character to lower case as - * per {@link Character#toLowerCase(char)}. No other characters are changed.

- * - *

For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#uncapitalize(String)}. - * A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.uncapitalize(null)  = null
-     * StringUtils.uncapitalize("")    = ""
-     * StringUtils.uncapitalize("cat") = "cat"
-     * StringUtils.uncapitalize("Cat") = "cat"
-     * StringUtils.uncapitalize("CAT") = "cAT"
-     * 
- * - * @param str the String to uncapitalize, may be null - * @return the uncapitalized String, {@code null} if null String input - * @see org.apache.commons.lang3.text.WordUtils#uncapitalize(String) - * @see #capitalize(String) - * @since 2.0 - */ - public static String uncapitalize(final String str) { - int strLen; - if (str == null || (strLen = str.length()) == 0) { - return str; - } - - final char firstChar = str.charAt(0); - final char newChar = Character.toLowerCase(firstChar); - if (firstChar == newChar) { - // already uncapitalized - return str; - } - - char[] newChars = new char[strLen]; - newChars[0] = newChar; - str.getChars(1,strLen, newChars, 1); - return String.valueOf(newChars); - } - - /** - *

Swaps the case of a String changing upper and title case to - * lower case, and lower case to upper case.

- * - *
    - *
  • Upper case character converts to Lower case
  • - *
  • Title case character converts to Lower case
  • - *
  • Lower case character converts to Upper case
  • - *
- * - *

For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#swapCase(String)}. - * A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.swapCase(null)                 = null
-     * StringUtils.swapCase("")                   = ""
-     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
-     * 
- * - *

NOTE: This method changed in Lang version 2.0. - * It no longer performs a word based algorithm. - * If you only use ASCII, you will notice no change. - * That functionality is available in org.apache.commons.lang3.text.WordUtils.

- * - * @param str the String to swap case, may be null - * @return the changed String, {@code null} if null String input - */ - public static String swapCase(final String str) { - if (StringUtils.isEmpty(str)) { - return str; - } - - final char[] buffer = str.toCharArray(); - - for (int i = 0; i < buffer.length; i++) { - final char ch = buffer[i]; - if (Character.isUpperCase(ch)) { - buffer[i] = Character.toLowerCase(ch); - } else if (Character.isTitleCase(ch)) { - buffer[i] = Character.toLowerCase(ch); - } else if (Character.isLowerCase(ch)) { - buffer[i] = Character.toUpperCase(ch); - } - } - return new String(buffer); - } - - // Count matches - //----------------------------------------------------------------------- - /** - *

Counts how many times the substring appears in the larger string.

- * - *

A {@code null} or empty ("") String input returns {@code 0}.

- * - *
-     * StringUtils.countMatches(null, *)       = 0
-     * StringUtils.countMatches("", *)         = 0
-     * StringUtils.countMatches("abba", null)  = 0
-     * StringUtils.countMatches("abba", "")    = 0
-     * StringUtils.countMatches("abba", "a")   = 2
-     * StringUtils.countMatches("abba", "ab")  = 1
-     * StringUtils.countMatches("abba", "xxx") = 0
-     * 
- * - * @param str the CharSequence to check, may be null - * @param sub the substring to count, may be null - * @return the number of occurrences, 0 if either CharSequence is {@code null} - * @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence) - */ - public static int countMatches(final CharSequence str, final CharSequence sub) { - if (isEmpty(str) || isEmpty(sub)) { - return 0; - } - int count = 0; - int idx = 0; - while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) { - count++; - idx += sub.length(); - } - return count; - } - - /** - *

Counts how many times the char appears in the given string.

- * - *

A {@code null} or empty ("") String input returns {@code 0}.

- * - *
-     * StringUtils.countMatches(null, *)       = 0
-     * StringUtils.countMatches("", *)         = 0
-     * StringUtils.countMatches("abba", 0)  = 0
-     * StringUtils.countMatches("abba", 'a')   = 2
-     * StringUtils.countMatches("abba", 'b')  = 2
-     * StringUtils.countMatches("abba", 'x') = 0
-     * 
- * - * @param str the CharSequence to check, may be null - * @param ch the char to count - * @return the number of occurrences, 0 if the CharSequence is {@code null} - * @since 3.4 - */ - public static int countMatches(final CharSequence str, final char ch) { - if (isEmpty(str)) { - return 0; - } - int count = 0; - // We could also call str.toCharArray() for faster look ups but that would generate more garbage. - for (int i = 0; i < str.length(); i++) { - if (ch == str.charAt(i)) { - count++; - } - } - return count; - } - - // Character Tests - //----------------------------------------------------------------------- - /** - *

Checks if the CharSequence contains only Unicode letters.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code false}.

- * - *
-     * StringUtils.isAlpha(null)   = false
-     * StringUtils.isAlpha("")     = false
-     * StringUtils.isAlpha("  ")   = false
-     * StringUtils.isAlpha("abc")  = true
-     * StringUtils.isAlpha("ab2c") = false
-     * StringUtils.isAlpha("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains letters, and is non-null - * @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence) - * @since 3.0 Changed "" to return false and not true - */ - public static boolean isAlpha(final CharSequence cs) { - if (isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLetter(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode letters and - * space (' ').

- * - *

{@code null} will return {@code false} - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isAlphaSpace(null)   = false
-     * StringUtils.isAlphaSpace("")     = true
-     * StringUtils.isAlphaSpace("  ")   = true
-     * StringUtils.isAlphaSpace("abc")  = true
-     * StringUtils.isAlphaSpace("ab c") = true
-     * StringUtils.isAlphaSpace("ab2c") = false
-     * StringUtils.isAlphaSpace("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains letters and space, - * and is non-null - * @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence) - */ - public static boolean isAlphaSpace(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLetter(cs.charAt(i)) == false && cs.charAt(i) != ' ') { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode letters or digits.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code false}.

- * - *
-     * StringUtils.isAlphanumeric(null)   = false
-     * StringUtils.isAlphanumeric("")     = false
-     * StringUtils.isAlphanumeric("  ")   = false
-     * StringUtils.isAlphanumeric("abc")  = true
-     * StringUtils.isAlphanumeric("ab c") = false
-     * StringUtils.isAlphanumeric("ab2c") = true
-     * StringUtils.isAlphanumeric("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains letters or digits, - * and is non-null - * @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence) - * @since 3.0 Changed "" to return false and not true - */ - public static boolean isAlphanumeric(final CharSequence cs) { - if (isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLetterOrDigit(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode letters, digits - * or space ({@code ' '}).

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isAlphanumericSpace(null)   = false
-     * StringUtils.isAlphanumericSpace("")     = true
-     * StringUtils.isAlphanumericSpace("  ")   = true
-     * StringUtils.isAlphanumericSpace("abc")  = true
-     * StringUtils.isAlphanumericSpace("ab c") = true
-     * StringUtils.isAlphanumericSpace("ab2c") = true
-     * StringUtils.isAlphanumericSpace("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains letters, digits or space, - * and is non-null - * @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence) - */ - public static boolean isAlphanumericSpace(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLetterOrDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only ASCII printable characters.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isAsciiPrintable(null)     = false
-     * StringUtils.isAsciiPrintable("")       = true
-     * StringUtils.isAsciiPrintable(" ")      = true
-     * StringUtils.isAsciiPrintable("Ceki")   = true
-     * StringUtils.isAsciiPrintable("ab2c")   = true
-     * StringUtils.isAsciiPrintable("!ab-c~") = true
-     * StringUtils.isAsciiPrintable("\u0020") = true
-     * StringUtils.isAsciiPrintable("\u0021") = true
-     * StringUtils.isAsciiPrintable("\u007e") = true
-     * StringUtils.isAsciiPrintable("\u007f") = false
-     * StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if every character is in the range - * 32 thru 126 - * @since 2.1 - * @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence) - */ - public static boolean isAsciiPrintable(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (CharUtils.isAsciiPrintable(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode digits. - * A decimal point is not a Unicode digit and returns false.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code false}.

- * - *

Note that the method does not allow for a leading sign, either positive or negative. - * Also, if a String passes the numeric test, it may still generate a NumberFormatException - * when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range - * for int or long respectively.

- * - *
-     * StringUtils.isNumeric(null)   = false
-     * StringUtils.isNumeric("")     = false
-     * StringUtils.isNumeric("  ")   = false
-     * StringUtils.isNumeric("123")  = true
-     * StringUtils.isNumeric("\u0967\u0968\u0969")  = true
-     * StringUtils.isNumeric("12 3") = false
-     * StringUtils.isNumeric("ab2c") = false
-     * StringUtils.isNumeric("12-3") = false
-     * StringUtils.isNumeric("12.3") = false
-     * StringUtils.isNumeric("-123") = false
-     * StringUtils.isNumeric("+123") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains digits, and is non-null - * @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence) - * @since 3.0 Changed "" to return false and not true - */ - public static boolean isNumeric(final CharSequence cs) { - if (isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (!Character.isDigit(cs.charAt(i))) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode digits or space - * ({@code ' '}). - * A decimal point is not a Unicode digit and returns false.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isNumericSpace(null)   = false
-     * StringUtils.isNumericSpace("")     = true
-     * StringUtils.isNumericSpace("  ")   = true
-     * StringUtils.isNumericSpace("123")  = true
-     * StringUtils.isNumericSpace("12 3") = true
-     * StringUtils.isNumeric("\u0967\u0968\u0969")  = true
-     * StringUtils.isNumeric("\u0967\u0968 \u0969")  = true
-     * StringUtils.isNumericSpace("ab2c") = false
-     * StringUtils.isNumericSpace("12-3") = false
-     * StringUtils.isNumericSpace("12.3") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains digits or space, - * and is non-null - * @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence) - */ - public static boolean isNumericSpace(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only whitespace.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isWhitespace(null)   = false
-     * StringUtils.isWhitespace("")     = true
-     * StringUtils.isWhitespace("  ")   = true
-     * StringUtils.isWhitespace("abc")  = false
-     * StringUtils.isWhitespace("ab2c") = false
-     * StringUtils.isWhitespace("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains whitespace, and is non-null - * @since 2.0 - * @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence) - */ - public static boolean isWhitespace(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isWhitespace(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only lowercase characters.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code false}.

- * - *
-     * StringUtils.isAllLowerCase(null)   = false
-     * StringUtils.isAllLowerCase("")     = false
-     * StringUtils.isAllLowerCase("  ")   = false
-     * StringUtils.isAllLowerCase("abc")  = true
-     * StringUtils.isAllLowerCase("abC")  = false
-     * StringUtils.isAllLowerCase("ab c") = false
-     * StringUtils.isAllLowerCase("ab1c") = false
-     * StringUtils.isAllLowerCase("ab/c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains lowercase characters, and is non-null - * @since 2.5 - * @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence) - */ - public static boolean isAllLowerCase(final CharSequence cs) { - if (cs == null || isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLowerCase(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only uppercase characters.

- * - *

{@code null} will return {@code false}. - * An empty String (length()=0) will return {@code false}.

- * - *
-     * StringUtils.isAllUpperCase(null)   = false
-     * StringUtils.isAllUpperCase("")     = false
-     * StringUtils.isAllUpperCase("  ")   = false
-     * StringUtils.isAllUpperCase("ABC")  = true
-     * StringUtils.isAllUpperCase("aBC")  = false
-     * StringUtils.isAllUpperCase("A C")  = false
-     * StringUtils.isAllUpperCase("A1C")  = false
-     * StringUtils.isAllUpperCase("A/C")  = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains uppercase characters, and is non-null - * @since 2.5 - * @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence) - */ - public static boolean isAllUpperCase(final CharSequence cs) { - if (cs == null || isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isUpperCase(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - // Defaults - //----------------------------------------------------------------------- - /** - *

Returns either the passed in String, - * or if the String is {@code null}, an empty String ("").

- * - *
-     * StringUtils.defaultString(null)  = ""
-     * StringUtils.defaultString("")    = ""
-     * StringUtils.defaultString("bat") = "bat"
-     * 
- * - * @see ObjectUtils#toString(Object) - * @see String#valueOf(Object) - * @param str the String to check, may be null - * @return the passed in String, or the empty String if it - * was {@code null} - */ - public static String defaultString(final String str) { - return str == null ? EMPTY : str; - } - - /** - *

Returns either the passed in String, or if the String is - * {@code null}, the value of {@code defaultStr}.

- * - *
-     * StringUtils.defaultString(null, "NULL")  = "NULL"
-     * StringUtils.defaultString("", "NULL")    = ""
-     * StringUtils.defaultString("bat", "NULL") = "bat"
-     * 
- * - * @see ObjectUtils#toString(Object,String) - * @see String#valueOf(Object) - * @param str the String to check, may be null - * @param defaultStr the default String to return - * if the input is {@code null}, may be null - * @return the passed in String, or the default if it was {@code null} - */ - public static String defaultString(final String str, final String defaultStr) { - return str == null ? defaultStr : str; - } - - /** - *

Returns either the passed in CharSequence, or if the CharSequence is - * whitespace, empty ("") or {@code null}, the value of {@code defaultStr}.

- * - *
-     * StringUtils.defaultIfBlank(null, "NULL")  = "NULL"
-     * StringUtils.defaultIfBlank("", "NULL")    = "NULL"
-     * StringUtils.defaultIfBlank(" ", "NULL")   = "NULL"
-     * StringUtils.defaultIfBlank("bat", "NULL") = "bat"
-     * StringUtils.defaultIfBlank("", null)      = null
-     * 
- * @param the specific kind of CharSequence - * @param str the CharSequence to check, may be null - * @param defaultStr the default CharSequence to return - * if the input is whitespace, empty ("") or {@code null}, may be null - * @return the passed in CharSequence, or the default - * @see StringUtils#defaultString(String, String) - */ - public static T defaultIfBlank(final T str, final T defaultStr) { - return isBlank(str) ? defaultStr : str; - } - - /** - *

Returns either the passed in CharSequence, or if the CharSequence is - * empty or {@code null}, the value of {@code defaultStr}.

- * - *
-     * StringUtils.defaultIfEmpty(null, "NULL")  = "NULL"
-     * StringUtils.defaultIfEmpty("", "NULL")    = "NULL"
-     * StringUtils.defaultIfEmpty(" ", "NULL")   = " "
-     * StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
-     * StringUtils.defaultIfEmpty("", null)      = null
-     * 
- * @param the specific kind of CharSequence - * @param str the CharSequence to check, may be null - * @param defaultStr the default CharSequence to return - * if the input is empty ("") or {@code null}, may be null - * @return the passed in CharSequence, or the default - * @see StringUtils#defaultString(String, String) - */ - public static T defaultIfEmpty(final T str, final T defaultStr) { - return isEmpty(str) ? defaultStr : str; - } - - // Rotating (circular shift) - //----------------------------------------------------------------------- - /** - *

Rotate (circular shift) a String of {@code shift} characters.

- *
    - *
  • If {@code shift > 0}, right circular shift (ex : ABCDEF => FABCDE)
  • - *
  • If {@code shift < 0}, left circular shift (ex : ABCDEF => BCDEFA)
  • - *
- * - *
-     * StringUtils.rotate(null, *)        = null
-     * StringUtils.rotate("", *)          = ""
-     * StringUtils.rotate("abcdefg", 0)   = "abcdefg"
-     * StringUtils.rotate("abcdefg", 2)   = "fgabcde"
-     * StringUtils.rotate("abcdefg", -2)  = "cdefgab"
-     * StringUtils.rotate("abcdefg", 7)   = "abcdefg"
-     * StringUtils.rotate("abcdefg", -7)  = "abcdefg"
-     * StringUtils.rotate("abcdefg", 9)   = "fgabcde"
-     * StringUtils.rotate("abcdefg", -9)  = "cdefgab"
-     * 
- * - * @param str the String to rotate, may be null - * @param shift number of time to shift (positive : right shift, negative : left shift) - * @return the rotated String, - * or the original String if {@code shift == 0}, - * or {@code null} if null String input - */ - public static String rotate(String str, int shift) { - if (str == null) { - return null; - } - - final int strLen = str.length(); - if (shift == 0 || strLen == 0 || shift % strLen == 0) { - return str; - } - - final StringBuilder builder = new StringBuilder(strLen); - final int offset = - (shift % strLen); - builder.append(substring(str, offset)); - builder.append(substring(str, 0, offset)); - return builder.toString(); - } - - // Reversing - //----------------------------------------------------------------------- - /** - *

Reverses a String as per {@link StringBuilder#reverse()}.

- * - *

A {@code null} String returns {@code null}.

- * - *
-     * StringUtils.reverse(null)  = null
-     * StringUtils.reverse("")    = ""
-     * StringUtils.reverse("bat") = "tab"
-     * 
- * - * @param str the String to reverse, may be null - * @return the reversed String, {@code null} if null String input - */ - public static String reverse(final String str) { - if (str == null) { - return null; - } - return new StringBuilder(str).reverse().toString(); - } - - /** - *

Reverses a String that is delimited by a specific character.

- * - *

The Strings between the delimiters are not reversed. - * Thus java.lang.String becomes String.lang.java (if the delimiter - * is {@code '.'}).

- * - *
-     * StringUtils.reverseDelimited(null, *)      = null
-     * StringUtils.reverseDelimited("", *)        = ""
-     * StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
-     * StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
-     * 
- * - * @param str the String to reverse, may be null - * @param separatorChar the separator character to use - * @return the reversed String, {@code null} if null String input - * @since 2.0 - */ - public static String reverseDelimited(final String str, final char separatorChar) { - if (str == null) { - return null; - } - // could implement manually, but simple way is to reuse other, - // probably slower, methods. - final String[] strs = split(str, separatorChar); - ArrayUtils.reverse(strs); - return join(strs, separatorChar); - } - - // Abbreviating - //----------------------------------------------------------------------- - /** - *

Abbreviates a String using ellipses. This will turn - * "Now is the time for all good men" into "Now is the time for..."

- * - *

Specifically:

- *
    - *
  • If the number of characters in {@code str} is less than or equal to - * {@code maxWidth}, return {@code str}.
  • - *
  • Else abbreviate it to {@code (substring(str, 0, max-3) + "...")}.
  • - *
  • If {@code maxWidth} is less than {@code 4}, throw an - * {@code IllegalArgumentException}.
  • - *
  • In no case will it return a String of length greater than - * {@code maxWidth}.
  • - *
- * - *
-     * StringUtils.abbreviate(null, *)      = null
-     * StringUtils.abbreviate("", 4)        = ""
-     * StringUtils.abbreviate("abcdefg", 6) = "abc..."
-     * StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
-     * StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
-     * StringUtils.abbreviate("abcdefg", 4) = "a..."
-     * StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
-     * 
- * - * @param str the String to check, may be null - * @param maxWidth maximum length of result String, must be at least 4 - * @return abbreviated String, {@code null} if null String input - * @throws IllegalArgumentException if the width is too small - * @since 2.0 - */ - public static String abbreviate(final String str, final int maxWidth) { - return abbreviate(str, 0, maxWidth); - } - - /** - *

Abbreviates a String using ellipses. This will turn - * "Now is the time for all good men" into "...is the time for..."

- * - *

Works like {@code abbreviate(String, int)}, but allows you to specify - * a "left edge" offset. Note that this left edge is not necessarily going to - * be the leftmost character in the result, or the first character following the - * ellipses, but it will appear somewhere in the result. - * - *

In no case will it return a String of length greater than - * {@code maxWidth}.

- * - *
-     * StringUtils.abbreviate(null, *, *)                = null
-     * StringUtils.abbreviate("", 0, 4)                  = ""
-     * StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
-     * StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
-     * StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
-     * StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
-     * StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
-     * StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
-     * StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
-     * StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
-     * StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
-     * StringUtils.abbreviate("abcdefghij", 0, 3)        = IllegalArgumentException
-     * StringUtils.abbreviate("abcdefghij", 5, 6)        = IllegalArgumentException
-     * 
- * - * @param str the String to check, may be null - * @param offset left edge of source String - * @param maxWidth maximum length of result String, must be at least 4 - * @return abbreviated String, {@code null} if null String input - * @throws IllegalArgumentException if the width is too small - * @since 2.0 - */ - public static String abbreviate(final String str, int offset, final int maxWidth) { - if (str == null) { - return null; - } - if (maxWidth < 4) { - throw new IllegalArgumentException("Minimum abbreviation width is 4"); - } - if (str.length() <= maxWidth) { - return str; - } - if (offset > str.length()) { - offset = str.length(); - } - if (str.length() - offset < maxWidth - 3) { - offset = str.length() - (maxWidth - 3); - } - final String abrevMarker = "..."; - if (offset <= 4) { - return str.substring(0, maxWidth - 3) + abrevMarker; - } - if (maxWidth < 7) { - throw new IllegalArgumentException("Minimum abbreviation width with offset is 7"); - } - if (offset + maxWidth - 3 < str.length()) { - return abrevMarker + abbreviate(str.substring(offset), maxWidth - 3); - } - return abrevMarker + str.substring(str.length() - (maxWidth - 3)); - } - - /** - *

Abbreviates a String to the length passed, replacing the middle characters with the supplied - * replacement String.

- * - *

This abbreviation only occurs if the following criteria is met:

- *
    - *
  • Neither the String for abbreviation nor the replacement String are null or empty
  • - *
  • The length to truncate to is less than the length of the supplied String
  • - *
  • The length to truncate to is greater than 0
  • - *
  • The abbreviated String will have enough room for the length supplied replacement String - * and the first and last characters of the supplied String for abbreviation
  • - *
- *

Otherwise, the returned String will be the same as the supplied String for abbreviation. - *

- * - *
-     * StringUtils.abbreviateMiddle(null, null, 0)      = null
-     * StringUtils.abbreviateMiddle("abc", null, 0)      = "abc"
-     * StringUtils.abbreviateMiddle("abc", ".", 0)      = "abc"
-     * StringUtils.abbreviateMiddle("abc", ".", 3)      = "abc"
-     * StringUtils.abbreviateMiddle("abcdef", ".", 4)     = "ab.f"
-     * 
- * - * @param str the String to abbreviate, may be null - * @param middle the String to replace the middle characters with, may be null - * @param length the length to abbreviate {@code str} to. - * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation. - * @since 2.5 - */ - public static String abbreviateMiddle(final String str, final String middle, final int length) { - if (isEmpty(str) || isEmpty(middle)) { - return str; - } - - if (length >= str.length() || length < middle.length()+2) { - return str; - } - - final int targetSting = length-middle.length(); - final int startOffset = targetSting/2+targetSting%2; - final int endOffset = str.length()-targetSting/2; - - final StringBuilder builder = new StringBuilder(length); - builder.append(str.substring(0,startOffset)); - builder.append(middle); - builder.append(str.substring(endOffset)); - - return builder.toString(); - } - - // Difference - //----------------------------------------------------------------------- - /** - *

Compares two Strings, and returns the portion where they differ. - * More precisely, return the remainder of the second String, - * starting from where it's different from the first. This means that - * the difference between "abc" and "ab" is the empty String and not "c".

- * - *

For example, - * {@code difference("i am a machine", "i am a robot") -> "robot"}.

- * - *
-     * StringUtils.difference(null, null) = null
-     * StringUtils.difference("", "") = ""
-     * StringUtils.difference("", "abc") = "abc"
-     * StringUtils.difference("abc", "") = ""
-     * StringUtils.difference("abc", "abc") = ""
-     * StringUtils.difference("abc", "ab") = ""
-     * StringUtils.difference("ab", "abxyz") = "xyz"
-     * StringUtils.difference("abcde", "abxyz") = "xyz"
-     * StringUtils.difference("abcde", "xyz") = "xyz"
-     * 
- * - * @param str1 the first String, may be null - * @param str2 the second String, may be null - * @return the portion of str2 where it differs from str1; returns the - * empty String if they are equal - * @see #indexOfDifference(CharSequence,CharSequence) - * @since 2.0 - */ - public static String difference(final String str1, final String str2) { - if (str1 == null) { - return str2; - } - if (str2 == null) { - return str1; - } - final int at = indexOfDifference(str1, str2); - if (at == INDEX_NOT_FOUND) { - return EMPTY; - } - return str2.substring(at); - } - - /** - *

Compares two CharSequences, and returns the index at which the - * CharSequences begin to differ.

- * - *

For example, - * {@code indexOfDifference("i am a machine", "i am a robot") -> 7}

- * - *
-     * StringUtils.indexOfDifference(null, null) = -1
-     * StringUtils.indexOfDifference("", "") = -1
-     * StringUtils.indexOfDifference("", "abc") = 0
-     * StringUtils.indexOfDifference("abc", "") = 0
-     * StringUtils.indexOfDifference("abc", "abc") = -1
-     * StringUtils.indexOfDifference("ab", "abxyz") = 2
-     * StringUtils.indexOfDifference("abcde", "abxyz") = 2
-     * StringUtils.indexOfDifference("abcde", "xyz") = 0
-     * 
- * - * @param cs1 the first CharSequence, may be null - * @param cs2 the second CharSequence, may be null - * @return the index where cs1 and cs2 begin to differ; -1 if they are equal - * @since 2.0 - * @since 3.0 Changed signature from indexOfDifference(String, String) to - * indexOfDifference(CharSequence, CharSequence) - */ - public static int indexOfDifference(final CharSequence cs1, final CharSequence cs2) { - if (cs1 == cs2) { - return INDEX_NOT_FOUND; - } - if (cs1 == null || cs2 == null) { - return 0; - } - int i; - for (i = 0; i < cs1.length() && i < cs2.length(); ++i) { - if (cs1.charAt(i) != cs2.charAt(i)) { - break; - } - } - if (i < cs2.length() || i < cs1.length()) { - return i; - } - return INDEX_NOT_FOUND; - } - - /** - *

Compares all CharSequences in an array and returns the index at which the - * CharSequences begin to differ.

- * - *

For example, - * indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7

- * - *
-     * StringUtils.indexOfDifference(null) = -1
-     * StringUtils.indexOfDifference(new String[] {}) = -1
-     * StringUtils.indexOfDifference(new String[] {"abc"}) = -1
-     * StringUtils.indexOfDifference(new String[] {null, null}) = -1
-     * StringUtils.indexOfDifference(new String[] {"", ""}) = -1
-     * StringUtils.indexOfDifference(new String[] {"", null}) = 0
-     * StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
-     * StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
-     * StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
-     * StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
-     * StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
-     * StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
-     * StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
-     * StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
-     * StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
-     * StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
-     * StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
-     * 
- * - * @param css array of CharSequences, entries may be null - * @return the index where the strings begin to differ; -1 if they are all equal - * @since 2.4 - * @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...) - */ - public static int indexOfDifference(final CharSequence... css) { - if (css == null || css.length <= 1) { - return INDEX_NOT_FOUND; - } - boolean anyStringNull = false; - boolean allStringsNull = true; - final int arrayLen = css.length; - int shortestStrLen = Integer.MAX_VALUE; - int longestStrLen = 0; - - // find the min and max string lengths; this avoids checking to make - // sure we are not exceeding the length of the string each time through - // the bottom loop. - for (int i = 0; i < arrayLen; i++) { - if (css[i] == null) { - anyStringNull = true; - shortestStrLen = 0; - } else { - allStringsNull = false; - shortestStrLen = Math.min(css[i].length(), shortestStrLen); - longestStrLen = Math.max(css[i].length(), longestStrLen); - } - } - - // handle lists containing all nulls or all empty strings - if (allStringsNull || longestStrLen == 0 && !anyStringNull) { - return INDEX_NOT_FOUND; - } - - // handle lists containing some nulls or some empty strings - if (shortestStrLen == 0) { - return 0; - } - - // find the position with the first difference across all strings - int firstDiff = -1; - for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) { - final char comparisonChar = css[0].charAt(stringPos); - for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) { - if (css[arrayPos].charAt(stringPos) != comparisonChar) { - firstDiff = stringPos; - break; - } - } - if (firstDiff != -1) { - break; - } - } - - if (firstDiff == -1 && shortestStrLen != longestStrLen) { - // we compared all of the characters up to the length of the - // shortest string and didn't find a match, but the string lengths - // vary, so return the length of the shortest string. - return shortestStrLen; - } - return firstDiff; - } - - /** - *

Compares all Strings in an array and returns the initial sequence of - * characters that is common to all of them.

- * - *

For example, - * getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "

- * - *
-     * StringUtils.getCommonPrefix(null) = ""
-     * StringUtils.getCommonPrefix(new String[] {}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
-     * StringUtils.getCommonPrefix(new String[] {null, null}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"", null}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
-     * StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
-     * StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
-     * StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
-     * StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
-     * StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
-     * 
- * - * @param strs array of String objects, entries may be null - * @return the initial sequence of characters that are common to all Strings - * in the array; empty String if the array is null, the elements are all null - * or if there is no common prefix. - * @since 2.4 - */ - public static String getCommonPrefix(final String... strs) { - if (strs == null || strs.length == 0) { - return EMPTY; - } - final int smallestIndexOfDiff = indexOfDifference(strs); - if (smallestIndexOfDiff == INDEX_NOT_FOUND) { - // all strings were identical - if (strs[0] == null) { - return EMPTY; - } - return strs[0]; - } else if (smallestIndexOfDiff == 0) { - // there were no common initial characters - return EMPTY; - } else { - // we found a common initial character sequence - return strs[0].substring(0, smallestIndexOfDiff); - } - } - - // Misc - //----------------------------------------------------------------------- - /** - *

Find the Levenshtein distance between two Strings.

- * - *

This is the number of changes needed to change one String into - * another, where each change is a single character modification (deletion, - * insertion or substitution).

- * - *

The previous implementation of the Levenshtein distance algorithm - * was from http://www.merriampark.com/ld.htm

- * - *

Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError - * which can occur when my Java implementation is used with very large strings.
- * This implementation of the Levenshtein distance algorithm - * is from http://www.merriampark.com/ldjava.htm

- * - *
-     * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance("","")               = 0
-     * StringUtils.getLevenshteinDistance("","a")              = 1
-     * StringUtils.getLevenshteinDistance("aaapppp", "")       = 7
-     * StringUtils.getLevenshteinDistance("frog", "fog")       = 1
-     * StringUtils.getLevenshteinDistance("fly", "ant")        = 3
-     * StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
-     * StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
-     * StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
-     * StringUtils.getLevenshteinDistance("hello", "hallo")    = 1
-     * 
- * - * @param s the first String, must not be null - * @param t the second String, must not be null - * @return result distance - * @throws IllegalArgumentException if either String input {@code null} - * @since 3.0 Changed signature from getLevenshteinDistance(String, String) to - * getLevenshteinDistance(CharSequence, CharSequence) - */ - public static int getLevenshteinDistance(CharSequence s, CharSequence t) { - if (s == null || t == null) { - throw new IllegalArgumentException("Strings must not be null"); - } - - /* - The difference between this impl. and the previous is that, rather - than creating and retaining a matrix of size s.length() + 1 by t.length() + 1, - we maintain two single-dimensional arrays of length s.length() + 1. The first, d, - is the 'current working' distance array that maintains the newest distance cost - counts as we iterate through the characters of String s. Each time we increment - the index of String t we are comparing, d is copied to p, the second int[]. Doing so - allows us to retain the previous cost counts as required by the algorithm (taking - the minimum of the cost count to the left, up one, and diagonally up and to the left - of the current cost count being calculated). (Note that the arrays aren't really - copied anymore, just switched...this is clearly much better than cloning an array - or doing a System.arraycopy() each time through the outer loop.) - - Effectively, the difference between the two implementations is this one does not - cause an out of memory condition when calculating the LD over two very large strings. - */ - - int n = s.length(); // length of s - int m = t.length(); // length of t - - if (n == 0) { - return m; - } else if (m == 0) { - return n; - } - - if (n > m) { - // swap the input strings to consume less memory - final CharSequence tmp = s; - s = t; - t = tmp; - n = m; - m = t.length(); - } - - int p[] = new int[n + 1]; //'previous' cost array, horizontally - int d[] = new int[n + 1]; // cost array, horizontally - int _d[]; //placeholder to assist in swapping p and d - - // indexes into strings s and t - int i; // iterates through s - int j; // iterates through t - - char t_j; // jth character of t - - int cost; // cost - - for (i = 0; i <= n; i++) { - p[i] = i; - } - - for (j = 1; j <= m; j++) { - t_j = t.charAt(j - 1); - d[0] = j; - - for (i = 1; i <= n; i++) { - cost = s.charAt(i - 1) == t_j ? 0 : 1; - // minimum of cell to the left+1, to the top+1, diagonally left and up +cost - d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); - } - - // copy current distance counts to 'previous row' distance counts - _d = p; - p = d; - d = _d; - } - - // our last action in the above loop was to switch d and p, so p now - // actually has the most recent cost counts - return p[n]; - } - - /** - *

Find the Levenshtein distance between two Strings if it's less than or equal to a given - * threshold.

- * - *

This is the number of changes needed to change one String into - * another, where each change is a single character modification (deletion, - * insertion or substitution).

- * - *

This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield - * and Chas Emerick's implementation of the Levenshtein distance algorithm from - * http://www.merriampark.com/ld.htm

- * - *
-     * StringUtils.getLevenshteinDistance(null, *, *)             = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance(*, null, *)             = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance(*, *, -1)               = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance("","", 0)               = 0
-     * StringUtils.getLevenshteinDistance("aaapppp", "", 8)       = 7
-     * StringUtils.getLevenshteinDistance("aaapppp", "", 7)       = 7
-     * StringUtils.getLevenshteinDistance("aaapppp", "", 6))      = -1
-     * StringUtils.getLevenshteinDistance("elephant", "hippo", 7) = 7
-     * StringUtils.getLevenshteinDistance("elephant", "hippo", 6) = -1
-     * StringUtils.getLevenshteinDistance("hippo", "elephant", 7) = 7
-     * StringUtils.getLevenshteinDistance("hippo", "elephant", 6) = -1
-     * 
- * - * @param s the first String, must not be null - * @param t the second String, must not be null - * @param threshold the target threshold, must not be negative - * @return result distance, or {@code -1} if the distance would be greater than the threshold - * @throws IllegalArgumentException if either String input {@code null} or negative threshold - */ - public static int getLevenshteinDistance(CharSequence s, CharSequence t, final int threshold) { - if (s == null || t == null) { - throw new IllegalArgumentException("Strings must not be null"); - } - if (threshold < 0) { - throw new IllegalArgumentException("Threshold must not be negative"); - } - - /* - This implementation only computes the distance if it's less than or equal to the - threshold value, returning -1 if it's greater. The advantage is performance: unbounded - distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only - computing a diagonal stripe of width 2k + 1 of the cost table. - It is also possible to use this to compute the unbounded Levenshtein distance by starting - the threshold at 1 and doubling each time until the distance is found; this is O(dm), where - d is the distance. - - One subtlety comes from needing to ignore entries on the border of our stripe - eg. - p[] = |#|#|#|* - d[] = *|#|#|#| - We must ignore the entry to the left of the leftmost member - We must ignore the entry above the rightmost member - - Another subtlety comes from our stripe running off the matrix if the strings aren't - of the same size. Since string s is always swapped to be the shorter of the two, - the stripe will always run off to the upper right instead of the lower left of the matrix. - - As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1. - In this case we're going to walk a stripe of length 3. The matrix would look like so: - - 1 2 3 4 5 - 1 |#|#| | | | - 2 |#|#|#| | | - 3 | |#|#|#| | - 4 | | |#|#|#| - 5 | | | |#|#| - 6 | | | | |#| - 7 | | | | | | - - Note how the stripe leads off the table as there is no possible way to turn a string of length 5 - into one of length 7 in edit distance of 1. - - Additionally, this implementation decreases memory usage by using two - single-dimensional arrays and swapping them back and forth instead of allocating - an entire n by m matrix. This requires a few minor changes, such as immediately returning - when it's detected that the stripe has run off the matrix and initially filling the arrays with - large values so that entries we don't compute are ignored. - - See Algorithms on Strings, Trees and Sequences by Dan Gusfield for some discussion. - */ - - int n = s.length(); // length of s - int m = t.length(); // length of t - - // if one string is empty, the edit distance is necessarily the length of the other - if (n == 0) { - return m <= threshold ? m : -1; - } else if (m == 0) { - return n <= threshold ? n : -1; - } - - if (n > m) { - // swap the two strings to consume less memory - final CharSequence tmp = s; - s = t; - t = tmp; - n = m; - m = t.length(); - } - - int p[] = new int[n + 1]; // 'previous' cost array, horizontally - int d[] = new int[n + 1]; // cost array, horizontally - int _d[]; // placeholder to assist in swapping p and d - - // fill in starting table values - final int boundary = Math.min(n, threshold) + 1; - for (int i = 0; i < boundary; i++) { - p[i] = i; - } - // these fills ensure that the value above the rightmost entry of our - // stripe will be ignored in following loop iterations - Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE); - Arrays.fill(d, Integer.MAX_VALUE); - - // iterates through t - for (int j = 1; j <= m; j++) { - final char t_j = t.charAt(j - 1); // jth character of t - d[0] = j; - - // compute stripe indices, constrain to array size - final int min = Math.max(1, j - threshold); - final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold); - - // the stripe may lead off of the table if s and t are of different sizes - if (min > max) { - return -1; - } - - // ignore entry left of leftmost - if (min > 1) { - d[min - 1] = Integer.MAX_VALUE; - } - - // iterates through [min, max] in s - for (int i = min; i <= max; i++) { - if (s.charAt(i - 1) == t_j) { - // diagonally left and up - d[i] = p[i - 1]; - } else { - // 1 + minimum of cell to the left, to the top, diagonally left and up - d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]); - } - } - - // copy current distance counts to 'previous row' distance counts - _d = p; - p = d; - d = _d; - } - - // if p[n] is greater than the threshold, there's no guarantee on it being the correct - // distance - if (p[n] <= threshold) { - return p[n]; - } - return -1; - } - - /** - *

Find the Jaro Winkler Distance which indicates the similarity score between two Strings.

- * - *

The Jaro measure is the weighted sum of percentage of matched characters from each file and transposed characters. - * Winkler increased this measure for matching initial characters.

- * - *

This implementation is based on the Jaro Winkler similarity algorithm - * from http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance.

- * - *
-     * StringUtils.getJaroWinklerDistance(null, null)          = IllegalArgumentException
-     * StringUtils.getJaroWinklerDistance("","")               = 0.0
-     * StringUtils.getJaroWinklerDistance("","a")              = 0.0
-     * StringUtils.getJaroWinklerDistance("aaapppp", "")       = 0.0
-     * StringUtils.getJaroWinklerDistance("frog", "fog")       = 0.93
-     * StringUtils.getJaroWinklerDistance("fly", "ant")        = 0.0
-     * StringUtils.getJaroWinklerDistance("elephant", "hippo") = 0.44
-     * StringUtils.getJaroWinklerDistance("hippo", "elephant") = 0.44
-     * StringUtils.getJaroWinklerDistance("hippo", "zzzzzzzz") = 0.0
-     * StringUtils.getJaroWinklerDistance("hello", "hallo")    = 0.88
-     * StringUtils.getJaroWinklerDistance("ABC Corporation", "ABC Corp") = 0.91
-     * StringUtils.getJaroWinklerDistance("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.93
-     * StringUtils.getJaroWinklerDistance("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.94
-     * StringUtils.getJaroWinklerDistance("PENNSYLVANIA", "PENNCISYLVNIA")    = 0.9
-     * 
- * - * @param first the first String, must not be null - * @param second the second String, must not be null - * @return result distance - * @throws IllegalArgumentException if either String input {@code null} - * @since 3.3 - */ - public static double getJaroWinklerDistance(final CharSequence first, final CharSequence second) { - final double DEFAULT_SCALING_FACTOR = 0.1; - - if (first == null || second == null) { - throw new IllegalArgumentException("Strings must not be null"); - } - - final double jaro = score(first,second); - final int cl = commonPrefixLength(first, second); - final double matchScore = Math.round((jaro + (DEFAULT_SCALING_FACTOR * cl * (1.0 - jaro))) *100.0)/100.0; - - return matchScore; - } - - /** - * This method returns the Jaro-Winkler score for string matching. - * @param first the first string to be matched - * @param second the second string to be machted - * @return matching score without scaling factor impact - */ - private static double score(final CharSequence first, final CharSequence second) { - String shorter; - String longer; - - // Determine which String is longer. - if (first.length() > second.length()) { - longer = first.toString().toLowerCase(); - shorter = second.toString().toLowerCase(); - } else { - longer = second.toString().toLowerCase(); - shorter = first.toString().toLowerCase(); - } - - // Calculate the half length() distance of the shorter String. - final int halflength = shorter.length() / 2 + 1; - - // Find the set of matching characters between the shorter and longer strings. Note that - // the set of matching characters may be different depending on the order of the strings. - final String m1 = getSetOfMatchingCharacterWithin(shorter, longer, halflength); - final String m2 = getSetOfMatchingCharacterWithin(longer, shorter, halflength); - - // If one or both of the sets of common characters is empty, then - // there is no similarity between the two strings. - if (m1.length() == 0 || m2.length() == 0) { - return 0.0; - } - - // If the set of common characters is not the same size, then - // there is no similarity between the two strings, either. - if (m1.length() != m2.length()) { - return 0.0; - } - - // Calculate the number of transposition between the two sets - // of common characters. - final int transpositions = transpositions(m1, m2); - - // Calculate the distance. - final double dist = - (m1.length() / ((double)shorter.length()) + - m2.length() / ((double)longer.length()) + - (m1.length() - transpositions) / ((double)m1.length())) / 3.0; - return dist; - } - - /** - *

Find the Fuzzy Distance which indicates the similarity score between two Strings.

- * - *

This string matching algorithm is similar to the algorithms of editors such as Sublime Text, - * TextMate, Atom and others. One point is given for every matched character. Subsequent - * matches yield two bonus points. A higher score indicates a higher similarity.

- * - *
-     * StringUtils.getFuzzyDistance(null, null, null)                                    = IllegalArgumentException
-     * StringUtils.getFuzzyDistance("", "", Locale.ENGLISH)                              = 0
-     * StringUtils.getFuzzyDistance("Workshop", "b", Locale.ENGLISH)                     = 0
-     * StringUtils.getFuzzyDistance("Room", "o", Locale.ENGLISH)                         = 1
-     * StringUtils.getFuzzyDistance("Workshop", "w", Locale.ENGLISH)                     = 1
-     * StringUtils.getFuzzyDistance("Workshop", "ws", Locale.ENGLISH)                    = 2
-     * StringUtils.getFuzzyDistance("Workshop", "wo", Locale.ENGLISH)                    = 4
-     * StringUtils.getFuzzyDistance("Apache Software Foundation", "asf", Locale.ENGLISH) = 3
-     * 
- * - * @param term a full term that should be matched against, must not be null - * @param query the query that will be matched against a term, must not be null - * @param locale This string matching logic is case insensitive. A locale is necessary to normalize - * both Strings to lower case. - * @return result score - * @throws IllegalArgumentException if either String input {@code null} or Locale input {@code null} - * @since 3.4 - */ - public static int getFuzzyDistance(final CharSequence term, final CharSequence query, final Locale locale) { - if (term == null || query == null) { - throw new IllegalArgumentException("Strings must not be null"); - } else if (locale == null) { - throw new IllegalArgumentException("Locale must not be null"); - } - - // fuzzy logic is case insensitive. We normalize the Strings to lower - // case right from the start. Turning characters to lower case - // via Character.toLowerCase(char) is unfortunately insufficient - // as it does not accept a locale. - final String termLowerCase = term.toString().toLowerCase(locale); - final String queryLowerCase = query.toString().toLowerCase(locale); - - // the resulting score - int score = 0; - - // the position in the term which will be scanned next for potential - // query character matches - int termIndex = 0; - - // index of the previously matched character in the term - int previousMatchingCharacterIndex = Integer.MIN_VALUE; - - for (int queryIndex = 0; queryIndex < queryLowerCase.length(); queryIndex++) { - final char queryChar = queryLowerCase.charAt(queryIndex); - - boolean termCharacterMatchFound = false; - for (; termIndex < termLowerCase.length() && !termCharacterMatchFound; termIndex++) { - final char termChar = termLowerCase.charAt(termIndex); - - if (queryChar == termChar) { - // simple character matches result in one point - score++; - - // subsequent character matches further improve - // the score. - if (previousMatchingCharacterIndex + 1 == termIndex) { - score += 2; - } - - previousMatchingCharacterIndex = termIndex; - - // we can leave the nested loop. Every character in the - // query can match at most one character in the term. - termCharacterMatchFound = true; - } - } - } - - return score; - } - - /** - * Gets a set of matching characters between two strings. - * - *

- * - * @param first The first string. - * @param second The second string. - * @param limit The maximum distance to consider. - * @return A string contain the set of common characters. - */ - private static String getSetOfMatchingCharacterWithin(final CharSequence first, final CharSequence second, final int limit) { - final StringBuilder common = new StringBuilder(); - final StringBuilder copy = new StringBuilder(second); - - for (int i = 0; i < first.length(); i++) { - final char ch = first.charAt(i); - boolean found = false; - - // See if the character is within the limit positions away from the original position of that character. - for (int j = Math.max(0, i - limit); !found && j < Math.min(i + limit, second.length()); j++) { - if (copy.charAt(j) == ch) { - found = true; - common.append(ch); - copy.setCharAt(j,'*'); - } - } - } - return common.toString(); - } - - /** - * Calculates the number of transposition between two strings. - * @param first The first string. - * @param second The second string. - * @return The number of transposition between the two strings. - */ - private static int transpositions(final CharSequence first, final CharSequence second) { - int transpositions = 0; - for (int i = 0; i < first.length(); i++) { - if (first.charAt(i) != second.charAt(i)) { - transpositions++; - } - } - return transpositions / 2; - } - - /** - * Calculates the number of characters from the beginning of the strings that match exactly one-to-one, - * up to a maximum of four (4) characters. - * @param first The first string. - * @param second The second string. - * @return A number between 0 and 4. - */ - private static int commonPrefixLength(final CharSequence first, final CharSequence second) { - final int result = getCommonPrefix(first.toString(), second.toString()).length(); - - // Limit the result to 4. - return result > 4 ? 4 : result; - } - - // startsWith - //----------------------------------------------------------------------- - - /** - *

Check if a CharSequence starts with a specified prefix.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case sensitive.

- * - *
-     * StringUtils.startsWith(null, null)      = true
-     * StringUtils.startsWith(null, "abc")     = false
-     * StringUtils.startsWith("abcdef", null)  = false
-     * StringUtils.startsWith("abcdef", "abc") = true
-     * StringUtils.startsWith("ABCDEF", "abc") = false
-     * 
- * - * @see java.lang.String#startsWith(String) - * @param str the CharSequence to check, may be null - * @param prefix the prefix to find, may be null - * @return {@code true} if the CharSequence starts with the prefix, case sensitive, or - * both {@code null} - * @since 2.4 - * @since 3.0 Changed signature from startsWith(String, String) to startsWith(CharSequence, CharSequence) - */ - public static boolean startsWith(final CharSequence str, final CharSequence prefix) { - return startsWith(str, prefix, false); - } - - /** - *

Case insensitive check if a CharSequence starts with a specified prefix.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case insensitive.

- * - *
-     * StringUtils.startsWithIgnoreCase(null, null)      = true
-     * StringUtils.startsWithIgnoreCase(null, "abc")     = false
-     * StringUtils.startsWithIgnoreCase("abcdef", null)  = false
-     * StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
-     * StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
-     * 
- * - * @see java.lang.String#startsWith(String) - * @param str the CharSequence to check, may be null - * @param prefix the prefix to find, may be null - * @return {@code true} if the CharSequence starts with the prefix, case insensitive, or - * both {@code null} - * @since 2.4 - * @since 3.0 Changed signature from startsWithIgnoreCase(String, String) to startsWithIgnoreCase(CharSequence, CharSequence) - */ - public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) { - return startsWith(str, prefix, true); - } - - /** - *

Check if a CharSequence starts with a specified prefix (optionally case insensitive).

- * - * @see java.lang.String#startsWith(String) - * @param str the CharSequence to check, may be null - * @param prefix the prefix to find, may be null - * @param ignoreCase indicates whether the compare should ignore case - * (case insensitive) or not. - * @return {@code true} if the CharSequence starts with the prefix or - * both {@code null} - */ - private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) { - if (str == null || prefix == null) { - return str == null && prefix == null; - } - if (prefix.length() > str.length()) { - return false; - } - return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length()); - } - - /** - *

Check if a CharSequence starts with any of an array of specified strings.

- * - *
-     * StringUtils.startsWithAny(null, null)      = false
-     * StringUtils.startsWithAny(null, new String[] {"abc"})  = false
-     * StringUtils.startsWithAny("abcxyz", null)     = false
-     * StringUtils.startsWithAny("abcxyz", new String[] {""}) = false
-     * StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
-     * StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
-     * 
- * - * @param string the CharSequence to check, may be null - * @param searchStrings the CharSequences to find, may be null or empty - * @return {@code true} if the CharSequence starts with any of the the prefixes, case insensitive, or - * both {@code null} - * @since 2.5 - * @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...) - */ - public static boolean startsWithAny(final CharSequence string, final CharSequence... searchStrings) { - if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) { - return false; - } - for (final CharSequence searchString : searchStrings) { - if (startsWith(string, searchString)) { - return true; - } - } - return false; - } - - // endsWith - //----------------------------------------------------------------------- - - /** - *

Check if a CharSequence ends with a specified suffix.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case sensitive.

- * - *
-     * StringUtils.endsWith(null, null)      = true
-     * StringUtils.endsWith(null, "def")     = false
-     * StringUtils.endsWith("abcdef", null)  = false
-     * StringUtils.endsWith("abcdef", "def") = true
-     * StringUtils.endsWith("ABCDEF", "def") = false
-     * StringUtils.endsWith("ABCDEF", "cde") = false
-     * 
- * - * @see java.lang.String#endsWith(String) - * @param str the CharSequence to check, may be null - * @param suffix the suffix to find, may be null - * @return {@code true} if the CharSequence ends with the suffix, case sensitive, or - * both {@code null} - * @since 2.4 - * @since 3.0 Changed signature from endsWith(String, String) to endsWith(CharSequence, CharSequence) - */ - public static boolean endsWith(final CharSequence str, final CharSequence suffix) { - return endsWith(str, suffix, false); - } - - /** - *

Case insensitive check if a CharSequence ends with a specified suffix.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case insensitive.

- * - *
-     * StringUtils.endsWithIgnoreCase(null, null)      = true
-     * StringUtils.endsWithIgnoreCase(null, "def")     = false
-     * StringUtils.endsWithIgnoreCase("abcdef", null)  = false
-     * StringUtils.endsWithIgnoreCase("abcdef", "def") = true
-     * StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
-     * StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
-     * 
- * - * @see java.lang.String#endsWith(String) - * @param str the CharSequence to check, may be null - * @param suffix the suffix to find, may be null - * @return {@code true} if the CharSequence ends with the suffix, case insensitive, or - * both {@code null} - * @since 2.4 - * @since 3.0 Changed signature from endsWithIgnoreCase(String, String) to endsWithIgnoreCase(CharSequence, CharSequence) - */ - public static boolean endsWithIgnoreCase(final CharSequence str, final CharSequence suffix) { - return endsWith(str, suffix, true); - } - - /** - *

Check if a CharSequence ends with a specified suffix (optionally case insensitive).

- * - * @see java.lang.String#endsWith(String) - * @param str the CharSequence to check, may be null - * @param suffix the suffix to find, may be null - * @param ignoreCase indicates whether the compare should ignore case - * (case insensitive) or not. - * @return {@code true} if the CharSequence starts with the prefix or - * both {@code null} - */ - private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) { - if (str == null || suffix == null) { - return str == null && suffix == null; - } - if (suffix.length() > str.length()) { - return false; - } - final int strOffset = str.length() - suffix.length(); - return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length()); - } - - /** - *

- * Similar to http://www.w3.org/TR/xpath/#function-normalize - * -space - *

- *

- * The function returns the argument string with whitespace normalized by using - * {@link #trim(String)} to remove leading and trailing whitespace - * and then replacing sequences of whitespace characters by a single space. - *

- * In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+ - *

- * Java's regexp pattern \s defines whitespace as [ \t\n\x0B\f\r] - * - *

For reference:

- *
    - *
  • \x0B = vertical tab
  • - *
  • \f = #xC = form feed
  • - *
  • #x20 = space
  • - *
  • #x9 = \t
  • - *
  • #xA = \n
  • - *
  • #xD = \r
  • - *
- * - *

- * The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also - * normalize. Additionally {@link #trim(String)} removes control characters (char <= 32) from both - * ends of this String. - *

- * - * @see Pattern - * @see #trim(String) - * @see http://www.w3.org/TR/xpath/#function-normalize-space - * @param str the source String to normalize whitespaces from, may be null - * @return the modified string with whitespace normalized, {@code null} if null String input - * - * @since 3.0 - */ - public static String normalizeSpace(final String str) { - // LANG-1020: Improved performance significantly by normalizing manually instead of using regex - // See https://github.com/librucha/commons-lang-normalizespaces-benchmark for performance test - if (isEmpty(str)) { - return str; - } - final int size = str.length(); - final char[] newChars = new char[size]; - int count = 0; - int whitespacesCount = 0; - boolean startWhitespaces = true; - for (int i = 0; i < size; i++) { - char actualChar = str.charAt(i); - boolean isWhitespace = Character.isWhitespace(actualChar); - if (!isWhitespace) { - startWhitespaces = false; - newChars[count++] = (actualChar == 160 ? 32 : actualChar); - whitespacesCount = 0; - } else { - if (whitespacesCount == 0 && !startWhitespaces) { - newChars[count++] = SPACE.charAt(0); - } - whitespacesCount++; - } - } - if (startWhitespaces) { - return EMPTY; - } - return new String(newChars, 0, count - (whitespacesCount > 0 ? 1 : 0)); - } - - /** - *

Check if a CharSequence ends with any of an array of specified strings.

- * - *
-     * StringUtils.endsWithAny(null, null)      = false
-     * StringUtils.endsWithAny(null, new String[] {"abc"})  = false
-     * StringUtils.endsWithAny("abcxyz", null)     = false
-     * StringUtils.endsWithAny("abcxyz", new String[] {""}) = true
-     * StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true
-     * StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
-     * 
- * - * @param string the CharSequence to check, may be null - * @param searchStrings the CharSequences to find, may be null or empty - * @return {@code true} if the CharSequence ends with any of the the prefixes, case insensitive, or - * both {@code null} - * @since 3.0 - */ - public static boolean endsWithAny(final CharSequence string, final CharSequence... searchStrings) { - if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) { - return false; - } - for (final CharSequence searchString : searchStrings) { - if (endsWith(string, searchString)) { - return true; - } - } - return false; - } - - /** - * Appends the suffix to the end of the string if the string does not - * already end in the suffix. - * - * @param str The string. - * @param suffix The suffix to append to the end of the string. - * @param ignoreCase Indicates whether the compare should ignore case. - * @param suffixes Additional suffixes that are valid terminators (optional). - * - * @return A new String if suffix was appened, the same string otherwise. - */ - private static String appendIfMissing(final String str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes) { - if (str == null || isEmpty(suffix) || endsWith(str, suffix, ignoreCase)) { - return str; - } - if (suffixes != null && suffixes.length > 0) { - for (final CharSequence s : suffixes) { - if (endsWith(str, s, ignoreCase)) { - return str; - } - } - } - return str + suffix.toString(); - } - - /** - * Appends the suffix to the end of the string if the string does not - * already end with any the suffixes. - * - *
-     * StringUtils.appendIfMissing(null, null) = null
-     * StringUtils.appendIfMissing("abc", null) = "abc"
-     * StringUtils.appendIfMissing("", "xyz") = "xyz"
-     * StringUtils.appendIfMissing("abc", "xyz") = "abcxyz"
-     * StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz"
-     * StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz"
-     * 
- *

With additional suffixes,

- *
-     * StringUtils.appendIfMissing(null, null, null) = null
-     * StringUtils.appendIfMissing("abc", null, null) = "abc"
-     * StringUtils.appendIfMissing("", "xyz", null) = "xyz"
-     * StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
-     * StringUtils.appendIfMissing("abc", "xyz", "") = "abc"
-     * StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz"
-     * StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz"
-     * StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno"
-     * StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz"
-     * StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz"
-     * 
- * - * @param str The string. - * @param suffix The suffix to append to the end of the string. - * @param suffixes Additional suffixes that are valid terminators. - * - * @return A new String if suffix was appened, the same string otherwise. - * - * @since 3.2 - */ - public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) { - return appendIfMissing(str, suffix, false, suffixes); - } - - /** - * Appends the suffix to the end of the string if the string does not - * already end, case insensitive, with any of the suffixes. - * - *
-     * StringUtils.appendIfMissingIgnoreCase(null, null) = null
-     * StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc"
-     * StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz"
-     * StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz"
-     * StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz"
-     * StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ"
-     * 
- *

With additional suffixes,

- *
-     * StringUtils.appendIfMissingIgnoreCase(null, null, null) = null
-     * StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc"
-     * StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz"
-     * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
-     * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc"
-     * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "axyz"
-     * StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz"
-     * StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno"
-     * StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ"
-     * StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO"
-     * 
- * - * @param str The string. - * @param suffix The suffix to append to the end of the string. - * @param suffixes Additional suffixes that are valid terminators. - * - * @return A new String if suffix was appened, the same string otherwise. - * - * @since 3.2 - */ - public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) { - return appendIfMissing(str, suffix, true, suffixes); - } - - /** - * Prepends the prefix to the start of the string if the string does not - * already start with any of the prefixes. - * - * @param str The string. - * @param prefix The prefix to prepend to the start of the string. - * @param ignoreCase Indicates whether the compare should ignore case. - * @param prefixes Additional prefixes that are valid (optional). - * - * @return A new String if prefix was prepended, the same string otherwise. - */ - private static String prependIfMissing(final String str, final CharSequence prefix, final boolean ignoreCase, final CharSequence... prefixes) { - if (str == null || isEmpty(prefix) || startsWith(str, prefix, ignoreCase)) { - return str; - } - if (prefixes != null && prefixes.length > 0) { - for (final CharSequence p : prefixes) { - if (startsWith(str, p, ignoreCase)) { - return str; - } - } - } - return prefix.toString() + str; - } - - /** - * Prepends the prefix to the start of the string if the string does not - * already start with any of the prefixes. - * - *
-     * StringUtils.prependIfMissing(null, null) = null
-     * StringUtils.prependIfMissing("abc", null) = "abc"
-     * StringUtils.prependIfMissing("", "xyz") = "xyz"
-     * StringUtils.prependIfMissing("abc", "xyz") = "xyzabc"
-     * StringUtils.prependIfMissing("xyzabc", "xyz") = "xyzabc"
-     * StringUtils.prependIfMissing("XYZabc", "xyz") = "xyzXYZabc"
-     * 
- *

With additional prefixes,

- *
-     * StringUtils.prependIfMissing(null, null, null) = null
-     * StringUtils.prependIfMissing("abc", null, null) = "abc"
-     * StringUtils.prependIfMissing("", "xyz", null) = "xyz"
-     * StringUtils.prependIfMissing("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
-     * StringUtils.prependIfMissing("abc", "xyz", "") = "abc"
-     * StringUtils.prependIfMissing("abc", "xyz", "mno") = "xyzabc"
-     * StringUtils.prependIfMissing("xyzabc", "xyz", "mno") = "xyzabc"
-     * StringUtils.prependIfMissing("mnoabc", "xyz", "mno") = "mnoabc"
-     * StringUtils.prependIfMissing("XYZabc", "xyz", "mno") = "xyzXYZabc"
-     * StringUtils.prependIfMissing("MNOabc", "xyz", "mno") = "xyzMNOabc"
-     * 
- * - * @param str The string. - * @param prefix The prefix to prepend to the start of the string. - * @param prefixes Additional prefixes that are valid. - * - * @return A new String if prefix was prepended, the same string otherwise. - * - * @since 3.2 - */ - public static String prependIfMissing(final String str, final CharSequence prefix, final CharSequence... prefixes) { - return prependIfMissing(str, prefix, false, prefixes); - } - - /** - * Prepends the prefix to the start of the string if the string does not - * already start, case insensitive, with any of the prefixes. - * - *
-     * StringUtils.prependIfMissingIgnoreCase(null, null) = null
-     * StringUtils.prependIfMissingIgnoreCase("abc", null) = "abc"
-     * StringUtils.prependIfMissingIgnoreCase("", "xyz") = "xyz"
-     * StringUtils.prependIfMissingIgnoreCase("abc", "xyz") = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz") = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz") = "XYZabc"
-     * 
- *

With additional prefixes,

- *
-     * StringUtils.prependIfMissingIgnoreCase(null, null, null) = null
-     * StringUtils.prependIfMissingIgnoreCase("abc", null, null) = "abc"
-     * StringUtils.prependIfMissingIgnoreCase("", "xyz", null) = "xyz"
-     * StringUtils.prependIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "") = "abc"
-     * StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "mno") = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz", "mno") = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("mnoabc", "xyz", "mno") = "mnoabc"
-     * StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz", "mno") = "XYZabc"
-     * StringUtils.prependIfMissingIgnoreCase("MNOabc", "xyz", "mno") = "MNOabc"
-     * 
- * - * @param str The string. - * @param prefix The prefix to prepend to the start of the string. - * @param prefixes Additional prefixes that are valid (optional). - * - * @return A new String if prefix was prepended, the same string otherwise. - * - * @since 3.2 - */ - public static String prependIfMissingIgnoreCase(final String str, final CharSequence prefix, final CharSequence... prefixes) { - return prependIfMissing(str, prefix, true, prefixes); - } - - /** - * Converts a byte[] to a String using the specified character encoding. - * - * @param bytes - * the byte array to read from - * @param charsetName - * the encoding to use, if null then use the platform default - * @return a new String - * @throws UnsupportedEncodingException - * If the named charset is not supported - * @throws NullPointerException - * if the input is null - * @deprecated use {@link StringUtils#toEncodedString(byte[], Charset)} instead of String constants in your code - * @since 3.1 - */ - @Deprecated - public static String toString(final byte[] bytes, final String charsetName) throws UnsupportedEncodingException { - return charsetName != null ? new String(bytes, charsetName) : new String(bytes, Charset.defaultCharset()); - } - - /** - * Converts a byte[] to a String using the specified character encoding. - * - * @param bytes - * the byte array to read from - * @param charset - * the encoding to use, if null then use the platform default - * @return a new String - * @throws NullPointerException - * if {@code bytes} is null - * @since 3.2 - * @since 3.3 No longer throws {@link UnsupportedEncodingException}. - */ - public static String toEncodedString(final byte[] bytes, final Charset charset) { - return new String(bytes, charset != null ? charset : Charset.defaultCharset()); - } - - /** - *

- * Wraps a string with a char. - *

- * - *
-     * StringUtils.wrap(null, *)        = null
-     * StringUtils.wrap("", *)          = ""
-     * StringUtils.wrap("ab", '\0')     = "ab"
-     * StringUtils.wrap("ab", 'x')      = "xabx"
-     * StringUtils.wrap("ab", '\'')     = "'ab'"
-     * StringUtils.wrap("\"ab\"", '\"') = "\"\"ab\"\""
-     * 
- * - * @param str - * the string to be wrapped, may be {@code null} - * @param wrapWith - * the char that will wrap {@code str} - * @return the wrapped string, or {@code null} if {@code str==null} - * @since 3.4 - */ - public static String wrap(final String str, final char wrapWith) { - - if (isEmpty(str) || wrapWith == '\0') { - return str; - } - - return wrapWith + str + wrapWith; - } - - /** - *

- * Wraps a String with another String. - *

- * - *

- * A {@code null} input String returns {@code null}. - *

- * - *
-     * StringUtils.wrap(null, *)         = null
-     * StringUtils.wrap("", *)           = ""
-     * StringUtils.wrap("ab", null)      = "ab"
-     * StringUtils.wrap("ab", "x")       = "xabx"
-     * StringUtils.wrap("ab", "\"")      = "\"ab\""
-     * StringUtils.wrap("\"ab\"", "\"")  = "\"\"ab\"\""
-     * StringUtils.wrap("ab", "'")       = "'ab'"
-     * StringUtils.wrap("'abcd'", "'")   = "''abcd''"
-     * StringUtils.wrap("\"abcd\"", "'") = "'\"abcd\"'"
-     * StringUtils.wrap("'abcd'", "\"")  = "\"'abcd'\""
-     * 
- * - * @param str - * the String to be wrapper, may be null - * @param wrapWith - * the String that will wrap str - * @return wrapped String, {@code null} if null String input - * @since 3.4 - */ - public static String wrap(final String str, final String wrapWith) { - - if (isEmpty(str) || isEmpty(wrapWith)) { - return str; - } - - return wrapWith.concat(str).concat(wrapWith); - } -} diff --git a/All/Genesis-OOB/Genesis#33/new/changes.xml b/All/Genesis-OOB/Genesis#33/new/changes.xml deleted file mode 100755 index 65e0b3d..0000000 --- a/All/Genesis-OOB/Genesis#33/new/changes.xml +++ /dev/null @@ -1,814 +0,0 @@ - - - - - Apache Commons Lang Changes - - - - - Replace StringBuilder with String concatenation for better optimization - Deprecate SystemUtils.FILE_SEPARATOR and SystemUtils.PATH_SEPARATOR - FastDateFormat APIs that use a StringBuilder - Ability to throw checked exceptions without declaring them - Several predefined ISO FastDateFormats in DateFormatUtils are incorrect - StringIndexOutOfBoundsException or field over-write for large year fields in FastDateParser - Implement ParsePosition api for FastDateParser - StrLookup.systemPropertiesLookup() no longer reacts on changes on system properties - EnumUtils *BitVector issue with more than 32 values Enum - Capitalize javadoc is incorrect - Add check for duplicate event listener in EventListenerSupport - FastDateParser_TimeZoneStrategyTest#testTimeZoneStrategyPattern fails on Windows with German Locale - Add method containsAllWords to WordUtils - ReflectionToStringBuilder doesn't throw IllegalArgumentException when the constructor's object param is null - Inconsistent behavior of swap for malformed inputs - StringUtils join with var args - Fix critical issues reported by SonarQube - StrBuilder.equals(StrBuilder) doesn't check for null inputs - Add ThreadUtils - A utility class which provides helper methods related to java.lang.Thread - Add annotations to exclude fields from ReflectionEqualsBuilder, ReflectionToStringBuilder and ReflectionHashCodeBuilder - Use JUnit rules to set and reset the default Locale and TimeZone - JsonToStringStyle doesn't handle chars and objects correctly - HashCodeBuilder throws StackOverflowError in bidirectional navigable association - DateFormatUtilsTest.testSMTP depends on the default Locale - Unit test FastDatePrinterTimeZonesTest needs a timezone set - CLONE - DateFormatUtils.format does not correctly change Calendar TimeZone in certain situations - DateUtilsTest.testLang530 fails for some timezones - TypeUtils.ParameterizedType#equals doesn't work with wildcard types - Add rotate(string, int) method to StringUtils - StringUtils.repeat('z', -1) throws NegativeArraySizeException - Add swap and shift operations for arrays to ArrayUtils - TypeUtils.parameterizeWithOwner - wrong format descriptor for "invalid number of type parameters". - MultilineRecursiveToStringStyle largely unusable due to being package-private. - StringUtils.uncapitalize performance improvement - CharSet.getInstance documentation does not clearly explain how to include negation character in set - Change nullToEmpty methods to generics - Fix FindBugs warnings in DurationFormatUtils - Add a method to ArrayUtils for removing all occurrences of a given element - Fix parsing edge cases in FastDateParser - StringUtils#equals fails with Index OOBE on non-Strings with identical leading prefix - - - - Support OS X versions in SystemUtils - SystemUtils.IS_OS_WINDOWS_2008, VISTA are incorrect - Parse test fails for TimeZone America/Sao_Paulo - Add SystemUtils.IS_JAVA_1_9 - Make logic for comparing OS versions in SystemUtils smarter - Shutdown thread pools in test cases - FastDateParser and FastDatePrinter support 'X' format - Avoid memory allocation when using date formating to StringBuffer - Possible performance improvement on string escape functions - Exception while using ExtendedMessageFormat and escaping braces - Avoid String allocation in StrBuilder.append(CharSequence) - Update maven-checkstyle-plugin to 2.14 - Update org.easymock:easymock to 3.3.1 - Update maven-pmd-plugin to 3.4 - Update maven-antrun-plugin to 1.8 - Wrong formating of time zones with daylight saving time in FastDatePrinter - Performance improvements for StringEscapeUtils - Add ClassUtils.getAbbreviatedName() - FastDateParser does not set error indication in ParsePosition - FastDateParser does not handle excess hours as per SimpleDateFormat - FastDateParser error - timezones not handled correctly - NumberUtils#createNumber() returns positive BigDecimal when negative Float is expected - DiffBuilder.append(String, Object left, Object right) does not do a left.equals(right) check - StrSubstitutor.replaceSystemProperties does not work consistently - Add option to disable the "objectsTriviallyEqual" test in DiffBuilder - Add (T) casts to get unit tests to pass in old JDK - Add JsonToStringStyle implementation to ToStringStyle - Add NoClassNameToStringStyle implementation of ToStringStyle - Fix wrong examples in JavaDoc of StringUtils.replaceEachRepeatedly(...), StringUtils.replaceEach(...) - Add StringUtils.containsAny(CharSequence, CharSequence...) method - Read wrong component type of array in add in ArrayUtils - StringUtils.ordinalIndexOf("aaaaaa", "aa", 2) != 3 in StringUtils - Duplicated "0x" check in createBigInteger in NumberUtils - StringUtils.abbreviate description doesn't agree with the examples - Multiline recursive to string style - Add isSorted() to ArrayUtils - Fix MethodUtilsTest so it does not depend on JDK method ordering - CompareToBuilder's doc doesn't specify precedence of fields it uses in performing comparisons - ParseException when trying to parse UTC dates with Z as zone designator using DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT - Javadoc for EqualsBuilder.reflectionEquals() is unclear - Improve performance of normalize space - Add StringUtils.countMatches(CharSequence, char) - org.apache.commons.lang3.SystemUtils#isJavaVersionAtLeast should return true by default - Provide methods to retrieve all fields/methods annotated with a specific type - Bring static method references in StringUtils to consistent style - NumberUtils#isParsable method(s) - Use non-ASCII digits in Javadoc examples for StringUtils.isNumeric - Change min/max methods in NumberUtils/IEEE754rUtils from array input parameters to varargs - Add fuzzy String matching logic to StringUtils - Add wrap (with String or char) to StringUtils - Extend DurationFormatUtils#formatDurationISO default pattern to match #formatDurationHMS - Fixing NumberUtils JAVADoc comments for max methods - Better Javadoc for BitField class - DurationFormatUtils#formatDurationHMS implementation does not correspond to Javadoc and vice versa - DurationFormatUtils are not able to handle negative durations/periods - ISO 8601 misspelled throughout the Javadocs - Add zero copy read method to StrBuilder - Add zero copy write method to StrBuilder - Javadoc is not clear on preferred pattern to instantiate FastDateParser / FastDatePrinter - FastDateParser should be case insensitive - Fix bug with stripping spaces on last line in WordUtils.wrap() - Add method org.apache.commons.lang3.reflect.MethodUtils.invokeExactMethod(Object, String) - Add method org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(Object, String) - - - - NumberUtils#isNumber() returns false for "0.0", "0.4790", et al - Add org.apache.commons.lang3.SystemUtils.IS_JAVA_1_8 - - - - DateUtils.getFragmentInDays(Date, Calendar.MONTH) returns wrong days - DurationFormatUtils does not describe format string fully - DurationFormatUtils#lexx does not detect unmatched quote char - DurationFormatUtils does not handle large durations correctly - DurationFormatUtils.formatDuration(61999, "s.SSSS") - ms field size should be 4 digits - Failing tests with Java 8 b128 - - - - ReflectionToStringBuilder.toString does not debug 3rd party object fields within 3rd party object - Add methods for removing all invalid characters according to XML 1.0 and XML 1.1 in an input string to StringEscapeUtils - NumericEntityEscaper incorrectly encodes supplementary characters - Make some private fields final - NumberUtils#isNumber(String) fails to reject invalid Octal numbers - NumberUtils#isNumber does not allow for hex 0XABCD - StringUtils.toEncodedString(byte[], Charset) needlessly throws UnsupportedEncodingException - Add APIs MutableBoolean setTrue() and setFalse() - ConstantInitializerTest fails when building with IBM JDK 7 - Add SerializationUtils.roundtrip(T extends Serializable) to serialize then deserialize - org.apache.commons.lang3.reflect.FieldUtils.removeFinalModifier(Field) does not clean up after itself - FastDateParser javadoc incorrectly states that SimpleDateFormat is used internally - There should be a DifferenceBuilder with a ReflectionDifferenceBuilder implementation - uncaught PatternSyntaxException in FastDateFormat on Android - Improve JavaDoc of WordUtils.wrap methods - Add the Jaro-Winkler string distance algorithm to StringUtils - StringUtils.getLevenshteinDistance with too big of a threshold returns wrong result - Test DurationFormatUtilsTest.testEdgeDuration fails in JDK 1.6, 1.7 and 1.8, BRST time zone - ConstructorUtils.getAccessibleConstructor() Does Not Check the Accessibility of Enclosing Classes - Fragments are wrong by 1 day when using fragment YEAR or MONTH - New class ClassPathUtils with methods for turning FQN into resource path - Move Documentation from user guide to package-info files - Convert package.html files to package-info.java files - FastDateParser does not handle two digit year parsing like SimpleDateFormat - FastDateParserTest.testParses does not test FastDateParser - Fix deprecation warnings - EnumUtils.generateBitVector needs a "? extends" - Validate: add inclusiveBetween and exclusiveBetween overloads for primitive types - New RandomUtils class - Wrong locale handling in LocaleUtils.toLocale() - Add IBM OS/400 detection - - - - Fix missing Hamcrest dependency in Ant Build - Test failure in LocaleUtilsTest when building with JDK 8 - Test failure in FastDateParserTest and FastDateFormat_ParserTest when building with JDK8 - Build fails with test failures when building with JDK 8 - - - - Add removeFinalModifier to FieldUtils - Method returns number of inheritance hops between parent and subclass - Spelling fixes - Misleading Javadoc comment in StrBuilderReader class - OctalUnescaper tried to parse all of \279 - OctalUnescaper had bugs when parsing octals starting with a zero - EqualsBuilder returned true when comparing arrays, even when the elements are different - Added isStarted, isSuspended and isStopped to StopWatch - Fixed exception when combining custom and choice format in ExtendedMessageFormat - Added StringUtils.isBlank/isEmpty CharSequence... methods - Added ArrayUtils.reverse(array, from, to) methods - StringUtils.toString(byte[], String) deprecated in favour of a new StringUtils.toString(byte[], CharSet) - RandomStringUtils.random javadoc was incorrectly promising letters and numbers would, as opposed to may, appear - BooleanUtils.xor(boolean...) produces wrong results - StringUtils.normalizeSpace now handles non-breaking spaces (Unicode 00A0) - Redundant check for zero in HashCodeBuilder ctor - StrSubstitutor now supports default values for variables - Adding .gitignore to commons-lang - Add ObjectUtils.toIdentityString methods that support StringBuilder, StrBuilder, and Appendable - BooleanUtils.toBoolean(String str) javadoc is not updated - LocaleUtils test fails with new Locale "ja_JP_JP_#u-ca-japanese" of JDK7 - StrSubstitutor does not support StringBuilder or CharSequence - Method createNumber from NumberUtils doesn't work for floating point numbers other than Float - FastDateFormat does not use the locale specific cache correctly - Simplify FastDateFormat; eliminate boxing - LookupTranslator now works with implementations of CharSequence other than String - ClassUtils.getShortName(String) will now only do a reverse lookup for array types - Added CharSetUtils.containsAny(String, String) - Provide CharSequenceUtils.regionMatches with a proper green implementation instead of inefficiently converting to Strings - Added escape/unescapeJson to StringEscapeUtils - Added appendIfMissing and prependIfMissing methods to StringUtils - NumberUtils.createNumber() Javadoc says it does not work for octal numbers - Fixed URLs in javadoc to point to new oracle.com pages - Add StringUtils.LF and StringUtils.CR values - Add FieldUtils getAllFields() to return all the fields defined in the given class and super classes - LocaleUtils.toLocale does not parse strings starting with an underscore - StrBuilder should support StringBuilder as an input parameter - StringEscapeUtils.escapeJava() and escapeEcmaScript() do not output the escaped surrogate pairs that are Java parsable - StringIndexOutOfBoundsException in CharSequenceTranslator - Code refactoring in NumberUtils - NumberUtils#createBigInteger does not allow for hex and octal numbers - NumberUtils#createNumber - does not allow for hex numbers to be larger than Long - StringUtils join APIs for primitives - FastDateFormat and FastDatePrinter generates Date objects wastefully - Spelling fixes - Fix examples contained in javadoc of StringUtils.center methods - Add StringUtils API to call String.replaceAll in DOTALL a.k.a. single-line mode - ArrayUtils removeElements methods use unnecessary HashSet - ArrayUtils removeElements methods clone temporary index arrays unnecessarily - FastDateParser does not handle unterminated quotes correctly - FastDateParser does not handle white-space properly - FastDateParser could use \Q \E to quote regexes - FastDateParser does not handle non-Gregorian calendars properly - FastDateParser does not handle non-ASCII digits correctly - Create StrBuilder APIs similar to String.format(String, Object...) - NumberUtils#createNumber - bad behaviour for leading "--" - FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format() - Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8 - StringUtils.equalsIgnoreCase doesn't check string reference equality - StringUtils.join() endIndex, bugged for loop - RandomStringUtils throws confusing IAE when end <= start - RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException - LocaleUtils - unnecessary recursive call in SyncAvoid class. - Javadoc bug in DateUtils#ceiling for Calendar and Object versions. - DateUtils#parseDate uses default locale; add Locale support - Use generics in SerializationUtils - SerializationUtils throws ClassNotFoundException when cloning primitive classes - StringUtils equals() relies on undefined behavior - Documentation bug: StringUtils.split - jar contains velocity template of release notes - TypeUtilsTest contains incorrect type assignability assertion - TypeUtils.getTypeArguments() misses type arguments for partially-assigned classes - ImmutablePair doc contains nonsense text - ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text - EventListenerSupport.ProxyInvocationHandler no longer defines serialVersionUID - StrBuilder is now serializable - Fix Javadoc Ant warnings - NumberUtils does not handle Long Hex numbers - Javadoc bug in static inner class DateIterator - Add Triple class (ternary version of Pair) - FastDateFormat supports parse methods - - - - Add API StringUtils.toString(byte[] intput, String charsetName) - Add an example with whitespace in StringUtils.defaultIfEmpty - Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and isPrimitiveOrWrapper(Class<?>) - Fix createLong() so it behaves like createInteger() - Include the actual type in the Validate.isInstance and isAssignableFrom exception messages - Incorrect Bundle-SymbolicName in Manifest - Deprecating chomp(String, String) - NumberUtils does not handle upper-case hex: 0X and -0X - StringUtils throws java.security.AccessControlException on Google App Engine - Ant build has wrong component.name - CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY - Document that the Mutable numbers don't work as expected with String.format - SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system - - - - SerializationUtils.clone: Fallback to context classloader if class not found in current classloader. - ToStringBuilderTest.testReflectionHierarchyArrayList fails with IBM JDK 6. - StringEscapeUtils.escapeXml(input) wrong when input contains characters in Supplementary Planes. - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long unicode string. - Improve exception message when StringUtils.replaceEachRepeatedly detects recursion. - Specify source encoding for Ant build. - Complement ArrayUtils.addAll() variants with by-index and by-value removal methods. - Add Range<T> Range<T>.intersectionWith(Range<T>). - Add mode and median Comparable... methods to ObjectUtils. - Add BooleanUtils.and + or varargs methods. - EnumSet -> bit vector. - The CHAR_ARRAY cache in CharUtils duplicates the cache in java.lang.Character. - Deprecate CharUtils.toCharacterObject(char) in favor of java.lang.Character.valueOf(char). - Missing method getRawMessage for ContextedException and ContextedRuntimeException. - Use internal Java's Number caches instead creating new objects. - - - - StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes. - build.xml Java 1.5+ updates. - swapCase and *capitalize speedups. - CharSetUtils.squeeze() speedup. - StringUtils doc/comment spelling fixes. - Increase test coverage of FieldUtils read methods and tweak Javadoc. - Add includeantruntime=false to javac targets to quell warnings in ant 1.8.1 and better (and modest performance gain). - StringIndexOutOfBoundsException when calling unescapeHtml4("&#03"). - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long Unicode string. - StringUtils.join throws NPE when toString returns null for one of objects in collection. - Add FormattableUtils class. - Add ClassUtils.getSimpleName() methods. - Add hashCodeMulti varargs method. - Removed DateUtils.UTC_TIME_ZONE. - Convert more of the StringUtils API to take CharSequence. - EqualsBuilder synchronizes on HashCodeBuilder. - StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for "". - Add support for ConcurrentMap.putIfAbsent(). - Documented potential NPE if auto-boxing occurs for some BooleanUtils methods. - DateUtils.isSameLocalTime compares using 12 hour clock and not 24 hour. - Extend exception handling in ConcurrentUtils to runtime exceptions. - SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - WordUtils.abbreviate() removed. - Doc bug in DateUtils#ceiling. - StringEscapeUtils.unescapeJava doesn't handle octal escapes and Unicode with extra u. - org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k). - org.apache.commons.lang3.math.Fraction does not always succeed in multiplyBy and divideBy. - Change ObjectUtils min() & max() functions to use varargs rather than just two parameters. - Add a Null-safe compare() method to ObjectUtils. - NumberUtils.isNumber(String) is not right when the String is "1.1L". - EntityArrays typo: {"\u2122", "&minus;"}, // minus sign, U+2212 ISOtech. - Some Entitys like &Ouml; are not matched properly against its ISO8859-1 representation. - Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect. - Add StringUtils.defaultIfBlank(). - Provide a very basic ConcurrentInitializer implementation. - Support lazy initialization using atomic variables. - Enhance StrSubstitutor to support nested ${var-${subvr}} expansion. - Provide documentation about the new concurrent package. - Charset may not be threadsafe, because the HashSet is not synch. - StringEscapeUtils.escapeXML() can't process UTF-16 supplementary characters. - StringUtils.endsWithAny method. - Add AnnotationUtils. - BooleanUtils.toBooleanObject to support single character input. - FastDateFormat.format() outputs incorrect week of year because locale isn't respected. - StrSubstitutor should also handle the default properties of a java.util.Properties class. - Javadoc StringUtils.left() claims to throw on negative len, but doesn't. - Add normalizeSpace to StringUtils. - NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - - NOTE: The below were included in the Commons Lang 3.0-beta release. - Convert StringUtils API to take CharSequence. - Push down WordUtils to "text" sub-package. - Extend exception handling in ConcurrentUtils to runtime exceptions. - Some StringUtils methods should take an int character instead of char to use String API features. - EqualsBuilder causes StackOverflowException. - DefaultExceptionContext overwrites values in recursive situations. - ContextedRuntimeException no longer an 'unchecked' exception. - Add Builder Interface / Update Builders to Implement It. - Javadoc is incorrect for public static int lastIndexOf(String str, String searchStr). - ClassUtils.getClass(): Allow Dots as Inner Class Separators. - DateUtils equal & compare functions up to most significant field. - Remove JDK 1.2/1.3 bug handling in StringUtils.indexOf(String, String, int). - Create a basic Pair<L, R> class. - exception.DefaultExceptionContext.getFormattedExceptionMessage catches Throwable. - Provide an implementation of the ThreadFactory interface. - Add new Validate methods. - ArrayUtils.add(T[] array, T element) can create unexpected ClassCastException. - Do the test cases really still require main() and suite() methods?. - @SuppressWarnings("unchecked") is used too generally. - Improve StrLookup API documentation. - Change Java package name. - Change Maven groupId. - New TimedSemaphore class. - Added validState validation method. - Added isAssignableFrom and isInstanceOf validation methods. - Add TypeUtils class to provide utility code for working with generic types. - Replace Range classes with generic version. - Use Iterable on API instead of Collection. - Add methods to Validate to check whether the index is valid for the array/list/string. - Add ability to create a Future for a constant. - Replace StringBuffer with StringBuilder. - Make NumericEntityEscaper immutable. - Compile commons.lang for CDC 1.1/Foundation 1.1. - Add ArrayUtils.toArray to create generic arrays. - Validate: support for validating blank strings. - Add a concurrent package. - Mutable classes should implement an appropriately typed Mutable interface. - Better EnumUtils. - StringEscapeUtils.unescapeJava should support \u+ notation. - Rewrite StringEscapeUtils. - bring ArrayUtils.isEmpty to the generics world. - Add support for background initialization. - Add support for the handling of ExecutionExceptions. - Add StringEscapeUtils.escapeText() methods. - Addition of ContextedException and ContextedRuntimeException. - A generic implementation of the Lazy initialization pattern. - Remove code that does not hold enough value to remain. - Remove code handled now by the JDK. - StrSubstitutor now supports substitution in variable names. - Possible race-conditions in hashCode of the range classes. - StringEscapeUtils.escapeHtml incorrectly converts Unicode characters above U+00FFFF into 2 characters. - Document where in SVN trunk is. - StopWatch does not resist to system time changes. - Fixes for thread safety. - Refactor Validate.java to eliminate code redundancy. - Lower Ascii Characters don't get encoded by Entities.java. - StringUtils.emptyToNull. - StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20). - Remove @deprecateds. - Add ClassUtils.isAssignable() variants with autoboxing. - Improve Javadoc for StringUtils class. - Javadoc incorrect for StringUtils.endsWithIgnoreCase. - Investigate for vararg usages. - JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder). - LeftOf/RightOfNumber in Range convenience methods necessary. - ExceptionUtils not thread-safe. - ObjectUtils.coalesce. - StrBuilder should implement CharSequence and Appendable. - StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanese, etc. - Finally start using generics. - StrBuilder does not implement clone(). - EnumUtils for JDK 5.0. - Wish : method unaccent. - MutableBigDecimal and MutableBigInteger. - StringEscaper.escapeXml() escapes characters > 0x7f. - Depend on JDK 1.5+. - - - - BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String). - ClassUtils: allow Dots as Inner Class Separators in getClass(). - DateUtils: equal and compare functions up to most significant field. - DateUtils: provide a Date to Calendar convenience method. - ObjectUtils: add clone methods to ObjectUtils. - ObjectUtils: add a Null-safe compare() method. - ObjectUtils: add notEqual() method. - StrBuilder: implement clone() method. - StringUtils: add a normalizeSpace() method. - StringUtils: add endsWithAny() method. - StringUtils: add defaultIfBlank() method. - StrSubstitutor: add a replace(String, Properties) variant. - StrSubstitutor: support substitution in variable names. - Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue. - CharSet: make the underlying set synchronized. - CompareToBuilder: fix passing along compareTransients to the reflectionCompare method. - ExtendedMessageFormat doesn't override equals(Object). - FastDateFormat: fix to properly include the locale when formatting a Date. - NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly. - SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading. - Javadoc is incorrect for lastIndexOf() method. - Javadoc for HashCodeBuilder.append(boolean) does not match implementation. - Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't. - Javadoc - document thread safety. - Test for StringUtils replaceChars() icelandic characters. - - - - ArrayUtils - add isNotEmpty() methods. - ArrayUtils - add nullToEmpty() methods. - CharRange - provide an iterator that lets you walk the chars in the range. - CharRange - add more readable static builder methods. - ClassUtils - new isAssignable() methods with autoboxing. - ClassUtils - add support to getShortClassName and getPackageName for arrays. - DateUtils - add ceiling() method. - DateUtils - add parseDateStrictly() method. - EqualsBuilder - add reset() method. - NumberUtils - add toByte() and toShort() methods. - Mutable numbers - add string constructors. - MutableBoolean - add toBoolean(), isTrue() and isFalse() methods. - StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty. - SystemUtils - add IS_OS_WINDOWS_7 constant. - SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7. - StringUtils - add abbreviateMiddle() method. - StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods. - StringUtils - add isAllUpperCase() and isAllLowerCase() methods. - StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method. - StringUtils - add repeat() method. - StringUtils - add startsWithAny() method. - StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods. - New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils. - ArrayUtils - addAll() does not handle mixed types very well. - CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread. - ClassUtils - improving performance of getAllInterfaces. - ClassUtils - toClass() throws NullPointerException on null array element. - DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat. - DateUtils - round() doesn't work correct for Calendar.AM_PM. - DateUtils - improve tests. - Entities - multithreaded initialization. - Entities - missing final modifiers; thread-safety issues. - EnumUtils - getEnum() doesn't work well in 1.5+. - ExceptionUtils - use immutable lock target. - ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes. - FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state. - FastDateFormat - Remove unused field. - LocaleUtils - Initialization of available locales in LocaleUtils can be deferred. - NumberUtils - createNumber() thows a StringIndexOutOfBoundsException when only an "l" is passed in. - NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.'. - StringUtils - improve handling of case-insensitive Strings. - StringUtils - replaceEach() no longer NPEs when null appears in the last String[]. - StringUtils - correct Javadoc for startsWith() and startsWithIgnoreCase(). - StringEscapeUtils - escapeJava() escapes '/' characters. - StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException and returning null. - WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length. - StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity. - Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List. - EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo instead of equals because it creates an inequality with HashCodeBuilder. - HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks. - HashCodeBuilder - Changing the hashCode() method to return toHashCode(). - HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes. - HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments. - ToStringBuilder - make default style thread-safe. - RandomUtils - nextLong() always produces even numbers. - RandomUtils - RandomUtils tests are failing frequently. - - - - ClassUtils.getShortClassName(String) inefficient. - Shouldn't Commons Lang's StringUtils have a "common" string method?. - FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change. - OSGi-ify Lang. - StrBuilder appendFixedWidth does not handle nulls. - infinite loop in Fraction.reduce when numerator == 0. - FastDateFormat thread safety. - ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array. - LocaleUtils.toLocale() rejects strings with only language+variant. - Enum is not thread-safe. - BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException. - ArrayUtils.toClass. - Why does appendIdentityToString return null?. - NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN. - Dates.round() behaves incorrectly for minutes and seconds. - StringUtils.length(String) returns null-safe length. - adding a StringUtils.replace method that takes an array or List of replacement strings. - Adding functionality to DateUtils to allow direct setting of various fields. - Add escaping for CSV columns to StringEscapeUtils. - StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods. - Extension to ClassUtils: Obtain the primitive class from a wrapper. - Javadoc bugs - cannot find object. - Optimize HashCodeBuilder.append(Object). - http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete. - Ambiguous / confusing names in StringUtils replace* methods. - Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils. - Add getStartTime to StopWatch. - Perhaps add containsAny() methods?. - Javadoc Example for EqualsBuilder is questionable. - EqualsBuilder don't compare BigDecimals correctly. - Split camel case strings. - Add Calendar flavour format methods to DateFormatUtils. - Calculating A date fragment in any time-unit. - Memory usage improvement for StringUtils#getLevenshteinDistance(). - Add ExtendedMessageFormat to org.apache.commons.lang.text. - StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly. - Add toArray() method to IntRange and LongRange classes. - add SystemUtils.IS_OS_WINDOWS_VISTA field. - Pointless synchronized in ThreadLocal.initialValue should be removed. - ToStringStyle Javadoc should show examples of styles. - Documentation bug for ignoreEmptyTokens accessors in StrTokenizer. - BooleanUtils toBooleanObject Javadoc does not match implementation. - truncateNicely method which avoids truncating in the middle of a word. - - - - Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions. - NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing. - Null-safe comparison methods for finding most recent / least recent dates. - StopWatch: suspend() acts as split(), if followed by stop(). - StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException. - Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException. - ToStringBuilder throws StackOverflowError when an Object cycle exists. - Create more tests to test out the +=31 replacement code in DurationFormatUtils. - StrBuilder contains usages of thisBuf.length when they should use size. - Enum Javadoc: 1) outline 5.0 native Enum migration 2) warn not to use the switch() , 3) point out approaches for persistence and gui. - Wrong behavior of Entities.unescape. - NumberUtils.createNumber throws NumberFormatException for one digit long. - NullPointerException in isAvailableLocale(Locale). - FastDateFormat.mRules is not transient or serializable. - StringUtils.join should allow you to pass a range for it (so it only joins a part of the array). - Refactor Entities methods. - Tests fail to pass when building with Maven 2. - DurationFormatUtils returns wrong result. - unescapeXml("&12345678;") should be "&12345678;". - Optimize StringEscapeUtils.unescapeXml(String). - BooleanUtils isNotTrue/isNotFalse. - Extra StrBuilder methods. - Add a pair of StringUtils.substringsBetween;String[] methods. - HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle. - Wish for StringUtils.join(Collection, *). - - - - StrBuilderTest#testReplaceStringString fails. - EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null. - Serialization - not backwards compatible. - Replace Clover with Cobertura. - ValuedEnum.compareTo(Object other) not typesafe - it easily could be... - LocaleUtils test fails under Mustang. - Javadoc example for StringUtils.splitByWholeSeparator incorrect. - PADDING array in StringUtils overflows on '\uffff'. - ClassUtils.primitiveToWrapper and Void. - unit test for org.apache.commons.lang.text.StrBuilder. - DateUtils.truncate method is buggy when dealing with DST switching hours. - RandomStringUtils.random() family of methods create invalid Unicode sequences. - StringUtils#getLevenshteinDistance() performance is sub-optimal. - Wrong length check in StrTokenizer.StringMatcher. - ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable. - FastDateFormat: wrong format for date "01.01.1000". - Unclear Javadoc for DateUtils.iterator(). - Memory "leak" in StringUtils. - StringEscapeUtils should expose escape*() methods taking Writer argument. - Fraction.toProperString() returns -1/1 for -1. - DurationFormatUtils.formatDurationWords "11 <unit>s" gets converted to "11 <unit>". - Performance modifications on StringUtils.replace. - StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand. - DurationFormatUtils.formatPeriod() returns the wrong result. - Request for MutableBoolean implementation. - New method for EqualsBuilder. - New ExceptionUtils method setCause(). - Add Mutable<Type> to<Type>() methods. - Provides a Class.getPublicMethod which returns public invocable Method. - Using ReflectionToStringBuilder and excluding secure fields. - add generic add method to DateUtils. - Tokenizer Enhancements: reset input string, static CSV/TSV factories. - Trivial cleanup of Javadoc in various files. - CompositeFormat. - Performance boost for RandomStringUtils. - Enhanced Class.forName version. - Add StringUtils.containsIgnoreCase(...). - Support char array converters on ArrayUtils. - DurationFormatUtils.formatDurationISO() Javadoc is missing T in duration string between date and time part. - Minor build and checkstyle changes. - Javadoc errors on StringUtils.splitPreserveAllTokens(String, char). - EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to &apos;. - Add methods and tests to StrBuilder. - replace() length calculation improvement. - New interpolation features. - Implementation of escape/unescapeHtml methods with Writer. - CompareToBuilder excludeFields for reflection method. - Add WordUtils.getInitials(String). - Error in an example in the Javadoc of the StringUtils.splitPreserveAllTokens() method. - ToStringBuilder/HashCodeBuilder Javadoc code examples. - Cannot build tests from latest SVN. - minor Javadoc improvements for StringUtils.stripXxx() methods. - Javadoc for StringUtils.removeEnd is incorrect. - Minor tweak to fix of bug # 26616. - - - - make optional parameters in FastDateFormat really optional. - Nestable.indexOfThrowable(Class) uses Class.equals() to match. - buffer under/overrun on Strings.strip, stripStart & stripEnd. - ToStringStyle.setArrayEnd(String) doesn't replace null with empty string. - New class proposal: CharacterEncoding. - SystemUtils fails init on HP-UX. - Javadoc - 'four basic XML entities' should be 5 (apos is missing). - o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0. - StringEscapeUtils.unescapeHtml() doesn't handle an empty entity. - EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class. - Method enums.Enum.equals(Object o) doesn't work correctly. - ExceptionUtils.addCauseMethodName(String) does not check for duplicates. - Make StopWatch validate state transitions. - enum package is not compatible with 1.5 jdk. - WordUtils capitalizeFully() throws a null pointer exception. - ValuedEnum. - parseDate class from HttpClient's DateParser class. - ArrayUtils.isEquals() throws ClassCastException when array1 and array2 are different dimension. - ClassCastException in Enum.equals(Object). - FastDateFormat year bug. - unbalanced ReflectionToStringBuilder. - FastDateFormat.getDateInstance(int, Locale) always uses the pattern from the first invocation. - ReflectionToStringBuilder.toString(null) throws exception by design. - Make ClassUtils methods null-safe and not throw an IAE. - StringUtils.split ignores empty items. - EqualsBuilder.append(Object[], Object[]) throws NPE. - ArrayUtils.addAll doesn't always return new array. - Enum.equals does not handle different class loaders. - Add SystemUtils.AWT_TOOLKIT and others. - Throwable cause for NotImplementedException. - ClassUtils.primitivesToWrappers method. - public static boolean DateUtils.equals(Date dt1, Date dt2) ?. - Documentation error in StringUtils.replace. - DateUtils constants should be long. - DateUtils.truncate() is off by one hour when using a date in DST switch 'zone'. - StringEscapeUtils.unescapeHtml() doesn't handle hex entities. - new StringUtils.replaceChars behaves differently from old CharSetUtils.translate. - last substring returned by StringUtils.split( String, String, int ) is too long. - Can't subclass EqualsBuilder because isEquals is private. - new StringUtils.split methods that split on the whole separator string. - New method for converting a primitive Class to its corresponding wrapper Class. - Add convenience format(long) methods to FastDateFormat. - Enum's outer class may not be loaded for EnumUtils. - WordUtils.capitalizeFully(String str) should take a delimiter. - Make Javadoc crosslinking configurable. - Minor Javadoc fixes for StringUtils.contains(String, String). - Error in Javadoc for StringUtils.chomp(String, String). - StringUtils.defaultString: Documentation error. - Add hashCode-support to class ObjectUtils. - add another "known method" to ExceptionUtils. - Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES. - DateUtils.truncate oddity at the far end of the Date spectrum. - add getLength() method to ArrayUtils. - Validate.java: fixes comment skew, removes unused loop counter. - StringUtils.isAsciiPrintable(). - ExceptionUtils: new getCause() methodname (for tomcat-exception). - fixes 75 typos. - mutable numbers. - Javadoc fixes for ClassUtils. - Add StringUtils.nIndexOf?. - Javadoc fixes for CharSetUtils. - Remove redundant check for null separator in StringUtils#join. - Class and Package Comparators for ClassUtils. - add remove methods to ArrayUtils. - WordUtils capitalize improvement. - add isEmpty method to ArrayUtils. - lang.math.Fraction class deficiencies. - Add methods to ArrayUtils: add at end and insert-like ops. - Add SystemUtils methods for directory properties. - Add method that validates Collection elements are a certain type. - elapsed time formatting utility method. - - - - Infinite loop in ToStringBuilder.reflectionToString for inner classes. - NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08. - Rationalize StringUtils slice functions. - SystemUtils.IS_OS_OS2 Javadoc is wrong. - A small, but important Javadoc fix for Fraction proper whole and numerator. - Adding tolerance to double[] search methods in ArrayUtils. - lang.builder classes Javadoc edits (mostly typo fixes). - StringUtils Javadoc and test enhancements. - SystemUtils.IS_OS_*, IS_JAVA_* are always false. - Improve util.Validate tests. - maven-beta10 checkstyle problem. - StringUtils.chopNewLine - StringIndexOutOfBoundsException. - ToStringBuilder doesn't work well in subclasses. - static option for reversing the stacktrace. - NullPointerException in CompareToBuilder. - RandomStringUtils.randomAlpha methods omit 'z'. - test.time fails in Japanese (non-us) locale. - NumberUtils.isNumber allows illegal trailing characters. - Improve Javadoc and overflow behavior of Fraction. - RandomStringUtils infloops with length > 1. - test.lang fails if compiled with non iso-8859-1 locales. - SystemUtils does not play nice in an Applet. - time unit tests fail on Sundays. - java.lang.ExceptionInInitializerError thrown by JVMRandom constructor. - StringUtils.chomp does not match Perl. - patch and test case fixing problem with RandomStringUtils.random(). - General case: infinite loop: ToStringBuilder.reflectionToString. - Should ToStringBuilder.reflectionToString handle arrays?. - EnumUtils nit: The import java.io.Serializable is never used. - Example in Javadoc for ToStringBuilder wrong for append. - Added class hierarchy support to HashCodeBuilder.reflectionHashCode(). - ExceptionUtils new methods. - Infinite loop in StringUtils.replace(text, repl, with) + FIX. - StackOverflow due to ToStringBuilder. - No Javadoc for NestableDelegate. - Specify initial size for Enum's HashMap. - Enum does not support inner sub-classes. - Removed compile warning in ObjectUtils. - SystemUtils.IS_JAVA_1_5 Javadoc is wrong. - NumberRange inaccurate for Long, etc. - Hierarchy support in ToStringBuilder.reflectionToString(). - StringUtils.countMatches loops forever if substring empty. - Javadoc fixes (remove @links to non-public identifiers). - Add Javadoc examples and tests for StringUtils. - Make NumberUtils null handling consistent. - Unused field 'startFinal' in DateIterator. - reduce object creation in ToStringBuilder. - Improved tests, Javadoc for CharSetUtils, StringEscapeUtils. - NumberUtils min/max, BooleanUtils.xor, and ArrayUtils toPrimitive and toObject. - Javadoc, tests improvements for CharSet, CharSetUtils. - StringUtil enhancement. - Javadoc nit. - Additional Lang Method Suggestions. - Make NestableDelegate methods public instead of package private. - Missing @since tags. - Refactored reflection feature of ToStringBuilder into new ReflectionToStringBuilder. - Typo in documentation. - Patch for Javadoc. - Add join(..., char c) to StringUtils (and some performance fixes). Even contains tests!. - Resurrect the WordWrapUtils from commons-sandbox/utils. - EnumTest fails on Linux Sun JDK 1.3.0. - What to do with FastDateFormat unused private constructors. - Added class hierarchy support to CompareToBuilder.reflectionCompare(). - Removed compile warning in FastDateFormat. - typo in the Javadoc example code. - MethodUtils: Removed unused code/unused local vars. - Hierarchy support in EqualsBuilder.reflectionEquals(). - Javadoc Errata. - ArrayUtils.contains(). - More flexibility for getRootCause in ExceptionUtils. - - - - NumberRange.getMaximum returns minimum. - Enum constructor validations. - NestableException/Delegate is not serializable. - split using null and max less than actual token count adds "null". - ExceptionUtils cannot handle J2EE-Exception in a default way. - - - - - - - diff --git a/All/Genesis-OOB/Genesis#33/old/StringUtils.java b/All/Genesis-OOB/Genesis#33/old/StringUtils.java deleted file mode 100755 index 5f167b9..0000000 --- a/All/Genesis-OOB/Genesis#33/old/StringUtils.java +++ /dev/null @@ -1,7973 +0,0 @@ -/* - * 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.commons.lang3; - -import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; -import java.text.Normalizer; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; -import java.util.regex.Pattern; - -/** - *

Operations on {@link java.lang.String} that are - * {@code null} safe.

- * - *
    - *
  • IsEmpty/IsBlank - * - checks if a String contains text
  • - *
  • Trim/Strip - * - removes leading and trailing whitespace
  • - *
  • Equals - * - compares two strings null-safe
  • - *
  • startsWith - * - check if a String starts with a prefix null-safe
  • - *
  • endsWith - * - check if a String ends with a suffix null-safe
  • - *
  • IndexOf/LastIndexOf/Contains - * - null-safe index-of checks - *
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - * - index-of any of a set of Strings
  • - *
  • ContainsOnly/ContainsNone/ContainsAny - * - does String contains only/none/any of these characters
  • - *
  • Substring/Left/Right/Mid - * - null-safe substring extractions
  • - *
  • SubstringBefore/SubstringAfter/SubstringBetween - * - substring extraction relative to other strings
  • - *
  • Split/Join - * - splits a String into an array of substrings and vice versa
  • - *
  • Remove/Delete - * - removes part of a String
  • - *
  • Replace/Overlay - * - Searches a String and replaces one String with another
  • - *
  • Chomp/Chop - * - removes the last part of a String
  • - *
  • AppendIfMissing - * - appends a suffix to the end of the String if not present
  • - *
  • PrependIfMissing - * - prepends a prefix to the start of the String if not present
  • - *
  • LeftPad/RightPad/Center/Repeat - * - pads a String
  • - *
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - * - changes the case of a String
  • - *
  • CountMatches - * - counts the number of occurrences of one String in another
  • - *
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - * - checks the characters in a String
  • - *
  • DefaultString - * - protects against a null input String
  • - *
  • Rotate - * - rotate (circular shift) a String
  • - *
  • Reverse/ReverseDelimited - * - reverses a String
  • - *
  • Abbreviate - * - abbreviates a string using ellipsis
  • - *
  • Difference - * - compares Strings and reports on their differences
  • - *
  • LevenshteinDistance - * - the number of changes needed to change one String into another
  • - *
- * - *

The {@code StringUtils} class defines certain words related to - * String handling.

- * - *
    - *
  • null - {@code null}
  • - *
  • empty - a zero-length string ({@code ""})
  • - *
  • space - the space character ({@code ' '}, char 32)
  • - *
  • whitespace - the characters defined by {@link Character#isWhitespace(char)}
  • - *
  • trim - the characters <= 32 as in {@link String#trim()}
  • - *
- * - *

{@code StringUtils} handles {@code null} input Strings quietly. - * That is to say that a {@code null} input will return {@code null}. - * Where a {@code boolean} or {@code int} is being returned - * details vary by method.

- * - *

A side effect of the {@code null} handling is that a - * {@code NullPointerException} should be considered a bug in - * {@code StringUtils}.

- * - *

Methods in this class give sample code to explain their operation. - * The symbol {@code *} is used to indicate any input including {@code null}.

- * - *

#ThreadSafe#

- * @see java.lang.String - * @since 1.0 - */ -//@Immutable -public class StringUtils { - // Performance testing notes (JDK 1.4, Jul03, scolebourne) - // Whitespace: - // Character.isWhitespace() is faster than WHITESPACE.indexOf() - // where WHITESPACE is a string of all whitespace characters - // - // Character access: - // String.charAt(n) versus toCharArray(), then array[n] - // String.charAt(n) is about 15% worse for a 10K string - // They are about equal for a length 50 string - // String.charAt(n) is about 4 times better for a length 3 string - // String.charAt(n) is best bet overall - // - // Append: - // String.concat about twice as fast as StringBuffer.append - // (not sure who tested this) - - /** - * A String for a space character. - * - * @since 3.2 - */ - public static final String SPACE = " "; - - /** - * The empty String {@code ""}. - * @since 2.0 - */ - public static final String EMPTY = ""; - - /** - * A String for linefeed LF ("\n"). - * - * @see JLF: Escape Sequences - * for Character and String Literals - * @since 3.2 - */ - public static final String LF = "\n"; - - /** - * A String for carriage return CR ("\r"). - * - * @see JLF: Escape Sequences - * for Character and String Literals - * @since 3.2 - */ - public static final String CR = "\r"; - - /** - * Represents a failed index search. - * @since 2.1 - */ - public static final int INDEX_NOT_FOUND = -1; - - /** - *

The maximum size to which the padding constant(s) can expand.

- */ - private static final int PAD_LIMIT = 8192; - - /** - *

{@code StringUtils} instances should NOT be constructed in - * standard programming. Instead, the class should be used as - * {@code StringUtils.trim(" foo ");}.

- * - *

This constructor is public to permit tools that require a JavaBean - * instance to operate.

- */ - public StringUtils() { - super(); - } - - // Empty checks - //----------------------------------------------------------------------- - /** - *

Checks if a CharSequence is empty ("") or null.

- * - *
-     * StringUtils.isEmpty(null)      = true
-     * StringUtils.isEmpty("")        = true
-     * StringUtils.isEmpty(" ")       = false
-     * StringUtils.isEmpty("bob")     = false
-     * StringUtils.isEmpty("  bob  ") = false
-     * 
- * - *

NOTE: This method changed in Lang version 2.0. - * It no longer trims the CharSequence. - * That functionality is available in isBlank().

- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if the CharSequence is empty or null - * @since 3.0 Changed signature from isEmpty(String) to isEmpty(CharSequence) - */ - public static boolean isEmpty(final CharSequence cs) { - return cs == null || cs.length() == 0; - } - - /** - *

Checks if a CharSequence is not empty ("") and not null.

- * - *
-     * StringUtils.isNotEmpty(null)      = false
-     * StringUtils.isNotEmpty("")        = false
-     * StringUtils.isNotEmpty(" ")       = true
-     * StringUtils.isNotEmpty("bob")     = true
-     * StringUtils.isNotEmpty("  bob  ") = true
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if the CharSequence is not empty and not null - * @since 3.0 Changed signature from isNotEmpty(String) to isNotEmpty(CharSequence) - */ - public static boolean isNotEmpty(final CharSequence cs) { - return !isEmpty(cs); - } - - /** - *

Checks if any one of the CharSequences are empty ("") or null.

- * - *
-     * StringUtils.isAnyEmpty(null)             = true
-     * StringUtils.isAnyEmpty(null, "foo")      = true
-     * StringUtils.isAnyEmpty("", "bar")        = true
-     * StringUtils.isAnyEmpty("bob", "")        = true
-     * StringUtils.isAnyEmpty("  bob  ", null)  = true
-     * StringUtils.isAnyEmpty(" ", "bar")       = false
-     * StringUtils.isAnyEmpty("foo", "bar")     = false
-     * 
- * - * @param css the CharSequences to check, may be null or empty - * @return {@code true} if any of the CharSequences are empty or null - * @since 3.2 - */ - public static boolean isAnyEmpty(final CharSequence... css) { - if (ArrayUtils.isEmpty(css)) { - return true; - } - for (final CharSequence cs : css){ - if (isEmpty(cs)) { - return true; - } - } - return false; - } - - /** - *

Checks if none of the CharSequences are empty ("") or null.

- * - *
-     * StringUtils.isNoneEmpty(null)             = false
-     * StringUtils.isNoneEmpty(null, "foo")      = false
-     * StringUtils.isNoneEmpty("", "bar")        = false
-     * StringUtils.isNoneEmpty("bob", "")        = false
-     * StringUtils.isNoneEmpty("  bob  ", null)  = false
-     * StringUtils.isNoneEmpty(" ", "bar")       = true
-     * StringUtils.isNoneEmpty("foo", "bar")     = true
-     * 
- * - * @param css the CharSequences to check, may be null or empty - * @return {@code true} if none of the CharSequences are empty or null - * @since 3.2 - */ - public static boolean isNoneEmpty(final CharSequence... css) { - return !isAnyEmpty(css); - } - /** - *

Checks if a CharSequence is whitespace, empty ("") or null.

- * - *
-     * StringUtils.isBlank(null)      = true
-     * StringUtils.isBlank("")        = true
-     * StringUtils.isBlank(" ")       = true
-     * StringUtils.isBlank("bob")     = false
-     * StringUtils.isBlank("  bob  ") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if the CharSequence is null, empty or whitespace - * @since 2.0 - * @since 3.0 Changed signature from isBlank(String) to isBlank(CharSequence) - */ - public static boolean isBlank(final CharSequence cs) { - int strLen; - if (cs == null || (strLen = cs.length()) == 0) { - return true; - } - for (int i = 0; i < strLen; i++) { - if (Character.isWhitespace(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if a CharSequence is not empty (""), not null and not whitespace only.

- * - *
-     * StringUtils.isNotBlank(null)      = false
-     * StringUtils.isNotBlank("")        = false
-     * StringUtils.isNotBlank(" ")       = false
-     * StringUtils.isNotBlank("bob")     = true
-     * StringUtils.isNotBlank("  bob  ") = true
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if the CharSequence is - * not empty and not null and not whitespace - * @since 2.0 - * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) - */ - public static boolean isNotBlank(final CharSequence cs) { - return !isBlank(cs); - } - - /** - *

Checks if any one of the CharSequences are blank ("") or null and not whitespace only..

- * - *
-     * StringUtils.isAnyBlank(null)             = true
-     * StringUtils.isAnyBlank(null, "foo")      = true
-     * StringUtils.isAnyBlank(null, null)       = true
-     * StringUtils.isAnyBlank("", "bar")        = true
-     * StringUtils.isAnyBlank("bob", "")        = true
-     * StringUtils.isAnyBlank("  bob  ", null)  = true
-     * StringUtils.isAnyBlank(" ", "bar")       = true
-     * StringUtils.isAnyBlank("foo", "bar")     = false
-     * 
- * - * @param css the CharSequences to check, may be null or empty - * @return {@code true} if any of the CharSequences are blank or null or whitespace only - * @since 3.2 - */ - public static boolean isAnyBlank(final CharSequence... css) { - if (ArrayUtils.isEmpty(css)) { - return true; - } - for (final CharSequence cs : css){ - if (isBlank(cs)) { - return true; - } - } - return false; - } - - /** - *

Checks if none of the CharSequences are blank ("") or null and whitespace only..

- * - *
-     * StringUtils.isNoneBlank(null)             = false
-     * StringUtils.isNoneBlank(null, "foo")      = false
-     * StringUtils.isNoneBlank(null, null)       = false
-     * StringUtils.isNoneBlank("", "bar")        = false
-     * StringUtils.isNoneBlank("bob", "")        = false
-     * StringUtils.isNoneBlank("  bob  ", null)  = false
-     * StringUtils.isNoneBlank(" ", "bar")       = false
-     * StringUtils.isNoneBlank("foo", "bar")     = true
-     * 
- * - * @param css the CharSequences to check, may be null or empty - * @return {@code true} if none of the CharSequences are blank or null or whitespace only - * @since 3.2 - */ - public static boolean isNoneBlank(final CharSequence... css) { - return !isAnyBlank(css); - } - - // Trim - //----------------------------------------------------------------------- - /** - *

Removes control characters (char <= 32) from both - * ends of this String, handling {@code null} by returning - * {@code null}.

- * - *

The String is trimmed using {@link String#trim()}. - * Trim removes start and end characters <= 32. - * To strip whitespace use {@link #strip(String)}.

- * - *

To trim your choice of characters, use the - * {@link #strip(String, String)} methods.

- * - *
-     * StringUtils.trim(null)          = null
-     * StringUtils.trim("")            = ""
-     * StringUtils.trim("     ")       = ""
-     * StringUtils.trim("abc")         = "abc"
-     * StringUtils.trim("    abc    ") = "abc"
-     * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed string, {@code null} if null String input - */ - public static String trim(final String str) { - return str == null ? null : str.trim(); - } - - /** - *

Removes control characters (char <= 32) from both - * ends of this String returning {@code null} if the String is - * empty ("") after the trim or if it is {@code null}. - * - *

The String is trimmed using {@link String#trim()}. - * Trim removes start and end characters <= 32. - * To strip whitespace use {@link #stripToNull(String)}.

- * - *
-     * StringUtils.trimToNull(null)          = null
-     * StringUtils.trimToNull("")            = null
-     * StringUtils.trimToNull("     ")       = null
-     * StringUtils.trimToNull("abc")         = "abc"
-     * StringUtils.trimToNull("    abc    ") = "abc"
-     * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed String, - * {@code null} if only chars <= 32, empty or null String input - * @since 2.0 - */ - public static String trimToNull(final String str) { - final String ts = trim(str); - return isEmpty(ts) ? null : ts; - } - - /** - *

Removes control characters (char <= 32) from both - * ends of this String returning an empty String ("") if the String - * is empty ("") after the trim or if it is {@code null}. - * - *

The String is trimmed using {@link String#trim()}. - * Trim removes start and end characters <= 32. - * To strip whitespace use {@link #stripToEmpty(String)}.

- * - *
-     * StringUtils.trimToEmpty(null)          = ""
-     * StringUtils.trimToEmpty("")            = ""
-     * StringUtils.trimToEmpty("     ")       = ""
-     * StringUtils.trimToEmpty("abc")         = "abc"
-     * StringUtils.trimToEmpty("    abc    ") = "abc"
-     * 
- * - * @param str the String to be trimmed, may be null - * @return the trimmed String, or an empty String if {@code null} input - * @since 2.0 - */ - public static String trimToEmpty(final String str) { - return str == null ? EMPTY : str.trim(); - } - - // Stripping - //----------------------------------------------------------------------- - /** - *

Strips whitespace from the start and end of a String.

- * - *

This is similar to {@link #trim(String)} but removes whitespace. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.strip(null)     = null
-     * StringUtils.strip("")       = ""
-     * StringUtils.strip("   ")    = ""
-     * StringUtils.strip("abc")    = "abc"
-     * StringUtils.strip("  abc")  = "abc"
-     * StringUtils.strip("abc  ")  = "abc"
-     * StringUtils.strip(" abc ")  = "abc"
-     * StringUtils.strip(" ab c ") = "ab c"
-     * 
- * - * @param str the String to remove whitespace from, may be null - * @return the stripped String, {@code null} if null String input - */ - public static String strip(final String str) { - return strip(str, null); - } - - /** - *

Strips whitespace from the start and end of a String returning - * {@code null} if the String is empty ("") after the strip.

- * - *

This is similar to {@link #trimToNull(String)} but removes whitespace. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripToNull(null)     = null
-     * StringUtils.stripToNull("")       = null
-     * StringUtils.stripToNull("   ")    = null
-     * StringUtils.stripToNull("abc")    = "abc"
-     * StringUtils.stripToNull("  abc")  = "abc"
-     * StringUtils.stripToNull("abc  ")  = "abc"
-     * StringUtils.stripToNull(" abc ")  = "abc"
-     * StringUtils.stripToNull(" ab c ") = "ab c"
-     * 
- * - * @param str the String to be stripped, may be null - * @return the stripped String, - * {@code null} if whitespace, empty or null String input - * @since 2.0 - */ - public static String stripToNull(String str) { - if (str == null) { - return null; - } - str = strip(str, null); - return str.isEmpty() ? null : str; - } - - /** - *

Strips whitespace from the start and end of a String returning - * an empty String if {@code null} input.

- * - *

This is similar to {@link #trimToEmpty(String)} but removes whitespace. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripToEmpty(null)     = ""
-     * StringUtils.stripToEmpty("")       = ""
-     * StringUtils.stripToEmpty("   ")    = ""
-     * StringUtils.stripToEmpty("abc")    = "abc"
-     * StringUtils.stripToEmpty("  abc")  = "abc"
-     * StringUtils.stripToEmpty("abc  ")  = "abc"
-     * StringUtils.stripToEmpty(" abc ")  = "abc"
-     * StringUtils.stripToEmpty(" ab c ") = "ab c"
-     * 
- * - * @param str the String to be stripped, may be null - * @return the trimmed String, or an empty String if {@code null} input - * @since 2.0 - */ - public static String stripToEmpty(final String str) { - return str == null ? EMPTY : strip(str, null); - } - - /** - *

Strips any of a set of characters from the start and end of a String. - * This is similar to {@link String#trim()} but allows the characters - * to be stripped to be controlled.

- * - *

A {@code null} input String returns {@code null}. - * An empty string ("") input returns the empty string.

- * - *

If the stripChars String is {@code null}, whitespace is - * stripped as defined by {@link Character#isWhitespace(char)}. - * Alternatively use {@link #strip(String)}.

- * - *
-     * StringUtils.strip(null, *)          = null
-     * StringUtils.strip("", *)            = ""
-     * StringUtils.strip("abc", null)      = "abc"
-     * StringUtils.strip("  abc", null)    = "abc"
-     * StringUtils.strip("abc  ", null)    = "abc"
-     * StringUtils.strip(" abc ", null)    = "abc"
-     * StringUtils.strip("  abcyx", "xyz") = "  abc"
-     * 
- * - * @param str the String to remove characters from, may be null - * @param stripChars the characters to remove, null treated as whitespace - * @return the stripped String, {@code null} if null String input - */ - public static String strip(String str, final String stripChars) { - if (isEmpty(str)) { - return str; - } - str = stripStart(str, stripChars); - return stripEnd(str, stripChars); - } - - /** - *

Strips any of a set of characters from the start of a String.

- * - *

A {@code null} input String returns {@code null}. - * An empty string ("") input returns the empty string.

- * - *

If the stripChars String is {@code null}, whitespace is - * stripped as defined by {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripStart(null, *)          = null
-     * StringUtils.stripStart("", *)            = ""
-     * StringUtils.stripStart("abc", "")        = "abc"
-     * StringUtils.stripStart("abc", null)      = "abc"
-     * StringUtils.stripStart("  abc", null)    = "abc"
-     * StringUtils.stripStart("abc  ", null)    = "abc  "
-     * StringUtils.stripStart(" abc ", null)    = "abc "
-     * StringUtils.stripStart("yxabc  ", "xyz") = "abc  "
-     * 
- * - * @param str the String to remove characters from, may be null - * @param stripChars the characters to remove, null treated as whitespace - * @return the stripped String, {@code null} if null String input - */ - public static String stripStart(final String str, final String stripChars) { - int strLen; - if (str == null || (strLen = str.length()) == 0) { - return str; - } - int start = 0; - if (stripChars == null) { - while (start != strLen && Character.isWhitespace(str.charAt(start))) { - start++; - } - } else if (stripChars.isEmpty()) { - return str; - } else { - while (start != strLen && stripChars.indexOf(str.charAt(start)) != INDEX_NOT_FOUND) { - start++; - } - } - return str.substring(start); - } - - /** - *

Strips any of a set of characters from the end of a String.

- * - *

A {@code null} input String returns {@code null}. - * An empty string ("") input returns the empty string.

- * - *

If the stripChars String is {@code null}, whitespace is - * stripped as defined by {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripEnd(null, *)          = null
-     * StringUtils.stripEnd("", *)            = ""
-     * StringUtils.stripEnd("abc", "")        = "abc"
-     * StringUtils.stripEnd("abc", null)      = "abc"
-     * StringUtils.stripEnd("  abc", null)    = "  abc"
-     * StringUtils.stripEnd("abc  ", null)    = "abc"
-     * StringUtils.stripEnd(" abc ", null)    = " abc"
-     * StringUtils.stripEnd("  abcyx", "xyz") = "  abc"
-     * StringUtils.stripEnd("120.00", ".0")   = "12"
-     * 
- * - * @param str the String to remove characters from, may be null - * @param stripChars the set of characters to remove, null treated as whitespace - * @return the stripped String, {@code null} if null String input - */ - public static String stripEnd(final String str, final String stripChars) { - int end; - if (str == null || (end = str.length()) == 0) { - return str; - } - - if (stripChars == null) { - while (end != 0 && Character.isWhitespace(str.charAt(end - 1))) { - end--; - } - } else if (stripChars.isEmpty()) { - return str; - } else { - while (end != 0 && stripChars.indexOf(str.charAt(end - 1)) != INDEX_NOT_FOUND) { - end--; - } - } - return str.substring(0, end); - } - - // StripAll - //----------------------------------------------------------------------- - /** - *

Strips whitespace from the start and end of every String in an array. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

A new array is returned each time, except for length zero. - * A {@code null} array will return {@code null}. - * An empty array will return itself. - * A {@code null} array entry will be ignored.

- * - *
-     * StringUtils.stripAll(null)             = null
-     * StringUtils.stripAll([])               = []
-     * StringUtils.stripAll(["abc", "  abc"]) = ["abc", "abc"]
-     * StringUtils.stripAll(["abc  ", null])  = ["abc", null]
-     * 
- * - * @param strs the array to remove whitespace from, may be null - * @return the stripped Strings, {@code null} if null array input - */ - public static String[] stripAll(final String... strs) { - return stripAll(strs, null); - } - - /** - *

Strips any of a set of characters from the start and end of every - * String in an array.

- *

Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

A new array is returned each time, except for length zero. - * A {@code null} array will return {@code null}. - * An empty array will return itself. - * A {@code null} array entry will be ignored. - * A {@code null} stripChars will strip whitespace as defined by - * {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.stripAll(null, *)                = null
-     * StringUtils.stripAll([], *)                  = []
-     * StringUtils.stripAll(["abc", "  abc"], null) = ["abc", "abc"]
-     * StringUtils.stripAll(["abc  ", null], null)  = ["abc", null]
-     * StringUtils.stripAll(["abc  ", null], "yz")  = ["abc  ", null]
-     * StringUtils.stripAll(["yabcz", null], "yz")  = ["abc", null]
-     * 
- * - * @param strs the array to remove characters from, may be null - * @param stripChars the characters to remove, null treated as whitespace - * @return the stripped Strings, {@code null} if null array input - */ - public static String[] stripAll(final String[] strs, final String stripChars) { - int strsLen; - if (strs == null || (strsLen = strs.length) == 0) { - return strs; - } - final String[] newArr = new String[strsLen]; - for (int i = 0; i < strsLen; i++) { - newArr[i] = strip(strs[i], stripChars); - } - return newArr; - } - - /** - *

Removes diacritics (~= accents) from a string. The case will not be altered.

- *

For instance, 'à' will be replaced by 'a'.

- *

Note that ligatures will be left as is.

- * - *
-     * StringUtils.stripAccents(null)                = null
-     * StringUtils.stripAccents("")                  = ""
-     * StringUtils.stripAccents("control")           = "control"
-     * StringUtils.stripAccents("éclair")     = "eclair"
-     * 
- * - * @param input String to be stripped - * @return input text with diacritics removed - * - * @since 3.0 - */ - // See also Lucene's ASCIIFoldingFilter (Lucene 2.9) that replaces accented characters by their unaccented equivalent (and uncommitted bug fix: https://issues.apache.org/jira/browse/LUCENE-1343?focusedCommentId=12858907&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#action_12858907). - public static String stripAccents(final String input) { - if(input == null) { - return null; - } - final Pattern pattern = Pattern.compile("\\p{InCombiningDiacriticalMarks}+");//$NON-NLS-1$ - final String decomposed = Normalizer.normalize(input, Normalizer.Form.NFD); - // Note that this doesn't correctly remove ligatures... - return pattern.matcher(decomposed).replaceAll("");//$NON-NLS-1$ - } - - // Equals - //----------------------------------------------------------------------- - /** - *

Compares two CharSequences, returning {@code true} if they represent - * equal sequences of characters.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case sensitive.

- * - *
-     * StringUtils.equals(null, null)   = true
-     * StringUtils.equals(null, "abc")  = false
-     * StringUtils.equals("abc", null)  = false
-     * StringUtils.equals("abc", "abc") = true
-     * StringUtils.equals("abc", "ABC") = false
-     * 
- * - * @see Object#equals(Object) - * @param cs1 the first CharSequence, may be {@code null} - * @param cs2 the second CharSequence, may be {@code null} - * @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null} - * @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence) - */ - public static boolean equals(final CharSequence cs1, final CharSequence cs2) { - if (cs1 == cs2) { - return true; - } - if (cs1 == null || cs2 == null) { - return false; - } - if (cs1 instanceof String && cs2 instanceof String) { - return cs1.equals(cs2); - } - return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length())); - } - - /** - *

Compares two CharSequences, returning {@code true} if they represent - * equal sequences of characters, ignoring case.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered equal. Comparison is case insensitive.

- * - *
-     * StringUtils.equalsIgnoreCase(null, null)   = true
-     * StringUtils.equalsIgnoreCase(null, "abc")  = false
-     * StringUtils.equalsIgnoreCase("abc", null)  = false
-     * StringUtils.equalsIgnoreCase("abc", "abc") = true
-     * StringUtils.equalsIgnoreCase("abc", "ABC") = true
-     * 
- * - * @param str1 the first CharSequence, may be null - * @param str2 the second CharSequence, may be null - * @return {@code true} if the CharSequence are equal, case insensitive, or - * both {@code null} - * @since 3.0 Changed signature from equalsIgnoreCase(String, String) to equalsIgnoreCase(CharSequence, CharSequence) - */ - public static boolean equalsIgnoreCase(final CharSequence str1, final CharSequence str2) { - if (str1 == null || str2 == null) { - return str1 == str2; - } else if (str1 == str2) { - return true; - } else if (str1.length() != str2.length()) { - return false; - } else { - return CharSequenceUtils.regionMatches(str1, true, 0, str2, 0, str1.length()); - } - } - - // IndexOf - //----------------------------------------------------------------------- - /** - *

Finds the first index within a CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(int, int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code INDEX_NOT_FOUND (-1)}.

- * - *
-     * StringUtils.indexOf(null, *)         = -1
-     * StringUtils.indexOf("", *)           = -1
-     * StringUtils.indexOf("aabaabaa", 'a') = 0
-     * StringUtils.indexOf("aabaabaa", 'b') = 2
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @return the first index of the search character, - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from indexOf(String, int) to indexOf(CharSequence, int) - */ - public static int indexOf(final CharSequence seq, final int searchChar) { - if (isEmpty(seq)) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.indexOf(seq, searchChar, 0); - } - - /** - *

Finds the first index within a CharSequence from a start position, - * handling {@code null}. - * This method uses {@link String#indexOf(int, int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code (INDEX_NOT_FOUND) -1}. - * A negative start position is treated as zero. - * A start position greater than the string length returns {@code -1}.

- * - *
-     * StringUtils.indexOf(null, *, *)          = -1
-     * StringUtils.indexOf("", *, *)            = -1
-     * StringUtils.indexOf("aabaabaa", 'b', 0)  = 2
-     * StringUtils.indexOf("aabaabaa", 'b', 3)  = 5
-     * StringUtils.indexOf("aabaabaa", 'b', 9)  = -1
-     * StringUtils.indexOf("aabaabaa", 'b', -1) = 2
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @param startPos the start position, negative treated as zero - * @return the first index of the search character (always ≥ startPos), - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from indexOf(String, int, int) to indexOf(CharSequence, int, int) - */ - public static int indexOf(final CharSequence seq, final int searchChar, final int startPos) { - if (isEmpty(seq)) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.indexOf(seq, searchChar, startPos); - } - - /** - *

Finds the first index within a CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(String, int)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}.

- * - *
-     * StringUtils.indexOf(null, *)          = -1
-     * StringUtils.indexOf(*, null)          = -1
-     * StringUtils.indexOf("", "")           = 0
-     * StringUtils.indexOf("", *)            = -1 (except when * = "")
-     * StringUtils.indexOf("aabaabaa", "a")  = 0
-     * StringUtils.indexOf("aabaabaa", "b")  = 2
-     * StringUtils.indexOf("aabaabaa", "ab") = 1
-     * StringUtils.indexOf("aabaabaa", "")   = 0
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @return the first index of the search CharSequence, - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from indexOf(String, String) to indexOf(CharSequence, CharSequence) - */ - public static int indexOf(final CharSequence seq, final CharSequence searchSeq) { - if (seq == null || searchSeq == null) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.indexOf(seq, searchSeq, 0); - } - - /** - *

Finds the first index within a CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(String, int)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position is treated as zero. - * An empty ("") search CharSequence always matches. - * A start position greater than the string length only matches - * an empty search CharSequence.

- * - *
-     * StringUtils.indexOf(null, *, *)          = -1
-     * StringUtils.indexOf(*, null, *)          = -1
-     * StringUtils.indexOf("", "", 0)           = 0
-     * StringUtils.indexOf("", *, 0)            = -1 (except when * = "")
-     * StringUtils.indexOf("aabaabaa", "a", 0)  = 0
-     * StringUtils.indexOf("aabaabaa", "b", 0)  = 2
-     * StringUtils.indexOf("aabaabaa", "ab", 0) = 1
-     * StringUtils.indexOf("aabaabaa", "b", 3)  = 5
-     * StringUtils.indexOf("aabaabaa", "b", 9)  = -1
-     * StringUtils.indexOf("aabaabaa", "b", -1) = 2
-     * StringUtils.indexOf("aabaabaa", "", 2)   = 2
-     * StringUtils.indexOf("abc", "", 9)        = 3
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @param startPos the start position, negative treated as zero - * @return the first index of the search CharSequence (always ≥ startPos), - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from indexOf(String, String, int) to indexOf(CharSequence, CharSequence, int) - */ - public static int indexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) { - if (seq == null || searchSeq == null) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.indexOf(seq, searchSeq, startPos); - } - - /** - *

Finds the n-th index within a CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(String)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}.

- * - *
-     * StringUtils.ordinalIndexOf(null, *, *)          = -1
-     * StringUtils.ordinalIndexOf(*, null, *)          = -1
-     * StringUtils.ordinalIndexOf("", "", *)           = 0
-     * StringUtils.ordinalIndexOf("aabaabaa", "a", 1)  = 0
-     * StringUtils.ordinalIndexOf("aabaabaa", "a", 2)  = 1
-     * StringUtils.ordinalIndexOf("aabaabaa", "b", 1)  = 2
-     * StringUtils.ordinalIndexOf("aabaabaa", "b", 2)  = 5
-     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 1) = 1
-     * StringUtils.ordinalIndexOf("aabaabaa", "ab", 2) = 4
-     * StringUtils.ordinalIndexOf("aabaabaa", "", 1)   = 0
-     * StringUtils.ordinalIndexOf("aabaabaa", "", 2)   = 0
-     * 
- * - *

Note that 'head(CharSequence str, int n)' may be implemented as:

- * - *
-     *   str.substring(0, lastOrdinalIndexOf(str, "\n", n))
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param ordinal the n-th {@code searchStr} to find - * @return the n-th index of the search CharSequence, - * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input - * @since 2.1 - * @since 3.0 Changed signature from ordinalIndexOf(String, String, int) to ordinalIndexOf(CharSequence, CharSequence, int) - */ - public static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) { - return ordinalIndexOf(str, searchStr, ordinal, false); - } - - /** - *

Finds the n-th index within a String, handling {@code null}. - * This method uses {@link String#indexOf(String)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}.

- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param ordinal the n-th {@code searchStr} to find - * @param lastIndex true if lastOrdinalIndexOf() otherwise false if ordinalIndexOf() - * @return the n-th index of the search CharSequence, - * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input - */ - // Shared code between ordinalIndexOf(String,String,int) and lastOrdinalIndexOf(String,String,int) - private static int ordinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal, final boolean lastIndex) { - if (str == null || searchStr == null || ordinal <= 0) { - return INDEX_NOT_FOUND; - } - if (searchStr.length() == 0) { - return lastIndex ? str.length() : 0; - } - int found = 0; - int index = lastIndex ? str.length() : INDEX_NOT_FOUND; - do { - if (lastIndex) { - index = CharSequenceUtils.lastIndexOf(str, searchStr, index - searchStr.length()); - } else { - index = CharSequenceUtils.indexOf(str, searchStr, index + searchStr.length()); - } - if (index < 0) { - return index; - } - found++; - } while (found < ordinal); - return index; - } - - /** - *

Case in-sensitive find of the first index within a CharSequence.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position is treated as zero. - * An empty ("") search CharSequence always matches. - * A start position greater than the string length only matches - * an empty search CharSequence.

- * - *
-     * StringUtils.indexOfIgnoreCase(null, *)          = -1
-     * StringUtils.indexOfIgnoreCase(*, null)          = -1
-     * StringUtils.indexOfIgnoreCase("", "")           = 0
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "a")  = 0
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "b")  = 2
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "ab") = 1
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @return the first index of the search CharSequence, - * -1 if no match or {@code null} string input - * @since 2.5 - * @since 3.0 Changed signature from indexOfIgnoreCase(String, String) to indexOfIgnoreCase(CharSequence, CharSequence) - */ - public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { - return indexOfIgnoreCase(str, searchStr, 0); - } - - /** - *

Case in-sensitive find of the first index within a CharSequence - * from the specified position.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position is treated as zero. - * An empty ("") search CharSequence always matches. - * A start position greater than the string length only matches - * an empty search CharSequence.

- * - *
-     * StringUtils.indexOfIgnoreCase(null, *, *)          = -1
-     * StringUtils.indexOfIgnoreCase(*, null, *)          = -1
-     * StringUtils.indexOfIgnoreCase("", "", 0)           = 0
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "A", 0)  = 0
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 0)  = 2
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "AB", 0) = 1
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 3)  = 5
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", 9)  = -1
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "B", -1) = 2
-     * StringUtils.indexOfIgnoreCase("aabaabaa", "", 2)   = 2
-     * StringUtils.indexOfIgnoreCase("abc", "", 9)        = 3
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param startPos the start position, negative treated as zero - * @return the first index of the search CharSequence (always ≥ startPos), - * -1 if no match or {@code null} string input - * @since 2.5 - * @since 3.0 Changed signature from indexOfIgnoreCase(String, String, int) to indexOfIgnoreCase(CharSequence, CharSequence, int) - */ - public static int indexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) { - if (str == null || searchStr == null) { - return INDEX_NOT_FOUND; - } - if (startPos < 0) { - startPos = 0; - } - final int endLimit = str.length() - searchStr.length() + 1; - if (startPos > endLimit) { - return INDEX_NOT_FOUND; - } - if (searchStr.length() == 0) { - return startPos; - } - for (int i = startPos; i < endLimit; i++) { - if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - // LastIndexOf - //----------------------------------------------------------------------- - /** - *

Finds the last index within a CharSequence, handling {@code null}. - * This method uses {@link String#lastIndexOf(int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code -1}.

- * - *
-     * StringUtils.lastIndexOf(null, *)         = -1
-     * StringUtils.lastIndexOf("", *)           = -1
-     * StringUtils.lastIndexOf("aabaabaa", 'a') = 7
-     * StringUtils.lastIndexOf("aabaabaa", 'b') = 5
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @return the last index of the search character, - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from lastIndexOf(String, int) to lastIndexOf(CharSequence, int) - */ - public static int lastIndexOf(final CharSequence seq, final int searchChar) { - if (isEmpty(seq)) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.lastIndexOf(seq, searchChar, seq.length()); - } - - /** - *

Finds the last index within a CharSequence from a start position, - * handling {@code null}. - * This method uses {@link String#lastIndexOf(int, int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code -1}. - * A negative start position returns {@code -1}. - * A start position greater than the string length searches the whole string. - * The search starts at the startPos and works backwards; matches starting after the start - * position are ignored. - *

- * - *
-     * StringUtils.lastIndexOf(null, *, *)          = -1
-     * StringUtils.lastIndexOf("", *,  *)           = -1
-     * StringUtils.lastIndexOf("aabaabaa", 'b', 8)  = 5
-     * StringUtils.lastIndexOf("aabaabaa", 'b', 4)  = 2
-     * StringUtils.lastIndexOf("aabaabaa", 'b', 0)  = -1
-     * StringUtils.lastIndexOf("aabaabaa", 'b', 9)  = 5
-     * StringUtils.lastIndexOf("aabaabaa", 'b', -1) = -1
-     * StringUtils.lastIndexOf("aabaabaa", 'a', 0)  = 0
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @param startPos the start position - * @return the last index of the search character (always ≤ startPos), - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from lastIndexOf(String, int, int) to lastIndexOf(CharSequence, int, int) - */ - public static int lastIndexOf(final CharSequence seq, final int searchChar, final int startPos) { - if (isEmpty(seq)) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.lastIndexOf(seq, searchChar, startPos); - } - - /** - *

Finds the last index within a CharSequence, handling {@code null}. - * This method uses {@link String#lastIndexOf(String)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}.

- * - *
-     * StringUtils.lastIndexOf(null, *)          = -1
-     * StringUtils.lastIndexOf(*, null)          = -1
-     * StringUtils.lastIndexOf("", "")           = 0
-     * StringUtils.lastIndexOf("aabaabaa", "a")  = 7
-     * StringUtils.lastIndexOf("aabaabaa", "b")  = 5
-     * StringUtils.lastIndexOf("aabaabaa", "ab") = 4
-     * StringUtils.lastIndexOf("aabaabaa", "")   = 8
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @return the last index of the search String, - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from lastIndexOf(String, String) to lastIndexOf(CharSequence, CharSequence) - */ - public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq) { - if (seq == null || searchSeq == null) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.lastIndexOf(seq, searchSeq, seq.length()); - } - - /** - *

Finds the n-th last index within a String, handling {@code null}. - * This method uses {@link String#lastIndexOf(String)}.

- * - *

A {@code null} String will return {@code -1}.

- * - *
-     * StringUtils.lastOrdinalIndexOf(null, *, *)          = -1
-     * StringUtils.lastOrdinalIndexOf(*, null, *)          = -1
-     * StringUtils.lastOrdinalIndexOf("", "", *)           = 0
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 1)  = 7
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "a", 2)  = 6
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 1)  = 5
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "b", 2)  = 2
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 1) = 4
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "ab", 2) = 1
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 1)   = 8
-     * StringUtils.lastOrdinalIndexOf("aabaabaa", "", 2)   = 8
-     * 
- * - *

Note that 'tail(CharSequence str, int n)' may be implemented as:

- * - *
-     *   str.substring(lastOrdinalIndexOf(str, "\n", n) + 1)
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param ordinal the n-th last {@code searchStr} to find - * @return the n-th last index of the search CharSequence, - * {@code -1} ({@code INDEX_NOT_FOUND}) if no match or {@code null} string input - * @since 2.5 - * @since 3.0 Changed signature from lastOrdinalIndexOf(String, String, int) to lastOrdinalIndexOf(CharSequence, CharSequence, int) - */ - public static int lastOrdinalIndexOf(final CharSequence str, final CharSequence searchStr, final int ordinal) { - return ordinalIndexOf(str, searchStr, ordinal, true); - } - - /** - *

Finds the last index within a CharSequence, handling {@code null}. - * This method uses {@link String#lastIndexOf(String, int)} if possible.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position returns {@code -1}. - * An empty ("") search CharSequence always matches unless the start position is negative. - * A start position greater than the string length searches the whole string. - * The search starts at the startPos and works backwards; matches starting after the start - * position are ignored. - *

- * - *
-     * StringUtils.lastIndexOf(null, *, *)          = -1
-     * StringUtils.lastIndexOf(*, null, *)          = -1
-     * StringUtils.lastIndexOf("aabaabaa", "a", 8)  = 7
-     * StringUtils.lastIndexOf("aabaabaa", "b", 8)  = 5
-     * StringUtils.lastIndexOf("aabaabaa", "ab", 8) = 4
-     * StringUtils.lastIndexOf("aabaabaa", "b", 9)  = 5
-     * StringUtils.lastIndexOf("aabaabaa", "b", -1) = -1
-     * StringUtils.lastIndexOf("aabaabaa", "a", 0)  = 0
-     * StringUtils.lastIndexOf("aabaabaa", "b", 0)  = -1
-     * StringUtils.lastIndexOf("aabaabaa", "b", 1)  = -1
-     * StringUtils.lastIndexOf("aabaabaa", "b", 2)  = 2
-     * StringUtils.lastIndexOf("aabaabaa", "ba", 2)  = -1
-     * StringUtils.lastIndexOf("aabaabaa", "ba", 2)  = 2
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @param startPos the start position, negative treated as zero - * @return the last index of the search CharSequence (always ≤ startPos), - * -1 if no match or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from lastIndexOf(String, String, int) to lastIndexOf(CharSequence, CharSequence, int) - */ - public static int lastIndexOf(final CharSequence seq, final CharSequence searchSeq, final int startPos) { - if (seq == null || searchSeq == null) { - return INDEX_NOT_FOUND; - } - return CharSequenceUtils.lastIndexOf(seq, searchSeq, startPos); - } - - /** - *

Case in-sensitive find of the last index within a CharSequence.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position returns {@code -1}. - * An empty ("") search CharSequence always matches unless the start position is negative. - * A start position greater than the string length searches the whole string.

- * - *
-     * StringUtils.lastIndexOfIgnoreCase(null, *)          = -1
-     * StringUtils.lastIndexOfIgnoreCase(*, null)          = -1
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A")  = 7
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B")  = 5
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB") = 4
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @return the first index of the search CharSequence, - * -1 if no match or {@code null} string input - * @since 2.5 - * @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String) to lastIndexOfIgnoreCase(CharSequence, CharSequence) - */ - public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr) { - if (str == null || searchStr == null) { - return INDEX_NOT_FOUND; - } - return lastIndexOfIgnoreCase(str, searchStr, str.length()); - } - - /** - *

Case in-sensitive find of the last index within a CharSequence - * from the specified position.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A negative start position returns {@code -1}. - * An empty ("") search CharSequence always matches unless the start position is negative. - * A start position greater than the string length searches the whole string. - * The search starts at the startPos and works backwards; matches starting after the start - * position are ignored. - *

- * - *
-     * StringUtils.lastIndexOfIgnoreCase(null, *, *)          = -1
-     * StringUtils.lastIndexOfIgnoreCase(*, null, *)          = -1
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 8)  = 7
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 8)  = 5
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "AB", 8) = 4
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 9)  = 5
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", -1) = -1
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "A", 0)  = 0
-     * StringUtils.lastIndexOfIgnoreCase("aabaabaa", "B", 0)  = -1
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @param startPos the start position - * @return the last index of the search CharSequence (always ≤ startPos), - * -1 if no match or {@code null} input - * @since 2.5 - * @since 3.0 Changed signature from lastIndexOfIgnoreCase(String, String, int) to lastIndexOfIgnoreCase(CharSequence, CharSequence, int) - */ - public static int lastIndexOfIgnoreCase(final CharSequence str, final CharSequence searchStr, int startPos) { - if (str == null || searchStr == null) { - return INDEX_NOT_FOUND; - } - if (startPos > str.length() - searchStr.length()) { - startPos = str.length() - searchStr.length(); - } - if (startPos < 0) { - return INDEX_NOT_FOUND; - } - if (searchStr.length() == 0) { - return startPos; - } - - for (int i = startPos; i >= 0; i--) { - if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, searchStr.length())) { - return i; - } - } - return INDEX_NOT_FOUND; - } - - // Contains - //----------------------------------------------------------------------- - /** - *

Checks if CharSequence contains a search character, handling {@code null}. - * This method uses {@link String#indexOf(int)} if possible.

- * - *

A {@code null} or empty ("") CharSequence will return {@code false}.

- * - *
-     * StringUtils.contains(null, *)    = false
-     * StringUtils.contains("", *)      = false
-     * StringUtils.contains("abc", 'a') = true
-     * StringUtils.contains("abc", 'z') = false
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChar the character to find - * @return true if the CharSequence contains the search character, - * false if not or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from contains(String, int) to contains(CharSequence, int) - */ - public static boolean contains(final CharSequence seq, final int searchChar) { - if (isEmpty(seq)) { - return false; - } - return CharSequenceUtils.indexOf(seq, searchChar, 0) >= 0; - } - - /** - *

Checks if CharSequence contains a search CharSequence, handling {@code null}. - * This method uses {@link String#indexOf(String)} if possible.

- * - *

A {@code null} CharSequence will return {@code false}.

- * - *
-     * StringUtils.contains(null, *)     = false
-     * StringUtils.contains(*, null)     = false
-     * StringUtils.contains("", "")      = true
-     * StringUtils.contains("abc", "")   = true
-     * StringUtils.contains("abc", "a")  = true
-     * StringUtils.contains("abc", "z")  = false
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchSeq the CharSequence to find, may be null - * @return true if the CharSequence contains the search CharSequence, - * false if not or {@code null} string input - * @since 2.0 - * @since 3.0 Changed signature from contains(String, String) to contains(CharSequence, CharSequence) - */ - public static boolean contains(final CharSequence seq, final CharSequence searchSeq) { - if (seq == null || searchSeq == null) { - return false; - } - return CharSequenceUtils.indexOf(seq, searchSeq, 0) >= 0; - } - - /** - *

Checks if CharSequence contains a search CharSequence irrespective of case, - * handling {@code null}. Case-insensitivity is defined as by - * {@link String#equalsIgnoreCase(String)}. - * - *

A {@code null} CharSequence will return {@code false}.

- * - *
-     * StringUtils.contains(null, *) = false
-     * StringUtils.contains(*, null) = false
-     * StringUtils.contains("", "") = true
-     * StringUtils.contains("abc", "") = true
-     * StringUtils.contains("abc", "a") = true
-     * StringUtils.contains("abc", "z") = false
-     * StringUtils.contains("abc", "A") = true
-     * StringUtils.contains("abc", "Z") = false
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStr the CharSequence to find, may be null - * @return true if the CharSequence contains the search CharSequence irrespective of - * case or false if not or {@code null} string input - * @since 3.0 Changed signature from containsIgnoreCase(String, String) to containsIgnoreCase(CharSequence, CharSequence) - */ - public static boolean containsIgnoreCase(final CharSequence str, final CharSequence searchStr) { - if (str == null || searchStr == null) { - return false; - } - final int len = searchStr.length(); - final int max = str.length() - len; - for (int i = 0; i <= max; i++) { - if (CharSequenceUtils.regionMatches(str, true, i, searchStr, 0, len)) { - return true; - } - } - return false; - } - - /** - * Check whether the given CharSequence contains any whitespace characters. - * @param seq the CharSequence to check (may be {@code null}) - * @return {@code true} if the CharSequence is not empty and - * contains at least 1 whitespace character - * @see java.lang.Character#isWhitespace - * @since 3.0 - */ - // From org.springframework.util.StringUtils, under Apache License 2.0 - public static boolean containsWhitespace(final CharSequence seq) { - if (isEmpty(seq)) { - return false; - } - final int strLen = seq.length(); - for (int i = 0; i < strLen; i++) { - if (Character.isWhitespace(seq.charAt(i))) { - return true; - } - } - return false; - } - - // IndexOfAny chars - //----------------------------------------------------------------------- - /** - *

Search a CharSequence to find the first index of any - * character in the given set of characters.

- * - *

A {@code null} String will return {@code -1}. - * A {@code null} or zero length search array will return {@code -1}.

- * - *
-     * StringUtils.indexOfAny(null, *)                = -1
-     * StringUtils.indexOfAny("", *)                  = -1
-     * StringUtils.indexOfAny(*, null)                = -1
-     * StringUtils.indexOfAny(*, [])                  = -1
-     * StringUtils.indexOfAny("zzabyycdxx",['z','a']) = 0
-     * StringUtils.indexOfAny("zzabyycdxx",['b','y']) = 3
-     * StringUtils.indexOfAny("aba", ['z'])           = -1
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the index of any of the chars, -1 if no match or null input - * @since 2.0 - * @since 3.0 Changed signature from indexOfAny(String, char[]) to indexOfAny(CharSequence, char...) - */ - public static int indexOfAny(final CharSequence cs, final char... searchChars) { - if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { - return INDEX_NOT_FOUND; - } - final int csLen = cs.length(); - final int csLast = csLen - 1; - final int searchLen = searchChars.length; - final int searchLast = searchLen - 1; - for (int i = 0; i < csLen; i++) { - final char ch = cs.charAt(i); - for (int j = 0; j < searchLen; j++) { - if (searchChars[j] == ch) { - if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) { - // ch is a supplementary character - if (searchChars[j + 1] == cs.charAt(i + 1)) { - return i; - } - } else { - return i; - } - } - } - } - return INDEX_NOT_FOUND; - } - - /** - *

Search a CharSequence to find the first index of any - * character in the given set of characters.

- * - *

A {@code null} String will return {@code -1}. - * A {@code null} search string will return {@code -1}.

- * - *
-     * StringUtils.indexOfAny(null, *)            = -1
-     * StringUtils.indexOfAny("", *)              = -1
-     * StringUtils.indexOfAny(*, null)            = -1
-     * StringUtils.indexOfAny(*, "")              = -1
-     * StringUtils.indexOfAny("zzabyycdxx", "za") = 0
-     * StringUtils.indexOfAny("zzabyycdxx", "by") = 3
-     * StringUtils.indexOfAny("aba","z")          = -1
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the index of any of the chars, -1 if no match or null input - * @since 2.0 - * @since 3.0 Changed signature from indexOfAny(String, String) to indexOfAny(CharSequence, String) - */ - public static int indexOfAny(final CharSequence cs, final String searchChars) { - if (isEmpty(cs) || isEmpty(searchChars)) { - return INDEX_NOT_FOUND; - } - return indexOfAny(cs, searchChars.toCharArray()); - } - - // ContainsAny - //----------------------------------------------------------------------- - /** - *

Checks if the CharSequence contains any character in the given - * set of characters.

- * - *

A {@code null} CharSequence will return {@code false}. - * A {@code null} or zero length search array will return {@code false}.

- * - *
-     * StringUtils.containsAny(null, *)                = false
-     * StringUtils.containsAny("", *)                  = false
-     * StringUtils.containsAny(*, null)                = false
-     * StringUtils.containsAny(*, [])                  = false
-     * StringUtils.containsAny("zzabyycdxx",['z','a']) = true
-     * StringUtils.containsAny("zzabyycdxx",['b','y']) = true
-     * StringUtils.containsAny("zzabyycdxx",['z','y']) = true
-     * StringUtils.containsAny("aba", ['z'])           = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the {@code true} if any of the chars are found, - * {@code false} if no match or null input - * @since 2.4 - * @since 3.0 Changed signature from containsAny(String, char[]) to containsAny(CharSequence, char...) - */ - public static boolean containsAny(final CharSequence cs, final char... searchChars) { - if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { - return false; - } - final int csLength = cs.length(); - final int searchLength = searchChars.length; - final int csLast = csLength - 1; - final int searchLast = searchLength - 1; - for (int i = 0; i < csLength; i++) { - final char ch = cs.charAt(i); - for (int j = 0; j < searchLength; j++) { - if (searchChars[j] == ch) { - if (Character.isHighSurrogate(ch)) { - if (j == searchLast) { - // missing low surrogate, fine, like String.indexOf(String) - return true; - } - if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) { - return true; - } - } else { - // ch is in the Basic Multilingual Plane - return true; - } - } - } - } - return false; - } - - /** - *

- * Checks if the CharSequence contains any character in the given set of characters. - *

- * - *

- * A {@code null} CharSequence will return {@code false}. A {@code null} search CharSequence will return - * {@code false}. - *

- * - *
-     * StringUtils.containsAny(null, *)            = false
-     * StringUtils.containsAny("", *)              = false
-     * StringUtils.containsAny(*, null)            = false
-     * StringUtils.containsAny(*, "")              = false
-     * StringUtils.containsAny("zzabyycdxx", "za") = true
-     * StringUtils.containsAny("zzabyycdxx", "by") = true
-     * StringUtils.containsAny("zzabyycdxx", "zy") = true
-     * StringUtils.containsAny("aba","z")          = false
-     * 
- * - * @param cs - * the CharSequence to check, may be null - * @param searchChars - * the chars to search for, may be null - * @return the {@code true} if any of the chars are found, {@code false} if no match or null input - * @since 2.4 - * @since 3.0 Changed signature from containsAny(String, String) to containsAny(CharSequence, CharSequence) - */ - public static boolean containsAny(final CharSequence cs, final CharSequence searchChars) { - if (searchChars == null) { - return false; - } - return containsAny(cs, CharSequenceUtils.toCharArray(searchChars)); - } - - /** - *

Checks if the CharSequence contains any of the CharSequences in the given array.

- * - *

- * A {@code null} CharSequence will return {@code false}. A {@code null} or zero - * length search array will return {@code false}. - *

- * - *
-     * StringUtils.containsAny(null, *)            = false
-     * StringUtils.containsAny("", *)              = false
-     * StringUtils.containsAny(*, null)            = false
-     * StringUtils.containsAny(*, [])              = false
-     * StringUtils.containsAny("abcd", "ab", null) = false
-     * StringUtils.containsAny("abcd", "ab", "cd") = true
-     * StringUtils.containsAny("abc", "d", "abc")  = true
-     * 
- * - * - * @param cs The CharSequence to check, may be null - * @param searchCharSequences The array of CharSequences to search for, may be null - * @return {@code true} if any of the search CharSequences are found, {@code false} otherwise - * @since 3.4 - */ - public static boolean containsAny(CharSequence cs, CharSequence... searchCharSequences) { - if (isEmpty(cs) || ArrayUtils.isEmpty(searchCharSequences)) { - return false; - } - for (CharSequence searchCharSequence : searchCharSequences) { - if (contains(cs, searchCharSequence)) { - return true; - } - } - return false; - } - - // IndexOfAnyBut chars - //----------------------------------------------------------------------- - /** - *

Searches a CharSequence to find the first index of any - * character not in the given set of characters.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A {@code null} or zero length search array will return {@code -1}.

- * - *
-     * StringUtils.indexOfAnyBut(null, *)                              = -1
-     * StringUtils.indexOfAnyBut("", *)                                = -1
-     * StringUtils.indexOfAnyBut(*, null)                              = -1
-     * StringUtils.indexOfAnyBut(*, [])                                = -1
-     * StringUtils.indexOfAnyBut("zzabyycdxx", new char[] {'z', 'a'} ) = 3
-     * StringUtils.indexOfAnyBut("aba", new char[] {'z'} )             = 0
-     * StringUtils.indexOfAnyBut("aba", new char[] {'a', 'b'} )        = -1
-
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the index of any of the chars, -1 if no match or null input - * @since 2.0 - * @since 3.0 Changed signature from indexOfAnyBut(String, char[]) to indexOfAnyBut(CharSequence, char...) - */ - public static int indexOfAnyBut(final CharSequence cs, final char... searchChars) { - if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { - return INDEX_NOT_FOUND; - } - final int csLen = cs.length(); - final int csLast = csLen - 1; - final int searchLen = searchChars.length; - final int searchLast = searchLen - 1; - outer: - for (int i = 0; i < csLen; i++) { - final char ch = cs.charAt(i); - for (int j = 0; j < searchLen; j++) { - if (searchChars[j] == ch) { - if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) { - if (searchChars[j + 1] == cs.charAt(i + 1)) { - continue outer; - } - } else { - continue outer; - } - } - } - return i; - } - return INDEX_NOT_FOUND; - } - - /** - *

Search a CharSequence to find the first index of any - * character not in the given set of characters.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A {@code null} or empty search string will return {@code -1}.

- * - *
-     * StringUtils.indexOfAnyBut(null, *)            = -1
-     * StringUtils.indexOfAnyBut("", *)              = -1
-     * StringUtils.indexOfAnyBut(*, null)            = -1
-     * StringUtils.indexOfAnyBut(*, "")              = -1
-     * StringUtils.indexOfAnyBut("zzabyycdxx", "za") = 3
-     * StringUtils.indexOfAnyBut("zzabyycdxx", "")   = -1
-     * StringUtils.indexOfAnyBut("aba","ab")         = -1
-     * 
- * - * @param seq the CharSequence to check, may be null - * @param searchChars the chars to search for, may be null - * @return the index of any of the chars, -1 if no match or null input - * @since 2.0 - * @since 3.0 Changed signature from indexOfAnyBut(String, String) to indexOfAnyBut(CharSequence, CharSequence) - */ - public static int indexOfAnyBut(final CharSequence seq, final CharSequence searchChars) { - if (isEmpty(seq) || isEmpty(searchChars)) { - return INDEX_NOT_FOUND; - } - final int strLen = seq.length(); - for (int i = 0; i < strLen; i++) { - final char ch = seq.charAt(i); - final boolean chFound = CharSequenceUtils.indexOf(searchChars, ch, 0) >= 0; - if (i + 1 < strLen && Character.isHighSurrogate(ch)) { - final char ch2 = seq.charAt(i + 1); - if (chFound && CharSequenceUtils.indexOf(searchChars, ch2, 0) < 0) { - return i; - } - } else { - if (!chFound) { - return i; - } - } - } - return INDEX_NOT_FOUND; - } - - // ContainsOnly - //----------------------------------------------------------------------- - /** - *

Checks if the CharSequence contains only certain characters.

- * - *

A {@code null} CharSequence will return {@code false}. - * A {@code null} valid character array will return {@code false}. - * An empty CharSequence (length()=0) always returns {@code true}.

- * - *
-     * StringUtils.containsOnly(null, *)       = false
-     * StringUtils.containsOnly(*, null)       = false
-     * StringUtils.containsOnly("", *)         = true
-     * StringUtils.containsOnly("ab", '')      = false
-     * StringUtils.containsOnly("abab", 'abc') = true
-     * StringUtils.containsOnly("ab1", 'abc')  = false
-     * StringUtils.containsOnly("abz", 'abc')  = false
-     * 
- * - * @param cs the String to check, may be null - * @param valid an array of valid chars, may be null - * @return true if it only contains valid chars and is non-null - * @since 3.0 Changed signature from containsOnly(String, char[]) to containsOnly(CharSequence, char...) - */ - public static boolean containsOnly(final CharSequence cs, final char... valid) { - // All these pre-checks are to maintain API with an older version - if (valid == null || cs == null) { - return false; - } - if (cs.length() == 0) { - return true; - } - if (valid.length == 0) { - return false; - } - return indexOfAnyBut(cs, valid) == INDEX_NOT_FOUND; - } - - /** - *

Checks if the CharSequence contains only certain characters.

- * - *

A {@code null} CharSequence will return {@code false}. - * A {@code null} valid character String will return {@code false}. - * An empty String (length()=0) always returns {@code true}.

- * - *
-     * StringUtils.containsOnly(null, *)       = false
-     * StringUtils.containsOnly(*, null)       = false
-     * StringUtils.containsOnly("", *)         = true
-     * StringUtils.containsOnly("ab", "")      = false
-     * StringUtils.containsOnly("abab", "abc") = true
-     * StringUtils.containsOnly("ab1", "abc")  = false
-     * StringUtils.containsOnly("abz", "abc")  = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param validChars a String of valid chars, may be null - * @return true if it only contains valid chars and is non-null - * @since 2.0 - * @since 3.0 Changed signature from containsOnly(String, String) to containsOnly(CharSequence, String) - */ - public static boolean containsOnly(final CharSequence cs, final String validChars) { - if (cs == null || validChars == null) { - return false; - } - return containsOnly(cs, validChars.toCharArray()); - } - - // ContainsNone - //----------------------------------------------------------------------- - /** - *

Checks that the CharSequence does not contain certain characters.

- * - *

A {@code null} CharSequence will return {@code true}. - * A {@code null} invalid character array will return {@code true}. - * An empty CharSequence (length()=0) always returns true.

- * - *
-     * StringUtils.containsNone(null, *)       = true
-     * StringUtils.containsNone(*, null)       = true
-     * StringUtils.containsNone("", *)         = true
-     * StringUtils.containsNone("ab", '')      = true
-     * StringUtils.containsNone("abab", 'xyz') = true
-     * StringUtils.containsNone("ab1", 'xyz')  = true
-     * StringUtils.containsNone("abz", 'xyz')  = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param searchChars an array of invalid chars, may be null - * @return true if it contains none of the invalid chars, or is null - * @since 2.0 - * @since 3.0 Changed signature from containsNone(String, char[]) to containsNone(CharSequence, char...) - */ - public static boolean containsNone(final CharSequence cs, final char... searchChars) { - if (cs == null || searchChars == null) { - return true; - } - final int csLen = cs.length(); - final int csLast = csLen - 1; - final int searchLen = searchChars.length; - final int searchLast = searchLen - 1; - for (int i = 0; i < csLen; i++) { - final char ch = cs.charAt(i); - for (int j = 0; j < searchLen; j++) { - if (searchChars[j] == ch) { - if (Character.isHighSurrogate(ch)) { - if (j == searchLast) { - // missing low surrogate, fine, like String.indexOf(String) - return false; - } - if (i < csLast && searchChars[j + 1] == cs.charAt(i + 1)) { - return false; - } - } else { - // ch is in the Basic Multilingual Plane - return false; - } - } - } - } - return true; - } - - /** - *

Checks that the CharSequence does not contain certain characters.

- * - *

A {@code null} CharSequence will return {@code true}. - * A {@code null} invalid character array will return {@code true}. - * An empty String ("") always returns true.

- * - *
-     * StringUtils.containsNone(null, *)       = true
-     * StringUtils.containsNone(*, null)       = true
-     * StringUtils.containsNone("", *)         = true
-     * StringUtils.containsNone("ab", "")      = true
-     * StringUtils.containsNone("abab", "xyz") = true
-     * StringUtils.containsNone("ab1", "xyz")  = true
-     * StringUtils.containsNone("abz", "xyz")  = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @param invalidChars a String of invalid chars, may be null - * @return true if it contains none of the invalid chars, or is null - * @since 2.0 - * @since 3.0 Changed signature from containsNone(String, String) to containsNone(CharSequence, String) - */ - public static boolean containsNone(final CharSequence cs, final String invalidChars) { - if (cs == null || invalidChars == null) { - return true; - } - return containsNone(cs, invalidChars.toCharArray()); - } - - // IndexOfAny strings - //----------------------------------------------------------------------- - /** - *

Find the first index of any of a set of potential substrings.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A {@code null} or zero length search array will return {@code -1}. - * A {@code null} search array entry will be ignored, but a search - * array containing "" will return {@code 0} if {@code str} is not - * null. This method uses {@link String#indexOf(String)} if possible.

- * - *
-     * StringUtils.indexOfAny(null, *)                     = -1
-     * StringUtils.indexOfAny(*, null)                     = -1
-     * StringUtils.indexOfAny(*, [])                       = -1
-     * StringUtils.indexOfAny("zzabyycdxx", ["ab","cd"])   = 2
-     * StringUtils.indexOfAny("zzabyycdxx", ["cd","ab"])   = 2
-     * StringUtils.indexOfAny("zzabyycdxx", ["mn","op"])   = -1
-     * StringUtils.indexOfAny("zzabyycdxx", ["zab","aby"]) = 1
-     * StringUtils.indexOfAny("zzabyycdxx", [""])          = 0
-     * StringUtils.indexOfAny("", [""])                    = 0
-     * StringUtils.indexOfAny("", ["a"])                   = -1
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStrs the CharSequences to search for, may be null - * @return the first index of any of the searchStrs in str, -1 if no match - * @since 3.0 Changed signature from indexOfAny(String, String[]) to indexOfAny(CharSequence, CharSequence...) - */ - public static int indexOfAny(final CharSequence str, final CharSequence... searchStrs) { - if (str == null || searchStrs == null) { - return INDEX_NOT_FOUND; - } - final int sz = searchStrs.length; - - // String's can't have a MAX_VALUEth index. - int ret = Integer.MAX_VALUE; - - int tmp = 0; - for (int i = 0; i < sz; i++) { - final CharSequence search = searchStrs[i]; - if (search == null) { - continue; - } - tmp = CharSequenceUtils.indexOf(str, search, 0); - if (tmp == INDEX_NOT_FOUND) { - continue; - } - - if (tmp < ret) { - ret = tmp; - } - } - - return ret == Integer.MAX_VALUE ? INDEX_NOT_FOUND : ret; - } - - /** - *

Find the latest index of any of a set of potential substrings.

- * - *

A {@code null} CharSequence will return {@code -1}. - * A {@code null} search array will return {@code -1}. - * A {@code null} or zero length search array entry will be ignored, - * but a search array containing "" will return the length of {@code str} - * if {@code str} is not null. This method uses {@link String#indexOf(String)} if possible

- * - *
-     * StringUtils.lastIndexOfAny(null, *)                   = -1
-     * StringUtils.lastIndexOfAny(*, null)                   = -1
-     * StringUtils.lastIndexOfAny(*, [])                     = -1
-     * StringUtils.lastIndexOfAny(*, [null])                 = -1
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["ab","cd"]) = 6
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["cd","ab"]) = 6
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn","op"]) = -1
-     * StringUtils.lastIndexOfAny("zzabyycdxx", ["mn",""])   = 10
-     * 
- * - * @param str the CharSequence to check, may be null - * @param searchStrs the CharSequences to search for, may be null - * @return the last index of any of the CharSequences, -1 if no match - * @since 3.0 Changed signature from lastIndexOfAny(String, String[]) to lastIndexOfAny(CharSequence, CharSequence) - */ - public static int lastIndexOfAny(final CharSequence str, final CharSequence... searchStrs) { - if (str == null || searchStrs == null) { - return INDEX_NOT_FOUND; - } - final int sz = searchStrs.length; - int ret = INDEX_NOT_FOUND; - int tmp = 0; - for (int i = 0; i < sz; i++) { - final CharSequence search = searchStrs[i]; - if (search == null) { - continue; - } - tmp = CharSequenceUtils.lastIndexOf(str, search, str.length()); - if (tmp > ret) { - ret = tmp; - } - } - return ret; - } - - // Substring - //----------------------------------------------------------------------- - /** - *

Gets a substring from the specified String avoiding exceptions.

- * - *

A negative start position can be used to start {@code n} - * characters from the end of the String.

- * - *

A {@code null} String will return {@code null}. - * An empty ("") String will return "".

- * - *
-     * StringUtils.substring(null, *)   = null
-     * StringUtils.substring("", *)     = ""
-     * StringUtils.substring("abc", 0)  = "abc"
-     * StringUtils.substring("abc", 2)  = "c"
-     * StringUtils.substring("abc", 4)  = ""
-     * StringUtils.substring("abc", -2) = "bc"
-     * StringUtils.substring("abc", -4) = "abc"
-     * 
- * - * @param str the String to get the substring from, may be null - * @param start the position to start from, negative means - * count back from the end of the String by this many characters - * @return substring from start position, {@code null} if null String input - */ - public static String substring(final String str, int start) { - if (str == null) { - return null; - } - - // handle negatives, which means last n characters - if (start < 0) { - start = str.length() + start; // remember start is negative - } - - if (start < 0) { - start = 0; - } - if (start > str.length()) { - return EMPTY; - } - - return str.substring(start); - } - - /** - *

Gets a substring from the specified String avoiding exceptions.

- * - *

A negative start position can be used to start/end {@code n} - * characters from the end of the String.

- * - *

The returned substring starts with the character in the {@code start} - * position and ends before the {@code end} position. All position counting is - * zero-based -- i.e., to start at the beginning of the string use - * {@code start = 0}. Negative start and end positions can be used to - * specify offsets relative to the end of the String.

- * - *

If {@code start} is not strictly to the left of {@code end}, "" - * is returned.

- * - *
-     * StringUtils.substring(null, *, *)    = null
-     * StringUtils.substring("", * ,  *)    = "";
-     * StringUtils.substring("abc", 0, 2)   = "ab"
-     * StringUtils.substring("abc", 2, 0)   = ""
-     * StringUtils.substring("abc", 2, 4)   = "c"
-     * StringUtils.substring("abc", 4, 6)   = ""
-     * StringUtils.substring("abc", 2, 2)   = ""
-     * StringUtils.substring("abc", -2, -1) = "b"
-     * StringUtils.substring("abc", -4, 2)  = "ab"
-     * 
- * - * @param str the String to get the substring from, may be null - * @param start the position to start from, negative means - * count back from the end of the String by this many characters - * @param end the position to end at (exclusive), negative means - * count back from the end of the String by this many characters - * @return substring from start position to end position, - * {@code null} if null String input - */ - public static String substring(final String str, int start, int end) { - if (str == null) { - return null; - } - - // handle negatives - if (end < 0) { - end = str.length() + end; // remember end is negative - } - if (start < 0) { - start = str.length() + start; // remember start is negative - } - - // check length next - if (end > str.length()) { - end = str.length(); - } - - // if start is greater than end, return "" - if (start > end) { - return EMPTY; - } - - if (start < 0) { - start = 0; - } - if (end < 0) { - end = 0; - } - - return str.substring(start, end); - } - - // Left/Right/Mid - //----------------------------------------------------------------------- - /** - *

Gets the leftmost {@code len} characters of a String.

- * - *

If {@code len} characters are not available, or the - * String is {@code null}, the String will be returned without - * an exception. An empty String is returned if len is negative.

- * - *
-     * StringUtils.left(null, *)    = null
-     * StringUtils.left(*, -ve)     = ""
-     * StringUtils.left("", *)      = ""
-     * StringUtils.left("abc", 0)   = ""
-     * StringUtils.left("abc", 2)   = "ab"
-     * StringUtils.left("abc", 4)   = "abc"
-     * 
- * - * @param str the String to get the leftmost characters from, may be null - * @param len the length of the required String - * @return the leftmost characters, {@code null} if null String input - */ - public static String left(final String str, final int len) { - if (str == null) { - return null; - } - if (len < 0) { - return EMPTY; - } - if (str.length() <= len) { - return str; - } - return str.substring(0, len); - } - - /** - *

Gets the rightmost {@code len} characters of a String.

- * - *

If {@code len} characters are not available, or the String - * is {@code null}, the String will be returned without an - * an exception. An empty String is returned if len is negative.

- * - *
-     * StringUtils.right(null, *)    = null
-     * StringUtils.right(*, -ve)     = ""
-     * StringUtils.right("", *)      = ""
-     * StringUtils.right("abc", 0)   = ""
-     * StringUtils.right("abc", 2)   = "bc"
-     * StringUtils.right("abc", 4)   = "abc"
-     * 
- * - * @param str the String to get the rightmost characters from, may be null - * @param len the length of the required String - * @return the rightmost characters, {@code null} if null String input - */ - public static String right(final String str, final int len) { - if (str == null) { - return null; - } - if (len < 0) { - return EMPTY; - } - if (str.length() <= len) { - return str; - } - return str.substring(str.length() - len); - } - - /** - *

Gets {@code len} characters from the middle of a String.

- * - *

If {@code len} characters are not available, the remainder - * of the String will be returned without an exception. If the - * String is {@code null}, {@code null} will be returned. - * An empty String is returned if len is negative or exceeds the - * length of {@code str}.

- * - *
-     * StringUtils.mid(null, *, *)    = null
-     * StringUtils.mid(*, *, -ve)     = ""
-     * StringUtils.mid("", 0, *)      = ""
-     * StringUtils.mid("abc", 0, 2)   = "ab"
-     * StringUtils.mid("abc", 0, 4)   = "abc"
-     * StringUtils.mid("abc", 2, 4)   = "c"
-     * StringUtils.mid("abc", 4, 2)   = ""
-     * StringUtils.mid("abc", -2, 2)  = "ab"
-     * 
- * - * @param str the String to get the characters from, may be null - * @param pos the position to start from, negative treated as zero - * @param len the length of the required String - * @return the middle characters, {@code null} if null String input - */ - public static String mid(final String str, int pos, final int len) { - if (str == null) { - return null; - } - if (len < 0 || pos > str.length()) { - return EMPTY; - } - if (pos < 0) { - pos = 0; - } - if (str.length() <= pos + len) { - return str.substring(pos); - } - return str.substring(pos, pos + len); - } - - // SubStringAfter/SubStringBefore - //----------------------------------------------------------------------- - /** - *

Gets the substring before the first occurrence of a separator. - * The separator is not returned.

- * - *

A {@code null} string input will return {@code null}. - * An empty ("") string input will return the empty string. - * A {@code null} separator will return the input string.

- * - *

If nothing is found, the string input is returned.

- * - *
-     * StringUtils.substringBefore(null, *)      = null
-     * StringUtils.substringBefore("", *)        = ""
-     * StringUtils.substringBefore("abc", "a")   = ""
-     * StringUtils.substringBefore("abcba", "b") = "a"
-     * StringUtils.substringBefore("abc", "c")   = "ab"
-     * StringUtils.substringBefore("abc", "d")   = "abc"
-     * StringUtils.substringBefore("abc", "")    = ""
-     * StringUtils.substringBefore("abc", null)  = "abc"
-     * 
- * - * @param str the String to get a substring from, may be null - * @param separator the String to search for, may be null - * @return the substring before the first occurrence of the separator, - * {@code null} if null String input - * @since 2.0 - */ - public static String substringBefore(final String str, final String separator) { - if (isEmpty(str) || separator == null) { - return str; - } - if (separator.isEmpty()) { - return EMPTY; - } - final int pos = str.indexOf(separator); - if (pos == INDEX_NOT_FOUND) { - return str; - } - return str.substring(0, pos); - } - - /** - *

Gets the substring after the first occurrence of a separator. - * The separator is not returned.

- * - *

A {@code null} string input will return {@code null}. - * An empty ("") string input will return the empty string. - * A {@code null} separator will return the empty string if the - * input string is not {@code null}.

- * - *

If nothing is found, the empty string is returned.

- * - *
-     * StringUtils.substringAfter(null, *)      = null
-     * StringUtils.substringAfter("", *)        = ""
-     * StringUtils.substringAfter(*, null)      = ""
-     * StringUtils.substringAfter("abc", "a")   = "bc"
-     * StringUtils.substringAfter("abcba", "b") = "cba"
-     * StringUtils.substringAfter("abc", "c")   = ""
-     * StringUtils.substringAfter("abc", "d")   = ""
-     * StringUtils.substringAfter("abc", "")    = "abc"
-     * 
- * - * @param str the String to get a substring from, may be null - * @param separator the String to search for, may be null - * @return the substring after the first occurrence of the separator, - * {@code null} if null String input - * @since 2.0 - */ - public static String substringAfter(final String str, final String separator) { - if (isEmpty(str)) { - return str; - } - if (separator == null) { - return EMPTY; - } - final int pos = str.indexOf(separator); - if (pos == INDEX_NOT_FOUND) { - return EMPTY; - } - return str.substring(pos + separator.length()); - } - - /** - *

Gets the substring before the last occurrence of a separator. - * The separator is not returned.

- * - *

A {@code null} string input will return {@code null}. - * An empty ("") string input will return the empty string. - * An empty or {@code null} separator will return the input string.

- * - *

If nothing is found, the string input is returned.

- * - *
-     * StringUtils.substringBeforeLast(null, *)      = null
-     * StringUtils.substringBeforeLast("", *)        = ""
-     * StringUtils.substringBeforeLast("abcba", "b") = "abc"
-     * StringUtils.substringBeforeLast("abc", "c")   = "ab"
-     * StringUtils.substringBeforeLast("a", "a")     = ""
-     * StringUtils.substringBeforeLast("a", "z")     = "a"
-     * StringUtils.substringBeforeLast("a", null)    = "a"
-     * StringUtils.substringBeforeLast("a", "")      = "a"
-     * 
- * - * @param str the String to get a substring from, may be null - * @param separator the String to search for, may be null - * @return the substring before the last occurrence of the separator, - * {@code null} if null String input - * @since 2.0 - */ - public static String substringBeforeLast(final String str, final String separator) { - if (isEmpty(str) || isEmpty(separator)) { - return str; - } - final int pos = str.lastIndexOf(separator); - if (pos == INDEX_NOT_FOUND) { - return str; - } - return str.substring(0, pos); - } - - /** - *

Gets the substring after the last occurrence of a separator. - * The separator is not returned.

- * - *

A {@code null} string input will return {@code null}. - * An empty ("") string input will return the empty string. - * An empty or {@code null} separator will return the empty string if - * the input string is not {@code null}.

- * - *

If nothing is found, the empty string is returned.

- * - *
-     * StringUtils.substringAfterLast(null, *)      = null
-     * StringUtils.substringAfterLast("", *)        = ""
-     * StringUtils.substringAfterLast(*, "")        = ""
-     * StringUtils.substringAfterLast(*, null)      = ""
-     * StringUtils.substringAfterLast("abc", "a")   = "bc"
-     * StringUtils.substringAfterLast("abcba", "b") = "a"
-     * StringUtils.substringAfterLast("abc", "c")   = ""
-     * StringUtils.substringAfterLast("a", "a")     = ""
-     * StringUtils.substringAfterLast("a", "z")     = ""
-     * 
- * - * @param str the String to get a substring from, may be null - * @param separator the String to search for, may be null - * @return the substring after the last occurrence of the separator, - * {@code null} if null String input - * @since 2.0 - */ - public static String substringAfterLast(final String str, final String separator) { - if (isEmpty(str)) { - return str; - } - if (isEmpty(separator)) { - return EMPTY; - } - final int pos = str.lastIndexOf(separator); - if (pos == INDEX_NOT_FOUND || pos == str.length() - separator.length()) { - return EMPTY; - } - return str.substring(pos + separator.length()); - } - - // Substring between - //----------------------------------------------------------------------- - /** - *

Gets the String that is nested in between two instances of the - * same String.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} tag returns {@code null}.

- * - *
-     * StringUtils.substringBetween(null, *)            = null
-     * StringUtils.substringBetween("", "")             = ""
-     * StringUtils.substringBetween("", "tag")          = null
-     * StringUtils.substringBetween("tagabctag", null)  = null
-     * StringUtils.substringBetween("tagabctag", "")    = ""
-     * StringUtils.substringBetween("tagabctag", "tag") = "abc"
-     * 
- * - * @param str the String containing the substring, may be null - * @param tag the String before and after the substring, may be null - * @return the substring, {@code null} if no match - * @since 2.0 - */ - public static String substringBetween(final String str, final String tag) { - return substringBetween(str, tag, tag); - } - - /** - *

Gets the String that is nested in between two Strings. - * Only the first match is returned.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} open/close returns {@code null} (no match). - * An empty ("") open and close returns an empty string.

- * - *
-     * StringUtils.substringBetween("wx[b]yz", "[", "]") = "b"
-     * StringUtils.substringBetween(null, *, *)          = null
-     * StringUtils.substringBetween(*, null, *)          = null
-     * StringUtils.substringBetween(*, *, null)          = null
-     * StringUtils.substringBetween("", "", "")          = ""
-     * StringUtils.substringBetween("", "", "]")         = null
-     * StringUtils.substringBetween("", "[", "]")        = null
-     * StringUtils.substringBetween("yabcz", "", "")     = ""
-     * StringUtils.substringBetween("yabcz", "y", "z")   = "abc"
-     * StringUtils.substringBetween("yabczyabcz", "y", "z")   = "abc"
-     * 
- * - * @param str the String containing the substring, may be null - * @param open the String before the substring, may be null - * @param close the String after the substring, may be null - * @return the substring, {@code null} if no match - * @since 2.0 - */ - public static String substringBetween(final String str, final String open, final String close) { - if (str == null || open == null || close == null) { - return null; - } - final int start = str.indexOf(open); - if (start != INDEX_NOT_FOUND) { - final int end = str.indexOf(close, start + open.length()); - if (end != INDEX_NOT_FOUND) { - return str.substring(start + open.length(), end); - } - } - return null; - } - - /** - *

Searches a String for substrings delimited by a start and end tag, - * returning all matching substrings in an array.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} open/close returns {@code null} (no match). - * An empty ("") open/close returns {@code null} (no match).

- * - *
-     * StringUtils.substringsBetween("[a][b][c]", "[", "]") = ["a","b","c"]
-     * StringUtils.substringsBetween(null, *, *)            = null
-     * StringUtils.substringsBetween(*, null, *)            = null
-     * StringUtils.substringsBetween(*, *, null)            = null
-     * StringUtils.substringsBetween("", "[", "]")          = []
-     * 
- * - * @param str the String containing the substrings, null returns null, empty returns empty - * @param open the String identifying the start of the substring, empty returns null - * @param close the String identifying the end of the substring, empty returns null - * @return a String Array of substrings, or {@code null} if no match - * @since 2.3 - */ - public static String[] substringsBetween(final String str, final String open, final String close) { - if (str == null || isEmpty(open) || isEmpty(close)) { - return null; - } - final int strLen = str.length(); - if (strLen == 0) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - final int closeLen = close.length(); - final int openLen = open.length(); - final List list = new ArrayList(); - int pos = 0; - while (pos < strLen - closeLen) { - int start = str.indexOf(open, pos); - if (start < 0) { - break; - } - start += openLen; - final int end = str.indexOf(close, start); - if (end < 0) { - break; - } - list.add(str.substring(start, end)); - pos = end + closeLen; - } - if (list.isEmpty()) { - return null; - } - return list.toArray(new String [list.size()]); - } - - // Nested extraction - //----------------------------------------------------------------------- - - // Splitting - //----------------------------------------------------------------------- - /** - *

Splits the provided text into an array, using whitespace as the - * separator. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as one separator. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.split(null)       = null
-     * StringUtils.split("")         = []
-     * StringUtils.split("abc def")  = ["abc", "def"]
-     * StringUtils.split("abc  def") = ["abc", "def"]
-     * StringUtils.split(" abc ")    = ["abc"]
-     * 
- * - * @param str the String to parse, may be null - * @return an array of parsed Strings, {@code null} if null String input - */ - public static String[] split(final String str) { - return split(str, null, -1); - } - - /** - *

Splits the provided text into an array, separator specified. - * This is an alternative to using StringTokenizer.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as one separator. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.split(null, *)         = null
-     * StringUtils.split("", *)           = []
-     * StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
-     * StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
-     * StringUtils.split("a:b:c", '.')    = ["a:b:c"]
-     * StringUtils.split("a b c", ' ')    = ["a", "b", "c"]
-     * 
- * - * @param str the String to parse, may be null - * @param separatorChar the character used as the delimiter - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.0 - */ - public static String[] split(final String str, final char separatorChar) { - return splitWorker(str, separatorChar, false); - } - - /** - *

Splits the provided text into an array, separators specified. - * This is an alternative to using StringTokenizer.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as one separator. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separatorChars splits on whitespace.

- * - *
-     * StringUtils.split(null, *)         = null
-     * StringUtils.split("", *)           = []
-     * StringUtils.split("abc def", null) = ["abc", "def"]
-     * StringUtils.split("abc def", " ")  = ["abc", "def"]
-     * StringUtils.split("abc  def", " ") = ["abc", "def"]
-     * StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separatorChars the characters used as the delimiters, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String input - */ - public static String[] split(final String str, final String separatorChars) { - return splitWorker(str, separatorChars, -1, false); - } - - /** - *

Splits the provided text into an array with a maximum length, - * separators specified.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as one separator.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separatorChars splits on whitespace.

- * - *

If more than {@code max} delimited substrings are found, the last - * returned string includes all characters after the first {@code max - 1} - * returned strings (including separator characters).

- * - *
-     * StringUtils.split(null, *, *)            = null
-     * StringUtils.split("", *, *)              = []
-     * StringUtils.split("ab cd ef", null, 0)   = ["ab", "cd", "ef"]
-     * StringUtils.split("ab   cd ef", null, 0) = ["ab", "cd", "ef"]
-     * StringUtils.split("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
-     * StringUtils.split("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separatorChars the characters used as the delimiters, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the - * array. A zero or negative value implies no limit - * @return an array of parsed Strings, {@code null} if null String input - */ - public static String[] split(final String str, final String separatorChars, final int max) { - return splitWorker(str, separatorChars, max, false); - } - - /** - *

Splits the provided text into an array, separator string specified.

- * - *

The separator(s) will not be included in the returned String array. - * Adjacent separators are treated as one separator.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separator splits on whitespace.

- * - *
-     * StringUtils.splitByWholeSeparator(null, *)               = null
-     * StringUtils.splitByWholeSeparator("", *)                 = []
-     * StringUtils.splitByWholeSeparator("ab de fg", null)      = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparator("ab   de fg", null)    = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparator("ab:cd:ef", ":")       = ["ab", "cd", "ef"]
-     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String was input - */ - public static String[] splitByWholeSeparator(final String str, final String separator) { - return splitByWholeSeparatorWorker( str, separator, -1, false ) ; - } - - /** - *

Splits the provided text into an array, separator string specified. - * Returns a maximum of {@code max} substrings.

- * - *

The separator(s) will not be included in the returned String array. - * Adjacent separators are treated as one separator.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separator splits on whitespace.

- * - *
-     * StringUtils.splitByWholeSeparator(null, *, *)               = null
-     * StringUtils.splitByWholeSeparator("", *, *)                 = []
-     * StringUtils.splitByWholeSeparator("ab de fg", null, 0)      = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparator("ab   de fg", null, 0)    = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2)       = ["ab", "cd:ef"]
-     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
-     * StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the returned - * array. A zero or negative value implies no limit. - * @return an array of parsed Strings, {@code null} if null String was input - */ - public static String[] splitByWholeSeparator( final String str, final String separator, final int max ) { - return splitByWholeSeparatorWorker(str, separator, max, false); - } - - /** - *

Splits the provided text into an array, separator string specified.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separator splits on whitespace.

- * - *
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *)               = null
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *)                 = []
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null)      = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab   de fg", null)    = ["ab", "", "", "de", "fg"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":")       = ["ab", "cd", "ef"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String was input - * @since 2.4 - */ - public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator) { - return splitByWholeSeparatorWorker(str, separator, -1, true); - } - - /** - *

Splits the provided text into an array, separator string specified. - * Returns a maximum of {@code max} substrings.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separator splits on whitespace.

- * - *
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens(null, *, *)               = null
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("", *, *)                 = []
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab de fg", null, 0)      = ["ab", "de", "fg"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab   de fg", null, 0)    = ["ab", "", "", "de", "fg"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab:cd:ef", ":", 2)       = ["ab", "cd:ef"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 5) = ["ab", "cd", "ef"]
-     * StringUtils.splitByWholeSeparatorPreserveAllTokens("ab-!-cd-!-ef", "-!-", 2) = ["ab", "cd-!-ef"]
-     * 
- * - * @param str the String to parse, may be null - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the returned - * array. A zero or negative value implies no limit. - * @return an array of parsed Strings, {@code null} if null String was input - * @since 2.4 - */ - public static String[] splitByWholeSeparatorPreserveAllTokens(final String str, final String separator, final int max) { - return splitByWholeSeparatorWorker(str, separator, max, true); - } - - /** - * Performs the logic for the {@code splitByWholeSeparatorPreserveAllTokens} methods. - * - * @param str the String to parse, may be {@code null} - * @param separator String containing the String to be used as a delimiter, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the returned - * array. A zero or negative value implies no limit. - * @param preserveAllTokens if {@code true}, adjacent separators are - * treated as empty token separators; if {@code false}, adjacent - * separators are treated as one separator. - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.4 - */ - private static String[] splitByWholeSeparatorWorker( - final String str, final String separator, final int max, final boolean preserveAllTokens) { - if (str == null) { - return null; - } - - final int len = str.length(); - - if (len == 0) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - - if (separator == null || EMPTY.equals(separator)) { - // Split on whitespace. - return splitWorker(str, null, max, preserveAllTokens); - } - - final int separatorLength = separator.length(); - - final ArrayList substrings = new ArrayList(); - int numberOfSubstrings = 0; - int beg = 0; - int end = 0; - while (end < len) { - end = str.indexOf(separator, beg); - - if (end > -1) { - if (end > beg) { - numberOfSubstrings += 1; - - if (numberOfSubstrings == max) { - end = len; - substrings.add(str.substring(beg)); - } else { - // The following is OK, because String.substring( beg, end ) excludes - // the character at the position 'end'. - substrings.add(str.substring(beg, end)); - - // Set the starting point for the next search. - // The following is equivalent to beg = end + (separatorLength - 1) + 1, - // which is the right calculation: - beg = end + separatorLength; - } - } else { - // We found a consecutive occurrence of the separator, so skip it. - if (preserveAllTokens) { - numberOfSubstrings += 1; - if (numberOfSubstrings == max) { - end = len; - substrings.add(str.substring(beg)); - } else { - substrings.add(EMPTY); - } - } - beg = end + separatorLength; - } - } else { - // String.substring( beg ) goes from 'beg' to the end of the String. - substrings.add(str.substring(beg)); - end = len; - } - } - - return substrings.toArray(new String[substrings.size()]); - } - - // ----------------------------------------------------------------------- - /** - *

Splits the provided text into an array, using whitespace as the - * separator, preserving all tokens, including empty tokens created by - * adjacent separators. This is an alternative to using StringTokenizer. - * Whitespace is defined by {@link Character#isWhitespace(char)}.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.splitPreserveAllTokens(null)       = null
-     * StringUtils.splitPreserveAllTokens("")         = []
-     * StringUtils.splitPreserveAllTokens("abc def")  = ["abc", "def"]
-     * StringUtils.splitPreserveAllTokens("abc  def") = ["abc", "", "def"]
-     * StringUtils.splitPreserveAllTokens(" abc ")    = ["", "abc", ""]
-     * 
- * - * @param str the String to parse, may be {@code null} - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.1 - */ - public static String[] splitPreserveAllTokens(final String str) { - return splitWorker(str, null, -1, true); - } - - /** - *

Splits the provided text into an array, separator specified, - * preserving all tokens, including empty tokens created by adjacent - * separators. This is an alternative to using StringTokenizer.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.splitPreserveAllTokens(null, *)         = null
-     * StringUtils.splitPreserveAllTokens("", *)           = []
-     * StringUtils.splitPreserveAllTokens("a.b.c", '.')    = ["a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("a..b.c", '.')   = ["a", "", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("a:b:c", '.')    = ["a:b:c"]
-     * StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("a b c", ' ')    = ["a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("a b c ", ' ')   = ["a", "b", "c", ""]
-     * StringUtils.splitPreserveAllTokens("a b c  ", ' ')   = ["a", "b", "c", "", ""]
-     * StringUtils.splitPreserveAllTokens(" a b c", ' ')   = ["", a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens("  a b c", ' ')  = ["", "", a", "b", "c"]
-     * StringUtils.splitPreserveAllTokens(" a b c ", ' ')  = ["", a", "b", "c", ""]
-     * 
- * - * @param str the String to parse, may be {@code null} - * @param separatorChar the character used as the delimiter, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.1 - */ - public static String[] splitPreserveAllTokens(final String str, final char separatorChar) { - return splitWorker(str, separatorChar, true); - } - - /** - * Performs the logic for the {@code split} and - * {@code splitPreserveAllTokens} methods that do not return a - * maximum array length. - * - * @param str the String to parse, may be {@code null} - * @param separatorChar the separate character - * @param preserveAllTokens if {@code true}, adjacent separators are - * treated as empty token separators; if {@code false}, adjacent - * separators are treated as one separator. - * @return an array of parsed Strings, {@code null} if null String input - */ - private static String[] splitWorker(final String str, final char separatorChar, final boolean preserveAllTokens) { - // Performance tuned for 2.0 (JDK1.4) - - if (str == null) { - return null; - } - final int len = str.length(); - if (len == 0) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - final List list = new ArrayList(); - int i = 0, start = 0; - boolean match = false; - boolean lastMatch = false; - while (i < len) { - if (str.charAt(i) == separatorChar) { - if (match || preserveAllTokens) { - list.add(str.substring(start, i)); - match = false; - lastMatch = true; - } - start = ++i; - continue; - } - lastMatch = false; - match = true; - i++; - } - if (match || preserveAllTokens && lastMatch) { - list.add(str.substring(start, i)); - } - return list.toArray(new String[list.size()]); - } - - /** - *

Splits the provided text into an array, separators specified, - * preserving all tokens, including empty tokens created by adjacent - * separators. This is an alternative to using StringTokenizer.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * For more control over the split use the StrTokenizer class.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separatorChars splits on whitespace.

- * - *
-     * StringUtils.splitPreserveAllTokens(null, *)           = null
-     * StringUtils.splitPreserveAllTokens("", *)             = []
-     * StringUtils.splitPreserveAllTokens("abc def", null)   = ["abc", "def"]
-     * StringUtils.splitPreserveAllTokens("abc def", " ")    = ["abc", "def"]
-     * StringUtils.splitPreserveAllTokens("abc  def", " ")   = ["abc", "", def"]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":")   = ["ab", "cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":")  = ["ab", "cd", "ef", ""]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""]
-     * StringUtils.splitPreserveAllTokens("ab::cd:ef", ":")  = ["ab", "", cd", "ef"]
-     * StringUtils.splitPreserveAllTokens(":cd:ef", ":")     = ["", cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("::cd:ef", ":")    = ["", "", cd", "ef"]
-     * StringUtils.splitPreserveAllTokens(":cd:ef:", ":")    = ["", cd", "ef", ""]
-     * 
- * - * @param str the String to parse, may be {@code null} - * @param separatorChars the characters used as the delimiters, - * {@code null} splits on whitespace - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.1 - */ - public static String[] splitPreserveAllTokens(final String str, final String separatorChars) { - return splitWorker(str, separatorChars, -1, true); - } - - /** - *

Splits the provided text into an array with a maximum length, - * separators specified, preserving all tokens, including empty tokens - * created by adjacent separators.

- * - *

The separator is not included in the returned String array. - * Adjacent separators are treated as separators for empty tokens. - * Adjacent separators are treated as one separator.

- * - *

A {@code null} input String returns {@code null}. - * A {@code null} separatorChars splits on whitespace.

- * - *

If more than {@code max} delimited substrings are found, the last - * returned string includes all characters after the first {@code max - 1} - * returned strings (including separator characters).

- * - *
-     * StringUtils.splitPreserveAllTokens(null, *, *)            = null
-     * StringUtils.splitPreserveAllTokens("", *, *)              = []
-     * StringUtils.splitPreserveAllTokens("ab de fg", null, 0)   = ["ab", "cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 0) = ["ab", "cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
-     * StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
-     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 2) = ["ab", "  de fg"]
-     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 3) = ["ab", "", " de fg"]
-     * StringUtils.splitPreserveAllTokens("ab   de fg", null, 4) = ["ab", "", "", "de fg"]
-     * 
- * - * @param str the String to parse, may be {@code null} - * @param separatorChars the characters used as the delimiters, - * {@code null} splits on whitespace - * @param max the maximum number of elements to include in the - * array. A zero or negative value implies no limit - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.1 - */ - public static String[] splitPreserveAllTokens(final String str, final String separatorChars, final int max) { - return splitWorker(str, separatorChars, max, true); - } - - /** - * Performs the logic for the {@code split} and - * {@code splitPreserveAllTokens} methods that return a maximum array - * length. - * - * @param str the String to parse, may be {@code null} - * @param separatorChars the separate character - * @param max the maximum number of elements to include in the - * array. A zero or negative value implies no limit. - * @param preserveAllTokens if {@code true}, adjacent separators are - * treated as empty token separators; if {@code false}, adjacent - * separators are treated as one separator. - * @return an array of parsed Strings, {@code null} if null String input - */ - private static String[] splitWorker(final String str, final String separatorChars, final int max, final boolean preserveAllTokens) { - // Performance tuned for 2.0 (JDK1.4) - // Direct code is quicker than StringTokenizer. - // Also, StringTokenizer uses isSpace() not isWhitespace() - - if (str == null) { - return null; - } - final int len = str.length(); - if (len == 0) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - final List list = new ArrayList(); - int sizePlus1 = 1; - int i = 0, start = 0; - boolean match = false; - boolean lastMatch = false; - if (separatorChars == null) { - // Null separator means use whitespace - while (i < len) { - if (Character.isWhitespace(str.charAt(i))) { - if (match || preserveAllTokens) { - lastMatch = true; - if (sizePlus1++ == max) { - i = len; - lastMatch = false; - } - list.add(str.substring(start, i)); - match = false; - } - start = ++i; - continue; - } - lastMatch = false; - match = true; - i++; - } - } else if (separatorChars.length() == 1) { - // Optimise 1 character case - final char sep = separatorChars.charAt(0); - while (i < len) { - if (str.charAt(i) == sep) { - if (match || preserveAllTokens) { - lastMatch = true; - if (sizePlus1++ == max) { - i = len; - lastMatch = false; - } - list.add(str.substring(start, i)); - match = false; - } - start = ++i; - continue; - } - lastMatch = false; - match = true; - i++; - } - } else { - // standard case - while (i < len) { - if (separatorChars.indexOf(str.charAt(i)) >= 0) { - if (match || preserveAllTokens) { - lastMatch = true; - if (sizePlus1++ == max) { - i = len; - lastMatch = false; - } - list.add(str.substring(start, i)); - match = false; - } - start = ++i; - continue; - } - lastMatch = false; - match = true; - i++; - } - } - if (match || preserveAllTokens && lastMatch) { - list.add(str.substring(start, i)); - } - return list.toArray(new String[list.size()]); - } - - /** - *

Splits a String by Character type as returned by - * {@code java.lang.Character.getType(char)}. Groups of contiguous - * characters of the same type are returned as complete tokens. - *

-     * StringUtils.splitByCharacterType(null)         = null
-     * StringUtils.splitByCharacterType("")           = []
-     * StringUtils.splitByCharacterType("ab de fg")   = ["ab", " ", "de", " ", "fg"]
-     * StringUtils.splitByCharacterType("ab   de fg") = ["ab", "   ", "de", " ", "fg"]
-     * StringUtils.splitByCharacterType("ab:cd:ef")   = ["ab", ":", "cd", ":", "ef"]
-     * StringUtils.splitByCharacterType("number5")    = ["number", "5"]
-     * StringUtils.splitByCharacterType("fooBar")     = ["foo", "B", "ar"]
-     * StringUtils.splitByCharacterType("foo200Bar")  = ["foo", "200", "B", "ar"]
-     * StringUtils.splitByCharacterType("ASFRules")   = ["ASFR", "ules"]
-     * 
- * @param str the String to split, may be {@code null} - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.4 - */ - public static String[] splitByCharacterType(final String str) { - return splitByCharacterType(str, false); - } - - /** - *

Splits a String by Character type as returned by - * {@code java.lang.Character.getType(char)}. Groups of contiguous - * characters of the same type are returned as complete tokens, with the - * following exception: the character of type - * {@code Character.UPPERCASE_LETTER}, if any, immediately - * preceding a token of type {@code Character.LOWERCASE_LETTER} - * will belong to the following token rather than to the preceding, if any, - * {@code Character.UPPERCASE_LETTER} token. - *

-     * StringUtils.splitByCharacterTypeCamelCase(null)         = null
-     * StringUtils.splitByCharacterTypeCamelCase("")           = []
-     * StringUtils.splitByCharacterTypeCamelCase("ab de fg")   = ["ab", " ", "de", " ", "fg"]
-     * StringUtils.splitByCharacterTypeCamelCase("ab   de fg") = ["ab", "   ", "de", " ", "fg"]
-     * StringUtils.splitByCharacterTypeCamelCase("ab:cd:ef")   = ["ab", ":", "cd", ":", "ef"]
-     * StringUtils.splitByCharacterTypeCamelCase("number5")    = ["number", "5"]
-     * StringUtils.splitByCharacterTypeCamelCase("fooBar")     = ["foo", "Bar"]
-     * StringUtils.splitByCharacterTypeCamelCase("foo200Bar")  = ["foo", "200", "Bar"]
-     * StringUtils.splitByCharacterTypeCamelCase("ASFRules")   = ["ASF", "Rules"]
-     * 
- * @param str the String to split, may be {@code null} - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.4 - */ - public static String[] splitByCharacterTypeCamelCase(final String str) { - return splitByCharacterType(str, true); - } - - /** - *

Splits a String by Character type as returned by - * {@code java.lang.Character.getType(char)}. Groups of contiguous - * characters of the same type are returned as complete tokens, with the - * following exception: if {@code camelCase} is {@code true}, - * the character of type {@code Character.UPPERCASE_LETTER}, if any, - * immediately preceding a token of type {@code Character.LOWERCASE_LETTER} - * will belong to the following token rather than to the preceding, if any, - * {@code Character.UPPERCASE_LETTER} token. - * @param str the String to split, may be {@code null} - * @param camelCase whether to use so-called "camel-case" for letter types - * @return an array of parsed Strings, {@code null} if null String input - * @since 2.4 - */ - private static String[] splitByCharacterType(final String str, final boolean camelCase) { - if (str == null) { - return null; - } - if (str.isEmpty()) { - return ArrayUtils.EMPTY_STRING_ARRAY; - } - final char[] c = str.toCharArray(); - final List list = new ArrayList(); - int tokenStart = 0; - int currentType = Character.getType(c[tokenStart]); - for (int pos = tokenStart + 1; pos < c.length; pos++) { - final int type = Character.getType(c[pos]); - if (type == currentType) { - continue; - } - if (camelCase && type == Character.LOWERCASE_LETTER && currentType == Character.UPPERCASE_LETTER) { - final int newTokenStart = pos - 1; - if (newTokenStart != tokenStart) { - list.add(new String(c, tokenStart, newTokenStart - tokenStart)); - tokenStart = newTokenStart; - } - } else { - list.add(new String(c, tokenStart, pos - tokenStart)); - tokenStart = pos; - } - currentType = type; - } - list.add(new String(c, tokenStart, c.length - tokenStart)); - return list.toArray(new String[list.size()]); - } - - // Joining - //----------------------------------------------------------------------- - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No separator is added to the joined String. - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null)            = null
-     * StringUtils.join([])              = ""
-     * StringUtils.join([null])          = ""
-     * StringUtils.join(["a", "b", "c"]) = "abc"
-     * StringUtils.join([null, "", "a"]) = "a"
-     * 
- * - * @param the specific type of values to join together - * @param elements the values to join together, may be null - * @return the joined String, {@code null} if null array input - * @since 2.0 - * @since 3.0 Changed signature to use varargs - */ - public static String join(final T... elements) { - return join(elements, null); - } - - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No delimiter is added before or after the list. - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
-     * StringUtils.join(["a", "b", "c"], null) = "abc"
-     * StringUtils.join([null, "", "a"], ';')  = ";;a"
-     * 
- * - * @param array the array of values to join together, may be null - * @param separator the separator character to use - * @return the joined String, {@code null} if null array input - * @since 2.0 - */ - public static String join(final Object[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final long[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final int[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final short[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final byte[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final char[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final float[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final double[] array, final char separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No delimiter is added before or after the list. - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join(["a", "b", "c"], ';')  = "a;b;c"
-     * StringUtils.join(["a", "b", "c"], null) = "abc"
-     * StringUtils.join([null, "", "a"], ';')  = ";;a"
-     * 
- * - * @param array the array of values to join together, may be null - * @param separator the separator character to use - * @param startIndex the first index to start joining from. It is - * an error to pass in an end index past the end of the array - * @param endIndex the index to stop joining from (exclusive). It is - * an error to pass in an end index past the end of the array - * @return the joined String, {@code null} if null array input - * @since 2.0 - */ - public static String join(final Object[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - if (array[i] != null) { - buf.append(array[i]); - } - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final long[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final int[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final byte[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final short[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final char[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final double[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - /** - *

- * Joins the elements of the provided array into a single String containing the provided list of elements. - *

- * - *

- * No delimiter is added before or after the list. Null objects or empty strings within the array are represented - * by empty strings. - *

- * - *
-     * StringUtils.join(null, *)               = null
-     * StringUtils.join([], *)                 = ""
-     * StringUtils.join([null], *)             = ""
-     * StringUtils.join([1, 2, 3], ';')  = "1;2;3"
-     * StringUtils.join([1, 2, 3], null) = "123"
-     * 
- * - * @param array - * the array of values to join together, may be null - * @param separator - * the separator character to use - * @param startIndex - * the first index to start joining from. It is an error to pass in an end index past the end of the - * array - * @param endIndex - * the index to stop joining from (exclusive). It is an error to pass in an end index past the end of - * the array - * @return the joined String, {@code null} if null array input - * @since 3.2 - */ - public static String join(final float[] array, final char separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - final StringBuilder buf = new StringBuilder(noOfItems * 16); - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - buf.append(array[i]); - } - return buf.toString(); - } - - - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No delimiter is added before or after the list. - * A {@code null} separator is the same as an empty String (""). - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null, *)                = null
-     * StringUtils.join([], *)                  = ""
-     * StringUtils.join([null], *)              = ""
-     * StringUtils.join(["a", "b", "c"], "--")  = "a--b--c"
-     * StringUtils.join(["a", "b", "c"], null)  = "abc"
-     * StringUtils.join(["a", "b", "c"], "")    = "abc"
-     * StringUtils.join([null, "", "a"], ',')   = ",,a"
-     * 
- * - * @param array the array of values to join together, may be null - * @param separator the separator character to use, null treated as "" - * @return the joined String, {@code null} if null array input - */ - public static String join(final Object[] array, final String separator) { - if (array == null) { - return null; - } - return join(array, separator, 0, array.length); - } - - /** - *

Joins the elements of the provided array into a single String - * containing the provided list of elements.

- * - *

No delimiter is added before or after the list. - * A {@code null} separator is the same as an empty String (""). - * Null objects or empty strings within the array are represented by - * empty strings.

- * - *
-     * StringUtils.join(null, *, *, *)                = null
-     * StringUtils.join([], *, *, *)                  = ""
-     * StringUtils.join([null], *, *, *)              = ""
-     * StringUtils.join(["a", "b", "c"], "--", 0, 3)  = "a--b--c"
-     * StringUtils.join(["a", "b", "c"], "--", 1, 3)  = "b--c"
-     * StringUtils.join(["a", "b", "c"], "--", 2, 3)  = "c"
-     * StringUtils.join(["a", "b", "c"], "--", 2, 2)  = ""
-     * StringUtils.join(["a", "b", "c"], null, 0, 3)  = "abc"
-     * StringUtils.join(["a", "b", "c"], "", 0, 3)    = "abc"
-     * StringUtils.join([null, "", "a"], ',', 0, 3)   = ",,a"
-     * 
- * - * @param array the array of values to join together, may be null - * @param separator the separator character to use, null treated as "" - * @param startIndex the first index to start joining from. - * @param endIndex the index to stop joining from (exclusive). - * @return the joined String, {@code null} if null array input; or the empty string - * if {@code endIndex - startIndex <= 0}. The number of joined entries is given by - * {@code endIndex - startIndex} - * @throws ArrayIndexOutOfBoundsException ife
- * {@code startIndex < 0} or
- * {@code startIndex >= array.length()} or
- * {@code endIndex < 0} or
- * {@code endIndex > array.length()} - */ - public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) { - if (array == null) { - return null; - } - if (separator == null) { - separator = EMPTY; - } - - // endIndex - startIndex > 0: Len = NofStrings *(len(firstString) + len(separator)) - // (Assuming that all Strings are roughly equally long) - final int noOfItems = endIndex - startIndex; - if (noOfItems <= 0) { - return EMPTY; - } - - final StringBuilder buf = new StringBuilder(noOfItems * 16); - - for (int i = startIndex; i < endIndex; i++) { - if (i > startIndex) { - buf.append(separator); - } - if (array[i] != null) { - buf.append(array[i]); - } - } - return buf.toString(); - } - - /** - *

Joins the elements of the provided {@code Iterator} into - * a single String containing the provided elements.

- * - *

No delimiter is added before or after the list. Null objects or empty - * strings within the iteration are represented by empty strings.

- * - *

See the examples here: {@link #join(Object[],char)}.

- * - * @param iterator the {@code Iterator} of values to join together, may be null - * @param separator the separator character to use - * @return the joined String, {@code null} if null iterator input - * @since 2.0 - */ - public static String join(final Iterator iterator, final char separator) { - - // handle null, zero and one elements before building a buffer - if (iterator == null) { - return null; - } - if (!iterator.hasNext()) { - return EMPTY; - } - final Object first = iterator.next(); - if (!iterator.hasNext()) { - @SuppressWarnings( "deprecation" ) // ObjectUtils.toString(Object) has been deprecated in 3.2 - final - String result = ObjectUtils.toString(first); - return result; - } - - // two or more elements - final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small - if (first != null) { - buf.append(first); - } - - while (iterator.hasNext()) { - buf.append(separator); - final Object obj = iterator.next(); - if (obj != null) { - buf.append(obj); - } - } - - return buf.toString(); - } - - /** - *

Joins the elements of the provided {@code Iterator} into - * a single String containing the provided elements.

- * - *

No delimiter is added before or after the list. - * A {@code null} separator is the same as an empty String ("").

- * - *

See the examples here: {@link #join(Object[],String)}.

- * - * @param iterator the {@code Iterator} of values to join together, may be null - * @param separator the separator character to use, null treated as "" - * @return the joined String, {@code null} if null iterator input - */ - public static String join(final Iterator iterator, final String separator) { - - // handle null, zero and one elements before building a buffer - if (iterator == null) { - return null; - } - if (!iterator.hasNext()) { - return EMPTY; - } - final Object first = iterator.next(); - if (!iterator.hasNext()) { - @SuppressWarnings( "deprecation" ) // ObjectUtils.toString(Object) has been deprecated in 3.2 - final String result = ObjectUtils.toString(first); - return result; - } - - // two or more elements - final StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small - if (first != null) { - buf.append(first); - } - - while (iterator.hasNext()) { - if (separator != null) { - buf.append(separator); - } - final Object obj = iterator.next(); - if (obj != null) { - buf.append(obj); - } - } - return buf.toString(); - } - - /** - *

Joins the elements of the provided {@code Iterable} into - * a single String containing the provided elements.

- * - *

No delimiter is added before or after the list. Null objects or empty - * strings within the iteration are represented by empty strings.

- * - *

See the examples here: {@link #join(Object[],char)}.

- * - * @param iterable the {@code Iterable} providing the values to join together, may be null - * @param separator the separator character to use - * @return the joined String, {@code null} if null iterator input - * @since 2.3 - */ - public static String join(final Iterable iterable, final char separator) { - if (iterable == null) { - return null; - } - return join(iterable.iterator(), separator); - } - - /** - *

Joins the elements of the provided {@code Iterable} into - * a single String containing the provided elements.

- * - *

No delimiter is added before or after the list. - * A {@code null} separator is the same as an empty String ("").

- * - *

See the examples here: {@link #join(Object[],String)}.

- * - * @param iterable the {@code Iterable} providing the values to join together, may be null - * @param separator the separator character to use, null treated as "" - * @return the joined String, {@code null} if null iterator input - * @since 2.3 - */ - public static String join(final Iterable iterable, final String separator) { - if (iterable == null) { - return null; - } - return join(iterable.iterator(), separator); - } - - /** - *

Joins the elements of the provided varargs into a - * single String containing the provided elements.

- * - *

No delimiter is added before or after the list. - * {@code null} elements and separator are treated as empty Strings ("").

- * - *
-     * StringUtils.joinWith(",", {"a", "b"})        = "a,b"
-     * StringUtils.joinWith(",", {"a", "b",""})     = "a,b,"
-     * StringUtils.joinWith(",", {"a", null, "b"})  = "a,,b"
-     * StringUtils.joinWith(null, {"a", "b"})       = "ab"
-     * 
- * - * @param separator the separator character to use, null treated as "" - * @param objects the varargs providing the values to join together. {@code null} elements are treated as "" - * @return the joined String. - * @throws java.lang.IllegalArgumentException if a null varargs is provided - */ - public static String joinWith(final String separator, final Object... objects) { - if (objects == null) { - throw new IllegalArgumentException("Object varargs must not be null"); - } - - final String sanitizedSeparator = defaultString(separator, StringUtils.EMPTY); - - final StringBuilder result = new StringBuilder(); - - final Iterator iterator = Arrays.asList(objects).iterator(); - while (iterator.hasNext()) { - @SuppressWarnings("deprecation") // o.k. to use as long as we do not require java 7 or greater - final String value = ObjectUtils.toString(iterator.next()); - result.append(value); - - if (iterator.hasNext()) { - result.append(sanitizedSeparator); - } - } - - return result.toString(); - } - - // Delete - //----------------------------------------------------------------------- - /** - *

Deletes all whitespaces from a String as defined by - * {@link Character#isWhitespace(char)}.

- * - *
-     * StringUtils.deleteWhitespace(null)         = null
-     * StringUtils.deleteWhitespace("")           = ""
-     * StringUtils.deleteWhitespace("abc")        = "abc"
-     * StringUtils.deleteWhitespace("   ab  c  ") = "abc"
-     * 
- * - * @param str the String to delete whitespace from, may be null - * @return the String without whitespaces, {@code null} if null String input - */ - public static String deleteWhitespace(final String str) { - if (isEmpty(str)) { - return str; - } - final int sz = str.length(); - final char[] chs = new char[sz]; - int count = 0; - for (int i = 0; i < sz; i++) { - if (!Character.isWhitespace(str.charAt(i))) { - chs[count++] = str.charAt(i); - } - } - if (count == sz) { - return str; - } - return new String(chs, 0, count); - } - - // Remove - //----------------------------------------------------------------------- - /** - *

Removes a substring only if it is at the beginning of a source string, - * otherwise returns the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} search string will return the source string.

- * - *
-     * StringUtils.removeStart(null, *)      = null
-     * StringUtils.removeStart("", *)        = ""
-     * StringUtils.removeStart(*, null)      = *
-     * StringUtils.removeStart("www.domain.com", "www.")   = "domain.com"
-     * StringUtils.removeStart("domain.com", "www.")       = "domain.com"
-     * StringUtils.removeStart("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeStart("abc", "")    = "abc"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.1 - */ - public static String removeStart(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (str.startsWith(remove)){ - return str.substring(remove.length()); - } - return str; - } - - /** - *

Case insensitive removal of a substring if it is at the beginning of a source string, - * otherwise returns the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} search string will return the source string.

- * - *
-     * StringUtils.removeStartIgnoreCase(null, *)      = null
-     * StringUtils.removeStartIgnoreCase("", *)        = ""
-     * StringUtils.removeStartIgnoreCase(*, null)      = *
-     * StringUtils.removeStartIgnoreCase("www.domain.com", "www.")   = "domain.com"
-     * StringUtils.removeStartIgnoreCase("www.domain.com", "WWW.")   = "domain.com"
-     * StringUtils.removeStartIgnoreCase("domain.com", "www.")       = "domain.com"
-     * StringUtils.removeStartIgnoreCase("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeStartIgnoreCase("abc", "")    = "abc"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for (case insensitive) and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.4 - */ - public static String removeStartIgnoreCase(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (startsWithIgnoreCase(str, remove)) { - return str.substring(remove.length()); - } - return str; - } - - /** - *

Removes a substring only if it is at the end of a source string, - * otherwise returns the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} search string will return the source string.

- * - *
-     * StringUtils.removeEnd(null, *)      = null
-     * StringUtils.removeEnd("", *)        = ""
-     * StringUtils.removeEnd(*, null)      = *
-     * StringUtils.removeEnd("www.domain.com", ".com.")  = "www.domain.com"
-     * StringUtils.removeEnd("www.domain.com", ".com")   = "www.domain"
-     * StringUtils.removeEnd("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeEnd("abc", "")    = "abc"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.1 - */ - public static String removeEnd(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (str.endsWith(remove)) { - return str.substring(0, str.length() - remove.length()); - } - return str; - } - - /** - *

Case insensitive removal of a substring if it is at the end of a source string, - * otherwise returns the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} search string will return the source string.

- * - *
-     * StringUtils.removeEndIgnoreCase(null, *)      = null
-     * StringUtils.removeEndIgnoreCase("", *)        = ""
-     * StringUtils.removeEndIgnoreCase(*, null)      = *
-     * StringUtils.removeEndIgnoreCase("www.domain.com", ".com.")  = "www.domain.com"
-     * StringUtils.removeEndIgnoreCase("www.domain.com", ".com")   = "www.domain"
-     * StringUtils.removeEndIgnoreCase("www.domain.com", "domain") = "www.domain.com"
-     * StringUtils.removeEndIgnoreCase("abc", "")    = "abc"
-     * StringUtils.removeEndIgnoreCase("www.domain.com", ".COM") = "www.domain")
-     * StringUtils.removeEndIgnoreCase("www.domain.COM", ".com") = "www.domain")
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for (case insensitive) and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.4 - */ - public static String removeEndIgnoreCase(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - if (endsWithIgnoreCase(str, remove)) { - return str.substring(0, str.length() - remove.length()); - } - return str; - } - - /** - *

Removes all occurrences of a substring from within the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string. - * A {@code null} remove string will return the source string. - * An empty ("") remove string will return the source string.

- * - *
-     * StringUtils.remove(null, *)        = null
-     * StringUtils.remove("", *)          = ""
-     * StringUtils.remove(*, null)        = *
-     * StringUtils.remove(*, "")          = *
-     * StringUtils.remove("queued", "ue") = "qd"
-     * StringUtils.remove("queued", "zz") = "queued"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the String to search for and remove, may be null - * @return the substring with the string removed if found, - * {@code null} if null String input - * @since 2.1 - */ - public static String remove(final String str, final String remove) { - if (isEmpty(str) || isEmpty(remove)) { - return str; - } - return replace(str, remove, EMPTY, -1); - } - - /** - *

Removes all occurrences of a character from within the source string.

- * - *

A {@code null} source string will return {@code null}. - * An empty ("") source string will return the empty string.

- * - *
-     * StringUtils.remove(null, *)       = null
-     * StringUtils.remove("", *)         = ""
-     * StringUtils.remove("queued", 'u') = "qeed"
-     * StringUtils.remove("queued", 'z') = "queued"
-     * 
- * - * @param str the source String to search, may be null - * @param remove the char to search for and remove, may be null - * @return the substring with the char removed if found, - * {@code null} if null String input - * @since 2.1 - */ - public static String remove(final String str, final char remove) { - if (isEmpty(str) || str.indexOf(remove) == INDEX_NOT_FOUND) { - return str; - } - final char[] chars = str.toCharArray(); - int pos = 0; - for (int i = 0; i < chars.length; i++) { - if (chars[i] != remove) { - chars[pos++] = chars[i]; - } - } - return new String(chars, 0, pos); - } - - // Replacing - //----------------------------------------------------------------------- - /** - *

Replaces a String with another String inside a larger String, once.

- * - *

A {@code null} reference passed to this method is a no-op.

- * - *
-     * StringUtils.replaceOnce(null, *, *)        = null
-     * StringUtils.replaceOnce("", *, *)          = ""
-     * StringUtils.replaceOnce("any", null, *)    = "any"
-     * StringUtils.replaceOnce("any", *, null)    = "any"
-     * StringUtils.replaceOnce("any", "", *)      = "any"
-     * StringUtils.replaceOnce("aba", "a", null)  = "aba"
-     * StringUtils.replaceOnce("aba", "a", "")    = "ba"
-     * StringUtils.replaceOnce("aba", "a", "z")   = "zba"
-     * 
- * - * @see #replace(String text, String searchString, String replacement, int max) - * @param text text to search and replace in, may be null - * @param searchString the String to search for, may be null - * @param replacement the String to replace with, may be null - * @return the text with any replacements processed, - * {@code null} if null String input - */ - public static String replaceOnce(final String text, final String searchString, final String replacement) { - return replace(text, searchString, replacement, 1); - } - - /** - * Replaces each substring of the source String that matches the given regular expression with the given - * replacement using the {@link Pattern#DOTALL} option. DOTALL is also know as single-line mode in Perl. This call - * is also equivalent to: - *
    - *
  • {@code source.replaceAll("(?s)" + regex, replacement)}
  • - *
  • {@code Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement)}
  • - *
- * - * @param source - * the source string - * @param regex - * the regular expression to which this string is to be matched - * @param replacement - * the string to be substituted for each match - * @return The resulting {@code String} - * @see String#replaceAll(String, String) - * @see Pattern#DOTALL - * @since 3.2 - */ - public static String replacePattern(final String source, final String regex, final String replacement) { - return Pattern.compile(regex, Pattern.DOTALL).matcher(source).replaceAll(replacement); - } - - /** - * Removes each substring of the source String that matches the given regular expression using the DOTALL option. - * - * @param source - * the source string - * @param regex - * the regular expression to which this string is to be matched - * @return The resulting {@code String} - * @see String#replaceAll(String, String) - * @see Pattern#DOTALL - * @since 3.2 - */ - public static String removePattern(final String source, final String regex) { - return replacePattern(source, regex, StringUtils.EMPTY); - } - - /** - *

Replaces all occurrences of a String within another String.

- * - *

A {@code null} reference passed to this method is a no-op.

- * - *
-     * StringUtils.replace(null, *, *)        = null
-     * StringUtils.replace("", *, *)          = ""
-     * StringUtils.replace("any", null, *)    = "any"
-     * StringUtils.replace("any", *, null)    = "any"
-     * StringUtils.replace("any", "", *)      = "any"
-     * StringUtils.replace("aba", "a", null)  = "aba"
-     * StringUtils.replace("aba", "a", "")    = "b"
-     * StringUtils.replace("aba", "a", "z")   = "zbz"
-     * 
- * - * @see #replace(String text, String searchString, String replacement, int max) - * @param text text to search and replace in, may be null - * @param searchString the String to search for, may be null - * @param replacement the String to replace it with, may be null - * @return the text with any replacements processed, - * {@code null} if null String input - */ - public static String replace(final String text, final String searchString, final String replacement) { - return replace(text, searchString, replacement, -1); - } - - /** - *

Replaces a String with another String inside a larger String, - * for the first {@code max} values of the search String.

- * - *

A {@code null} reference passed to this method is a no-op.

- * - *
-     * StringUtils.replace(null, *, *, *)         = null
-     * StringUtils.replace("", *, *, *)           = ""
-     * StringUtils.replace("any", null, *, *)     = "any"
-     * StringUtils.replace("any", *, null, *)     = "any"
-     * StringUtils.replace("any", "", *, *)       = "any"
-     * StringUtils.replace("any", *, *, 0)        = "any"
-     * StringUtils.replace("abaa", "a", null, -1) = "abaa"
-     * StringUtils.replace("abaa", "a", "", -1)   = "b"
-     * StringUtils.replace("abaa", "a", "z", 0)   = "abaa"
-     * StringUtils.replace("abaa", "a", "z", 1)   = "zbaa"
-     * StringUtils.replace("abaa", "a", "z", 2)   = "zbza"
-     * StringUtils.replace("abaa", "a", "z", -1)  = "zbzz"
-     * 
- * - * @param text text to search and replace in, may be null - * @param searchString the String to search for, may be null - * @param replacement the String to replace it with, may be null - * @param max maximum number of values to replace, or {@code -1} if no maximum - * @return the text with any replacements processed, - * {@code null} if null String input - */ - public static String replace(final String text, final String searchString, final String replacement, int max) { - if (isEmpty(text) || isEmpty(searchString) || replacement == null || max == 0) { - return text; - } - int start = 0; - int end = text.indexOf(searchString, start); - if (end == INDEX_NOT_FOUND) { - return text; - } - final int replLength = searchString.length(); - int increase = replacement.length() - replLength; - increase = increase < 0 ? 0 : increase; - increase *= max < 0 ? 16 : max > 64 ? 64 : max; - final StringBuilder buf = new StringBuilder(text.length() + increase); - while (end != INDEX_NOT_FOUND) { - buf.append(text.substring(start, end)).append(replacement); - start = end + replLength; - if (--max == 0) { - break; - } - end = text.indexOf(searchString, start); - } - buf.append(text.substring(start)); - return buf.toString(); - } - - /** - *

- * Replaces all occurrences of Strings within another String. - *

- * - *

- * A {@code null} reference passed to this method is a no-op, or if - * any "search string" or "string to replace" is null, that replace will be - * ignored. This will not repeat. For repeating replaces, call the - * overloaded method. - *

- * - *
-     *  StringUtils.replaceEach(null, *, *)        = null
-     *  StringUtils.replaceEach("", *, *)          = ""
-     *  StringUtils.replaceEach("aba", null, null) = "aba"
-     *  StringUtils.replaceEach("aba", new String[0], null) = "aba"
-     *  StringUtils.replaceEach("aba", null, new String[0]) = "aba"
-     *  StringUtils.replaceEach("aba", new String[]{"a"}, null)  = "aba"
-     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""})  = "b"
-     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"})  = "aba"
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"})  = "wcte"
-     *  (example of how it does not repeat)
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"})  = "dcte"
-     * 
- * - * @param text - * text to search and replace in, no-op if null - * @param searchList - * the Strings to search for, no-op if null - * @param replacementList - * the Strings to replace them with, no-op if null - * @return the text with any replacements processed, {@code null} if - * null String input - * @throws IllegalArgumentException - * if the lengths of the arrays are not the same (null is ok, - * and/or size 0) - * @since 2.4 - */ - public static String replaceEach(final String text, final String[] searchList, final String[] replacementList) { - return replaceEach(text, searchList, replacementList, false, 0); - } - - /** - *

- * Replaces all occurrences of Strings within another String. - *

- * - *

- * A {@code null} reference passed to this method is a no-op, or if - * any "search string" or "string to replace" is null, that replace will be - * ignored. - *

- * - *
-     *  StringUtils.replaceEachRepeatedly(null, *, *) = null
-     *  StringUtils.replaceEachRepeatedly("", *, *) = ""
-     *  StringUtils.replaceEachRepeatedly("aba", null, null) = "aba"
-     *  StringUtils.replaceEachRepeatedly("aba", new String[0], null) = "aba"
-     *  StringUtils.replaceEachRepeatedly("aba", null, new String[0]) = "aba"
-     *  StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, null) = "aba"
-     *  StringUtils.replaceEachRepeatedly("aba", new String[]{"a"}, new String[]{""}) = "b"
-     *  StringUtils.replaceEachRepeatedly("aba", new String[]{null}, new String[]{"a"}) = "aba"
-     *  StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
-     *  (example of how it repeats)
-     *  StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "tcte"
-     *  StringUtils.replaceEachRepeatedly("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}) = IllegalStateException
-     * 
- * - * @param text - * text to search and replace in, no-op if null - * @param searchList - * the Strings to search for, no-op if null - * @param replacementList - * the Strings to replace them with, no-op if null - * @return the text with any replacements processed, {@code null} if - * null String input - * @throws IllegalStateException - * if the search is repeating and there is an endless loop due - * to outputs of one being inputs to another - * @throws IllegalArgumentException - * if the lengths of the arrays are not the same (null is ok, - * and/or size 0) - * @since 2.4 - */ - public static String replaceEachRepeatedly(final String text, final String[] searchList, final String[] replacementList) { - // timeToLive should be 0 if not used or nothing to replace, else it's - // the length of the replace array - final int timeToLive = searchList == null ? 0 : searchList.length; - return replaceEach(text, searchList, replacementList, true, timeToLive); - } - - /** - *

- * Replace all occurrences of Strings within another String. - * This is a private recursive helper method for {@link #replaceEachRepeatedly(String, String[], String[])} and - * {@link #replaceEach(String, String[], String[])} - *

- * - *

- * A {@code null} reference passed to this method is a no-op, or if - * any "search string" or "string to replace" is null, that replace will be - * ignored. - *

- * - *
-     *  StringUtils.replaceEach(null, *, *, *, *) = null
-     *  StringUtils.replaceEach("", *, *, *, *) = ""
-     *  StringUtils.replaceEach("aba", null, null, *, *) = "aba"
-     *  StringUtils.replaceEach("aba", new String[0], null, *, *) = "aba"
-     *  StringUtils.replaceEach("aba", null, new String[0], *, *) = "aba"
-     *  StringUtils.replaceEach("aba", new String[]{"a"}, null, *, *) = "aba"
-     *  StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}, *, >=0) = "b"
-     *  StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}, *, >=0) = "aba"
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}, *, >=0) = "wcte"
-     *  (example of how it repeats)
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, false, >=0) = "dcte"
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}, true, >=2) = "tcte"
-     *  StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "ab"}, *, *) = IllegalStateException
-     * 
- * - * @param text - * text to search and replace in, no-op if null - * @param searchList - * the Strings to search for, no-op if null - * @param replacementList - * the Strings to replace them with, no-op if null - * @param repeat if true, then replace repeatedly - * until there are no more possible replacements or timeToLive < 0 - * @param timeToLive - * if less than 0 then there is a circular reference and endless - * loop - * @return the text with any replacements processed, {@code null} if - * null String input - * @throws IllegalStateException - * if the search is repeating and there is an endless loop due - * to outputs of one being inputs to another - * @throws IllegalArgumentException - * if the lengths of the arrays are not the same (null is ok, - * and/or size 0) - * @since 2.4 - */ - private static String replaceEach( - final String text, final String[] searchList, final String[] replacementList, final boolean repeat, final int timeToLive) { - - // mchyzer Performance note: This creates very few new objects (one major goal) - // let me know if there are performance requests, we can create a harness to measure - - if (text == null || text.isEmpty() || searchList == null || - searchList.length == 0 || replacementList == null || replacementList.length == 0) { - return text; - } - - // if recursing, this shouldn't be less than 0 - if (timeToLive < 0) { - throw new IllegalStateException("Aborting to protect against StackOverflowError - " + - "output of one loop is the input of another"); - } - - final int searchLength = searchList.length; - final int replacementLength = replacementList.length; - - // make sure lengths are ok, these need to be equal - if (searchLength != replacementLength) { - throw new IllegalArgumentException("Search and Replace array lengths don't match: " - + searchLength - + " vs " - + replacementLength); - } - - // keep track of which still have matches - final boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; - - // index on index that the match was found - int textIndex = -1; - int replaceIndex = -1; - int tempIndex = -1; - - // index of replace array that will replace the search string found - // NOTE: logic duplicated below START - for (int i = 0; i < searchLength; i++) { - if (noMoreMatchesForReplIndex[i] || searchList[i] == null || - searchList[i].isEmpty() || replacementList[i] == null) { - continue; - } - tempIndex = text.indexOf(searchList[i]); - - // see if we need to keep searching for this - if (tempIndex == -1) { - noMoreMatchesForReplIndex[i] = true; - } else { - if (textIndex == -1 || tempIndex < textIndex) { - textIndex = tempIndex; - replaceIndex = i; - } - } - } - // NOTE: logic mostly below END - - // no search strings found, we are done - if (textIndex == -1) { - return text; - } - - int start = 0; - - // get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit - int increase = 0; - - // count the replacement text elements that are larger than their corresponding text being replaced - for (int i = 0; i < searchList.length; i++) { - if (searchList[i] == null || replacementList[i] == null) { - continue; - } - final int greater = replacementList[i].length() - searchList[i].length(); - if (greater > 0) { - increase += 3 * greater; // assume 3 matches - } - } - // have upper-bound at 20% increase, then let Java take over - increase = Math.min(increase, text.length() / 5); - - final StringBuilder buf = new StringBuilder(text.length() + increase); - - while (textIndex != -1) { - - for (int i = start; i < textIndex; i++) { - buf.append(text.charAt(i)); - } - buf.append(replacementList[replaceIndex]); - - start = textIndex + searchList[replaceIndex].length(); - - textIndex = -1; - replaceIndex = -1; - tempIndex = -1; - // find the next earliest match - // NOTE: logic mostly duplicated above START - for (int i = 0; i < searchLength; i++) { - if (noMoreMatchesForReplIndex[i] || searchList[i] == null || - searchList[i].isEmpty() || replacementList[i] == null) { - continue; - } - tempIndex = text.indexOf(searchList[i], start); - - // see if we need to keep searching for this - if (tempIndex == -1) { - noMoreMatchesForReplIndex[i] = true; - } else { - if (textIndex == -1 || tempIndex < textIndex) { - textIndex = tempIndex; - replaceIndex = i; - } - } - } - // NOTE: logic duplicated above END - - } - final int textLength = text.length(); - for (int i = start; i < textLength; i++) { - buf.append(text.charAt(i)); - } - final String result = buf.toString(); - if (!repeat) { - return result; - } - - return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1); - } - - // Replace, character based - //----------------------------------------------------------------------- - /** - *

Replaces all occurrences of a character in a String with another. - * This is a null-safe version of {@link String#replace(char, char)}.

- * - *

A {@code null} string input returns {@code null}. - * An empty ("") string input returns an empty string.

- * - *
-     * StringUtils.replaceChars(null, *, *)        = null
-     * StringUtils.replaceChars("", *, *)          = ""
-     * StringUtils.replaceChars("abcba", 'b', 'y') = "aycya"
-     * StringUtils.replaceChars("abcba", 'z', 'y') = "abcba"
-     * 
- * - * @param str String to replace characters in, may be null - * @param searchChar the character to search for, may be null - * @param replaceChar the character to replace, may be null - * @return modified String, {@code null} if null string input - * @since 2.0 - */ - public static String replaceChars(final String str, final char searchChar, final char replaceChar) { - if (str == null) { - return null; - } - return str.replace(searchChar, replaceChar); - } - - /** - *

Replaces multiple characters in a String in one go. - * This method can also be used to delete characters.

- * - *

For example:
- * replaceChars("hello", "ho", "jy") = jelly.

- * - *

A {@code null} string input returns {@code null}. - * An empty ("") string input returns an empty string. - * A null or empty set of search characters returns the input string.

- * - *

The length of the search characters should normally equal the length - * of the replace characters. - * If the search characters is longer, then the extra search characters - * are deleted. - * If the search characters is shorter, then the extra replace characters - * are ignored.

- * - *
-     * StringUtils.replaceChars(null, *, *)           = null
-     * StringUtils.replaceChars("", *, *)             = ""
-     * StringUtils.replaceChars("abc", null, *)       = "abc"
-     * StringUtils.replaceChars("abc", "", *)         = "abc"
-     * StringUtils.replaceChars("abc", "b", null)     = "ac"
-     * StringUtils.replaceChars("abc", "b", "")       = "ac"
-     * StringUtils.replaceChars("abcba", "bc", "yz")  = "ayzya"
-     * StringUtils.replaceChars("abcba", "bc", "y")   = "ayya"
-     * StringUtils.replaceChars("abcba", "bc", "yzx") = "ayzya"
-     * 
- * - * @param str String to replace characters in, may be null - * @param searchChars a set of characters to search for, may be null - * @param replaceChars a set of characters to replace, may be null - * @return modified String, {@code null} if null string input - * @since 2.0 - */ - public static String replaceChars(final String str, final String searchChars, String replaceChars) { - if (isEmpty(str) || isEmpty(searchChars)) { - return str; - } - if (replaceChars == null) { - replaceChars = EMPTY; - } - boolean modified = false; - final int replaceCharsLength = replaceChars.length(); - final int strLength = str.length(); - final StringBuilder buf = new StringBuilder(strLength); - for (int i = 0; i < strLength; i++) { - final char ch = str.charAt(i); - final int index = searchChars.indexOf(ch); - if (index >= 0) { - modified = true; - if (index < replaceCharsLength) { - buf.append(replaceChars.charAt(index)); - } - } else { - buf.append(ch); - } - } - if (modified) { - return buf.toString(); - } - return str; - } - - // Overlay - //----------------------------------------------------------------------- - /** - *

Overlays part of a String with another String.

- * - *

A {@code null} string input returns {@code null}. - * A negative index is treated as zero. - * An index greater than the string length is treated as the string length. - * The start index is always the smaller of the two indices.

- * - *
-     * StringUtils.overlay(null, *, *, *)            = null
-     * StringUtils.overlay("", "abc", 0, 0)          = "abc"
-     * StringUtils.overlay("abcdef", null, 2, 4)     = "abef"
-     * StringUtils.overlay("abcdef", "", 2, 4)       = "abef"
-     * StringUtils.overlay("abcdef", "", 4, 2)       = "abef"
-     * StringUtils.overlay("abcdef", "zzzz", 2, 4)   = "abzzzzef"
-     * StringUtils.overlay("abcdef", "zzzz", 4, 2)   = "abzzzzef"
-     * StringUtils.overlay("abcdef", "zzzz", -1, 4)  = "zzzzef"
-     * StringUtils.overlay("abcdef", "zzzz", 2, 8)   = "abzzzz"
-     * StringUtils.overlay("abcdef", "zzzz", -2, -3) = "zzzzabcdef"
-     * StringUtils.overlay("abcdef", "zzzz", 8, 10)  = "abcdefzzzz"
-     * 
- * - * @param str the String to do overlaying in, may be null - * @param overlay the String to overlay, may be null - * @param start the position to start overlaying at - * @param end the position to stop overlaying before - * @return overlayed String, {@code null} if null String input - * @since 2.0 - */ - public static String overlay(final String str, String overlay, int start, int end) { - if (str == null) { - return null; - } - if (overlay == null) { - overlay = EMPTY; - } - final int len = str.length(); - if (start < 0) { - start = 0; - } - if (start > len) { - start = len; - } - if (end < 0) { - end = 0; - } - if (end > len) { - end = len; - } - if (start > end) { - final int temp = start; - start = end; - end = temp; - } - return new StringBuilder(len + start - end + overlay.length() + 1) - .append(str.substring(0, start)) - .append(overlay) - .append(str.substring(end)) - .toString(); - } - - // Chomping - //----------------------------------------------------------------------- - /** - *

Removes one newline from end of a String if it's there, - * otherwise leave it alone. A newline is "{@code \n}", - * "{@code \r}", or "{@code \r\n}".

- * - *

NOTE: This method changed in 2.0. - * It now more closely matches Perl chomp.

- * - *
-     * StringUtils.chomp(null)          = null
-     * StringUtils.chomp("")            = ""
-     * StringUtils.chomp("abc \r")      = "abc "
-     * StringUtils.chomp("abc\n")       = "abc"
-     * StringUtils.chomp("abc\r\n")     = "abc"
-     * StringUtils.chomp("abc\r\n\r\n") = "abc\r\n"
-     * StringUtils.chomp("abc\n\r")     = "abc\n"
-     * StringUtils.chomp("abc\n\rabc")  = "abc\n\rabc"
-     * StringUtils.chomp("\r")          = ""
-     * StringUtils.chomp("\n")          = ""
-     * StringUtils.chomp("\r\n")        = ""
-     * 
- * - * @param str the String to chomp a newline from, may be null - * @return String without newline, {@code null} if null String input - */ - public static String chomp(final String str) { - if (isEmpty(str)) { - return str; - } - - if (str.length() == 1) { - final char ch = str.charAt(0); - if (ch == CharUtils.CR || ch == CharUtils.LF) { - return EMPTY; - } - return str; - } - - int lastIdx = str.length() - 1; - final char last = str.charAt(lastIdx); - - if (last == CharUtils.LF) { - if (str.charAt(lastIdx - 1) == CharUtils.CR) { - lastIdx--; - } - } else if (last != CharUtils.CR) { - lastIdx++; - } - return str.substring(0, lastIdx); - } - - /** - *

Removes {@code separator} from the end of - * {@code str} if it's there, otherwise leave it alone.

- * - *

NOTE: This method changed in version 2.0. - * It now more closely matches Perl chomp. - * For the previous behavior, use {@link #substringBeforeLast(String, String)}. - * This method uses {@link String#endsWith(String)}.

- * - *
-     * StringUtils.chomp(null, *)         = null
-     * StringUtils.chomp("", *)           = ""
-     * StringUtils.chomp("foobar", "bar") = "foo"
-     * StringUtils.chomp("foobar", "baz") = "foobar"
-     * StringUtils.chomp("foo", "foo")    = ""
-     * StringUtils.chomp("foo ", "foo")   = "foo "
-     * StringUtils.chomp(" foo", "foo")   = " "
-     * StringUtils.chomp("foo", "foooo")  = "foo"
-     * StringUtils.chomp("foo", "")       = "foo"
-     * StringUtils.chomp("foo", null)     = "foo"
-     * 
- * - * @param str the String to chomp from, may be null - * @param separator separator String, may be null - * @return String without trailing separator, {@code null} if null String input - * @deprecated This feature will be removed in Lang 4.0, use {@link StringUtils#removeEnd(String, String)} instead - */ - @Deprecated - public static String chomp(final String str, final String separator) { - return removeEnd(str,separator); - } - - // Chopping - //----------------------------------------------------------------------- - /** - *

Remove the last character from a String.

- * - *

If the String ends in {@code \r\n}, then remove both - * of them.

- * - *
-     * StringUtils.chop(null)          = null
-     * StringUtils.chop("")            = ""
-     * StringUtils.chop("abc \r")      = "abc "
-     * StringUtils.chop("abc\n")       = "abc"
-     * StringUtils.chop("abc\r\n")     = "abc"
-     * StringUtils.chop("abc")         = "ab"
-     * StringUtils.chop("abc\nabc")    = "abc\nab"
-     * StringUtils.chop("a")           = ""
-     * StringUtils.chop("\r")          = ""
-     * StringUtils.chop("\n")          = ""
-     * StringUtils.chop("\r\n")        = ""
-     * 
- * - * @param str the String to chop last character from, may be null - * @return String without last character, {@code null} if null String input - */ - public static String chop(final String str) { - if (str == null) { - return null; - } - final int strLen = str.length(); - if (strLen < 2) { - return EMPTY; - } - final int lastIdx = strLen - 1; - final String ret = str.substring(0, lastIdx); - final char last = str.charAt(lastIdx); - if (last == CharUtils.LF && ret.charAt(lastIdx - 1) == CharUtils.CR) { - return ret.substring(0, lastIdx - 1); - } - return ret; - } - - // Conversion - //----------------------------------------------------------------------- - - // Padding - //----------------------------------------------------------------------- - /** - *

Repeat a String {@code repeat} times to form a - * new String.

- * - *
-     * StringUtils.repeat(null, 2) = null
-     * StringUtils.repeat("", 0)   = ""
-     * StringUtils.repeat("", 2)   = ""
-     * StringUtils.repeat("a", 3)  = "aaa"
-     * StringUtils.repeat("ab", 2) = "abab"
-     * StringUtils.repeat("a", -2) = ""
-     * 
- * - * @param str the String to repeat, may be null - * @param repeat number of times to repeat str, negative treated as zero - * @return a new String consisting of the original String repeated, - * {@code null} if null String input - */ - public static String repeat(final String str, final int repeat) { - // Performance tuned for 2.0 (JDK1.4) - - if (str == null) { - return null; - } - if (repeat <= 0) { - return EMPTY; - } - final int inputLength = str.length(); - if (repeat == 1 || inputLength == 0) { - return str; - } - if (inputLength == 1 && repeat <= PAD_LIMIT) { - return repeat(str.charAt(0), repeat); - } - - final int outputLength = inputLength * repeat; - switch (inputLength) { - case 1 : - return repeat(str.charAt(0), repeat); - case 2 : - final char ch0 = str.charAt(0); - final char ch1 = str.charAt(1); - final char[] output2 = new char[outputLength]; - for (int i = repeat * 2 - 2; i >= 0; i--, i--) { - output2[i] = ch0; - output2[i + 1] = ch1; - } - return new String(output2); - default : - final StringBuilder buf = new StringBuilder(outputLength); - for (int i = 0; i < repeat; i++) { - buf.append(str); - } - return buf.toString(); - } - } - - /** - *

Repeat a String {@code repeat} times to form a - * new String, with a String separator injected each time.

- * - *
-     * StringUtils.repeat(null, null, 2) = null
-     * StringUtils.repeat(null, "x", 2)  = null
-     * StringUtils.repeat("", null, 0)   = ""
-     * StringUtils.repeat("", "", 2)     = ""
-     * StringUtils.repeat("", "x", 3)    = "xxx"
-     * StringUtils.repeat("?", ", ", 3)  = "?, ?, ?"
-     * 
- * - * @param str the String to repeat, may be null - * @param separator the String to inject, may be null - * @param repeat number of times to repeat str, negative treated as zero - * @return a new String consisting of the original String repeated, - * {@code null} if null String input - * @since 2.5 - */ - public static String repeat(final String str, final String separator, final int repeat) { - if(str == null || separator == null) { - return repeat(str, repeat); - } - // given that repeat(String, int) is quite optimized, better to rely on it than try and splice this into it - final String result = repeat(str + separator, repeat); - return removeEnd(result, separator); - } - - /** - *

Returns padding using the specified delimiter repeated - * to a given length.

- * - *
-     * StringUtils.repeat('e', 0)  = ""
-     * StringUtils.repeat('e', 3)  = "eee"
-     * StringUtils.repeat('e', -2) = ""
-     * 
- * - *

Note: this method doesn't not support padding with - * Unicode Supplementary Characters - * as they require a pair of {@code char}s to be represented. - * If you are needing to support full I18N of your applications - * consider using {@link #repeat(String, int)} instead. - *

- * - * @param ch character to repeat - * @param repeat number of times to repeat char, negative treated as zero - * @return String with repeated character - * @see #repeat(String, int) - */ - public static String repeat(final char ch, final int repeat) { - if (repeat <= 0) { - return EMPTY; - } - final char[] buf = new char[repeat]; - for (int i = repeat - 1; i >= 0; i--) { - buf[i] = ch; - } - return new String(buf); - } - - /** - *

Right pad a String with spaces (' ').

- * - *

The String is padded to the size of {@code size}.

- * - *
-     * StringUtils.rightPad(null, *)   = null
-     * StringUtils.rightPad("", 3)     = "   "
-     * StringUtils.rightPad("bat", 3)  = "bat"
-     * StringUtils.rightPad("bat", 5)  = "bat  "
-     * StringUtils.rightPad("bat", 1)  = "bat"
-     * StringUtils.rightPad("bat", -1) = "bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @return right padded String or original String if no padding is necessary, - * {@code null} if null String input - */ - public static String rightPad(final String str, final int size) { - return rightPad(str, size, ' '); - } - - /** - *

Right pad a String with a specified character.

- * - *

The String is padded to the size of {@code size}.

- * - *
-     * StringUtils.rightPad(null, *, *)     = null
-     * StringUtils.rightPad("", 3, 'z')     = "zzz"
-     * StringUtils.rightPad("bat", 3, 'z')  = "bat"
-     * StringUtils.rightPad("bat", 5, 'z')  = "batzz"
-     * StringUtils.rightPad("bat", 1, 'z')  = "bat"
-     * StringUtils.rightPad("bat", -1, 'z') = "bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @param padChar the character to pad with - * @return right padded String or original String if no padding is necessary, - * {@code null} if null String input - * @since 2.0 - */ - public static String rightPad(final String str, final int size, final char padChar) { - if (str == null) { - return null; - } - final int pads = size - str.length(); - if (pads <= 0) { - return str; // returns original String when possible - } - if (pads > PAD_LIMIT) { - return rightPad(str, size, String.valueOf(padChar)); - } - return str.concat(repeat(padChar, pads)); - } - - /** - *

Right pad a String with a specified String.

- * - *

The String is padded to the size of {@code size}.

- * - *
-     * StringUtils.rightPad(null, *, *)      = null
-     * StringUtils.rightPad("", 3, "z")      = "zzz"
-     * StringUtils.rightPad("bat", 3, "yz")  = "bat"
-     * StringUtils.rightPad("bat", 5, "yz")  = "batyz"
-     * StringUtils.rightPad("bat", 8, "yz")  = "batyzyzy"
-     * StringUtils.rightPad("bat", 1, "yz")  = "bat"
-     * StringUtils.rightPad("bat", -1, "yz") = "bat"
-     * StringUtils.rightPad("bat", 5, null)  = "bat  "
-     * StringUtils.rightPad("bat", 5, "")    = "bat  "
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @param padStr the String to pad with, null or empty treated as single space - * @return right padded String or original String if no padding is necessary, - * {@code null} if null String input - */ - public static String rightPad(final String str, final int size, String padStr) { - if (str == null) { - return null; - } - if (isEmpty(padStr)) { - padStr = SPACE; - } - final int padLen = padStr.length(); - final int strLen = str.length(); - final int pads = size - strLen; - if (pads <= 0) { - return str; // returns original String when possible - } - if (padLen == 1 && pads <= PAD_LIMIT) { - return rightPad(str, size, padStr.charAt(0)); - } - - if (pads == padLen) { - return str.concat(padStr); - } else if (pads < padLen) { - return str.concat(padStr.substring(0, pads)); - } else { - final char[] padding = new char[pads]; - final char[] padChars = padStr.toCharArray(); - for (int i = 0; i < pads; i++) { - padding[i] = padChars[i % padLen]; - } - return str.concat(new String(padding)); - } - } - - /** - *

Left pad a String with spaces (' ').

- * - *

The String is padded to the size of {@code size}.

- * - *
-     * StringUtils.leftPad(null, *)   = null
-     * StringUtils.leftPad("", 3)     = "   "
-     * StringUtils.leftPad("bat", 3)  = "bat"
-     * StringUtils.leftPad("bat", 5)  = "  bat"
-     * StringUtils.leftPad("bat", 1)  = "bat"
-     * StringUtils.leftPad("bat", -1) = "bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @return left padded String or original String if no padding is necessary, - * {@code null} if null String input - */ - public static String leftPad(final String str, final int size) { - return leftPad(str, size, ' '); - } - - /** - *

Left pad a String with a specified character.

- * - *

Pad to a size of {@code size}.

- * - *
-     * StringUtils.leftPad(null, *, *)     = null
-     * StringUtils.leftPad("", 3, 'z')     = "zzz"
-     * StringUtils.leftPad("bat", 3, 'z')  = "bat"
-     * StringUtils.leftPad("bat", 5, 'z')  = "zzbat"
-     * StringUtils.leftPad("bat", 1, 'z')  = "bat"
-     * StringUtils.leftPad("bat", -1, 'z') = "bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @param padChar the character to pad with - * @return left padded String or original String if no padding is necessary, - * {@code null} if null String input - * @since 2.0 - */ - public static String leftPad(final String str, final int size, final char padChar) { - if (str == null) { - return null; - } - final int pads = size - str.length(); - if (pads <= 0) { - return str; // returns original String when possible - } - if (pads > PAD_LIMIT) { - return leftPad(str, size, String.valueOf(padChar)); - } - return repeat(padChar, pads).concat(str); - } - - /** - *

Left pad a String with a specified String.

- * - *

Pad to a size of {@code size}.

- * - *
-     * StringUtils.leftPad(null, *, *)      = null
-     * StringUtils.leftPad("", 3, "z")      = "zzz"
-     * StringUtils.leftPad("bat", 3, "yz")  = "bat"
-     * StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
-     * StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
-     * StringUtils.leftPad("bat", 1, "yz")  = "bat"
-     * StringUtils.leftPad("bat", -1, "yz") = "bat"
-     * StringUtils.leftPad("bat", 5, null)  = "  bat"
-     * StringUtils.leftPad("bat", 5, "")    = "  bat"
-     * 
- * - * @param str the String to pad out, may be null - * @param size the size to pad to - * @param padStr the String to pad with, null or empty treated as single space - * @return left padded String or original String if no padding is necessary, - * {@code null} if null String input - */ - public static String leftPad(final String str, final int size, String padStr) { - if (str == null) { - return null; - } - if (isEmpty(padStr)) { - padStr = SPACE; - } - final int padLen = padStr.length(); - final int strLen = str.length(); - final int pads = size - strLen; - if (pads <= 0) { - return str; // returns original String when possible - } - if (padLen == 1 && pads <= PAD_LIMIT) { - return leftPad(str, size, padStr.charAt(0)); - } - - if (pads == padLen) { - return padStr.concat(str); - } else if (pads < padLen) { - return padStr.substring(0, pads).concat(str); - } else { - final char[] padding = new char[pads]; - final char[] padChars = padStr.toCharArray(); - for (int i = 0; i < pads; i++) { - padding[i] = padChars[i % padLen]; - } - return new String(padding).concat(str); - } - } - - /** - * Gets a CharSequence length or {@code 0} if the CharSequence is - * {@code null}. - * - * @param cs - * a CharSequence or {@code null} - * @return CharSequence length or {@code 0} if the CharSequence is - * {@code null}. - * @since 2.4 - * @since 3.0 Changed signature from length(String) to length(CharSequence) - */ - public static int length(final CharSequence cs) { - return cs == null ? 0 : cs.length(); - } - - // Centering - //----------------------------------------------------------------------- - /** - *

Centers a String in a larger String of size {@code size} - * using the space character (' ').

- * - *

If the size is less than the String length, the String is returned. - * A {@code null} String returns {@code null}. - * A negative size is treated as zero.

- * - *

Equivalent to {@code center(str, size, " ")}.

- * - *
-     * StringUtils.center(null, *)   = null
-     * StringUtils.center("", 4)     = "    "
-     * StringUtils.center("ab", -1)  = "ab"
-     * StringUtils.center("ab", 4)   = " ab "
-     * StringUtils.center("abcd", 2) = "abcd"
-     * StringUtils.center("a", 4)    = " a  "
-     * 
- * - * @param str the String to center, may be null - * @param size the int size of new String, negative treated as zero - * @return centered String, {@code null} if null String input - */ - public static String center(final String str, final int size) { - return center(str, size, ' '); - } - - /** - *

Centers a String in a larger String of size {@code size}. - * Uses a supplied character as the value to pad the String with.

- * - *

If the size is less than the String length, the String is returned. - * A {@code null} String returns {@code null}. - * A negative size is treated as zero.

- * - *
-     * StringUtils.center(null, *, *)     = null
-     * StringUtils.center("", 4, ' ')     = "    "
-     * StringUtils.center("ab", -1, ' ')  = "ab"
-     * StringUtils.center("ab", 4, ' ')   = " ab "
-     * StringUtils.center("abcd", 2, ' ') = "abcd"
-     * StringUtils.center("a", 4, ' ')    = " a  "
-     * StringUtils.center("a", 4, 'y')    = "yayy"
-     * 
- * - * @param str the String to center, may be null - * @param size the int size of new String, negative treated as zero - * @param padChar the character to pad the new String with - * @return centered String, {@code null} if null String input - * @since 2.0 - */ - public static String center(String str, final int size, final char padChar) { - if (str == null || size <= 0) { - return str; - } - final int strLen = str.length(); - final int pads = size - strLen; - if (pads <= 0) { - return str; - } - str = leftPad(str, strLen + pads / 2, padChar); - str = rightPad(str, size, padChar); - return str; - } - - /** - *

Centers a String in a larger String of size {@code size}. - * Uses a supplied String as the value to pad the String with.

- * - *

If the size is less than the String length, the String is returned. - * A {@code null} String returns {@code null}. - * A negative size is treated as zero.

- * - *
-     * StringUtils.center(null, *, *)     = null
-     * StringUtils.center("", 4, " ")     = "    "
-     * StringUtils.center("ab", -1, " ")  = "ab"
-     * StringUtils.center("ab", 4, " ")   = " ab "
-     * StringUtils.center("abcd", 2, " ") = "abcd"
-     * StringUtils.center("a", 4, " ")    = " a  "
-     * StringUtils.center("a", 4, "yz")   = "yayz"
-     * StringUtils.center("abc", 7, null) = "  abc  "
-     * StringUtils.center("abc", 7, "")   = "  abc  "
-     * 
- * - * @param str the String to center, may be null - * @param size the int size of new String, negative treated as zero - * @param padStr the String to pad the new String with, must not be null or empty - * @return centered String, {@code null} if null String input - * @throws IllegalArgumentException if padStr is {@code null} or empty - */ - public static String center(String str, final int size, String padStr) { - if (str == null || size <= 0) { - return str; - } - if (isEmpty(padStr)) { - padStr = SPACE; - } - final int strLen = str.length(); - final int pads = size - strLen; - if (pads <= 0) { - return str; - } - str = leftPad(str, strLen + pads / 2, padStr); - str = rightPad(str, size, padStr); - return str; - } - - // Case conversion - //----------------------------------------------------------------------- - /** - *

Converts a String to upper case as per {@link String#toUpperCase()}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.upperCase(null)  = null
-     * StringUtils.upperCase("")    = ""
-     * StringUtils.upperCase("aBc") = "ABC"
-     * 
- * - *

Note: As described in the documentation for {@link String#toUpperCase()}, - * the result of this method is affected by the current locale. - * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)} - * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

- * - * @param str the String to upper case, may be null - * @return the upper cased String, {@code null} if null String input - */ - public static String upperCase(final String str) { - if (str == null) { - return null; - } - return str.toUpperCase(); - } - - /** - *

Converts a String to upper case as per {@link String#toUpperCase(Locale)}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.upperCase(null, Locale.ENGLISH)  = null
-     * StringUtils.upperCase("", Locale.ENGLISH)    = ""
-     * StringUtils.upperCase("aBc", Locale.ENGLISH) = "ABC"
-     * 
- * - * @param str the String to upper case, may be null - * @param locale the locale that defines the case transformation rules, must not be null - * @return the upper cased String, {@code null} if null String input - * @since 2.5 - */ - public static String upperCase(final String str, final Locale locale) { - if (str == null) { - return null; - } - return str.toUpperCase(locale); - } - - /** - *

Converts a String to lower case as per {@link String#toLowerCase()}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.lowerCase(null)  = null
-     * StringUtils.lowerCase("")    = ""
-     * StringUtils.lowerCase("aBc") = "abc"
-     * 
- * - *

Note: As described in the documentation for {@link String#toLowerCase()}, - * the result of this method is affected by the current locale. - * For platform-independent case transformations, the method {@link #lowerCase(String, Locale)} - * should be used with a specific locale (e.g. {@link Locale#ENGLISH}).

- * - * @param str the String to lower case, may be null - * @return the lower cased String, {@code null} if null String input - */ - public static String lowerCase(final String str) { - if (str == null) { - return null; - } - return str.toLowerCase(); - } - - /** - *

Converts a String to lower case as per {@link String#toLowerCase(Locale)}.

- * - *

A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.lowerCase(null, Locale.ENGLISH)  = null
-     * StringUtils.lowerCase("", Locale.ENGLISH)    = ""
-     * StringUtils.lowerCase("aBc", Locale.ENGLISH) = "abc"
-     * 
- * - * @param str the String to lower case, may be null - * @param locale the locale that defines the case transformation rules, must not be null - * @return the lower cased String, {@code null} if null String input - * @since 2.5 - */ - public static String lowerCase(final String str, final Locale locale) { - if (str == null) { - return null; - } - return str.toLowerCase(locale); - } - - /** - *

Capitalizes a String changing the first character to title case as - * per {@link Character#toTitleCase(char)}. No other characters are changed.

- * - *

For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#capitalize(String)}. - * A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.capitalize(null)  = null
-     * StringUtils.capitalize("")    = ""
-     * StringUtils.capitalize("cat") = "Cat"
-     * StringUtils.capitalize("cAt") = "CAt"
-     * StringUtils.capitalize("'cat'") = "'cat'"
-     * 
- * - * @param str the String to capitalize, may be null - * @return the capitalized String, {@code null} if null String input - * @see org.apache.commons.lang3.text.WordUtils#capitalize(String) - * @see #uncapitalize(String) - * @since 2.0 - */ - public static String capitalize(final String str) { - int strLen; - if (str == null || (strLen = str.length()) == 0) { - return str; - } - - final char firstChar = str.charAt(0); - final char newChar = Character.toTitleCase(firstChar); - if (firstChar == newChar) { - // already capitalized - return str; - } - - char[] newChars = new char[strLen]; - newChars[0] = newChar; - str.getChars(1,strLen, newChars, 1); - return String.valueOf(newChars); - } - - /** - *

Uncapitalizes a String, changing the first character to lower case as - * per {@link Character#toLowerCase(char)}. No other characters are changed.

- * - *

For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#uncapitalize(String)}. - * A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.uncapitalize(null)  = null
-     * StringUtils.uncapitalize("")    = ""
-     * StringUtils.uncapitalize("cat") = "cat"
-     * StringUtils.uncapitalize("Cat") = "cat"
-     * StringUtils.uncapitalize("CAT") = "cAT"
-     * 
- * - * @param str the String to uncapitalize, may be null - * @return the uncapitalized String, {@code null} if null String input - * @see org.apache.commons.lang3.text.WordUtils#uncapitalize(String) - * @see #capitalize(String) - * @since 2.0 - */ - public static String uncapitalize(final String str) { - int strLen; - if (str == null || (strLen = str.length()) == 0) { - return str; - } - - final char firstChar = str.charAt(0); - final char newChar = Character.toLowerCase(firstChar); - if (firstChar == newChar) { - // already uncapitalized - return str; - } - - char[] newChars = new char[strLen]; - newChars[0] = newChar; - str.getChars(1,strLen, newChars, 1); - return String.valueOf(newChars); - } - - /** - *

Swaps the case of a String changing upper and title case to - * lower case, and lower case to upper case.

- * - *
    - *
  • Upper case character converts to Lower case
  • - *
  • Title case character converts to Lower case
  • - *
  • Lower case character converts to Upper case
  • - *
- * - *

For a word based algorithm, see {@link org.apache.commons.lang3.text.WordUtils#swapCase(String)}. - * A {@code null} input String returns {@code null}.

- * - *
-     * StringUtils.swapCase(null)                 = null
-     * StringUtils.swapCase("")                   = ""
-     * StringUtils.swapCase("The dog has a BONE") = "tHE DOG HAS A bone"
-     * 
- * - *

NOTE: This method changed in Lang version 2.0. - * It no longer performs a word based algorithm. - * If you only use ASCII, you will notice no change. - * That functionality is available in org.apache.commons.lang3.text.WordUtils.

- * - * @param str the String to swap case, may be null - * @return the changed String, {@code null} if null String input - */ - public static String swapCase(final String str) { - if (StringUtils.isEmpty(str)) { - return str; - } - - final char[] buffer = str.toCharArray(); - - for (int i = 0; i < buffer.length; i++) { - final char ch = buffer[i]; - if (Character.isUpperCase(ch)) { - buffer[i] = Character.toLowerCase(ch); - } else if (Character.isTitleCase(ch)) { - buffer[i] = Character.toLowerCase(ch); - } else if (Character.isLowerCase(ch)) { - buffer[i] = Character.toUpperCase(ch); - } - } - return new String(buffer); - } - - // Count matches - //----------------------------------------------------------------------- - /** - *

Counts how many times the substring appears in the larger string.

- * - *

A {@code null} or empty ("") String input returns {@code 0}.

- * - *
-     * StringUtils.countMatches(null, *)       = 0
-     * StringUtils.countMatches("", *)         = 0
-     * StringUtils.countMatches("abba", null)  = 0
-     * StringUtils.countMatches("abba", "")    = 0
-     * StringUtils.countMatches("abba", "a")   = 2
-     * StringUtils.countMatches("abba", "ab")  = 1
-     * StringUtils.countMatches("abba", "xxx") = 0
-     * 
- * - * @param str the CharSequence to check, may be null - * @param sub the substring to count, may be null - * @return the number of occurrences, 0 if either CharSequence is {@code null} - * @since 3.0 Changed signature from countMatches(String, String) to countMatches(CharSequence, CharSequence) - */ - public static int countMatches(final CharSequence str, final CharSequence sub) { - if (isEmpty(str) || isEmpty(sub)) { - return 0; - } - int count = 0; - int idx = 0; - while ((idx = CharSequenceUtils.indexOf(str, sub, idx)) != INDEX_NOT_FOUND) { - count++; - idx += sub.length(); - } - return count; - } - - /** - *

Counts how many times the char appears in the given string.

- * - *

A {@code null} or empty ("") String input returns {@code 0}.

- * - *
-     * StringUtils.countMatches(null, *)       = 0
-     * StringUtils.countMatches("", *)         = 0
-     * StringUtils.countMatches("abba", 0)  = 0
-     * StringUtils.countMatches("abba", 'a')   = 2
-     * StringUtils.countMatches("abba", 'b')  = 2
-     * StringUtils.countMatches("abba", 'x') = 0
-     * 
- * - * @param str the CharSequence to check, may be null - * @param ch the char to count - * @return the number of occurrences, 0 if the CharSequence is {@code null} - * @since 3.4 - */ - public static int countMatches(final CharSequence str, final char ch) { - if (isEmpty(str)) { - return 0; - } - int count = 0; - // We could also call str.toCharArray() for faster look ups but that would generate more garbage. - for (int i = 0; i < str.length(); i++) { - if (ch == str.charAt(i)) { - count++; - } - } - return count; - } - - // Character Tests - //----------------------------------------------------------------------- - /** - *

Checks if the CharSequence contains only Unicode letters.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code false}.

- * - *
-     * StringUtils.isAlpha(null)   = false
-     * StringUtils.isAlpha("")     = false
-     * StringUtils.isAlpha("  ")   = false
-     * StringUtils.isAlpha("abc")  = true
-     * StringUtils.isAlpha("ab2c") = false
-     * StringUtils.isAlpha("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains letters, and is non-null - * @since 3.0 Changed signature from isAlpha(String) to isAlpha(CharSequence) - * @since 3.0 Changed "" to return false and not true - */ - public static boolean isAlpha(final CharSequence cs) { - if (isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLetter(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode letters and - * space (' ').

- * - *

{@code null} will return {@code false} - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isAlphaSpace(null)   = false
-     * StringUtils.isAlphaSpace("")     = true
-     * StringUtils.isAlphaSpace("  ")   = true
-     * StringUtils.isAlphaSpace("abc")  = true
-     * StringUtils.isAlphaSpace("ab c") = true
-     * StringUtils.isAlphaSpace("ab2c") = false
-     * StringUtils.isAlphaSpace("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains letters and space, - * and is non-null - * @since 3.0 Changed signature from isAlphaSpace(String) to isAlphaSpace(CharSequence) - */ - public static boolean isAlphaSpace(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLetter(cs.charAt(i)) == false && cs.charAt(i) != ' ') { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode letters or digits.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code false}.

- * - *
-     * StringUtils.isAlphanumeric(null)   = false
-     * StringUtils.isAlphanumeric("")     = false
-     * StringUtils.isAlphanumeric("  ")   = false
-     * StringUtils.isAlphanumeric("abc")  = true
-     * StringUtils.isAlphanumeric("ab c") = false
-     * StringUtils.isAlphanumeric("ab2c") = true
-     * StringUtils.isAlphanumeric("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains letters or digits, - * and is non-null - * @since 3.0 Changed signature from isAlphanumeric(String) to isAlphanumeric(CharSequence) - * @since 3.0 Changed "" to return false and not true - */ - public static boolean isAlphanumeric(final CharSequence cs) { - if (isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLetterOrDigit(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode letters, digits - * or space ({@code ' '}).

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isAlphanumericSpace(null)   = false
-     * StringUtils.isAlphanumericSpace("")     = true
-     * StringUtils.isAlphanumericSpace("  ")   = true
-     * StringUtils.isAlphanumericSpace("abc")  = true
-     * StringUtils.isAlphanumericSpace("ab c") = true
-     * StringUtils.isAlphanumericSpace("ab2c") = true
-     * StringUtils.isAlphanumericSpace("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains letters, digits or space, - * and is non-null - * @since 3.0 Changed signature from isAlphanumericSpace(String) to isAlphanumericSpace(CharSequence) - */ - public static boolean isAlphanumericSpace(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLetterOrDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only ASCII printable characters.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isAsciiPrintable(null)     = false
-     * StringUtils.isAsciiPrintable("")       = true
-     * StringUtils.isAsciiPrintable(" ")      = true
-     * StringUtils.isAsciiPrintable("Ceki")   = true
-     * StringUtils.isAsciiPrintable("ab2c")   = true
-     * StringUtils.isAsciiPrintable("!ab-c~") = true
-     * StringUtils.isAsciiPrintable("\u0020") = true
-     * StringUtils.isAsciiPrintable("\u0021") = true
-     * StringUtils.isAsciiPrintable("\u007e") = true
-     * StringUtils.isAsciiPrintable("\u007f") = false
-     * StringUtils.isAsciiPrintable("Ceki G\u00fclc\u00fc") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if every character is in the range - * 32 thru 126 - * @since 2.1 - * @since 3.0 Changed signature from isAsciiPrintable(String) to isAsciiPrintable(CharSequence) - */ - public static boolean isAsciiPrintable(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (CharUtils.isAsciiPrintable(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode digits. - * A decimal point is not a Unicode digit and returns false.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code false}.

- * - *

Note that the method does not allow for a leading sign, either positive or negative. - * Also, if a String passes the numeric test, it may still generate a NumberFormatException - * when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range - * for int or long respectively.

- * - *
-     * StringUtils.isNumeric(null)   = false
-     * StringUtils.isNumeric("")     = false
-     * StringUtils.isNumeric("  ")   = false
-     * StringUtils.isNumeric("123")  = true
-     * StringUtils.isNumeric("\u0967\u0968\u0969")  = true
-     * StringUtils.isNumeric("12 3") = false
-     * StringUtils.isNumeric("ab2c") = false
-     * StringUtils.isNumeric("12-3") = false
-     * StringUtils.isNumeric("12.3") = false
-     * StringUtils.isNumeric("-123") = false
-     * StringUtils.isNumeric("+123") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains digits, and is non-null - * @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence) - * @since 3.0 Changed "" to return false and not true - */ - public static boolean isNumeric(final CharSequence cs) { - if (isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (!Character.isDigit(cs.charAt(i))) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only Unicode digits or space - * ({@code ' '}). - * A decimal point is not a Unicode digit and returns false.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isNumericSpace(null)   = false
-     * StringUtils.isNumericSpace("")     = true
-     * StringUtils.isNumericSpace("  ")   = true
-     * StringUtils.isNumericSpace("123")  = true
-     * StringUtils.isNumericSpace("12 3") = true
-     * StringUtils.isNumeric("\u0967\u0968\u0969")  = true
-     * StringUtils.isNumeric("\u0967\u0968 \u0969")  = true
-     * StringUtils.isNumericSpace("ab2c") = false
-     * StringUtils.isNumericSpace("12-3") = false
-     * StringUtils.isNumericSpace("12.3") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains digits or space, - * and is non-null - * @since 3.0 Changed signature from isNumericSpace(String) to isNumericSpace(CharSequence) - */ - public static boolean isNumericSpace(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isDigit(cs.charAt(i)) == false && cs.charAt(i) != ' ') { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only whitespace.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code true}.

- * - *
-     * StringUtils.isWhitespace(null)   = false
-     * StringUtils.isWhitespace("")     = true
-     * StringUtils.isWhitespace("  ")   = true
-     * StringUtils.isWhitespace("abc")  = false
-     * StringUtils.isWhitespace("ab2c") = false
-     * StringUtils.isWhitespace("ab-c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains whitespace, and is non-null - * @since 2.0 - * @since 3.0 Changed signature from isWhitespace(String) to isWhitespace(CharSequence) - */ - public static boolean isWhitespace(final CharSequence cs) { - if (cs == null) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isWhitespace(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only lowercase characters.

- * - *

{@code null} will return {@code false}. - * An empty CharSequence (length()=0) will return {@code false}.

- * - *
-     * StringUtils.isAllLowerCase(null)   = false
-     * StringUtils.isAllLowerCase("")     = false
-     * StringUtils.isAllLowerCase("  ")   = false
-     * StringUtils.isAllLowerCase("abc")  = true
-     * StringUtils.isAllLowerCase("abC")  = false
-     * StringUtils.isAllLowerCase("ab c") = false
-     * StringUtils.isAllLowerCase("ab1c") = false
-     * StringUtils.isAllLowerCase("ab/c") = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains lowercase characters, and is non-null - * @since 2.5 - * @since 3.0 Changed signature from isAllLowerCase(String) to isAllLowerCase(CharSequence) - */ - public static boolean isAllLowerCase(final CharSequence cs) { - if (cs == null || isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isLowerCase(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - /** - *

Checks if the CharSequence contains only uppercase characters.

- * - *

{@code null} will return {@code false}. - * An empty String (length()=0) will return {@code false}.

- * - *
-     * StringUtils.isAllUpperCase(null)   = false
-     * StringUtils.isAllUpperCase("")     = false
-     * StringUtils.isAllUpperCase("  ")   = false
-     * StringUtils.isAllUpperCase("ABC")  = true
-     * StringUtils.isAllUpperCase("aBC")  = false
-     * StringUtils.isAllUpperCase("A C")  = false
-     * StringUtils.isAllUpperCase("A1C")  = false
-     * StringUtils.isAllUpperCase("A/C")  = false
-     * 
- * - * @param cs the CharSequence to check, may be null - * @return {@code true} if only contains uppercase characters, and is non-null - * @since 2.5 - * @since 3.0 Changed signature from isAllUpperCase(String) to isAllUpperCase(CharSequence) - */ - public static boolean isAllUpperCase(final CharSequence cs) { - if (cs == null || isEmpty(cs)) { - return false; - } - final int sz = cs.length(); - for (int i = 0; i < sz; i++) { - if (Character.isUpperCase(cs.charAt(i)) == false) { - return false; - } - } - return true; - } - - // Defaults - //----------------------------------------------------------------------- - /** - *

Returns either the passed in String, - * or if the String is {@code null}, an empty String ("").

- * - *
-     * StringUtils.defaultString(null)  = ""
-     * StringUtils.defaultString("")    = ""
-     * StringUtils.defaultString("bat") = "bat"
-     * 
- * - * @see ObjectUtils#toString(Object) - * @see String#valueOf(Object) - * @param str the String to check, may be null - * @return the passed in String, or the empty String if it - * was {@code null} - */ - public static String defaultString(final String str) { - return str == null ? EMPTY : str; - } - - /** - *

Returns either the passed in String, or if the String is - * {@code null}, the value of {@code defaultStr}.

- * - *
-     * StringUtils.defaultString(null, "NULL")  = "NULL"
-     * StringUtils.defaultString("", "NULL")    = ""
-     * StringUtils.defaultString("bat", "NULL") = "bat"
-     * 
- * - * @see ObjectUtils#toString(Object,String) - * @see String#valueOf(Object) - * @param str the String to check, may be null - * @param defaultStr the default String to return - * if the input is {@code null}, may be null - * @return the passed in String, or the default if it was {@code null} - */ - public static String defaultString(final String str, final String defaultStr) { - return str == null ? defaultStr : str; - } - - /** - *

Returns either the passed in CharSequence, or if the CharSequence is - * whitespace, empty ("") or {@code null}, the value of {@code defaultStr}.

- * - *
-     * StringUtils.defaultIfBlank(null, "NULL")  = "NULL"
-     * StringUtils.defaultIfBlank("", "NULL")    = "NULL"
-     * StringUtils.defaultIfBlank(" ", "NULL")   = "NULL"
-     * StringUtils.defaultIfBlank("bat", "NULL") = "bat"
-     * StringUtils.defaultIfBlank("", null)      = null
-     * 
- * @param the specific kind of CharSequence - * @param str the CharSequence to check, may be null - * @param defaultStr the default CharSequence to return - * if the input is whitespace, empty ("") or {@code null}, may be null - * @return the passed in CharSequence, or the default - * @see StringUtils#defaultString(String, String) - */ - public static T defaultIfBlank(final T str, final T defaultStr) { - return isBlank(str) ? defaultStr : str; - } - - /** - *

Returns either the passed in CharSequence, or if the CharSequence is - * empty or {@code null}, the value of {@code defaultStr}.

- * - *
-     * StringUtils.defaultIfEmpty(null, "NULL")  = "NULL"
-     * StringUtils.defaultIfEmpty("", "NULL")    = "NULL"
-     * StringUtils.defaultIfEmpty(" ", "NULL")   = " "
-     * StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
-     * StringUtils.defaultIfEmpty("", null)      = null
-     * 
- * @param the specific kind of CharSequence - * @param str the CharSequence to check, may be null - * @param defaultStr the default CharSequence to return - * if the input is empty ("") or {@code null}, may be null - * @return the passed in CharSequence, or the default - * @see StringUtils#defaultString(String, String) - */ - public static T defaultIfEmpty(final T str, final T defaultStr) { - return isEmpty(str) ? defaultStr : str; - } - - // Rotating (circular shift) - //----------------------------------------------------------------------- - /** - *

Rotate (circular shift) a String of {@code shift} characters.

- *
    - *
  • If {@code shift > 0}, right circular shift (ex : ABCDEF => FABCDE)
  • - *
  • If {@code shift < 0}, left circular shift (ex : ABCDEF => BCDEFA)
  • - *
- * - *
-     * StringUtils.rotate(null, *)        = null
-     * StringUtils.rotate("", *)          = ""
-     * StringUtils.rotate("abcdefg", 0)   = "abcdefg"
-     * StringUtils.rotate("abcdefg", 2)   = "fgabcde"
-     * StringUtils.rotate("abcdefg", -2)  = "cdefgab"
-     * StringUtils.rotate("abcdefg", 7)   = "abcdefg"
-     * StringUtils.rotate("abcdefg", -7)  = "abcdefg"
-     * StringUtils.rotate("abcdefg", 9)   = "fgabcde"
-     * StringUtils.rotate("abcdefg", -9)  = "cdefgab"
-     * 
- * - * @param str the String to rotate, may be null - * @param shift number of time to shift (positive : right shift, negative : left shift) - * @return the rotated String, - * or the original String if {@code shift == 0}, - * or {@code null} if null String input - */ - public static String rotate(String str, int shift) { - if (str == null) { - return null; - } - - final int strLen = str.length(); - if (shift == 0 || strLen == 0 || shift % strLen == 0) { - return str; - } - - final StringBuilder builder = new StringBuilder(strLen); - final int offset = - (shift % strLen); - builder.append(substring(str, offset)); - builder.append(substring(str, 0, offset)); - return builder.toString(); - } - - // Reversing - //----------------------------------------------------------------------- - /** - *

Reverses a String as per {@link StringBuilder#reverse()}.

- * - *

A {@code null} String returns {@code null}.

- * - *
-     * StringUtils.reverse(null)  = null
-     * StringUtils.reverse("")    = ""
-     * StringUtils.reverse("bat") = "tab"
-     * 
- * - * @param str the String to reverse, may be null - * @return the reversed String, {@code null} if null String input - */ - public static String reverse(final String str) { - if (str == null) { - return null; - } - return new StringBuilder(str).reverse().toString(); - } - - /** - *

Reverses a String that is delimited by a specific character.

- * - *

The Strings between the delimiters are not reversed. - * Thus java.lang.String becomes String.lang.java (if the delimiter - * is {@code '.'}).

- * - *
-     * StringUtils.reverseDelimited(null, *)      = null
-     * StringUtils.reverseDelimited("", *)        = ""
-     * StringUtils.reverseDelimited("a.b.c", 'x') = "a.b.c"
-     * StringUtils.reverseDelimited("a.b.c", ".") = "c.b.a"
-     * 
- * - * @param str the String to reverse, may be null - * @param separatorChar the separator character to use - * @return the reversed String, {@code null} if null String input - * @since 2.0 - */ - public static String reverseDelimited(final String str, final char separatorChar) { - if (str == null) { - return null; - } - // could implement manually, but simple way is to reuse other, - // probably slower, methods. - final String[] strs = split(str, separatorChar); - ArrayUtils.reverse(strs); - return join(strs, separatorChar); - } - - // Abbreviating - //----------------------------------------------------------------------- - /** - *

Abbreviates a String using ellipses. This will turn - * "Now is the time for all good men" into "Now is the time for..."

- * - *

Specifically:

- *
    - *
  • If the number of characters in {@code str} is less than or equal to - * {@code maxWidth}, return {@code str}.
  • - *
  • Else abbreviate it to {@code (substring(str, 0, max-3) + "...")}.
  • - *
  • If {@code maxWidth} is less than {@code 4}, throw an - * {@code IllegalArgumentException}.
  • - *
  • In no case will it return a String of length greater than - * {@code maxWidth}.
  • - *
- * - *
-     * StringUtils.abbreviate(null, *)      = null
-     * StringUtils.abbreviate("", 4)        = ""
-     * StringUtils.abbreviate("abcdefg", 6) = "abc..."
-     * StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
-     * StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
-     * StringUtils.abbreviate("abcdefg", 4) = "a..."
-     * StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
-     * 
- * - * @param str the String to check, may be null - * @param maxWidth maximum length of result String, must be at least 4 - * @return abbreviated String, {@code null} if null String input - * @throws IllegalArgumentException if the width is too small - * @since 2.0 - */ - public static String abbreviate(final String str, final int maxWidth) { - return abbreviate(str, 0, maxWidth); - } - - /** - *

Abbreviates a String using ellipses. This will turn - * "Now is the time for all good men" into "...is the time for..."

- * - *

Works like {@code abbreviate(String, int)}, but allows you to specify - * a "left edge" offset. Note that this left edge is not necessarily going to - * be the leftmost character in the result, or the first character following the - * ellipses, but it will appear somewhere in the result. - * - *

In no case will it return a String of length greater than - * {@code maxWidth}.

- * - *
-     * StringUtils.abbreviate(null, *, *)                = null
-     * StringUtils.abbreviate("", 0, 4)                  = ""
-     * StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
-     * StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
-     * StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
-     * StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
-     * StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
-     * StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
-     * StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
-     * StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
-     * StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
-     * StringUtils.abbreviate("abcdefghij", 0, 3)        = IllegalArgumentException
-     * StringUtils.abbreviate("abcdefghij", 5, 6)        = IllegalArgumentException
-     * 
- * - * @param str the String to check, may be null - * @param offset left edge of source String - * @param maxWidth maximum length of result String, must be at least 4 - * @return abbreviated String, {@code null} if null String input - * @throws IllegalArgumentException if the width is too small - * @since 2.0 - */ - public static String abbreviate(final String str, int offset, final int maxWidth) { - if (str == null) { - return null; - } - if (maxWidth < 4) { - throw new IllegalArgumentException("Minimum abbreviation width is 4"); - } - if (str.length() <= maxWidth) { - return str; - } - if (offset > str.length()) { - offset = str.length(); - } - if (str.length() - offset < maxWidth - 3) { - offset = str.length() - (maxWidth - 3); - } - final String abrevMarker = "..."; - if (offset <= 4) { - return str.substring(0, maxWidth - 3) + abrevMarker; - } - if (maxWidth < 7) { - throw new IllegalArgumentException("Minimum abbreviation width with offset is 7"); - } - if (offset + maxWidth - 3 < str.length()) { - return abrevMarker + abbreviate(str.substring(offset), maxWidth - 3); - } - return abrevMarker + str.substring(str.length() - (maxWidth - 3)); - } - - /** - *

Abbreviates a String to the length passed, replacing the middle characters with the supplied - * replacement String.

- * - *

This abbreviation only occurs if the following criteria is met:

- *
    - *
  • Neither the String for abbreviation nor the replacement String are null or empty
  • - *
  • The length to truncate to is less than the length of the supplied String
  • - *
  • The length to truncate to is greater than 0
  • - *
  • The abbreviated String will have enough room for the length supplied replacement String - * and the first and last characters of the supplied String for abbreviation
  • - *
- *

Otherwise, the returned String will be the same as the supplied String for abbreviation. - *

- * - *
-     * StringUtils.abbreviateMiddle(null, null, 0)      = null
-     * StringUtils.abbreviateMiddle("abc", null, 0)      = "abc"
-     * StringUtils.abbreviateMiddle("abc", ".", 0)      = "abc"
-     * StringUtils.abbreviateMiddle("abc", ".", 3)      = "abc"
-     * StringUtils.abbreviateMiddle("abcdef", ".", 4)     = "ab.f"
-     * 
- * - * @param str the String to abbreviate, may be null - * @param middle the String to replace the middle characters with, may be null - * @param length the length to abbreviate {@code str} to. - * @return the abbreviated String if the above criteria is met, or the original String supplied for abbreviation. - * @since 2.5 - */ - public static String abbreviateMiddle(final String str, final String middle, final int length) { - if (isEmpty(str) || isEmpty(middle)) { - return str; - } - - if (length >= str.length() || length < middle.length()+2) { - return str; - } - - final int targetSting = length-middle.length(); - final int startOffset = targetSting/2+targetSting%2; - final int endOffset = str.length()-targetSting/2; - - final StringBuilder builder = new StringBuilder(length); - builder.append(str.substring(0,startOffset)); - builder.append(middle); - builder.append(str.substring(endOffset)); - - return builder.toString(); - } - - // Difference - //----------------------------------------------------------------------- - /** - *

Compares two Strings, and returns the portion where they differ. - * More precisely, return the remainder of the second String, - * starting from where it's different from the first. This means that - * the difference between "abc" and "ab" is the empty String and not "c".

- * - *

For example, - * {@code difference("i am a machine", "i am a robot") -> "robot"}.

- * - *
-     * StringUtils.difference(null, null) = null
-     * StringUtils.difference("", "") = ""
-     * StringUtils.difference("", "abc") = "abc"
-     * StringUtils.difference("abc", "") = ""
-     * StringUtils.difference("abc", "abc") = ""
-     * StringUtils.difference("abc", "ab") = ""
-     * StringUtils.difference("ab", "abxyz") = "xyz"
-     * StringUtils.difference("abcde", "abxyz") = "xyz"
-     * StringUtils.difference("abcde", "xyz") = "xyz"
-     * 
- * - * @param str1 the first String, may be null - * @param str2 the second String, may be null - * @return the portion of str2 where it differs from str1; returns the - * empty String if they are equal - * @see #indexOfDifference(CharSequence,CharSequence) - * @since 2.0 - */ - public static String difference(final String str1, final String str2) { - if (str1 == null) { - return str2; - } - if (str2 == null) { - return str1; - } - final int at = indexOfDifference(str1, str2); - if (at == INDEX_NOT_FOUND) { - return EMPTY; - } - return str2.substring(at); - } - - /** - *

Compares two CharSequences, and returns the index at which the - * CharSequences begin to differ.

- * - *

For example, - * {@code indexOfDifference("i am a machine", "i am a robot") -> 7}

- * - *
-     * StringUtils.indexOfDifference(null, null) = -1
-     * StringUtils.indexOfDifference("", "") = -1
-     * StringUtils.indexOfDifference("", "abc") = 0
-     * StringUtils.indexOfDifference("abc", "") = 0
-     * StringUtils.indexOfDifference("abc", "abc") = -1
-     * StringUtils.indexOfDifference("ab", "abxyz") = 2
-     * StringUtils.indexOfDifference("abcde", "abxyz") = 2
-     * StringUtils.indexOfDifference("abcde", "xyz") = 0
-     * 
- * - * @param cs1 the first CharSequence, may be null - * @param cs2 the second CharSequence, may be null - * @return the index where cs1 and cs2 begin to differ; -1 if they are equal - * @since 2.0 - * @since 3.0 Changed signature from indexOfDifference(String, String) to - * indexOfDifference(CharSequence, CharSequence) - */ - public static int indexOfDifference(final CharSequence cs1, final CharSequence cs2) { - if (cs1 == cs2) { - return INDEX_NOT_FOUND; - } - if (cs1 == null || cs2 == null) { - return 0; - } - int i; - for (i = 0; i < cs1.length() && i < cs2.length(); ++i) { - if (cs1.charAt(i) != cs2.charAt(i)) { - break; - } - } - if (i < cs2.length() || i < cs1.length()) { - return i; - } - return INDEX_NOT_FOUND; - } - - /** - *

Compares all CharSequences in an array and returns the index at which the - * CharSequences begin to differ.

- * - *

For example, - * indexOfDifference(new String[] {"i am a machine", "i am a robot"}) -> 7

- * - *
-     * StringUtils.indexOfDifference(null) = -1
-     * StringUtils.indexOfDifference(new String[] {}) = -1
-     * StringUtils.indexOfDifference(new String[] {"abc"}) = -1
-     * StringUtils.indexOfDifference(new String[] {null, null}) = -1
-     * StringUtils.indexOfDifference(new String[] {"", ""}) = -1
-     * StringUtils.indexOfDifference(new String[] {"", null}) = 0
-     * StringUtils.indexOfDifference(new String[] {"abc", null, null}) = 0
-     * StringUtils.indexOfDifference(new String[] {null, null, "abc"}) = 0
-     * StringUtils.indexOfDifference(new String[] {"", "abc"}) = 0
-     * StringUtils.indexOfDifference(new String[] {"abc", ""}) = 0
-     * StringUtils.indexOfDifference(new String[] {"abc", "abc"}) = -1
-     * StringUtils.indexOfDifference(new String[] {"abc", "a"}) = 1
-     * StringUtils.indexOfDifference(new String[] {"ab", "abxyz"}) = 2
-     * StringUtils.indexOfDifference(new String[] {"abcde", "abxyz"}) = 2
-     * StringUtils.indexOfDifference(new String[] {"abcde", "xyz"}) = 0
-     * StringUtils.indexOfDifference(new String[] {"xyz", "abcde"}) = 0
-     * StringUtils.indexOfDifference(new String[] {"i am a machine", "i am a robot"}) = 7
-     * 
- * - * @param css array of CharSequences, entries may be null - * @return the index where the strings begin to differ; -1 if they are all equal - * @since 2.4 - * @since 3.0 Changed signature from indexOfDifference(String...) to indexOfDifference(CharSequence...) - */ - public static int indexOfDifference(final CharSequence... css) { - if (css == null || css.length <= 1) { - return INDEX_NOT_FOUND; - } - boolean anyStringNull = false; - boolean allStringsNull = true; - final int arrayLen = css.length; - int shortestStrLen = Integer.MAX_VALUE; - int longestStrLen = 0; - - // find the min and max string lengths; this avoids checking to make - // sure we are not exceeding the length of the string each time through - // the bottom loop. - for (int i = 0; i < arrayLen; i++) { - if (css[i] == null) { - anyStringNull = true; - shortestStrLen = 0; - } else { - allStringsNull = false; - shortestStrLen = Math.min(css[i].length(), shortestStrLen); - longestStrLen = Math.max(css[i].length(), longestStrLen); - } - } - - // handle lists containing all nulls or all empty strings - if (allStringsNull || longestStrLen == 0 && !anyStringNull) { - return INDEX_NOT_FOUND; - } - - // handle lists containing some nulls or some empty strings - if (shortestStrLen == 0) { - return 0; - } - - // find the position with the first difference across all strings - int firstDiff = -1; - for (int stringPos = 0; stringPos < shortestStrLen; stringPos++) { - final char comparisonChar = css[0].charAt(stringPos); - for (int arrayPos = 1; arrayPos < arrayLen; arrayPos++) { - if (css[arrayPos].charAt(stringPos) != comparisonChar) { - firstDiff = stringPos; - break; - } - } - if (firstDiff != -1) { - break; - } - } - - if (firstDiff == -1 && shortestStrLen != longestStrLen) { - // we compared all of the characters up to the length of the - // shortest string and didn't find a match, but the string lengths - // vary, so return the length of the shortest string. - return shortestStrLen; - } - return firstDiff; - } - - /** - *

Compares all Strings in an array and returns the initial sequence of - * characters that is common to all of them.

- * - *

For example, - * getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) -> "i am a "

- * - *
-     * StringUtils.getCommonPrefix(null) = ""
-     * StringUtils.getCommonPrefix(new String[] {}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"abc"}) = "abc"
-     * StringUtils.getCommonPrefix(new String[] {null, null}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"", ""}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"", null}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"abc", null, null}) = ""
-     * StringUtils.getCommonPrefix(new String[] {null, null, "abc"}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"", "abc"}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"abc", ""}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"abc", "abc"}) = "abc"
-     * StringUtils.getCommonPrefix(new String[] {"abc", "a"}) = "a"
-     * StringUtils.getCommonPrefix(new String[] {"ab", "abxyz"}) = "ab"
-     * StringUtils.getCommonPrefix(new String[] {"abcde", "abxyz"}) = "ab"
-     * StringUtils.getCommonPrefix(new String[] {"abcde", "xyz"}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"xyz", "abcde"}) = ""
-     * StringUtils.getCommonPrefix(new String[] {"i am a machine", "i am a robot"}) = "i am a "
-     * 
- * - * @param strs array of String objects, entries may be null - * @return the initial sequence of characters that are common to all Strings - * in the array; empty String if the array is null, the elements are all null - * or if there is no common prefix. - * @since 2.4 - */ - public static String getCommonPrefix(final String... strs) { - if (strs == null || strs.length == 0) { - return EMPTY; - } - final int smallestIndexOfDiff = indexOfDifference(strs); - if (smallestIndexOfDiff == INDEX_NOT_FOUND) { - // all strings were identical - if (strs[0] == null) { - return EMPTY; - } - return strs[0]; - } else if (smallestIndexOfDiff == 0) { - // there were no common initial characters - return EMPTY; - } else { - // we found a common initial character sequence - return strs[0].substring(0, smallestIndexOfDiff); - } - } - - // Misc - //----------------------------------------------------------------------- - /** - *

Find the Levenshtein distance between two Strings.

- * - *

This is the number of changes needed to change one String into - * another, where each change is a single character modification (deletion, - * insertion or substitution).

- * - *

The previous implementation of the Levenshtein distance algorithm - * was from http://www.merriampark.com/ld.htm

- * - *

Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError - * which can occur when my Java implementation is used with very large strings.
- * This implementation of the Levenshtein distance algorithm - * is from http://www.merriampark.com/ldjava.htm

- * - *
-     * StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance("","")               = 0
-     * StringUtils.getLevenshteinDistance("","a")              = 1
-     * StringUtils.getLevenshteinDistance("aaapppp", "")       = 7
-     * StringUtils.getLevenshteinDistance("frog", "fog")       = 1
-     * StringUtils.getLevenshteinDistance("fly", "ant")        = 3
-     * StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
-     * StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
-     * StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
-     * StringUtils.getLevenshteinDistance("hello", "hallo")    = 1
-     * 
- * - * @param s the first String, must not be null - * @param t the second String, must not be null - * @return result distance - * @throws IllegalArgumentException if either String input {@code null} - * @since 3.0 Changed signature from getLevenshteinDistance(String, String) to - * getLevenshteinDistance(CharSequence, CharSequence) - */ - public static int getLevenshteinDistance(CharSequence s, CharSequence t) { - if (s == null || t == null) { - throw new IllegalArgumentException("Strings must not be null"); - } - - /* - The difference between this impl. and the previous is that, rather - than creating and retaining a matrix of size s.length() + 1 by t.length() + 1, - we maintain two single-dimensional arrays of length s.length() + 1. The first, d, - is the 'current working' distance array that maintains the newest distance cost - counts as we iterate through the characters of String s. Each time we increment - the index of String t we are comparing, d is copied to p, the second int[]. Doing so - allows us to retain the previous cost counts as required by the algorithm (taking - the minimum of the cost count to the left, up one, and diagonally up and to the left - of the current cost count being calculated). (Note that the arrays aren't really - copied anymore, just switched...this is clearly much better than cloning an array - or doing a System.arraycopy() each time through the outer loop.) - - Effectively, the difference between the two implementations is this one does not - cause an out of memory condition when calculating the LD over two very large strings. - */ - - int n = s.length(); // length of s - int m = t.length(); // length of t - - if (n == 0) { - return m; - } else if (m == 0) { - return n; - } - - if (n > m) { - // swap the input strings to consume less memory - final CharSequence tmp = s; - s = t; - t = tmp; - n = m; - m = t.length(); - } - - int p[] = new int[n + 1]; //'previous' cost array, horizontally - int d[] = new int[n + 1]; // cost array, horizontally - int _d[]; //placeholder to assist in swapping p and d - - // indexes into strings s and t - int i; // iterates through s - int j; // iterates through t - - char t_j; // jth character of t - - int cost; // cost - - for (i = 0; i <= n; i++) { - p[i] = i; - } - - for (j = 1; j <= m; j++) { - t_j = t.charAt(j - 1); - d[0] = j; - - for (i = 1; i <= n; i++) { - cost = s.charAt(i - 1) == t_j ? 0 : 1; - // minimum of cell to the left+1, to the top+1, diagonally left and up +cost - d[i] = Math.min(Math.min(d[i - 1] + 1, p[i] + 1), p[i - 1] + cost); - } - - // copy current distance counts to 'previous row' distance counts - _d = p; - p = d; - d = _d; - } - - // our last action in the above loop was to switch d and p, so p now - // actually has the most recent cost counts - return p[n]; - } - - /** - *

Find the Levenshtein distance between two Strings if it's less than or equal to a given - * threshold.

- * - *

This is the number of changes needed to change one String into - * another, where each change is a single character modification (deletion, - * insertion or substitution).

- * - *

This implementation follows from Algorithms on Strings, Trees and Sequences by Dan Gusfield - * and Chas Emerick's implementation of the Levenshtein distance algorithm from - * http://www.merriampark.com/ld.htm

- * - *
-     * StringUtils.getLevenshteinDistance(null, *, *)             = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance(*, null, *)             = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance(*, *, -1)               = IllegalArgumentException
-     * StringUtils.getLevenshteinDistance("","", 0)               = 0
-     * StringUtils.getLevenshteinDistance("aaapppp", "", 8)       = 7
-     * StringUtils.getLevenshteinDistance("aaapppp", "", 7)       = 7
-     * StringUtils.getLevenshteinDistance("aaapppp", "", 6))      = -1
-     * StringUtils.getLevenshteinDistance("elephant", "hippo", 7) = 7
-     * StringUtils.getLevenshteinDistance("elephant", "hippo", 6) = -1
-     * StringUtils.getLevenshteinDistance("hippo", "elephant", 7) = 7
-     * StringUtils.getLevenshteinDistance("hippo", "elephant", 6) = -1
-     * 
- * - * @param s the first String, must not be null - * @param t the second String, must not be null - * @param threshold the target threshold, must not be negative - * @return result distance, or {@code -1} if the distance would be greater than the threshold - * @throws IllegalArgumentException if either String input {@code null} or negative threshold - */ - public static int getLevenshteinDistance(CharSequence s, CharSequence t, final int threshold) { - if (s == null || t == null) { - throw new IllegalArgumentException("Strings must not be null"); - } - if (threshold < 0) { - throw new IllegalArgumentException("Threshold must not be negative"); - } - - /* - This implementation only computes the distance if it's less than or equal to the - threshold value, returning -1 if it's greater. The advantage is performance: unbounded - distance is O(nm), but a bound of k allows us to reduce it to O(km) time by only - computing a diagonal stripe of width 2k + 1 of the cost table. - It is also possible to use this to compute the unbounded Levenshtein distance by starting - the threshold at 1 and doubling each time until the distance is found; this is O(dm), where - d is the distance. - - One subtlety comes from needing to ignore entries on the border of our stripe - eg. - p[] = |#|#|#|* - d[] = *|#|#|#| - We must ignore the entry to the left of the leftmost member - We must ignore the entry above the rightmost member - - Another subtlety comes from our stripe running off the matrix if the strings aren't - of the same size. Since string s is always swapped to be the shorter of the two, - the stripe will always run off to the upper right instead of the lower left of the matrix. - - As a concrete example, suppose s is of length 5, t is of length 7, and our threshold is 1. - In this case we're going to walk a stripe of length 3. The matrix would look like so: - - 1 2 3 4 5 - 1 |#|#| | | | - 2 |#|#|#| | | - 3 | |#|#|#| | - 4 | | |#|#|#| - 5 | | | |#|#| - 6 | | | | |#| - 7 | | | | | | - - Note how the stripe leads off the table as there is no possible way to turn a string of length 5 - into one of length 7 in edit distance of 1. - - Additionally, this implementation decreases memory usage by using two - single-dimensional arrays and swapping them back and forth instead of allocating - an entire n by m matrix. This requires a few minor changes, such as immediately returning - when it's detected that the stripe has run off the matrix and initially filling the arrays with - large values so that entries we don't compute are ignored. - - See Algorithms on Strings, Trees and Sequences by Dan Gusfield for some discussion. - */ - - int n = s.length(); // length of s - int m = t.length(); // length of t - - // if one string is empty, the edit distance is necessarily the length of the other - if (n == 0) { - return m <= threshold ? m : -1; - } else if (m == 0) { - return n <= threshold ? n : -1; - } - - if (n > m) { - // swap the two strings to consume less memory - final CharSequence tmp = s; - s = t; - t = tmp; - n = m; - m = t.length(); - } - - int p[] = new int[n + 1]; // 'previous' cost array, horizontally - int d[] = new int[n + 1]; // cost array, horizontally - int _d[]; // placeholder to assist in swapping p and d - - // fill in starting table values - final int boundary = Math.min(n, threshold) + 1; - for (int i = 0; i < boundary; i++) { - p[i] = i; - } - // these fills ensure that the value above the rightmost entry of our - // stripe will be ignored in following loop iterations - Arrays.fill(p, boundary, p.length, Integer.MAX_VALUE); - Arrays.fill(d, Integer.MAX_VALUE); - - // iterates through t - for (int j = 1; j <= m; j++) { - final char t_j = t.charAt(j - 1); // jth character of t - d[0] = j; - - // compute stripe indices, constrain to array size - final int min = Math.max(1, j - threshold); - final int max = j > Integer.MAX_VALUE - threshold ? n : Math.min(n, j + threshold); - - // the stripe may lead off of the table if s and t are of different sizes - if (min > max) { - return -1; - } - - // ignore entry left of leftmost - if (min > 1) { - d[min - 1] = Integer.MAX_VALUE; - } - - // iterates through [min, max] in s - for (int i = min; i <= max; i++) { - if (s.charAt(i - 1) == t_j) { - // diagonally left and up - d[i] = p[i - 1]; - } else { - // 1 + minimum of cell to the left, to the top, diagonally left and up - d[i] = 1 + Math.min(Math.min(d[i - 1], p[i]), p[i - 1]); - } - } - - // copy current distance counts to 'previous row' distance counts - _d = p; - p = d; - d = _d; - } - - // if p[n] is greater than the threshold, there's no guarantee on it being the correct - // distance - if (p[n] <= threshold) { - return p[n]; - } - return -1; - } - - /** - *

Find the Jaro Winkler Distance which indicates the similarity score between two Strings.

- * - *

The Jaro measure is the weighted sum of percentage of matched characters from each file and transposed characters. - * Winkler increased this measure for matching initial characters.

- * - *

This implementation is based on the Jaro Winkler similarity algorithm - * from http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance.

- * - *
-     * StringUtils.getJaroWinklerDistance(null, null)          = IllegalArgumentException
-     * StringUtils.getJaroWinklerDistance("","")               = 0.0
-     * StringUtils.getJaroWinklerDistance("","a")              = 0.0
-     * StringUtils.getJaroWinklerDistance("aaapppp", "")       = 0.0
-     * StringUtils.getJaroWinklerDistance("frog", "fog")       = 0.93
-     * StringUtils.getJaroWinklerDistance("fly", "ant")        = 0.0
-     * StringUtils.getJaroWinklerDistance("elephant", "hippo") = 0.44
-     * StringUtils.getJaroWinklerDistance("hippo", "elephant") = 0.44
-     * StringUtils.getJaroWinklerDistance("hippo", "zzzzzzzz") = 0.0
-     * StringUtils.getJaroWinklerDistance("hello", "hallo")    = 0.88
-     * StringUtils.getJaroWinklerDistance("ABC Corporation", "ABC Corp") = 0.91
-     * StringUtils.getJaroWinklerDistance("D N H Enterprises Inc", "D & H Enterprises, Inc.") = 0.93
-     * StringUtils.getJaroWinklerDistance("My Gym Children's Fitness Center", "My Gym. Childrens Fitness") = 0.94
-     * StringUtils.getJaroWinklerDistance("PENNSYLVANIA", "PENNCISYLVNIA")    = 0.9
-     * 
- * - * @param first the first String, must not be null - * @param second the second String, must not be null - * @return result distance - * @throws IllegalArgumentException if either String input {@code null} - * @since 3.3 - */ - public static double getJaroWinklerDistance(final CharSequence first, final CharSequence second) { - final double DEFAULT_SCALING_FACTOR = 0.1; - - if (first == null || second == null) { - throw new IllegalArgumentException("Strings must not be null"); - } - - final double jaro = score(first,second); - final int cl = commonPrefixLength(first, second); - final double matchScore = Math.round((jaro + (DEFAULT_SCALING_FACTOR * cl * (1.0 - jaro))) *100.0)/100.0; - - return matchScore; - } - - /** - * This method returns the Jaro-Winkler score for string matching. - * @param first the first string to be matched - * @param second the second string to be machted - * @return matching score without scaling factor impact - */ - private static double score(final CharSequence first, final CharSequence second) { - String shorter; - String longer; - - // Determine which String is longer. - if (first.length() > second.length()) { - longer = first.toString().toLowerCase(); - shorter = second.toString().toLowerCase(); - } else { - longer = second.toString().toLowerCase(); - shorter = first.toString().toLowerCase(); - } - - // Calculate the half length() distance of the shorter String. - final int halflength = shorter.length() / 2 + 1; - - // Find the set of matching characters between the shorter and longer strings. Note that - // the set of matching characters may be different depending on the order of the strings. - final String m1 = getSetOfMatchingCharacterWithin(shorter, longer, halflength); - final String m2 = getSetOfMatchingCharacterWithin(longer, shorter, halflength); - - // If one or both of the sets of common characters is empty, then - // there is no similarity between the two strings. - if (m1.length() == 0 || m2.length() == 0) { - return 0.0; - } - - // If the set of common characters is not the same size, then - // there is no similarity between the two strings, either. - if (m1.length() != m2.length()) { - return 0.0; - } - - // Calculate the number of transposition between the two sets - // of common characters. - final int transpositions = transpositions(m1, m2); - - // Calculate the distance. - final double dist = - (m1.length() / ((double)shorter.length()) + - m2.length() / ((double)longer.length()) + - (m1.length() - transpositions) / ((double)m1.length())) / 3.0; - return dist; - } - - /** - *

Find the Fuzzy Distance which indicates the similarity score between two Strings.

- * - *

This string matching algorithm is similar to the algorithms of editors such as Sublime Text, - * TextMate, Atom and others. One point is given for every matched character. Subsequent - * matches yield two bonus points. A higher score indicates a higher similarity.

- * - *
-     * StringUtils.getFuzzyDistance(null, null, null)                                    = IllegalArgumentException
-     * StringUtils.getFuzzyDistance("", "", Locale.ENGLISH)                              = 0
-     * StringUtils.getFuzzyDistance("Workshop", "b", Locale.ENGLISH)                     = 0
-     * StringUtils.getFuzzyDistance("Room", "o", Locale.ENGLISH)                         = 1
-     * StringUtils.getFuzzyDistance("Workshop", "w", Locale.ENGLISH)                     = 1
-     * StringUtils.getFuzzyDistance("Workshop", "ws", Locale.ENGLISH)                    = 2
-     * StringUtils.getFuzzyDistance("Workshop", "wo", Locale.ENGLISH)                    = 4
-     * StringUtils.getFuzzyDistance("Apache Software Foundation", "asf", Locale.ENGLISH) = 3
-     * 
- * - * @param term a full term that should be matched against, must not be null - * @param query the query that will be matched against a term, must not be null - * @param locale This string matching logic is case insensitive. A locale is necessary to normalize - * both Strings to lower case. - * @return result score - * @throws IllegalArgumentException if either String input {@code null} or Locale input {@code null} - * @since 3.4 - */ - public static int getFuzzyDistance(final CharSequence term, final CharSequence query, final Locale locale) { - if (term == null || query == null) { - throw new IllegalArgumentException("Strings must not be null"); - } else if (locale == null) { - throw new IllegalArgumentException("Locale must not be null"); - } - - // fuzzy logic is case insensitive. We normalize the Strings to lower - // case right from the start. Turning characters to lower case - // via Character.toLowerCase(char) is unfortunately insufficient - // as it does not accept a locale. - final String termLowerCase = term.toString().toLowerCase(locale); - final String queryLowerCase = query.toString().toLowerCase(locale); - - // the resulting score - int score = 0; - - // the position in the term which will be scanned next for potential - // query character matches - int termIndex = 0; - - // index of the previously matched character in the term - int previousMatchingCharacterIndex = Integer.MIN_VALUE; - - for (int queryIndex = 0; queryIndex < queryLowerCase.length(); queryIndex++) { - final char queryChar = queryLowerCase.charAt(queryIndex); - - boolean termCharacterMatchFound = false; - for (; termIndex < termLowerCase.length() && !termCharacterMatchFound; termIndex++) { - final char termChar = termLowerCase.charAt(termIndex); - - if (queryChar == termChar) { - // simple character matches result in one point - score++; - - // subsequent character matches further improve - // the score. - if (previousMatchingCharacterIndex + 1 == termIndex) { - score += 2; - } - - previousMatchingCharacterIndex = termIndex; - - // we can leave the nested loop. Every character in the - // query can match at most one character in the term. - termCharacterMatchFound = true; - } - } - } - - return score; - } - - /** - * Gets a set of matching characters between two strings. - * - *

- * - * @param first The first string. - * @param second The second string. - * @param limit The maximum distance to consider. - * @return A string contain the set of common characters. - */ - private static String getSetOfMatchingCharacterWithin(final CharSequence first, final CharSequence second, final int limit) { - final StringBuilder common = new StringBuilder(); - final StringBuilder copy = new StringBuilder(second); - - for (int i = 0; i < first.length(); i++) { - final char ch = first.charAt(i); - boolean found = false; - - // See if the character is within the limit positions away from the original position of that character. - for (int j = Math.max(0, i - limit); !found && j < Math.min(i + limit, second.length()); j++) { - if (copy.charAt(j) == ch) { - found = true; - common.append(ch); - copy.setCharAt(j,'*'); - } - } - } - return common.toString(); - } - - /** - * Calculates the number of transposition between two strings. - * @param first The first string. - * @param second The second string. - * @return The number of transposition between the two strings. - */ - private static int transpositions(final CharSequence first, final CharSequence second) { - int transpositions = 0; - for (int i = 0; i < first.length(); i++) { - if (first.charAt(i) != second.charAt(i)) { - transpositions++; - } - } - return transpositions / 2; - } - - /** - * Calculates the number of characters from the beginning of the strings that match exactly one-to-one, - * up to a maximum of four (4) characters. - * @param first The first string. - * @param second The second string. - * @return A number between 0 and 4. - */ - private static int commonPrefixLength(final CharSequence first, final CharSequence second) { - final int result = getCommonPrefix(first.toString(), second.toString()).length(); - - // Limit the result to 4. - return result > 4 ? 4 : result; - } - - // startsWith - //----------------------------------------------------------------------- - - /** - *

Check if a CharSequence starts with a specified prefix.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case sensitive.

- * - *
-     * StringUtils.startsWith(null, null)      = true
-     * StringUtils.startsWith(null, "abc")     = false
-     * StringUtils.startsWith("abcdef", null)  = false
-     * StringUtils.startsWith("abcdef", "abc") = true
-     * StringUtils.startsWith("ABCDEF", "abc") = false
-     * 
- * - * @see java.lang.String#startsWith(String) - * @param str the CharSequence to check, may be null - * @param prefix the prefix to find, may be null - * @return {@code true} if the CharSequence starts with the prefix, case sensitive, or - * both {@code null} - * @since 2.4 - * @since 3.0 Changed signature from startsWith(String, String) to startsWith(CharSequence, CharSequence) - */ - public static boolean startsWith(final CharSequence str, final CharSequence prefix) { - return startsWith(str, prefix, false); - } - - /** - *

Case insensitive check if a CharSequence starts with a specified prefix.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case insensitive.

- * - *
-     * StringUtils.startsWithIgnoreCase(null, null)      = true
-     * StringUtils.startsWithIgnoreCase(null, "abc")     = false
-     * StringUtils.startsWithIgnoreCase("abcdef", null)  = false
-     * StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
-     * StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
-     * 
- * - * @see java.lang.String#startsWith(String) - * @param str the CharSequence to check, may be null - * @param prefix the prefix to find, may be null - * @return {@code true} if the CharSequence starts with the prefix, case insensitive, or - * both {@code null} - * @since 2.4 - * @since 3.0 Changed signature from startsWithIgnoreCase(String, String) to startsWithIgnoreCase(CharSequence, CharSequence) - */ - public static boolean startsWithIgnoreCase(final CharSequence str, final CharSequence prefix) { - return startsWith(str, prefix, true); - } - - /** - *

Check if a CharSequence starts with a specified prefix (optionally case insensitive).

- * - * @see java.lang.String#startsWith(String) - * @param str the CharSequence to check, may be null - * @param prefix the prefix to find, may be null - * @param ignoreCase indicates whether the compare should ignore case - * (case insensitive) or not. - * @return {@code true} if the CharSequence starts with the prefix or - * both {@code null} - */ - private static boolean startsWith(final CharSequence str, final CharSequence prefix, final boolean ignoreCase) { - if (str == null || prefix == null) { - return str == null && prefix == null; - } - if (prefix.length() > str.length()) { - return false; - } - return CharSequenceUtils.regionMatches(str, ignoreCase, 0, prefix, 0, prefix.length()); - } - - /** - *

Check if a CharSequence starts with any of an array of specified strings.

- * - *
-     * StringUtils.startsWithAny(null, null)      = false
-     * StringUtils.startsWithAny(null, new String[] {"abc"})  = false
-     * StringUtils.startsWithAny("abcxyz", null)     = false
-     * StringUtils.startsWithAny("abcxyz", new String[] {""}) = false
-     * StringUtils.startsWithAny("abcxyz", new String[] {"abc"}) = true
-     * StringUtils.startsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
-     * 
- * - * @param string the CharSequence to check, may be null - * @param searchStrings the CharSequences to find, may be null or empty - * @return {@code true} if the CharSequence starts with any of the the prefixes, case insensitive, or - * both {@code null} - * @since 2.5 - * @since 3.0 Changed signature from startsWithAny(String, String[]) to startsWithAny(CharSequence, CharSequence...) - */ - public static boolean startsWithAny(final CharSequence string, final CharSequence... searchStrings) { - if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) { - return false; - } - for (final CharSequence searchString : searchStrings) { - if (startsWith(string, searchString)) { - return true; - } - } - return false; - } - - // endsWith - //----------------------------------------------------------------------- - - /** - *

Check if a CharSequence ends with a specified suffix.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case sensitive.

- * - *
-     * StringUtils.endsWith(null, null)      = true
-     * StringUtils.endsWith(null, "def")     = false
-     * StringUtils.endsWith("abcdef", null)  = false
-     * StringUtils.endsWith("abcdef", "def") = true
-     * StringUtils.endsWith("ABCDEF", "def") = false
-     * StringUtils.endsWith("ABCDEF", "cde") = false
-     * 
- * - * @see java.lang.String#endsWith(String) - * @param str the CharSequence to check, may be null - * @param suffix the suffix to find, may be null - * @return {@code true} if the CharSequence ends with the suffix, case sensitive, or - * both {@code null} - * @since 2.4 - * @since 3.0 Changed signature from endsWith(String, String) to endsWith(CharSequence, CharSequence) - */ - public static boolean endsWith(final CharSequence str, final CharSequence suffix) { - return endsWith(str, suffix, false); - } - - /** - *

Case insensitive check if a CharSequence ends with a specified suffix.

- * - *

{@code null}s are handled without exceptions. Two {@code null} - * references are considered to be equal. The comparison is case insensitive.

- * - *
-     * StringUtils.endsWithIgnoreCase(null, null)      = true
-     * StringUtils.endsWithIgnoreCase(null, "def")     = false
-     * StringUtils.endsWithIgnoreCase("abcdef", null)  = false
-     * StringUtils.endsWithIgnoreCase("abcdef", "def") = true
-     * StringUtils.endsWithIgnoreCase("ABCDEF", "def") = true
-     * StringUtils.endsWithIgnoreCase("ABCDEF", "cde") = false
-     * 
- * - * @see java.lang.String#endsWith(String) - * @param str the CharSequence to check, may be null - * @param suffix the suffix to find, may be null - * @return {@code true} if the CharSequence ends with the suffix, case insensitive, or - * both {@code null} - * @since 2.4 - * @since 3.0 Changed signature from endsWithIgnoreCase(String, String) to endsWithIgnoreCase(CharSequence, CharSequence) - */ - public static boolean endsWithIgnoreCase(final CharSequence str, final CharSequence suffix) { - return endsWith(str, suffix, true); - } - - /** - *

Check if a CharSequence ends with a specified suffix (optionally case insensitive).

- * - * @see java.lang.String#endsWith(String) - * @param str the CharSequence to check, may be null - * @param suffix the suffix to find, may be null - * @param ignoreCase indicates whether the compare should ignore case - * (case insensitive) or not. - * @return {@code true} if the CharSequence starts with the prefix or - * both {@code null} - */ - private static boolean endsWith(final CharSequence str, final CharSequence suffix, final boolean ignoreCase) { - if (str == null || suffix == null) { - return str == null && suffix == null; - } - if (suffix.length() > str.length()) { - return false; - } - final int strOffset = str.length() - suffix.length(); - return CharSequenceUtils.regionMatches(str, ignoreCase, strOffset, suffix, 0, suffix.length()); - } - - /** - *

- * Similar to http://www.w3.org/TR/xpath/#function-normalize - * -space - *

- *

- * The function returns the argument string with whitespace normalized by using - * {@link #trim(String)} to remove leading and trailing whitespace - * and then replacing sequences of whitespace characters by a single space. - *

- * In XML Whitespace characters are the same as those allowed by the S production, which is S ::= (#x20 | #x9 | #xD | #xA)+ - *

- * Java's regexp pattern \s defines whitespace as [ \t\n\x0B\f\r] - * - *

For reference:

- *
    - *
  • \x0B = vertical tab
  • - *
  • \f = #xC = form feed
  • - *
  • #x20 = space
  • - *
  • #x9 = \t
  • - *
  • #xA = \n
  • - *
  • #xD = \r
  • - *
- * - *

- * The difference is that Java's whitespace includes vertical tab and form feed, which this functional will also - * normalize. Additionally {@link #trim(String)} removes control characters (char <= 32) from both - * ends of this String. - *

- * - * @see Pattern - * @see #trim(String) - * @see http://www.w3.org/TR/xpath/#function-normalize-space - * @param str the source String to normalize whitespaces from, may be null - * @return the modified string with whitespace normalized, {@code null} if null String input - * - * @since 3.0 - */ - public static String normalizeSpace(final String str) { - // LANG-1020: Improved performance significantly by normalizing manually instead of using regex - // See https://github.com/librucha/commons-lang-normalizespaces-benchmark for performance test - if (isEmpty(str)) { - return str; - } - final int size = str.length(); - final char[] newChars = new char[size]; - int count = 0; - int whitespacesCount = 0; - boolean startWhitespaces = true; - for (int i = 0; i < size; i++) { - char actualChar = str.charAt(i); - boolean isWhitespace = Character.isWhitespace(actualChar); - if (!isWhitespace) { - startWhitespaces = false; - newChars[count++] = (actualChar == 160 ? 32 : actualChar); - whitespacesCount = 0; - } else { - if (whitespacesCount == 0 && !startWhitespaces) { - newChars[count++] = SPACE.charAt(0); - } - whitespacesCount++; - } - } - if (startWhitespaces) { - return EMPTY; - } - return new String(newChars, 0, count - (whitespacesCount > 0 ? 1 : 0)); - } - - /** - *

Check if a CharSequence ends with any of an array of specified strings.

- * - *
-     * StringUtils.endsWithAny(null, null)      = false
-     * StringUtils.endsWithAny(null, new String[] {"abc"})  = false
-     * StringUtils.endsWithAny("abcxyz", null)     = false
-     * StringUtils.endsWithAny("abcxyz", new String[] {""}) = true
-     * StringUtils.endsWithAny("abcxyz", new String[] {"xyz"}) = true
-     * StringUtils.endsWithAny("abcxyz", new String[] {null, "xyz", "abc"}) = true
-     * 
- * - * @param string the CharSequence to check, may be null - * @param searchStrings the CharSequences to find, may be null or empty - * @return {@code true} if the CharSequence ends with any of the the prefixes, case insensitive, or - * both {@code null} - * @since 3.0 - */ - public static boolean endsWithAny(final CharSequence string, final CharSequence... searchStrings) { - if (isEmpty(string) || ArrayUtils.isEmpty(searchStrings)) { - return false; - } - for (final CharSequence searchString : searchStrings) { - if (endsWith(string, searchString)) { - return true; - } - } - return false; - } - - /** - * Appends the suffix to the end of the string if the string does not - * already end in the suffix. - * - * @param str The string. - * @param suffix The suffix to append to the end of the string. - * @param ignoreCase Indicates whether the compare should ignore case. - * @param suffixes Additional suffixes that are valid terminators (optional). - * - * @return A new String if suffix was appened, the same string otherwise. - */ - private static String appendIfMissing(final String str, final CharSequence suffix, final boolean ignoreCase, final CharSequence... suffixes) { - if (str == null || isEmpty(suffix) || endsWith(str, suffix, ignoreCase)) { - return str; - } - if (suffixes != null && suffixes.length > 0) { - for (final CharSequence s : suffixes) { - if (endsWith(str, s, ignoreCase)) { - return str; - } - } - } - return str + suffix.toString(); - } - - /** - * Appends the suffix to the end of the string if the string does not - * already end with any the suffixes. - * - *
-     * StringUtils.appendIfMissing(null, null) = null
-     * StringUtils.appendIfMissing("abc", null) = "abc"
-     * StringUtils.appendIfMissing("", "xyz") = "xyz"
-     * StringUtils.appendIfMissing("abc", "xyz") = "abcxyz"
-     * StringUtils.appendIfMissing("abcxyz", "xyz") = "abcxyz"
-     * StringUtils.appendIfMissing("abcXYZ", "xyz") = "abcXYZxyz"
-     * 
- *

With additional suffixes,

- *
-     * StringUtils.appendIfMissing(null, null, null) = null
-     * StringUtils.appendIfMissing("abc", null, null) = "abc"
-     * StringUtils.appendIfMissing("", "xyz", null) = "xyz"
-     * StringUtils.appendIfMissing("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
-     * StringUtils.appendIfMissing("abc", "xyz", "") = "abc"
-     * StringUtils.appendIfMissing("abc", "xyz", "mno") = "abcxyz"
-     * StringUtils.appendIfMissing("abcxyz", "xyz", "mno") = "abcxyz"
-     * StringUtils.appendIfMissing("abcmno", "xyz", "mno") = "abcmno"
-     * StringUtils.appendIfMissing("abcXYZ", "xyz", "mno") = "abcXYZxyz"
-     * StringUtils.appendIfMissing("abcMNO", "xyz", "mno") = "abcMNOxyz"
-     * 
- * - * @param str The string. - * @param suffix The suffix to append to the end of the string. - * @param suffixes Additional suffixes that are valid terminators. - * - * @return A new String if suffix was appened, the same string otherwise. - * - * @since 3.2 - */ - public static String appendIfMissing(final String str, final CharSequence suffix, final CharSequence... suffixes) { - return appendIfMissing(str, suffix, false, suffixes); - } - - /** - * Appends the suffix to the end of the string if the string does not - * already end, case insensitive, with any of the suffixes. - * - *
-     * StringUtils.appendIfMissingIgnoreCase(null, null) = null
-     * StringUtils.appendIfMissingIgnoreCase("abc", null) = "abc"
-     * StringUtils.appendIfMissingIgnoreCase("", "xyz") = "xyz"
-     * StringUtils.appendIfMissingIgnoreCase("abc", "xyz") = "abcxyz"
-     * StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz") = "abcxyz"
-     * StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz") = "abcXYZ"
-     * 
- *

With additional suffixes,

- *
-     * StringUtils.appendIfMissingIgnoreCase(null, null, null) = null
-     * StringUtils.appendIfMissingIgnoreCase("abc", null, null) = "abc"
-     * StringUtils.appendIfMissingIgnoreCase("", "xyz", null) = "xyz"
-     * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "abcxyz"
-     * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "") = "abc"
-     * StringUtils.appendIfMissingIgnoreCase("abc", "xyz", "mno") = "axyz"
-     * StringUtils.appendIfMissingIgnoreCase("abcxyz", "xyz", "mno") = "abcxyz"
-     * StringUtils.appendIfMissingIgnoreCase("abcmno", "xyz", "mno") = "abcmno"
-     * StringUtils.appendIfMissingIgnoreCase("abcXYZ", "xyz", "mno") = "abcXYZ"
-     * StringUtils.appendIfMissingIgnoreCase("abcMNO", "xyz", "mno") = "abcMNO"
-     * 
- * - * @param str The string. - * @param suffix The suffix to append to the end of the string. - * @param suffixes Additional suffixes that are valid terminators. - * - * @return A new String if suffix was appened, the same string otherwise. - * - * @since 3.2 - */ - public static String appendIfMissingIgnoreCase(final String str, final CharSequence suffix, final CharSequence... suffixes) { - return appendIfMissing(str, suffix, true, suffixes); - } - - /** - * Prepends the prefix to the start of the string if the string does not - * already start with any of the prefixes. - * - * @param str The string. - * @param prefix The prefix to prepend to the start of the string. - * @param ignoreCase Indicates whether the compare should ignore case. - * @param prefixes Additional prefixes that are valid (optional). - * - * @return A new String if prefix was prepended, the same string otherwise. - */ - private static String prependIfMissing(final String str, final CharSequence prefix, final boolean ignoreCase, final CharSequence... prefixes) { - if (str == null || isEmpty(prefix) || startsWith(str, prefix, ignoreCase)) { - return str; - } - if (prefixes != null && prefixes.length > 0) { - for (final CharSequence p : prefixes) { - if (startsWith(str, p, ignoreCase)) { - return str; - } - } - } - return prefix.toString() + str; - } - - /** - * Prepends the prefix to the start of the string if the string does not - * already start with any of the prefixes. - * - *
-     * StringUtils.prependIfMissing(null, null) = null
-     * StringUtils.prependIfMissing("abc", null) = "abc"
-     * StringUtils.prependIfMissing("", "xyz") = "xyz"
-     * StringUtils.prependIfMissing("abc", "xyz") = "xyzabc"
-     * StringUtils.prependIfMissing("xyzabc", "xyz") = "xyzabc"
-     * StringUtils.prependIfMissing("XYZabc", "xyz") = "xyzXYZabc"
-     * 
- *

With additional prefixes,

- *
-     * StringUtils.prependIfMissing(null, null, null) = null
-     * StringUtils.prependIfMissing("abc", null, null) = "abc"
-     * StringUtils.prependIfMissing("", "xyz", null) = "xyz"
-     * StringUtils.prependIfMissing("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
-     * StringUtils.prependIfMissing("abc", "xyz", "") = "abc"
-     * StringUtils.prependIfMissing("abc", "xyz", "mno") = "xyzabc"
-     * StringUtils.prependIfMissing("xyzabc", "xyz", "mno") = "xyzabc"
-     * StringUtils.prependIfMissing("mnoabc", "xyz", "mno") = "mnoabc"
-     * StringUtils.prependIfMissing("XYZabc", "xyz", "mno") = "xyzXYZabc"
-     * StringUtils.prependIfMissing("MNOabc", "xyz", "mno") = "xyzMNOabc"
-     * 
- * - * @param str The string. - * @param prefix The prefix to prepend to the start of the string. - * @param prefixes Additional prefixes that are valid. - * - * @return A new String if prefix was prepended, the same string otherwise. - * - * @since 3.2 - */ - public static String prependIfMissing(final String str, final CharSequence prefix, final CharSequence... prefixes) { - return prependIfMissing(str, prefix, false, prefixes); - } - - /** - * Prepends the prefix to the start of the string if the string does not - * already start, case insensitive, with any of the prefixes. - * - *
-     * StringUtils.prependIfMissingIgnoreCase(null, null) = null
-     * StringUtils.prependIfMissingIgnoreCase("abc", null) = "abc"
-     * StringUtils.prependIfMissingIgnoreCase("", "xyz") = "xyz"
-     * StringUtils.prependIfMissingIgnoreCase("abc", "xyz") = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz") = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz") = "XYZabc"
-     * 
- *

With additional prefixes,

- *
-     * StringUtils.prependIfMissingIgnoreCase(null, null, null) = null
-     * StringUtils.prependIfMissingIgnoreCase("abc", null, null) = "abc"
-     * StringUtils.prependIfMissingIgnoreCase("", "xyz", null) = "xyz"
-     * StringUtils.prependIfMissingIgnoreCase("abc", "xyz", new CharSequence[]{null}) = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "") = "abc"
-     * StringUtils.prependIfMissingIgnoreCase("abc", "xyz", "mno") = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("xyzabc", "xyz", "mno") = "xyzabc"
-     * StringUtils.prependIfMissingIgnoreCase("mnoabc", "xyz", "mno") = "mnoabc"
-     * StringUtils.prependIfMissingIgnoreCase("XYZabc", "xyz", "mno") = "XYZabc"
-     * StringUtils.prependIfMissingIgnoreCase("MNOabc", "xyz", "mno") = "MNOabc"
-     * 
- * - * @param str The string. - * @param prefix The prefix to prepend to the start of the string. - * @param prefixes Additional prefixes that are valid (optional). - * - * @return A new String if prefix was prepended, the same string otherwise. - * - * @since 3.2 - */ - public static String prependIfMissingIgnoreCase(final String str, final CharSequence prefix, final CharSequence... prefixes) { - return prependIfMissing(str, prefix, true, prefixes); - } - - /** - * Converts a byte[] to a String using the specified character encoding. - * - * @param bytes - * the byte array to read from - * @param charsetName - * the encoding to use, if null then use the platform default - * @return a new String - * @throws UnsupportedEncodingException - * If the named charset is not supported - * @throws NullPointerException - * if the input is null - * @deprecated use {@link StringUtils#toEncodedString(byte[], Charset)} instead of String constants in your code - * @since 3.1 - */ - @Deprecated - public static String toString(final byte[] bytes, final String charsetName) throws UnsupportedEncodingException { - return charsetName != null ? new String(bytes, charsetName) : new String(bytes, Charset.defaultCharset()); - } - - /** - * Converts a byte[] to a String using the specified character encoding. - * - * @param bytes - * the byte array to read from - * @param charset - * the encoding to use, if null then use the platform default - * @return a new String - * @throws NullPointerException - * if {@code bytes} is null - * @since 3.2 - * @since 3.3 No longer throws {@link UnsupportedEncodingException}. - */ - public static String toEncodedString(final byte[] bytes, final Charset charset) { - return new String(bytes, charset != null ? charset : Charset.defaultCharset()); - } - - /** - *

- * Wraps a string with a char. - *

- * - *
-     * StringUtils.wrap(null, *)        = null
-     * StringUtils.wrap("", *)          = ""
-     * StringUtils.wrap("ab", '\0')     = "ab"
-     * StringUtils.wrap("ab", 'x')      = "xabx"
-     * StringUtils.wrap("ab", '\'')     = "'ab'"
-     * StringUtils.wrap("\"ab\"", '\"') = "\"\"ab\"\""
-     * 
- * - * @param str - * the string to be wrapped, may be {@code null} - * @param wrapWith - * the char that will wrap {@code str} - * @return the wrapped string, or {@code null} if {@code str==null} - * @since 3.4 - */ - public static String wrap(final String str, final char wrapWith) { - - if (isEmpty(str) || wrapWith == '\0') { - return str; - } - - return wrapWith + str + wrapWith; - } - - /** - *

- * Wraps a String with another String. - *

- * - *

- * A {@code null} input String returns {@code null}. - *

- * - *
-     * StringUtils.wrap(null, *)         = null
-     * StringUtils.wrap("", *)           = ""
-     * StringUtils.wrap("ab", null)      = "ab"
-     * StringUtils.wrap("ab", "x")       = "xabx"
-     * StringUtils.wrap("ab", "\"")      = "\"ab\""
-     * StringUtils.wrap("\"ab\"", "\"")  = "\"\"ab\"\""
-     * StringUtils.wrap("ab", "'")       = "'ab'"
-     * StringUtils.wrap("'abcd'", "'")   = "''abcd''"
-     * StringUtils.wrap("\"abcd\"", "'") = "'\"abcd\"'"
-     * StringUtils.wrap("'abcd'", "\"")  = "\"'abcd'\""
-     * 
- * - * @param str - * the String to be wrapper, may be null - * @param wrapWith - * the String that will wrap str - * @return wrapped String, {@code null} if null String input - * @since 3.4 - */ - public static String wrap(final String str, final String wrapWith) { - - if (isEmpty(str) || isEmpty(wrapWith)) { - return str; - } - - return wrapWith.concat(str).concat(wrapWith); - } -} diff --git a/All/Genesis-OOB/Genesis#33/old/changes.xml b/All/Genesis-OOB/Genesis#33/old/changes.xml deleted file mode 100755 index fa53e12..0000000 --- a/All/Genesis-OOB/Genesis#33/old/changes.xml +++ /dev/null @@ -1,813 +0,0 @@ - - - - - Apache Commons Lang Changes - - - - - Replace StringBuilder with String concatenation for better optimization - Deprecate SystemUtils.FILE_SEPARATOR and SystemUtils.PATH_SEPARATOR - FastDateFormat APIs that use a StringBuilder - Ability to throw checked exceptions without declaring them - Several predefined ISO FastDateFormats in DateFormatUtils are incorrect - StringIndexOutOfBoundsException or field over-write for large year fields in FastDateParser - Implement ParsePosition api for FastDateParser - StrLookup.systemPropertiesLookup() no longer reacts on changes on system properties - EnumUtils *BitVector issue with more than 32 values Enum - Capitalize javadoc is incorrect - Add check for duplicate event listener in EventListenerSupport - FastDateParser_TimeZoneStrategyTest#testTimeZoneStrategyPattern fails on Windows with German Locale - Add method containsAllWords to WordUtils - ReflectionToStringBuilder doesn't throw IllegalArgumentException when the constructor's object param is null - Inconsistent behavior of swap for malformed inputs - StringUtils join with var args - Fix critical issues reported by SonarQube - StrBuilder.equals(StrBuilder) doesn't check for null inputs - Add ThreadUtils - A utility class which provides helper methods related to java.lang.Thread - Add annotations to exclude fields from ReflectionEqualsBuilder, ReflectionToStringBuilder and ReflectionHashCodeBuilder - Use JUnit rules to set and reset the default Locale and TimeZone - JsonToStringStyle doesn't handle chars and objects correctly - HashCodeBuilder throws StackOverflowError in bidirectional navigable association - DateFormatUtilsTest.testSMTP depends on the default Locale - Unit test FastDatePrinterTimeZonesTest needs a timezone set - CLONE - DateFormatUtils.format does not correctly change Calendar TimeZone in certain situations - DateUtilsTest.testLang530 fails for some timezones - TypeUtils.ParameterizedType#equals doesn't work with wildcard types - Add rotate(string, int) method to StringUtils - StringUtils.repeat('z', -1) throws NegativeArraySizeException - Add swap and shift operations for arrays to ArrayUtils - TypeUtils.parameterizeWithOwner - wrong format descriptor for "invalid number of type parameters". - MultilineRecursiveToStringStyle largely unusable due to being package-private. - StringUtils.uncapitalize performance improvement - CharSet.getInstance documentation does not clearly explain how to include negation character in set - Change nullToEmpty methods to generics - Fix FindBugs warnings in DurationFormatUtils - Add a method to ArrayUtils for removing all occurrences of a given element - Fix parsing edge cases in FastDateParser - - - - Support OS X versions in SystemUtils - SystemUtils.IS_OS_WINDOWS_2008, VISTA are incorrect - Parse test fails for TimeZone America/Sao_Paulo - Add SystemUtils.IS_JAVA_1_9 - Make logic for comparing OS versions in SystemUtils smarter - Shutdown thread pools in test cases - FastDateParser and FastDatePrinter support 'X' format - Avoid memory allocation when using date formating to StringBuffer - Possible performance improvement on string escape functions - Exception while using ExtendedMessageFormat and escaping braces - Avoid String allocation in StrBuilder.append(CharSequence) - Update maven-checkstyle-plugin to 2.14 - Update org.easymock:easymock to 3.3.1 - Update maven-pmd-plugin to 3.4 - Update maven-antrun-plugin to 1.8 - Wrong formating of time zones with daylight saving time in FastDatePrinter - Performance improvements for StringEscapeUtils - Add ClassUtils.getAbbreviatedName() - FastDateParser does not set error indication in ParsePosition - FastDateParser does not handle excess hours as per SimpleDateFormat - FastDateParser error - timezones not handled correctly - NumberUtils#createNumber() returns positive BigDecimal when negative Float is expected - DiffBuilder.append(String, Object left, Object right) does not do a left.equals(right) check - StrSubstitutor.replaceSystemProperties does not work consistently - Add option to disable the "objectsTriviallyEqual" test in DiffBuilder - Add (T) casts to get unit tests to pass in old JDK - Add JsonToStringStyle implementation to ToStringStyle - Add NoClassNameToStringStyle implementation of ToStringStyle - Fix wrong examples in JavaDoc of StringUtils.replaceEachRepeatedly(...), StringUtils.replaceEach(...) - Add StringUtils.containsAny(CharSequence, CharSequence...) method - Read wrong component type of array in add in ArrayUtils - StringUtils.ordinalIndexOf("aaaaaa", "aa", 2) != 3 in StringUtils - Duplicated "0x" check in createBigInteger in NumberUtils - StringUtils.abbreviate description doesn't agree with the examples - Multiline recursive to string style - Add isSorted() to ArrayUtils - Fix MethodUtilsTest so it does not depend on JDK method ordering - CompareToBuilder's doc doesn't specify precedence of fields it uses in performing comparisons - ParseException when trying to parse UTC dates with Z as zone designator using DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT - Javadoc for EqualsBuilder.reflectionEquals() is unclear - Improve performance of normalize space - Add StringUtils.countMatches(CharSequence, char) - org.apache.commons.lang3.SystemUtils#isJavaVersionAtLeast should return true by default - Provide methods to retrieve all fields/methods annotated with a specific type - Bring static method references in StringUtils to consistent style - NumberUtils#isParsable method(s) - Use non-ASCII digits in Javadoc examples for StringUtils.isNumeric - Change min/max methods in NumberUtils/IEEE754rUtils from array input parameters to varargs - Add fuzzy String matching logic to StringUtils - Add wrap (with String or char) to StringUtils - Extend DurationFormatUtils#formatDurationISO default pattern to match #formatDurationHMS - Fixing NumberUtils JAVADoc comments for max methods - Better Javadoc for BitField class - DurationFormatUtils#formatDurationHMS implementation does not correspond to Javadoc and vice versa - DurationFormatUtils are not able to handle negative durations/periods - ISO 8601 misspelled throughout the Javadocs - Add zero copy read method to StrBuilder - Add zero copy write method to StrBuilder - Javadoc is not clear on preferred pattern to instantiate FastDateParser / FastDatePrinter - FastDateParser should be case insensitive - Fix bug with stripping spaces on last line in WordUtils.wrap() - Add method org.apache.commons.lang3.reflect.MethodUtils.invokeExactMethod(Object, String) - Add method org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(Object, String) - - - - NumberUtils#isNumber() returns false for "0.0", "0.4790", et al - Add org.apache.commons.lang3.SystemUtils.IS_JAVA_1_8 - - - - DateUtils.getFragmentInDays(Date, Calendar.MONTH) returns wrong days - DurationFormatUtils does not describe format string fully - DurationFormatUtils#lexx does not detect unmatched quote char - DurationFormatUtils does not handle large durations correctly - DurationFormatUtils.formatDuration(61999, "s.SSSS") - ms field size should be 4 digits - Failing tests with Java 8 b128 - - - - ReflectionToStringBuilder.toString does not debug 3rd party object fields within 3rd party object - Add methods for removing all invalid characters according to XML 1.0 and XML 1.1 in an input string to StringEscapeUtils - NumericEntityEscaper incorrectly encodes supplementary characters - Make some private fields final - NumberUtils#isNumber(String) fails to reject invalid Octal numbers - NumberUtils#isNumber does not allow for hex 0XABCD - StringUtils.toEncodedString(byte[], Charset) needlessly throws UnsupportedEncodingException - Add APIs MutableBoolean setTrue() and setFalse() - ConstantInitializerTest fails when building with IBM JDK 7 - Add SerializationUtils.roundtrip(T extends Serializable) to serialize then deserialize - org.apache.commons.lang3.reflect.FieldUtils.removeFinalModifier(Field) does not clean up after itself - FastDateParser javadoc incorrectly states that SimpleDateFormat is used internally - There should be a DifferenceBuilder with a ReflectionDifferenceBuilder implementation - uncaught PatternSyntaxException in FastDateFormat on Android - Improve JavaDoc of WordUtils.wrap methods - Add the Jaro-Winkler string distance algorithm to StringUtils - StringUtils.getLevenshteinDistance with too big of a threshold returns wrong result - Test DurationFormatUtilsTest.testEdgeDuration fails in JDK 1.6, 1.7 and 1.8, BRST time zone - ConstructorUtils.getAccessibleConstructor() Does Not Check the Accessibility of Enclosing Classes - Fragments are wrong by 1 day when using fragment YEAR or MONTH - New class ClassPathUtils with methods for turning FQN into resource path - Move Documentation from user guide to package-info files - Convert package.html files to package-info.java files - FastDateParser does not handle two digit year parsing like SimpleDateFormat - FastDateParserTest.testParses does not test FastDateParser - Fix deprecation warnings - EnumUtils.generateBitVector needs a "? extends" - Validate: add inclusiveBetween and exclusiveBetween overloads for primitive types - New RandomUtils class - Wrong locale handling in LocaleUtils.toLocale() - Add IBM OS/400 detection - - - - Fix missing Hamcrest dependency in Ant Build - Test failure in LocaleUtilsTest when building with JDK 8 - Test failure in FastDateParserTest and FastDateFormat_ParserTest when building with JDK8 - Build fails with test failures when building with JDK 8 - - - - Add removeFinalModifier to FieldUtils - Method returns number of inheritance hops between parent and subclass - Spelling fixes - Misleading Javadoc comment in StrBuilderReader class - OctalUnescaper tried to parse all of \279 - OctalUnescaper had bugs when parsing octals starting with a zero - EqualsBuilder returned true when comparing arrays, even when the elements are different - Added isStarted, isSuspended and isStopped to StopWatch - Fixed exception when combining custom and choice format in ExtendedMessageFormat - Added StringUtils.isBlank/isEmpty CharSequence... methods - Added ArrayUtils.reverse(array, from, to) methods - StringUtils.toString(byte[], String) deprecated in favour of a new StringUtils.toString(byte[], CharSet) - RandomStringUtils.random javadoc was incorrectly promising letters and numbers would, as opposed to may, appear - BooleanUtils.xor(boolean...) produces wrong results - StringUtils.normalizeSpace now handles non-breaking spaces (Unicode 00A0) - Redundant check for zero in HashCodeBuilder ctor - StrSubstitutor now supports default values for variables - Adding .gitignore to commons-lang - Add ObjectUtils.toIdentityString methods that support StringBuilder, StrBuilder, and Appendable - BooleanUtils.toBoolean(String str) javadoc is not updated - LocaleUtils test fails with new Locale "ja_JP_JP_#u-ca-japanese" of JDK7 - StrSubstitutor does not support StringBuilder or CharSequence - Method createNumber from NumberUtils doesn't work for floating point numbers other than Float - FastDateFormat does not use the locale specific cache correctly - Simplify FastDateFormat; eliminate boxing - LookupTranslator now works with implementations of CharSequence other than String - ClassUtils.getShortName(String) will now only do a reverse lookup for array types - Added CharSetUtils.containsAny(String, String) - Provide CharSequenceUtils.regionMatches with a proper green implementation instead of inefficiently converting to Strings - Added escape/unescapeJson to StringEscapeUtils - Added appendIfMissing and prependIfMissing methods to StringUtils - NumberUtils.createNumber() Javadoc says it does not work for octal numbers - Fixed URLs in javadoc to point to new oracle.com pages - Add StringUtils.LF and StringUtils.CR values - Add FieldUtils getAllFields() to return all the fields defined in the given class and super classes - LocaleUtils.toLocale does not parse strings starting with an underscore - StrBuilder should support StringBuilder as an input parameter - StringEscapeUtils.escapeJava() and escapeEcmaScript() do not output the escaped surrogate pairs that are Java parsable - StringIndexOutOfBoundsException in CharSequenceTranslator - Code refactoring in NumberUtils - NumberUtils#createBigInteger does not allow for hex and octal numbers - NumberUtils#createNumber - does not allow for hex numbers to be larger than Long - StringUtils join APIs for primitives - FastDateFormat and FastDatePrinter generates Date objects wastefully - Spelling fixes - Fix examples contained in javadoc of StringUtils.center methods - Add StringUtils API to call String.replaceAll in DOTALL a.k.a. single-line mode - ArrayUtils removeElements methods use unnecessary HashSet - ArrayUtils removeElements methods clone temporary index arrays unnecessarily - FastDateParser does not handle unterminated quotes correctly - FastDateParser does not handle white-space properly - FastDateParser could use \Q \E to quote regexes - FastDateParser does not handle non-Gregorian calendars properly - FastDateParser does not handle non-ASCII digits correctly - Create StrBuilder APIs similar to String.format(String, Object...) - NumberUtils#createNumber - bad behaviour for leading "--" - FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format() - Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8 - StringUtils.equalsIgnoreCase doesn't check string reference equality - StringUtils.join() endIndex, bugged for loop - RandomStringUtils throws confusing IAE when end <= start - RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException - LocaleUtils - unnecessary recursive call in SyncAvoid class. - Javadoc bug in DateUtils#ceiling for Calendar and Object versions. - DateUtils#parseDate uses default locale; add Locale support - Use generics in SerializationUtils - SerializationUtils throws ClassNotFoundException when cloning primitive classes - StringUtils equals() relies on undefined behavior - Documentation bug: StringUtils.split - jar contains velocity template of release notes - TypeUtilsTest contains incorrect type assignability assertion - TypeUtils.getTypeArguments() misses type arguments for partially-assigned classes - ImmutablePair doc contains nonsense text - ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text - EventListenerSupport.ProxyInvocationHandler no longer defines serialVersionUID - StrBuilder is now serializable - Fix Javadoc Ant warnings - NumberUtils does not handle Long Hex numbers - Javadoc bug in static inner class DateIterator - Add Triple class (ternary version of Pair) - FastDateFormat supports parse methods - - - - Add API StringUtils.toString(byte[] intput, String charsetName) - Add an example with whitespace in StringUtils.defaultIfEmpty - Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and isPrimitiveOrWrapper(Class<?>) - Fix createLong() so it behaves like createInteger() - Include the actual type in the Validate.isInstance and isAssignableFrom exception messages - Incorrect Bundle-SymbolicName in Manifest - Deprecating chomp(String, String) - NumberUtils does not handle upper-case hex: 0X and -0X - StringUtils throws java.security.AccessControlException on Google App Engine - Ant build has wrong component.name - CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY - Document that the Mutable numbers don't work as expected with String.format - SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system - - - - SerializationUtils.clone: Fallback to context classloader if class not found in current classloader. - ToStringBuilderTest.testReflectionHierarchyArrayList fails with IBM JDK 6. - StringEscapeUtils.escapeXml(input) wrong when input contains characters in Supplementary Planes. - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long unicode string. - Improve exception message when StringUtils.replaceEachRepeatedly detects recursion. - Specify source encoding for Ant build. - Complement ArrayUtils.addAll() variants with by-index and by-value removal methods. - Add Range<T> Range<T>.intersectionWith(Range<T>). - Add mode and median Comparable... methods to ObjectUtils. - Add BooleanUtils.and + or varargs methods. - EnumSet -> bit vector. - The CHAR_ARRAY cache in CharUtils duplicates the cache in java.lang.Character. - Deprecate CharUtils.toCharacterObject(char) in favor of java.lang.Character.valueOf(char). - Missing method getRawMessage for ContextedException and ContextedRuntimeException. - Use internal Java's Number caches instead creating new objects. - - - - StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes. - build.xml Java 1.5+ updates. - swapCase and *capitalize speedups. - CharSetUtils.squeeze() speedup. - StringUtils doc/comment spelling fixes. - Increase test coverage of FieldUtils read methods and tweak Javadoc. - Add includeantruntime=false to javac targets to quell warnings in ant 1.8.1 and better (and modest performance gain). - StringIndexOutOfBoundsException when calling unescapeHtml4("&#03"). - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long Unicode string. - StringUtils.join throws NPE when toString returns null for one of objects in collection. - Add FormattableUtils class. - Add ClassUtils.getSimpleName() methods. - Add hashCodeMulti varargs method. - Removed DateUtils.UTC_TIME_ZONE. - Convert more of the StringUtils API to take CharSequence. - EqualsBuilder synchronizes on HashCodeBuilder. - StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for "". - Add support for ConcurrentMap.putIfAbsent(). - Documented potential NPE if auto-boxing occurs for some BooleanUtils methods. - DateUtils.isSameLocalTime compares using 12 hour clock and not 24 hour. - Extend exception handling in ConcurrentUtils to runtime exceptions. - SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - WordUtils.abbreviate() removed. - Doc bug in DateUtils#ceiling. - StringEscapeUtils.unescapeJava doesn't handle octal escapes and Unicode with extra u. - org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k). - org.apache.commons.lang3.math.Fraction does not always succeed in multiplyBy and divideBy. - Change ObjectUtils min() & max() functions to use varargs rather than just two parameters. - Add a Null-safe compare() method to ObjectUtils. - NumberUtils.isNumber(String) is not right when the String is "1.1L". - EntityArrays typo: {"\u2122", "&minus;"}, // minus sign, U+2212 ISOtech. - Some Entitys like &Ouml; are not matched properly against its ISO8859-1 representation. - Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect. - Add StringUtils.defaultIfBlank(). - Provide a very basic ConcurrentInitializer implementation. - Support lazy initialization using atomic variables. - Enhance StrSubstitutor to support nested ${var-${subvr}} expansion. - Provide documentation about the new concurrent package. - Charset may not be threadsafe, because the HashSet is not synch. - StringEscapeUtils.escapeXML() can't process UTF-16 supplementary characters. - StringUtils.endsWithAny method. - Add AnnotationUtils. - BooleanUtils.toBooleanObject to support single character input. - FastDateFormat.format() outputs incorrect week of year because locale isn't respected. - StrSubstitutor should also handle the default properties of a java.util.Properties class. - Javadoc StringUtils.left() claims to throw on negative len, but doesn't. - Add normalizeSpace to StringUtils. - NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - - NOTE: The below were included in the Commons Lang 3.0-beta release. - Convert StringUtils API to take CharSequence. - Push down WordUtils to "text" sub-package. - Extend exception handling in ConcurrentUtils to runtime exceptions. - Some StringUtils methods should take an int character instead of char to use String API features. - EqualsBuilder causes StackOverflowException. - DefaultExceptionContext overwrites values in recursive situations. - ContextedRuntimeException no longer an 'unchecked' exception. - Add Builder Interface / Update Builders to Implement It. - Javadoc is incorrect for public static int lastIndexOf(String str, String searchStr). - ClassUtils.getClass(): Allow Dots as Inner Class Separators. - DateUtils equal & compare functions up to most significant field. - Remove JDK 1.2/1.3 bug handling in StringUtils.indexOf(String, String, int). - Create a basic Pair<L, R> class. - exception.DefaultExceptionContext.getFormattedExceptionMessage catches Throwable. - Provide an implementation of the ThreadFactory interface. - Add new Validate methods. - ArrayUtils.add(T[] array, T element) can create unexpected ClassCastException. - Do the test cases really still require main() and suite() methods?. - @SuppressWarnings("unchecked") is used too generally. - Improve StrLookup API documentation. - Change Java package name. - Change Maven groupId. - New TimedSemaphore class. - Added validState validation method. - Added isAssignableFrom and isInstanceOf validation methods. - Add TypeUtils class to provide utility code for working with generic types. - Replace Range classes with generic version. - Use Iterable on API instead of Collection. - Add methods to Validate to check whether the index is valid for the array/list/string. - Add ability to create a Future for a constant. - Replace StringBuffer with StringBuilder. - Make NumericEntityEscaper immutable. - Compile commons.lang for CDC 1.1/Foundation 1.1. - Add ArrayUtils.toArray to create generic arrays. - Validate: support for validating blank strings. - Add a concurrent package. - Mutable classes should implement an appropriately typed Mutable interface. - Better EnumUtils. - StringEscapeUtils.unescapeJava should support \u+ notation. - Rewrite StringEscapeUtils. - bring ArrayUtils.isEmpty to the generics world. - Add support for background initialization. - Add support for the handling of ExecutionExceptions. - Add StringEscapeUtils.escapeText() methods. - Addition of ContextedException and ContextedRuntimeException. - A generic implementation of the Lazy initialization pattern. - Remove code that does not hold enough value to remain. - Remove code handled now by the JDK. - StrSubstitutor now supports substitution in variable names. - Possible race-conditions in hashCode of the range classes. - StringEscapeUtils.escapeHtml incorrectly converts Unicode characters above U+00FFFF into 2 characters. - Document where in SVN trunk is. - StopWatch does not resist to system time changes. - Fixes for thread safety. - Refactor Validate.java to eliminate code redundancy. - Lower Ascii Characters don't get encoded by Entities.java. - StringUtils.emptyToNull. - StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20). - Remove @deprecateds. - Add ClassUtils.isAssignable() variants with autoboxing. - Improve Javadoc for StringUtils class. - Javadoc incorrect for StringUtils.endsWithIgnoreCase. - Investigate for vararg usages. - JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder). - LeftOf/RightOfNumber in Range convenience methods necessary. - ExceptionUtils not thread-safe. - ObjectUtils.coalesce. - StrBuilder should implement CharSequence and Appendable. - StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanese, etc. - Finally start using generics. - StrBuilder does not implement clone(). - EnumUtils for JDK 5.0. - Wish : method unaccent. - MutableBigDecimal and MutableBigInteger. - StringEscaper.escapeXml() escapes characters > 0x7f. - Depend on JDK 1.5+. - - - - BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String). - ClassUtils: allow Dots as Inner Class Separators in getClass(). - DateUtils: equal and compare functions up to most significant field. - DateUtils: provide a Date to Calendar convenience method. - ObjectUtils: add clone methods to ObjectUtils. - ObjectUtils: add a Null-safe compare() method. - ObjectUtils: add notEqual() method. - StrBuilder: implement clone() method. - StringUtils: add a normalizeSpace() method. - StringUtils: add endsWithAny() method. - StringUtils: add defaultIfBlank() method. - StrSubstitutor: add a replace(String, Properties) variant. - StrSubstitutor: support substitution in variable names. - Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue. - CharSet: make the underlying set synchronized. - CompareToBuilder: fix passing along compareTransients to the reflectionCompare method. - ExtendedMessageFormat doesn't override equals(Object). - FastDateFormat: fix to properly include the locale when formatting a Date. - NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly. - SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading. - Javadoc is incorrect for lastIndexOf() method. - Javadoc for HashCodeBuilder.append(boolean) does not match implementation. - Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't. - Javadoc - document thread safety. - Test for StringUtils replaceChars() icelandic characters. - - - - ArrayUtils - add isNotEmpty() methods. - ArrayUtils - add nullToEmpty() methods. - CharRange - provide an iterator that lets you walk the chars in the range. - CharRange - add more readable static builder methods. - ClassUtils - new isAssignable() methods with autoboxing. - ClassUtils - add support to getShortClassName and getPackageName for arrays. - DateUtils - add ceiling() method. - DateUtils - add parseDateStrictly() method. - EqualsBuilder - add reset() method. - NumberUtils - add toByte() and toShort() methods. - Mutable numbers - add string constructors. - MutableBoolean - add toBoolean(), isTrue() and isFalse() methods. - StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty. - SystemUtils - add IS_OS_WINDOWS_7 constant. - SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7. - StringUtils - add abbreviateMiddle() method. - StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods. - StringUtils - add isAllUpperCase() and isAllLowerCase() methods. - StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method. - StringUtils - add repeat() method. - StringUtils - add startsWithAny() method. - StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods. - New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils. - ArrayUtils - addAll() does not handle mixed types very well. - CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread. - ClassUtils - improving performance of getAllInterfaces. - ClassUtils - toClass() throws NullPointerException on null array element. - DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat. - DateUtils - round() doesn't work correct for Calendar.AM_PM. - DateUtils - improve tests. - Entities - multithreaded initialization. - Entities - missing final modifiers; thread-safety issues. - EnumUtils - getEnum() doesn't work well in 1.5+. - ExceptionUtils - use immutable lock target. - ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes. - FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state. - FastDateFormat - Remove unused field. - LocaleUtils - Initialization of available locales in LocaleUtils can be deferred. - NumberUtils - createNumber() thows a StringIndexOutOfBoundsException when only an "l" is passed in. - NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.'. - StringUtils - improve handling of case-insensitive Strings. - StringUtils - replaceEach() no longer NPEs when null appears in the last String[]. - StringUtils - correct Javadoc for startsWith() and startsWithIgnoreCase(). - StringEscapeUtils - escapeJava() escapes '/' characters. - StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException and returning null. - WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length. - StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity. - Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List. - EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo instead of equals because it creates an inequality with HashCodeBuilder. - HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks. - HashCodeBuilder - Changing the hashCode() method to return toHashCode(). - HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes. - HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments. - ToStringBuilder - make default style thread-safe. - RandomUtils - nextLong() always produces even numbers. - RandomUtils - RandomUtils tests are failing frequently. - - - - ClassUtils.getShortClassName(String) inefficient. - Shouldn't Commons Lang's StringUtils have a "common" string method?. - FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change. - OSGi-ify Lang. - StrBuilder appendFixedWidth does not handle nulls. - infinite loop in Fraction.reduce when numerator == 0. - FastDateFormat thread safety. - ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array. - LocaleUtils.toLocale() rejects strings with only language+variant. - Enum is not thread-safe. - BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException. - ArrayUtils.toClass. - Why does appendIdentityToString return null?. - NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN. - Dates.round() behaves incorrectly for minutes and seconds. - StringUtils.length(String) returns null-safe length. - adding a StringUtils.replace method that takes an array or List of replacement strings. - Adding functionality to DateUtils to allow direct setting of various fields. - Add escaping for CSV columns to StringEscapeUtils. - StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods. - Extension to ClassUtils: Obtain the primitive class from a wrapper. - Javadoc bugs - cannot find object. - Optimize HashCodeBuilder.append(Object). - http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete. - Ambiguous / confusing names in StringUtils replace* methods. - Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils. - Add getStartTime to StopWatch. - Perhaps add containsAny() methods?. - Javadoc Example for EqualsBuilder is questionable. - EqualsBuilder don't compare BigDecimals correctly. - Split camel case strings. - Add Calendar flavour format methods to DateFormatUtils. - Calculating A date fragment in any time-unit. - Memory usage improvement for StringUtils#getLevenshteinDistance(). - Add ExtendedMessageFormat to org.apache.commons.lang.text. - StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly. - Add toArray() method to IntRange and LongRange classes. - add SystemUtils.IS_OS_WINDOWS_VISTA field. - Pointless synchronized in ThreadLocal.initialValue should be removed. - ToStringStyle Javadoc should show examples of styles. - Documentation bug for ignoreEmptyTokens accessors in StrTokenizer. - BooleanUtils toBooleanObject Javadoc does not match implementation. - truncateNicely method which avoids truncating in the middle of a word. - - - - Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions. - NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing. - Null-safe comparison methods for finding most recent / least recent dates. - StopWatch: suspend() acts as split(), if followed by stop(). - StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException. - Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException. - ToStringBuilder throws StackOverflowError when an Object cycle exists. - Create more tests to test out the +=31 replacement code in DurationFormatUtils. - StrBuilder contains usages of thisBuf.length when they should use size. - Enum Javadoc: 1) outline 5.0 native Enum migration 2) warn not to use the switch() , 3) point out approaches for persistence and gui. - Wrong behavior of Entities.unescape. - NumberUtils.createNumber throws NumberFormatException for one digit long. - NullPointerException in isAvailableLocale(Locale). - FastDateFormat.mRules is not transient or serializable. - StringUtils.join should allow you to pass a range for it (so it only joins a part of the array). - Refactor Entities methods. - Tests fail to pass when building with Maven 2. - DurationFormatUtils returns wrong result. - unescapeXml("&12345678;") should be "&12345678;". - Optimize StringEscapeUtils.unescapeXml(String). - BooleanUtils isNotTrue/isNotFalse. - Extra StrBuilder methods. - Add a pair of StringUtils.substringsBetween;String[] methods. - HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle. - Wish for StringUtils.join(Collection, *). - - - - StrBuilderTest#testReplaceStringString fails. - EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null. - Serialization - not backwards compatible. - Replace Clover with Cobertura. - ValuedEnum.compareTo(Object other) not typesafe - it easily could be... - LocaleUtils test fails under Mustang. - Javadoc example for StringUtils.splitByWholeSeparator incorrect. - PADDING array in StringUtils overflows on '\uffff'. - ClassUtils.primitiveToWrapper and Void. - unit test for org.apache.commons.lang.text.StrBuilder. - DateUtils.truncate method is buggy when dealing with DST switching hours. - RandomStringUtils.random() family of methods create invalid Unicode sequences. - StringUtils#getLevenshteinDistance() performance is sub-optimal. - Wrong length check in StrTokenizer.StringMatcher. - ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable. - FastDateFormat: wrong format for date "01.01.1000". - Unclear Javadoc for DateUtils.iterator(). - Memory "leak" in StringUtils. - StringEscapeUtils should expose escape*() methods taking Writer argument. - Fraction.toProperString() returns -1/1 for -1. - DurationFormatUtils.formatDurationWords "11 <unit>s" gets converted to "11 <unit>". - Performance modifications on StringUtils.replace. - StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand. - DurationFormatUtils.formatPeriod() returns the wrong result. - Request for MutableBoolean implementation. - New method for EqualsBuilder. - New ExceptionUtils method setCause(). - Add Mutable<Type> to<Type>() methods. - Provides a Class.getPublicMethod which returns public invocable Method. - Using ReflectionToStringBuilder and excluding secure fields. - add generic add method to DateUtils. - Tokenizer Enhancements: reset input string, static CSV/TSV factories. - Trivial cleanup of Javadoc in various files. - CompositeFormat. - Performance boost for RandomStringUtils. - Enhanced Class.forName version. - Add StringUtils.containsIgnoreCase(...). - Support char array converters on ArrayUtils. - DurationFormatUtils.formatDurationISO() Javadoc is missing T in duration string between date and time part. - Minor build and checkstyle changes. - Javadoc errors on StringUtils.splitPreserveAllTokens(String, char). - EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to &apos;. - Add methods and tests to StrBuilder. - replace() length calculation improvement. - New interpolation features. - Implementation of escape/unescapeHtml methods with Writer. - CompareToBuilder excludeFields for reflection method. - Add WordUtils.getInitials(String). - Error in an example in the Javadoc of the StringUtils.splitPreserveAllTokens() method. - ToStringBuilder/HashCodeBuilder Javadoc code examples. - Cannot build tests from latest SVN. - minor Javadoc improvements for StringUtils.stripXxx() methods. - Javadoc for StringUtils.removeEnd is incorrect. - Minor tweak to fix of bug # 26616. - - - - make optional parameters in FastDateFormat really optional. - Nestable.indexOfThrowable(Class) uses Class.equals() to match. - buffer under/overrun on Strings.strip, stripStart & stripEnd. - ToStringStyle.setArrayEnd(String) doesn't replace null with empty string. - New class proposal: CharacterEncoding. - SystemUtils fails init on HP-UX. - Javadoc - 'four basic XML entities' should be 5 (apos is missing). - o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0. - StringEscapeUtils.unescapeHtml() doesn't handle an empty entity. - EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class. - Method enums.Enum.equals(Object o) doesn't work correctly. - ExceptionUtils.addCauseMethodName(String) does not check for duplicates. - Make StopWatch validate state transitions. - enum package is not compatible with 1.5 jdk. - WordUtils capitalizeFully() throws a null pointer exception. - ValuedEnum. - parseDate class from HttpClient's DateParser class. - ArrayUtils.isEquals() throws ClassCastException when array1 and array2 are different dimension. - ClassCastException in Enum.equals(Object). - FastDateFormat year bug. - unbalanced ReflectionToStringBuilder. - FastDateFormat.getDateInstance(int, Locale) always uses the pattern from the first invocation. - ReflectionToStringBuilder.toString(null) throws exception by design. - Make ClassUtils methods null-safe and not throw an IAE. - StringUtils.split ignores empty items. - EqualsBuilder.append(Object[], Object[]) throws NPE. - ArrayUtils.addAll doesn't always return new array. - Enum.equals does not handle different class loaders. - Add SystemUtils.AWT_TOOLKIT and others. - Throwable cause for NotImplementedException. - ClassUtils.primitivesToWrappers method. - public static boolean DateUtils.equals(Date dt1, Date dt2) ?. - Documentation error in StringUtils.replace. - DateUtils constants should be long. - DateUtils.truncate() is off by one hour when using a date in DST switch 'zone'. - StringEscapeUtils.unescapeHtml() doesn't handle hex entities. - new StringUtils.replaceChars behaves differently from old CharSetUtils.translate. - last substring returned by StringUtils.split( String, String, int ) is too long. - Can't subclass EqualsBuilder because isEquals is private. - new StringUtils.split methods that split on the whole separator string. - New method for converting a primitive Class to its corresponding wrapper Class. - Add convenience format(long) methods to FastDateFormat. - Enum's outer class may not be loaded for EnumUtils. - WordUtils.capitalizeFully(String str) should take a delimiter. - Make Javadoc crosslinking configurable. - Minor Javadoc fixes for StringUtils.contains(String, String). - Error in Javadoc for StringUtils.chomp(String, String). - StringUtils.defaultString: Documentation error. - Add hashCode-support to class ObjectUtils. - add another "known method" to ExceptionUtils. - Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES. - DateUtils.truncate oddity at the far end of the Date spectrum. - add getLength() method to ArrayUtils. - Validate.java: fixes comment skew, removes unused loop counter. - StringUtils.isAsciiPrintable(). - ExceptionUtils: new getCause() methodname (for tomcat-exception). - fixes 75 typos. - mutable numbers. - Javadoc fixes for ClassUtils. - Add StringUtils.nIndexOf?. - Javadoc fixes for CharSetUtils. - Remove redundant check for null separator in StringUtils#join. - Class and Package Comparators for ClassUtils. - add remove methods to ArrayUtils. - WordUtils capitalize improvement. - add isEmpty method to ArrayUtils. - lang.math.Fraction class deficiencies. - Add methods to ArrayUtils: add at end and insert-like ops. - Add SystemUtils methods for directory properties. - Add method that validates Collection elements are a certain type. - elapsed time formatting utility method. - - - - Infinite loop in ToStringBuilder.reflectionToString for inner classes. - NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08. - Rationalize StringUtils slice functions. - SystemUtils.IS_OS_OS2 Javadoc is wrong. - A small, but important Javadoc fix for Fraction proper whole and numerator. - Adding tolerance to double[] search methods in ArrayUtils. - lang.builder classes Javadoc edits (mostly typo fixes). - StringUtils Javadoc and test enhancements. - SystemUtils.IS_OS_*, IS_JAVA_* are always false. - Improve util.Validate tests. - maven-beta10 checkstyle problem. - StringUtils.chopNewLine - StringIndexOutOfBoundsException. - ToStringBuilder doesn't work well in subclasses. - static option for reversing the stacktrace. - NullPointerException in CompareToBuilder. - RandomStringUtils.randomAlpha methods omit 'z'. - test.time fails in Japanese (non-us) locale. - NumberUtils.isNumber allows illegal trailing characters. - Improve Javadoc and overflow behavior of Fraction. - RandomStringUtils infloops with length > 1. - test.lang fails if compiled with non iso-8859-1 locales. - SystemUtils does not play nice in an Applet. - time unit tests fail on Sundays. - java.lang.ExceptionInInitializerError thrown by JVMRandom constructor. - StringUtils.chomp does not match Perl. - patch and test case fixing problem with RandomStringUtils.random(). - General case: infinite loop: ToStringBuilder.reflectionToString. - Should ToStringBuilder.reflectionToString handle arrays?. - EnumUtils nit: The import java.io.Serializable is never used. - Example in Javadoc for ToStringBuilder wrong for append. - Added class hierarchy support to HashCodeBuilder.reflectionHashCode(). - ExceptionUtils new methods. - Infinite loop in StringUtils.replace(text, repl, with) + FIX. - StackOverflow due to ToStringBuilder. - No Javadoc for NestableDelegate. - Specify initial size for Enum's HashMap. - Enum does not support inner sub-classes. - Removed compile warning in ObjectUtils. - SystemUtils.IS_JAVA_1_5 Javadoc is wrong. - NumberRange inaccurate for Long, etc. - Hierarchy support in ToStringBuilder.reflectionToString(). - StringUtils.countMatches loops forever if substring empty. - Javadoc fixes (remove @links to non-public identifiers). - Add Javadoc examples and tests for StringUtils. - Make NumberUtils null handling consistent. - Unused field 'startFinal' in DateIterator. - reduce object creation in ToStringBuilder. - Improved tests, Javadoc for CharSetUtils, StringEscapeUtils. - NumberUtils min/max, BooleanUtils.xor, and ArrayUtils toPrimitive and toObject. - Javadoc, tests improvements for CharSet, CharSetUtils. - StringUtil enhancement. - Javadoc nit. - Additional Lang Method Suggestions. - Make NestableDelegate methods public instead of package private. - Missing @since tags. - Refactored reflection feature of ToStringBuilder into new ReflectionToStringBuilder. - Typo in documentation. - Patch for Javadoc. - Add join(..., char c) to StringUtils (and some performance fixes). Even contains tests!. - Resurrect the WordWrapUtils from commons-sandbox/utils. - EnumTest fails on Linux Sun JDK 1.3.0. - What to do with FastDateFormat unused private constructors. - Added class hierarchy support to CompareToBuilder.reflectionCompare(). - Removed compile warning in FastDateFormat. - typo in the Javadoc example code. - MethodUtils: Removed unused code/unused local vars. - Hierarchy support in EqualsBuilder.reflectionEquals(). - Javadoc Errata. - ArrayUtils.contains(). - More flexibility for getRootCause in ExceptionUtils. - - - - NumberRange.getMaximum returns minimum. - Enum constructor validations. - NestableException/Delegate is not serializable. - split using null and max less than actual token count adds "null". - ExceptionUtils cannot handle J2EE-Exception in a default way. - - - - - - - diff --git a/All/Genesis-OOB/Genesis#33/pair.info b/All/Genesis-OOB/Genesis#33/pair.info deleted file mode 100755 index a30fdb2..0000000 --- a/All/Genesis-OOB/Genesis#33/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:33 -SATName:Genesis -modifiedFPath:src/main/java/org/apache/commons/lang3/StringUtils.java -comSha:6849dfc8a660bf8c95354520a2fa1283c9b3aa43 -parentComSha:6849dfc8a660bf8c95354520a2fa1283c9b3aa43^1 -githubUrl:https://github.com/apache/commons-lang -repoName:apache#commons-lang \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#34/comMsg.txt b/All/Genesis-OOB/Genesis#34/comMsg.txt deleted file mode 100755 index ca99ba1..0000000 --- a/All/Genesis-OOB/Genesis#34/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -LANG-1152 StringIndexOutOfBoundsException or field over-write for large year fields in FastDateParser diff --git a/All/Genesis-OOB/Genesis#34/diff.diff b/All/Genesis-OOB/Genesis#34/diff.diff deleted file mode 100755 index 1ccb843..0000000 --- a/All/Genesis-OOB/Genesis#34/diff.diff +++ /dev/null @@ -1,15 +0,0 @@ -diff --git a/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java b/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java -index 3f6b3bd..84bf7e2 100644 ---- a/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java -+++ b/src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java -@@ -877,0 +878 @@ public final void appendTo(final StringBuffer buffer, int value) { -+ int first = buffer.length(); -@@ -885 +886,7 @@ public final void appendTo(final StringBuffer buffer, int value) { -- buffer.setCharAt(--index, (char)('0' + value % 10)); -+ char c= (char)('0' + value % 10); -+ if(--indexFastDatePrinter is a fast and thread-safe version of - * {@link java.text.SimpleDateFormat}.

- * - *

To obtain a FastDatePrinter, use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} - * or another variation of the factory methods of {@link FastDateFormat}.

- * - *

Since FastDatePrinter is thread safe, you can use a static member instance:

- * - * private static final DatePrinter DATE_PRINTER = FastDateFormat.getInstance("yyyy-MM-dd"); - * - * - *

This class can be used as a direct replacement to - * {@code SimpleDateFormat} in most formatting situations. - * This class is especially useful in multi-threaded server environments. - * {@code SimpleDateFormat} is not thread-safe in any JDK version, - * nor will it be as Sun have closed the bug/RFE. - *

- * - *

Only formatting is supported by this class, but all patterns are compatible with - * SimpleDateFormat (except time zones and some year patterns - see below).

- * - *

Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent - * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}). - * This pattern letter can be used here (on all JDK versions).

- * - *

In addition, the pattern {@code 'ZZ'} has been made to represent - * ISO 8601 full format time zones (eg. {@code +08:00} or {@code -11:00}). - * This introduces a minor incompatibility with Java 1.4, but at a gain of - * useful functionality.

- * - *

Starting with JDK7, ISO 8601 support was added using the pattern {@code 'X'}. - * To maintain compatibility, {@code 'ZZ'} will continue to be supported, but using - * one of the {@code 'X'} formats is recommended. - * - *

Javadoc cites for the year pattern: For formatting, if the number of - * pattern letters is 2, the year is truncated to 2 digits; otherwise it is - * interpreted as a number. Starting with Java 1.7 a pattern of 'Y' or - * 'YYY' will be formatted as '2003', while it was '03' in former Java - * versions. FastDatePrinter implements the behavior of Java 7.

- * - * @since 3.2 - * @see FastDateParser - */ -public class FastDatePrinter implements DatePrinter, Serializable { - // A lot of the speed in this class comes from caching, but some comes - // from the special int to StringBuffer conversion. - // - // The following produces a padded 2 digit number: - // buffer.append((char)(value / 10 + '0')); - // buffer.append((char)(value % 10 + '0')); - // - // Note that the fastest append to StringBuffer is a single char (used here). - // Note that Integer.toString() is not called, the conversion is simply - // taking the value and adding (mathematically) the ASCII value for '0'. - // So, don't change this code! It works and is very fast. - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 1L; - - /** - * FULL locale dependent date or time style. - */ - public static final int FULL = DateFormat.FULL; - /** - * LONG locale dependent date or time style. - */ - public static final int LONG = DateFormat.LONG; - /** - * MEDIUM locale dependent date or time style. - */ - public static final int MEDIUM = DateFormat.MEDIUM; - /** - * SHORT locale dependent date or time style. - */ - public static final int SHORT = DateFormat.SHORT; - - /** - * The pattern. - */ - private final String mPattern; - /** - * The time zone. - */ - private final TimeZone mTimeZone; - /** - * The locale. - */ - private final Locale mLocale; - /** - * The parsed rules. - */ - private transient Rule[] mRules; - /** - * The estimated maximum length. - */ - private transient int mMaxLengthEstimate; - - // Constructor - //----------------------------------------------------------------------- - /** - *

Constructs a new FastDatePrinter.

- * Use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} or another variation of the - * factory methods of {@link FastDateFormat} to get a cached FastDatePrinter instance. - * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern - * @param timeZone non-null time zone to use - * @param locale non-null locale to use - * @throws NullPointerException if pattern, timeZone, or locale is null. - */ - protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) { - mPattern = pattern; - mTimeZone = timeZone; - mLocale = locale; - - init(); - } - - /** - *

Initializes the instance for first use.

- */ - private void init() { - final List rulesList = parsePattern(); - mRules = rulesList.toArray(new Rule[rulesList.size()]); - - int len = 0; - for (int i=mRules.length; --i >= 0; ) { - len += mRules[i].estimateLength(); - } - - mMaxLengthEstimate = len; - } - - // Parse the pattern - //----------------------------------------------------------------------- - /** - *

Returns a list of Rules given a pattern.

- * - * @return a {@code List} of Rule objects - * @throws IllegalArgumentException if pattern is invalid - */ - protected List parsePattern() { - final DateFormatSymbols symbols = new DateFormatSymbols(mLocale); - final List rules = new ArrayList(); - - final String[] ERAs = symbols.getEras(); - final String[] months = symbols.getMonths(); - final String[] shortMonths = symbols.getShortMonths(); - final String[] weekdays = symbols.getWeekdays(); - final String[] shortWeekdays = symbols.getShortWeekdays(); - final String[] AmPmStrings = symbols.getAmPmStrings(); - - final int length = mPattern.length(); - final int[] indexRef = new int[1]; - - for (int i = 0; i < length; i++) { - indexRef[0] = i; - final String token = parseToken(mPattern, indexRef); - i = indexRef[0]; - - final int tokenLen = token.length(); - if (tokenLen == 0) { - break; - } - - Rule rule; - final char c = token.charAt(0); - - switch (c) { - case 'G': // era designator (text) - rule = new TextField(Calendar.ERA, ERAs); - break; - case 'y': // year (number) - if (tokenLen == 2) { - rule = TwoDigitYearField.INSTANCE; - } else { - rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen); - } - break; - case 'M': // month in year (text and number) - if (tokenLen >= 4) { - rule = new TextField(Calendar.MONTH, months); - } else if (tokenLen == 3) { - rule = new TextField(Calendar.MONTH, shortMonths); - } else if (tokenLen == 2) { - rule = TwoDigitMonthField.INSTANCE; - } else { - rule = UnpaddedMonthField.INSTANCE; - } - break; - case 'd': // day in month (number) - rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); - break; - case 'h': // hour in am/pm (number, 1..12) - rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); - break; - case 'H': // hour in day (number, 0..23) - rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); - break; - case 'm': // minute in hour (number) - rule = selectNumberRule(Calendar.MINUTE, tokenLen); - break; - case 's': // second in minute (number) - rule = selectNumberRule(Calendar.SECOND, tokenLen); - break; - case 'S': // millisecond (number) - rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); - break; - case 'E': // day in week (text) - rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); - break; - case 'D': // day in year (number) - rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); - break; - case 'F': // day of week in month (number) - rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); - break; - case 'w': // week in year (number) - rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); - break; - case 'W': // week in month (number) - rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); - break; - case 'a': // am/pm marker (text) - rule = new TextField(Calendar.AM_PM, AmPmStrings); - break; - case 'k': // hour in day (1..24) - rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); - break; - case 'K': // hour in am/pm (0..11) - rule = selectNumberRule(Calendar.HOUR, tokenLen); - break; - case 'X': // ISO 8601 - rule = Iso8601_Rule.getRule(tokenLen); - break; - case 'z': // time zone (text) - if (tokenLen >= 4) { - rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG); - } else { - rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT); - } - break; - case 'Z': // time zone (value) - if (tokenLen == 1) { - rule = TimeZoneNumberRule.INSTANCE_NO_COLON; - } else if (tokenLen == 2) { - rule = Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES; - } else { - rule = TimeZoneNumberRule.INSTANCE_COLON; - } - break; - case '\'': // literal text - final String sub = token.substring(1); - if (sub.length() == 1) { - rule = new CharacterLiteral(sub.charAt(0)); - } else { - rule = new StringLiteral(sub); - } - break; - default: - throw new IllegalArgumentException("Illegal pattern component: " + token); - } - - rules.add(rule); - } - - return rules; - } - - /** - *

Performs the parsing of tokens.

- * - * @param pattern the pattern - * @param indexRef index references - * @return parsed token - */ - protected String parseToken(final String pattern, final int[] indexRef) { - final StringBuilder buf = new StringBuilder(); - - int i = indexRef[0]; - final int length = pattern.length(); - - char c = pattern.charAt(i); - if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { - // Scan a run of the same character, which indicates a time - // pattern. - buf.append(c); - - while (i + 1 < length) { - final char peek = pattern.charAt(i + 1); - if (peek == c) { - buf.append(c); - i++; - } else { - break; - } - } - } else { - // This will identify token as text. - buf.append('\''); - - boolean inLiteral = false; - - for (; i < length; i++) { - c = pattern.charAt(i); - - if (c == '\'') { - if (i + 1 < length && pattern.charAt(i + 1) == '\'') { - // '' is treated as escaped ' - i++; - buf.append(c); - } else { - inLiteral = !inLiteral; - } - } else if (!inLiteral && - (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { - i--; - break; - } else { - buf.append(c); - } - } - } - - indexRef[0] = i; - return buf.toString(); - } - - /** - *

Gets an appropriate rule for the padding required.

- * - * @param field the field to get a rule for - * @param padding the padding required - * @return a new rule with the correct padding - */ - protected NumberRule selectNumberRule(final int field, final int padding) { - switch (padding) { - case 1: - return new UnpaddedNumberField(field); - case 2: - return new TwoDigitNumberField(field); - default: - return new PaddedNumberField(field, padding); - } - } - - // Format methods - //----------------------------------------------------------------------- - /** - *

Formats a {@code Date}, {@code Calendar} or - * {@code Long} (milliseconds) object.

- * - * @param obj the object to format - * @param toAppendTo the buffer to append to - * @param pos the position - ignored - * @return the buffer passed in - */ - @Override - public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { - if (obj instanceof Date) { - return format((Date) obj, toAppendTo); - } else if (obj instanceof Calendar) { - return format((Calendar) obj, toAppendTo); - } else if (obj instanceof Long) { - return format(((Long) obj).longValue(), toAppendTo); - } else { - throw new IllegalArgumentException("Unknown class: " + - (obj == null ? "" : obj.getClass().getName())); - } - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(long) - */ - @Override - public String format(final long millis) { - final Calendar c = newCalendar(); // hard code GregorianCalendar - c.setTimeInMillis(millis); - return applyRulesToString(c); - } - - /** - * Creates a String representation of the given Calendar by applying the rules of this printer to it. - * @param c the Calender to apply the rules to. - * @return a String representation of the given Calendar. - */ - private String applyRulesToString(final Calendar c) { - return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString(); - } - - /** - * Creation method for ne calender instances. - * @return a new Calendar instance. - */ - private GregorianCalendar newCalendar() { - // hard code GregorianCalendar - return new GregorianCalendar(mTimeZone, mLocale); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date) - */ - @Override - public String format(final Date date) { - final Calendar c = newCalendar(); // hard code GregorianCalendar - c.setTime(date); - return applyRulesToString(c); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar) - */ - @Override - public String format(final Calendar calendar) { - return format(calendar, new StringBuffer(mMaxLengthEstimate)).toString(); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final long millis, final StringBuffer buf) { - return format(new Date(millis), buf); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final Date date, final StringBuffer buf) { - final Calendar c = newCalendar(); // hard code GregorianCalendar - c.setTime(date); - return applyRules(c, buf); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final Calendar calendar, final StringBuffer buf) { - // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored - return format(calendar.getTime(), buf); - } - - /** - *

Performs the formatting by applying the rules to the - * specified calendar.

- * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - */ - protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { - for (final Rule rule : mRules) { - rule.appendTo(buf, calendar); - } - return buf; - } - - // Accessors - //----------------------------------------------------------------------- - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#getPattern() - */ - @Override - public String getPattern() { - return mPattern; - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() - */ - @Override - public TimeZone getTimeZone() { - return mTimeZone; - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#getLocale() - */ - @Override - public Locale getLocale() { - return mLocale; - } - - /** - *

Gets an estimate for the maximum string length that the - * formatter will produce.

- * - *

The actual formatted length will almost always be less than or - * equal to this amount.

- * - * @return the maximum formatted length - */ - public int getMaxLengthEstimate() { - return mMaxLengthEstimate; - } - - // Basics - //----------------------------------------------------------------------- - /** - *

Compares two objects for equality.

- * - * @param obj the object to compare to - * @return {@code true} if equal - */ - @Override - public boolean equals(final Object obj) { - if (obj instanceof FastDatePrinter == false) { - return false; - } - final FastDatePrinter other = (FastDatePrinter) obj; - return mPattern.equals(other.mPattern) - && mTimeZone.equals(other.mTimeZone) - && mLocale.equals(other.mLocale); - } - - /** - *

Returns a hashcode compatible with equals.

- * - * @return a hashcode compatible with equals - */ - @Override - public int hashCode() { - return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode()); - } - - /** - *

Gets a debugging string version of this formatter.

- * - * @return a debugging string - */ - @Override - public String toString() { - return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]"; - } - - // Serializing - //----------------------------------------------------------------------- - /** - * Create the object after serialization. This implementation reinitializes the - * transient properties. - * - * @param in ObjectInputStream from which the object is being deserialized. - * @throws IOException if there is an IO issue. - * @throws ClassNotFoundException if a class cannot be found. - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - init(); - } - - /** - * Appends digits to the given buffer. - * - * @param buffer the buffer to append to. - * @param value the value to append digits from. - */ - private static void appendDigits(final StringBuffer buffer, final int value) { - buffer.append((char)(value / 10 + '0')); - buffer.append((char)(value % 10 + '0')); - } - - // Rules - //----------------------------------------------------------------------- - /** - *

Inner class defining a rule.

- */ - private interface Rule { - /** - * Returns the estimated length of the result. - * - * @return the estimated length - */ - int estimateLength(); - - /** - * Appends the value of the specified calendar to the output buffer based on the rule implementation. - * - * @param buffer the output buffer - * @param calendar calendar to be appended - */ - void appendTo(StringBuffer buffer, Calendar calendar); - } - - /** - *

Inner class defining a numeric rule.

- */ - private interface NumberRule extends Rule { - /** - * Appends the specified value to the output buffer based on the rule implementation. - * - * @param buffer the output buffer - * @param value the value to be appended - */ - void appendTo(StringBuffer buffer, int value); - } - - /** - *

Inner class to output a constant single character.

- */ - private static class CharacterLiteral implements Rule { - private final char mValue; - - /** - * Constructs a new instance of {@code CharacterLiteral} - * to hold the specified value. - * - * @param value the character literal - */ - CharacterLiteral(final char value) { - mValue = value; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 1; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - buffer.append(mValue); - } - } - - /** - *

Inner class to output a constant string.

- */ - private static class StringLiteral implements Rule { - private final String mValue; - - /** - * Constructs a new instance of {@code StringLiteral} - * to hold the specified value. - * - * @param value the string literal - */ - StringLiteral(final String value) { - mValue = value; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mValue.length(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - buffer.append(mValue); - } - } - - /** - *

Inner class to output one of a set of values.

- */ - private static class TextField implements Rule { - private final int mField; - private final String[] mValues; - - /** - * Constructs an instance of {@code TextField} - * with the specified field and values. - * - * @param field the field - * @param values the field values - */ - TextField(final int field, final String[] values) { - mField = field; - mValues = values; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - int max = 0; - for (int i=mValues.length; --i >= 0; ) { - final int len = mValues[i].length(); - if (len > max) { - max = len; - } - } - return max; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - buffer.append(mValues[calendar.get(mField)]); - } - } - - /** - *

Inner class to output an unpadded number.

- */ - private static class UnpaddedNumberField implements NumberRule { - private final int mField; - - /** - * Constructs an instance of {@code UnpadedNumberField} with the specified field. - * - * @param field the field - */ - UnpaddedNumberField(final int field) { - mField = field; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 4; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - if (value < 10) { - buffer.append((char)(value + '0')); - } else if (value < 100) { - appendDigits(buffer, value); - } else { - buffer.append(value); - } - } - } - - /** - *

Inner class to output an unpadded month.

- */ - private static class UnpaddedMonthField implements NumberRule { - static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); - - /** - * Constructs an instance of {@code UnpaddedMonthField}. - * - */ - UnpaddedMonthField() { - super(); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(Calendar.MONTH) + 1); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - if (value < 10) { - buffer.append((char)(value + '0')); - } else { - appendDigits(buffer, value); - } - } - } - - /** - *

Inner class to output a padded number.

- */ - private static class PaddedNumberField implements NumberRule { - private final int mField; - private final int mSize; - - /** - * Constructs an instance of {@code PaddedNumberField}. - * - * @param field the field - * @param size size of the output field - */ - PaddedNumberField(final int field, final int size) { - if (size < 3) { - // Should use UnpaddedNumberField or TwoDigitNumberField. - throw new IllegalArgumentException(); - } - mField = field; - mSize = size; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mSize; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, int value) { - int first = buffer.length(); - // pad the buffer with adequate zeros - for(int digit = 0; digit0; value /= 10) { - char c= (char)('0' + value % 10); - if(--indexInner class to output a two digit number.

- */ - private static class TwoDigitNumberField implements NumberRule { - private final int mField; - - /** - * Constructs an instance of {@code TwoDigitNumberField} with the specified field. - * - * @param field the field - */ - TwoDigitNumberField(final int field) { - mField = field; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - if (value < 100) { - appendDigits(buffer, value); - } else { - buffer.append(value); - } - } - } - - /** - *

Inner class to output a two digit year.

- */ - private static class TwoDigitYearField implements NumberRule { - static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); - - /** - * Constructs an instance of {@code TwoDigitYearField}. - */ - TwoDigitYearField() { - super(); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(Calendar.YEAR) % 100); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - appendDigits(buffer, value); - } - } - - /** - *

Inner class to output a two digit month.

- */ - private static class TwoDigitMonthField implements NumberRule { - static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); - - /** - * Constructs an instance of {@code TwoDigitMonthField}. - */ - TwoDigitMonthField() { - super(); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(Calendar.MONTH) + 1); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - appendDigits(buffer, value); - } - } - - /** - *

Inner class to output the twelve hour field.

- */ - private static class TwelveHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance of {@code TwelveHourField} with the specified - * {@code NumberRule}. - * - * @param rule the rule - */ - TwelveHourField(final NumberRule rule) { - mRule = rule; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - int value = calendar.get(Calendar.HOUR); - if (value == 0) { - value = calendar.getLeastMaximum(Calendar.HOUR) + 1; - } - mRule.appendTo(buffer, value); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final int value) { - mRule.appendTo(buffer, value); - } - } - - /** - *

Inner class to output the twenty four hour field.

- */ - private static class TwentyFourHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance of {@code TwentyFourHourField} with the specified - * {@code NumberRule}. - * - * @param rule the rule - */ - TwentyFourHourField(final NumberRule rule) { - mRule = rule; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - int value = calendar.get(Calendar.HOUR_OF_DAY); - if (value == 0) { - value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; - } - mRule.appendTo(buffer, value); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final int value) { - mRule.appendTo(buffer, value); - } - } - - //----------------------------------------------------------------------- - - private static final ConcurrentMap cTimeZoneDisplayCache = - new ConcurrentHashMap(7); - /** - *

Gets the time zone display name, using a cache for performance.

- * - * @param tz the zone to query - * @param daylight true if daylight savings - * @param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT} - * @param locale the locale to use - * @return the textual name of the time zone - */ - static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) { - final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale); - String value = cTimeZoneDisplayCache.get(key); - if (value == null) { - // This is a very slow call, so cache the results. - value = tz.getDisplayName(daylight, style, locale); - final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value); - if (prior != null) { - value= prior; - } - } - return value; - } - - /** - *

Inner class to output a time zone name.

- */ - private static class TimeZoneNameRule implements Rule { - private final Locale mLocale; - private final int mStyle; - private final String mStandard; - private final String mDaylight; - - /** - * Constructs an instance of {@code TimeZoneNameRule} with the specified properties. - * - * @param timeZone the time zone - * @param locale the locale - * @param style the style - */ - TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { - mLocale = locale; - mStyle = style; - - mStandard = getTimeZoneDisplay(timeZone, false, style, locale); - mDaylight = getTimeZoneDisplay(timeZone, true, style, locale); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - // We have no access to the Calendar object that will be passed to - // appendTo so base estimate on the TimeZone passed to the - // constructor - return Math.max(mStandard.length(), mDaylight.length()); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - final TimeZone zone = calendar.getTimeZone(); - if (calendar.get(Calendar.DST_OFFSET) != 0) { - buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale)); - } else { - buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale)); - } - } - } - - /** - *

Inner class to output a time zone as a number {@code +/-HHMM} - * or {@code +/-HH:MM}.

- */ - private static class TimeZoneNumberRule implements Rule { - static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); - static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); - - final boolean mColon; - - /** - * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties. - * - * @param colon add colon between HH and MM in the output if {@code true} - */ - TimeZoneNumberRule(final boolean colon) { - mColon = colon; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 5; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - - if (offset < 0) { - buffer.append('-'); - offset = -offset; - } else { - buffer.append('+'); - } - - final int hours = offset / (60 * 60 * 1000); - appendDigits(buffer, hours); - - if (mColon) { - buffer.append(':'); - } - - final int minutes = offset / (60 * 1000) - 60 * hours; - appendDigits(buffer, minutes); - } - } - - /** - *

Inner class to output a time zone as a number {@code +/-HHMM} - * or {@code +/-HH:MM}.

- */ - private static class Iso8601_Rule implements Rule { - - // Sign TwoDigitHours or Z - static final Iso8601_Rule ISO8601_HOURS = new Iso8601_Rule(3); - // Sign TwoDigitHours Minutes or Z - static final Iso8601_Rule ISO8601_HOURS_MINUTES = new Iso8601_Rule(5); - // Sign TwoDigitHours : Minutes or Z - static final Iso8601_Rule ISO8601_HOURS_COLON_MINUTES = new Iso8601_Rule(6); - - /** - * Factory method for Iso8601_Rules. - * - * @param tokenLen a token indicating the length of the TimeZone String to be formatted. - * @return a Iso8601_Rule that can format TimeZone String of length {@code tokenLen}. If no such - * rule exists, an IllegalArgumentException will be thrown. - */ - static Iso8601_Rule getRule(int tokenLen) { - switch(tokenLen) { - case 1: - return Iso8601_Rule.ISO8601_HOURS; - case 2: - return Iso8601_Rule.ISO8601_HOURS_MINUTES; - case 3: - return Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES; - default: - throw new IllegalArgumentException("invalid number of X"); - } - } - - final int length; - - /** - * Constructs an instance of {@code Iso8601_Rule} with the specified properties. - * - * @param length The number of characters in output (unless Z is output) - */ - Iso8601_Rule(final int length) { - this.length = length; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return length; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - if (offset == 0) { - buffer.append("Z"); - return; - } - - if (offset < 0) { - buffer.append('-'); - offset = -offset; - } else { - buffer.append('+'); - } - - final int hours = offset / (60 * 60 * 1000); - appendDigits(buffer, hours); - - if (length<5) { - return; - } - - if (length==6) { - buffer.append(':'); - } - - final int minutes = offset / (60 * 1000) - 60 * hours; - appendDigits(buffer, minutes); - } - } - - // ---------------------------------------------------------------------- - /** - *

Inner class that acts as a compound key for time zone names.

- */ - private static class TimeZoneDisplayKey { - private final TimeZone mTimeZone; - private final int mStyle; - private final Locale mLocale; - - /** - * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties. - * - * @param timeZone the time zone - * @param daylight adjust the style for daylight saving time if {@code true} - * @param style the timezone style - * @param locale the timezone locale - */ - TimeZoneDisplayKey(final TimeZone timeZone, - final boolean daylight, final int style, final Locale locale) { - mTimeZone = timeZone; - if (daylight) { - mStyle = style | 0x80000000; - } else { - mStyle = style; - } - mLocale = locale; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return (mStyle * 31 + mLocale.hashCode() ) * 31 + mTimeZone.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof TimeZoneDisplayKey) { - final TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj; - return - mTimeZone.equals(other.mTimeZone) && - mStyle == other.mStyle && - mLocale.equals(other.mLocale); - } - return false; - } - } -} diff --git a/All/Genesis-OOB/Genesis#34/new/changes.xml b/All/Genesis-OOB/Genesis#34/new/changes.xml deleted file mode 100755 index 83bf55a..0000000 --- a/All/Genesis-OOB/Genesis#34/new/changes.xml +++ /dev/null @@ -1,808 +0,0 @@ - - - - - Apache Commons Lang Changes - - - - - StringIndexOutOfBoundsException or field over-write for large year fields in FastDateParser - Implement ParsePosition api for FastDateParser - StrLookup.systemPropertiesLookup() no longer reacts on changes on system properties - EnumUtils *BitVector issue with more than 32 values Enum - Capitalize javadoc is incorrect - Add check for duplicate event listener in EventListenerSupport - FastDateParser_TimeZoneStrategyTest#testTimeZoneStrategyPattern fails on Windows with German Locale - Add method containsAllWords to WordUtils - ReflectionToStringBuilder doesn't throw IllegalArgumentException when the constructor's object param is null - Inconsistent behavior of swap for malformed inputs - StringUtils join with var args - Fix critical issues reported by SonarQube - StrBuilder.equals(StrBuilder) doesn't check for null inputs - Add ThreadUtils - A utility class which provides helper methods related to java.lang.Thread - Add annotations to exclude fields from ReflectionEqualsBuilder, ReflectionToStringBuilder and ReflectionHashCodeBuilder - Use JUnit rules to set and reset the default Locale and TimeZone - JsonToStringStyle doesn't handle chars and objects correctly - HashCodeBuilder throws StackOverflowError in bidirectional navigable association - DateFormatUtilsTest.testSMTP depends on the default Locale - Unit test FastDatePrinterTimeZonesTest needs a timezone set - CLONE - DateFormatUtils.format does not correctly change Calendar TimeZone in certain situations - DateUtilsTest.testLang530 fails for some timezones - TypeUtils.ParameterizedType#equals doesn't work with wildcard types - Add rotate(string, int) method to StringUtils - StringUtils.repeat('z', -1) throws NegativeArraySizeException - Add swap and shift operations for arrays to ArrayUtils - TypeUtils.parameterizeWithOwner - wrong format descriptor for "invalid number of type parameters". - MultilineRecursiveToStringStyle largely unusable due to being package-private. - StringUtils.uncapitalize performance improvement - CharSet.getInstance documentation does not clearly explain how to include negation character in set - Change nullToEmpty methods to generics - Fix FindBugs warnings in DurationFormatUtils - Add a method to ArrayUtils for removing all occurrences of a given element - Fix parsing edge cases in FastDateParser - - - - Support OS X versions in SystemUtils - SystemUtils.IS_OS_WINDOWS_2008, VISTA are incorrect - Parse test fails for TimeZone America/Sao_Paulo - Add SystemUtils.IS_JAVA_1_9 - Make logic for comparing OS versions in SystemUtils smarter - Shutdown thread pools in test cases - FastDateParser and FastDatePrinter support 'X' format - Avoid memory allocation when using date formating to StringBuffer - Possible performance improvement on string escape functions - Exception while using ExtendedMessageFormat and escaping braces - Avoid String allocation in StrBuilder.append(CharSequence) - Update maven-checkstyle-plugin to 2.14 - Update org.easymock:easymock to 3.3.1 - Update maven-pmd-plugin to 3.4 - Update maven-antrun-plugin to 1.8 - Wrong formating of time zones with daylight saving time in FastDatePrinter - Performance improvements for StringEscapeUtils - Add ClassUtils.getAbbreviatedName() - FastDateParser does not set error indication in ParsePosition - FastDateParser does not handle excess hours as per SimpleDateFormat - FastDateParser error - timezones not handled correctly - NumberUtils#createNumber() returns positive BigDecimal when negative Float is expected - DiffBuilder.append(String, Object left, Object right) does not do a left.equals(right) check - StrSubstitutor.replaceSystemProperties does not work consistently - Add option to disable the "objectsTriviallyEqual" test in DiffBuilder - Add (T) casts to get unit tests to pass in old JDK - Add JsonToStringStyle implementation to ToStringStyle - Add NoClassNameToStringStyle implementation of ToStringStyle - Fix wrong examples in JavaDoc of StringUtils.replaceEachRepeatedly(...), StringUtils.replaceEach(...) - Add StringUtils.containsAny(CharSequence, CharSequence...) method - Read wrong component type of array in add in ArrayUtils - StringUtils.ordinalIndexOf("aaaaaa", "aa", 2) != 3 in StringUtils - Duplicated "0x" check in createBigInteger in NumberUtils - StringUtils.abbreviate description doesn't agree with the examples - Multiline recursive to string style - Add isSorted() to ArrayUtils - Fix MethodUtilsTest so it does not depend on JDK method ordering - CompareToBuilder's doc doesn't specify precedence of fields it uses in performing comparisons - ParseException when trying to parse UTC dates with Z as zone designator using DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT - Javadoc for EqualsBuilder.reflectionEquals() is unclear - Improve performance of normalize space - Add StringUtils.countMatches(CharSequence, char) - org.apache.commons.lang3.SystemUtils#isJavaVersionAtLeast should return true by default - Provide methods to retrieve all fields/methods annotated with a specific type - Bring static method references in StringUtils to consistent style - NumberUtils#isParsable method(s) - Use non-ASCII digits in Javadoc examples for StringUtils.isNumeric - Change min/max methods in NumberUtils/IEEE754rUtils from array input parameters to varargs - Add fuzzy String matching logic to StringUtils - Add wrap (with String or char) to StringUtils - Extend DurationFormatUtils#formatDurationISO default pattern to match #formatDurationHMS - Fixing NumberUtils JAVADoc comments for max methods - Better Javadoc for BitField class - DurationFormatUtils#formatDurationHMS implementation does not correspond to Javadoc and vice versa - DurationFormatUtils are not able to handle negative durations/periods - ISO 8601 misspelled throughout the Javadocs - Add zero copy read method to StrBuilder - Add zero copy write method to StrBuilder - Javadoc is not clear on preferred pattern to instantiate FastDateParser / FastDatePrinter - FastDateParser should be case insensitive - Fix bug with stripping spaces on last line in WordUtils.wrap() - Add method org.apache.commons.lang3.reflect.MethodUtils.invokeExactMethod(Object, String) - Add method org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(Object, String) - - - - NumberUtils#isNumber() returns false for "0.0", "0.4790", et al - Add org.apache.commons.lang3.SystemUtils.IS_JAVA_1_8 - - - - DateUtils.getFragmentInDays(Date, Calendar.MONTH) returns wrong days - DurationFormatUtils does not describe format string fully - DurationFormatUtils#lexx does not detect unmatched quote char - DurationFormatUtils does not handle large durations correctly - DurationFormatUtils.formatDuration(61999, "s.SSSS") - ms field size should be 4 digits - Failing tests with Java 8 b128 - - - - ReflectionToStringBuilder.toString does not debug 3rd party object fields within 3rd party object - Add methods for removing all invalid characters according to XML 1.0 and XML 1.1 in an input string to StringEscapeUtils - NumericEntityEscaper incorrectly encodes supplementary characters - Make some private fields final - NumberUtils#isNumber(String) fails to reject invalid Octal numbers - NumberUtils#isNumber does not allow for hex 0XABCD - StringUtils.toEncodedString(byte[], Charset) needlessly throws UnsupportedEncodingException - Add APIs MutableBoolean setTrue() and setFalse() - ConstantInitializerTest fails when building with IBM JDK 7 - Add SerializationUtils.roundtrip(T extends Serializable) to serialize then deserialize - org.apache.commons.lang3.reflect.FieldUtils.removeFinalModifier(Field) does not clean up after itself - FastDateParser javadoc incorrectly states that SimpleDateFormat is used internally - There should be a DifferenceBuilder with a ReflectionDifferenceBuilder implementation - uncaught PatternSyntaxException in FastDateFormat on Android - Improve JavaDoc of WordUtils.wrap methods - Add the Jaro-Winkler string distance algorithm to StringUtils - StringUtils.getLevenshteinDistance with too big of a threshold returns wrong result - Test DurationFormatUtilsTest.testEdgeDuration fails in JDK 1.6, 1.7 and 1.8, BRST time zone - ConstructorUtils.getAccessibleConstructor() Does Not Check the Accessibility of Enclosing Classes - Fragments are wrong by 1 day when using fragment YEAR or MONTH - New class ClassPathUtils with methods for turning FQN into resource path - Move Documentation from user guide to package-info files - Convert package.html files to package-info.java files - FastDateParser does not handle two digit year parsing like SimpleDateFormat - FastDateParserTest.testParses does not test FastDateParser - Fix deprecation warnings - EnumUtils.generateBitVector needs a "? extends" - Validate: add inclusiveBetween and exclusiveBetween overloads for primitive types - New RandomUtils class - Wrong locale handling in LocaleUtils.toLocale() - Add IBM OS/400 detection - - - - Fix missing Hamcrest dependency in Ant Build - Test failure in LocaleUtilsTest when building with JDK 8 - Test failure in FastDateParserTest and FastDateFormat_ParserTest when building with JDK8 - Build fails with test failures when building with JDK 8 - - - - Add removeFinalModifier to FieldUtils - Method returns number of inheritance hops between parent and subclass - Spelling fixes - Misleading Javadoc comment in StrBuilderReader class - OctalUnescaper tried to parse all of \279 - OctalUnescaper had bugs when parsing octals starting with a zero - EqualsBuilder returned true when comparing arrays, even when the elements are different - Added isStarted, isSuspended and isStopped to StopWatch - Fixed exception when combining custom and choice format in ExtendedMessageFormat - Added StringUtils.isBlank/isEmpty CharSequence... methods - Added ArrayUtils.reverse(array, from, to) methods - StringUtils.toString(byte[], String) deprecated in favour of a new StringUtils.toString(byte[], CharSet) - RandomStringUtils.random javadoc was incorrectly promising letters and numbers would, as opposed to may, appear - BooleanUtils.xor(boolean...) produces wrong results - StringUtils.normalizeSpace now handles non-breaking spaces (Unicode 00A0) - Redundant check for zero in HashCodeBuilder ctor - StrSubstitutor now supports default values for variables - Adding .gitignore to commons-lang - Add ObjectUtils.toIdentityString methods that support StringBuilder, StrBuilder, and Appendable - BooleanUtils.toBoolean(String str) javadoc is not updated - LocaleUtils test fails with new Locale "ja_JP_JP_#u-ca-japanese" of JDK7 - StrSubstitutor does not support StringBuilder or CharSequence - Method createNumber from NumberUtils doesn't work for floating point numbers other than Float - FastDateFormat does not use the locale specific cache correctly - Simplify FastDateFormat; eliminate boxing - LookupTranslator now works with implementations of CharSequence other than String - ClassUtils.getShortName(String) will now only do a reverse lookup for array types - Added CharSetUtils.containsAny(String, String) - Provide CharSequenceUtils.regionMatches with a proper green implementation instead of inefficiently converting to Strings - Added escape/unescapeJson to StringEscapeUtils - Added appendIfMissing and prependIfMissing methods to StringUtils - NumberUtils.createNumber() Javadoc says it does not work for octal numbers - Fixed URLs in javadoc to point to new oracle.com pages - Add StringUtils.LF and StringUtils.CR values - Add FieldUtils getAllFields() to return all the fields defined in the given class and super classes - LocaleUtils.toLocale does not parse strings starting with an underscore - StrBuilder should support StringBuilder as an input parameter - StringEscapeUtils.escapeJava() and escapeEcmaScript() do not output the escaped surrogate pairs that are Java parsable - StringIndexOutOfBoundsException in CharSequenceTranslator - Code refactoring in NumberUtils - NumberUtils#createBigInteger does not allow for hex and octal numbers - NumberUtils#createNumber - does not allow for hex numbers to be larger than Long - StringUtils join APIs for primitives - FastDateFormat and FastDatePrinter generates Date objects wastefully - Spelling fixes - Fix examples contained in javadoc of StringUtils.center methods - Add StringUtils API to call String.replaceAll in DOTALL a.k.a. single-line mode - ArrayUtils removeElements methods use unnecessary HashSet - ArrayUtils removeElements methods clone temporary index arrays unnecessarily - FastDateParser does not handle unterminated quotes correctly - FastDateParser does not handle white-space properly - FastDateParser could use \Q \E to quote regexes - FastDateParser does not handle non-Gregorian calendars properly - FastDateParser does not handle non-ASCII digits correctly - Create StrBuilder APIs similar to String.format(String, Object...) - NumberUtils#createNumber - bad behaviour for leading "--" - FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format() - Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8 - StringUtils.equalsIgnoreCase doesn't check string reference equality - StringUtils.join() endIndex, bugged for loop - RandomStringUtils throws confusing IAE when end <= start - RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException - LocaleUtils - unnecessary recursive call in SyncAvoid class. - Javadoc bug in DateUtils#ceiling for Calendar and Object versions. - DateUtils#parseDate uses default locale; add Locale support - Use generics in SerializationUtils - SerializationUtils throws ClassNotFoundException when cloning primitive classes - StringUtils equals() relies on undefined behavior - Documentation bug: StringUtils.split - jar contains velocity template of release notes - TypeUtilsTest contains incorrect type assignability assertion - TypeUtils.getTypeArguments() misses type arguments for partially-assigned classes - ImmutablePair doc contains nonsense text - ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text - EventListenerSupport.ProxyInvocationHandler no longer defines serialVersionUID - StrBuilder is now serializable - Fix Javadoc Ant warnings - NumberUtils does not handle Long Hex numbers - Javadoc bug in static inner class DateIterator - Add Triple class (ternary version of Pair) - FastDateFormat supports parse methods - - - - Add API StringUtils.toString(byte[] intput, String charsetName) - Add an example with whitespace in StringUtils.defaultIfEmpty - Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and isPrimitiveOrWrapper(Class<?>) - Fix createLong() so it behaves like createInteger() - Include the actual type in the Validate.isInstance and isAssignableFrom exception messages - Incorrect Bundle-SymbolicName in Manifest - Deprecating chomp(String, String) - NumberUtils does not handle upper-case hex: 0X and -0X - StringUtils throws java.security.AccessControlException on Google App Engine - Ant build has wrong component.name - CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY - Document that the Mutable numbers don't work as expected with String.format - SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system - - - - SerializationUtils.clone: Fallback to context classloader if class not found in current classloader. - ToStringBuilderTest.testReflectionHierarchyArrayList fails with IBM JDK 6. - StringEscapeUtils.escapeXml(input) wrong when input contains characters in Supplementary Planes. - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long unicode string. - Improve exception message when StringUtils.replaceEachRepeatedly detects recursion. - Specify source encoding for Ant build. - Complement ArrayUtils.addAll() variants with by-index and by-value removal methods. - Add Range<T> Range<T>.intersectionWith(Range<T>). - Add mode and median Comparable... methods to ObjectUtils. - Add BooleanUtils.and + or varargs methods. - EnumSet -> bit vector. - The CHAR_ARRAY cache in CharUtils duplicates the cache in java.lang.Character. - Deprecate CharUtils.toCharacterObject(char) in favor of java.lang.Character.valueOf(char). - Missing method getRawMessage for ContextedException and ContextedRuntimeException. - Use internal Java's Number caches instead creating new objects. - - - - StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes. - build.xml Java 1.5+ updates. - swapCase and *capitalize speedups. - CharSetUtils.squeeze() speedup. - StringUtils doc/comment spelling fixes. - Increase test coverage of FieldUtils read methods and tweak Javadoc. - Add includeantruntime=false to javac targets to quell warnings in ant 1.8.1 and better (and modest performance gain). - StringIndexOutOfBoundsException when calling unescapeHtml4("&#03"). - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long Unicode string. - StringUtils.join throws NPE when toString returns null for one of objects in collection. - Add FormattableUtils class. - Add ClassUtils.getSimpleName() methods. - Add hashCodeMulti varargs method. - Removed DateUtils.UTC_TIME_ZONE. - Convert more of the StringUtils API to take CharSequence. - EqualsBuilder synchronizes on HashCodeBuilder. - StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for "". - Add support for ConcurrentMap.putIfAbsent(). - Documented potential NPE if auto-boxing occurs for some BooleanUtils methods. - DateUtils.isSameLocalTime compares using 12 hour clock and not 24 hour. - Extend exception handling in ConcurrentUtils to runtime exceptions. - SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - WordUtils.abbreviate() removed. - Doc bug in DateUtils#ceiling. - StringEscapeUtils.unescapeJava doesn't handle octal escapes and Unicode with extra u. - org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k). - org.apache.commons.lang3.math.Fraction does not always succeed in multiplyBy and divideBy. - Change ObjectUtils min() & max() functions to use varargs rather than just two parameters. - Add a Null-safe compare() method to ObjectUtils. - NumberUtils.isNumber(String) is not right when the String is "1.1L". - EntityArrays typo: {"\u2122", "&minus;"}, // minus sign, U+2212 ISOtech. - Some Entitys like &Ouml; are not matched properly against its ISO8859-1 representation. - Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect. - Add StringUtils.defaultIfBlank(). - Provide a very basic ConcurrentInitializer implementation. - Support lazy initialization using atomic variables. - Enhance StrSubstitutor to support nested ${var-${subvr}} expansion. - Provide documentation about the new concurrent package. - Charset may not be threadsafe, because the HashSet is not synch. - StringEscapeUtils.escapeXML() can't process UTF-16 supplementary characters. - StringUtils.endsWithAny method. - Add AnnotationUtils. - BooleanUtils.toBooleanObject to support single character input. - FastDateFormat.format() outputs incorrect week of year because locale isn't respected. - StrSubstitutor should also handle the default properties of a java.util.Properties class. - Javadoc StringUtils.left() claims to throw on negative len, but doesn't. - Add normalizeSpace to StringUtils. - NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - - NOTE: The below were included in the Commons Lang 3.0-beta release. - Convert StringUtils API to take CharSequence. - Push down WordUtils to "text" sub-package. - Extend exception handling in ConcurrentUtils to runtime exceptions. - Some StringUtils methods should take an int character instead of char to use String API features. - EqualsBuilder causes StackOverflowException. - DefaultExceptionContext overwrites values in recursive situations. - ContextedRuntimeException no longer an 'unchecked' exception. - Add Builder Interface / Update Builders to Implement It. - Javadoc is incorrect for public static int lastIndexOf(String str, String searchStr). - ClassUtils.getClass(): Allow Dots as Inner Class Separators. - DateUtils equal & compare functions up to most significant field. - Remove JDK 1.2/1.3 bug handling in StringUtils.indexOf(String, String, int). - Create a basic Pair<L, R> class. - exception.DefaultExceptionContext.getFormattedExceptionMessage catches Throwable. - Provide an implementation of the ThreadFactory interface. - Add new Validate methods. - ArrayUtils.add(T[] array, T element) can create unexpected ClassCastException. - Do the test cases really still require main() and suite() methods?. - @SuppressWarnings("unchecked") is used too generally. - Improve StrLookup API documentation. - Change Java package name. - Change Maven groupId. - New TimedSemaphore class. - Added validState validation method. - Added isAssignableFrom and isInstanceOf validation methods. - Add TypeUtils class to provide utility code for working with generic types. - Replace Range classes with generic version. - Use Iterable on API instead of Collection. - Add methods to Validate to check whether the index is valid for the array/list/string. - Add ability to create a Future for a constant. - Replace StringBuffer with StringBuilder. - Make NumericEntityEscaper immutable. - Compile commons.lang for CDC 1.1/Foundation 1.1. - Add ArrayUtils.toArray to create generic arrays. - Validate: support for validating blank strings. - Add a concurrent package. - Mutable classes should implement an appropriately typed Mutable interface. - Better EnumUtils. - StringEscapeUtils.unescapeJava should support \u+ notation. - Rewrite StringEscapeUtils. - bring ArrayUtils.isEmpty to the generics world. - Add support for background initialization. - Add support for the handling of ExecutionExceptions. - Add StringEscapeUtils.escapeText() methods. - Addition of ContextedException and ContextedRuntimeException. - A generic implementation of the Lazy initialization pattern. - Remove code that does not hold enough value to remain. - Remove code handled now by the JDK. - StrSubstitutor now supports substitution in variable names. - Possible race-conditions in hashCode of the range classes. - StringEscapeUtils.escapeHtml incorrectly converts Unicode characters above U+00FFFF into 2 characters. - Document where in SVN trunk is. - StopWatch does not resist to system time changes. - Fixes for thread safety. - Refactor Validate.java to eliminate code redundancy. - Lower Ascii Characters don't get encoded by Entities.java. - StringUtils.emptyToNull. - StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20). - Remove @deprecateds. - Add ClassUtils.isAssignable() variants with autoboxing. - Improve Javadoc for StringUtils class. - Javadoc incorrect for StringUtils.endsWithIgnoreCase. - Investigate for vararg usages. - JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder). - LeftOf/RightOfNumber in Range convenience methods necessary. - ExceptionUtils not thread-safe. - ObjectUtils.coalesce. - StrBuilder should implement CharSequence and Appendable. - StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanese, etc. - Finally start using generics. - StrBuilder does not implement clone(). - EnumUtils for JDK 5.0. - Wish : method unaccent. - MutableBigDecimal and MutableBigInteger. - StringEscaper.escapeXml() escapes characters > 0x7f. - Depend on JDK 1.5+. - - - - BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String). - ClassUtils: allow Dots as Inner Class Separators in getClass(). - DateUtils: equal and compare functions up to most significant field. - DateUtils: provide a Date to Calendar convenience method. - ObjectUtils: add clone methods to ObjectUtils. - ObjectUtils: add a Null-safe compare() method. - ObjectUtils: add notEqual() method. - StrBuilder: implement clone() method. - StringUtils: add a normalizeSpace() method. - StringUtils: add endsWithAny() method. - StringUtils: add defaultIfBlank() method. - StrSubstitutor: add a replace(String, Properties) variant. - StrSubstitutor: support substitution in variable names. - Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue. - CharSet: make the underlying set synchronized. - CompareToBuilder: fix passing along compareTransients to the reflectionCompare method. - ExtendedMessageFormat doesn't override equals(Object). - FastDateFormat: fix to properly include the locale when formatting a Date. - NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly. - SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading. - Javadoc is incorrect for lastIndexOf() method. - Javadoc for HashCodeBuilder.append(boolean) does not match implementation. - Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't. - Javadoc - document thread safety. - Test for StringUtils replaceChars() icelandic characters. - - - - ArrayUtils - add isNotEmpty() methods. - ArrayUtils - add nullToEmpty() methods. - CharRange - provide an iterator that lets you walk the chars in the range. - CharRange - add more readable static builder methods. - ClassUtils - new isAssignable() methods with autoboxing. - ClassUtils - add support to getShortClassName and getPackageName for arrays. - DateUtils - add ceiling() method. - DateUtils - add parseDateStrictly() method. - EqualsBuilder - add reset() method. - NumberUtils - add toByte() and toShort() methods. - Mutable numbers - add string constructors. - MutableBoolean - add toBoolean(), isTrue() and isFalse() methods. - StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty. - SystemUtils - add IS_OS_WINDOWS_7 constant. - SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7. - StringUtils - add abbreviateMiddle() method. - StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods. - StringUtils - add isAllUpperCase() and isAllLowerCase() methods. - StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method. - StringUtils - add repeat() method. - StringUtils - add startsWithAny() method. - StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods. - New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils. - ArrayUtils - addAll() does not handle mixed types very well. - CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread. - ClassUtils - improving performance of getAllInterfaces. - ClassUtils - toClass() throws NullPointerException on null array element. - DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat. - DateUtils - round() doesn't work correct for Calendar.AM_PM. - DateUtils - improve tests. - Entities - multithreaded initialization. - Entities - missing final modifiers; thread-safety issues. - EnumUtils - getEnum() doesn't work well in 1.5+. - ExceptionUtils - use immutable lock target. - ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes. - FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state. - FastDateFormat - Remove unused field. - LocaleUtils - Initialization of available locales in LocaleUtils can be deferred. - NumberUtils - createNumber() thows a StringIndexOutOfBoundsException when only an "l" is passed in. - NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.'. - StringUtils - improve handling of case-insensitive Strings. - StringUtils - replaceEach() no longer NPEs when null appears in the last String[]. - StringUtils - correct Javadoc for startsWith() and startsWithIgnoreCase(). - StringEscapeUtils - escapeJava() escapes '/' characters. - StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException and returning null. - WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length. - StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity. - Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List. - EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo instead of equals because it creates an inequality with HashCodeBuilder. - HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks. - HashCodeBuilder - Changing the hashCode() method to return toHashCode(). - HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes. - HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments. - ToStringBuilder - make default style thread-safe. - RandomUtils - nextLong() always produces even numbers. - RandomUtils - RandomUtils tests are failing frequently. - - - - ClassUtils.getShortClassName(String) inefficient. - Shouldn't Commons Lang's StringUtils have a "common" string method?. - FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change. - OSGi-ify Lang. - StrBuilder appendFixedWidth does not handle nulls. - infinite loop in Fraction.reduce when numerator == 0. - FastDateFormat thread safety. - ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array. - LocaleUtils.toLocale() rejects strings with only language+variant. - Enum is not thread-safe. - BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException. - ArrayUtils.toClass. - Why does appendIdentityToString return null?. - NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN. - Dates.round() behaves incorrectly for minutes and seconds. - StringUtils.length(String) returns null-safe length. - adding a StringUtils.replace method that takes an array or List of replacement strings. - Adding functionality to DateUtils to allow direct setting of various fields. - Add escaping for CSV columns to StringEscapeUtils. - StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods. - Extension to ClassUtils: Obtain the primitive class from a wrapper. - Javadoc bugs - cannot find object. - Optimize HashCodeBuilder.append(Object). - http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete. - Ambiguous / confusing names in StringUtils replace* methods. - Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils. - Add getStartTime to StopWatch. - Perhaps add containsAny() methods?. - Javadoc Example for EqualsBuilder is questionable. - EqualsBuilder don't compare BigDecimals correctly. - Split camel case strings. - Add Calendar flavour format methods to DateFormatUtils. - Calculating A date fragment in any time-unit. - Memory usage improvement for StringUtils#getLevenshteinDistance(). - Add ExtendedMessageFormat to org.apache.commons.lang.text. - StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly. - Add toArray() method to IntRange and LongRange classes. - add SystemUtils.IS_OS_WINDOWS_VISTA field. - Pointless synchronized in ThreadLocal.initialValue should be removed. - ToStringStyle Javadoc should show examples of styles. - Documentation bug for ignoreEmptyTokens accessors in StrTokenizer. - BooleanUtils toBooleanObject Javadoc does not match implementation. - truncateNicely method which avoids truncating in the middle of a word. - - - - Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions. - NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing. - Null-safe comparison methods for finding most recent / least recent dates. - StopWatch: suspend() acts as split(), if followed by stop(). - StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException. - Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException. - ToStringBuilder throws StackOverflowError when an Object cycle exists. - Create more tests to test out the +=31 replacement code in DurationFormatUtils. - StrBuilder contains usages of thisBuf.length when they should use size. - Enum Javadoc: 1) outline 5.0 native Enum migration 2) warn not to use the switch() , 3) point out approaches for persistence and gui. - Wrong behavior of Entities.unescape. - NumberUtils.createNumber throws NumberFormatException for one digit long. - NullPointerException in isAvailableLocale(Locale). - FastDateFormat.mRules is not transient or serializable. - StringUtils.join should allow you to pass a range for it (so it only joins a part of the array). - Refactor Entities methods. - Tests fail to pass when building with Maven 2. - DurationFormatUtils returns wrong result. - unescapeXml("&12345678;") should be "&12345678;". - Optimize StringEscapeUtils.unescapeXml(String). - BooleanUtils isNotTrue/isNotFalse. - Extra StrBuilder methods. - Add a pair of StringUtils.substringsBetween;String[] methods. - HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle. - Wish for StringUtils.join(Collection, *). - - - - StrBuilderTest#testReplaceStringString fails. - EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null. - Serialization - not backwards compatible. - Replace Clover with Cobertura. - ValuedEnum.compareTo(Object other) not typesafe - it easily could be... - LocaleUtils test fails under Mustang. - Javadoc example for StringUtils.splitByWholeSeparator incorrect. - PADDING array in StringUtils overflows on '\uffff'. - ClassUtils.primitiveToWrapper and Void. - unit test for org.apache.commons.lang.text.StrBuilder. - DateUtils.truncate method is buggy when dealing with DST switching hours. - RandomStringUtils.random() family of methods create invalid Unicode sequences. - StringUtils#getLevenshteinDistance() performance is sub-optimal. - Wrong length check in StrTokenizer.StringMatcher. - ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable. - FastDateFormat: wrong format for date "01.01.1000". - Unclear Javadoc for DateUtils.iterator(). - Memory "leak" in StringUtils. - StringEscapeUtils should expose escape*() methods taking Writer argument. - Fraction.toProperString() returns -1/1 for -1. - DurationFormatUtils.formatDurationWords "11 <unit>s" gets converted to "11 <unit>". - Performance modifications on StringUtils.replace. - StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand. - DurationFormatUtils.formatPeriod() returns the wrong result. - Request for MutableBoolean implementation. - New method for EqualsBuilder. - New ExceptionUtils method setCause(). - Add Mutable<Type> to<Type>() methods. - Provides a Class.getPublicMethod which returns public invocable Method. - Using ReflectionToStringBuilder and excluding secure fields. - add generic add method to DateUtils. - Tokenizer Enhancements: reset input string, static CSV/TSV factories. - Trivial cleanup of Javadoc in various files. - CompositeFormat. - Performance boost for RandomStringUtils. - Enhanced Class.forName version. - Add StringUtils.containsIgnoreCase(...). - Support char array converters on ArrayUtils. - DurationFormatUtils.formatDurationISO() Javadoc is missing T in duration string between date and time part. - Minor build and checkstyle changes. - Javadoc errors on StringUtils.splitPreserveAllTokens(String, char). - EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to &apos;. - Add methods and tests to StrBuilder. - replace() length calculation improvement. - New interpolation features. - Implementation of escape/unescapeHtml methods with Writer. - CompareToBuilder excludeFields for reflection method. - Add WordUtils.getInitials(String). - Error in an example in the Javadoc of the StringUtils.splitPreserveAllTokens() method. - ToStringBuilder/HashCodeBuilder Javadoc code examples. - Cannot build tests from latest SVN. - minor Javadoc improvements for StringUtils.stripXxx() methods. - Javadoc for StringUtils.removeEnd is incorrect. - Minor tweak to fix of bug # 26616. - - - - make optional parameters in FastDateFormat really optional. - Nestable.indexOfThrowable(Class) uses Class.equals() to match. - buffer under/overrun on Strings.strip, stripStart & stripEnd. - ToStringStyle.setArrayEnd(String) doesn't replace null with empty string. - New class proposal: CharacterEncoding. - SystemUtils fails init on HP-UX. - Javadoc - 'four basic XML entities' should be 5 (apos is missing). - o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0. - StringEscapeUtils.unescapeHtml() doesn't handle an empty entity. - EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class. - Method enums.Enum.equals(Object o) doesn't work correctly. - ExceptionUtils.addCauseMethodName(String) does not check for duplicates. - Make StopWatch validate state transitions. - enum package is not compatible with 1.5 jdk. - WordUtils capitalizeFully() throws a null pointer exception. - ValuedEnum. - parseDate class from HttpClient's DateParser class. - ArrayUtils.isEquals() throws ClassCastException when array1 and array2 are different dimension. - ClassCastException in Enum.equals(Object). - FastDateFormat year bug. - unbalanced ReflectionToStringBuilder. - FastDateFormat.getDateInstance(int, Locale) always uses the pattern from the first invocation. - ReflectionToStringBuilder.toString(null) throws exception by design. - Make ClassUtils methods null-safe and not throw an IAE. - StringUtils.split ignores empty items. - EqualsBuilder.append(Object[], Object[]) throws NPE. - ArrayUtils.addAll doesn't always return new array. - Enum.equals does not handle different class loaders. - Add SystemUtils.AWT_TOOLKIT and others. - Throwable cause for NotImplementedException. - ClassUtils.primitivesToWrappers method. - public static boolean DateUtils.equals(Date dt1, Date dt2) ?. - Documentation error in StringUtils.replace. - DateUtils constants should be long. - DateUtils.truncate() is off by one hour when using a date in DST switch 'zone'. - StringEscapeUtils.unescapeHtml() doesn't handle hex entities. - new StringUtils.replaceChars behaves differently from old CharSetUtils.translate. - last substring returned by StringUtils.split( String, String, int ) is too long. - Can't subclass EqualsBuilder because isEquals is private. - new StringUtils.split methods that split on the whole separator string. - New method for converting a primitive Class to its corresponding wrapper Class. - Add convenience format(long) methods to FastDateFormat. - Enum's outer class may not be loaded for EnumUtils. - WordUtils.capitalizeFully(String str) should take a delimiter. - Make Javadoc crosslinking configurable. - Minor Javadoc fixes for StringUtils.contains(String, String). - Error in Javadoc for StringUtils.chomp(String, String). - StringUtils.defaultString: Documentation error. - Add hashCode-support to class ObjectUtils. - add another "known method" to ExceptionUtils. - Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES. - DateUtils.truncate oddity at the far end of the Date spectrum. - add getLength() method to ArrayUtils. - Validate.java: fixes comment skew, removes unused loop counter. - StringUtils.isAsciiPrintable(). - ExceptionUtils: new getCause() methodname (for tomcat-exception). - fixes 75 typos. - mutable numbers. - Javadoc fixes for ClassUtils. - Add StringUtils.nIndexOf?. - Javadoc fixes for CharSetUtils. - Remove redundant check for null separator in StringUtils#join. - Class and Package Comparators for ClassUtils. - add remove methods to ArrayUtils. - WordUtils capitalize improvement. - add isEmpty method to ArrayUtils. - lang.math.Fraction class deficiencies. - Add methods to ArrayUtils: add at end and insert-like ops. - Add SystemUtils methods for directory properties. - Add method that validates Collection elements are a certain type. - elapsed time formatting utility method. - - - - Infinite loop in ToStringBuilder.reflectionToString for inner classes. - NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08. - Rationalize StringUtils slice functions. - SystemUtils.IS_OS_OS2 Javadoc is wrong. - A small, but important Javadoc fix for Fraction proper whole and numerator. - Adding tolerance to double[] search methods in ArrayUtils. - lang.builder classes Javadoc edits (mostly typo fixes). - StringUtils Javadoc and test enhancements. - SystemUtils.IS_OS_*, IS_JAVA_* are always false. - Improve util.Validate tests. - maven-beta10 checkstyle problem. - StringUtils.chopNewLine - StringIndexOutOfBoundsException. - ToStringBuilder doesn't work well in subclasses. - static option for reversing the stacktrace. - NullPointerException in CompareToBuilder. - RandomStringUtils.randomAlpha methods omit 'z'. - test.time fails in Japanese (non-us) locale. - NumberUtils.isNumber allows illegal trailing characters. - Improve Javadoc and overflow behavior of Fraction. - RandomStringUtils infloops with length > 1. - test.lang fails if compiled with non iso-8859-1 locales. - SystemUtils does not play nice in an Applet. - time unit tests fail on Sundays. - java.lang.ExceptionInInitializerError thrown by JVMRandom constructor. - StringUtils.chomp does not match Perl. - patch and test case fixing problem with RandomStringUtils.random(). - General case: infinite loop: ToStringBuilder.reflectionToString. - Should ToStringBuilder.reflectionToString handle arrays?. - EnumUtils nit: The import java.io.Serializable is never used. - Example in Javadoc for ToStringBuilder wrong for append. - Added class hierarchy support to HashCodeBuilder.reflectionHashCode(). - ExceptionUtils new methods. - Infinite loop in StringUtils.replace(text, repl, with) + FIX. - StackOverflow due to ToStringBuilder. - No Javadoc for NestableDelegate. - Specify initial size for Enum's HashMap. - Enum does not support inner sub-classes. - Removed compile warning in ObjectUtils. - SystemUtils.IS_JAVA_1_5 Javadoc is wrong. - NumberRange inaccurate for Long, etc. - Hierarchy support in ToStringBuilder.reflectionToString(). - StringUtils.countMatches loops forever if substring empty. - Javadoc fixes (remove @links to non-public identifiers). - Add Javadoc examples and tests for StringUtils. - Make NumberUtils null handling consistent. - Unused field 'startFinal' in DateIterator. - reduce object creation in ToStringBuilder. - Improved tests, Javadoc for CharSetUtils, StringEscapeUtils. - NumberUtils min/max, BooleanUtils.xor, and ArrayUtils toPrimitive and toObject. - Javadoc, tests improvements for CharSet, CharSetUtils. - StringUtil enhancement. - Javadoc nit. - Additional Lang Method Suggestions. - Make NestableDelegate methods public instead of package private. - Missing @since tags. - Refactored reflection feature of ToStringBuilder into new ReflectionToStringBuilder. - Typo in documentation. - Patch for Javadoc. - Add join(..., char c) to StringUtils (and some performance fixes). Even contains tests!. - Resurrect the WordWrapUtils from commons-sandbox/utils. - EnumTest fails on Linux Sun JDK 1.3.0. - What to do with FastDateFormat unused private constructors. - Added class hierarchy support to CompareToBuilder.reflectionCompare(). - Removed compile warning in FastDateFormat. - typo in the Javadoc example code. - MethodUtils: Removed unused code/unused local vars. - Hierarchy support in EqualsBuilder.reflectionEquals(). - Javadoc Errata. - ArrayUtils.contains(). - More flexibility for getRootCause in ExceptionUtils. - - - - NumberRange.getMaximum returns minimum. - Enum constructor validations. - NestableException/Delegate is not serializable. - split using null and max less than actual token count adds "null". - ExceptionUtils cannot handle J2EE-Exception in a default way. - - - - - - - diff --git a/All/Genesis-OOB/Genesis#34/old/FastDatePrinter.java b/All/Genesis-OOB/Genesis#34/old/FastDatePrinter.java deleted file mode 100755 index 3f6b3bd..0000000 --- a/All/Genesis-OOB/Genesis#34/old/FastDatePrinter.java +++ /dev/null @@ -1,1370 +0,0 @@ -/* - * 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.commons.lang3.time; - -import java.io.IOException; -import java.io.ObjectInputStream; -import java.io.Serializable; -import java.text.DateFormat; -import java.text.DateFormatSymbols; -import java.text.FieldPosition; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.List; -import java.util.Locale; -import java.util.TimeZone; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -/** - *

FastDatePrinter is a fast and thread-safe version of - * {@link java.text.SimpleDateFormat}.

- * - *

To obtain a FastDatePrinter, use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} - * or another variation of the factory methods of {@link FastDateFormat}.

- * - *

Since FastDatePrinter is thread safe, you can use a static member instance:

- * - * private static final DatePrinter DATE_PRINTER = FastDateFormat.getInstance("yyyy-MM-dd"); - * - * - *

This class can be used as a direct replacement to - * {@code SimpleDateFormat} in most formatting situations. - * This class is especially useful in multi-threaded server environments. - * {@code SimpleDateFormat} is not thread-safe in any JDK version, - * nor will it be as Sun have closed the bug/RFE. - *

- * - *

Only formatting is supported by this class, but all patterns are compatible with - * SimpleDateFormat (except time zones and some year patterns - see below).

- * - *

Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent - * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}). - * This pattern letter can be used here (on all JDK versions).

- * - *

In addition, the pattern {@code 'ZZ'} has been made to represent - * ISO 8601 full format time zones (eg. {@code +08:00} or {@code -11:00}). - * This introduces a minor incompatibility with Java 1.4, but at a gain of - * useful functionality.

- * - *

Starting with JDK7, ISO 8601 support was added using the pattern {@code 'X'}. - * To maintain compatibility, {@code 'ZZ'} will continue to be supported, but using - * one of the {@code 'X'} formats is recommended. - * - *

Javadoc cites for the year pattern: For formatting, if the number of - * pattern letters is 2, the year is truncated to 2 digits; otherwise it is - * interpreted as a number. Starting with Java 1.7 a pattern of 'Y' or - * 'YYY' will be formatted as '2003', while it was '03' in former Java - * versions. FastDatePrinter implements the behavior of Java 7.

- * - * @since 3.2 - * @see FastDateParser - */ -public class FastDatePrinter implements DatePrinter, Serializable { - // A lot of the speed in this class comes from caching, but some comes - // from the special int to StringBuffer conversion. - // - // The following produces a padded 2 digit number: - // buffer.append((char)(value / 10 + '0')); - // buffer.append((char)(value % 10 + '0')); - // - // Note that the fastest append to StringBuffer is a single char (used here). - // Note that Integer.toString() is not called, the conversion is simply - // taking the value and adding (mathematically) the ASCII value for '0'. - // So, don't change this code! It works and is very fast. - - /** - * Required for serialization support. - * - * @see java.io.Serializable - */ - private static final long serialVersionUID = 1L; - - /** - * FULL locale dependent date or time style. - */ - public static final int FULL = DateFormat.FULL; - /** - * LONG locale dependent date or time style. - */ - public static final int LONG = DateFormat.LONG; - /** - * MEDIUM locale dependent date or time style. - */ - public static final int MEDIUM = DateFormat.MEDIUM; - /** - * SHORT locale dependent date or time style. - */ - public static final int SHORT = DateFormat.SHORT; - - /** - * The pattern. - */ - private final String mPattern; - /** - * The time zone. - */ - private final TimeZone mTimeZone; - /** - * The locale. - */ - private final Locale mLocale; - /** - * The parsed rules. - */ - private transient Rule[] mRules; - /** - * The estimated maximum length. - */ - private transient int mMaxLengthEstimate; - - // Constructor - //----------------------------------------------------------------------- - /** - *

Constructs a new FastDatePrinter.

- * Use {@link FastDateFormat#getInstance(String, TimeZone, Locale)} or another variation of the - * factory methods of {@link FastDateFormat} to get a cached FastDatePrinter instance. - * - * @param pattern {@link java.text.SimpleDateFormat} compatible pattern - * @param timeZone non-null time zone to use - * @param locale non-null locale to use - * @throws NullPointerException if pattern, timeZone, or locale is null. - */ - protected FastDatePrinter(final String pattern, final TimeZone timeZone, final Locale locale) { - mPattern = pattern; - mTimeZone = timeZone; - mLocale = locale; - - init(); - } - - /** - *

Initializes the instance for first use.

- */ - private void init() { - final List rulesList = parsePattern(); - mRules = rulesList.toArray(new Rule[rulesList.size()]); - - int len = 0; - for (int i=mRules.length; --i >= 0; ) { - len += mRules[i].estimateLength(); - } - - mMaxLengthEstimate = len; - } - - // Parse the pattern - //----------------------------------------------------------------------- - /** - *

Returns a list of Rules given a pattern.

- * - * @return a {@code List} of Rule objects - * @throws IllegalArgumentException if pattern is invalid - */ - protected List parsePattern() { - final DateFormatSymbols symbols = new DateFormatSymbols(mLocale); - final List rules = new ArrayList(); - - final String[] ERAs = symbols.getEras(); - final String[] months = symbols.getMonths(); - final String[] shortMonths = symbols.getShortMonths(); - final String[] weekdays = symbols.getWeekdays(); - final String[] shortWeekdays = symbols.getShortWeekdays(); - final String[] AmPmStrings = symbols.getAmPmStrings(); - - final int length = mPattern.length(); - final int[] indexRef = new int[1]; - - for (int i = 0; i < length; i++) { - indexRef[0] = i; - final String token = parseToken(mPattern, indexRef); - i = indexRef[0]; - - final int tokenLen = token.length(); - if (tokenLen == 0) { - break; - } - - Rule rule; - final char c = token.charAt(0); - - switch (c) { - case 'G': // era designator (text) - rule = new TextField(Calendar.ERA, ERAs); - break; - case 'y': // year (number) - if (tokenLen == 2) { - rule = TwoDigitYearField.INSTANCE; - } else { - rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen); - } - break; - case 'M': // month in year (text and number) - if (tokenLen >= 4) { - rule = new TextField(Calendar.MONTH, months); - } else if (tokenLen == 3) { - rule = new TextField(Calendar.MONTH, shortMonths); - } else if (tokenLen == 2) { - rule = TwoDigitMonthField.INSTANCE; - } else { - rule = UnpaddedMonthField.INSTANCE; - } - break; - case 'd': // day in month (number) - rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); - break; - case 'h': // hour in am/pm (number, 1..12) - rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); - break; - case 'H': // hour in day (number, 0..23) - rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); - break; - case 'm': // minute in hour (number) - rule = selectNumberRule(Calendar.MINUTE, tokenLen); - break; - case 's': // second in minute (number) - rule = selectNumberRule(Calendar.SECOND, tokenLen); - break; - case 'S': // millisecond (number) - rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); - break; - case 'E': // day in week (text) - rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); - break; - case 'D': // day in year (number) - rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); - break; - case 'F': // day of week in month (number) - rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); - break; - case 'w': // week in year (number) - rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); - break; - case 'W': // week in month (number) - rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); - break; - case 'a': // am/pm marker (text) - rule = new TextField(Calendar.AM_PM, AmPmStrings); - break; - case 'k': // hour in day (1..24) - rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); - break; - case 'K': // hour in am/pm (0..11) - rule = selectNumberRule(Calendar.HOUR, tokenLen); - break; - case 'X': // ISO 8601 - rule = Iso8601_Rule.getRule(tokenLen); - break; - case 'z': // time zone (text) - if (tokenLen >= 4) { - rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG); - } else { - rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT); - } - break; - case 'Z': // time zone (value) - if (tokenLen == 1) { - rule = TimeZoneNumberRule.INSTANCE_NO_COLON; - } else if (tokenLen == 2) { - rule = Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES; - } else { - rule = TimeZoneNumberRule.INSTANCE_COLON; - } - break; - case '\'': // literal text - final String sub = token.substring(1); - if (sub.length() == 1) { - rule = new CharacterLiteral(sub.charAt(0)); - } else { - rule = new StringLiteral(sub); - } - break; - default: - throw new IllegalArgumentException("Illegal pattern component: " + token); - } - - rules.add(rule); - } - - return rules; - } - - /** - *

Performs the parsing of tokens.

- * - * @param pattern the pattern - * @param indexRef index references - * @return parsed token - */ - protected String parseToken(final String pattern, final int[] indexRef) { - final StringBuilder buf = new StringBuilder(); - - int i = indexRef[0]; - final int length = pattern.length(); - - char c = pattern.charAt(i); - if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') { - // Scan a run of the same character, which indicates a time - // pattern. - buf.append(c); - - while (i + 1 < length) { - final char peek = pattern.charAt(i + 1); - if (peek == c) { - buf.append(c); - i++; - } else { - break; - } - } - } else { - // This will identify token as text. - buf.append('\''); - - boolean inLiteral = false; - - for (; i < length; i++) { - c = pattern.charAt(i); - - if (c == '\'') { - if (i + 1 < length && pattern.charAt(i + 1) == '\'') { - // '' is treated as escaped ' - i++; - buf.append(c); - } else { - inLiteral = !inLiteral; - } - } else if (!inLiteral && - (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z')) { - i--; - break; - } else { - buf.append(c); - } - } - } - - indexRef[0] = i; - return buf.toString(); - } - - /** - *

Gets an appropriate rule for the padding required.

- * - * @param field the field to get a rule for - * @param padding the padding required - * @return a new rule with the correct padding - */ - protected NumberRule selectNumberRule(final int field, final int padding) { - switch (padding) { - case 1: - return new UnpaddedNumberField(field); - case 2: - return new TwoDigitNumberField(field); - default: - return new PaddedNumberField(field, padding); - } - } - - // Format methods - //----------------------------------------------------------------------- - /** - *

Formats a {@code Date}, {@code Calendar} or - * {@code Long} (milliseconds) object.

- * - * @param obj the object to format - * @param toAppendTo the buffer to append to - * @param pos the position - ignored - * @return the buffer passed in - */ - @Override - public StringBuffer format(final Object obj, final StringBuffer toAppendTo, final FieldPosition pos) { - if (obj instanceof Date) { - return format((Date) obj, toAppendTo); - } else if (obj instanceof Calendar) { - return format((Calendar) obj, toAppendTo); - } else if (obj instanceof Long) { - return format(((Long) obj).longValue(), toAppendTo); - } else { - throw new IllegalArgumentException("Unknown class: " + - (obj == null ? "" : obj.getClass().getName())); - } - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(long) - */ - @Override - public String format(final long millis) { - final Calendar c = newCalendar(); // hard code GregorianCalendar - c.setTimeInMillis(millis); - return applyRulesToString(c); - } - - /** - * Creates a String representation of the given Calendar by applying the rules of this printer to it. - * @param c the Calender to apply the rules to. - * @return a String representation of the given Calendar. - */ - private String applyRulesToString(final Calendar c) { - return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString(); - } - - /** - * Creation method for ne calender instances. - * @return a new Calendar instance. - */ - private GregorianCalendar newCalendar() { - // hard code GregorianCalendar - return new GregorianCalendar(mTimeZone, mLocale); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date) - */ - @Override - public String format(final Date date) { - final Calendar c = newCalendar(); // hard code GregorianCalendar - c.setTime(date); - return applyRulesToString(c); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar) - */ - @Override - public String format(final Calendar calendar) { - return format(calendar, new StringBuffer(mMaxLengthEstimate)).toString(); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final long millis, final StringBuffer buf) { - return format(new Date(millis), buf); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final Date date, final StringBuffer buf) { - final Calendar c = newCalendar(); // hard code GregorianCalendar - c.setTime(date); - return applyRules(c, buf); - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.StringBuffer) - */ - @Override - public StringBuffer format(final Calendar calendar, final StringBuffer buf) { - // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored - return format(calendar.getTime(), buf); - } - - /** - *

Performs the formatting by applying the rules to the - * specified calendar.

- * - * @param calendar the calendar to format - * @param buf the buffer to format into - * @return the specified string buffer - */ - protected StringBuffer applyRules(final Calendar calendar, final StringBuffer buf) { - for (final Rule rule : mRules) { - rule.appendTo(buf, calendar); - } - return buf; - } - - // Accessors - //----------------------------------------------------------------------- - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#getPattern() - */ - @Override - public String getPattern() { - return mPattern; - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() - */ - @Override - public TimeZone getTimeZone() { - return mTimeZone; - } - - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#getLocale() - */ - @Override - public Locale getLocale() { - return mLocale; - } - - /** - *

Gets an estimate for the maximum string length that the - * formatter will produce.

- * - *

The actual formatted length will almost always be less than or - * equal to this amount.

- * - * @return the maximum formatted length - */ - public int getMaxLengthEstimate() { - return mMaxLengthEstimate; - } - - // Basics - //----------------------------------------------------------------------- - /** - *

Compares two objects for equality.

- * - * @param obj the object to compare to - * @return {@code true} if equal - */ - @Override - public boolean equals(final Object obj) { - if (obj instanceof FastDatePrinter == false) { - return false; - } - final FastDatePrinter other = (FastDatePrinter) obj; - return mPattern.equals(other.mPattern) - && mTimeZone.equals(other.mTimeZone) - && mLocale.equals(other.mLocale); - } - - /** - *

Returns a hashcode compatible with equals.

- * - * @return a hashcode compatible with equals - */ - @Override - public int hashCode() { - return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode()); - } - - /** - *

Gets a debugging string version of this formatter.

- * - * @return a debugging string - */ - @Override - public String toString() { - return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]"; - } - - // Serializing - //----------------------------------------------------------------------- - /** - * Create the object after serialization. This implementation reinitializes the - * transient properties. - * - * @param in ObjectInputStream from which the object is being deserialized. - * @throws IOException if there is an IO issue. - * @throws ClassNotFoundException if a class cannot be found. - */ - private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { - in.defaultReadObject(); - init(); - } - - /** - * Appends digits to the given buffer. - * - * @param buffer the buffer to append to. - * @param value the value to append digits from. - */ - private static void appendDigits(final StringBuffer buffer, final int value) { - buffer.append((char)(value / 10 + '0')); - buffer.append((char)(value % 10 + '0')); - } - - // Rules - //----------------------------------------------------------------------- - /** - *

Inner class defining a rule.

- */ - private interface Rule { - /** - * Returns the estimated length of the result. - * - * @return the estimated length - */ - int estimateLength(); - - /** - * Appends the value of the specified calendar to the output buffer based on the rule implementation. - * - * @param buffer the output buffer - * @param calendar calendar to be appended - */ - void appendTo(StringBuffer buffer, Calendar calendar); - } - - /** - *

Inner class defining a numeric rule.

- */ - private interface NumberRule extends Rule { - /** - * Appends the specified value to the output buffer based on the rule implementation. - * - * @param buffer the output buffer - * @param value the value to be appended - */ - void appendTo(StringBuffer buffer, int value); - } - - /** - *

Inner class to output a constant single character.

- */ - private static class CharacterLiteral implements Rule { - private final char mValue; - - /** - * Constructs a new instance of {@code CharacterLiteral} - * to hold the specified value. - * - * @param value the character literal - */ - CharacterLiteral(final char value) { - mValue = value; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 1; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - buffer.append(mValue); - } - } - - /** - *

Inner class to output a constant string.

- */ - private static class StringLiteral implements Rule { - private final String mValue; - - /** - * Constructs a new instance of {@code StringLiteral} - * to hold the specified value. - * - * @param value the string literal - */ - StringLiteral(final String value) { - mValue = value; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mValue.length(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - buffer.append(mValue); - } - } - - /** - *

Inner class to output one of a set of values.

- */ - private static class TextField implements Rule { - private final int mField; - private final String[] mValues; - - /** - * Constructs an instance of {@code TextField} - * with the specified field and values. - * - * @param field the field - * @param values the field values - */ - TextField(final int field, final String[] values) { - mField = field; - mValues = values; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - int max = 0; - for (int i=mValues.length; --i >= 0; ) { - final int len = mValues[i].length(); - if (len > max) { - max = len; - } - } - return max; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - buffer.append(mValues[calendar.get(mField)]); - } - } - - /** - *

Inner class to output an unpadded number.

- */ - private static class UnpaddedNumberField implements NumberRule { - private final int mField; - - /** - * Constructs an instance of {@code UnpadedNumberField} with the specified field. - * - * @param field the field - */ - UnpaddedNumberField(final int field) { - mField = field; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 4; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - if (value < 10) { - buffer.append((char)(value + '0')); - } else if (value < 100) { - appendDigits(buffer, value); - } else { - buffer.append(value); - } - } - } - - /** - *

Inner class to output an unpadded month.

- */ - private static class UnpaddedMonthField implements NumberRule { - static final UnpaddedMonthField INSTANCE = new UnpaddedMonthField(); - - /** - * Constructs an instance of {@code UnpaddedMonthField}. - * - */ - UnpaddedMonthField() { - super(); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(Calendar.MONTH) + 1); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - if (value < 10) { - buffer.append((char)(value + '0')); - } else { - appendDigits(buffer, value); - } - } - } - - /** - *

Inner class to output a padded number.

- */ - private static class PaddedNumberField implements NumberRule { - private final int mField; - private final int mSize; - - /** - * Constructs an instance of {@code PaddedNumberField}. - * - * @param field the field - * @param size size of the output field - */ - PaddedNumberField(final int field, final int size) { - if (size < 3) { - // Should use UnpaddedNumberField or TwoDigitNumberField. - throw new IllegalArgumentException(); - } - mField = field; - mSize = size; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mSize; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, int value) { - // pad the buffer with adequate zeros - for(int digit = 0; digit0; value /= 10) { - buffer.setCharAt(--index, (char)('0' + value % 10)); - } - } - } - - /** - *

Inner class to output a two digit number.

- */ - private static class TwoDigitNumberField implements NumberRule { - private final int mField; - - /** - * Constructs an instance of {@code TwoDigitNumberField} with the specified field. - * - * @param field the field - */ - TwoDigitNumberField(final int field) { - mField = field; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(mField)); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - if (value < 100) { - appendDigits(buffer, value); - } else { - buffer.append(value); - } - } - } - - /** - *

Inner class to output a two digit year.

- */ - private static class TwoDigitYearField implements NumberRule { - static final TwoDigitYearField INSTANCE = new TwoDigitYearField(); - - /** - * Constructs an instance of {@code TwoDigitYearField}. - */ - TwoDigitYearField() { - super(); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(Calendar.YEAR) % 100); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - appendDigits(buffer, value); - } - } - - /** - *

Inner class to output a two digit month.

- */ - private static class TwoDigitMonthField implements NumberRule { - static final TwoDigitMonthField INSTANCE = new TwoDigitMonthField(); - - /** - * Constructs an instance of {@code TwoDigitMonthField}. - */ - TwoDigitMonthField() { - super(); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 2; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - appendTo(buffer, calendar.get(Calendar.MONTH) + 1); - } - - /** - * {@inheritDoc} - */ - @Override - public final void appendTo(final StringBuffer buffer, final int value) { - appendDigits(buffer, value); - } - } - - /** - *

Inner class to output the twelve hour field.

- */ - private static class TwelveHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance of {@code TwelveHourField} with the specified - * {@code NumberRule}. - * - * @param rule the rule - */ - TwelveHourField(final NumberRule rule) { - mRule = rule; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - int value = calendar.get(Calendar.HOUR); - if (value == 0) { - value = calendar.getLeastMaximum(Calendar.HOUR) + 1; - } - mRule.appendTo(buffer, value); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final int value) { - mRule.appendTo(buffer, value); - } - } - - /** - *

Inner class to output the twenty four hour field.

- */ - private static class TwentyFourHourField implements NumberRule { - private final NumberRule mRule; - - /** - * Constructs an instance of {@code TwentyFourHourField} with the specified - * {@code NumberRule}. - * - * @param rule the rule - */ - TwentyFourHourField(final NumberRule rule) { - mRule = rule; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return mRule.estimateLength(); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - int value = calendar.get(Calendar.HOUR_OF_DAY); - if (value == 0) { - value = calendar.getMaximum(Calendar.HOUR_OF_DAY) + 1; - } - mRule.appendTo(buffer, value); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final int value) { - mRule.appendTo(buffer, value); - } - } - - //----------------------------------------------------------------------- - - private static final ConcurrentMap cTimeZoneDisplayCache = - new ConcurrentHashMap(7); - /** - *

Gets the time zone display name, using a cache for performance.

- * - * @param tz the zone to query - * @param daylight true if daylight savings - * @param style the style to use {@code TimeZone.LONG} or {@code TimeZone.SHORT} - * @param locale the locale to use - * @return the textual name of the time zone - */ - static String getTimeZoneDisplay(final TimeZone tz, final boolean daylight, final int style, final Locale locale) { - final TimeZoneDisplayKey key = new TimeZoneDisplayKey(tz, daylight, style, locale); - String value = cTimeZoneDisplayCache.get(key); - if (value == null) { - // This is a very slow call, so cache the results. - value = tz.getDisplayName(daylight, style, locale); - final String prior = cTimeZoneDisplayCache.putIfAbsent(key, value); - if (prior != null) { - value= prior; - } - } - return value; - } - - /** - *

Inner class to output a time zone name.

- */ - private static class TimeZoneNameRule implements Rule { - private final Locale mLocale; - private final int mStyle; - private final String mStandard; - private final String mDaylight; - - /** - * Constructs an instance of {@code TimeZoneNameRule} with the specified properties. - * - * @param timeZone the time zone - * @param locale the locale - * @param style the style - */ - TimeZoneNameRule(final TimeZone timeZone, final Locale locale, final int style) { - mLocale = locale; - mStyle = style; - - mStandard = getTimeZoneDisplay(timeZone, false, style, locale); - mDaylight = getTimeZoneDisplay(timeZone, true, style, locale); - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - // We have no access to the Calendar object that will be passed to - // appendTo so base estimate on the TimeZone passed to the - // constructor - return Math.max(mStandard.length(), mDaylight.length()); - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - final TimeZone zone = calendar.getTimeZone(); - if (calendar.get(Calendar.DST_OFFSET) != 0) { - buffer.append(getTimeZoneDisplay(zone, true, mStyle, mLocale)); - } else { - buffer.append(getTimeZoneDisplay(zone, false, mStyle, mLocale)); - } - } - } - - /** - *

Inner class to output a time zone as a number {@code +/-HHMM} - * or {@code +/-HH:MM}.

- */ - private static class TimeZoneNumberRule implements Rule { - static final TimeZoneNumberRule INSTANCE_COLON = new TimeZoneNumberRule(true); - static final TimeZoneNumberRule INSTANCE_NO_COLON = new TimeZoneNumberRule(false); - - final boolean mColon; - - /** - * Constructs an instance of {@code TimeZoneNumberRule} with the specified properties. - * - * @param colon add colon between HH and MM in the output if {@code true} - */ - TimeZoneNumberRule(final boolean colon) { - mColon = colon; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return 5; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - - if (offset < 0) { - buffer.append('-'); - offset = -offset; - } else { - buffer.append('+'); - } - - final int hours = offset / (60 * 60 * 1000); - appendDigits(buffer, hours); - - if (mColon) { - buffer.append(':'); - } - - final int minutes = offset / (60 * 1000) - 60 * hours; - appendDigits(buffer, minutes); - } - } - - /** - *

Inner class to output a time zone as a number {@code +/-HHMM} - * or {@code +/-HH:MM}.

- */ - private static class Iso8601_Rule implements Rule { - - // Sign TwoDigitHours or Z - static final Iso8601_Rule ISO8601_HOURS = new Iso8601_Rule(3); - // Sign TwoDigitHours Minutes or Z - static final Iso8601_Rule ISO8601_HOURS_MINUTES = new Iso8601_Rule(5); - // Sign TwoDigitHours : Minutes or Z - static final Iso8601_Rule ISO8601_HOURS_COLON_MINUTES = new Iso8601_Rule(6); - - /** - * Factory method for Iso8601_Rules. - * - * @param tokenLen a token indicating the length of the TimeZone String to be formatted. - * @return a Iso8601_Rule that can format TimeZone String of length {@code tokenLen}. If no such - * rule exists, an IllegalArgumentException will be thrown. - */ - static Iso8601_Rule getRule(int tokenLen) { - switch(tokenLen) { - case 1: - return Iso8601_Rule.ISO8601_HOURS; - case 2: - return Iso8601_Rule.ISO8601_HOURS_MINUTES; - case 3: - return Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES; - default: - throw new IllegalArgumentException("invalid number of X"); - } - } - - final int length; - - /** - * Constructs an instance of {@code Iso8601_Rule} with the specified properties. - * - * @param length The number of characters in output (unless Z is output) - */ - Iso8601_Rule(final int length) { - this.length = length; - } - - /** - * {@inheritDoc} - */ - @Override - public int estimateLength() { - return length; - } - - /** - * {@inheritDoc} - */ - @Override - public void appendTo(final StringBuffer buffer, final Calendar calendar) { - int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); - if (offset == 0) { - buffer.append("Z"); - return; - } - - if (offset < 0) { - buffer.append('-'); - offset = -offset; - } else { - buffer.append('+'); - } - - final int hours = offset / (60 * 60 * 1000); - appendDigits(buffer, hours); - - if (length<5) { - return; - } - - if (length==6) { - buffer.append(':'); - } - - final int minutes = offset / (60 * 1000) - 60 * hours; - appendDigits(buffer, minutes); - } - } - - // ---------------------------------------------------------------------- - /** - *

Inner class that acts as a compound key for time zone names.

- */ - private static class TimeZoneDisplayKey { - private final TimeZone mTimeZone; - private final int mStyle; - private final Locale mLocale; - - /** - * Constructs an instance of {@code TimeZoneDisplayKey} with the specified properties. - * - * @param timeZone the time zone - * @param daylight adjust the style for daylight saving time if {@code true} - * @param style the timezone style - * @param locale the timezone locale - */ - TimeZoneDisplayKey(final TimeZone timeZone, - final boolean daylight, final int style, final Locale locale) { - mTimeZone = timeZone; - if (daylight) { - mStyle = style | 0x80000000; - } else { - mStyle = style; - } - mLocale = locale; - } - - /** - * {@inheritDoc} - */ - @Override - public int hashCode() { - return (mStyle * 31 + mLocale.hashCode() ) * 31 + mTimeZone.hashCode(); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean equals(final Object obj) { - if (this == obj) { - return true; - } - if (obj instanceof TimeZoneDisplayKey) { - final TimeZoneDisplayKey other = (TimeZoneDisplayKey)obj; - return - mTimeZone.equals(other.mTimeZone) && - mStyle == other.mStyle && - mLocale.equals(other.mLocale); - } - return false; - } - } -} diff --git a/All/Genesis-OOB/Genesis#34/old/changes.xml b/All/Genesis-OOB/Genesis#34/old/changes.xml deleted file mode 100755 index 9e14f45..0000000 --- a/All/Genesis-OOB/Genesis#34/old/changes.xml +++ /dev/null @@ -1,807 +0,0 @@ - - - - - Apache Commons Lang Changes - - - - - Implement ParsePosition api for FastDateParser - StrLookup.systemPropertiesLookup() no longer reacts on changes on system properties - EnumUtils *BitVector issue with more than 32 values Enum - Capitalize javadoc is incorrect - Add check for duplicate event listener in EventListenerSupport - FastDateParser_TimeZoneStrategyTest#testTimeZoneStrategyPattern fails on Windows with German Locale - Add method containsAllWords to WordUtils - ReflectionToStringBuilder doesn't throw IllegalArgumentException when the constructor's object param is null - Inconsistent behavior of swap for malformed inputs - StringUtils join with var args - Fix critical issues reported by SonarQube - StrBuilder.equals(StrBuilder) doesn't check for null inputs - Add ThreadUtils - A utility class which provides helper methods related to java.lang.Thread - Add annotations to exclude fields from ReflectionEqualsBuilder, ReflectionToStringBuilder and ReflectionHashCodeBuilder - Use JUnit rules to set and reset the default Locale and TimeZone - JsonToStringStyle doesn't handle chars and objects correctly - HashCodeBuilder throws StackOverflowError in bidirectional navigable association - DateFormatUtilsTest.testSMTP depends on the default Locale - Unit test FastDatePrinterTimeZonesTest needs a timezone set - CLONE - DateFormatUtils.format does not correctly change Calendar TimeZone in certain situations - DateUtilsTest.testLang530 fails for some timezones - TypeUtils.ParameterizedType#equals doesn't work with wildcard types - Add rotate(string, int) method to StringUtils - StringUtils.repeat('z', -1) throws NegativeArraySizeException - Add swap and shift operations for arrays to ArrayUtils - TypeUtils.parameterizeWithOwner - wrong format descriptor for "invalid number of type parameters". - MultilineRecursiveToStringStyle largely unusable due to being package-private. - StringUtils.uncapitalize performance improvement - CharSet.getInstance documentation does not clearly explain how to include negation character in set - Change nullToEmpty methods to generics - Fix FindBugs warnings in DurationFormatUtils - Add a method to ArrayUtils for removing all occurrences of a given element - Fix parsing edge cases in FastDateParser - - - - Support OS X versions in SystemUtils - SystemUtils.IS_OS_WINDOWS_2008, VISTA are incorrect - Parse test fails for TimeZone America/Sao_Paulo - Add SystemUtils.IS_JAVA_1_9 - Make logic for comparing OS versions in SystemUtils smarter - Shutdown thread pools in test cases - FastDateParser and FastDatePrinter support 'X' format - Avoid memory allocation when using date formating to StringBuffer - Possible performance improvement on string escape functions - Exception while using ExtendedMessageFormat and escaping braces - Avoid String allocation in StrBuilder.append(CharSequence) - Update maven-checkstyle-plugin to 2.14 - Update org.easymock:easymock to 3.3.1 - Update maven-pmd-plugin to 3.4 - Update maven-antrun-plugin to 1.8 - Wrong formating of time zones with daylight saving time in FastDatePrinter - Performance improvements for StringEscapeUtils - Add ClassUtils.getAbbreviatedName() - FastDateParser does not set error indication in ParsePosition - FastDateParser does not handle excess hours as per SimpleDateFormat - FastDateParser error - timezones not handled correctly - NumberUtils#createNumber() returns positive BigDecimal when negative Float is expected - DiffBuilder.append(String, Object left, Object right) does not do a left.equals(right) check - StrSubstitutor.replaceSystemProperties does not work consistently - Add option to disable the "objectsTriviallyEqual" test in DiffBuilder - Add (T) casts to get unit tests to pass in old JDK - Add JsonToStringStyle implementation to ToStringStyle - Add NoClassNameToStringStyle implementation of ToStringStyle - Fix wrong examples in JavaDoc of StringUtils.replaceEachRepeatedly(...), StringUtils.replaceEach(...) - Add StringUtils.containsAny(CharSequence, CharSequence...) method - Read wrong component type of array in add in ArrayUtils - StringUtils.ordinalIndexOf("aaaaaa", "aa", 2) != 3 in StringUtils - Duplicated "0x" check in createBigInteger in NumberUtils - StringUtils.abbreviate description doesn't agree with the examples - Multiline recursive to string style - Add isSorted() to ArrayUtils - Fix MethodUtilsTest so it does not depend on JDK method ordering - CompareToBuilder's doc doesn't specify precedence of fields it uses in performing comparisons - ParseException when trying to parse UTC dates with Z as zone designator using DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT - Javadoc for EqualsBuilder.reflectionEquals() is unclear - Improve performance of normalize space - Add StringUtils.countMatches(CharSequence, char) - org.apache.commons.lang3.SystemUtils#isJavaVersionAtLeast should return true by default - Provide methods to retrieve all fields/methods annotated with a specific type - Bring static method references in StringUtils to consistent style - NumberUtils#isParsable method(s) - Use non-ASCII digits in Javadoc examples for StringUtils.isNumeric - Change min/max methods in NumberUtils/IEEE754rUtils from array input parameters to varargs - Add fuzzy String matching logic to StringUtils - Add wrap (with String or char) to StringUtils - Extend DurationFormatUtils#formatDurationISO default pattern to match #formatDurationHMS - Fixing NumberUtils JAVADoc comments for max methods - Better Javadoc for BitField class - DurationFormatUtils#formatDurationHMS implementation does not correspond to Javadoc and vice versa - DurationFormatUtils are not able to handle negative durations/periods - ISO 8601 misspelled throughout the Javadocs - Add zero copy read method to StrBuilder - Add zero copy write method to StrBuilder - Javadoc is not clear on preferred pattern to instantiate FastDateParser / FastDatePrinter - FastDateParser should be case insensitive - Fix bug with stripping spaces on last line in WordUtils.wrap() - Add method org.apache.commons.lang3.reflect.MethodUtils.invokeExactMethod(Object, String) - Add method org.apache.commons.lang3.reflect.MethodUtils.invokeMethod(Object, String) - - - - NumberUtils#isNumber() returns false for "0.0", "0.4790", et al - Add org.apache.commons.lang3.SystemUtils.IS_JAVA_1_8 - - - - DateUtils.getFragmentInDays(Date, Calendar.MONTH) returns wrong days - DurationFormatUtils does not describe format string fully - DurationFormatUtils#lexx does not detect unmatched quote char - DurationFormatUtils does not handle large durations correctly - DurationFormatUtils.formatDuration(61999, "s.SSSS") - ms field size should be 4 digits - Failing tests with Java 8 b128 - - - - ReflectionToStringBuilder.toString does not debug 3rd party object fields within 3rd party object - Add methods for removing all invalid characters according to XML 1.0 and XML 1.1 in an input string to StringEscapeUtils - NumericEntityEscaper incorrectly encodes supplementary characters - Make some private fields final - NumberUtils#isNumber(String) fails to reject invalid Octal numbers - NumberUtils#isNumber does not allow for hex 0XABCD - StringUtils.toEncodedString(byte[], Charset) needlessly throws UnsupportedEncodingException - Add APIs MutableBoolean setTrue() and setFalse() - ConstantInitializerTest fails when building with IBM JDK 7 - Add SerializationUtils.roundtrip(T extends Serializable) to serialize then deserialize - org.apache.commons.lang3.reflect.FieldUtils.removeFinalModifier(Field) does not clean up after itself - FastDateParser javadoc incorrectly states that SimpleDateFormat is used internally - There should be a DifferenceBuilder with a ReflectionDifferenceBuilder implementation - uncaught PatternSyntaxException in FastDateFormat on Android - Improve JavaDoc of WordUtils.wrap methods - Add the Jaro-Winkler string distance algorithm to StringUtils - StringUtils.getLevenshteinDistance with too big of a threshold returns wrong result - Test DurationFormatUtilsTest.testEdgeDuration fails in JDK 1.6, 1.7 and 1.8, BRST time zone - ConstructorUtils.getAccessibleConstructor() Does Not Check the Accessibility of Enclosing Classes - Fragments are wrong by 1 day when using fragment YEAR or MONTH - New class ClassPathUtils with methods for turning FQN into resource path - Move Documentation from user guide to package-info files - Convert package.html files to package-info.java files - FastDateParser does not handle two digit year parsing like SimpleDateFormat - FastDateParserTest.testParses does not test FastDateParser - Fix deprecation warnings - EnumUtils.generateBitVector needs a "? extends" - Validate: add inclusiveBetween and exclusiveBetween overloads for primitive types - New RandomUtils class - Wrong locale handling in LocaleUtils.toLocale() - Add IBM OS/400 detection - - - - Fix missing Hamcrest dependency in Ant Build - Test failure in LocaleUtilsTest when building with JDK 8 - Test failure in FastDateParserTest and FastDateFormat_ParserTest when building with JDK8 - Build fails with test failures when building with JDK 8 - - - - Add removeFinalModifier to FieldUtils - Method returns number of inheritance hops between parent and subclass - Spelling fixes - Misleading Javadoc comment in StrBuilderReader class - OctalUnescaper tried to parse all of \279 - OctalUnescaper had bugs when parsing octals starting with a zero - EqualsBuilder returned true when comparing arrays, even when the elements are different - Added isStarted, isSuspended and isStopped to StopWatch - Fixed exception when combining custom and choice format in ExtendedMessageFormat - Added StringUtils.isBlank/isEmpty CharSequence... methods - Added ArrayUtils.reverse(array, from, to) methods - StringUtils.toString(byte[], String) deprecated in favour of a new StringUtils.toString(byte[], CharSet) - RandomStringUtils.random javadoc was incorrectly promising letters and numbers would, as opposed to may, appear - BooleanUtils.xor(boolean...) produces wrong results - StringUtils.normalizeSpace now handles non-breaking spaces (Unicode 00A0) - Redundant check for zero in HashCodeBuilder ctor - StrSubstitutor now supports default values for variables - Adding .gitignore to commons-lang - Add ObjectUtils.toIdentityString methods that support StringBuilder, StrBuilder, and Appendable - BooleanUtils.toBoolean(String str) javadoc is not updated - LocaleUtils test fails with new Locale "ja_JP_JP_#u-ca-japanese" of JDK7 - StrSubstitutor does not support StringBuilder or CharSequence - Method createNumber from NumberUtils doesn't work for floating point numbers other than Float - FastDateFormat does not use the locale specific cache correctly - Simplify FastDateFormat; eliminate boxing - LookupTranslator now works with implementations of CharSequence other than String - ClassUtils.getShortName(String) will now only do a reverse lookup for array types - Added CharSetUtils.containsAny(String, String) - Provide CharSequenceUtils.regionMatches with a proper green implementation instead of inefficiently converting to Strings - Added escape/unescapeJson to StringEscapeUtils - Added appendIfMissing and prependIfMissing methods to StringUtils - NumberUtils.createNumber() Javadoc says it does not work for octal numbers - Fixed URLs in javadoc to point to new oracle.com pages - Add StringUtils.LF and StringUtils.CR values - Add FieldUtils getAllFields() to return all the fields defined in the given class and super classes - LocaleUtils.toLocale does not parse strings starting with an underscore - StrBuilder should support StringBuilder as an input parameter - StringEscapeUtils.escapeJava() and escapeEcmaScript() do not output the escaped surrogate pairs that are Java parsable - StringIndexOutOfBoundsException in CharSequenceTranslator - Code refactoring in NumberUtils - NumberUtils#createBigInteger does not allow for hex and octal numbers - NumberUtils#createNumber - does not allow for hex numbers to be larger than Long - StringUtils join APIs for primitives - FastDateFormat and FastDatePrinter generates Date objects wastefully - Spelling fixes - Fix examples contained in javadoc of StringUtils.center methods - Add StringUtils API to call String.replaceAll in DOTALL a.k.a. single-line mode - ArrayUtils removeElements methods use unnecessary HashSet - ArrayUtils removeElements methods clone temporary index arrays unnecessarily - FastDateParser does not handle unterminated quotes correctly - FastDateParser does not handle white-space properly - FastDateParser could use \Q \E to quote regexes - FastDateParser does not handle non-Gregorian calendars properly - FastDateParser does not handle non-ASCII digits correctly - Create StrBuilder APIs similar to String.format(String, Object...) - NumberUtils#createNumber - bad behaviour for leading "--" - FastDateFormat's "z" pattern does not respect timezone of Calendar instances passed to format() - Add org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS_8 - StringUtils.equalsIgnoreCase doesn't check string reference equality - StringUtils.join() endIndex, bugged for loop - RandomStringUtils throws confusing IAE when end <= start - RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException - LocaleUtils - unnecessary recursive call in SyncAvoid class. - Javadoc bug in DateUtils#ceiling for Calendar and Object versions. - DateUtils#parseDate uses default locale; add Locale support - Use generics in SerializationUtils - SerializationUtils throws ClassNotFoundException when cloning primitive classes - StringUtils equals() relies on undefined behavior - Documentation bug: StringUtils.split - jar contains velocity template of release notes - TypeUtilsTest contains incorrect type assignability assertion - TypeUtils.getTypeArguments() misses type arguments for partially-assigned classes - ImmutablePair doc contains nonsense text - ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text - EventListenerSupport.ProxyInvocationHandler no longer defines serialVersionUID - StrBuilder is now serializable - Fix Javadoc Ant warnings - NumberUtils does not handle Long Hex numbers - Javadoc bug in static inner class DateIterator - Add Triple class (ternary version of Pair) - FastDateFormat supports parse methods - - - - Add API StringUtils.toString(byte[] intput, String charsetName) - Add an example with whitespace in StringUtils.defaultIfEmpty - Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and isPrimitiveOrWrapper(Class<?>) - Fix createLong() so it behaves like createInteger() - Include the actual type in the Validate.isInstance and isAssignableFrom exception messages - Incorrect Bundle-SymbolicName in Manifest - Deprecating chomp(String, String) - NumberUtils does not handle upper-case hex: 0X and -0X - StringUtils throws java.security.AccessControlException on Google App Engine - Ant build has wrong component.name - CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY - Document that the Mutable numbers don't work as expected with String.format - SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system - - - - SerializationUtils.clone: Fallback to context classloader if class not found in current classloader. - ToStringBuilderTest.testReflectionHierarchyArrayList fails with IBM JDK 6. - StringEscapeUtils.escapeXml(input) wrong when input contains characters in Supplementary Planes. - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long unicode string. - Improve exception message when StringUtils.replaceEachRepeatedly detects recursion. - Specify source encoding for Ant build. - Complement ArrayUtils.addAll() variants with by-index and by-value removal methods. - Add Range<T> Range<T>.intersectionWith(Range<T>). - Add mode and median Comparable... methods to ObjectUtils. - Add BooleanUtils.and + or varargs methods. - EnumSet -> bit vector. - The CHAR_ARRAY cache in CharUtils duplicates the cache in java.lang.Character. - Deprecate CharUtils.toCharacterObject(char) in favor of java.lang.Character.valueOf(char). - Missing method getRawMessage for ContextedException and ContextedRuntimeException. - Use internal Java's Number caches instead creating new objects. - - - - StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes. - build.xml Java 1.5+ updates. - swapCase and *capitalize speedups. - CharSetUtils.squeeze() speedup. - StringUtils doc/comment spelling fixes. - Increase test coverage of FieldUtils read methods and tweak Javadoc. - Add includeantruntime=false to javac targets to quell warnings in ant 1.8.1 and better (and modest performance gain). - StringIndexOutOfBoundsException when calling unescapeHtml4("&#03"). - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long Unicode string. - StringUtils.join throws NPE when toString returns null for one of objects in collection. - Add FormattableUtils class. - Add ClassUtils.getSimpleName() methods. - Add hashCodeMulti varargs method. - Removed DateUtils.UTC_TIME_ZONE. - Convert more of the StringUtils API to take CharSequence. - EqualsBuilder synchronizes on HashCodeBuilder. - StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for "". - Add support for ConcurrentMap.putIfAbsent(). - Documented potential NPE if auto-boxing occurs for some BooleanUtils methods. - DateUtils.isSameLocalTime compares using 12 hour clock and not 24 hour. - Extend exception handling in ConcurrentUtils to runtime exceptions. - SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - WordUtils.abbreviate() removed. - Doc bug in DateUtils#ceiling. - StringEscapeUtils.unescapeJava doesn't handle octal escapes and Unicode with extra u. - org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k). - org.apache.commons.lang3.math.Fraction does not always succeed in multiplyBy and divideBy. - Change ObjectUtils min() & max() functions to use varargs rather than just two parameters. - Add a Null-safe compare() method to ObjectUtils. - NumberUtils.isNumber(String) is not right when the String is "1.1L". - EntityArrays typo: {"\u2122", "&minus;"}, // minus sign, U+2212 ISOtech. - Some Entitys like &Ouml; are not matched properly against its ISO8859-1 representation. - Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect. - Add StringUtils.defaultIfBlank(). - Provide a very basic ConcurrentInitializer implementation. - Support lazy initialization using atomic variables. - Enhance StrSubstitutor to support nested ${var-${subvr}} expansion. - Provide documentation about the new concurrent package. - Charset may not be threadsafe, because the HashSet is not synch. - StringEscapeUtils.escapeXML() can't process UTF-16 supplementary characters. - StringUtils.endsWithAny method. - Add AnnotationUtils. - BooleanUtils.toBooleanObject to support single character input. - FastDateFormat.format() outputs incorrect week of year because locale isn't respected. - StrSubstitutor should also handle the default properties of a java.util.Properties class. - Javadoc StringUtils.left() claims to throw on negative len, but doesn't. - Add normalizeSpace to StringUtils. - NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - - NOTE: The below were included in the Commons Lang 3.0-beta release. - Convert StringUtils API to take CharSequence. - Push down WordUtils to "text" sub-package. - Extend exception handling in ConcurrentUtils to runtime exceptions. - Some StringUtils methods should take an int character instead of char to use String API features. - EqualsBuilder causes StackOverflowException. - DefaultExceptionContext overwrites values in recursive situations. - ContextedRuntimeException no longer an 'unchecked' exception. - Add Builder Interface / Update Builders to Implement It. - Javadoc is incorrect for public static int lastIndexOf(String str, String searchStr). - ClassUtils.getClass(): Allow Dots as Inner Class Separators. - DateUtils equal & compare functions up to most significant field. - Remove JDK 1.2/1.3 bug handling in StringUtils.indexOf(String, String, int). - Create a basic Pair<L, R> class. - exception.DefaultExceptionContext.getFormattedExceptionMessage catches Throwable. - Provide an implementation of the ThreadFactory interface. - Add new Validate methods. - ArrayUtils.add(T[] array, T element) can create unexpected ClassCastException. - Do the test cases really still require main() and suite() methods?. - @SuppressWarnings("unchecked") is used too generally. - Improve StrLookup API documentation. - Change Java package name. - Change Maven groupId. - New TimedSemaphore class. - Added validState validation method. - Added isAssignableFrom and isInstanceOf validation methods. - Add TypeUtils class to provide utility code for working with generic types. - Replace Range classes with generic version. - Use Iterable on API instead of Collection. - Add methods to Validate to check whether the index is valid for the array/list/string. - Add ability to create a Future for a constant. - Replace StringBuffer with StringBuilder. - Make NumericEntityEscaper immutable. - Compile commons.lang for CDC 1.1/Foundation 1.1. - Add ArrayUtils.toArray to create generic arrays. - Validate: support for validating blank strings. - Add a concurrent package. - Mutable classes should implement an appropriately typed Mutable interface. - Better EnumUtils. - StringEscapeUtils.unescapeJava should support \u+ notation. - Rewrite StringEscapeUtils. - bring ArrayUtils.isEmpty to the generics world. - Add support for background initialization. - Add support for the handling of ExecutionExceptions. - Add StringEscapeUtils.escapeText() methods. - Addition of ContextedException and ContextedRuntimeException. - A generic implementation of the Lazy initialization pattern. - Remove code that does not hold enough value to remain. - Remove code handled now by the JDK. - StrSubstitutor now supports substitution in variable names. - Possible race-conditions in hashCode of the range classes. - StringEscapeUtils.escapeHtml incorrectly converts Unicode characters above U+00FFFF into 2 characters. - Document where in SVN trunk is. - StopWatch does not resist to system time changes. - Fixes for thread safety. - Refactor Validate.java to eliminate code redundancy. - Lower Ascii Characters don't get encoded by Entities.java. - StringUtils.emptyToNull. - StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20). - Remove @deprecateds. - Add ClassUtils.isAssignable() variants with autoboxing. - Improve Javadoc for StringUtils class. - Javadoc incorrect for StringUtils.endsWithIgnoreCase. - Investigate for vararg usages. - JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder). - LeftOf/RightOfNumber in Range convenience methods necessary. - ExceptionUtils not thread-safe. - ObjectUtils.coalesce. - StrBuilder should implement CharSequence and Appendable. - StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanese, etc. - Finally start using generics. - StrBuilder does not implement clone(). - EnumUtils for JDK 5.0. - Wish : method unaccent. - MutableBigDecimal and MutableBigInteger. - StringEscaper.escapeXml() escapes characters > 0x7f. - Depend on JDK 1.5+. - - - - BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String). - ClassUtils: allow Dots as Inner Class Separators in getClass(). - DateUtils: equal and compare functions up to most significant field. - DateUtils: provide a Date to Calendar convenience method. - ObjectUtils: add clone methods to ObjectUtils. - ObjectUtils: add a Null-safe compare() method. - ObjectUtils: add notEqual() method. - StrBuilder: implement clone() method. - StringUtils: add a normalizeSpace() method. - StringUtils: add endsWithAny() method. - StringUtils: add defaultIfBlank() method. - StrSubstitutor: add a replace(String, Properties) variant. - StrSubstitutor: support substitution in variable names. - Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue. - CharSet: make the underlying set synchronized. - CompareToBuilder: fix passing along compareTransients to the reflectionCompare method. - ExtendedMessageFormat doesn't override equals(Object). - FastDateFormat: fix to properly include the locale when formatting a Date. - NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly. - SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading. - Javadoc is incorrect for lastIndexOf() method. - Javadoc for HashCodeBuilder.append(boolean) does not match implementation. - Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't. - Javadoc - document thread safety. - Test for StringUtils replaceChars() icelandic characters. - - - - ArrayUtils - add isNotEmpty() methods. - ArrayUtils - add nullToEmpty() methods. - CharRange - provide an iterator that lets you walk the chars in the range. - CharRange - add more readable static builder methods. - ClassUtils - new isAssignable() methods with autoboxing. - ClassUtils - add support to getShortClassName and getPackageName for arrays. - DateUtils - add ceiling() method. - DateUtils - add parseDateStrictly() method. - EqualsBuilder - add reset() method. - NumberUtils - add toByte() and toShort() methods. - Mutable numbers - add string constructors. - MutableBoolean - add toBoolean(), isTrue() and isFalse() methods. - StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty. - SystemUtils - add IS_OS_WINDOWS_7 constant. - SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7. - StringUtils - add abbreviateMiddle() method. - StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods. - StringUtils - add isAllUpperCase() and isAllLowerCase() methods. - StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method. - StringUtils - add repeat() method. - StringUtils - add startsWithAny() method. - StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods. - New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils. - ArrayUtils - addAll() does not handle mixed types very well. - CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread. - ClassUtils - improving performance of getAllInterfaces. - ClassUtils - toClass() throws NullPointerException on null array element. - DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat. - DateUtils - round() doesn't work correct for Calendar.AM_PM. - DateUtils - improve tests. - Entities - multithreaded initialization. - Entities - missing final modifiers; thread-safety issues. - EnumUtils - getEnum() doesn't work well in 1.5+. - ExceptionUtils - use immutable lock target. - ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes. - FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state. - FastDateFormat - Remove unused field. - LocaleUtils - Initialization of available locales in LocaleUtils can be deferred. - NumberUtils - createNumber() thows a StringIndexOutOfBoundsException when only an "l" is passed in. - NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.'. - StringUtils - improve handling of case-insensitive Strings. - StringUtils - replaceEach() no longer NPEs when null appears in the last String[]. - StringUtils - correct Javadoc for startsWith() and startsWithIgnoreCase(). - StringEscapeUtils - escapeJava() escapes '/' characters. - StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException and returning null. - WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length. - StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity. - Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List. - EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo instead of equals because it creates an inequality with HashCodeBuilder. - HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks. - HashCodeBuilder - Changing the hashCode() method to return toHashCode(). - HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes. - HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments. - ToStringBuilder - make default style thread-safe. - RandomUtils - nextLong() always produces even numbers. - RandomUtils - RandomUtils tests are failing frequently. - - - - ClassUtils.getShortClassName(String) inefficient. - Shouldn't Commons Lang's StringUtils have a "common" string method?. - FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change. - OSGi-ify Lang. - StrBuilder appendFixedWidth does not handle nulls. - infinite loop in Fraction.reduce when numerator == 0. - FastDateFormat thread safety. - ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array. - LocaleUtils.toLocale() rejects strings with only language+variant. - Enum is not thread-safe. - BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException. - ArrayUtils.toClass. - Why does appendIdentityToString return null?. - NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN. - Dates.round() behaves incorrectly for minutes and seconds. - StringUtils.length(String) returns null-safe length. - adding a StringUtils.replace method that takes an array or List of replacement strings. - Adding functionality to DateUtils to allow direct setting of various fields. - Add escaping for CSV columns to StringEscapeUtils. - StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods. - Extension to ClassUtils: Obtain the primitive class from a wrapper. - Javadoc bugs - cannot find object. - Optimize HashCodeBuilder.append(Object). - http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete. - Ambiguous / confusing names in StringUtils replace* methods. - Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils. - Add getStartTime to StopWatch. - Perhaps add containsAny() methods?. - Javadoc Example for EqualsBuilder is questionable. - EqualsBuilder don't compare BigDecimals correctly. - Split camel case strings. - Add Calendar flavour format methods to DateFormatUtils. - Calculating A date fragment in any time-unit. - Memory usage improvement for StringUtils#getLevenshteinDistance(). - Add ExtendedMessageFormat to org.apache.commons.lang.text. - StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly. - Add toArray() method to IntRange and LongRange classes. - add SystemUtils.IS_OS_WINDOWS_VISTA field. - Pointless synchronized in ThreadLocal.initialValue should be removed. - ToStringStyle Javadoc should show examples of styles. - Documentation bug for ignoreEmptyTokens accessors in StrTokenizer. - BooleanUtils toBooleanObject Javadoc does not match implementation. - truncateNicely method which avoids truncating in the middle of a word. - - - - Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions. - NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing. - Null-safe comparison methods for finding most recent / least recent dates. - StopWatch: suspend() acts as split(), if followed by stop(). - StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException. - Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException. - ToStringBuilder throws StackOverflowError when an Object cycle exists. - Create more tests to test out the +=31 replacement code in DurationFormatUtils. - StrBuilder contains usages of thisBuf.length when they should use size. - Enum Javadoc: 1) outline 5.0 native Enum migration 2) warn not to use the switch() , 3) point out approaches for persistence and gui. - Wrong behavior of Entities.unescape. - NumberUtils.createNumber throws NumberFormatException for one digit long. - NullPointerException in isAvailableLocale(Locale). - FastDateFormat.mRules is not transient or serializable. - StringUtils.join should allow you to pass a range for it (so it only joins a part of the array). - Refactor Entities methods. - Tests fail to pass when building with Maven 2. - DurationFormatUtils returns wrong result. - unescapeXml("&12345678;") should be "&12345678;". - Optimize StringEscapeUtils.unescapeXml(String). - BooleanUtils isNotTrue/isNotFalse. - Extra StrBuilder methods. - Add a pair of StringUtils.substringsBetween;String[] methods. - HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle. - Wish for StringUtils.join(Collection, *). - - - - StrBuilderTest#testReplaceStringString fails. - EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null. - Serialization - not backwards compatible. - Replace Clover with Cobertura. - ValuedEnum.compareTo(Object other) not typesafe - it easily could be... - LocaleUtils test fails under Mustang. - Javadoc example for StringUtils.splitByWholeSeparator incorrect. - PADDING array in StringUtils overflows on '\uffff'. - ClassUtils.primitiveToWrapper and Void. - unit test for org.apache.commons.lang.text.StrBuilder. - DateUtils.truncate method is buggy when dealing with DST switching hours. - RandomStringUtils.random() family of methods create invalid Unicode sequences. - StringUtils#getLevenshteinDistance() performance is sub-optimal. - Wrong length check in StrTokenizer.StringMatcher. - ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable. - FastDateFormat: wrong format for date "01.01.1000". - Unclear Javadoc for DateUtils.iterator(). - Memory "leak" in StringUtils. - StringEscapeUtils should expose escape*() methods taking Writer argument. - Fraction.toProperString() returns -1/1 for -1. - DurationFormatUtils.formatDurationWords "11 <unit>s" gets converted to "11 <unit>". - Performance modifications on StringUtils.replace. - StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand. - DurationFormatUtils.formatPeriod() returns the wrong result. - Request for MutableBoolean implementation. - New method for EqualsBuilder. - New ExceptionUtils method setCause(). - Add Mutable<Type> to<Type>() methods. - Provides a Class.getPublicMethod which returns public invocable Method. - Using ReflectionToStringBuilder and excluding secure fields. - add generic add method to DateUtils. - Tokenizer Enhancements: reset input string, static CSV/TSV factories. - Trivial cleanup of Javadoc in various files. - CompositeFormat. - Performance boost for RandomStringUtils. - Enhanced Class.forName version. - Add StringUtils.containsIgnoreCase(...). - Support char array converters on ArrayUtils. - DurationFormatUtils.formatDurationISO() Javadoc is missing T in duration string between date and time part. - Minor build and checkstyle changes. - Javadoc errors on StringUtils.splitPreserveAllTokens(String, char). - EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to &apos;. - Add methods and tests to StrBuilder. - replace() length calculation improvement. - New interpolation features. - Implementation of escape/unescapeHtml methods with Writer. - CompareToBuilder excludeFields for reflection method. - Add WordUtils.getInitials(String). - Error in an example in the Javadoc of the StringUtils.splitPreserveAllTokens() method. - ToStringBuilder/HashCodeBuilder Javadoc code examples. - Cannot build tests from latest SVN. - minor Javadoc improvements for StringUtils.stripXxx() methods. - Javadoc for StringUtils.removeEnd is incorrect. - Minor tweak to fix of bug # 26616. - - - - make optional parameters in FastDateFormat really optional. - Nestable.indexOfThrowable(Class) uses Class.equals() to match. - buffer under/overrun on Strings.strip, stripStart & stripEnd. - ToStringStyle.setArrayEnd(String) doesn't replace null with empty string. - New class proposal: CharacterEncoding. - SystemUtils fails init on HP-UX. - Javadoc - 'four basic XML entities' should be 5 (apos is missing). - o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0. - StringEscapeUtils.unescapeHtml() doesn't handle an empty entity. - EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class. - Method enums.Enum.equals(Object o) doesn't work correctly. - ExceptionUtils.addCauseMethodName(String) does not check for duplicates. - Make StopWatch validate state transitions. - enum package is not compatible with 1.5 jdk. - WordUtils capitalizeFully() throws a null pointer exception. - ValuedEnum. - parseDate class from HttpClient's DateParser class. - ArrayUtils.isEquals() throws ClassCastException when array1 and array2 are different dimension. - ClassCastException in Enum.equals(Object). - FastDateFormat year bug. - unbalanced ReflectionToStringBuilder. - FastDateFormat.getDateInstance(int, Locale) always uses the pattern from the first invocation. - ReflectionToStringBuilder.toString(null) throws exception by design. - Make ClassUtils methods null-safe and not throw an IAE. - StringUtils.split ignores empty items. - EqualsBuilder.append(Object[], Object[]) throws NPE. - ArrayUtils.addAll doesn't always return new array. - Enum.equals does not handle different class loaders. - Add SystemUtils.AWT_TOOLKIT and others. - Throwable cause for NotImplementedException. - ClassUtils.primitivesToWrappers method. - public static boolean DateUtils.equals(Date dt1, Date dt2) ?. - Documentation error in StringUtils.replace. - DateUtils constants should be long. - DateUtils.truncate() is off by one hour when using a date in DST switch 'zone'. - StringEscapeUtils.unescapeHtml() doesn't handle hex entities. - new StringUtils.replaceChars behaves differently from old CharSetUtils.translate. - last substring returned by StringUtils.split( String, String, int ) is too long. - Can't subclass EqualsBuilder because isEquals is private. - new StringUtils.split methods that split on the whole separator string. - New method for converting a primitive Class to its corresponding wrapper Class. - Add convenience format(long) methods to FastDateFormat. - Enum's outer class may not be loaded for EnumUtils. - WordUtils.capitalizeFully(String str) should take a delimiter. - Make Javadoc crosslinking configurable. - Minor Javadoc fixes for StringUtils.contains(String, String). - Error in Javadoc for StringUtils.chomp(String, String). - StringUtils.defaultString: Documentation error. - Add hashCode-support to class ObjectUtils. - add another "known method" to ExceptionUtils. - Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES. - DateUtils.truncate oddity at the far end of the Date spectrum. - add getLength() method to ArrayUtils. - Validate.java: fixes comment skew, removes unused loop counter. - StringUtils.isAsciiPrintable(). - ExceptionUtils: new getCause() methodname (for tomcat-exception). - fixes 75 typos. - mutable numbers. - Javadoc fixes for ClassUtils. - Add StringUtils.nIndexOf?. - Javadoc fixes for CharSetUtils. - Remove redundant check for null separator in StringUtils#join. - Class and Package Comparators for ClassUtils. - add remove methods to ArrayUtils. - WordUtils capitalize improvement. - add isEmpty method to ArrayUtils. - lang.math.Fraction class deficiencies. - Add methods to ArrayUtils: add at end and insert-like ops. - Add SystemUtils methods for directory properties. - Add method that validates Collection elements are a certain type. - elapsed time formatting utility method. - - - - Infinite loop in ToStringBuilder.reflectionToString for inner classes. - NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08. - Rationalize StringUtils slice functions. - SystemUtils.IS_OS_OS2 Javadoc is wrong. - A small, but important Javadoc fix for Fraction proper whole and numerator. - Adding tolerance to double[] search methods in ArrayUtils. - lang.builder classes Javadoc edits (mostly typo fixes). - StringUtils Javadoc and test enhancements. - SystemUtils.IS_OS_*, IS_JAVA_* are always false. - Improve util.Validate tests. - maven-beta10 checkstyle problem. - StringUtils.chopNewLine - StringIndexOutOfBoundsException. - ToStringBuilder doesn't work well in subclasses. - static option for reversing the stacktrace. - NullPointerException in CompareToBuilder. - RandomStringUtils.randomAlpha methods omit 'z'. - test.time fails in Japanese (non-us) locale. - NumberUtils.isNumber allows illegal trailing characters. - Improve Javadoc and overflow behavior of Fraction. - RandomStringUtils infloops with length > 1. - test.lang fails if compiled with non iso-8859-1 locales. - SystemUtils does not play nice in an Applet. - time unit tests fail on Sundays. - java.lang.ExceptionInInitializerError thrown by JVMRandom constructor. - StringUtils.chomp does not match Perl. - patch and test case fixing problem with RandomStringUtils.random(). - General case: infinite loop: ToStringBuilder.reflectionToString. - Should ToStringBuilder.reflectionToString handle arrays?. - EnumUtils nit: The import java.io.Serializable is never used. - Example in Javadoc for ToStringBuilder wrong for append. - Added class hierarchy support to HashCodeBuilder.reflectionHashCode(). - ExceptionUtils new methods. - Infinite loop in StringUtils.replace(text, repl, with) + FIX. - StackOverflow due to ToStringBuilder. - No Javadoc for NestableDelegate. - Specify initial size for Enum's HashMap. - Enum does not support inner sub-classes. - Removed compile warning in ObjectUtils. - SystemUtils.IS_JAVA_1_5 Javadoc is wrong. - NumberRange inaccurate for Long, etc. - Hierarchy support in ToStringBuilder.reflectionToString(). - StringUtils.countMatches loops forever if substring empty. - Javadoc fixes (remove @links to non-public identifiers). - Add Javadoc examples and tests for StringUtils. - Make NumberUtils null handling consistent. - Unused field 'startFinal' in DateIterator. - reduce object creation in ToStringBuilder. - Improved tests, Javadoc for CharSetUtils, StringEscapeUtils. - NumberUtils min/max, BooleanUtils.xor, and ArrayUtils toPrimitive and toObject. - Javadoc, tests improvements for CharSet, CharSetUtils. - StringUtil enhancement. - Javadoc nit. - Additional Lang Method Suggestions. - Make NestableDelegate methods public instead of package private. - Missing @since tags. - Refactored reflection feature of ToStringBuilder into new ReflectionToStringBuilder. - Typo in documentation. - Patch for Javadoc. - Add join(..., char c) to StringUtils (and some performance fixes). Even contains tests!. - Resurrect the WordWrapUtils from commons-sandbox/utils. - EnumTest fails on Linux Sun JDK 1.3.0. - What to do with FastDateFormat unused private constructors. - Added class hierarchy support to CompareToBuilder.reflectionCompare(). - Removed compile warning in FastDateFormat. - typo in the Javadoc example code. - MethodUtils: Removed unused code/unused local vars. - Hierarchy support in EqualsBuilder.reflectionEquals(). - Javadoc Errata. - ArrayUtils.contains(). - More flexibility for getRootCause in ExceptionUtils. - - - - NumberRange.getMaximum returns minimum. - Enum constructor validations. - NestableException/Delegate is not serializable. - split using null and max less than actual token count adds "null". - ExceptionUtils cannot handle J2EE-Exception in a default way. - - - - - - - diff --git a/All/Genesis-OOB/Genesis#34/pair.info b/All/Genesis-OOB/Genesis#34/pair.info deleted file mode 100755 index 4cfdb51..0000000 --- a/All/Genesis-OOB/Genesis#34/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:34 -SATName:Genesis -modifiedFPath:src/main/java/org/apache/commons/lang3/time/FastDatePrinter.java -comSha:52b46e74dd29eb3eb65a593a872fd57694bc154c -parentComSha:52b46e74dd29eb3eb65a593a872fd57694bc154c^1 -githubUrl:https://github.com/apache/commons-lang -repoName:apache#commons-lang \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#35/comMsg.txt b/All/Genesis-OOB/Genesis#35/comMsg.txt deleted file mode 100755 index 3ff45d9..0000000 --- a/All/Genesis-OOB/Genesis#35/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -[LANG-857] StringIndexOutOfBoundsException in CharSequenceTranslator. diff --git a/All/Genesis-OOB/Genesis#35/diff.diff b/All/Genesis-OOB/Genesis#35/diff.diff deleted file mode 100755 index 6432cd5..0000000 --- a/All/Genesis-OOB/Genesis#35/diff.diff +++ /dev/null @@ -1,7 +0,0 @@ -diff --git a/src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java b/src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java -index 4d010ea..0500460 100644 ---- a/src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java -+++ b/src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java -@@ -95 +95 @@ public final void translate(CharSequence input, Writer out) throws IOException { -- pos += Character.charCount(Character.codePointAt(input, pos)); -+ pos += Character.charCount(Character.codePointAt(input, pt)); diff --git a/All/Genesis-OOB/Genesis#35/new/CharSequenceTranslator.java b/All/Genesis-OOB/Genesis#35/new/CharSequenceTranslator.java deleted file mode 100755 index 0500460..0000000 --- a/All/Genesis-OOB/Genesis#35/new/CharSequenceTranslator.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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.commons.lang3.text.translate; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Locale; - -/** - * An API for translating text. - * Its core use is to escape and unescape text. Because escaping and unescaping - * is completely contextual, the API does not present two separate signatures. - * - * @since 3.0 - * @version $Id$ - */ -public abstract class CharSequenceTranslator { - - /** - * Translate a set of codepoints, represented by an int index into a CharSequence, - * into another set of codepoints. The number of codepoints consumed must be returned, - * and the only IOExceptions thrown must be from interacting with the Writer so that - * the top level API may reliable ignore StringWriter IOExceptions. - * - * @param input CharSequence that is being translated - * @param index int representing the current point of translation - * @param out Writer to translate the text to - * @return int count of codepoints consumed - * @throws IOException if and only if the Writer produces an IOException - */ - public abstract int translate(CharSequence input, int index, Writer out) throws IOException; - - /** - * Helper for non-Writer usage. - * @param input CharSequence to be translated - * @return String output of translation - */ - public final String translate(CharSequence input) { - if (input == null) { - return null; - } - try { - StringWriter writer = new StringWriter(input.length() * 2); - translate(input, writer); - return writer.toString(); - } catch (IOException ioe) { - // this should never ever happen while writing to a StringWriter - throw new RuntimeException(ioe); - } - } - - /** - * Translate an input onto a Writer. This is intentionally final as its algorithm is - * tightly coupled with the abstract method of this class. - * - * @param input CharSequence that is being translated - * @param out Writer to translate the text to - * @throws IOException if and only if the Writer produces an IOException - */ - public final void translate(CharSequence input, Writer out) throws IOException { - if (out == null) { - throw new IllegalArgumentException("The Writer must not be null"); - } - if (input == null) { - return; - } - int pos = 0; - int len = input.length(); - while (pos < len) { - int consumed = translate(input, pos, out); - if (consumed == 0) { - char[] c = Character.toChars(Character.codePointAt(input, pos)); - out.write(c); - pos+= c.length; - continue; - } -// // contract with translators is that they have to understand codepoints -// // and they just took care of a surrogate pair - for (int pt = 0; pt < consumed; pt++) { - pos += Character.charCount(Character.codePointAt(input, pt)); - } - } - } - - /** - * Helper method to create a merger of this translator with another set of - * translators. Useful in customizing the standard functionality. - * - * @param translators CharSequenceTranslator array of translators to merge with this one - * @return CharSequenceTranslator merging this translator with the others - */ - public final CharSequenceTranslator with(CharSequenceTranslator... translators) { - CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1]; - newArray[0] = this; - System.arraycopy(translators, 0, newArray, 1, translators.length); - return new AggregateTranslator(newArray); - } - - /** - *

Returns an upper case hexadecimal String for the given - * character.

- * - * @param codepoint The codepoint to convert. - * @return An upper case hexadecimal String - */ - public static String hex(int codepoint) { - return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH); - } - -} diff --git a/All/Genesis-OOB/Genesis#35/old/CharSequenceTranslator.java b/All/Genesis-OOB/Genesis#35/old/CharSequenceTranslator.java deleted file mode 100755 index 4d010ea..0000000 --- a/All/Genesis-OOB/Genesis#35/old/CharSequenceTranslator.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * 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.commons.lang3.text.translate; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Locale; - -/** - * An API for translating text. - * Its core use is to escape and unescape text. Because escaping and unescaping - * is completely contextual, the API does not present two separate signatures. - * - * @since 3.0 - * @version $Id$ - */ -public abstract class CharSequenceTranslator { - - /** - * Translate a set of codepoints, represented by an int index into a CharSequence, - * into another set of codepoints. The number of codepoints consumed must be returned, - * and the only IOExceptions thrown must be from interacting with the Writer so that - * the top level API may reliable ignore StringWriter IOExceptions. - * - * @param input CharSequence that is being translated - * @param index int representing the current point of translation - * @param out Writer to translate the text to - * @return int count of codepoints consumed - * @throws IOException if and only if the Writer produces an IOException - */ - public abstract int translate(CharSequence input, int index, Writer out) throws IOException; - - /** - * Helper for non-Writer usage. - * @param input CharSequence to be translated - * @return String output of translation - */ - public final String translate(CharSequence input) { - if (input == null) { - return null; - } - try { - StringWriter writer = new StringWriter(input.length() * 2); - translate(input, writer); - return writer.toString(); - } catch (IOException ioe) { - // this should never ever happen while writing to a StringWriter - throw new RuntimeException(ioe); - } - } - - /** - * Translate an input onto a Writer. This is intentionally final as its algorithm is - * tightly coupled with the abstract method of this class. - * - * @param input CharSequence that is being translated - * @param out Writer to translate the text to - * @throws IOException if and only if the Writer produces an IOException - */ - public final void translate(CharSequence input, Writer out) throws IOException { - if (out == null) { - throw new IllegalArgumentException("The Writer must not be null"); - } - if (input == null) { - return; - } - int pos = 0; - int len = input.length(); - while (pos < len) { - int consumed = translate(input, pos, out); - if (consumed == 0) { - char[] c = Character.toChars(Character.codePointAt(input, pos)); - out.write(c); - pos+= c.length; - continue; - } -// // contract with translators is that they have to understand codepoints -// // and they just took care of a surrogate pair - for (int pt = 0; pt < consumed; pt++) { - pos += Character.charCount(Character.codePointAt(input, pos)); - } - } - } - - /** - * Helper method to create a merger of this translator with another set of - * translators. Useful in customizing the standard functionality. - * - * @param translators CharSequenceTranslator array of translators to merge with this one - * @return CharSequenceTranslator merging this translator with the others - */ - public final CharSequenceTranslator with(CharSequenceTranslator... translators) { - CharSequenceTranslator[] newArray = new CharSequenceTranslator[translators.length + 1]; - newArray[0] = this; - System.arraycopy(translators, 0, newArray, 1, translators.length); - return new AggregateTranslator(newArray); - } - - /** - *

Returns an upper case hexadecimal String for the given - * character.

- * - * @param codepoint The codepoint to convert. - * @return An upper case hexadecimal String - */ - public static String hex(int codepoint) { - return Integer.toHexString(codepoint).toUpperCase(Locale.ENGLISH); - } - -} diff --git a/All/Genesis-OOB/Genesis#35/pair.info b/All/Genesis-OOB/Genesis#35/pair.info deleted file mode 100755 index 590af7a..0000000 --- a/All/Genesis-OOB/Genesis#35/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:35 -SATName:Genesis -modifiedFPath:src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java -comSha:52bcd9b8e82d4d1d287b0d75df1e161aff8c65ab -parentComSha:52bcd9b8e82d4d1d287b0d75df1e161aff8c65ab^1 -githubUrl:https://github.com/apache/commons-lang -repoName:apache#commons-lang \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#36/comMsg.txt b/All/Genesis-OOB/Genesis#36/comMsg.txt deleted file mode 100755 index cd5c3ee..0000000 --- a/All/Genesis-OOB/Genesis#36/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -LANG-805 RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException diff --git a/All/Genesis-OOB/Genesis#36/diff.diff b/All/Genesis-OOB/Genesis#36/diff.diff deleted file mode 100755 index 6627cc1..0000000 --- a/All/Genesis-OOB/Genesis#36/diff.diff +++ /dev/null @@ -1,38 +0,0 @@ -diff --git a/src/main/java/org/apache/commons/lang3/RandomStringUtils.java b/src/main/java/org/apache/commons/lang3/RandomStringUtils.java -index bded154..a799057 100644 ---- a/src/main/java/org/apache/commons/lang3/RandomStringUtils.java -+++ b/src/main/java/org/apache/commons/lang3/RandomStringUtils.java -@@ -214 +214 @@ public static String random(int count, int start, int end, boolean letters, bool -- * @param chars the set of chars to choose randoms from. -+ * @param chars the set of chars to choose randoms from, must not be empty. -@@ -220 +220 @@ public static String random(int count, int start, int end, boolean letters, bool -- * @throws IllegalArgumentException if {@code count} < 0. -+ * @throws IllegalArgumentException if {@code count} < 0 or the provided chars array is empty. -@@ -229,0 +230,4 @@ public static String random(int count, int start, int end, boolean letters, bool -+ if (chars != null && chars.length == 0) { -+ throw new IllegalArgumentException("The chars array must not be empty"); -+ } -+ -@@ -231,2 +235,3 @@ public static String random(int count, int start, int end, boolean letters, bool -- end = 'z' + 1; -- start = ' '; -+ if (chars != null) { -+ end = chars.length; -+ } else { -@@ -234 +238,0 @@ public static String random(int count, int start, int end, boolean letters, bool -- start = 0; -@@ -235,0 +240,4 @@ public static String random(int count, int start, int end, boolean letters, bool -+ } else { -+ end = 'z' + 1; -+ start = ' '; -+ } -@@ -288 +296,2 @@ public static String random(int count, int start, int end, boolean letters, bool -- * specified.

-+ * specified by the string, must not be empty. -+ * If null, the set of all characters is used.

-@@ -292 +301 @@ public static String random(int count, int start, int end, boolean letters, bool -- * may be null -+ * may be null, but must not be empty -@@ -294 +303 @@ public static String random(int count, int start, int end, boolean letters, bool -- * @throws IllegalArgumentException if {@code count} < 0. -+ * @throws IllegalArgumentException if {@code count} < 0 or the string is empty. diff --git a/All/Genesis-OOB/Genesis#36/new/RandomStringUtils.java b/All/Genesis-OOB/Genesis#36/new/RandomStringUtils.java deleted file mode 100755 index a799057..0000000 --- a/All/Genesis-OOB/Genesis#36/new/RandomStringUtils.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * 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.commons.lang3; - -import java.util.Random; - -/** - *

Operations for random {@code String}s.

- *

Currently private high surrogate characters are ignored. - * These are Unicode characters that fall between the values 56192 (db80) - * and 56319 (dbff) as we don't know how to handle them. - * High and low surrogates are correctly dealt with - that is if a - * high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f) - * then it is followed by a low surrogate. If a low surrogate is chosen, - * 56320 (dc00) to 57343 (dfff) then it is placed after a randomly - * chosen high surrogate.

- * - *

#ThreadSafe#

- * @since 1.0 - * @version $Id$ - */ -public class RandomStringUtils { - - /** - *

Random object used by random method. This has to be not local - * to the random method so as to not return the same value in the - * same millisecond.

- */ - private static final Random RANDOM = new Random(); - - /** - *

{@code RandomStringUtils} instances should NOT be constructed in - * standard programming. Instead, the class should be used as - * {@code RandomStringUtils.random(5);}.

- * - *

This constructor is public to permit tools that require a JavaBean instance - * to operate.

- */ - public RandomStringUtils() { - super(); - } - - // Random - //----------------------------------------------------------------------- - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of all characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String random(int count) { - return random(count, false, false); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of characters whose - * ASCII value is between {@code 32} and {@code 126} (inclusive).

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAscii(int count) { - return random(count, 32, 127, false, false); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alphabetic - * characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphabetic(int count) { - return random(count, true, false); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alpha-numeric - * characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphanumeric(int count) { - return random(count, true, true); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of numeric - * characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomNumeric(int count) { - return random(count, false, true); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alpha-numeric - * characters as indicated by the arguments.

- * - * @param count the length of random string to create - * @param letters if {@code true}, generated string will include - * alphabetic characters - * @param numbers if {@code true}, generated string will include - * numeric characters - * @return the random string - */ - public static String random(int count, boolean letters, boolean numbers) { - return random(count, 0, 0, letters, numbers); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alpha-numeric - * characters as indicated by the arguments.

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters if {@code true}, generated string will include - * alphabetic characters - * @param numbers if {@code true}, generated string will include - * numeric characters - * @return the random string - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers) { - return random(count, start, end, letters, numbers, null, RANDOM); - } - - /** - *

Creates a random string based on a variety of options, using - * default source of randomness.

- * - *

This method has exactly the same semantics as - * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but - * instead of using an externally supplied source of randomness, it uses - * the internal static {@link Random} instance.

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters only allow letters? - * @param numbers only allow numbers? - * @param chars the set of chars to choose randoms from. - * If {@code null}, then it will use the set of all chars. - * @return the random string - * @throws ArrayIndexOutOfBoundsException if there are not - * {@code (end - start) + 1} characters in the set array. - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers, char... chars) { - return random(count, start, end, letters, numbers, chars, RANDOM); - } - - /** - *

Creates a random string based on a variety of options, using - * supplied source of randomness.

- * - *

If start and end are both {@code 0}, start and end are set - * to {@code ' '} and {@code 'z'}, the ASCII printable - * characters, will be used, unless letters and numbers are both - * {@code false}, in which case, start and end are set to - * {@code 0} and {@code Integer.MAX_VALUE}. - * - *

If set is not {@code null}, characters between start and - * end are chosen.

- * - *

This method accepts a user-supplied {@link Random} - * instance to use as a source of randomness. By seeding a single - * {@link Random} instance with a fixed seed and using it for each call, - * the same random sequence of strings can be generated repeatedly - * and predictably.

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters only allow letters? - * @param numbers only allow numbers? - * @param chars the set of chars to choose randoms from, must not be empty. - * If {@code null}, then it will use the set of all chars. - * @param random a source of randomness. - * @return the random string - * @throws ArrayIndexOutOfBoundsException if there are not - * {@code (end - start) + 1} characters in the set array. - * @throws IllegalArgumentException if {@code count} < 0 or the provided chars array is empty. - * @since 2.0 - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers, - char[] chars, Random random) { - if (count == 0) { - return ""; - } else if (count < 0) { - throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); - } - if (chars != null && chars.length == 0) { - throw new IllegalArgumentException("The chars array must not be empty"); - } - - if (start == 0 && end == 0) { - if (chars != null) { - end = chars.length; - } else { - if (!letters && !numbers) { - end = Integer.MAX_VALUE; - } else { - end = 'z' + 1; - start = ' '; - } - } - } - - char[] buffer = new char[count]; - int gap = end - start; - - while (count-- != 0) { - char ch; - if (chars == null) { - ch = (char) (random.nextInt(gap) + start); - } else { - ch = chars[random.nextInt(gap) + start]; - } - if (letters && Character.isLetter(ch) - || numbers && Character.isDigit(ch) - || !letters && !numbers) { - if(ch >= 56320 && ch <= 57343) { - if(count == 0) { - count++; - } else { - // low surrogate, insert high surrogate after putting it in - buffer[count] = ch; - count--; - buffer[count] = (char) (55296 + random.nextInt(128)); - } - } else if(ch >= 55296 && ch <= 56191) { - if(count == 0) { - count++; - } else { - // high surrogate, insert low surrogate before putting it in - buffer[count] = (char) (56320 + random.nextInt(128)); - count--; - buffer[count] = ch; - } - } else if(ch >= 56192 && ch <= 56319) { - // private high surrogate, no effing clue, so skip it - count++; - } else { - buffer[count] = ch; - } - } else { - count++; - } - } - return new String(buffer); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of characters - * specified by the string, must not be empty. - * If null, the set of all characters is used.

- * - * @param count the length of random string to create - * @param chars the String containing the set of characters to use, - * may be null, but must not be empty - * @return the random string - * @throws IllegalArgumentException if {@code count} < 0 or the string is empty. - */ - public static String random(int count, String chars) { - if (chars == null) { - return random(count, 0, 0, false, false, null, RANDOM); - } - return random(count, chars.toCharArray()); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of characters specified.

- * - * @param count the length of random string to create - * @param chars the character array containing the set of characters to use, - * may be null - * @return the random string - * @throws IllegalArgumentException if {@code count} < 0. - */ - public static String random(int count, char... chars) { - if (chars == null) { - return random(count, 0, 0, false, false, null, RANDOM); - } - return random(count, 0, chars.length, false, false, chars, RANDOM); - } - -} diff --git a/All/Genesis-OOB/Genesis#36/new/changes.xml b/All/Genesis-OOB/Genesis#36/new/changes.xml deleted file mode 100755 index 1aae92a..0000000 --- a/All/Genesis-OOB/Genesis#36/new/changes.xml +++ /dev/null @@ -1,586 +0,0 @@ - - - - - Commons Lang Changes - - - - - RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException - LocaleUtils - unnecessary recursive call in SyncAvoid class. - Javadoc bug in DateUtils#ceiling for Calendar and Object versions. - Use generics in SerializationUtils - SerializationUtils throws ClassNotFoundException when cloning primitive classes - StringUtils equals() relies on undefined behavior - Documentation bug: StringUtils.split - TypeUtilsTest contains incorrect type assignability assertion - TypeUtils.getTypeArguments() misses type arguments for partially-assigned classes - ImmutablePair doc contains nonsense text - ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text - EventListenerSupport.ProxyInvocationHandler no longer defines serialVersionUID - StrBuilder is now serializable - Fix Javadoc Ant warnings - Javadoc bug in static inner class DateIterator - Add Triple class (ternary version of Pair) - FastDateFormat supports parse methods - - - - Add API StringUtils.toString(byte[] intput, String charsetName) - Add an example with whitespace in StringUtils.defaultIfEmpty - Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and isPrimitiveOrWrapper(Class<?>) - Fix createLong() so it behaves like createInteger() - Include the actual type in the Validate.isInstance and isAssignableFrom exception messages - Incorrect Bundle-SymbolicName in Manifest - Deprecating chomp(String, String) - NumberUtils does not handle upper-case hex: 0X and -0X - StringUtils throws java.security.AccessControlException on Google App Engine - Ant build has wrong component.name - CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY - Document that the Mutable numbers don't work as expected with String.format - SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system - - - - SerializationUtils.clone: Fallback to context classloader if class not found in current classloader. - ToStringBuilderTest.testReflectionHierarchyArrayList fails with IBM JDK 6. - StringEscapeUtils.escapeXml(input) wrong when input contains characters in Supplementary Planes. - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long unicode string. - Improve exception message when StringUtils.replaceEachRepeatedly detects recursion. - Specify source encoding for Ant build. - Complement ArrayUtils.addAll() variants with by-index and by-value removal methods. - Add Range<T> Range<T>.intersectionWith(Range<T>). - Add mode and median Comparable... methods to ObjectUtils. - Add BooleanUtils.and + or varargs methods. - EnumSet -> bit vector. - The CHAR_ARRAY cache in CharUtils duplicates the cache in java.lang.Character. - Deprecate CharUtils.toCharacterObject(char) in favor of java.lang.Character.valueOf(char). - Missing method getRawMessage for ContextedException and ContextedRuntimeException. - Use internal Java's Number caches instead creating new objects. - - - - StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes. - build.xml Java 1.5+ updates. - swapCase and *capitalize speedups. - CharSetUtils.squeeze() speedup. - StringUtils doc/comment spelling fixes. - Increase test coverage of FieldUtils read methods and tweak Javadoc. - Add includeantruntime=false to javac targets to quell warnings in ant 1.8.1 and better (and modest performance gain). - StringIndexOutOfBoundsException when calling unescapeHtml4("&#03"). - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long Unicode string. - StringUtils.join throws NPE when toString returns null for one of objects in collection. - Add FormattableUtils class. - Add ClassUtils.getSimpleName() methods. - Add hashCodeMulti varargs method. - Removed DateUtils.UTC_TIME_ZONE. - Convert more of the StringUtils API to take CharSequence. - EqualsBuilder synchronizes on HashCodeBuilder. - StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for "". - Add support for ConcurrentMap.putIfAbsent(). - Documented potential NPE if auto-boxing occurs for some BooleanUtils methods. - DateUtils.isSameLocalTime compares using 12 hour clock and not 24 hour. - Extend exception handling in ConcurrentUtils to runtime exceptions. - SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - WordUtils.abbreviate() removed. - Doc bug in DateUtils#ceiling. - StringEscapeUtils.unescapeJava doesn't handle octal escapes and Unicode with extra u. - org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k). - org.apache.commons.lang3.math.Fraction does not always succeed in multiplyBy and divideBy. - Change ObjectUtils min() & max() functions to use varargs rather than just two parameters. - Add a Null-safe compare() method to ObjectUtils. - NumberUtils.isNumber(String) is not right when the String is "1.1L". - EntityArrays typo: {"\u2122", "&minus;"}, // minus sign, U+2212 ISOtech. - Some Entitys like &Ouml; are not matched properly against its ISO8859-1 representation. - Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect. - Add StringUtils.defaultIfBlank(). - Provide a very basic ConcurrentInitializer implementation. - Support lazy initialization using atomic variables. - Enhance StrSubstitutor to support nested ${var-${subvr}} expansion. - Provide documentation about the new concurrent package. - Charset may not be threadsafe, because the HashSet is not synch. - StringEscapeUtils.escapeXML() can't process UTF-16 supplementary characters. - StringUtils.endsWithAny method. - Add AnnotationUtils. - BooleanUtils.toBooleanObject to support single character input. - FastDateFormat.format() outputs incorrect week of year because locale isn't respected. - StrSubstitutor should also handle the default properties of a java.util.Properties class. - Javadoc StringUtils.left() claims to throw on negative len, but doesn't. - Add normalizeSpace to StringUtils. - NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - - NOTE: The below were included in the Commons Lang 3.0-beta release. - Convert StringUtils API to take CharSequence. - Push down WordUtils to "text" sub-package. - Extend exception handling in ConcurrentUtils to runtime exceptions. - Some StringUtils methods should take an int character instead of char to use String API features. - EqualsBuilder causes StackOverflowException. - DefaultExceptionContext overwrites values in recursive situations. - ContextedRuntimeException no longer an 'unchecked' exception. - Add Builder Interface / Update Builders to Implement It. - Javadoc is incorrect for public static int lastIndexOf(String str, String searchStr). - ClassUtils.getClass(): Allow Dots as Inner Class Separators. - DateUtils equal & compare functions up to most significant field. - Remove JDK 1.2/1.3 bug handling in StringUtils.indexOf(String, String, int). - Create a basic Pair<L, R> class. - exception.DefaultExceptionContext.getFormattedExceptionMessage catches Throwable. - Provide an implementation of the ThreadFactory interface. - Add new Validate methods. - ArrayUtils.add(T[] array, T element) can create unexpected ClassCastException. - Do the test cases really still require main() and suite() methods?. - @SuppressWarnings("unchecked") is used too generally. - Improve StrLookup API documentation. - Change Java package name. - Change Maven groupId. - New TimedSemaphore class. - Added validState validation method. - Added isAssignableFrom and isInstanceOf validation methods. - Add TypeUtils class to provide utility code for working with generic types. - Replace Range classes with generic version. - Use Iterable on API instead of Collection. - Add methods to Validate to check whether the index is valid for the array/list/string. - Add ability to create a Future for a constant. - Replace StringBuffer with StringBuilder. - Make NumericEntityEscaper immutable. - Compile commons.lang for CDC 1.1/Foundation 1.1. - Add ArrayUtils.toArray to create generic arrays. - Validate: support for validating blank strings. - Add a concurrent package. - Mutable classes should implement an appropriately typed Mutable interface. - Better EnumUtils. - StringEscapeUtils.unescapeJava should support \u+ notation. - Rewrite StringEscapeUtils. - bring ArrayUtils.isEmpty to the generics world. - Add support for background initialization. - Add support for the handling of ExecutionExceptions. - Add StringEscapeUtils.escapeText() methods. - Addition of ContextedException and ContextedRuntimeException. - A generic implementation of the Lazy initialization pattern. - Remove code that does not hold enough value to remain. - Remove code handled now by the JDK. - StrSubstitutor now supports substitution in variable names. - Possible race-conditions in hashCode of the range classes. - StringEscapeUtils.escapeHtml incorrectly converts Unicode characters above U+00FFFF into 2 characters. - Document where in SVN trunk is. - StopWatch does not resist to system time changes. - Fixes for thread safety. - Refactor Validate.java to eliminate code redundancy. - Lower Ascii Characters don't get encoded by Entities.java. - StringUtils.emptyToNull. - StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20). - Remove @deprecateds. - Add ClassUtils.isAssignable() variants with autoboxing. - Improve Javadoc for StringUtils class. - Javadoc incorrect for StringUtils.endsWithIgnoreCase. - Investigate for vararg usages. - JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder). - LeftOf/RightOfNumber in Range convenience methods necessary. - ExceptionUtils not thread-safe. - ObjectUtils.coalesce. - StrBuilder should implement CharSequence and Appendable. - StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanes, etc. - Finally start using generics. - StrBuilder does not implement clone(). - EnumUtils for JDK 5.0. - Wish : method unaccent. - MutableBigDecimal and MutableBigInteger. - StringEscaper.escapeXml() escapes characters > 0x7f. - Depend on JDK 1.5+. - - - - BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String). - ClassUtils: allow Dots as Inner Class Separators in getClass(). - DateUtils: equal and compare functions up to most significant field. - DateUtils: provide a Date to Calendar convenience method. - ObjectUtils: add clone methods to ObjectUtils. - ObjectUtils: add a Null-safe compare() method. - ObjectUtils: add notEqual() method. - StrBuilder: implement clone() method. - StringUtils: add a normalizeSpace() method. - StringUtils: add endsWithAny() method. - StringUtils: add defaultIfBlank() method. - StrSubstitutor: add a replace(String, Properties) variant. - StrSubstitutor: support substitution in variable names. - Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue. - CharSet: make the underlying set synchronized. - CompareToBuilder: fix passing along compareTransients to the reflectionCompare method. - ExtendedMessageFormat doesn't override equals(Object). - FastDateFormat: fix to properly include the locale when formatting a Date. - NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly. - SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading. - Javadoc is incorrect for lastIndexOf() method. - Javadoc for HashCodeBuilder.append(boolean) does not match implementation. - Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't. - Javadoc - document thread safety. - Test for StringUtils replaceChars() icelandic characters. - - - - ArrayUtils - add isNotEmpty() methods. - ArrayUtils - add nullToEmpty() methods. - CharRange - provide an iterator that lets you walk the chars in the range. - CharRange - add more readable static builder methods. - ClassUtils - new isAssignable() methods with autoboxing. - ClassUtils - add support to getShortClassName and getPackageName for arrays. - DateUtils - add ceiling() method. - DateUtils - add parseDateStrictly() method. - EqualsBuilder - add reset() method. - NumberUtils - add toByte() and toShort() methods. - Mutable numbers - add string constructors. - MutableBoolean - add toBoolean(), isTrue() and isFalse() methods. - StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty. - SystemUtils - add IS_OS_WINDOWS_7 constant. - SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7. - StringUtils - add abbreviateMiddle() method. - StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods. - StringUtils - add isAllUpperCase() and isAllLowerCase() methods. - StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method. - StringUtils - add repeat() method. - StringUtils - add startsWithAny() method. - StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods. - New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils. - ArrayUtils - addAll() does not handle mixed types very well. - CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread. - ClassUtils - improving performance of getAllInterfaces. - ClassUtils - toClass() throws NullPointerException on null array element. - DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat. - DateUtils - round() doesn't work correct for Calendar.AM_PM. - DateUtils - improve tests. - Entities - multithreaded initialization. - Entities - missing final modifiers; thread-safety issues. - EnumUtils - getEnum() doesn't work well in 1.5+. - ExceptionUtils - use immutable lock target. - ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes. - FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state. - FastDateFormat - Remove unused field. - LocaleUtils - Initialization of available locales in LocaleUtils can be deferred. - NumberUtils - createNumber() thows a StringIndexOutOfBoundsException when only an "l" is passed in. - NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.'. - StringUtils - improve handling of case-insensitive Strings. - StringUtils - replaceEach() no longer NPEs when null appears in the last String[]. - StringUtils - correct Javadoc for startsWith() and startsWithIgnoreCase(). - StringEscapeUtils - escapeJava() escapes '/' characters. - StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException and returning null. - WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length. - StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity. - Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List. - EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo instead of equals because it creates an inequality with HashCodeBuilder. - HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks. - HashCodeBuilder - Changing the hashCode() method to return toHashCode(). - HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes. - HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments. - ToStringBuilder - make default style thread-safe. - RandomUtils - nextLong() always produces even numbers. - RandomUtils - RandomUtils tests are failing frequently. - - - - ClassUtils.getShortClassName(String) inefficient. - Shouldn't Commons Lang's StringUtils have a "common" string method?. - FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change. - OSGi-ify Lang. - StrBuilder appendFixedWidth does not handle nulls. - infinite loop in Fraction.reduce when numerator == 0. - FastDateFormat thread safety. - ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array. - LocaleUtils.toLocale() rejects strings with only language+variant. - Enum is not thread-safe. - BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException. - ArrayUtils.toClass. - Why does appendIdentityToString return null?. - NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN. - Dates.round() behaves incorrectly for minutes and seconds. - StringUtils.length(String) returns null-safe length. - adding a StringUtils.replace method that takes an array or List of replacement strings. - Adding functionality to DateUtils to allow direct setting of various fields. - Add escaping for CSV columns to StringEscapeUtils. - StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods. - Extension to ClassUtils: Obtain the primitive class from a wrapper. - Javadoc bugs - cannot find object. - Optimize HashCodeBuilder.append(Object). - http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete. - Ambiguous / confusing names in StringUtils replace* methods. - Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils. - Add getStartTime to StopWatch. - Perhaps add containsAny() methods?. - Javadoc Example for EqualsBuilder is questionable. - EqualsBuilder don't compare BigDecimals correctly. - Split camel case strings. - Add Calendar flavour format methods to DateFormatUtils. - Calculating A date fragment in any time-unit. - Memory usage improvement for StringUtils#getLevenshteinDistance(). - Add ExtendedMessageFormat to org.apache.commons.lang.text. - StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly. - Add toArray() method to IntRange and LongRange classes. - add SystemUtils.IS_OS_WINDOWS_VISTA field. - Pointless synchronized in ThreadLocal.initialValue should be removed. - ToStringStyle Javadoc should show examples of styles. - Documentation bug for ignoreEmptyTokens accessors in StrTokenizer. - BooleanUtils toBooleanObject Javadoc does not match implementation. - truncateNicely method which avoids truncating in the middle of a word. - - - - Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions. - NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing. - Null-safe comparison methods for finding most recent / least recent dates. - StopWatch: suspend() acts as split(), if followed by stop(). - StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException. - Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException. - ToStringBuilder throws StackOverflowError when an Object cycle exists. - Create more tests to test out the +=31 replacement code in DurationFormatUtils. - StrBuilder contains usages of thisBuf.length when they should use size. - Enum Javadoc: 1) outline 5.0 native Enum migration 2) warn not to use the switch() , 3) point out approaches for persistence and gui. - Wrong behavior of Entities.unescape. - NumberUtils.createNumber throws NumberFormatException for one digit long. - NullPointerException in isAvailableLocale(Locale). - FastDateFormat.mRules is not transient or serializable. - StringUtils.join should allow you to pass a range for it (so it only joins a part of the array). - Refactor Entities methods. - Tests fail to pass when building with Maven 2. - DurationFormatUtils returns wrong result. - unescapeXml("&12345678;") should be "&12345678;". - Optimize StringEscapeUtils.unescapeXml(String). - BooleanUtils isNotTrue/isNotFalse. - Extra StrBuilder methods. - Add a pair of StringUtils.substringsBetween;String[] methods. - HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle. - Wish for StringUtils.join(Collection, *). - - - - StrBuilderTest#testReplaceStringString fails. - EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null. - Serialization - not backwards compatible. - Replace Clover with Cobertura. - ValuedEnum.compareTo(Object other) not typesafe - it easily could be... - LocaleUtils test fails under Mustang. - Javadoc example for StringUtils.splitByWholeSeparator incorrect. - PADDING array in StringUtils overflows on '\uffff'. - ClassUtils.primitiveToWrapper and Void. - unit test for org.apache.commons.lang.text.StrBuilder. - DateUtils.truncate method is buggy when dealing with DST switching hours. - RandomStringUtils.random() family of methods create invalid Unicode sequences. - StringUtils#getLevenshteinDistance() performance is sub-optimal. - Wrong length check in StrTokenizer.StringMatcher. - ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable. - FastDateFormat: wrong format for date "01.01.1000". - Unclear Javadoc for DateUtils.iterator(). - Memory "leak" in StringUtils. - StringEscapeUtils should expose escape*() methods taking Writer argument. - Fraction.toProperString() returns -1/1 for -1. - DurationFormatUtils.formatDurationWords "11 <unit>s" gets converted to "11 <unit>". - Performance modifications on StringUtils.replace. - StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand. - DurationFormatUtils.formatPeriod() returns the wrong result. - Request for MutableBoolean implementation. - New method for EqualsBuilder. - New ExceptionUtils method setCause(). - Add Mutable<Type> to<Type>() methods. - Provides a Class.getPublicMethod which returns public invocable Method. - Using ReflectionToStringBuilder and excluding secure fields. - add generic add method to DateUtils. - Tokenizer Enhancements: reset input string, static CSV/TSV factories. - Trivial cleanup of Javadoc in various files. - CompositeFormat. - Performance boost for RandomStringUtils. - Enhanced Class.forName version. - Add StringUtils.containsIgnoreCase(...). - Support char array converters on ArrayUtils. - DurationFormatUtils.formatDurationISO() Javadoc is missing T in duration string between date and time part. - Minor build and checkstyle changes. - Javadoc errors on StringUtils.splitPreserveAllTokens(String, char). - EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to &apos;. - Add methods and tests to StrBuilder. - replace() length calculation improvement. - New interpolation features. - Implementation of escape/unescapeHtml methods with Writer. - CompareToBuilder excludeFields for reflection method. - Add WordUtils.getInitials(String). - Error in an example in the Javadoc of the StringUtils.splitPreserveAllTokens() method. - ToStringBuilder/HashCodeBuilder Javadoc code examples. - Cannot build tests from latest SVN. - minor Javadoc improvements for StringUtils.stripXxx() methods. - Javadoc for StringUtils.removeEnd is incorrect. - Minor tweak to fix of bug # 26616. - - - - make optional parameters in FastDateFormat really optional. - Nestable.indexOfThrowable(Class) uses Class.equals() to match. - buffer under/overrun on Strings.strip, stripStart & stripEnd. - ToStringStyle.setArrayEnd(String) doesn't replace null with empty string. - New class proposal: CharacterEncoding. - SystemUtils fails init on HP-UX. - Javadoc - 'four basic XML entities' should be 5 (apos is missing). - o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0. - StringEscapeUtils.unescapeHtml() doesn't handle an empty entity. - EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class. - Method enums.Enum.equals(Object o) doesn't work correctly. - ExceptionUtils.addCauseMethodName(String) does not check for duplicates. - Make StopWatch validate state transitions. - enum package is not compatible with 1.5 jdk. - WordUtils capitalizeFully() throws a null pointer exception. - ValuedEnum. - parseDate class from HttpClient's DateParser class. - ArrayUtils.isEquals() throws ClassCastException when array1 and array2 are different dimension. - ClassCastException in Enum.equals(Object). - FastDateFormat year bug. - unbalanced ReflectionToStringBuilder. - FastDateFormat.getDateInstance(int, Locale) always uses the pattern from the first invocation. - ReflectionToStringBuilder.toString(null) throws exception by design. - Make ClassUtils methods null-safe and not throw an IAE. - StringUtils.split ignores empty items. - EqualsBuilder.append(Object[], Object[]) throws NPE. - ArrayUtils.addAll doesn't always return new array. - Enum.equals does not handle different class loaders. - Add SystemUtils.AWT_TOOLKIT and others. - Throwable cause for NotImplementedException. - ClassUtils.primitivesToWrappers method. - public static boolean DateUtils.equals(Date dt1, Date dt2) ?. - Documentation error in StringUtils.replace. - DateUtils constants should be long. - DateUtils.truncate() is off by one hour when using a date in DST switch 'zone'. - StringEscapeUtils.unescapeHtml() doesn't handle hex entities. - new StringUtils.replaceChars behaves differently from old CharSetUtils.translate. - last substring returned by StringUtils.split( String, String, int ) is too long. - Can't subclass EqualsBuilder because isEquals is private. - new StringUtils.split methods that split on the whole separator string. - New method for converting a primitive Class to its corresponding wrapper Class. - Add convenience format(long) methods to FastDateFormat. - Enum's outer class may not be loaded for EnumUtils. - WordUtils.capitalizeFully(String str) should take a delimiter. - Make Javadoc crosslinking configurable. - Minor Javadoc fixes for StringUtils.contains(String, String). - Error in Javadoc for StringUtils.chomp(String, String). - StringUtils.defaultString: Documentation error. - Add hashCode-support to class ObjectUtils. - add another "known method" to ExceptionUtils. - Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES. - DateUtils.truncate oddity at the far end of the Date spectrum. - add getLength() method to ArrayUtils. - Validate.java: fixes comment skew, removes unused loop counter. - StringUtils.isAsciiPrintable(). - ExceptionUtils: new getCause() methodname (for tomcat-exception). - fixes 75 typos. - mutable numbers. - Javadoc fixes for ClassUtils. - Add StringUtils.nIndexOf?. - Javadoc fixes for CharSetUtils. - Remove redundant check for null separator in StringUtils#join. - Class and Package Comparators for ClassUtils. - add remove methods to ArrayUtils. - WordUtils capitalize improvement. - add isEmpty method to ArrayUtils. - lang.math.Fraction class deficiencies. - Add methods to ArrayUtils: add at end and insert-like ops. - Add SystemUtils methods for directory properties. - Add method that validates Collection elements are a certain type. - elapsed time formatting utility method. - - - - Infinite loop in ToStringBuilder.reflectionToString for inner classes. - NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08. - Rationalize StringUtils slice functions. - SystemUtils.IS_OS_OS2 Javadoc is wrong. - A small, but important Javadoc fix for Fraction proper whole and numerator. - Adding tolerance to double[] search methods in ArrayUtils. - lang.builder classes Javadoc edits (mostly typo fixes). - StringUtils Javadoc and test enhancements. - SystemUtils.IS_OS_*, IS_JAVA_* are always false. - Improve util.Validate tests. - maven-beta10 checkstyle problem. - StringUtils.chopNewLine - StringIndexOutOfBoundsException. - ToStringBuilder doesn't work well in subclasses. - static option for reversing the stacktrace. - NullPointerException in CompareToBuilder. - RandomStringUtils.randomAlpha methods omit 'z'. - test.time fails in Japanese (non-us) locale. - NumberUtils.isNumber allows illegal trailing characters. - Improve Javadoc and overflow behavior of Fraction. - RandomStringUtils infloops with length > 1. - test.lang fails if compiled with non iso-8859-1 locales. - SystemUtils does not play nice in an Applet. - time unit tests fail on Sundays. - java.lang.ExceptionInInitializerError thrown by JVMRandom constructor. - StringUtils.chomp does not match Perl. - patch and test case fixing problem with RandomStringUtils.random(). - General case: infinite loop: ToStringBuilder.reflectionToString. - Should ToStringBuilder.reflectionToString handle arrays?. - EnumUtils nit: The import java.io.Serializable is never used. - Example in Javadoc for ToStringBuilder wrong for append. - Added class hierachy support to HashCodeBuilder.reflectionHashCode(). - ExceptionUtils new methods. - Infinite loop in StringUtils.replace(text, repl, with) + FIX. - StackOverflow due to ToStringBuilder. - No Javadoc for NestableDelegate. - Specify initial size for Enum's HashMap. - Enum does not support inner sub-classes. - Removed compile warning in ObjectUtils. - SystemUtils.IS_JAVA_1_5 Javadoc is wrong. - NumberRange inaccurate for Long, etc. - Hierarchy support in ToStringBuilder.reflectionToString(). - StringUtils.countMatches loops forever if substring empty. - Javadoc fixes (remove @links to non-public identifiers). - Add Javadoc examples and tests for StringUtils. - Make NumberUtils null handling consistent. - Unused field 'startFinal' in DateIterator. - reduce object creation in ToStringBuilder. - Improved tests, Javadoc for CharSetUtils, StringEscapeUtils. - NumberUtils min/max, BooleanUtils.xor, and ArrayUtils toPrimitive and toObject. - Javadoc, tests improvements for CharSet, CharSetUtils. - StringUtil enhancement. - Javadoc nit. - Additional Lang Method Suggestions. - Make NestableDelegate methods public instead of package private. - Missing @since tags. - Refactored reflection feature of ToStringBuilder into new ReflectionToStringBuilder. - Typo in documentation. - Patch for Javadoc. - Add join(..., char c) to StringUtils (and some performance fixes). Even contains tests!. - Resurrect the WordWrapUtils from commons-sandbox/utils. - EnumTest fails on Linux Sun JDK 1.3.0. - What to do with FastDateFormat unused private constructors. - Added class hierachy support to CompareToBuilder.reflectionCompare(). - Removed compile warning in FastDateFormat. - typo in the Javadoc example code. - MethodUtils: Removed unused code/unused local vars. - Hierarchy support in EqualsBuilder.reflectionEquals(). - Javadoc Errata. - ArrayUtils.contains(). - More flexibility for getRootCause in ExceptionUtils. - - - - NumberRange.getMaximum returns minimum. - Enum constructor validations. - NestableException/Delegate is not serializable. - split using null and max less than actual token count adds "null". - ExceptionUtils cannot handle J2EE-Exception in a default way. - - - - - - - diff --git a/All/Genesis-OOB/Genesis#36/old/RandomStringUtils.java b/All/Genesis-OOB/Genesis#36/old/RandomStringUtils.java deleted file mode 100755 index bded154..0000000 --- a/All/Genesis-OOB/Genesis#36/old/RandomStringUtils.java +++ /dev/null @@ -1,322 +0,0 @@ -/* - * 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.commons.lang3; - -import java.util.Random; - -/** - *

Operations for random {@code String}s.

- *

Currently private high surrogate characters are ignored. - * These are Unicode characters that fall between the values 56192 (db80) - * and 56319 (dbff) as we don't know how to handle them. - * High and low surrogates are correctly dealt with - that is if a - * high surrogate is randomly chosen, 55296 (d800) to 56191 (db7f) - * then it is followed by a low surrogate. If a low surrogate is chosen, - * 56320 (dc00) to 57343 (dfff) then it is placed after a randomly - * chosen high surrogate.

- * - *

#ThreadSafe#

- * @since 1.0 - * @version $Id$ - */ -public class RandomStringUtils { - - /** - *

Random object used by random method. This has to be not local - * to the random method so as to not return the same value in the - * same millisecond.

- */ - private static final Random RANDOM = new Random(); - - /** - *

{@code RandomStringUtils} instances should NOT be constructed in - * standard programming. Instead, the class should be used as - * {@code RandomStringUtils.random(5);}.

- * - *

This constructor is public to permit tools that require a JavaBean instance - * to operate.

- */ - public RandomStringUtils() { - super(); - } - - // Random - //----------------------------------------------------------------------- - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of all characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String random(int count) { - return random(count, false, false); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of characters whose - * ASCII value is between {@code 32} and {@code 126} (inclusive).

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAscii(int count) { - return random(count, 32, 127, false, false); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alphabetic - * characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphabetic(int count) { - return random(count, true, false); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alpha-numeric - * characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomAlphanumeric(int count) { - return random(count, true, true); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of numeric - * characters.

- * - * @param count the length of random string to create - * @return the random string - */ - public static String randomNumeric(int count) { - return random(count, false, true); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alpha-numeric - * characters as indicated by the arguments.

- * - * @param count the length of random string to create - * @param letters if {@code true}, generated string will include - * alphabetic characters - * @param numbers if {@code true}, generated string will include - * numeric characters - * @return the random string - */ - public static String random(int count, boolean letters, boolean numbers) { - return random(count, 0, 0, letters, numbers); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of alpha-numeric - * characters as indicated by the arguments.

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters if {@code true}, generated string will include - * alphabetic characters - * @param numbers if {@code true}, generated string will include - * numeric characters - * @return the random string - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers) { - return random(count, start, end, letters, numbers, null, RANDOM); - } - - /** - *

Creates a random string based on a variety of options, using - * default source of randomness.

- * - *

This method has exactly the same semantics as - * {@link #random(int,int,int,boolean,boolean,char[],Random)}, but - * instead of using an externally supplied source of randomness, it uses - * the internal static {@link Random} instance.

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters only allow letters? - * @param numbers only allow numbers? - * @param chars the set of chars to choose randoms from. - * If {@code null}, then it will use the set of all chars. - * @return the random string - * @throws ArrayIndexOutOfBoundsException if there are not - * {@code (end - start) + 1} characters in the set array. - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers, char... chars) { - return random(count, start, end, letters, numbers, chars, RANDOM); - } - - /** - *

Creates a random string based on a variety of options, using - * supplied source of randomness.

- * - *

If start and end are both {@code 0}, start and end are set - * to {@code ' '} and {@code 'z'}, the ASCII printable - * characters, will be used, unless letters and numbers are both - * {@code false}, in which case, start and end are set to - * {@code 0} and {@code Integer.MAX_VALUE}. - * - *

If set is not {@code null}, characters between start and - * end are chosen.

- * - *

This method accepts a user-supplied {@link Random} - * instance to use as a source of randomness. By seeding a single - * {@link Random} instance with a fixed seed and using it for each call, - * the same random sequence of strings can be generated repeatedly - * and predictably.

- * - * @param count the length of random string to create - * @param start the position in set of chars to start at - * @param end the position in set of chars to end before - * @param letters only allow letters? - * @param numbers only allow numbers? - * @param chars the set of chars to choose randoms from. - * If {@code null}, then it will use the set of all chars. - * @param random a source of randomness. - * @return the random string - * @throws ArrayIndexOutOfBoundsException if there are not - * {@code (end - start) + 1} characters in the set array. - * @throws IllegalArgumentException if {@code count} < 0. - * @since 2.0 - */ - public static String random(int count, int start, int end, boolean letters, boolean numbers, - char[] chars, Random random) { - if (count == 0) { - return ""; - } else if (count < 0) { - throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); - } - if (start == 0 && end == 0) { - end = 'z' + 1; - start = ' '; - if (!letters && !numbers) { - start = 0; - end = Integer.MAX_VALUE; - } - } - - char[] buffer = new char[count]; - int gap = end - start; - - while (count-- != 0) { - char ch; - if (chars == null) { - ch = (char) (random.nextInt(gap) + start); - } else { - ch = chars[random.nextInt(gap) + start]; - } - if (letters && Character.isLetter(ch) - || numbers && Character.isDigit(ch) - || !letters && !numbers) { - if(ch >= 56320 && ch <= 57343) { - if(count == 0) { - count++; - } else { - // low surrogate, insert high surrogate after putting it in - buffer[count] = ch; - count--; - buffer[count] = (char) (55296 + random.nextInt(128)); - } - } else if(ch >= 55296 && ch <= 56191) { - if(count == 0) { - count++; - } else { - // high surrogate, insert low surrogate before putting it in - buffer[count] = (char) (56320 + random.nextInt(128)); - count--; - buffer[count] = ch; - } - } else if(ch >= 56192 && ch <= 56319) { - // private high surrogate, no effing clue, so skip it - count++; - } else { - buffer[count] = ch; - } - } else { - count++; - } - } - return new String(buffer); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of characters - * specified.

- * - * @param count the length of random string to create - * @param chars the String containing the set of characters to use, - * may be null - * @return the random string - * @throws IllegalArgumentException if {@code count} < 0. - */ - public static String random(int count, String chars) { - if (chars == null) { - return random(count, 0, 0, false, false, null, RANDOM); - } - return random(count, chars.toCharArray()); - } - - /** - *

Creates a random string whose length is the number of characters - * specified.

- * - *

Characters will be chosen from the set of characters specified.

- * - * @param count the length of random string to create - * @param chars the character array containing the set of characters to use, - * may be null - * @return the random string - * @throws IllegalArgumentException if {@code count} < 0. - */ - public static String random(int count, char... chars) { - if (chars == null) { - return random(count, 0, 0, false, false, null, RANDOM); - } - return random(count, 0, chars.length, false, false, chars, RANDOM); - } - -} diff --git a/All/Genesis-OOB/Genesis#36/old/changes.xml b/All/Genesis-OOB/Genesis#36/old/changes.xml deleted file mode 100755 index da5cd18..0000000 --- a/All/Genesis-OOB/Genesis#36/old/changes.xml +++ /dev/null @@ -1,585 +0,0 @@ - - - - - Commons Lang Changes - - - - - LocaleUtils - unnecessary recursive call in SyncAvoid class. - Javadoc bug in DateUtils#ceiling for Calendar and Object versions. - Use generics in SerializationUtils - SerializationUtils throws ClassNotFoundException when cloning primitive classes - StringUtils equals() relies on undefined behavior - Documentation bug: StringUtils.split - TypeUtilsTest contains incorrect type assignability assertion - TypeUtils.getTypeArguments() misses type arguments for partially-assigned classes - ImmutablePair doc contains nonsense text - ClassUtils.PACKAGE_SEPARATOR Javadoc contains garbage text - EventListenerSupport.ProxyInvocationHandler no longer defines serialVersionUID - StrBuilder is now serializable - Fix Javadoc Ant warnings - Javadoc bug in static inner class DateIterator - Add Triple class (ternary version of Pair) - FastDateFormat supports parse methods - - - - Add API StringUtils.toString(byte[] intput, String charsetName) - Add an example with whitespace in StringUtils.defaultIfEmpty - Add APIs ClassUtils.isPrimitiveWrapper(Class<?>) and isPrimitiveOrWrapper(Class<?>) - Fix createLong() so it behaves like createInteger() - Include the actual type in the Validate.isInstance and isAssignableFrom exception messages - Incorrect Bundle-SymbolicName in Manifest - Deprecating chomp(String, String) - NumberUtils does not handle upper-case hex: 0X and -0X - StringUtils throws java.security.AccessControlException on Google App Engine - Ant build has wrong component.name - CharUtils static final array CHAR_STRING is not needed to compute CHAR_STRING_ARRAY - Document that the Mutable numbers don't work as expected with String.format - SystemUtils.IS_OS_UNIX doesn't recognize FreeBSD as a Unix system - - - - SerializationUtils.clone: Fallback to context classloader if class not found in current classloader. - ToStringBuilderTest.testReflectionHierarchyArrayList fails with IBM JDK 6. - StringEscapeUtils.escapeXml(input) wrong when input contains characters in Supplementary Planes. - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long unicode string. - Improve exception message when StringUtils.replaceEachRepeatedly detects recursion. - Specify source encoding for Ant build. - Complement ArrayUtils.addAll() variants with by-index and by-value removal methods. - Add Range<T> Range<T>.intersectionWith(Range<T>). - Add mode and median Comparable... methods to ObjectUtils. - Add BooleanUtils.and + or varargs methods. - EnumSet -> bit vector. - The CHAR_ARRAY cache in CharUtils duplicates the cache in java.lang.Character. - Deprecate CharUtils.toCharacterObject(char) in favor of java.lang.Character.valueOf(char). - Missing method getRawMessage for ContextedException and ContextedRuntimeException. - Use internal Java's Number caches instead creating new objects. - - - - StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes. - build.xml Java 1.5+ updates. - swapCase and *capitalize speedups. - CharSetUtils.squeeze() speedup. - StringUtils doc/comment spelling fixes. - Increase test coverage of FieldUtils read methods and tweak Javadoc. - Add includeantruntime=false to javac targets to quell warnings in ant 1.8.1 and better (and modest performance gain). - StringIndexOutOfBoundsException when calling unescapeHtml4("&#03"). - StringEscapeUtils.escapeEcmaScript from lang3 cuts off long Unicode string. - StringUtils.join throws NPE when toString returns null for one of objects in collection. - Add FormattableUtils class. - Add ClassUtils.getSimpleName() methods. - Add hashCodeMulti varargs method. - Removed DateUtils.UTC_TIME_ZONE. - Convert more of the StringUtils API to take CharSequence. - EqualsBuilder synchronizes on HashCodeBuilder. - StringUtils.isAlpha, isAlphanumeric and isNumeric now return false for "". - Add support for ConcurrentMap.putIfAbsent(). - Documented potential NPE if auto-boxing occurs for some BooleanUtils methods. - DateUtils.isSameLocalTime compares using 12 hour clock and not 24 hour. - Extend exception handling in ConcurrentUtils to runtime exceptions. - SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - WordUtils.abbreviate() removed. - Doc bug in DateUtils#ceiling. - StringEscapeUtils.unescapeJava doesn't handle octal escapes and Unicode with extra u. - org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k). - org.apache.commons.lang3.math.Fraction does not always succeed in multiplyBy and divideBy. - Change ObjectUtils min() & max() functions to use varargs rather than just two parameters. - Add a Null-safe compare() method to ObjectUtils. - NumberUtils.isNumber(String) is not right when the String is "1.1L". - EntityArrays typo: {"\u2122", "&minus;"}, // minus sign, U+2212 ISOtech. - Some Entitys like &Ouml; are not matched properly against its ISO8859-1 representation. - Example StringUtils.indexOfAnyBut("zzabyycdxx", '') = 0 incorrect. - Add StringUtils.defaultIfBlank(). - Provide a very basic ConcurrentInitializer implementation. - Support lazy initialization using atomic variables. - Enhance StrSubstitutor to support nested ${var-${subvr}} expansion. - Provide documentation about the new concurrent package. - Charset may not be threadsafe, because the HashSet is not synch. - StringEscapeUtils.escapeXML() can't process UTF-16 supplementary characters. - StringUtils.endsWithAny method. - Add AnnotationUtils. - BooleanUtils.toBooleanObject to support single character input. - FastDateFormat.format() outputs incorrect week of year because locale isn't respected. - StrSubstitutor should also handle the default properties of a java.util.Properties class. - Javadoc StringUtils.left() claims to throw on negative len, but doesn't. - Add normalizeSpace to StringUtils. - NumberUtils createNumber throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - - NOTE: The below were included in the Commons Lang 3.0-beta release. - Convert StringUtils API to take CharSequence. - Push down WordUtils to "text" sub-package. - Extend exception handling in ConcurrentUtils to runtime exceptions. - Some StringUtils methods should take an int character instead of char to use String API features. - EqualsBuilder causes StackOverflowException. - DefaultExceptionContext overwrites values in recursive situations. - ContextedRuntimeException no longer an 'unchecked' exception. - Add Builder Interface / Update Builders to Implement It. - Javadoc is incorrect for public static int lastIndexOf(String str, String searchStr). - ClassUtils.getClass(): Allow Dots as Inner Class Separators. - DateUtils equal & compare functions up to most significant field. - Remove JDK 1.2/1.3 bug handling in StringUtils.indexOf(String, String, int). - Create a basic Pair<L, R> class. - exception.DefaultExceptionContext.getFormattedExceptionMessage catches Throwable. - Provide an implementation of the ThreadFactory interface. - Add new Validate methods. - ArrayUtils.add(T[] array, T element) can create unexpected ClassCastException. - Do the test cases really still require main() and suite() methods?. - @SuppressWarnings("unchecked") is used too generally. - Improve StrLookup API documentation. - Change Java package name. - Change Maven groupId. - New TimedSemaphore class. - Added validState validation method. - Added isAssignableFrom and isInstanceOf validation methods. - Add TypeUtils class to provide utility code for working with generic types. - Replace Range classes with generic version. - Use Iterable on API instead of Collection. - Add methods to Validate to check whether the index is valid for the array/list/string. - Add ability to create a Future for a constant. - Replace StringBuffer with StringBuilder. - Make NumericEntityEscaper immutable. - Compile commons.lang for CDC 1.1/Foundation 1.1. - Add ArrayUtils.toArray to create generic arrays. - Validate: support for validating blank strings. - Add a concurrent package. - Mutable classes should implement an appropriately typed Mutable interface. - Better EnumUtils. - StringEscapeUtils.unescapeJava should support \u+ notation. - Rewrite StringEscapeUtils. - bring ArrayUtils.isEmpty to the generics world. - Add support for background initialization. - Add support for the handling of ExecutionExceptions. - Add StringEscapeUtils.escapeText() methods. - Addition of ContextedException and ContextedRuntimeException. - A generic implementation of the Lazy initialization pattern. - Remove code that does not hold enough value to remain. - Remove code handled now by the JDK. - StrSubstitutor now supports substitution in variable names. - Possible race-conditions in hashCode of the range classes. - StringEscapeUtils.escapeHtml incorrectly converts Unicode characters above U+00FFFF into 2 characters. - Document where in SVN trunk is. - StopWatch does not resist to system time changes. - Fixes for thread safety. - Refactor Validate.java to eliminate code redundancy. - Lower Ascii Characters don't get encoded by Entities.java. - StringUtils.emptyToNull. - StringEscapeUtils.escapeHTML() does not escape chars (0x00-0x20). - Remove @deprecateds. - Add ClassUtils.isAssignable() variants with autoboxing. - Improve Javadoc for StringUtils class. - Javadoc incorrect for StringUtils.endsWithIgnoreCase. - Investigate for vararg usages. - JDK 1.5 build/runtime failure on LANG-393 (EqualsBuilder). - LeftOf/RightOfNumber in Range convenience methods necessary. - ExceptionUtils not thread-safe. - ObjectUtils.coalesce. - StrBuilder should implement CharSequence and Appendable. - StringEscapeUtils.escapeHtml() escapes multibyte characters like Chinese, Japanes, etc. - Finally start using generics. - StrBuilder does not implement clone(). - EnumUtils for JDK 5.0. - Wish : method unaccent. - MutableBigDecimal and MutableBigInteger. - StringEscaper.escapeXml() escapes characters > 0x7f. - Depend on JDK 1.5+. - - - - BooleanUtils: use same optimization in toBooleanObject(String) as in toBoolean(String). - ClassUtils: allow Dots as Inner Class Separators in getClass(). - DateUtils: equal and compare functions up to most significant field. - DateUtils: provide a Date to Calendar convenience method. - ObjectUtils: add clone methods to ObjectUtils. - ObjectUtils: add a Null-safe compare() method. - ObjectUtils: add notEqual() method. - StrBuilder: implement clone() method. - StringUtils: add a normalizeSpace() method. - StringUtils: add endsWithAny() method. - StringUtils: add defaultIfBlank() method. - StrSubstitutor: add a replace(String, Properties) variant. - StrSubstitutor: support substitution in variable names. - Use StrBuilder instead of StringBuffer to improve performance where sync. is not an issue. - CharSet: make the underlying set synchronized. - CompareToBuilder: fix passing along compareTransients to the reflectionCompare method. - ExtendedMessageFormat doesn't override equals(Object). - FastDateFormat: fix to properly include the locale when formatting a Date. - NumberUtils: createNumber() throws a StringIndexOutOfBoundsException when argument containing "e" and "E" is passed in. - StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly. - SystemUtils: getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM. - MemberUtils: getMatchingAccessibleMethod does not correctly handle inheritance and method overloading. - Javadoc is incorrect for lastIndexOf() method. - Javadoc for HashCodeBuilder.append(boolean) does not match implementation. - Javadoc StringUtils.left() claims to throw an exception on negative lenth, but doesn't. - Javadoc - document thread safety. - Test for StringUtils replaceChars() icelandic characters. - - - - ArrayUtils - add isNotEmpty() methods. - ArrayUtils - add nullToEmpty() methods. - CharRange - provide an iterator that lets you walk the chars in the range. - CharRange - add more readable static builder methods. - ClassUtils - new isAssignable() methods with autoboxing. - ClassUtils - add support to getShortClassName and getPackageName for arrays. - DateUtils - add ceiling() method. - DateUtils - add parseDateStrictly() method. - EqualsBuilder - add reset() method. - NumberUtils - add toByte() and toShort() methods. - Mutable numbers - add string constructors. - MutableBoolean - add toBoolean(), isTrue() and isFalse() methods. - StrBuilder - add appendSeparator() methods with an alternative default separator if the StrBuilder is currently empty. - SystemUtils - add IS_OS_WINDOWS_7 constant. - SystemUtils - add IS_JAVA_1_7 constant for JDK 1.7. - StringUtils - add abbreviateMiddle() method. - StringUtils - add indexOfIgnoreCase() and lastIndexOfIgnoreCase() methods. - StringUtils - add isAllUpperCase() and isAllLowerCase() methods. - StringUtils - add lastOrdinalIndexOf() method to complement the existing ordinalIndexOf() method. - StringUtils - add repeat() method. - StringUtils - add startsWithAny() method. - StringUtils - add upperCase(String, Locale) and lowerCase(String, Locale) methods. - New Reflection package containing ConstructorUtils, FieldUtils, MemberUtils and MethodUtils. - ArrayUtils - addAll() does not handle mixed types very well. - CharSet - Synchronizing the COMMON Map so that getInstance doesn't miss a put from a subclass in another thread. - ClassUtils - improving performance of getAllInterfaces. - ClassUtils - toClass() throws NullPointerException on null array element. - DateUtils - Fix parseDate() cannot parse ISO8601 dates produced by FastDateFormat. - DateUtils - round() doesn't work correct for Calendar.AM_PM. - DateUtils - improve tests. - Entities - multithreaded initialization. - Entities - missing final modifiers; thread-safety issues. - EnumUtils - getEnum() doesn't work well in 1.5+. - ExceptionUtils - use immutable lock target. - ExtendedMessageFormat - OutOfMemory with a pattern containing single quotes. - FastDateFormat - call getTime() on a calendar to ensure timezone is in the right state. - FastDateFormat - Remove unused field. - LocaleUtils - Initialization of available locales in LocaleUtils can be deferred. - NumberUtils - createNumber() thows a StringIndexOutOfBoundsException when only an "l" is passed in. - NumberUtils - isNumber(String) and createNumber(String) both modified to support '2.'. - StringUtils - improve handling of case-insensitive Strings. - StringUtils - replaceEach() no longer NPEs when null appears in the last String[]. - StringUtils - correct Javadoc for startsWith() and startsWithIgnoreCase(). - StringEscapeUtils - escapeJava() escapes '/' characters. - StringEscapeUtils - change escapeJavaStyleString() to throw UnhandledException instead swallowing IOException and returning null. - WordUtils - fix StringIndexOutOfBoundsException when lower is greater than the String length. - StrBuilder - Performance improvement by doubling the size of the String in ensureCapacity. - Compare, Equals and HashCode builders - use ArrayUtils to avoid creating a temporary List. - EqualsBuilder - removing the special handling of BigDecimal (LANG-393) to use compareTo instead of equals because it creates an inequality with HashCodeBuilder. - HashCodeBuilder - Performance improvement: check for isArray to short-circuit the 9 instanceof checks. - HashCodeBuilder - Changing the hashCode() method to return toHashCode(). - HashCodeBuilder - reflectionHashCode() can generate incorrect hashcodes. - HashCodeBuilder and ToStringStyle - use of ThreadLocal causes memory leaks in container environments. - ToStringBuilder - make default style thread-safe. - RandomUtils - nextLong() always produces even numbers. - RandomUtils - RandomUtils tests are failing frequently. - - - - ClassUtils.getShortClassName(String) inefficient. - Shouldn't Commons Lang's StringUtils have a "common" string method?. - FastDateFormat getDateInstance() and getDateTimeInstance() assume Locale.getDefault() won't change. - OSGi-ify Lang. - StrBuilder appendFixedWidth does not handle nulls. - infinite loop in Fraction.reduce when numerator == 0. - FastDateFormat thread safety. - ClassUtils.getShortClassName and ClassUtils.getPackageName and class of array. - LocaleUtils.toLocale() rejects strings with only language+variant. - Enum is not thread-safe. - BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException. - ArrayUtils.toClass. - Why does appendIdentityToString return null?. - NumberUtils.min(floatArray) returns wrong value if floatArray[0] happens to be Float.NaN. - Dates.round() behaves incorrectly for minutes and seconds. - StringUtils.length(String) returns null-safe length. - adding a StringUtils.replace method that takes an array or List of replacement strings. - Adding functionality to DateUtils to allow direct setting of various fields. - Add escaping for CSV columns to StringEscapeUtils. - StringUtils: startsWith / endsWith / startsWithIgnoreCase / endsWithIgnoreCase / removeStartIgnoreCase / removeEndIgnoreCase methods. - Extension to ClassUtils: Obtain the primitive class from a wrapper. - Javadoc bugs - cannot find object. - Optimize HashCodeBuilder.append(Object). - http://commons.apache.org/lang/developerguide.html "Building" section is incorrect and incomplete. - Ambiguous / confusing names in StringUtils replace* methods. - Add new splitByWholeSeparatorPreserveAllTokens() methods to StringUtils. - Add getStartTime to StopWatch. - Perhaps add containsAny() methods?. - Javadoc Example for EqualsBuilder is questionable. - EqualsBuilder don't compare BigDecimals correctly. - Split camel case strings. - Add Calendar flavour format methods to DateFormatUtils. - Calculating A date fragment in any time-unit. - Memory usage improvement for StringUtils#getLevenshteinDistance(). - Add ExtendedMessageFormat to org.apache.commons.lang.text. - StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly. - Add toArray() method to IntRange and LongRange classes. - add SystemUtils.IS_OS_WINDOWS_VISTA field. - Pointless synchronized in ThreadLocal.initialValue should be removed. - ToStringStyle Javadoc should show examples of styles. - Documentation bug for ignoreEmptyTokens accessors in StrTokenizer. - BooleanUtils toBooleanObject Javadoc does not match implementation. - truncateNicely method which avoids truncating in the middle of a word. - - - - Use of enum prevents a classloader from being garbage collected resuling in out of memory exceptions. - NumberUtils.max(byte[]) and NumberUtils.min(byte[]) are missing. - Null-safe comparison methods for finding most recent / least recent dates. - StopWatch: suspend() acts as split(), if followed by stop(). - StrBuilder.replaceAll and StrBuilder.deleteAll can throw ArrayIndexOutOfBoundsException. - Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException. - ToStringBuilder throws StackOverflowError when an Object cycle exists. - Create more tests to test out the +=31 replacement code in DurationFormatUtils. - StrBuilder contains usages of thisBuf.length when they should use size. - Enum Javadoc: 1) outline 5.0 native Enum migration 2) warn not to use the switch() , 3) point out approaches for persistence and gui. - Wrong behavior of Entities.unescape. - NumberUtils.createNumber throws NumberFormatException for one digit long. - NullPointerException in isAvailableLocale(Locale). - FastDateFormat.mRules is not transient or serializable. - StringUtils.join should allow you to pass a range for it (so it only joins a part of the array). - Refactor Entities methods. - Tests fail to pass when building with Maven 2. - DurationFormatUtils returns wrong result. - unescapeXml("&12345678;") should be "&12345678;". - Optimize StringEscapeUtils.unescapeXml(String). - BooleanUtils isNotTrue/isNotFalse. - Extra StrBuilder methods. - Add a pair of StringUtils.substringsBetween;String[] methods. - HashCodeBuilder throws java.lang.StackOverflowError when an object contains a cycle. - Wish for StringUtils.join(Collection, *). - - - - StrBuilderTest#testReplaceStringString fails. - EqualsBuilder.append(Object[], Object[]) crashes with a NullPointerException if an element of the first array is null. - Serialization - not backwards compatible. - Replace Clover with Cobertura. - ValuedEnum.compareTo(Object other) not typesafe - it easily could be... - LocaleUtils test fails under Mustang. - Javadoc example for StringUtils.splitByWholeSeparator incorrect. - PADDING array in StringUtils overflows on '\uffff'. - ClassUtils.primitiveToWrapper and Void. - unit test for org.apache.commons.lang.text.StrBuilder. - DateUtils.truncate method is buggy when dealing with DST switching hours. - RandomStringUtils.random() family of methods create invalid Unicode sequences. - StringUtils#getLevenshteinDistance() performance is sub-optimal. - Wrong length check in StrTokenizer.StringMatcher. - ExceptionUtils goes into infinite loop in getThrowables is throwable.getCause() == throwable. - FastDateFormat: wrong format for date "01.01.1000". - Unclear Javadoc for DateUtils.iterator(). - Memory "leak" in StringUtils. - StringEscapeUtils should expose escape*() methods taking Writer argument. - Fraction.toProperString() returns -1/1 for -1. - DurationFormatUtils.formatDurationWords "11 <unit>s" gets converted to "11 <unit>". - Performance modifications on StringUtils.replace. - StringEscapeUtils.unescapeHtml skips first entity after standalone ampersand. - DurationFormatUtils.formatPeriod() returns the wrong result. - Request for MutableBoolean implementation. - New method for EqualsBuilder. - New ExceptionUtils method setCause(). - Add Mutable<Type> to<Type>() methods. - Provides a Class.getPublicMethod which returns public invocable Method. - Using ReflectionToStringBuilder and excluding secure fields. - add generic add method to DateUtils. - Tokenizer Enhancements: reset input string, static CSV/TSV factories. - Trivial cleanup of Javadoc in various files. - CompositeFormat. - Performance boost for RandomStringUtils. - Enhanced Class.forName version. - Add StringUtils.containsIgnoreCase(...). - Support char array converters on ArrayUtils. - DurationFormatUtils.formatDurationISO() Javadoc is missing T in duration string between date and time part. - Minor build and checkstyle changes. - Javadoc errors on StringUtils.splitPreserveAllTokens(String, char). - EscapeUtil.escapeHtml() should clarify that it does not escape ' chars to &apos;. - Add methods and tests to StrBuilder. - replace() length calculation improvement. - New interpolation features. - Implementation of escape/unescapeHtml methods with Writer. - CompareToBuilder excludeFields for reflection method. - Add WordUtils.getInitials(String). - Error in an example in the Javadoc of the StringUtils.splitPreserveAllTokens() method. - ToStringBuilder/HashCodeBuilder Javadoc code examples. - Cannot build tests from latest SVN. - minor Javadoc improvements for StringUtils.stripXxx() methods. - Javadoc for StringUtils.removeEnd is incorrect. - Minor tweak to fix of bug # 26616. - - - - make optional parameters in FastDateFormat really optional. - Nestable.indexOfThrowable(Class) uses Class.equals() to match. - buffer under/overrun on Strings.strip, stripStart & stripEnd. - ToStringStyle.setArrayEnd(String) doesn't replace null with empty string. - New class proposal: CharacterEncoding. - SystemUtils fails init on HP-UX. - Javadoc - 'four basic XML entities' should be 5 (apos is missing). - o.a.c.lang.enum.ValuedEnum: 'enum'is a keyword in JDK1.5.0. - StringEscapeUtils.unescapeHtml() doesn't handle an empty entity. - EqualsBuilder.append(Object[], Object[]) incorrectly checks that rhs[i] is instance of lhs[i]'s class. - Method enums.Enum.equals(Object o) doesn't work correctly. - ExceptionUtils.addCauseMethodName(String) does not check for duplicates. - Make StopWatch validate state transitions. - enum package is not compatible with 1.5 jdk. - WordUtils capitalizeFully() throws a null pointer exception. - ValuedEnum. - parseDate class from HttpClient's DateParser class. - ArrayUtils.isEquals() throws ClassCastException when array1 and array2 are different dimension. - ClassCastException in Enum.equals(Object). - FastDateFormat year bug. - unbalanced ReflectionToStringBuilder. - FastDateFormat.getDateInstance(int, Locale) always uses the pattern from the first invocation. - ReflectionToStringBuilder.toString(null) throws exception by design. - Make ClassUtils methods null-safe and not throw an IAE. - StringUtils.split ignores empty items. - EqualsBuilder.append(Object[], Object[]) throws NPE. - ArrayUtils.addAll doesn't always return new array. - Enum.equals does not handle different class loaders. - Add SystemUtils.AWT_TOOLKIT and others. - Throwable cause for NotImplementedException. - ClassUtils.primitivesToWrappers method. - public static boolean DateUtils.equals(Date dt1, Date dt2) ?. - Documentation error in StringUtils.replace. - DateUtils constants should be long. - DateUtils.truncate() is off by one hour when using a date in DST switch 'zone'. - StringEscapeUtils.unescapeHtml() doesn't handle hex entities. - new StringUtils.replaceChars behaves differently from old CharSetUtils.translate. - last substring returned by StringUtils.split( String, String, int ) is too long. - Can't subclass EqualsBuilder because isEquals is private. - new StringUtils.split methods that split on the whole separator string. - New method for converting a primitive Class to its corresponding wrapper Class. - Add convenience format(long) methods to FastDateFormat. - Enum's outer class may not be loaded for EnumUtils. - WordUtils.capitalizeFully(String str) should take a delimiter. - Make Javadoc crosslinking configurable. - Minor Javadoc fixes for StringUtils.contains(String, String). - Error in Javadoc for StringUtils.chomp(String, String). - StringUtils.defaultString: Documentation error. - Add hashCode-support to class ObjectUtils. - add another "known method" to ExceptionUtils. - Enhancement of ExceptionUtils.CAUSE_METHOD_NAMES. - DateUtils.truncate oddity at the far end of the Date spectrum. - add getLength() method to ArrayUtils. - Validate.java: fixes comment skew, removes unused loop counter. - StringUtils.isAsciiPrintable(). - ExceptionUtils: new getCause() methodname (for tomcat-exception). - fixes 75 typos. - mutable numbers. - Javadoc fixes for ClassUtils. - Add StringUtils.nIndexOf?. - Javadoc fixes for CharSetUtils. - Remove redundant check for null separator in StringUtils#join. - Class and Package Comparators for ClassUtils. - add remove methods to ArrayUtils. - WordUtils capitalize improvement. - add isEmpty method to ArrayUtils. - lang.math.Fraction class deficiencies. - Add methods to ArrayUtils: add at end and insert-like ops. - Add SystemUtils methods for directory properties. - Add method that validates Collection elements are a certain type. - elapsed time formatting utility method. - - - - Infinite loop in ToStringBuilder.reflectionToString for inner classes. - NumberUtils.createBigDecimal("") NPE in Sun 1.3.1_08. - Rationalize StringUtils slice functions. - SystemUtils.IS_OS_OS2 Javadoc is wrong. - A small, but important Javadoc fix for Fraction proper whole and numerator. - Adding tolerance to double[] search methods in ArrayUtils. - lang.builder classes Javadoc edits (mostly typo fixes). - StringUtils Javadoc and test enhancements. - SystemUtils.IS_OS_*, IS_JAVA_* are always false. - Improve util.Validate tests. - maven-beta10 checkstyle problem. - StringUtils.chopNewLine - StringIndexOutOfBoundsException. - ToStringBuilder doesn't work well in subclasses. - static option for reversing the stacktrace. - NullPointerException in CompareToBuilder. - RandomStringUtils.randomAlpha methods omit 'z'. - test.time fails in Japanese (non-us) locale. - NumberUtils.isNumber allows illegal trailing characters. - Improve Javadoc and overflow behavior of Fraction. - RandomStringUtils infloops with length > 1. - test.lang fails if compiled with non iso-8859-1 locales. - SystemUtils does not play nice in an Applet. - time unit tests fail on Sundays. - java.lang.ExceptionInInitializerError thrown by JVMRandom constructor. - StringUtils.chomp does not match Perl. - patch and test case fixing problem with RandomStringUtils.random(). - General case: infinite loop: ToStringBuilder.reflectionToString. - Should ToStringBuilder.reflectionToString handle arrays?. - EnumUtils nit: The import java.io.Serializable is never used. - Example in Javadoc for ToStringBuilder wrong for append. - Added class hierachy support to HashCodeBuilder.reflectionHashCode(). - ExceptionUtils new methods. - Infinite loop in StringUtils.replace(text, repl, with) + FIX. - StackOverflow due to ToStringBuilder. - No Javadoc for NestableDelegate. - Specify initial size for Enum's HashMap. - Enum does not support inner sub-classes. - Removed compile warning in ObjectUtils. - SystemUtils.IS_JAVA_1_5 Javadoc is wrong. - NumberRange inaccurate for Long, etc. - Hierarchy support in ToStringBuilder.reflectionToString(). - StringUtils.countMatches loops forever if substring empty. - Javadoc fixes (remove @links to non-public identifiers). - Add Javadoc examples and tests for StringUtils. - Make NumberUtils null handling consistent. - Unused field 'startFinal' in DateIterator. - reduce object creation in ToStringBuilder. - Improved tests, Javadoc for CharSetUtils, StringEscapeUtils. - NumberUtils min/max, BooleanUtils.xor, and ArrayUtils toPrimitive and toObject. - Javadoc, tests improvements for CharSet, CharSetUtils. - StringUtil enhancement. - Javadoc nit. - Additional Lang Method Suggestions. - Make NestableDelegate methods public instead of package private. - Missing @since tags. - Refactored reflection feature of ToStringBuilder into new ReflectionToStringBuilder. - Typo in documentation. - Patch for Javadoc. - Add join(..., char c) to StringUtils (and some performance fixes). Even contains tests!. - Resurrect the WordWrapUtils from commons-sandbox/utils. - EnumTest fails on Linux Sun JDK 1.3.0. - What to do with FastDateFormat unused private constructors. - Added class hierachy support to CompareToBuilder.reflectionCompare(). - Removed compile warning in FastDateFormat. - typo in the Javadoc example code. - MethodUtils: Removed unused code/unused local vars. - Hierarchy support in EqualsBuilder.reflectionEquals(). - Javadoc Errata. - ArrayUtils.contains(). - More flexibility for getRootCause in ExceptionUtils. - - - - NumberRange.getMaximum returns minimum. - Enum constructor validations. - NestableException/Delegate is not serializable. - split using null and max less than actual token count adds "null". - ExceptionUtils cannot handle J2EE-Exception in a default way. - - - - - - - diff --git a/All/Genesis-OOB/Genesis#36/pair.info b/All/Genesis-OOB/Genesis#36/pair.info deleted file mode 100755 index 1af0d7d..0000000 --- a/All/Genesis-OOB/Genesis#36/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:36 -SATName:Genesis -modifiedFPath:src/main/java/org/apache/commons/lang3/RandomStringUtils.java -comSha:27bcbcc728434ffb2c45e81c0e75e6a3d6da3441 -parentComSha:27bcbcc728434ffb2c45e81c0e75e6a3d6da3441^1 -githubUrl:https://github.com/apache/commons-lang -repoName:apache#commons-lang \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#59/comMsg.txt b/All/Genesis-OOB/Genesis#59/comMsg.txt deleted file mode 100755 index d9d6e3e..0000000 --- a/All/Genesis-OOB/Genesis#59/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Check array length to protect against IndexOutOfBoundsException. diff --git a/All/Genesis-OOB/Genesis#59/diff.diff b/All/Genesis-OOB/Genesis#59/diff.diff deleted file mode 100755 index 0c407cf..0000000 --- a/All/Genesis-OOB/Genesis#59/diff.diff +++ /dev/null @@ -1,10 +0,0 @@ -diff --git a/Source/com/drew/metadata/iptc/Iso2022Converter.java b/Source/com/drew/metadata/iptc/Iso2022Converter.java -index f01e4bd..ed05089 100644 ---- a/Source/com/drew/metadata/iptc/Iso2022Converter.java -+++ b/Source/com/drew/metadata/iptc/Iso2022Converter.java -@@ -26 +26 @@ public final class Iso2022Converter -- if (bytes[0] == ESC && bytes[1] == PERCENT_SIGN && bytes[2] == LATIN_CAPITAL_G) -+ if (bytes.length > 2 && bytes[0] == ESC && bytes[1] == PERCENT_SIGN && bytes[2] == LATIN_CAPITAL_G) -@@ -29 +29 @@ public final class Iso2022Converter -- if (bytes[0] == ESC && (bytes[3] & 0xFF | ((bytes[2] & 0xFF) << 8) | ((bytes[1] & 0xFF ) <<16)) == DOT && bytes[4] == LATIN_CAPITAL_A) -+ if (bytes.length > 3 && bytes[0] == ESC && (bytes[3] & 0xFF | ((bytes[2] & 0xFF) << 8) | ((bytes[1] & 0xFF) << 16)) == DOT && bytes[4] == LATIN_CAPITAL_A) diff --git a/All/Genesis-OOB/Genesis#59/new/Iso2022Converter.java b/All/Genesis-OOB/Genesis#59/new/Iso2022Converter.java deleted file mode 100755 index ed05089..0000000 --- a/All/Genesis-OOB/Genesis#59/new/Iso2022Converter.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.drew.metadata.iptc; - -import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; - -public final class Iso2022Converter -{ - private static final String ISO_8859_1 = "ISO-8859-1"; - private static final String UTF_8 = "UTF-8"; - private static final int LATIN_CAPITAL_A = 0x41; - private static final int DOT = 0xe280a2; - private static final int LATIN_CAPITAL_G = 0x47; - private static final int PERCENT_SIGN = 0x25; - private static final int ESC = 0x1B; - - /** - * Converts the given ISO2022 char set to a java char set. - * - * @param bytes the ISO2022 char set - * @return the java char set name as a string or null if the converting was not possible - */ - public static String convertISO2022CharsetToJavaCharset(byte[] bytes) - { - if (bytes.length > 2 && bytes[0] == ESC && bytes[1] == PERCENT_SIGN && bytes[2] == LATIN_CAPITAL_G) - return UTF_8; - - if (bytes.length > 3 && bytes[0] == ESC && (bytes[3] & 0xFF | ((bytes[2] & 0xFF) << 8) | ((bytes[1] & 0xFF) << 16)) == DOT && bytes[4] == LATIN_CAPITAL_A) - return ISO_8859_1; - - return null; - } - - /** - * This method tries to guess if the encoding is UTF-8, System.getProperty("file.encoding") or ISO-8859-1. - * Its only purpose is to guess the encoding if and only if iptc tag coded character set is not set. If the - * encoding is not UTF-8, the tag should be set. Otherwise it is bad practice. This method tries to - * workaround this issue since some metadata manipulating tools do not prevent such bad practice. - * - * About the reliability of this method: The check if some bytes are UTF-8 or not has a very high reliability. - * The two other checks are less reliable. - * - * @param bytes some text as bytes - * @return the name of the encoding or null if none could be guessed - */ - static String guessEncoding(byte[] bytes) - { - CharsetDecoder cs = Charset.forName(UTF_8).newDecoder(); - - try { - cs.decode(ByteBuffer.wrap(bytes)); - return UTF_8; - } catch (CharacterCodingException e) { - // fall through... - } - - cs = Charset.forName(System.getProperty("file.encoding")).newDecoder(); - try - { - cs.decode(ByteBuffer.wrap(bytes)); - return System.getProperty("file.encoding"); - } catch (CharacterCodingException e) { - // fall through... - } - - cs = Charset.forName(ISO_8859_1).newDecoder(); - try - { - cs.decode(ByteBuffer.wrap(bytes)); - return ISO_8859_1; - } catch (CharacterCodingException e) { - // fall through... - } - - return null; - } - - private Iso2022Converter() - {} -} diff --git a/All/Genesis-OOB/Genesis#59/old/Iso2022Converter.java b/All/Genesis-OOB/Genesis#59/old/Iso2022Converter.java deleted file mode 100755 index f01e4bd..0000000 --- a/All/Genesis-OOB/Genesis#59/old/Iso2022Converter.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.drew.metadata.iptc; - -import java.nio.ByteBuffer; -import java.nio.charset.CharacterCodingException; -import java.nio.charset.Charset; -import java.nio.charset.CharsetDecoder; - -public final class Iso2022Converter -{ - private static final String ISO_8859_1 = "ISO-8859-1"; - private static final String UTF_8 = "UTF-8"; - private static final int LATIN_CAPITAL_A = 0x41; - private static final int DOT = 0xe280a2; - private static final int LATIN_CAPITAL_G = 0x47; - private static final int PERCENT_SIGN = 0x25; - private static final int ESC = 0x1B; - - /** - * Converts the given ISO2022 char set to a java char set. - * - * @param bytes the ISO2022 char set - * @return the java char set name as a string or null if the converting was not possible - */ - public static String convertISO2022CharsetToJavaCharset(byte[] bytes) - { - if (bytes[0] == ESC && bytes[1] == PERCENT_SIGN && bytes[2] == LATIN_CAPITAL_G) - return UTF_8; - - if (bytes[0] == ESC && (bytes[3] & 0xFF | ((bytes[2] & 0xFF) << 8) | ((bytes[1] & 0xFF ) <<16)) == DOT && bytes[4] == LATIN_CAPITAL_A) - return ISO_8859_1; - - return null; - } - - /** - * This method tries to guess if the encoding is UTF-8, System.getProperty("file.encoding") or ISO-8859-1. - * Its only purpose is to guess the encoding if and only if iptc tag coded character set is not set. If the - * encoding is not UTF-8, the tag should be set. Otherwise it is bad practice. This method tries to - * workaround this issue since some metadata manipulating tools do not prevent such bad practice. - * - * About the reliability of this method: The check if some bytes are UTF-8 or not has a very high reliability. - * The two other checks are less reliable. - * - * @param bytes some text as bytes - * @return the name of the encoding or null if none could be guessed - */ - static String guessEncoding(byte[] bytes) - { - CharsetDecoder cs = Charset.forName(UTF_8).newDecoder(); - - try { - cs.decode(ByteBuffer.wrap(bytes)); - return UTF_8; - } catch (CharacterCodingException e) { - // fall through... - } - - cs = Charset.forName(System.getProperty("file.encoding")).newDecoder(); - try - { - cs.decode(ByteBuffer.wrap(bytes)); - return System.getProperty("file.encoding"); - } catch (CharacterCodingException e) { - // fall through... - } - - cs = Charset.forName(ISO_8859_1).newDecoder(); - try - { - cs.decode(ByteBuffer.wrap(bytes)); - return ISO_8859_1; - } catch (CharacterCodingException e) { - // fall through... - } - - return null; - } - - private Iso2022Converter() - {} -} diff --git a/All/Genesis-OOB/Genesis#59/pair.info b/All/Genesis-OOB/Genesis#59/pair.info deleted file mode 100755 index 8935c95..0000000 --- a/All/Genesis-OOB/Genesis#59/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:59 -SATName:Genesis -modifiedFPath:Source/com/drew/metadata/iptc/Iso2022Converter.java -comSha:34cdf7747c37611cea4de43c7b33bd47448e610a -parentComSha:34cdf7747c37611cea4de43c7b33bd47448e610a^1 -githubUrl:https://github.com/drewnoakes/metadata-extractor -repoName:drewnoakes#metadata-extractor \ No newline at end of file diff --git a/All/Genesis-OOB/Genesis#eval_6/comMsg.txt b/All/Genesis-OOB/Genesis#eval_6/comMsg.txt deleted file mode 100755 index 5e2a4f5..0000000 --- a/All/Genesis-OOB/Genesis#eval_6/comMsg.txt +++ /dev/null @@ -1 +0,0 @@ -Improved exception message for out of bounds coverage. diff --git a/All/Genesis-OOB/Genesis#eval_6/diff.diff b/All/Genesis-OOB/Genesis#eval_6/diff.diff deleted file mode 100755 index a818dde..0000000 --- a/All/Genesis-OOB/Genesis#eval_6/diff.diff +++ /dev/null @@ -1,17 +0,0 @@ -diff --git a/src/main/java/org/eluder/coveralls/maven/plugin/domain/Source.java b/src/main/java/org/eluder/coveralls/maven/plugin/domain/Source.java -index a87034a..6ed0d09 100644 ---- a/src/main/java/org/eluder/coveralls/maven/plugin/domain/Source.java -+++ b/src/main/java/org/eluder/coveralls/maven/plugin/domain/Source.java -@@ -29,3 +28,0 @@ package org.eluder.coveralls.maven.plugin.domain; --import java.util.regex.Matcher; --import java.util.regex.Pattern; -- -@@ -34,0 +32,3 @@ import com.fasterxml.jackson.annotation.JsonProperty; -+import java.util.regex.Matcher; -+import java.util.regex.Pattern; -+ -@@ -91,0 +92,4 @@ public final class Source implements JsonObject { -+ int index = lineNumber - 1; -+ if (index >= this.coverage.length) { -+ throw new IllegalArgumentException("Line number " + lineNumber + " is greater than the source file " + name + " size"); -+ } diff --git a/All/Genesis-OOB/Genesis#eval_6/new/Source.java b/All/Genesis-OOB/Genesis#eval_6/new/Source.java deleted file mode 100755 index 6ed0d09..0000000 --- a/All/Genesis-OOB/Genesis#eval_6/new/Source.java +++ /dev/null @@ -1,98 +0,0 @@ -package org.eluder.coveralls.maven.plugin.domain; - -/* - * #[license] - * coveralls-maven-plugin - * %% - * Copyright (C) 2013 - 2015 Tapio Rautonen - * %% - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * %[license] - */ - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public final class Source implements JsonObject { - - private static final Pattern NEWLINE = Pattern.compile("\r\n|\r|\n"); - //private static final String CLASSIFIER_SEPARATOR = "#"; - - private final String name; - private final String source; - private final Integer[] coverage; - private String classifier; - - public Source(final String name, final String source) { - int lines = 1; - StringBuffer replaced = new StringBuffer(source.length()); - Matcher matcher = NEWLINE.matcher(source); - while (matcher.find()) { - lines++; - matcher.appendReplacement(replaced, "\n"); - } - matcher.appendTail(replaced); - this.source = replaced.toString(); - this.coverage = new Integer[lines]; - this.name = name; - } - - @JsonIgnore - public String getName() { - return name; - } - - @JsonProperty("name") - public String getFullName() { - return name; - - // #45: cannot use identifier due to unfetchable source files - //return (classifier == null ? name : name + CLASSIFIER_SEPARATOR + classifier); - } - - @JsonProperty("source") - public String getSource() { - return source; - } - - @JsonProperty("coverage") - public Integer[] getCoverage() { - return coverage; - } - - @JsonIgnore - public String getClassifier() { - return classifier; - } - - public void setClassifier(final String classifier) { - this.classifier = classifier; - } - - public void addCoverage(final int lineNumber, final Integer coverage) { - int index = lineNumber - 1; - if (index >= this.coverage.length) { - throw new IllegalArgumentException("Line number " + lineNumber + " is greater than the source file " + name + " size"); - } - this.coverage[lineNumber - 1] = coverage; - } -} diff --git a/All/Genesis-OOB/Genesis#eval_6/old/Source.java b/All/Genesis-OOB/Genesis#eval_6/old/Source.java deleted file mode 100755 index a87034a..0000000 --- a/All/Genesis-OOB/Genesis#eval_6/old/Source.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.eluder.coveralls.maven.plugin.domain; - -/* - * #[license] - * coveralls-maven-plugin - * %% - * Copyright (C) 2013 - 2015 Tapio Rautonen - * %% - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * %[license] - */ - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -public final class Source implements JsonObject { - - private static final Pattern NEWLINE = Pattern.compile("\r\n|\r|\n"); - //private static final String CLASSIFIER_SEPARATOR = "#"; - - private final String name; - private final String source; - private final Integer[] coverage; - private String classifier; - - public Source(final String name, final String source) { - int lines = 1; - StringBuffer replaced = new StringBuffer(source.length()); - Matcher matcher = NEWLINE.matcher(source); - while (matcher.find()) { - lines++; - matcher.appendReplacement(replaced, "\n"); - } - matcher.appendTail(replaced); - this.source = replaced.toString(); - this.coverage = new Integer[lines]; - this.name = name; - } - - @JsonIgnore - public String getName() { - return name; - } - - @JsonProperty("name") - public String getFullName() { - return name; - - // #45: cannot use identifier due to unfetchable source files - //return (classifier == null ? name : name + CLASSIFIER_SEPARATOR + classifier); - } - - @JsonProperty("source") - public String getSource() { - return source; - } - - @JsonProperty("coverage") - public Integer[] getCoverage() { - return coverage; - } - - @JsonIgnore - public String getClassifier() { - return classifier; - } - - public void setClassifier(final String classifier) { - this.classifier = classifier; - } - - public void addCoverage(final int lineNumber, final Integer coverage) { - this.coverage[lineNumber - 1] = coverage; - } -} diff --git a/All/Genesis-OOB/Genesis#eval_6/pair.info b/All/Genesis-OOB/Genesis#eval_6/pair.info deleted file mode 100755 index 46b5448..0000000 --- a/All/Genesis-OOB/Genesis#eval_6/pair.info +++ /dev/null @@ -1,7 +0,0 @@ -Id:6 -SATName:Genesis -modifiedFPath:src/main/java/org/eluder/coveralls/maven/plugin/domain/Source.java -comSha:20490f6 -parentComSha:20490f6^1 -githubUrl:https://github.com/trautonen/coveralls-maven-plugin -repoName:trautonen#coveralls-maven-plugin diff --git a/WithinSingleMethod/.DS_Store b/WithinSingleMethod/.DS_Store index 99bab32..51276bd 100644 Binary files a/WithinSingleMethod/.DS_Store and b/WithinSingleMethod/.DS_Store differ